hexsha
stringlengths 40
40
| repo
stringlengths 5
121
| path
stringlengths 4
227
| license
sequence | language
stringclasses 1
value | identifier
stringlengths 1
107
| return_type
stringlengths 2
237
⌀ | original_string
stringlengths 75
13.4k
| original_docstring
stringlengths 13
12.9k
| docstring
stringlengths 13
2.57k
| docstring_tokens
sequence | code
stringlengths 23
1.88k
| code_tokens
sequence | short_docstring
stringlengths 1
1.32k
| short_docstring_tokens
sequence | comment
sequence | parameters
list | docstring_params
dict | code_with_imports
stringlengths 23
1.88k
| idxs
int64 0
611k
| cluster
int64 0
1.02k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d067638ebb7eb7862938e528b755c5db2ec52a7 | LaudateCorpus1/code-align-evals-data | human_eval/6a183ce5-8d03-4fc0-a3c2-41e5b5be11b8.py | [
"MIT"
] | Python | find_max | <not_specific> | def find_max(words):
"""Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
find_max(["name", "of", "string"]) == "string"
find_max(["name", "enam", "game"]) == "enam"
find_max(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa"
"""
#[SOLUTION]
return sorted(words, key = lambda x: (-len(set(x)), x))[0] | Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
find_max(["name", "of", "string"]) == "string"
find_max(["name", "enam", "game"]) == "enam"
find_max(["aaaaaaa", "bb" ,"cc"]) == ""aaaaaaa"
| Write a function that accepts a list of strings.
The list contains different words. Return the word with maximum number
of unique characters. If multiple strings have maximum number of unique
characters, return the one which comes first in lexicographical order.
| [
"Write",
"a",
"function",
"that",
"accepts",
"a",
"list",
"of",
"strings",
".",
"The",
"list",
"contains",
"different",
"words",
".",
"Return",
"the",
"word",
"with",
"maximum",
"number",
"of",
"unique",
"characters",
".",
"If",
"multiple",
"strings",
"have",
"maximum",
"number",
"of",
"unique",
"characters",
"return",
"the",
"one",
"which",
"comes",
"first",
"in",
"lexicographical",
"order",
"."
] | def find_max(words):
return sorted(words, key = lambda x: (-len(set(x)), x))[0] | [
"def",
"find_max",
"(",
"words",
")",
":",
"return",
"sorted",
"(",
"words",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"-",
"len",
"(",
"set",
"(",
"x",
")",
")",
",",
"x",
")",
")",
"[",
"0",
"]"
] | Write a function that accepts a list of strings. | [
"Write",
"a",
"function",
"that",
"accepts",
"a",
"list",
"of",
"strings",
"."
] | [
"\"\"\"Write a function that accepts a list of strings.\n The list contains different words. Return the word with maximum number\n of unique characters. If multiple strings have maximum number of unique\n characters, return the one which comes first in lexicographical order.\n\n find_max([\"name\", \"of\", \"string\"]) == \"string\"\n find_max([\"name\", \"enam\", \"game\"]) == \"enam\"\n find_max([\"aaaaaaa\", \"bb\" ,\"cc\"]) == \"\"aaaaaaa\"\n \"\"\"",
"#[SOLUTION]"
] | [
{
"param": "words",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "words",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def find_max(words):
return sorted(words, key = lambda x: (-len(set(x)), x))[0] | 610,297 | 694 |
1563b7a0cc90c26e1c4d9a394ed3939197bcf886 | kaspermunch/argweaver | test/test_install.py | [
"MIT"
] | Python | run_cmd | null | def run_cmd(cmd, ret_code=0):
"""
Run shell command and assert success exit code.
"""
assert os.system(cmd) == ret_code |
Run shell command and assert success exit code.
| Run shell command and assert success exit code. | [
"Run",
"shell",
"command",
"and",
"assert",
"success",
"exit",
"code",
"."
] | def run_cmd(cmd, ret_code=0):
assert os.system(cmd) == ret_code | [
"def",
"run_cmd",
"(",
"cmd",
",",
"ret_code",
"=",
"0",
")",
":",
"assert",
"os",
".",
"system",
"(",
"cmd",
")",
"==",
"ret_code"
] | Run shell command and assert success exit code. | [
"Run",
"shell",
"command",
"and",
"assert",
"success",
"exit",
"code",
"."
] | [
"\"\"\"\n Run shell command and assert success exit code.\n \"\"\""
] | [
{
"param": "cmd",
"type": null
},
{
"param": "ret_code",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cmd",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ret_code",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def run_cmd(cmd, ret_code=0):
assert os.system(cmd) == ret_code | 610,298 | 1,009 |
4d3cd58a515acaa7e0ff402f7c16eedea3c458cd | BTBTravis/army_cook | armycook/cli.py | [
"MIT"
] | Python | load_master_txt | <not_specific> | def load_master_txt():
"""Load file containing text parts to be used in tweet"""
if(os.environ.get('DEV_ENV', '') is "1"):
txt_file = open("../master.txt", "r")
else:
txt_file = open("/txts/master/master.txt", "r")
txt = txt_file.read()
txt_parts = txt.split('--')
split_on_newline = lambda l: l.split("\n")
non_empty = lambda s: len(s) > 0
filter_nonempty = lambda ls: list(filter(non_empty, ls))
break_apart_row = lambda row: {
'title': filter_nonempty(split_on_newline(row))[0],
'body': filter_nonempty(split_on_newline(row))[1]
}
txt_parts = list(map(break_apart_row, txt_parts))
return txt_parts | Load file containing text parts to be used in tweet | Load file containing text parts to be used in tweet | [
"Load",
"file",
"containing",
"text",
"parts",
"to",
"be",
"used",
"in",
"tweet"
] | def load_master_txt():
if(os.environ.get('DEV_ENV', '') is "1"):
txt_file = open("../master.txt", "r")
else:
txt_file = open("/txts/master/master.txt", "r")
txt = txt_file.read()
txt_parts = txt.split('--')
split_on_newline = lambda l: l.split("\n")
non_empty = lambda s: len(s) > 0
filter_nonempty = lambda ls: list(filter(non_empty, ls))
break_apart_row = lambda row: {
'title': filter_nonempty(split_on_newline(row))[0],
'body': filter_nonempty(split_on_newline(row))[1]
}
txt_parts = list(map(break_apart_row, txt_parts))
return txt_parts | [
"def",
"load_master_txt",
"(",
")",
":",
"if",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DEV_ENV'",
",",
"''",
")",
"is",
"\"1\"",
")",
":",
"txt_file",
"=",
"open",
"(",
"\"../master.txt\"",
",",
"\"r\"",
")",
"else",
":",
"txt_file",
"=",
"open",
"(",
"\"/txts/master/master.txt\"",
",",
"\"r\"",
")",
"txt",
"=",
"txt_file",
".",
"read",
"(",
")",
"txt_parts",
"=",
"txt",
".",
"split",
"(",
"'--'",
")",
"split_on_newline",
"=",
"lambda",
"l",
":",
"l",
".",
"split",
"(",
"\"\\n\"",
")",
"non_empty",
"=",
"lambda",
"s",
":",
"len",
"(",
"s",
")",
">",
"0",
"filter_nonempty",
"=",
"lambda",
"ls",
":",
"list",
"(",
"filter",
"(",
"non_empty",
",",
"ls",
")",
")",
"break_apart_row",
"=",
"lambda",
"row",
":",
"{",
"'title'",
":",
"filter_nonempty",
"(",
"split_on_newline",
"(",
"row",
")",
")",
"[",
"0",
"]",
",",
"'body'",
":",
"filter_nonempty",
"(",
"split_on_newline",
"(",
"row",
")",
")",
"[",
"1",
"]",
"}",
"txt_parts",
"=",
"list",
"(",
"map",
"(",
"break_apart_row",
",",
"txt_parts",
")",
")",
"return",
"txt_parts"
] | Load file containing text parts to be used in tweet | [
"Load",
"file",
"containing",
"text",
"parts",
"to",
"be",
"used",
"in",
"tweet"
] | [
"\"\"\"Load file containing text parts to be used in tweet\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} | import os
def load_master_txt():
if(os.environ.get('DEV_ENV', '') is "1"):
txt_file = open("../master.txt", "r")
else:
txt_file = open("/txts/master/master.txt", "r")
txt = txt_file.read()
txt_parts = txt.split('--')
split_on_newline = lambda l: l.split("\n")
non_empty = lambda s: len(s) > 0
filter_nonempty = lambda ls: list(filter(non_empty, ls))
break_apart_row = lambda row: {
'title': filter_nonempty(split_on_newline(row))[0],
'body': filter_nonempty(split_on_newline(row))[1]
}
txt_parts = list(map(break_apart_row, txt_parts))
return txt_parts | 610,299 | 688 |
1aee590c82de256b8807c3e33aee6e4dd2e5f143 | Simske/exostriker | lib/RV_mod/functions.py | [
"MIT"
] | Python | randomString | <not_specific> | def randomString(stringLength=5):
"""
Generate a random string of fixed length
"""
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength)) |
Generate a random string of fixed length
| Generate a random string of fixed length | [
"Generate",
"a",
"random",
"string",
"of",
"fixed",
"length"
] | def randomString(stringLength=5):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength)) | [
"def",
"randomString",
"(",
"stringLength",
"=",
"5",
")",
":",
"letters",
"=",
"string",
".",
"ascii_lowercase",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"letters",
")",
"for",
"i",
"in",
"range",
"(",
"stringLength",
")",
")"
] | Generate a random string of fixed length | [
"Generate",
"a",
"random",
"string",
"of",
"fixed",
"length"
] | [
"\"\"\"\n Generate a random string of fixed length\n \"\"\""
] | [
{
"param": "stringLength",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stringLength",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import string
import random
def randomString(stringLength=5):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength)) | 610,300 | 316 |
8bb45507ba5223af53d7feb9bd4a27216cc4d760 | Cosive/chromewhip | chromewhip/protocol/storage.py | [
"MIT"
] | Python | trackCacheStorageForOrigin | <not_specific> | def trackCacheStorageForOrigin(cls,
origin: Union['str'],
):
"""Registers origin to be notified when an update occurs to its cache storage list.
:param origin: Security origin.
:type origin: str
"""
return (
cls.build_send_payload("trackCacheStorageForOrigin", {
"origin": origin,
}),
None
) | Registers origin to be notified when an update occurs to its cache storage list.
:param origin: Security origin.
:type origin: str
| Registers origin to be notified when an update occurs to its cache storage list. | [
"Registers",
"origin",
"to",
"be",
"notified",
"when",
"an",
"update",
"occurs",
"to",
"its",
"cache",
"storage",
"list",
"."
] | def trackCacheStorageForOrigin(cls,
origin: Union['str'],
):
return (
cls.build_send_payload("trackCacheStorageForOrigin", {
"origin": origin,
}),
None
) | [
"def",
"trackCacheStorageForOrigin",
"(",
"cls",
",",
"origin",
":",
"Union",
"[",
"'str'",
"]",
",",
")",
":",
"return",
"(",
"cls",
".",
"build_send_payload",
"(",
"\"trackCacheStorageForOrigin\"",
",",
"{",
"\"origin\"",
":",
"origin",
",",
"}",
")",
",",
"None",
")"
] | Registers origin to be notified when an update occurs to its cache storage list. | [
"Registers",
"origin",
"to",
"be",
"notified",
"when",
"an",
"update",
"occurs",
"to",
"its",
"cache",
"storage",
"list",
"."
] | [
"\"\"\"Registers origin to be notified when an update occurs to its cache storage list.\n :param origin: Security origin.\n :type origin: str\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "origin",
"type": "Union['str']"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "origin",
"type": "Union['str']",
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def trackCacheStorageForOrigin(cls,
origin: Union['str'],
):
return (
cls.build_send_payload("trackCacheStorageForOrigin", {
"origin": origin,
}),
None
) | 610,301 | 442 |
c189304925ad7368229a7e61ccf28a9c84260580 | Kitware/trame | trame/app/dev.py | [
"Apache-2.0"
] | Python | clear_triggers | null | def clear_triggers(server):
"""
Helper function to remove all triggers.
:param server: server on which we want to clear the triggers
:type server: trame_server.core.Server
"""
names = list(server._triggers.keys())
for name in names:
fn = server._triggers.pop(name)
server._triggers_fn2name.pop(fn)
print(f"unregister trigger {name}") |
Helper function to remove all triggers.
:param server: server on which we want to clear the triggers
:type server: trame_server.core.Server
| Helper function to remove all triggers. | [
"Helper",
"function",
"to",
"remove",
"all",
"triggers",
"."
] | def clear_triggers(server):
names = list(server._triggers.keys())
for name in names:
fn = server._triggers.pop(name)
server._triggers_fn2name.pop(fn)
print(f"unregister trigger {name}") | [
"def",
"clear_triggers",
"(",
"server",
")",
":",
"names",
"=",
"list",
"(",
"server",
".",
"_triggers",
".",
"keys",
"(",
")",
")",
"for",
"name",
"in",
"names",
":",
"fn",
"=",
"server",
".",
"_triggers",
".",
"pop",
"(",
"name",
")",
"server",
".",
"_triggers_fn2name",
".",
"pop",
"(",
"fn",
")",
"print",
"(",
"f\"unregister trigger {name}\"",
")"
] | Helper function to remove all triggers. | [
"Helper",
"function",
"to",
"remove",
"all",
"triggers",
"."
] | [
"\"\"\"\n Helper function to remove all triggers.\n\n :param server: server on which we want to clear the triggers\n :type server: trame_server.core.Server\n \"\"\""
] | [
{
"param": "server",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "server",
"type": null,
"docstring": "server on which we want to clear the triggers",
"docstring_tokens": [
"server",
"on",
"which",
"we",
"want",
"to",
"clear",
"the",
"triggers"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def clear_triggers(server):
names = list(server._triggers.keys())
for name in names:
fn = server._triggers.pop(name)
server._triggers_fn2name.pop(fn)
print(f"unregister trigger {name}") | 610,302 | 497 |
e59084b51c000616f08ea2828647d08173037f65 | adambyram/bite-project-mod | build/tools/base.py | [
"Apache-2.0"
] | Python | _GetExecutable | <not_specific> | def _GetExecutable(executable, location=None):
"""Returns the path to the given executable or None if it is not found.
This algorithm provides a reasonably accurate determination of whether or
not the given executable is on the machine and can be used without knowing
its full path. An optional path can be added to the search. The algorithm
returns the path or None.
Args:
executable: The name of the executable (no path info).(string)
location: Optional location to search for the tool. (string)
Returns:
The path to the executable or None. (string)
"""
extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
paths = os.environ.get('PATH', '').split(os.pathsep)
if location:
paths.append(location)
# Loop over every combination of path and file extension.
for extension in extensions:
for path in paths:
full_path = os.path.join(path, '%s%s' % (executable, extension))
if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
return full_path
return None | Returns the path to the given executable or None if it is not found.
This algorithm provides a reasonably accurate determination of whether or
not the given executable is on the machine and can be used without knowing
its full path. An optional path can be added to the search. The algorithm
returns the path or None.
Args:
executable: The name of the executable (no path info).(string)
location: Optional location to search for the tool. (string)
Returns:
The path to the executable or None. (string)
| Returns the path to the given executable or None if it is not found.
This algorithm provides a reasonably accurate determination of whether or
not the given executable is on the machine and can be used without knowing
its full path. An optional path can be added to the search. The algorithm
returns the path or None. | [
"Returns",
"the",
"path",
"to",
"the",
"given",
"executable",
"or",
"None",
"if",
"it",
"is",
"not",
"found",
".",
"This",
"algorithm",
"provides",
"a",
"reasonably",
"accurate",
"determination",
"of",
"whether",
"or",
"not",
"the",
"given",
"executable",
"is",
"on",
"the",
"machine",
"and",
"can",
"be",
"used",
"without",
"knowing",
"its",
"full",
"path",
".",
"An",
"optional",
"path",
"can",
"be",
"added",
"to",
"the",
"search",
".",
"The",
"algorithm",
"returns",
"the",
"path",
"or",
"None",
"."
] | def _GetExecutable(executable, location=None):
extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
paths = os.environ.get('PATH', '').split(os.pathsep)
if location:
paths.append(location)
for extension in extensions:
for path in paths:
full_path = os.path.join(path, '%s%s' % (executable, extension))
if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
return full_path
return None | [
"def",
"_GetExecutable",
"(",
"executable",
",",
"location",
"=",
"None",
")",
":",
"extensions",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATHEXT'",
",",
"''",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"if",
"location",
":",
"paths",
".",
"append",
"(",
"location",
")",
"for",
"extension",
"in",
"extensions",
":",
"for",
"path",
"in",
"paths",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'%s%s'",
"%",
"(",
"executable",
",",
"extension",
")",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"full_path",
")",
"and",
"os",
".",
"access",
"(",
"full_path",
",",
"os",
".",
"X_OK",
")",
":",
"return",
"full_path",
"return",
"None"
] | Returns the path to the given executable or None if it is not found. | [
"Returns",
"the",
"path",
"to",
"the",
"given",
"executable",
"or",
"None",
"if",
"it",
"is",
"not",
"found",
"."
] | [
"\"\"\"Returns the path to the given executable or None if it is not found.\n\n This algorithm provides a reasonably accurate determination of whether or\n not the given executable is on the machine and can be used without knowing\n its full path. An optional path can be added to the search. The algorithm\n returns the path or None.\n\n Args:\n executable: The name of the executable (no path info).(string)\n location: Optional location to search for the tool. (string)\n\n Returns:\n The path to the executable or None. (string)\n \"\"\"",
"# Loop over every combination of path and file extension."
] | [
{
"param": "executable",
"type": null
},
{
"param": "location",
"type": null
}
] | {
"returns": [
{
"docstring": "The path to the executable or None. (string)",
"docstring_tokens": [
"The",
"path",
"to",
"the",
"executable",
"or",
"None",
".",
"(",
"string",
")"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "executable",
"type": null,
"docstring": "The name of the executable (no path info).(string)",
"docstring_tokens": [
"The",
"name",
"of",
"the",
"executable",
"(",
"no",
"path",
"info",
")",
".",
"(",
"string",
")"
],
"default": null,
"is_optional": null
},
{
"identifier": "location",
"type": null,
"docstring": "Optional location to search for the tool. (string)",
"docstring_tokens": [
"Optional",
"location",
"to",
"search",
"for",
"the",
"tool",
".",
"(",
"string",
")"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def _GetExecutable(executable, location=None):
extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
paths = os.environ.get('PATH', '').split(os.pathsep)
if location:
paths.append(location)
for extension in extensions:
for path in paths:
full_path = os.path.join(path, '%s%s' % (executable, extension))
if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
return full_path
return None | 610,303 | 361 |
72ddceb682be19986f92cf069b181361ae4b6c32 | zc-alexfan/faster_rcnn_0.4 | extract_vg_feature.py | [
"MIT"
] | Python | formalize_bbox | <not_specific> | def formalize_bbox(_im_summary):
"""
Extract bboxes from all classes and return a list of bbox.
Each element of the list is in the form: [x1, y1, x2, y2, class_id, score].
The returned list is sorted descendingly according to score.
"""
boxes = [] # each element: x, y, w, h, class_id, score
probs = [] # prob distribution for each bounding box
feats = [] # pooled features
for class_id, items in enumerate(_im_summary.pred.boxes):
for bbox in items:
x1, y1, x2, y2, score = bbox
boxes.append([x1, y1, x2, y2, class_id, score])
for class_id, items in enumerate(_im_summary.pred.cls_prob):
for cls_prob in items:
probs.append(cls_prob)
for class_id, items in enumerate(_im_summary.pred.pooled_feat):
for f in items:
feats.append(f)
assert len(boxes) == len(probs)
assert len(boxes) == len(feats)
bundles = list(zip(boxes, probs, feats))
bundles = sorted(bundles, key=lambda x: x[0][-1], reverse = True) # sort by confidence descendingly
boxes, probs, feats = zip(*bundles)
return (list(boxes), list(probs), list(feats)) |
Extract bboxes from all classes and return a list of bbox.
Each element of the list is in the form: [x1, y1, x2, y2, class_id, score].
The returned list is sorted descendingly according to score.
| Extract bboxes from all classes and return a list of bbox.
Each element of the list is in the form: [x1, y1, x2, y2, class_id, score].
The returned list is sorted descendingly according to score. | [
"Extract",
"bboxes",
"from",
"all",
"classes",
"and",
"return",
"a",
"list",
"of",
"bbox",
".",
"Each",
"element",
"of",
"the",
"list",
"is",
"in",
"the",
"form",
":",
"[",
"x1",
"y1",
"x2",
"y2",
"class_id",
"score",
"]",
".",
"The",
"returned",
"list",
"is",
"sorted",
"descendingly",
"according",
"to",
"score",
"."
] | def formalize_bbox(_im_summary):
boxes = []
probs = []
feats = []
for class_id, items in enumerate(_im_summary.pred.boxes):
for bbox in items:
x1, y1, x2, y2, score = bbox
boxes.append([x1, y1, x2, y2, class_id, score])
for class_id, items in enumerate(_im_summary.pred.cls_prob):
for cls_prob in items:
probs.append(cls_prob)
for class_id, items in enumerate(_im_summary.pred.pooled_feat):
for f in items:
feats.append(f)
assert len(boxes) == len(probs)
assert len(boxes) == len(feats)
bundles = list(zip(boxes, probs, feats))
bundles = sorted(bundles, key=lambda x: x[0][-1], reverse = True)
boxes, probs, feats = zip(*bundles)
return (list(boxes), list(probs), list(feats)) | [
"def",
"formalize_bbox",
"(",
"_im_summary",
")",
":",
"boxes",
"=",
"[",
"]",
"probs",
"=",
"[",
"]",
"feats",
"=",
"[",
"]",
"for",
"class_id",
",",
"items",
"in",
"enumerate",
"(",
"_im_summary",
".",
"pred",
".",
"boxes",
")",
":",
"for",
"bbox",
"in",
"items",
":",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"score",
"=",
"bbox",
"boxes",
".",
"append",
"(",
"[",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"class_id",
",",
"score",
"]",
")",
"for",
"class_id",
",",
"items",
"in",
"enumerate",
"(",
"_im_summary",
".",
"pred",
".",
"cls_prob",
")",
":",
"for",
"cls_prob",
"in",
"items",
":",
"probs",
".",
"append",
"(",
"cls_prob",
")",
"for",
"class_id",
",",
"items",
"in",
"enumerate",
"(",
"_im_summary",
".",
"pred",
".",
"pooled_feat",
")",
":",
"for",
"f",
"in",
"items",
":",
"feats",
".",
"append",
"(",
"f",
")",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"probs",
")",
"assert",
"len",
"(",
"boxes",
")",
"==",
"len",
"(",
"feats",
")",
"bundles",
"=",
"list",
"(",
"zip",
"(",
"boxes",
",",
"probs",
",",
"feats",
")",
")",
"bundles",
"=",
"sorted",
"(",
"bundles",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
",",
"reverse",
"=",
"True",
")",
"boxes",
",",
"probs",
",",
"feats",
"=",
"zip",
"(",
"*",
"bundles",
")",
"return",
"(",
"list",
"(",
"boxes",
")",
",",
"list",
"(",
"probs",
")",
",",
"list",
"(",
"feats",
")",
")"
] | Extract bboxes from all classes and return a list of bbox. | [
"Extract",
"bboxes",
"from",
"all",
"classes",
"and",
"return",
"a",
"list",
"of",
"bbox",
"."
] | [
"\"\"\"\n Extract bboxes from all classes and return a list of bbox. \n Each element of the list is in the form: [x1, y1, x2, y2, class_id, score]. \n The returned list is sorted descendingly according to score. \n \"\"\"",
"# each element: x, y, w, h, class_id, score ",
"# prob distribution for each bounding box",
"# pooled features",
"# sort by confidence descendingly "
] | [
{
"param": "_im_summary",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "_im_summary",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def formalize_bbox(_im_summary):
boxes = []
probs = []
feats = []
for class_id, items in enumerate(_im_summary.pred.boxes):
for bbox in items:
x1, y1, x2, y2, score = bbox
boxes.append([x1, y1, x2, y2, class_id, score])
for class_id, items in enumerate(_im_summary.pred.cls_prob):
for cls_prob in items:
probs.append(cls_prob)
for class_id, items in enumerate(_im_summary.pred.pooled_feat):
for f in items:
feats.append(f)
assert len(boxes) == len(probs)
assert len(boxes) == len(feats)
bundles = list(zip(boxes, probs, feats))
bundles = sorted(bundles, key=lambda x: x[0][-1], reverse = True)
boxes, probs, feats = zip(*bundles)
return (list(boxes), list(probs), list(feats)) | 610,306 | 838 |
ef8c7f541b81229223b8d706278c1e5b5219598c | Zagorlu/PythonWorkSpace | Util/ConnectionUtil/FtpUtil.py | [
"BSD-3-Clause"
] | Python | transferedByteDisplay | null | def transferedByteDisplay(fileName, bytesToFar, totalByte):
"""
INFO: This function will display number of the how many bytes transfered. This function usefull for ftp, sftp
Internal modules inner callable functions.
:param fileName: Filename
:param bytesToFar: The proceeded byte count
:param totalByte: Total byte count of the filename
:return: NONE
"""
print('Transfer of %r is at %d/%d bytes (%.1f%%)' %
(fileName, bytesToFar, totalByte, 100. * bytesToFar / totalByte)) |
INFO: This function will display number of the how many bytes transfered. This function usefull for ftp, sftp
Internal modules inner callable functions.
:param fileName: Filename
:param bytesToFar: The proceeded byte count
:param totalByte: Total byte count of the filename
:return: NONE
| This function will display number of the how many bytes transfered. This function usefull for ftp, sftp
Internal modules inner callable functions. | [
"This",
"function",
"will",
"display",
"number",
"of",
"the",
"how",
"many",
"bytes",
"transfered",
".",
"This",
"function",
"usefull",
"for",
"ftp",
"sftp",
"Internal",
"modules",
"inner",
"callable",
"functions",
"."
] | def transferedByteDisplay(fileName, bytesToFar, totalByte):
print('Transfer of %r is at %d/%d bytes (%.1f%%)' %
(fileName, bytesToFar, totalByte, 100. * bytesToFar / totalByte)) | [
"def",
"transferedByteDisplay",
"(",
"fileName",
",",
"bytesToFar",
",",
"totalByte",
")",
":",
"print",
"(",
"'Transfer of %r is at %d/%d bytes (%.1f%%)'",
"%",
"(",
"fileName",
",",
"bytesToFar",
",",
"totalByte",
",",
"100.",
"*",
"bytesToFar",
"/",
"totalByte",
")",
")"
] | INFO: This function will display number of the how many bytes transfered. | [
"INFO",
":",
"This",
"function",
"will",
"display",
"number",
"of",
"the",
"how",
"many",
"bytes",
"transfered",
"."
] | [
"\"\"\"\n INFO: This function will display number of the how many bytes transfered. This function usefull for ftp, sftp\n Internal modules inner callable functions.\n :param fileName: Filename\n :param bytesToFar: The proceeded byte count\n :param totalByte: Total byte count of the filename\n :return: NONE\n \"\"\""
] | [
{
"param": "fileName",
"type": null
},
{
"param": "bytesToFar",
"type": null
},
{
"param": "totalByte",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "fileName",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
},
{
"identifier": "bytesToFar",
"type": null,
"docstring": "The proceeded byte count",
"docstring_tokens": [
"The",
"proceeded",
"byte",
"count"
],
"default": null,
"is_optional": null
},
{
"identifier": "totalByte",
"type": null,
"docstring": "Total byte count of the filename",
"docstring_tokens": [
"Total",
"byte",
"count",
"of",
"the",
"filename"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def transferedByteDisplay(fileName, bytesToFar, totalByte):
print('Transfer of %r is at %d/%d bytes (%.1f%%)' %
(fileName, bytesToFar, totalByte, 100. * bytesToFar / totalByte)) | 610,308 | 611 |
5f0ee81684056a551bdcaf4bf4f679468a1d5dd3 | ggirelli/fasta-tools-gg | src/fasta_lines.py | [
"MIT"
] | Python | format_element | <not_specific> | def format_element(eid, eseq, k):
"""Format a sequence element using FASTA format and k sequence length.
Args:
eid (string): element ID.
eseq (string): element sequence.
k (int): sequence line length.
Return:
string: "> %s\n%s" % (eid, eseq_split_by_k)
"""
if k > 0:
eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)]
eseq = "\n".join(eseq)
return("> %s\n%s" % (eid, eseq)) | Format a sequence element using FASTA format and k sequence length.
Args:
eid (string): element ID.
eseq (string): element sequence.
k (int): sequence line length.
Return:
string: "> %s\n%s" % (eid, eseq_split_by_k)
| Format a sequence element using FASTA format and k sequence length. | [
"Format",
"a",
"sequence",
"element",
"using",
"FASTA",
"format",
"and",
"k",
"sequence",
"length",
"."
] | def format_element(eid, eseq, k):
if k > 0:
eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)]
eseq = "\n".join(eseq)
return("> %s\n%s" % (eid, eseq)) | [
"def",
"format_element",
"(",
"eid",
",",
"eseq",
",",
"k",
")",
":",
"if",
"k",
">",
"0",
":",
"eseq",
"=",
"[",
"eseq",
"[",
"i",
":",
"min",
"(",
"i",
"+",
"k",
",",
"len",
"(",
"eseq",
")",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"eseq",
")",
",",
"k",
")",
"]",
"eseq",
"=",
"\"\\n\"",
".",
"join",
"(",
"eseq",
")",
"return",
"(",
"\"> %s\\n%s\"",
"%",
"(",
"eid",
",",
"eseq",
")",
")"
] | Format a sequence element using FASTA format and k sequence length. | [
"Format",
"a",
"sequence",
"element",
"using",
"FASTA",
"format",
"and",
"k",
"sequence",
"length",
"."
] | [
"\"\"\"Format a sequence element using FASTA format and k sequence length.\n\n\tArgs:\n\t\teid (string): element ID.\n\t\teseq (string): element sequence.\n\t\tk (int): sequence line length.\n\n\tReturn:\n\t\tstring: \"> %s\\n%s\" % (eid, eseq_split_by_k)\n\t\"\"\""
] | [
{
"param": "eid",
"type": null
},
{
"param": "eseq",
"type": null
},
{
"param": "k",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "eid",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "eseq",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
},
{
"identifier": "k",
"type": null,
"docstring": "sequence line length.",
"docstring_tokens": [
"sequence",
"line",
"length",
"."
],
"default": null,
"is_optional": false
}
],
"outlier_params": [],
"others": []
} | def format_element(eid, eseq, k):
if k > 0:
eseq = [eseq[i:min(i + k, len(eseq))]for i in range(0, len(eseq), k)]
eseq = "\n".join(eseq)
return("> %s\n%s" % (eid, eseq)) | 610,310 | 119 |
70d1df3039ac9d4a2ce893a6ba651d1c12e219ed | pedro-mgb/pedestrian-arc-lstm-smf | models/interaction_modules/train_aux.py | [
"MIT"
] | Python | create_gt_generator | <not_specific> | def create_gt_generator(model):
"""
Create a "gt generator". This will be a copy of the model, minus the shape configuration. It will be fixed
throughout one epoch, and will generate the ground truth to train the shape configuration model. This ground truth
will be the pooling shape dimensions that yielded the lowest loss - simulating what could be the real shape
dimension of the pedestrian.
May also disable gradient computation for parts of the original model (that are not relevant from a point of view
of training).
:param model: the original model
:return: the gt generator, and the interaction model
"""
# gt_model a model that will be used to generate "predictions" that will be simulated as ground truth data
shape_config = model.shape_config
model.shape_config = None # deepcopy might not work without this line, due to there being some extra tensors
gt_generator = copy.deepcopy(model)
gt_generator.eval()
gt_generator.shape_config = None
# disable all gradients - except for the ones associated to the shape configuration network
model.shape_config = shape_config
for param in gt_generator.parameters():
param.requires_grad = False
for param in model.parameters():
param.requires_grad = True
# because the actual pooling data will come from a dataset, and not computed by the module, the goal of this
# interaction module is just to embed the data, and send it as direct input to the LSTM cell
interaction_module = copy.deepcopy(gt_generator.interaction_module)
return gt_generator, interaction_module |
Create a "gt generator". This will be a copy of the model, minus the shape configuration. It will be fixed
throughout one epoch, and will generate the ground truth to train the shape configuration model. This ground truth
will be the pooling shape dimensions that yielded the lowest loss - simulating what could be the real shape
dimension of the pedestrian.
May also disable gradient computation for parts of the original model (that are not relevant from a point of view
of training).
:param model: the original model
:return: the gt generator, and the interaction model
| Create a "gt generator". This will be a copy of the model, minus the shape configuration. It will be fixed
throughout one epoch, and will generate the ground truth to train the shape configuration model. This ground truth
will be the pooling shape dimensions that yielded the lowest loss - simulating what could be the real shape
dimension of the pedestrian.
May also disable gradient computation for parts of the original model (that are not relevant from a point of view
of training). | [
"Create",
"a",
"\"",
"gt",
"generator",
"\"",
".",
"This",
"will",
"be",
"a",
"copy",
"of",
"the",
"model",
"minus",
"the",
"shape",
"configuration",
".",
"It",
"will",
"be",
"fixed",
"throughout",
"one",
"epoch",
"and",
"will",
"generate",
"the",
"ground",
"truth",
"to",
"train",
"the",
"shape",
"configuration",
"model",
".",
"This",
"ground",
"truth",
"will",
"be",
"the",
"pooling",
"shape",
"dimensions",
"that",
"yielded",
"the",
"lowest",
"loss",
"-",
"simulating",
"what",
"could",
"be",
"the",
"real",
"shape",
"dimension",
"of",
"the",
"pedestrian",
".",
"May",
"also",
"disable",
"gradient",
"computation",
"for",
"parts",
"of",
"the",
"original",
"model",
"(",
"that",
"are",
"not",
"relevant",
"from",
"a",
"point",
"of",
"view",
"of",
"training",
")",
"."
] | def create_gt_generator(model):
shape_config = model.shape_config
model.shape_config = None
gt_generator = copy.deepcopy(model)
gt_generator.eval()
gt_generator.shape_config = None
model.shape_config = shape_config
for param in gt_generator.parameters():
param.requires_grad = False
for param in model.parameters():
param.requires_grad = True
interaction_module = copy.deepcopy(gt_generator.interaction_module)
return gt_generator, interaction_module | [
"def",
"create_gt_generator",
"(",
"model",
")",
":",
"shape_config",
"=",
"model",
".",
"shape_config",
"model",
".",
"shape_config",
"=",
"None",
"gt_generator",
"=",
"copy",
".",
"deepcopy",
"(",
"model",
")",
"gt_generator",
".",
"eval",
"(",
")",
"gt_generator",
".",
"shape_config",
"=",
"None",
"model",
".",
"shape_config",
"=",
"shape_config",
"for",
"param",
"in",
"gt_generator",
".",
"parameters",
"(",
")",
":",
"param",
".",
"requires_grad",
"=",
"False",
"for",
"param",
"in",
"model",
".",
"parameters",
"(",
")",
":",
"param",
".",
"requires_grad",
"=",
"True",
"interaction_module",
"=",
"copy",
".",
"deepcopy",
"(",
"gt_generator",
".",
"interaction_module",
")",
"return",
"gt_generator",
",",
"interaction_module"
] | Create a "gt generator". | [
"Create",
"a",
"\"",
"gt",
"generator",
"\"",
"."
] | [
"\"\"\"\n Create a \"gt generator\". This will be a copy of the model, minus the shape configuration. It will be fixed\n throughout one epoch, and will generate the ground truth to train the shape configuration model. This ground truth\n will be the pooling shape dimensions that yielded the lowest loss - simulating what could be the real shape\n dimension of the pedestrian.\n May also disable gradient computation for parts of the original model (that are not relevant from a point of view\n of training).\n :param model: the original model\n :return: the gt generator, and the interaction model\n \"\"\"",
"# gt_model a model that will be used to generate \"predictions\" that will be simulated as ground truth data",
"# deepcopy might not work without this line, due to there being some extra tensors",
"# disable all gradients - except for the ones associated to the shape configuration network",
"# because the actual pooling data will come from a dataset, and not computed by the module, the goal of this",
"# interaction module is just to embed the data, and send it as direct input to the LSTM cell"
] | [
{
"param": "model",
"type": null
}
] | {
"returns": [
{
"docstring": "the gt generator, and the interaction model",
"docstring_tokens": [
"the",
"gt",
"generator",
"and",
"the",
"interaction",
"model"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "model",
"type": null,
"docstring": "the original model",
"docstring_tokens": [
"the",
"original",
"model"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import copy
def create_gt_generator(model):
shape_config = model.shape_config
model.shape_config = None
gt_generator = copy.deepcopy(model)
gt_generator.eval()
gt_generator.shape_config = None
model.shape_config = shape_config
for param in gt_generator.parameters():
param.requires_grad = False
for param in model.parameters():
param.requires_grad = True
interaction_module = copy.deepcopy(gt_generator.interaction_module)
return gt_generator, interaction_module | 610,311 | 631 |
2f6939d46124b482bbe624e60b8f654d810e3041 | lightvault/mlfinlab | mlfinlab/bet_sizing/ch10_snippets.py | [
"BSD-3-Clause"
] | Python | inv_price_sigmoid | <not_specific> | def inv_price_sigmoid(forecast_price, w_param, m_bet_size):
"""
Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price.
Based on a sigmoid function for a bet size algorithm.
:param forecast_price: (float) Forecast price.
:param w_param: (float) Coefficient regulating the width of the bet size function.
:param m_bet_size: (float) Bet size.
:return: (float) Inverse of bet size with respect to market price.
"""
return forecast_price - m_bet_size * (w_param / (1 - m_bet_size**2))**0.5 |
Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price.
Based on a sigmoid function for a bet size algorithm.
:param forecast_price: (float) Forecast price.
:param w_param: (float) Coefficient regulating the width of the bet size function.
:param m_bet_size: (float) Bet size.
:return: (float) Inverse of bet size with respect to market price.
| Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price.
Based on a sigmoid function for a bet size algorithm. | [
"Part",
"of",
"SNIPPET",
"10",
".",
"4",
"Calculates",
"the",
"inverse",
"of",
"the",
"bet",
"size",
"with",
"respect",
"to",
"the",
"market",
"price",
".",
"Based",
"on",
"a",
"sigmoid",
"function",
"for",
"a",
"bet",
"size",
"algorithm",
"."
] | def inv_price_sigmoid(forecast_price, w_param, m_bet_size):
return forecast_price - m_bet_size * (w_param / (1 - m_bet_size**2))**0.5 | [
"def",
"inv_price_sigmoid",
"(",
"forecast_price",
",",
"w_param",
",",
"m_bet_size",
")",
":",
"return",
"forecast_price",
"-",
"m_bet_size",
"*",
"(",
"w_param",
"/",
"(",
"1",
"-",
"m_bet_size",
"**",
"2",
")",
")",
"**",
"0.5"
] | Part of SNIPPET 10.4
Calculates the inverse of the bet size with respect to the market price. | [
"Part",
"of",
"SNIPPET",
"10",
".",
"4",
"Calculates",
"the",
"inverse",
"of",
"the",
"bet",
"size",
"with",
"respect",
"to",
"the",
"market",
"price",
"."
] | [
"\"\"\"\n Part of SNIPPET 10.4\n Calculates the inverse of the bet size with respect to the market price.\n Based on a sigmoid function for a bet size algorithm.\n\n :param forecast_price: (float) Forecast price.\n :param w_param: (float) Coefficient regulating the width of the bet size function.\n :param m_bet_size: (float) Bet size.\n :return: (float) Inverse of bet size with respect to market price.\n \"\"\""
] | [
{
"param": "forecast_price",
"type": null
},
{
"param": "w_param",
"type": null
},
{
"param": "m_bet_size",
"type": null
}
] | {
"returns": [
{
"docstring": "(float) Inverse of bet size with respect to market price.",
"docstring_tokens": [
"(",
"float",
")",
"Inverse",
"of",
"bet",
"size",
"with",
"respect",
"to",
"market",
"price",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "forecast_price",
"type": null,
"docstring": "(float) Forecast price.",
"docstring_tokens": [
"(",
"float",
")",
"Forecast",
"price",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "w_param",
"type": null,
"docstring": "(float) Coefficient regulating the width of the bet size function.",
"docstring_tokens": [
"(",
"float",
")",
"Coefficient",
"regulating",
"the",
"width",
"of",
"the",
"bet",
"size",
"function",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "m_bet_size",
"type": null,
"docstring": "(float) Bet size.",
"docstring_tokens": [
"(",
"float",
")",
"Bet",
"size",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def inv_price_sigmoid(forecast_price, w_param, m_bet_size):
return forecast_price - m_bet_size * (w_param / (1 - m_bet_size**2))**0.5 | 610,312 | 885 |
b39a896ba2d8b2db4d218fdecd89644a8862db07 | phy-q/benchmark | sciencebirdsagents/MultiAgentTestOnly.py | [
"MIT"
] | Python | sample_levels | <not_specific> | def sample_levels(training_level_set, num_agents, agent_idx):
'''
given idx, return the averaged distributed levels
'''
n = math.ceil(len(training_level_set) / num_agents)
total_list = []
for i in range(0, len(training_level_set), n):
total_list.append(training_level_set[i:i + n])
if agent_idx >= len(total_list):
return None
return total_list[agent_idx] |
given idx, return the averaged distributed levels
| given idx, return the averaged distributed levels | [
"given",
"idx",
"return",
"the",
"averaged",
"distributed",
"levels"
] | def sample_levels(training_level_set, num_agents, agent_idx):
n = math.ceil(len(training_level_set) / num_agents)
total_list = []
for i in range(0, len(training_level_set), n):
total_list.append(training_level_set[i:i + n])
if agent_idx >= len(total_list):
return None
return total_list[agent_idx] | [
"def",
"sample_levels",
"(",
"training_level_set",
",",
"num_agents",
",",
"agent_idx",
")",
":",
"n",
"=",
"math",
".",
"ceil",
"(",
"len",
"(",
"training_level_set",
")",
"/",
"num_agents",
")",
"total_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"training_level_set",
")",
",",
"n",
")",
":",
"total_list",
".",
"append",
"(",
"training_level_set",
"[",
"i",
":",
"i",
"+",
"n",
"]",
")",
"if",
"agent_idx",
">=",
"len",
"(",
"total_list",
")",
":",
"return",
"None",
"return",
"total_list",
"[",
"agent_idx",
"]"
] | given idx, return the averaged distributed levels | [
"given",
"idx",
"return",
"the",
"averaged",
"distributed",
"levels"
] | [
"'''\n given idx, return the averaged distributed levels\n '''"
] | [
{
"param": "training_level_set",
"type": null
},
{
"param": "num_agents",
"type": null
},
{
"param": "agent_idx",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "training_level_set",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "num_agents",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "agent_idx",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import math
def sample_levels(training_level_set, num_agents, agent_idx):
n = math.ceil(len(training_level_set) / num_agents)
total_list = []
for i in range(0, len(training_level_set), n):
total_list.append(training_level_set[i:i + n])
if agent_idx >= len(total_list):
return None
return total_list[agent_idx] | 610,313 | 659 |
e55b3bf2bd3c1bb3470fe6d7bdac45ebd5bd555e | kennethlove/django | django/contrib/admin/templatetags/admin_modify.py | [
"BSD-3-Clause"
] | Python | cell_count | <not_specific> | def cell_count(inline_admin_form):
"""Returns the number of cells used in a tabular inline"""
count = 1 # Hidden cell with hidden 'id' field
for fieldset in inline_admin_form:
# Loop through all the fields (one per cell)
for line in fieldset:
for field in line:
count += 1
if inline_admin_form.formset.can_delete:
# Delete checkbox
count += 1
return count | Returns the number of cells used in a tabular inline | Returns the number of cells used in a tabular inline | [
"Returns",
"the",
"number",
"of",
"cells",
"used",
"in",
"a",
"tabular",
"inline"
] | def cell_count(inline_admin_form):
count = 1
for fieldset in inline_admin_form:
for line in fieldset:
for field in line:
count += 1
if inline_admin_form.formset.can_delete:
count += 1
return count | [
"def",
"cell_count",
"(",
"inline_admin_form",
")",
":",
"count",
"=",
"1",
"for",
"fieldset",
"in",
"inline_admin_form",
":",
"for",
"line",
"in",
"fieldset",
":",
"for",
"field",
"in",
"line",
":",
"count",
"+=",
"1",
"if",
"inline_admin_form",
".",
"formset",
".",
"can_delete",
":",
"count",
"+=",
"1",
"return",
"count"
] | Returns the number of cells used in a tabular inline | [
"Returns",
"the",
"number",
"of",
"cells",
"used",
"in",
"a",
"tabular",
"inline"
] | [
"\"\"\"Returns the number of cells used in a tabular inline\"\"\"",
"# Hidden cell with hidden 'id' field",
"# Loop through all the fields (one per cell)",
"# Delete checkbox"
] | [
{
"param": "inline_admin_form",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "inline_admin_form",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def cell_count(inline_admin_form):
count = 1
for fieldset in inline_admin_form:
for line in fieldset:
for field in line:
count += 1
if inline_admin_form.formset.can_delete:
count += 1
return count | 610,314 | 105 |
9d2e5ac0e46e8b9a4d1dcf3049633f8bfe0d0456 | Mu-L/PaddleNLP | examples/language_model/xlm/xnli_train.py | [
"Apache-2.0"
] | Python | convert_example | <not_specific> | def convert_example(example, tokenizer, max_seq_length=256, language="en"):
"""convert a example into necessary features"""
# Get the label
label = example["label"]
premise = example["premise"]
hypothesis = example["hypothesis"]
# Convert raw text to feature
example = tokenizer(premise,
text_pair=hypothesis,
max_length=max_seq_length,
return_attention_mask=True,
return_token_type_ids=False,
lang=language)
return example["input_ids"], example["attention_mask"], label | convert a example into necessary features | convert a example into necessary features | [
"convert",
"a",
"example",
"into",
"necessary",
"features"
] | def convert_example(example, tokenizer, max_seq_length=256, language="en"):
label = example["label"]
premise = example["premise"]
hypothesis = example["hypothesis"]
example = tokenizer(premise,
text_pair=hypothesis,
max_length=max_seq_length,
return_attention_mask=True,
return_token_type_ids=False,
lang=language)
return example["input_ids"], example["attention_mask"], label | [
"def",
"convert_example",
"(",
"example",
",",
"tokenizer",
",",
"max_seq_length",
"=",
"256",
",",
"language",
"=",
"\"en\"",
")",
":",
"label",
"=",
"example",
"[",
"\"label\"",
"]",
"premise",
"=",
"example",
"[",
"\"premise\"",
"]",
"hypothesis",
"=",
"example",
"[",
"\"hypothesis\"",
"]",
"example",
"=",
"tokenizer",
"(",
"premise",
",",
"text_pair",
"=",
"hypothesis",
",",
"max_length",
"=",
"max_seq_length",
",",
"return_attention_mask",
"=",
"True",
",",
"return_token_type_ids",
"=",
"False",
",",
"lang",
"=",
"language",
")",
"return",
"example",
"[",
"\"input_ids\"",
"]",
",",
"example",
"[",
"\"attention_mask\"",
"]",
",",
"label"
] | convert a example into necessary features | [
"convert",
"a",
"example",
"into",
"necessary",
"features"
] | [
"\"\"\"convert a example into necessary features\"\"\"",
"# Get the label",
"# Convert raw text to feature"
] | [
{
"param": "example",
"type": null
},
{
"param": "tokenizer",
"type": null
},
{
"param": "max_seq_length",
"type": null
},
{
"param": "language",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "example",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tokenizer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "max_seq_length",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "language",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def convert_example(example, tokenizer, max_seq_length=256, language="en"):
label = example["label"]
premise = example["premise"]
hypothesis = example["hypothesis"]
example = tokenizer(premise,
text_pair=hypothesis,
max_length=max_seq_length,
return_attention_mask=True,
return_token_type_ids=False,
lang=language)
return example["input_ids"], example["attention_mask"], label | 610,315 | 171 |
9e70e8dde69f94d78567176d5ac581edba3c3a5d | giserh/gpkit | gpkit/small_scripts.py | [
"MIT"
] | Python | maybe_flatten | <not_specific> | def maybe_flatten(value):
"Extract values from 0-d numpy arrays, if necessary"
if hasattr(value, "shape") and not value.shape:
return value.flatten()[0] # 0-d numpy arrays
return value | Extract values from 0-d numpy arrays, if necessary | Extract values from 0-d numpy arrays, if necessary | [
"Extract",
"values",
"from",
"0",
"-",
"d",
"numpy",
"arrays",
"if",
"necessary"
] | def maybe_flatten(value):
if hasattr(value, "shape") and not value.shape:
return value.flatten()[0]
return value | [
"def",
"maybe_flatten",
"(",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"\"shape\"",
")",
"and",
"not",
"value",
".",
"shape",
":",
"return",
"value",
".",
"flatten",
"(",
")",
"[",
"0",
"]",
"return",
"value"
] | Extract values from 0-d numpy arrays, if necessary | [
"Extract",
"values",
"from",
"0",
"-",
"d",
"numpy",
"arrays",
"if",
"necessary"
] | [
"\"Extract values from 0-d numpy arrays, if necessary\"",
"# 0-d numpy arrays"
] | [
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "value",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def maybe_flatten(value):
if hasattr(value, "shape") and not value.shape:
return value.flatten()[0]
return value | 610,316 | 798 |
52c9a2d7b3c4d45eebfb12cb45f958d5bc4823c8 | Mindhome/field_service | mindhome_alpha/erpnext/patches/v12_0/set_purchase_receipt_delivery_note_detail.py | [
"MIT"
] | Python | row_is_mappable | <not_specific> | def row_is_mappable(doc_row, return_doc_row, detail_field):
"""Checks if two rows are similar enough to be mapped."""
if doc_row.item_code == return_doc_row.item_code and not return_doc_row.get(detail_field):
if doc_row.get('batch_no') and return_doc_row.get('batch_no') and doc_row.batch_no == return_doc_row.batch_no:
return True
elif doc_row.get('serial_no') and return_doc_row.get('serial_no'):
doc_sn = doc_row.serial_no.split('\n')
return_doc_sn = return_doc_row.serial_no.split('\n')
if set(doc_sn) & set(return_doc_sn):
# if two rows have serial nos in common, map them
return True
elif doc_row.rate == return_doc_row.rate:
return True
else:
return False | Checks if two rows are similar enough to be mapped. | Checks if two rows are similar enough to be mapped. | [
"Checks",
"if",
"two",
"rows",
"are",
"similar",
"enough",
"to",
"be",
"mapped",
"."
] | def row_is_mappable(doc_row, return_doc_row, detail_field):
if doc_row.item_code == return_doc_row.item_code and not return_doc_row.get(detail_field):
if doc_row.get('batch_no') and return_doc_row.get('batch_no') and doc_row.batch_no == return_doc_row.batch_no:
return True
elif doc_row.get('serial_no') and return_doc_row.get('serial_no'):
doc_sn = doc_row.serial_no.split('\n')
return_doc_sn = return_doc_row.serial_no.split('\n')
if set(doc_sn) & set(return_doc_sn):
return True
elif doc_row.rate == return_doc_row.rate:
return True
else:
return False | [
"def",
"row_is_mappable",
"(",
"doc_row",
",",
"return_doc_row",
",",
"detail_field",
")",
":",
"if",
"doc_row",
".",
"item_code",
"==",
"return_doc_row",
".",
"item_code",
"and",
"not",
"return_doc_row",
".",
"get",
"(",
"detail_field",
")",
":",
"if",
"doc_row",
".",
"get",
"(",
"'batch_no'",
")",
"and",
"return_doc_row",
".",
"get",
"(",
"'batch_no'",
")",
"and",
"doc_row",
".",
"batch_no",
"==",
"return_doc_row",
".",
"batch_no",
":",
"return",
"True",
"elif",
"doc_row",
".",
"get",
"(",
"'serial_no'",
")",
"and",
"return_doc_row",
".",
"get",
"(",
"'serial_no'",
")",
":",
"doc_sn",
"=",
"doc_row",
".",
"serial_no",
".",
"split",
"(",
"'\\n'",
")",
"return_doc_sn",
"=",
"return_doc_row",
".",
"serial_no",
".",
"split",
"(",
"'\\n'",
")",
"if",
"set",
"(",
"doc_sn",
")",
"&",
"set",
"(",
"return_doc_sn",
")",
":",
"return",
"True",
"elif",
"doc_row",
".",
"rate",
"==",
"return_doc_row",
".",
"rate",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Checks if two rows are similar enough to be mapped. | [
"Checks",
"if",
"two",
"rows",
"are",
"similar",
"enough",
"to",
"be",
"mapped",
"."
] | [
"\"\"\"Checks if two rows are similar enough to be mapped.\"\"\"",
"# if two rows have serial nos in common, map them"
] | [
{
"param": "doc_row",
"type": null
},
{
"param": "return_doc_row",
"type": null
},
{
"param": "detail_field",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "doc_row",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "return_doc_row",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "detail_field",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def row_is_mappable(doc_row, return_doc_row, detail_field):
if doc_row.item_code == return_doc_row.item_code and not return_doc_row.get(detail_field):
if doc_row.get('batch_no') and return_doc_row.get('batch_no') and doc_row.batch_no == return_doc_row.batch_no:
return True
elif doc_row.get('serial_no') and return_doc_row.get('serial_no'):
doc_sn = doc_row.serial_no.split('\n')
return_doc_sn = return_doc_row.serial_no.split('\n')
if set(doc_sn) & set(return_doc_sn):
return True
elif doc_row.rate == return_doc_row.rate:
return True
else:
return False | 610,317 | 505 |
4290c09bd48b420798cd63629f95f40d10e92ead | Jiaolong/gcn-parking-slot | psdet/utils/precision_recall.py | [
"MIT"
] | Python | match_gt_with_preds | <not_specific> | def match_gt_with_preds(ground_truth, predictions, match_labels):
"""Match a ground truth with every predictions and return matched index."""
max_confidence = 0.
matched_idx = -1
for i, pred in enumerate(predictions):
if match_labels(ground_truth, pred[1]) and max_confidence < pred[0]:
max_confidence = pred[0]
matched_idx = i
return matched_idx | Match a ground truth with every predictions and return matched index. | Match a ground truth with every predictions and return matched index. | [
"Match",
"a",
"ground",
"truth",
"with",
"every",
"predictions",
"and",
"return",
"matched",
"index",
"."
] | def match_gt_with_preds(ground_truth, predictions, match_labels):
max_confidence = 0.
matched_idx = -1
for i, pred in enumerate(predictions):
if match_labels(ground_truth, pred[1]) and max_confidence < pred[0]:
max_confidence = pred[0]
matched_idx = i
return matched_idx | [
"def",
"match_gt_with_preds",
"(",
"ground_truth",
",",
"predictions",
",",
"match_labels",
")",
":",
"max_confidence",
"=",
"0.",
"matched_idx",
"=",
"-",
"1",
"for",
"i",
",",
"pred",
"in",
"enumerate",
"(",
"predictions",
")",
":",
"if",
"match_labels",
"(",
"ground_truth",
",",
"pred",
"[",
"1",
"]",
")",
"and",
"max_confidence",
"<",
"pred",
"[",
"0",
"]",
":",
"max_confidence",
"=",
"pred",
"[",
"0",
"]",
"matched_idx",
"=",
"i",
"return",
"matched_idx"
] | Match a ground truth with every predictions and return matched index. | [
"Match",
"a",
"ground",
"truth",
"with",
"every",
"predictions",
"and",
"return",
"matched",
"index",
"."
] | [
"\"\"\"Match a ground truth with every predictions and return matched index.\"\"\""
] | [
{
"param": "ground_truth",
"type": null
},
{
"param": "predictions",
"type": null
},
{
"param": "match_labels",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ground_truth",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "predictions",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "match_labels",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def match_gt_with_preds(ground_truth, predictions, match_labels):
max_confidence = 0.
matched_idx = -1
for i, pred in enumerate(predictions):
if match_labels(ground_truth, pred[1]) and max_confidence < pred[0]:
max_confidence = pred[0]
matched_idx = i
return matched_idx | 610,318 | 415 |
fc4c8627d96961eb19b1e97f5dcf360877e78777 | brytemorio/WavesGatewayFramework | waves_gateway/common/utils.py | [
"MIT"
] | Python | map_array | list | def map_array(func, arr: list) -> list:
"""
Calls the given function on every element on the given array and returns the resulting elements.
"""
res = list()
for el in arr:
res.append(func(el))
return res |
Calls the given function on every element on the given array and returns the resulting elements.
| Calls the given function on every element on the given array and returns the resulting elements. | [
"Calls",
"the",
"given",
"function",
"on",
"every",
"element",
"on",
"the",
"given",
"array",
"and",
"returns",
"the",
"resulting",
"elements",
"."
] | def map_array(func, arr: list) -> list:
res = list()
for el in arr:
res.append(func(el))
return res | [
"def",
"map_array",
"(",
"func",
",",
"arr",
":",
"list",
")",
"->",
"list",
":",
"res",
"=",
"list",
"(",
")",
"for",
"el",
"in",
"arr",
":",
"res",
".",
"append",
"(",
"func",
"(",
"el",
")",
")",
"return",
"res"
] | Calls the given function on every element on the given array and returns the resulting elements. | [
"Calls",
"the",
"given",
"function",
"on",
"every",
"element",
"on",
"the",
"given",
"array",
"and",
"returns",
"the",
"resulting",
"elements",
"."
] | [
"\"\"\"\n Calls the given function on every element on the given array and returns the resulting elements.\n \"\"\""
] | [
{
"param": "func",
"type": null
},
{
"param": "arr",
"type": "list"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "func",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "arr",
"type": "list",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def map_array(func, arr: list) -> list:
res = list()
for el in arr:
res.append(func(el))
return res | 610,319 | 844 |
6a80ea554f72cf8c13686e53c42ff5e2244d083f | wibbico/bcpy | bcpy/format_file_builder.py | [
"MIT"
] | Python | _scaper | <not_specific> | def _scaper(input_string):
"""Adds the required scape characters to the format file.
:param input_string: Value before scaping
:type input_string: str
:return: Scaped string
"""
scaped_string = input_string.replace('"', '\\"').replace("'", "\\'") \
.replace('\r', '\\r').replace('\n', '\\n')
return scaped_string | Adds the required scape characters to the format file.
:param input_string: Value before scaping
:type input_string: str
:return: Scaped string
| Adds the required scape characters to the format file. | [
"Adds",
"the",
"required",
"scape",
"characters",
"to",
"the",
"format",
"file",
"."
] | def _scaper(input_string):
scaped_string = input_string.replace('"', '\\"').replace("'", "\\'") \
.replace('\r', '\\r').replace('\n', '\\n')
return scaped_string | [
"def",
"_scaper",
"(",
"input_string",
")",
":",
"scaped_string",
"=",
"input_string",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\\\'\"",
")",
".",
"replace",
"(",
"'\\r'",
",",
"'\\\\r'",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
"return",
"scaped_string"
] | Adds the required scape characters to the format file. | [
"Adds",
"the",
"required",
"scape",
"characters",
"to",
"the",
"format",
"file",
"."
] | [
"\"\"\"Adds the required scape characters to the format file.\n :param input_string: Value before scaping\n :type input_string: str\n :return: Scaped string\n \"\"\""
] | [
{
"param": "input_string",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "input_string",
"type": null,
"docstring": "Value before scaping",
"docstring_tokens": [
"Value",
"before",
"scaping"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _scaper(input_string):
scaped_string = input_string.replace('"', '\\"').replace("'", "\\'") \
.replace('\r', '\\r').replace('\n', '\\n')
return scaped_string | 610,320 | 202 |
14679d745d6ce0f2fc1dc8ef1430ba861dcc3559 | seefrye/waaaaagh-list | _notes/.obsidian/scripts/sympy-1.9/sympy/strategies/rl.py | [
"MIT"
] | Python | distribute | <not_specific> | def distribute(A, B):
""" Turns an A containing Bs into a B of As
where A, B are container types
>>> from sympy.strategies import distribute
>>> from sympy import Add, Mul, symbols
>>> x, y = symbols('x,y')
>>> dist = distribute(Mul, Add)
>>> expr = Mul(2, x+y, evaluate=False)
>>> expr
2*(x + y)
>>> dist(expr)
2*x + 2*y
"""
def distribute_rl(expr):
for i, arg in enumerate(expr.args):
if isinstance(arg, B):
first, b, tail = expr.args[:i], expr.args[i], expr.args[i+1:]
return B(*[A(*(first + (arg,) + tail)) for arg in b.args])
return expr
return distribute_rl | Turns an A containing Bs into a B of As
where A, B are container types
>>> from sympy.strategies import distribute
>>> from sympy import Add, Mul, symbols
>>> x, y = symbols('x,y')
>>> dist = distribute(Mul, Add)
>>> expr = Mul(2, x+y, evaluate=False)
>>> expr
2*(x + y)
>>> dist(expr)
2*x + 2*y
| Turns an A containing Bs into a B of As
where A, B are container types
| [
"Turns",
"an",
"A",
"containing",
"Bs",
"into",
"a",
"B",
"of",
"As",
"where",
"A",
"B",
"are",
"container",
"types"
] | def distribute(A, B):
def distribute_rl(expr):
for i, arg in enumerate(expr.args):
if isinstance(arg, B):
first, b, tail = expr.args[:i], expr.args[i], expr.args[i+1:]
return B(*[A(*(first + (arg,) + tail)) for arg in b.args])
return expr
return distribute_rl | [
"def",
"distribute",
"(",
"A",
",",
"B",
")",
":",
"def",
"distribute_rl",
"(",
"expr",
")",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"expr",
".",
"args",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"B",
")",
":",
"first",
",",
"b",
",",
"tail",
"=",
"expr",
".",
"args",
"[",
":",
"i",
"]",
",",
"expr",
".",
"args",
"[",
"i",
"]",
",",
"expr",
".",
"args",
"[",
"i",
"+",
"1",
":",
"]",
"return",
"B",
"(",
"*",
"[",
"A",
"(",
"*",
"(",
"first",
"+",
"(",
"arg",
",",
")",
"+",
"tail",
")",
")",
"for",
"arg",
"in",
"b",
".",
"args",
"]",
")",
"return",
"expr",
"return",
"distribute_rl"
] | Turns an A containing Bs into a B of As
where A, B are container types | [
"Turns",
"an",
"A",
"containing",
"Bs",
"into",
"a",
"B",
"of",
"As",
"where",
"A",
"B",
"are",
"container",
"types"
] | [
"\"\"\" Turns an A containing Bs into a B of As\n\n where A, B are container types\n\n >>> from sympy.strategies import distribute\n >>> from sympy import Add, Mul, symbols\n >>> x, y = symbols('x,y')\n >>> dist = distribute(Mul, Add)\n >>> expr = Mul(2, x+y, evaluate=False)\n >>> expr\n 2*(x + y)\n >>> dist(expr)\n 2*x + 2*y\n \"\"\""
] | [
{
"param": "A",
"type": null
},
{
"param": "B",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "A",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "B",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def distribute(A, B):
def distribute_rl(expr):
for i, arg in enumerate(expr.args):
if isinstance(arg, B):
first, b, tail = expr.args[:i], expr.args[i], expr.args[i+1:]
return B(*[A(*(first + (arg,) + tail)) for arg in b.args])
return expr
return distribute_rl | 610,322 | 365 |
913b3b136d852dee9672717386445abaad6a0056 | De117/scanner | SSLTester/SSLTester.py | [
"MIT"
] | Python | make_ssocket | <not_specific> | def make_ssocket(protocol, ciphers=ssl._DEFAULT_CIPHERS):
"""Creates a TCP socket wrapped in SSL."""
return ssl.wrap_socket( socket.socket(),
ssl_version=protocol,
ciphers=ciphers) | Creates a TCP socket wrapped in SSL. | Creates a TCP socket wrapped in SSL. | [
"Creates",
"a",
"TCP",
"socket",
"wrapped",
"in",
"SSL",
"."
] | def make_ssocket(protocol, ciphers=ssl._DEFAULT_CIPHERS):
return ssl.wrap_socket( socket.socket(),
ssl_version=protocol,
ciphers=ciphers) | [
"def",
"make_ssocket",
"(",
"protocol",
",",
"ciphers",
"=",
"ssl",
".",
"_DEFAULT_CIPHERS",
")",
":",
"return",
"ssl",
".",
"wrap_socket",
"(",
"socket",
".",
"socket",
"(",
")",
",",
"ssl_version",
"=",
"protocol",
",",
"ciphers",
"=",
"ciphers",
")"
] | Creates a TCP socket wrapped in SSL. | [
"Creates",
"a",
"TCP",
"socket",
"wrapped",
"in",
"SSL",
"."
] | [
"\"\"\"Creates a TCP socket wrapped in SSL.\"\"\""
] | [
{
"param": "protocol",
"type": null
},
{
"param": "ciphers",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "protocol",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ciphers",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import ssl
import socket
def make_ssocket(protocol, ciphers=ssl._DEFAULT_CIPHERS):
return ssl.wrap_socket( socket.socket(),
ssl_version=protocol,
ciphers=ciphers) | 610,324 | 357 |
c177d018efecea5a18366149644a7ba9caab240a | vc1492a/graphtransliterator | graphtransliterator/initialize.py | [
"MIT"
] | Python | _num_tokens_of | <not_specific> | def _num_tokens_of(rule):
"""Calculate the total number of tokens in a rule."""
total = len(rule.get("tokens"))
for _ in ("prev_classes", "prev_tokens", "next_tokens", "next_classes"):
val = rule.get(_)
if val:
total += len(val)
return total | Calculate the total number of tokens in a rule. | Calculate the total number of tokens in a rule. | [
"Calculate",
"the",
"total",
"number",
"of",
"tokens",
"in",
"a",
"rule",
"."
] | def _num_tokens_of(rule):
total = len(rule.get("tokens"))
for _ in ("prev_classes", "prev_tokens", "next_tokens", "next_classes"):
val = rule.get(_)
if val:
total += len(val)
return total | [
"def",
"_num_tokens_of",
"(",
"rule",
")",
":",
"total",
"=",
"len",
"(",
"rule",
".",
"get",
"(",
"\"tokens\"",
")",
")",
"for",
"_",
"in",
"(",
"\"prev_classes\"",
",",
"\"prev_tokens\"",
",",
"\"next_tokens\"",
",",
"\"next_classes\"",
")",
":",
"val",
"=",
"rule",
".",
"get",
"(",
"_",
")",
"if",
"val",
":",
"total",
"+=",
"len",
"(",
"val",
")",
"return",
"total"
] | Calculate the total number of tokens in a rule. | [
"Calculate",
"the",
"total",
"number",
"of",
"tokens",
"in",
"a",
"rule",
"."
] | [
"\"\"\"Calculate the total number of tokens in a rule.\"\"\""
] | [
{
"param": "rule",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _num_tokens_of(rule):
total = len(rule.get("tokens"))
for _ in ("prev_classes", "prev_tokens", "next_tokens", "next_classes"):
val = rule.get(_)
if val:
total += len(val)
return total | 610,325 | 98 |
6ad10b900bfb8f871b8237f634b696692e25c70b | tiltowait/inconnu | inconnu/character/update/paramupdate.py | [
"MIT"
] | Python | __update_xp | str | def __update_xp(character: VChar, xp_type: str, delta: str) -> str:
"""
Update a character's XP.
Args:
character (VChar): The character to update
xp_type (str): "total" or "current"
delta (str): The amount to add or remove
Does not catch exceptions.
"""
setting = False
# If the user doesn't supply a sign, they are setting the XP total rather
# than modifying it
if isinstance(delta, str):
if delta[0] not in ["+", "-"]:
setting = True
if not xp_type in ["total", "current"]:
raise SyntaxError(f"Unknown XP type: {xp_type}.") # Should never be seen
delta = int(delta)
new_xp = None
if setting:
new_xp = delta
else:
current = getattr(character, f"{xp_type.lower()}_xp")
new_xp = current + delta
# When displaying the update, we want to say whether they are doing a delta vs
# set and, if doing a delta, the *final* amound added/subtracted, after doing
# bounds-checking.
current = character.current_xp
if xp_type == "current":
character.current_xp = new_xp
cur_delta = character.current_xp - current
if setting:
return f"Set current/unspent XP to `{new_xp}`."
return f"`{cur_delta:+}` current/unspent XP."
total = character.total_xp
character.total_xp = new_xp
tot_delta = character.total_xp - total
cur_delta = character.current_xp - current
if setting:
return f"Set unspent XP to `{character.current_xp}`.\nSet lifetime XP to `{new_xp}`."
return f"`{cur_delta:+}` unspent XP.\n`{tot_delta:+}` lifetime XP." |
Update a character's XP.
Args:
character (VChar): The character to update
xp_type (str): "total" or "current"
delta (str): The amount to add or remove
Does not catch exceptions.
| Update a character's XP. | [
"Update",
"a",
"character",
"'",
"s",
"XP",
"."
] | def __update_xp(character: VChar, xp_type: str, delta: str) -> str:
setting = False
if isinstance(delta, str):
if delta[0] not in ["+", "-"]:
setting = True
if not xp_type in ["total", "current"]:
raise SyntaxError(f"Unknown XP type: {xp_type}.")
delta = int(delta)
new_xp = None
if setting:
new_xp = delta
else:
current = getattr(character, f"{xp_type.lower()}_xp")
new_xp = current + delta
current = character.current_xp
if xp_type == "current":
character.current_xp = new_xp
cur_delta = character.current_xp - current
if setting:
return f"Set current/unspent XP to `{new_xp}`."
return f"`{cur_delta:+}` current/unspent XP."
total = character.total_xp
character.total_xp = new_xp
tot_delta = character.total_xp - total
cur_delta = character.current_xp - current
if setting:
return f"Set unspent XP to `{character.current_xp}`.\nSet lifetime XP to `{new_xp}`."
return f"`{cur_delta:+}` unspent XP.\n`{tot_delta:+}` lifetime XP." | [
"def",
"__update_xp",
"(",
"character",
":",
"VChar",
",",
"xp_type",
":",
"str",
",",
"delta",
":",
"str",
")",
"->",
"str",
":",
"setting",
"=",
"False",
"if",
"isinstance",
"(",
"delta",
",",
"str",
")",
":",
"if",
"delta",
"[",
"0",
"]",
"not",
"in",
"[",
"\"+\"",
",",
"\"-\"",
"]",
":",
"setting",
"=",
"True",
"if",
"not",
"xp_type",
"in",
"[",
"\"total\"",
",",
"\"current\"",
"]",
":",
"raise",
"SyntaxError",
"(",
"f\"Unknown XP type: {xp_type}.\"",
")",
"delta",
"=",
"int",
"(",
"delta",
")",
"new_xp",
"=",
"None",
"if",
"setting",
":",
"new_xp",
"=",
"delta",
"else",
":",
"current",
"=",
"getattr",
"(",
"character",
",",
"f\"{xp_type.lower()}_xp\"",
")",
"new_xp",
"=",
"current",
"+",
"delta",
"current",
"=",
"character",
".",
"current_xp",
"if",
"xp_type",
"==",
"\"current\"",
":",
"character",
".",
"current_xp",
"=",
"new_xp",
"cur_delta",
"=",
"character",
".",
"current_xp",
"-",
"current",
"if",
"setting",
":",
"return",
"f\"Set current/unspent XP to `{new_xp}`.\"",
"return",
"f\"`{cur_delta:+}` current/unspent XP.\"",
"total",
"=",
"character",
".",
"total_xp",
"character",
".",
"total_xp",
"=",
"new_xp",
"tot_delta",
"=",
"character",
".",
"total_xp",
"-",
"total",
"cur_delta",
"=",
"character",
".",
"current_xp",
"-",
"current",
"if",
"setting",
":",
"return",
"f\"Set unspent XP to `{character.current_xp}`.\\nSet lifetime XP to `{new_xp}`.\"",
"return",
"f\"`{cur_delta:+}` unspent XP.\\n`{tot_delta:+}` lifetime XP.\""
] | Update a character's XP. | [
"Update",
"a",
"character",
"'",
"s",
"XP",
"."
] | [
"\"\"\"\n Update a character's XP.\n Args:\n character (VChar): The character to update\n xp_type (str): \"total\" or \"current\"\n delta (str): The amount to add or remove\n\n Does not catch exceptions.\n \"\"\"",
"# If the user doesn't supply a sign, they are setting the XP total rather",
"# than modifying it",
"# Should never be seen",
"# When displaying the update, we want to say whether they are doing a delta vs",
"# set and, if doing a delta, the *final* amound added/subtracted, after doing",
"# bounds-checking."
] | [
{
"param": "character",
"type": "VChar"
},
{
"param": "xp_type",
"type": "str"
},
{
"param": "delta",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "character",
"type": "VChar",
"docstring": "The character to update",
"docstring_tokens": [
"The",
"character",
"to",
"update"
],
"default": null,
"is_optional": false
},
{
"identifier": "xp_type",
"type": "str",
"docstring": "\"total\" or \"current\"",
"docstring_tokens": [
"\"",
"total",
"\"",
"or",
"\"",
"current",
"\""
],
"default": null,
"is_optional": false
},
{
"identifier": "delta",
"type": "str",
"docstring": "The amount to add or remove",
"docstring_tokens": [
"The",
"amount",
"to",
"add",
"or",
"remove"
],
"default": null,
"is_optional": false
}
],
"outlier_params": [],
"others": []
} | def __update_xp(character: VChar, xp_type: str, delta: str) -> str:
setting = False
if isinstance(delta, str):
if delta[0] not in ["+", "-"]:
setting = True
if not xp_type in ["total", "current"]:
raise SyntaxError(f"Unknown XP type: {xp_type}.")
delta = int(delta)
new_xp = None
if setting:
new_xp = delta
else:
current = getattr(character, f"{xp_type.lower()}_xp")
new_xp = current + delta
current = character.current_xp
if xp_type == "current":
character.current_xp = new_xp
cur_delta = character.current_xp - current
if setting:
return f"Set current/unspent XP to `{new_xp}`."
return f"`{cur_delta:+}` current/unspent XP."
total = character.total_xp
character.total_xp = new_xp
tot_delta = character.total_xp - total
cur_delta = character.current_xp - current
if setting:
return f"Set unspent XP to `{character.current_xp}`.\nSet lifetime XP to `{new_xp}`."
return f"`{cur_delta:+}` unspent XP.\n`{tot_delta:+}` lifetime XP." | 610,326 | 31 |
e873743178f538a5c1a82b0f66bcb08ba27a1f3a | mohamadmansourX/minihack | minihack/level_generator.py | [
"Apache-2.0"
] | Python | _validate_coord | <not_specific> | def _validate_coord(coord):
"""Validate a given typle of coordinates."""
assert (
isinstance(coord, tuple)
and len(coord) == 2
and isinstance(coord[0], int)
and isinstance(coord[1], int)
)
return coord | Validate a given typle of coordinates. | Validate a given typle of coordinates. | [
"Validate",
"a",
"given",
"typle",
"of",
"coordinates",
"."
] | def _validate_coord(coord):
assert (
isinstance(coord, tuple)
and len(coord) == 2
and isinstance(coord[0], int)
and isinstance(coord[1], int)
)
return coord | [
"def",
"_validate_coord",
"(",
"coord",
")",
":",
"assert",
"(",
"isinstance",
"(",
"coord",
",",
"tuple",
")",
"and",
"len",
"(",
"coord",
")",
"==",
"2",
"and",
"isinstance",
"(",
"coord",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"coord",
"[",
"1",
"]",
",",
"int",
")",
")",
"return",
"coord"
] | Validate a given typle of coordinates. | [
"Validate",
"a",
"given",
"typle",
"of",
"coordinates",
"."
] | [
"\"\"\"Validate a given typle of coordinates.\"\"\""
] | [
{
"param": "coord",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "coord",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _validate_coord(coord):
assert (
isinstance(coord, tuple)
and len(coord) == 2
and isinstance(coord[0], int)
and isinstance(coord[1], int)
)
return coord | 610,327 | 546 |
9b61e3e930687d581573d474a4b394e15115cc33 | KyleLavorato/Backpropagation-Machine-Learning | WineQualityAnalysis/ResultQuality7.py | [
"MIT"
] | Python | appendLine | null | def appendLine(line):
"""Append the supplied string to file"""
snOut = open("ResultsSeven.csv", "a")
snOut.write(line)
snOut.close() | Append the supplied string to file | Append the supplied string to file | [
"Append",
"the",
"supplied",
"string",
"to",
"file"
] | def appendLine(line):
snOut = open("ResultsSeven.csv", "a")
snOut.write(line)
snOut.close() | [
"def",
"appendLine",
"(",
"line",
")",
":",
"snOut",
"=",
"open",
"(",
"\"ResultsSeven.csv\"",
",",
"\"a\"",
")",
"snOut",
".",
"write",
"(",
"line",
")",
"snOut",
".",
"close",
"(",
")"
] | Append the supplied string to file | [
"Append",
"the",
"supplied",
"string",
"to",
"file"
] | [
"\"\"\"Append the supplied string to file\"\"\""
] | [
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def appendLine(line):
snOut = open("ResultsSeven.csv", "a")
snOut.write(line)
snOut.close() | 610,328 | 200 |
406593bd1e04e7cee53412c50948f49161d9faa8 | lawclaw/sudoku-cw | GameEngine/game.py | [
"Apache-2.0"
] | Python | save_game | None | def save_game(board) -> None:
"""
Save board into json save file
:param board: Board object
:return: None
"""
board.to_json() |
Save board into json save file
:param board: Board object
:return: None
| Save board into json save file | [
"Save",
"board",
"into",
"json",
"save",
"file"
] | def save_game(board) -> None:
board.to_json() | [
"def",
"save_game",
"(",
"board",
")",
"->",
"None",
":",
"board",
".",
"to_json",
"(",
")"
] | Save board into json save file | [
"Save",
"board",
"into",
"json",
"save",
"file"
] | [
"\"\"\"\n Save board into json save file\n :param board: Board object\n :return: None\n \"\"\""
] | [
{
"param": "board",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "board",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def save_game(board) -> None:
board.to_json() | 610,329 | 485 |
9a6c13a480b7082dfc5388a2abf5a3ea8375275c | Muhammada3178/checkov | checkov/common/util/http_utils.py | [
"Apache-2.0"
] | Python | normalize_prisma_url | <not_specific> | def normalize_prisma_url(url: str):
""" Correct common Prisma Cloud API URL misconfigurations """
if not url:
return None
return url.lower().replace('//app', '//api').replace('http:', 'https:').rstrip('/') | Correct common Prisma Cloud API URL misconfigurations | Correct common Prisma Cloud API URL misconfigurations | [
"Correct",
"common",
"Prisma",
"Cloud",
"API",
"URL",
"misconfigurations"
] | def normalize_prisma_url(url: str):
if not url:
return None
return url.lower().replace('//app', '//api').replace('http:', 'https:').rstrip('/') | [
"def",
"normalize_prisma_url",
"(",
"url",
":",
"str",
")",
":",
"if",
"not",
"url",
":",
"return",
"None",
"return",
"url",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'//app'",
",",
"'//api'",
")",
".",
"replace",
"(",
"'http:'",
",",
"'https:'",
")",
".",
"rstrip",
"(",
"'/'",
")"
] | Correct common Prisma Cloud API URL misconfigurations | [
"Correct",
"common",
"Prisma",
"Cloud",
"API",
"URL",
"misconfigurations"
] | [
"\"\"\" Correct common Prisma Cloud API URL misconfigurations \"\"\""
] | [
{
"param": "url",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "url",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def normalize_prisma_url(url: str):
if not url:
return None
return url.lower().replace('//app', '//api').replace('http:', 'https:').rstrip('/') | 610,330 | 976 |
c8a09034cfe1c9b23c365dbfba45931865d6386e | olaaustine/igsr_archive | tests/conftest.py | [
"Apache-2.0"
] | Python | chObject_withdrawn | <not_specific> | def chObject_withdrawn(ct_obj, db_dict):
"""
Fixture returning a ChangeEvents object
with a withdrawn path
"""
ct_obj.prod_tree = os.getenv('DATADIR') + "/ctree/current.plus1.tree"
file_dict = ct_obj.get_file_dict()
chObject = ct_obj.cmp_dicts(db_dict=db_dict, file_dict=file_dict)
return chObject |
Fixture returning a ChangeEvents object
with a withdrawn path
| Fixture returning a ChangeEvents object
with a withdrawn path | [
"Fixture",
"returning",
"a",
"ChangeEvents",
"object",
"with",
"a",
"withdrawn",
"path"
] | def chObject_withdrawn(ct_obj, db_dict):
ct_obj.prod_tree = os.getenv('DATADIR') + "/ctree/current.plus1.tree"
file_dict = ct_obj.get_file_dict()
chObject = ct_obj.cmp_dicts(db_dict=db_dict, file_dict=file_dict)
return chObject | [
"def",
"chObject_withdrawn",
"(",
"ct_obj",
",",
"db_dict",
")",
":",
"ct_obj",
".",
"prod_tree",
"=",
"os",
".",
"getenv",
"(",
"'DATADIR'",
")",
"+",
"\"/ctree/current.plus1.tree\"",
"file_dict",
"=",
"ct_obj",
".",
"get_file_dict",
"(",
")",
"chObject",
"=",
"ct_obj",
".",
"cmp_dicts",
"(",
"db_dict",
"=",
"db_dict",
",",
"file_dict",
"=",
"file_dict",
")",
"return",
"chObject"
] | Fixture returning a ChangeEvents object
with a withdrawn path | [
"Fixture",
"returning",
"a",
"ChangeEvents",
"object",
"with",
"a",
"withdrawn",
"path"
] | [
"\"\"\"\n Fixture returning a ChangeEvents object\n with a withdrawn path\n \"\"\""
] | [
{
"param": "ct_obj",
"type": null
},
{
"param": "db_dict",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ct_obj",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "db_dict",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def chObject_withdrawn(ct_obj, db_dict):
ct_obj.prod_tree = os.getenv('DATADIR') + "/ctree/current.plus1.tree"
file_dict = ct_obj.get_file_dict()
chObject = ct_obj.cmp_dicts(db_dict=db_dict, file_dict=file_dict)
return chObject | 610,332 | 438 |
b1223cb588ee3c17d3ecddd827dc25f86cc0505a | iashraful/fast-drf | fast_drf/tests/test_app/models.py | [
"MIT"
] | Python | api_version_fields | <not_specific> | def api_version_fields(cls, **kwargs):
"""
*** DEFAULT VERSION `v1` ***
This method will return a dictionary object with version number and fields name. Fields are similar like
serializer fields. Or you can say exactly as same as serializer fields.
:param kwargs: Currently nothing to receive on kwargs
:return: a dictionary object with version number
"""
versions = {
'v1': ['id', 'author', 'title', 'description'],
'v2': {
'fields': ['pk', 'author', 'title', 'description', 'meta', 'photo'],
'read_only_fields': ['pk', 'meta', 'photo'],
'optional_fields': ['description', 'author']
}
}
return versions |
*** DEFAULT VERSION `v1` ***
This method will return a dictionary object with version number and fields name. Fields are similar like
serializer fields. Or you can say exactly as same as serializer fields.
:param kwargs: Currently nothing to receive on kwargs
:return: a dictionary object with version number
| DEFAULT VERSION `v1`
This method will return a dictionary object with version number and fields name. Fields are similar like
serializer fields. Or you can say exactly as same as serializer fields. | [
"DEFAULT",
"VERSION",
"`",
"v1",
"`",
"This",
"method",
"will",
"return",
"a",
"dictionary",
"object",
"with",
"version",
"number",
"and",
"fields",
"name",
".",
"Fields",
"are",
"similar",
"like",
"serializer",
"fields",
".",
"Or",
"you",
"can",
"say",
"exactly",
"as",
"same",
"as",
"serializer",
"fields",
"."
] | def api_version_fields(cls, **kwargs):
versions = {
'v1': ['id', 'author', 'title', 'description'],
'v2': {
'fields': ['pk', 'author', 'title', 'description', 'meta', 'photo'],
'read_only_fields': ['pk', 'meta', 'photo'],
'optional_fields': ['description', 'author']
}
}
return versions | [
"def",
"api_version_fields",
"(",
"cls",
",",
"**",
"kwargs",
")",
":",
"versions",
"=",
"{",
"'v1'",
":",
"[",
"'id'",
",",
"'author'",
",",
"'title'",
",",
"'description'",
"]",
",",
"'v2'",
":",
"{",
"'fields'",
":",
"[",
"'pk'",
",",
"'author'",
",",
"'title'",
",",
"'description'",
",",
"'meta'",
",",
"'photo'",
"]",
",",
"'read_only_fields'",
":",
"[",
"'pk'",
",",
"'meta'",
",",
"'photo'",
"]",
",",
"'optional_fields'",
":",
"[",
"'description'",
",",
"'author'",
"]",
"}",
"}",
"return",
"versions"
] | DEFAULT VERSION `v1`
This method will return a dictionary object with version number and fields name. | [
"DEFAULT",
"VERSION",
"`",
"v1",
"`",
"This",
"method",
"will",
"return",
"a",
"dictionary",
"object",
"with",
"version",
"number",
"and",
"fields",
"name",
"."
] | [
"\"\"\"\n *** DEFAULT VERSION `v1` ***\n\n This method will return a dictionary object with version number and fields name. Fields are similar like\n serializer fields. Or you can say exactly as same as serializer fields.\n :param kwargs: Currently nothing to receive on kwargs\n :return: a dictionary object with version number\n \"\"\""
] | [
{
"param": "cls",
"type": null
}
] | {
"returns": [
{
"docstring": "a dictionary object with version number",
"docstring_tokens": [
"a",
"dictionary",
"object",
"with",
"version",
"number"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [
{
"identifier": "kwargs",
"type": null,
"docstring": "Currently nothing to receive on kwargs",
"docstring_tokens": [
"Currently",
"nothing",
"to",
"receive",
"on",
"kwargs"
],
"default": null,
"is_optional": null
}
],
"others": []
} | def api_version_fields(cls, **kwargs):
versions = {
'v1': ['id', 'author', 'title', 'description'],
'v2': {
'fields': ['pk', 'author', 'title', 'description', 'meta', 'photo'],
'read_only_fields': ['pk', 'meta', 'photo'],
'optional_fields': ['description', 'author']
}
}
return versions | 610,333 | 294 |
6d7ac876fdf65fe0e85cceb94c311a93d9ea39c2 | lijiancheng0614/Paddle | python/paddle/reader/decorator.py | [
"Apache-2.0"
] | Python | firstn | <not_specific> | def firstn(reader, n):
"""
Limit the max number of samples that reader could return.
:param reader: the data reader to read from.
:type reader: callable
:param n: the max number of samples that return.
:type n: int
:return: the decorated reader.
:rtype: callable
"""
# TODO(yuyang18): Check if just drop the reader, could clean the opened
# resource or not?
def firstn_reader():
for i, item in enumerate(reader()):
if i == n:
break
yield item
return firstn_reader |
Limit the max number of samples that reader could return.
:param reader: the data reader to read from.
:type reader: callable
:param n: the max number of samples that return.
:type n: int
:return: the decorated reader.
:rtype: callable
| Limit the max number of samples that reader could return. | [
"Limit",
"the",
"max",
"number",
"of",
"samples",
"that",
"reader",
"could",
"return",
"."
] | def firstn(reader, n):
def firstn_reader():
for i, item in enumerate(reader()):
if i == n:
break
yield item
return firstn_reader | [
"def",
"firstn",
"(",
"reader",
",",
"n",
")",
":",
"def",
"firstn_reader",
"(",
")",
":",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"reader",
"(",
")",
")",
":",
"if",
"i",
"==",
"n",
":",
"break",
"yield",
"item",
"return",
"firstn_reader"
] | Limit the max number of samples that reader could return. | [
"Limit",
"the",
"max",
"number",
"of",
"samples",
"that",
"reader",
"could",
"return",
"."
] | [
"\"\"\"\n Limit the max number of samples that reader could return.\n\n :param reader: the data reader to read from.\n :type reader: callable\n :param n: the max number of samples that return.\n :type n: int\n :return: the decorated reader.\n :rtype: callable\n \"\"\"",
"# TODO(yuyang18): Check if just drop the reader, could clean the opened",
"# resource or not?"
] | [
{
"param": "reader",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [
{
"docstring": "the decorated reader.",
"docstring_tokens": [
"the",
"decorated",
"reader",
"."
],
"type": "callable"
}
],
"raises": [],
"params": [
{
"identifier": "reader",
"type": null,
"docstring": "the data reader to read from.",
"docstring_tokens": [
"the",
"data",
"reader",
"to",
"read",
"from",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "n",
"type": null,
"docstring": "the max number of samples that return.",
"docstring_tokens": [
"the",
"max",
"number",
"of",
"samples",
"that",
"return",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def firstn(reader, n):
def firstn_reader():
for i, item in enumerate(reader()):
if i == n:
break
yield item
return firstn_reader | 610,334 | 23 |
215e1f50415caf80892021491f379d9a63a2bd27 | dendisuhubdy/two1-python | two1/bitcoin/crypto.py | [
"BSD-2-Clause-FreeBSD"
] | Python | from_private_key | <not_specific> | def from_private_key(private_key):
""" Generates a public key object from a PrivateKey object.
Args:
private_key (PrivateKey): The private key object from
which to derive this object.
Returns:
PublicKey: A PublicKey object.
"""
return private_key.public_key | Generates a public key object from a PrivateKey object.
Args:
private_key (PrivateKey): The private key object from
which to derive this object.
Returns:
PublicKey: A PublicKey object.
| Generates a public key object from a PrivateKey object. | [
"Generates",
"a",
"public",
"key",
"object",
"from",
"a",
"PrivateKey",
"object",
"."
] | def from_private_key(private_key):
return private_key.public_key | [
"def",
"from_private_key",
"(",
"private_key",
")",
":",
"return",
"private_key",
".",
"public_key"
] | Generates a public key object from a PrivateKey object. | [
"Generates",
"a",
"public",
"key",
"object",
"from",
"a",
"PrivateKey",
"object",
"."
] | [
"\"\"\" Generates a public key object from a PrivateKey object.\n\n Args:\n private_key (PrivateKey): The private key object from\n which to derive this object.\n\n Returns:\n PublicKey: A PublicKey object.\n \"\"\""
] | [
{
"param": "private_key",
"type": null
}
] | {
"returns": [
{
"docstring": "A PublicKey object.",
"docstring_tokens": [
"A",
"PublicKey",
"object",
"."
],
"type": "PublicKey"
}
],
"raises": [],
"params": [
{
"identifier": "private_key",
"type": null,
"docstring": "The private key object from\nwhich to derive this object.",
"docstring_tokens": [
"The",
"private",
"key",
"object",
"from",
"which",
"to",
"derive",
"this",
"object",
"."
],
"default": null,
"is_optional": false
}
],
"outlier_params": [],
"others": []
} | def from_private_key(private_key):
return private_key.public_key | 610,335 | 794 |
b4d192aa6e6a43a512a7e870476010fb0055e5df | mbargull/snakemake | snakemake/io.py | [
"MIT"
] | Python | limit | <not_specific> | def limit(pattern, **wildcards):
"""
Limit wildcards to the given values.
Arguments:
**wildcards -- the wildcards as keyword arguments
with their values as lists
"""
return pattern.format(
**{
wildcard: "{{{},{}}}".format(wildcard, "|".join(values))
for wildcard, values in wildcards.items()
}
) |
Limit wildcards to the given values.
Arguments:
**wildcards -- the wildcards as keyword arguments
with their values as lists
| Limit wildcards to the given values.
Arguments:
wildcards -- the wildcards as keyword arguments
with their values as lists | [
"Limit",
"wildcards",
"to",
"the",
"given",
"values",
".",
"Arguments",
":",
"wildcards",
"--",
"the",
"wildcards",
"as",
"keyword",
"arguments",
"with",
"their",
"values",
"as",
"lists"
] | def limit(pattern, **wildcards):
return pattern.format(
**{
wildcard: "{{{},{}}}".format(wildcard, "|".join(values))
for wildcard, values in wildcards.items()
}
) | [
"def",
"limit",
"(",
"pattern",
",",
"**",
"wildcards",
")",
":",
"return",
"pattern",
".",
"format",
"(",
"**",
"{",
"wildcard",
":",
"\"{{{},{}}}\"",
".",
"format",
"(",
"wildcard",
",",
"\"|\"",
".",
"join",
"(",
"values",
")",
")",
"for",
"wildcard",
",",
"values",
"in",
"wildcards",
".",
"items",
"(",
")",
"}",
")"
] | Limit wildcards to the given values. | [
"Limit",
"wildcards",
"to",
"the",
"given",
"values",
"."
] | [
"\"\"\"\n Limit wildcards to the given values.\n\n Arguments:\n **wildcards -- the wildcards as keyword arguments\n with their values as lists\n \"\"\""
] | [
{
"param": "pattern",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pattern",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def limit(pattern, **wildcards):
return pattern.format(
**{
wildcard: "{{{},{}}}".format(wildcard, "|".join(values))
for wildcard, values in wildcards.items()
}
) | 610,336 | 988 |
4ca72457efaa5e88f390b2b95946a5473af7a4de | RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | [
"Apache-2.0"
] | Python | print_result_for_plain_cgi_script | None | def print_result_for_plain_cgi_script(contenttype: str,
headers: TYPE_WSGI_RESPONSE_HEADERS,
content: bytes,
status: str = '200 OK') -> None:
"""
Writes HTTP request result to stdout.
"""
headers = [
("Status", status),
("Content-Type", contenttype),
("Content-Length", str(len(content))),
] + headers
sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n")
sys.stdout.buffer.write(content) |
Writes HTTP request result to stdout.
| Writes HTTP request result to stdout. | [
"Writes",
"HTTP",
"request",
"result",
"to",
"stdout",
"."
] | def print_result_for_plain_cgi_script(contenttype: str,
headers: TYPE_WSGI_RESPONSE_HEADERS,
content: bytes,
status: str = '200 OK') -> None:
headers = [
("Status", status),
("Content-Type", contenttype),
("Content-Length", str(len(content))),
] + headers
sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n")
sys.stdout.buffer.write(content) | [
"def",
"print_result_for_plain_cgi_script",
"(",
"contenttype",
":",
"str",
",",
"headers",
":",
"TYPE_WSGI_RESPONSE_HEADERS",
",",
"content",
":",
"bytes",
",",
"status",
":",
"str",
"=",
"'200 OK'",
")",
"->",
"None",
":",
"headers",
"=",
"[",
"(",
"\"Status\"",
",",
"status",
")",
",",
"(",
"\"Content-Type\"",
",",
"contenttype",
")",
",",
"(",
"\"Content-Length\"",
",",
"str",
"(",
"len",
"(",
"content",
")",
")",
")",
",",
"]",
"+",
"headers",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"\\n\"",
".",
"join",
"(",
"[",
"h",
"[",
"0",
"]",
"+",
"\": \"",
"+",
"h",
"[",
"1",
"]",
"for",
"h",
"in",
"headers",
"]",
")",
"+",
"\"\\n\\n\"",
")",
"sys",
".",
"stdout",
".",
"buffer",
".",
"write",
"(",
"content",
")"
] | Writes HTTP request result to stdout. | [
"Writes",
"HTTP",
"request",
"result",
"to",
"stdout",
"."
] | [
"\"\"\"\n Writes HTTP request result to stdout.\n \"\"\""
] | [
{
"param": "contenttype",
"type": "str"
},
{
"param": "headers",
"type": "TYPE_WSGI_RESPONSE_HEADERS"
},
{
"param": "content",
"type": "bytes"
},
{
"param": "status",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "contenttype",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "headers",
"type": "TYPE_WSGI_RESPONSE_HEADERS",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "content",
"type": "bytes",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "status",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import sys
def print_result_for_plain_cgi_script(contenttype: str,
headers: TYPE_WSGI_RESPONSE_HEADERS,
content: bytes,
status: str = '200 OK') -> None:
headers = [
("Status", status),
("Content-Type", contenttype),
("Content-Length", str(len(content))),
] + headers
sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n")
sys.stdout.buffer.write(content) | 610,337 | 241 |
7250f31f0856f540bacb7df2ef6ad8d151135858 | HMProenca/RuleList | rulelist/rulelistmodel/gain_add_rule.py | [
"MIT"
] | Python | compute_statistics_newrules | <not_specific> | def compute_statistics_newrules(rulelist, data, bitarray_subgroup):
""" Computes the statistics of 3 rules:
1. the new subgroup rule
2. the old "default" rule that covered the subgroup (only the cover of the subgroup not the rest)
3. the new default rule that covers the region not covered by any subgroup.
"""
rulelist.tmp_subgroup_statistic = rulelist.tmp_subgroup_statistic.replace_stats(data, bitarray_subgroup)
bitarray_new_defaultrule =rulelist.bitset_uncovered &~ bitarray_subgroup
rulelist.tmp_default_statistic = rulelist.tmp_default_statistic.replace_stats(data, bitarray_new_defaultrule)
return rulelist.tmp_subgroup_statistic, rulelist.tmp_default_statistic | Computes the statistics of 3 rules:
1. the new subgroup rule
2. the old "default" rule that covered the subgroup (only the cover of the subgroup not the rest)
3. the new default rule that covers the region not covered by any subgroup.
| Computes the statistics of 3 rules:
1. the new subgroup rule
2. the old "default" rule that covered the subgroup (only the cover of the subgroup not the rest)
3. the new default rule that covers the region not covered by any subgroup. | [
"Computes",
"the",
"statistics",
"of",
"3",
"rules",
":",
"1",
".",
"the",
"new",
"subgroup",
"rule",
"2",
".",
"the",
"old",
"\"",
"default",
"\"",
"rule",
"that",
"covered",
"the",
"subgroup",
"(",
"only",
"the",
"cover",
"of",
"the",
"subgroup",
"not",
"the",
"rest",
")",
"3",
".",
"the",
"new",
"default",
"rule",
"that",
"covers",
"the",
"region",
"not",
"covered",
"by",
"any",
"subgroup",
"."
] | def compute_statistics_newrules(rulelist, data, bitarray_subgroup):
rulelist.tmp_subgroup_statistic = rulelist.tmp_subgroup_statistic.replace_stats(data, bitarray_subgroup)
bitarray_new_defaultrule =rulelist.bitset_uncovered &~ bitarray_subgroup
rulelist.tmp_default_statistic = rulelist.tmp_default_statistic.replace_stats(data, bitarray_new_defaultrule)
return rulelist.tmp_subgroup_statistic, rulelist.tmp_default_statistic | [
"def",
"compute_statistics_newrules",
"(",
"rulelist",
",",
"data",
",",
"bitarray_subgroup",
")",
":",
"rulelist",
".",
"tmp_subgroup_statistic",
"=",
"rulelist",
".",
"tmp_subgroup_statistic",
".",
"replace_stats",
"(",
"data",
",",
"bitarray_subgroup",
")",
"bitarray_new_defaultrule",
"=",
"rulelist",
".",
"bitset_uncovered",
"&",
"~",
"bitarray_subgroup",
"rulelist",
".",
"tmp_default_statistic",
"=",
"rulelist",
".",
"tmp_default_statistic",
".",
"replace_stats",
"(",
"data",
",",
"bitarray_new_defaultrule",
")",
"return",
"rulelist",
".",
"tmp_subgroup_statistic",
",",
"rulelist",
".",
"tmp_default_statistic"
] | Computes the statistics of 3 rules:
1. the new subgroup rule
2. the old "default" rule that covered the subgroup (only the cover of the subgroup not the rest)
3. the new default rule that covers the region not covered by any subgroup. | [
"Computes",
"the",
"statistics",
"of",
"3",
"rules",
":",
"1",
".",
"the",
"new",
"subgroup",
"rule",
"2",
".",
"the",
"old",
"\"",
"default",
"\"",
"rule",
"that",
"covered",
"the",
"subgroup",
"(",
"only",
"the",
"cover",
"of",
"the",
"subgroup",
"not",
"the",
"rest",
")",
"3",
".",
"the",
"new",
"default",
"rule",
"that",
"covers",
"the",
"region",
"not",
"covered",
"by",
"any",
"subgroup",
"."
] | [
"\"\"\" Computes the statistics of 3 rules:\n 1. the new subgroup rule\n 2. the old \"default\" rule that covered the subgroup (only the cover of the subgroup not the rest)\n 3. the new default rule that covers the region not covered by any subgroup.\n\n \"\"\""
] | [
{
"param": "rulelist",
"type": null
},
{
"param": "data",
"type": null
},
{
"param": "bitarray_subgroup",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rulelist",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bitarray_subgroup",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def compute_statistics_newrules(rulelist, data, bitarray_subgroup):
rulelist.tmp_subgroup_statistic = rulelist.tmp_subgroup_statistic.replace_stats(data, bitarray_subgroup)
bitarray_new_defaultrule =rulelist.bitset_uncovered &~ bitarray_subgroup
rulelist.tmp_default_statistic = rulelist.tmp_default_statistic.replace_stats(data, bitarray_new_defaultrule)
return rulelist.tmp_subgroup_statistic, rulelist.tmp_default_statistic | 610,338 | 130 |
3b5a9203126f1cdf3d6b2e2421d2fa8c53288537 | nicolay-r/are-networks-experiments | callback_log_exp.py | [
"MIT"
] | Python | parse_last_epoch_results | <not_specific> | def parse_last_epoch_results(filepath):
""" Perform results reading from the related filepath
"""
# Example to parse:
# F1-last per iterations: [0.32, 0.229, 0.311]
iters = None
with open(filepath) as f:
for line in f.readlines():
if u'last per iterations' in line:
arr = line.split(':')[1].strip()
vals = arr[1:-1]
iters = [float(v) for v in vals.split(',')]
return iters | Perform results reading from the related filepath
| Perform results reading from the related filepath | [
"Perform",
"results",
"reading",
"from",
"the",
"related",
"filepath"
] | def parse_last_epoch_results(filepath):
iters = None
with open(filepath) as f:
for line in f.readlines():
if u'last per iterations' in line:
arr = line.split(':')[1].strip()
vals = arr[1:-1]
iters = [float(v) for v in vals.split(',')]
return iters | [
"def",
"parse_last_epoch_results",
"(",
"filepath",
")",
":",
"iters",
"=",
"None",
"with",
"open",
"(",
"filepath",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"u'last per iterations'",
"in",
"line",
":",
"arr",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"vals",
"=",
"arr",
"[",
"1",
":",
"-",
"1",
"]",
"iters",
"=",
"[",
"float",
"(",
"v",
")",
"for",
"v",
"in",
"vals",
".",
"split",
"(",
"','",
")",
"]",
"return",
"iters"
] | Perform results reading from the related filepath | [
"Perform",
"results",
"reading",
"from",
"the",
"related",
"filepath"
] | [
"\"\"\" Perform results reading from the related filepath\n \"\"\"",
"# Example to parse:",
"# F1-last per iterations: [0.32, 0.229, 0.311]"
] | [
{
"param": "filepath",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filepath",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def parse_last_epoch_results(filepath):
iters = None
with open(filepath) as f:
for line in f.readlines():
if u'last per iterations' in line:
arr = line.split(':')[1].strip()
vals = arr[1:-1]
iters = [float(v) for v in vals.split(',')]
return iters | 610,339 | 952 |
43bc49202b4a98d782f9b383db73722119dd67e4 | Vyryn/davidbot | functions.py | [
"MIT"
] | Python | order | <not_specific> | def order(x, count=0):
"""Returns the base 10 order of magnitude of a number"""
if x / 10 >= 1:
count += order(x / 10, count) + 1
return count | Returns the base 10 order of magnitude of a number | Returns the base 10 order of magnitude of a number | [
"Returns",
"the",
"base",
"10",
"order",
"of",
"magnitude",
"of",
"a",
"number"
] | def order(x, count=0):
if x / 10 >= 1:
count += order(x / 10, count) + 1
return count | [
"def",
"order",
"(",
"x",
",",
"count",
"=",
"0",
")",
":",
"if",
"x",
"/",
"10",
">=",
"1",
":",
"count",
"+=",
"order",
"(",
"x",
"/",
"10",
",",
"count",
")",
"+",
"1",
"return",
"count"
] | Returns the base 10 order of magnitude of a number | [
"Returns",
"the",
"base",
"10",
"order",
"of",
"magnitude",
"of",
"a",
"number"
] | [
"\"\"\"Returns the base 10 order of magnitude of a number\"\"\""
] | [
{
"param": "x",
"type": null
},
{
"param": "count",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "count",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def order(x, count=0):
if x / 10 >= 1:
count += order(x / 10, count) + 1
return count | 610,340 | 1,006 |
6326ebf3524a095a74e36281dbd8fbbb65af942e | dacb/elvizCluster | abundance_plot_utils.py | [
"BSD-3-Clause"
] | Python | axd_landscape | <not_specific> | def axd_landscape(axs):
"""
axis dictionary for landscape pages.
"""
return {('Low', 1): axs[0, 0], ('Low', 2): axs[0, 1], ('Low', 3): axs[0, 2], ('Low', 4): axs[0, 3],
('High', 1): axs[1, 0], ('High', 2): axs[1, 1], ('High', 3): axs[1, 2], ('High', 4): axs[1, 3]} |
axis dictionary for landscape pages.
| axis dictionary for landscape pages. | [
"axis",
"dictionary",
"for",
"landscape",
"pages",
"."
] | def axd_landscape(axs):
return {('Low', 1): axs[0, 0], ('Low', 2): axs[0, 1], ('Low', 3): axs[0, 2], ('Low', 4): axs[0, 3],
('High', 1): axs[1, 0], ('High', 2): axs[1, 1], ('High', 3): axs[1, 2], ('High', 4): axs[1, 3]} | [
"def",
"axd_landscape",
"(",
"axs",
")",
":",
"return",
"{",
"(",
"'Low'",
",",
"1",
")",
":",
"axs",
"[",
"0",
",",
"0",
"]",
",",
"(",
"'Low'",
",",
"2",
")",
":",
"axs",
"[",
"0",
",",
"1",
"]",
",",
"(",
"'Low'",
",",
"3",
")",
":",
"axs",
"[",
"0",
",",
"2",
"]",
",",
"(",
"'Low'",
",",
"4",
")",
":",
"axs",
"[",
"0",
",",
"3",
"]",
",",
"(",
"'High'",
",",
"1",
")",
":",
"axs",
"[",
"1",
",",
"0",
"]",
",",
"(",
"'High'",
",",
"2",
")",
":",
"axs",
"[",
"1",
",",
"1",
"]",
",",
"(",
"'High'",
",",
"3",
")",
":",
"axs",
"[",
"1",
",",
"2",
"]",
",",
"(",
"'High'",
",",
"4",
")",
":",
"axs",
"[",
"1",
",",
"3",
"]",
"}"
] | axis dictionary for landscape pages. | [
"axis",
"dictionary",
"for",
"landscape",
"pages",
"."
] | [
"\"\"\"\n axis dictionary for landscape pages.\n \"\"\""
] | [
{
"param": "axs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "axs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def axd_landscape(axs):
return {('Low', 1): axs[0, 0], ('Low', 2): axs[0, 1], ('Low', 3): axs[0, 2], ('Low', 4): axs[0, 3],
('High', 1): axs[1, 0], ('High', 2): axs[1, 1], ('High', 3): axs[1, 2], ('High', 4): axs[1, 3]} | 610,341 | 400 |
52788d70613495656c8e909b2542817317e55865 | zamberjo/tron-api-python | tronapi/tron.py | [
"Apache-2.0"
] | Python | string_utf8_to_hex | <not_specific> | def string_utf8_to_hex(name):
"""Convert a string to Hex format
Args:
name (str): string
"""
return bytes(name, encoding='utf-8').hex() | Convert a string to Hex format
Args:
name (str): string
| Convert a string to Hex format | [
"Convert",
"a",
"string",
"to",
"Hex",
"format"
] | def string_utf8_to_hex(name):
return bytes(name, encoding='utf-8').hex() | [
"def",
"string_utf8_to_hex",
"(",
"name",
")",
":",
"return",
"bytes",
"(",
"name",
",",
"encoding",
"=",
"'utf-8'",
")",
".",
"hex",
"(",
")"
] | Convert a string to Hex format | [
"Convert",
"a",
"string",
"to",
"Hex",
"format"
] | [
"\"\"\"Convert a string to Hex format\n\n Args:\n name (str): string\n\n \"\"\""
] | [
{
"param": "name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
}
],
"outlier_params": [],
"others": []
} | def string_utf8_to_hex(name):
return bytes(name, encoding='utf-8').hex() | 610,342 | 755 |
ffb7943a5e6f9276de04202036593148ae6db2ab | CGATOxford/Optic | Optic/MaliIO.py | [
"MIT"
] | Python | removeGappedColumns | <not_specific> | def removeGappedColumns(mali, gap_char="-"):
"""remove all gapped columns in mali."""
if len(mali) == 0:
return mali
keys = mali.keys()
lmali = len(mali[keys[0]])
wmali = len(keys)
gaps_per_column = [0] * lmali
for m in mali.values():
for x in range(lmali):
if m[x] == gap_char:
gaps_per_column[x] += 1
new_mali = {}
for k in keys:
s = []
m = mali[k]
for x in range(lmali):
if gaps_per_column[x] < wmali:
s += m[x]
new_mali[k] = string.join(s, "")
return new_mali | remove all gapped columns in mali. | remove all gapped columns in mali. | [
"remove",
"all",
"gapped",
"columns",
"in",
"mali",
"."
] | def removeGappedColumns(mali, gap_char="-"):
if len(mali) == 0:
return mali
keys = mali.keys()
lmali = len(mali[keys[0]])
wmali = len(keys)
gaps_per_column = [0] * lmali
for m in mali.values():
for x in range(lmali):
if m[x] == gap_char:
gaps_per_column[x] += 1
new_mali = {}
for k in keys:
s = []
m = mali[k]
for x in range(lmali):
if gaps_per_column[x] < wmali:
s += m[x]
new_mali[k] = string.join(s, "")
return new_mali | [
"def",
"removeGappedColumns",
"(",
"mali",
",",
"gap_char",
"=",
"\"-\"",
")",
":",
"if",
"len",
"(",
"mali",
")",
"==",
"0",
":",
"return",
"mali",
"keys",
"=",
"mali",
".",
"keys",
"(",
")",
"lmali",
"=",
"len",
"(",
"mali",
"[",
"keys",
"[",
"0",
"]",
"]",
")",
"wmali",
"=",
"len",
"(",
"keys",
")",
"gaps_per_column",
"=",
"[",
"0",
"]",
"*",
"lmali",
"for",
"m",
"in",
"mali",
".",
"values",
"(",
")",
":",
"for",
"x",
"in",
"range",
"(",
"lmali",
")",
":",
"if",
"m",
"[",
"x",
"]",
"==",
"gap_char",
":",
"gaps_per_column",
"[",
"x",
"]",
"+=",
"1",
"new_mali",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"s",
"=",
"[",
"]",
"m",
"=",
"mali",
"[",
"k",
"]",
"for",
"x",
"in",
"range",
"(",
"lmali",
")",
":",
"if",
"gaps_per_column",
"[",
"x",
"]",
"<",
"wmali",
":",
"s",
"+=",
"m",
"[",
"x",
"]",
"new_mali",
"[",
"k",
"]",
"=",
"string",
".",
"join",
"(",
"s",
",",
"\"\"",
")",
"return",
"new_mali"
] | remove all gapped columns in mali. | [
"remove",
"all",
"gapped",
"columns",
"in",
"mali",
"."
] | [
"\"\"\"remove all gapped columns in mali.\"\"\""
] | [
{
"param": "mali",
"type": null
},
{
"param": "gap_char",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "mali",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "gap_char",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import string
def removeGappedColumns(mali, gap_char="-"):
if len(mali) == 0:
return mali
keys = mali.keys()
lmali = len(mali[keys[0]])
wmali = len(keys)
gaps_per_column = [0] * lmali
for m in mali.values():
for x in range(lmali):
if m[x] == gap_char:
gaps_per_column[x] += 1
new_mali = {}
for k in keys:
s = []
m = mali[k]
for x in range(lmali):
if gaps_per_column[x] < wmali:
s += m[x]
new_mali[k] = string.join(s, "")
return new_mali | 610,344 | 945 |
18466c32671c98fab43d5fb4c276bb79d0c7d04d | cameron-freshworks/ppr | ppr-api/src/ppr_api/models/search_utils.py | [
"Apache-2.0"
] | Python | format_mhr_number | null | def format_mhr_number(request_json):
"""Trim and pad with zeroes search query mhr number query."""
mhr_num: str = request_json['criteria']['value']
mhr_num = mhr_num.strip().rjust(6, '0')
request_json['criteria']['value'] = mhr_num | Trim and pad with zeroes search query mhr number query. | Trim and pad with zeroes search query mhr number query. | [
"Trim",
"and",
"pad",
"with",
"zeroes",
"search",
"query",
"mhr",
"number",
"query",
"."
] | def format_mhr_number(request_json):
mhr_num: str = request_json['criteria']['value']
mhr_num = mhr_num.strip().rjust(6, '0')
request_json['criteria']['value'] = mhr_num | [
"def",
"format_mhr_number",
"(",
"request_json",
")",
":",
"mhr_num",
":",
"str",
"=",
"request_json",
"[",
"'criteria'",
"]",
"[",
"'value'",
"]",
"mhr_num",
"=",
"mhr_num",
".",
"strip",
"(",
")",
".",
"rjust",
"(",
"6",
",",
"'0'",
")",
"request_json",
"[",
"'criteria'",
"]",
"[",
"'value'",
"]",
"=",
"mhr_num"
] | Trim and pad with zeroes search query mhr number query. | [
"Trim",
"and",
"pad",
"with",
"zeroes",
"search",
"query",
"mhr",
"number",
"query",
"."
] | [
"\"\"\"Trim and pad with zeroes search query mhr number query.\"\"\""
] | [
{
"param": "request_json",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "request_json",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def format_mhr_number(request_json):
mhr_num: str = request_json['criteria']['value']
mhr_num = mhr_num.strip().rjust(6, '0')
request_json['criteria']['value'] = mhr_num | 610,345 | 97 |
87f25981d11d7b420f22f0f7f1a04dbcd458c247 | jeremie-gauthier/al-go-rithms | sort/selection_sort/python/selection_sort2.py | [
"CC0-1.0"
] | Python | selection_sort | <not_specific> | def selection_sort(items):
"""Implementation of the selection sort algorithm using Python
inside parameter we can pass some items which are heterogeneous
comparable
"""
length = len(items)
for i in range(length):
least = i
for j in range(i + 1, length):
if items[j] < items[least]:
least = j
items[least], items[i] = (
items[i], items[least]
)
return items | Implementation of the selection sort algorithm using Python
inside parameter we can pass some items which are heterogeneous
comparable
| Implementation of the selection sort algorithm using Python
inside parameter we can pass some items which are heterogeneous
comparable | [
"Implementation",
"of",
"the",
"selection",
"sort",
"algorithm",
"using",
"Python",
"inside",
"parameter",
"we",
"can",
"pass",
"some",
"items",
"which",
"are",
"heterogeneous",
"comparable"
] | def selection_sort(items):
length = len(items)
for i in range(length):
least = i
for j in range(i + 1, length):
if items[j] < items[least]:
least = j
items[least], items[i] = (
items[i], items[least]
)
return items | [
"def",
"selection_sort",
"(",
"items",
")",
":",
"length",
"=",
"len",
"(",
"items",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
":",
"least",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"length",
")",
":",
"if",
"items",
"[",
"j",
"]",
"<",
"items",
"[",
"least",
"]",
":",
"least",
"=",
"j",
"items",
"[",
"least",
"]",
",",
"items",
"[",
"i",
"]",
"=",
"(",
"items",
"[",
"i",
"]",
",",
"items",
"[",
"least",
"]",
")",
"return",
"items"
] | Implementation of the selection sort algorithm using Python
inside parameter we can pass some items which are heterogeneous
comparable | [
"Implementation",
"of",
"the",
"selection",
"sort",
"algorithm",
"using",
"Python",
"inside",
"parameter",
"we",
"can",
"pass",
"some",
"items",
"which",
"are",
"heterogeneous",
"comparable"
] | [
"\"\"\"Implementation of the selection sort algorithm using Python\n inside parameter we can pass some items which are heterogeneous\n comparable\n \"\"\""
] | [
{
"param": "items",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "items",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def selection_sort(items):
length = len(items)
for i in range(length):
least = i
for j in range(i + 1, length):
if items[j] < items[least]:
least = j
items[least], items[i] = (
items[i], items[least]
)
return items | 610,346 | 792 |
0c6f756e4a668819a1361332e48a1468d48c9f4a | JonathanBodine/stale-news | code/replication/utils.py | [
"MIT"
] | Python | bookValue | <not_specific> | def bookValue(firm, date, pdatabase, printWarnings=True, bookUnit=1000000):
"""
Firm's book value as of latest quarterly earnings report preceding date
Relies on naming of pdatabase (compustat) and chronological data for each firm
Returns -1 if no data available
Returns FLOAT
"""
bookQuery = pdatabase.data.query('(tic == "' + firm + '") & (datadate < ' + date + ')')
# print(bookQuery)
if bookQuery.empty:
if printWarnings:
print("NO BOOK DATA: " + firm + ", " + date)
return -1
bookSeries = bookQuery["ceqq"]
return float(bookSeries.iat[bookSeries.size - 1] * bookUnit) |
Firm's book value as of latest quarterly earnings report preceding date
Relies on naming of pdatabase (compustat) and chronological data for each firm
Returns -1 if no data available
Returns FLOAT
| Firm's book value as of latest quarterly earnings report preceding date
Relies on naming of pdatabase (compustat) and chronological data for each firm
Returns -1 if no data available
Returns FLOAT | [
"Firm",
"'",
"s",
"book",
"value",
"as",
"of",
"latest",
"quarterly",
"earnings",
"report",
"preceding",
"date",
"Relies",
"on",
"naming",
"of",
"pdatabase",
"(",
"compustat",
")",
"and",
"chronological",
"data",
"for",
"each",
"firm",
"Returns",
"-",
"1",
"if",
"no",
"data",
"available",
"Returns",
"FLOAT"
] | def bookValue(firm, date, pdatabase, printWarnings=True, bookUnit=1000000):
bookQuery = pdatabase.data.query('(tic == "' + firm + '") & (datadate < ' + date + ')')
if bookQuery.empty:
if printWarnings:
print("NO BOOK DATA: " + firm + ", " + date)
return -1
bookSeries = bookQuery["ceqq"]
return float(bookSeries.iat[bookSeries.size - 1] * bookUnit) | [
"def",
"bookValue",
"(",
"firm",
",",
"date",
",",
"pdatabase",
",",
"printWarnings",
"=",
"True",
",",
"bookUnit",
"=",
"1000000",
")",
":",
"bookQuery",
"=",
"pdatabase",
".",
"data",
".",
"query",
"(",
"'(tic == \"'",
"+",
"firm",
"+",
"'\") & (datadate < '",
"+",
"date",
"+",
"')'",
")",
"if",
"bookQuery",
".",
"empty",
":",
"if",
"printWarnings",
":",
"print",
"(",
"\"NO BOOK DATA: \"",
"+",
"firm",
"+",
"\", \"",
"+",
"date",
")",
"return",
"-",
"1",
"bookSeries",
"=",
"bookQuery",
"[",
"\"ceqq\"",
"]",
"return",
"float",
"(",
"bookSeries",
".",
"iat",
"[",
"bookSeries",
".",
"size",
"-",
"1",
"]",
"*",
"bookUnit",
")"
] | Firm's book value as of latest quarterly earnings report preceding date
Relies on naming of pdatabase (compustat) and chronological data for each firm
Returns -1 if no data available
Returns FLOAT | [
"Firm",
"'",
"s",
"book",
"value",
"as",
"of",
"latest",
"quarterly",
"earnings",
"report",
"preceding",
"date",
"Relies",
"on",
"naming",
"of",
"pdatabase",
"(",
"compustat",
")",
"and",
"chronological",
"data",
"for",
"each",
"firm",
"Returns",
"-",
"1",
"if",
"no",
"data",
"available",
"Returns",
"FLOAT"
] | [
"\"\"\"\n Firm's book value as of latest quarterly earnings report preceding date\n Relies on naming of pdatabase (compustat) and chronological data for each firm\n Returns -1 if no data available\n Returns FLOAT\n \"\"\"",
"# print(bookQuery)"
] | [
{
"param": "firm",
"type": null
},
{
"param": "date",
"type": null
},
{
"param": "pdatabase",
"type": null
},
{
"param": "printWarnings",
"type": null
},
{
"param": "bookUnit",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "firm",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "date",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pdatabase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "printWarnings",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bookUnit",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def bookValue(firm, date, pdatabase, printWarnings=True, bookUnit=1000000):
bookQuery = pdatabase.data.query('(tic == "' + firm + '") & (datadate < ' + date + ')')
if bookQuery.empty:
if printWarnings:
print("NO BOOK DATA: " + firm + ", " + date)
return -1
bookSeries = bookQuery["ceqq"]
return float(bookSeries.iat[bookSeries.size - 1] * bookUnit) | 610,347 | 423 |
2f414201eb94bd364da5c0e1db5d60819b258684 | eltoredo/ChatBot | venv/lib/python3.6/site-packages/falcon/testing/resource.py | [
"Apache-2.0"
] | Python | capture_responder_args | null | def capture_responder_args(req, resp, resource, params):
"""Before hook for capturing responder arguments.
Adds the following attributes to the hooked responder's resource
class:
* captured_req
* captured_resp
* captured_kwargs
"""
resource.captured_req = req
resource.captured_resp = resp
resource.captured_kwargs = params | Before hook for capturing responder arguments.
Adds the following attributes to the hooked responder's resource
class:
* captured_req
* captured_resp
* captured_kwargs
| Before hook for capturing responder arguments.
Adds the following attributes to the hooked responder's resource
class.
| [
"Before",
"hook",
"for",
"capturing",
"responder",
"arguments",
".",
"Adds",
"the",
"following",
"attributes",
"to",
"the",
"hooked",
"responder",
"'",
"s",
"resource",
"class",
"."
] | def capture_responder_args(req, resp, resource, params):
resource.captured_req = req
resource.captured_resp = resp
resource.captured_kwargs = params | [
"def",
"capture_responder_args",
"(",
"req",
",",
"resp",
",",
"resource",
",",
"params",
")",
":",
"resource",
".",
"captured_req",
"=",
"req",
"resource",
".",
"captured_resp",
"=",
"resp",
"resource",
".",
"captured_kwargs",
"=",
"params"
] | Before hook for capturing responder arguments. | [
"Before",
"hook",
"for",
"capturing",
"responder",
"arguments",
"."
] | [
"\"\"\"Before hook for capturing responder arguments.\n\n Adds the following attributes to the hooked responder's resource\n class:\n\n * captured_req\n * captured_resp\n * captured_kwargs\n \"\"\""
] | [
{
"param": "req",
"type": null
},
{
"param": "resp",
"type": null
},
{
"param": "resource",
"type": null
},
{
"param": "params",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "req",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "resp",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "resource",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "params",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def capture_responder_args(req, resp, resource, params):
resource.captured_req = req
resource.captured_resp = resp
resource.captured_kwargs = params | 610,348 | 657 |
4fc87b44d73d035a06d1285767817d16bf257e50 | xflows/clowdflows | workflows/templatetags/paginator.py | [
"MIT"
] | Python | paginator | <not_specific> | def paginator(context, adjacent_pages=2):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
Required context variables: paged: The Paginator.page() instance.
"""
paged = context['paged'] # the paginator.page(page) instance
paginator = paged.paginator
startPage = max(paged.number - adjacent_pages, 1)
if startPage <= 3: startPage = 1
endPage = paged.number + adjacent_pages + 1
if endPage >= paginator.num_pages - 1: endPage = paginator.num_pages + 1
page_numbers = [n for n in range(startPage, endPage) \
if n > 0 and n <= paginator.num_pages]
return {
'paged': paged,
'paginator': paginator,
'page': paged.number,
'pages': paginator.num_pages,
'page_numbers': page_numbers,
'next': paged.next_page_number(),
'previous': paged.previous_page_number(),
'has_next': paged.has_next(),
'has_previous': paged.has_previous(),
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'last':paginator.num_pages,
} |
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
Required context variables: paged: The Paginator.page() instance.
| To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
Required context variables: paged: The Paginator.page() instance. | [
"To",
"be",
"used",
"in",
"conjunction",
"with",
"the",
"object_list",
"generic",
"view",
".",
"Adds",
"pagination",
"context",
"variables",
"for",
"use",
"in",
"displaying",
"first",
"adjacent",
"and",
"last",
"page",
"links",
"in",
"addition",
"to",
"those",
"created",
"by",
"the",
"object_list",
"generic",
"view",
".",
"Required",
"context",
"variables",
":",
"paged",
":",
"The",
"Paginator",
".",
"page",
"()",
"instance",
"."
] | def paginator(context, adjacent_pages=2):
paged = context['paged']
paginator = paged.paginator
startPage = max(paged.number - adjacent_pages, 1)
if startPage <= 3: startPage = 1
endPage = paged.number + adjacent_pages + 1
if endPage >= paginator.num_pages - 1: endPage = paginator.num_pages + 1
page_numbers = [n for n in range(startPage, endPage) \
if n > 0 and n <= paginator.num_pages]
return {
'paged': paged,
'paginator': paginator,
'page': paged.number,
'pages': paginator.num_pages,
'page_numbers': page_numbers,
'next': paged.next_page_number(),
'previous': paged.previous_page_number(),
'has_next': paged.has_next(),
'has_previous': paged.has_previous(),
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'last':paginator.num_pages,
} | [
"def",
"paginator",
"(",
"context",
",",
"adjacent_pages",
"=",
"2",
")",
":",
"paged",
"=",
"context",
"[",
"'paged'",
"]",
"paginator",
"=",
"paged",
".",
"paginator",
"startPage",
"=",
"max",
"(",
"paged",
".",
"number",
"-",
"adjacent_pages",
",",
"1",
")",
"if",
"startPage",
"<=",
"3",
":",
"startPage",
"=",
"1",
"endPage",
"=",
"paged",
".",
"number",
"+",
"adjacent_pages",
"+",
"1",
"if",
"endPage",
">=",
"paginator",
".",
"num_pages",
"-",
"1",
":",
"endPage",
"=",
"paginator",
".",
"num_pages",
"+",
"1",
"page_numbers",
"=",
"[",
"n",
"for",
"n",
"in",
"range",
"(",
"startPage",
",",
"endPage",
")",
"if",
"n",
">",
"0",
"and",
"n",
"<=",
"paginator",
".",
"num_pages",
"]",
"return",
"{",
"'paged'",
":",
"paged",
",",
"'paginator'",
":",
"paginator",
",",
"'page'",
":",
"paged",
".",
"number",
",",
"'pages'",
":",
"paginator",
".",
"num_pages",
",",
"'page_numbers'",
":",
"page_numbers",
",",
"'next'",
":",
"paged",
".",
"next_page_number",
"(",
")",
",",
"'previous'",
":",
"paged",
".",
"previous_page_number",
"(",
")",
",",
"'has_next'",
":",
"paged",
".",
"has_next",
"(",
")",
",",
"'has_previous'",
":",
"paged",
".",
"has_previous",
"(",
")",
",",
"'show_first'",
":",
"1",
"not",
"in",
"page_numbers",
",",
"'show_last'",
":",
"paginator",
".",
"num_pages",
"not",
"in",
"page_numbers",
",",
"'last'",
":",
"paginator",
".",
"num_pages",
",",
"}"
] | To be used in conjunction with the object_list generic view. | [
"To",
"be",
"used",
"in",
"conjunction",
"with",
"the",
"object_list",
"generic",
"view",
"."
] | [
"\"\"\"\r\n To be used in conjunction with the object_list generic view.\r\n\r\n Adds pagination context variables for use in displaying first, adjacent and\r\n last page links in addition to those created by the object_list generic\r\n view.\r\n\r\n Required context variables: paged: The Paginator.page() instance.\r\n\r\n \"\"\"",
"# the paginator.page(page) instance\r"
] | [
{
"param": "context",
"type": null
},
{
"param": "adjacent_pages",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "context",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "adjacent_pages",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def paginator(context, adjacent_pages=2):
paged = context['paged']
paginator = paged.paginator
startPage = max(paged.number - adjacent_pages, 1)
if startPage <= 3: startPage = 1
endPage = paged.number + adjacent_pages + 1
if endPage >= paginator.num_pages - 1: endPage = paginator.num_pages + 1
page_numbers = [n for n in range(startPage, endPage) \
if n > 0 and n <= paginator.num_pages]
return {
'paged': paged,
'paginator': paginator,
'page': paged.number,
'pages': paginator.num_pages,
'page_numbers': page_numbers,
'next': paged.next_page_number(),
'previous': paged.previous_page_number(),
'has_next': paged.has_next(),
'has_previous': paged.has_previous(),
'show_first': 1 not in page_numbers,
'show_last': paginator.num_pages not in page_numbers,
'last':paginator.num_pages,
} | 610,349 | 909 |
ff5a5d6b21dcafb0ce8bcf79349adb89926842a0 | cloudpassage/ec2-halo-delta | app/ehdlib/report.py | [
"BSD-3-Clause"
] | Python | format_aws_instance | <not_specific> | def format_aws_instance(cls, aws_instance):
"""Format an AWS instance's metadata for reporting.
Args:
aws_instance(tuple): Formatted like this:
("i-231423452", {"aws_account": "12345",
"aws_region": "us-east-1",
"key_name": "my_ssh_key",
"launch_time": "1999-12-31T23:59.9"}}
"""
instance_id = "Instance ID: {instance}".format(instance=aws_instance[0]) # NOQA
aws_account = "AWS Account: {account}".format(account=aws_instance[1]["aws_account"]) # NOQA
aws_region = "AWS Region: {region}".format(region=aws_instance[1]["aws_region"]) # NOQA
key_name = "Key Name: {key_}".format(key_=aws_instance[1]["key_name"])
launch = "Launched at: {launch}".format(launch=aws_instance[1]["launch_time"]) # NOQA
vpc_id = "VPC ID: {vpc}".format(vpc=aws_instance[1]["vpc_id"])
ordered_fields = [aws_account, aws_region, key_name, vpc_id,
instance_id, launch]
return "\n".join(ordered_fields) | Format an AWS instance's metadata for reporting.
Args:
aws_instance(tuple): Formatted like this:
("i-231423452", {"aws_account": "12345",
"aws_region": "us-east-1",
"key_name": "my_ssh_key",
"launch_time": "1999-12-31T23:59.9"}}
| Format an AWS instance's metadata for reporting. | [
"Format",
"an",
"AWS",
"instance",
"'",
"s",
"metadata",
"for",
"reporting",
"."
] | def format_aws_instance(cls, aws_instance):
instance_id = "Instance ID: {instance}".format(instance=aws_instance[0])
aws_account = "AWS Account: {account}".format(account=aws_instance[1]["aws_account"])
aws_region = "AWS Region: {region}".format(region=aws_instance[1]["aws_region"])
key_name = "Key Name: {key_}".format(key_=aws_instance[1]["key_name"])
launch = "Launched at: {launch}".format(launch=aws_instance[1]["launch_time"])
vpc_id = "VPC ID: {vpc}".format(vpc=aws_instance[1]["vpc_id"])
ordered_fields = [aws_account, aws_region, key_name, vpc_id,
instance_id, launch]
return "\n".join(ordered_fields) | [
"def",
"format_aws_instance",
"(",
"cls",
",",
"aws_instance",
")",
":",
"instance_id",
"=",
"\"Instance ID: {instance}\"",
".",
"format",
"(",
"instance",
"=",
"aws_instance",
"[",
"0",
"]",
")",
"aws_account",
"=",
"\"AWS Account: {account}\"",
".",
"format",
"(",
"account",
"=",
"aws_instance",
"[",
"1",
"]",
"[",
"\"aws_account\"",
"]",
")",
"aws_region",
"=",
"\"AWS Region: {region}\"",
".",
"format",
"(",
"region",
"=",
"aws_instance",
"[",
"1",
"]",
"[",
"\"aws_region\"",
"]",
")",
"key_name",
"=",
"\"Key Name: {key_}\"",
".",
"format",
"(",
"key_",
"=",
"aws_instance",
"[",
"1",
"]",
"[",
"\"key_name\"",
"]",
")",
"launch",
"=",
"\"Launched at: {launch}\"",
".",
"format",
"(",
"launch",
"=",
"aws_instance",
"[",
"1",
"]",
"[",
"\"launch_time\"",
"]",
")",
"vpc_id",
"=",
"\"VPC ID: {vpc}\"",
".",
"format",
"(",
"vpc",
"=",
"aws_instance",
"[",
"1",
"]",
"[",
"\"vpc_id\"",
"]",
")",
"ordered_fields",
"=",
"[",
"aws_account",
",",
"aws_region",
",",
"key_name",
",",
"vpc_id",
",",
"instance_id",
",",
"launch",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
"ordered_fields",
")"
] | Format an AWS instance's metadata for reporting. | [
"Format",
"an",
"AWS",
"instance",
"'",
"s",
"metadata",
"for",
"reporting",
"."
] | [
"\"\"\"Format an AWS instance's metadata for reporting.\n\n Args:\n aws_instance(tuple): Formatted like this:\n (\"i-231423452\", {\"aws_account\": \"12345\",\n \"aws_region\": \"us-east-1\",\n \"key_name\": \"my_ssh_key\",\n \"launch_time\": \"1999-12-31T23:59.9\"}}\n\n \"\"\"",
"# NOQA",
"# NOQA",
"# NOQA",
"# NOQA"
] | [
{
"param": "cls",
"type": null
},
{
"param": "aws_instance",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "aws_instance",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": false
}
],
"outlier_params": [],
"others": []
} | def format_aws_instance(cls, aws_instance):
instance_id = "Instance ID: {instance}".format(instance=aws_instance[0])
aws_account = "AWS Account: {account}".format(account=aws_instance[1]["aws_account"])
aws_region = "AWS Region: {region}".format(region=aws_instance[1]["aws_region"])
key_name = "Key Name: {key_}".format(key_=aws_instance[1]["key_name"])
launch = "Launched at: {launch}".format(launch=aws_instance[1]["launch_time"])
vpc_id = "VPC ID: {vpc}".format(vpc=aws_instance[1]["vpc_id"])
ordered_fields = [aws_account, aws_region, key_name, vpc_id,
instance_id, launch]
return "\n".join(ordered_fields) | 610,350 | 396 |
7fc9df65c287b5d93f2e704f922065e8b34ff911 | nir-lavee/server_utils | auto/SafeUpdater.py | [
"MIT"
] | Python | run | <not_specific> | def run(commands, input_string="", fail_abort=True):
"""
Run the given commands as a subprocess, wait for it to finish.
If fail_abort is set, then a non-zero return code will trigger
an exception.
Return (return_code, stdout, stderr).
"""
process = subprocess.Popen(commands,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate(input=input_string)
return_code = process.returncode
if return_code != 0 and fail_abort:
raise Exception("Command returned non-zero: %s\n"
"Return code: %s\n"
"Stdout: %s\n"
"Stderr: %s\n" %
(commands, return_code, stdout, stderr))
return (return_code, stdout, stderr) |
Run the given commands as a subprocess, wait for it to finish.
If fail_abort is set, then a non-zero return code will trigger
an exception.
Return (return_code, stdout, stderr).
| Run the given commands as a subprocess, wait for it to finish.
If fail_abort is set, then a non-zero return code will trigger
an exception.
Return (return_code, stdout, stderr). | [
"Run",
"the",
"given",
"commands",
"as",
"a",
"subprocess",
"wait",
"for",
"it",
"to",
"finish",
".",
"If",
"fail_abort",
"is",
"set",
"then",
"a",
"non",
"-",
"zero",
"return",
"code",
"will",
"trigger",
"an",
"exception",
".",
"Return",
"(",
"return_code",
"stdout",
"stderr",
")",
"."
] | def run(commands, input_string="", fail_abort=True):
process = subprocess.Popen(commands,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate(input=input_string)
return_code = process.returncode
if return_code != 0 and fail_abort:
raise Exception("Command returned non-zero: %s\n"
"Return code: %s\n"
"Stdout: %s\n"
"Stderr: %s\n" %
(commands, return_code, stdout, stderr))
return (return_code, stdout, stderr) | [
"def",
"run",
"(",
"commands",
",",
"input_string",
"=",
"\"\"",
",",
"fail_abort",
"=",
"True",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"commands",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
"input",
"=",
"input_string",
")",
"return_code",
"=",
"process",
".",
"returncode",
"if",
"return_code",
"!=",
"0",
"and",
"fail_abort",
":",
"raise",
"Exception",
"(",
"\"Command returned non-zero: %s\\n\"",
"\"Return code: %s\\n\"",
"\"Stdout: %s\\n\"",
"\"Stderr: %s\\n\"",
"%",
"(",
"commands",
",",
"return_code",
",",
"stdout",
",",
"stderr",
")",
")",
"return",
"(",
"return_code",
",",
"stdout",
",",
"stderr",
")"
] | Run the given commands as a subprocess, wait for it to finish. | [
"Run",
"the",
"given",
"commands",
"as",
"a",
"subprocess",
"wait",
"for",
"it",
"to",
"finish",
"."
] | [
"\"\"\"\n Run the given commands as a subprocess, wait for it to finish.\n If fail_abort is set, then a non-zero return code will trigger\n an exception.\n Return (return_code, stdout, stderr).\n \"\"\""
] | [
{
"param": "commands",
"type": null
},
{
"param": "input_string",
"type": null
},
{
"param": "fail_abort",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "commands",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "input_string",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "fail_abort",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import subprocess
def run(commands, input_string="", fail_abort=True):
process = subprocess.Popen(commands,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate(input=input_string)
return_code = process.returncode
if return_code != 0 and fail_abort:
raise Exception("Command returned non-zero: %s\n"
"Return code: %s\n"
"Stdout: %s\n"
"Stderr: %s\n" %
(commands, return_code, stdout, stderr))
return (return_code, stdout, stderr) | 610,351 | 1,002 |
4f4201ab1b3d5f291e37c13f6fb55bb12fa43766 | shamirtowsif/soft_patterns | util.py | [
"MIT"
] | Python | nub_by | <not_specific> | def nub_by(xs, key):
""" Removes elements with duplicate keys, maintaining original order. """
seen = set()
def check_and_add(x):
k = key(x)
if k not in seen:
seen.add(k)
return True
return False
return (x for x in xs if check_and_add(x)) | Removes elements with duplicate keys, maintaining original order. | Removes elements with duplicate keys, maintaining original order. | [
"Removes",
"elements",
"with",
"duplicate",
"keys",
"maintaining",
"original",
"order",
"."
] | def nub_by(xs, key):
seen = set()
def check_and_add(x):
k = key(x)
if k not in seen:
seen.add(k)
return True
return False
return (x for x in xs if check_and_add(x)) | [
"def",
"nub_by",
"(",
"xs",
",",
"key",
")",
":",
"seen",
"=",
"set",
"(",
")",
"def",
"check_and_add",
"(",
"x",
")",
":",
"k",
"=",
"key",
"(",
"x",
")",
"if",
"k",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"k",
")",
"return",
"True",
"return",
"False",
"return",
"(",
"x",
"for",
"x",
"in",
"xs",
"if",
"check_and_add",
"(",
"x",
")",
")"
] | Removes elements with duplicate keys, maintaining original order. | [
"Removes",
"elements",
"with",
"duplicate",
"keys",
"maintaining",
"original",
"order",
"."
] | [
"\"\"\" Removes elements with duplicate keys, maintaining original order. \"\"\""
] | [
{
"param": "xs",
"type": null
},
{
"param": "key",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "xs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "key",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def nub_by(xs, key):
seen = set()
def check_and_add(x):
k = key(x)
if k not in seen:
seen.add(k)
return True
return False
return (x for x in xs if check_and_add(x)) | 610,352 | 946 |
6d6cb7975937ff4d353701b9f384fc97664e6109 | SelfAdjointOperator/adb-sync | src/ADBSync/__init__.py | [
"Apache-2.0"
] | Python | pruneTree | <not_specific> | def pruneTree(cls, tree):
"""Remove all Nones from a tree. May return None if tree is None however."""
if not isinstance(tree, dict):
return tree
else:
returnDict = {}
for key, value in tree.items():
value_pruned = cls.pruneTree(value)
if value_pruned is not None:
returnDict[key] = value_pruned
return returnDict or None | Remove all Nones from a tree. May return None if tree is None however. | Remove all Nones from a tree. May return None if tree is None however. | [
"Remove",
"all",
"Nones",
"from",
"a",
"tree",
".",
"May",
"return",
"None",
"if",
"tree",
"is",
"None",
"however",
"."
] | def pruneTree(cls, tree):
if not isinstance(tree, dict):
return tree
else:
returnDict = {}
for key, value in tree.items():
value_pruned = cls.pruneTree(value)
if value_pruned is not None:
returnDict[key] = value_pruned
return returnDict or None | [
"def",
"pruneTree",
"(",
"cls",
",",
"tree",
")",
":",
"if",
"not",
"isinstance",
"(",
"tree",
",",
"dict",
")",
":",
"return",
"tree",
"else",
":",
"returnDict",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"tree",
".",
"items",
"(",
")",
":",
"value_pruned",
"=",
"cls",
".",
"pruneTree",
"(",
"value",
")",
"if",
"value_pruned",
"is",
"not",
"None",
":",
"returnDict",
"[",
"key",
"]",
"=",
"value_pruned",
"return",
"returnDict",
"or",
"None"
] | Remove all Nones from a tree. | [
"Remove",
"all",
"Nones",
"from",
"a",
"tree",
"."
] | [
"\"\"\"Remove all Nones from a tree. May return None if tree is None however.\"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "tree",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tree",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def pruneTree(cls, tree):
if not isinstance(tree, dict):
return tree
else:
returnDict = {}
for key, value in tree.items():
value_pruned = cls.pruneTree(value)
if value_pruned is not None:
returnDict[key] = value_pruned
return returnDict or None | 610,353 | 114 |
080d3bca8afc2f008ffd64f5a8a292632dc78f2e | JFlynnXYZ/LichtensteinGenerator | bin/colour.py | [
"Apache-2.0"
] | Python | rgb_unflatten | <not_specific> | def rgb_unflatten(rgbCols):
'''Converts a list of separated RGB values into a 3 tuple groups of (R,G,B)
Parameters:
rgbCols [list][tuple] : A list of separate R,G,B values all being ints.
On Exit:
Combines and groups every 3 values into it's own tuple and returns a
complete list of grouped RGB values.
'''
return [tuple(rgbCols[i:i+3]) for i in range(0,len(rgbCols),3)] | Converts a list of separated RGB values into a 3 tuple groups of (R,G,B)
Parameters:
rgbCols [list][tuple] : A list of separate R,G,B values all being ints.
On Exit:
Combines and groups every 3 values into it's own tuple and returns a
complete list of grouped RGB values.
| Converts a list of separated RGB values into a 3 tuple groups of (R,G,B) | [
"Converts",
"a",
"list",
"of",
"separated",
"RGB",
"values",
"into",
"a",
"3",
"tuple",
"groups",
"of",
"(",
"R",
"G",
"B",
")"
] | def rgb_unflatten(rgbCols):
return [tuple(rgbCols[i:i+3]) for i in range(0,len(rgbCols),3)] | [
"def",
"rgb_unflatten",
"(",
"rgbCols",
")",
":",
"return",
"[",
"tuple",
"(",
"rgbCols",
"[",
"i",
":",
"i",
"+",
"3",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"rgbCols",
")",
",",
"3",
")",
"]"
] | Converts a list of separated RGB values into a 3 tuple groups of (R,G,B) | [
"Converts",
"a",
"list",
"of",
"separated",
"RGB",
"values",
"into",
"a",
"3",
"tuple",
"groups",
"of",
"(",
"R",
"G",
"B",
")"
] | [
"'''Converts a list of separated RGB values into a 3 tuple groups of (R,G,B)\n \n Parameters:\n rgbCols [list][tuple] : A list of separate R,G,B values all being ints.\n \n On Exit:\n Combines and groups every 3 values into it's own tuple and returns a \n complete list of grouped RGB values.\n \n '''"
] | [
{
"param": "rgbCols",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rgbCols",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [
{
"identifier": "rgbCols [list][tuple] ",
"type": null,
"docstring": "A list of separate R,G,B values all being ints.",
"docstring_tokens": [
"A",
"list",
"of",
"separate",
"R",
"G",
"B",
"values",
"all",
"being",
"ints",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
} | def rgb_unflatten(rgbCols):
return [tuple(rgbCols[i:i+3]) for i in range(0,len(rgbCols),3)] | 610,355 | 913 |
4bf9f4222c417dce11140fda6bf0634f2e72ac2b | minhtriet8752/Medusa | Degeneration/FeederPlot.py | [
"MIT"
] | Python | autolabel | null | def autolabel(rects, ax, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
xpos = xpos.lower() # normalize the case of the parameter
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom') |
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
| Attach a text label above each bar in *rects*, displaying its height.
xpos* indicates which side to place the text w.r.t. the center of
the bar. | [
"Attach",
"a",
"text",
"label",
"above",
"each",
"bar",
"in",
"*",
"rects",
"*",
"displaying",
"its",
"height",
".",
"xpos",
"*",
"indicates",
"which",
"side",
"to",
"place",
"the",
"text",
"w",
".",
"r",
".",
"t",
".",
"the",
"center",
"of",
"the",
"bar",
"."
] | def autolabel(rects, ax, xpos='center'):
xpos = xpos.lower()
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom') | [
"def",
"autolabel",
"(",
"rects",
",",
"ax",
",",
"xpos",
"=",
"'center'",
")",
":",
"xpos",
"=",
"xpos",
".",
"lower",
"(",
")",
"ha",
"=",
"{",
"'center'",
":",
"'center'",
",",
"'right'",
":",
"'left'",
",",
"'left'",
":",
"'right'",
"}",
"offset",
"=",
"{",
"'center'",
":",
"0.5",
",",
"'right'",
":",
"0.57",
",",
"'left'",
":",
"0.43",
"}",
"for",
"rect",
"in",
"rects",
":",
"height",
"=",
"rect",
".",
"get_height",
"(",
")",
"ax",
".",
"text",
"(",
"rect",
".",
"get_x",
"(",
")",
"+",
"rect",
".",
"get_width",
"(",
")",
"*",
"offset",
"[",
"xpos",
"]",
",",
"1.01",
"*",
"height",
",",
"'{}'",
".",
"format",
"(",
"height",
")",
",",
"ha",
"=",
"ha",
"[",
"xpos",
"]",
",",
"va",
"=",
"'bottom'",
")"
] | Attach a text label above each bar in *rects*, displaying its height. | [
"Attach",
"a",
"text",
"label",
"above",
"each",
"bar",
"in",
"*",
"rects",
"*",
"displaying",
"its",
"height",
"."
] | [
"\"\"\"\n Attach a text label above each bar in *rects*, displaying its height.\n\n *xpos* indicates which side to place the text w.r.t. the center of\n the bar. It can be one of the following {'center', 'right', 'left'}.\n \"\"\"",
"# normalize the case of the parameter",
"# x_txt = x + w*off"
] | [
{
"param": "rects",
"type": null
},
{
"param": "ax",
"type": null
},
{
"param": "xpos",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "rects",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ax",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "xpos",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def autolabel(rects, ax, xpos='center'):
xpos = xpos.lower()
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom') | 610,356 | 732 |
2f7109b51f8f8ddcd6b0e0a0c8a087863b3b4c87 | msyaifullah/Stargate | stargate/decorator_auth.py | [
"MIT"
] | Python | check_device | <not_specific> | def check_device(device):
"""
This function is called to check if a device id is valid.
"""
uuid = device.get('Device-Id')
if not uuid:
return False
return True |
This function is called to check if a device id is valid.
| This function is called to check if a device id is valid. | [
"This",
"function",
"is",
"called",
"to",
"check",
"if",
"a",
"device",
"id",
"is",
"valid",
"."
] | def check_device(device):
uuid = device.get('Device-Id')
if not uuid:
return False
return True | [
"def",
"check_device",
"(",
"device",
")",
":",
"uuid",
"=",
"device",
".",
"get",
"(",
"'Device-Id'",
")",
"if",
"not",
"uuid",
":",
"return",
"False",
"return",
"True"
] | This function is called to check if a device id is valid. | [
"This",
"function",
"is",
"called",
"to",
"check",
"if",
"a",
"device",
"id",
"is",
"valid",
"."
] | [
"\"\"\"\n This function is called to check if a device id is valid.\n\n \"\"\""
] | [
{
"param": "device",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "device",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def check_device(device):
uuid = device.get('Device-Id')
if not uuid:
return False
return True | 610,357 | 798 |
c36e32ccbecfa21558b38b6225165cb007f09915 | auroracramer/slurmjobs | slurmjobs/util.py | [
"MIT"
] | Python | make_executable | null | def make_executable(file_path):
'''Grant permission to execute a file.'''
# https://stackoverflow.com/a/30463972
mode = os.stat(file_path).st_mode
mode |= (mode & 0o444) >> 2
os.chmod(file_path, mode) | Grant permission to execute a file. | Grant permission to execute a file. | [
"Grant",
"permission",
"to",
"execute",
"a",
"file",
"."
] | def make_executable(file_path):
mode = os.stat(file_path).st_mode
mode |= (mode & 0o444) >> 2
os.chmod(file_path, mode) | [
"def",
"make_executable",
"(",
"file_path",
")",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"file_path",
")",
".",
"st_mode",
"mode",
"|=",
"(",
"mode",
"&",
"0o444",
")",
">>",
"2",
"os",
".",
"chmod",
"(",
"file_path",
",",
"mode",
")"
] | Grant permission to execute a file. | [
"Grant",
"permission",
"to",
"execute",
"a",
"file",
"."
] | [
"'''Grant permission to execute a file.'''",
"# https://stackoverflow.com/a/30463972"
] | [
{
"param": "file_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "file_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def make_executable(file_path):
mode = os.stat(file_path).st_mode
mode |= (mode & 0o444) >> 2
os.chmod(file_path, mode) | 610,358 | 300 |
f862e40f7957e74e24227dc2add2f1885ed898d1 | KURDO72/DiscordGBcreator | bot/utils/time.py | [
"MIT",
"BSD-3-Clause"
] | Python | wait_until | None | async def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
"""
Wait until a given time.
:param time: A datetime.datetime object to wait until.
:param start: The start from which to calculate the waiting duration. Defaults to UTC time.
"""
delay = time - (start or datetime.datetime.utcnow())
delay_seconds = delay.total_seconds()
# Incorporate a small delay so we don't rapid-fire the event due to time precision errors
if delay_seconds > 1.0:
await asyncio.sleep(delay_seconds) |
Wait until a given time.
:param time: A datetime.datetime object to wait until.
:param start: The start from which to calculate the waiting duration. Defaults to UTC time.
| Wait until a given time. | [
"Wait",
"until",
"a",
"given",
"time",
"."
] | async def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
delay = time - (start or datetime.datetime.utcnow())
delay_seconds = delay.total_seconds()
if delay_seconds > 1.0:
await asyncio.sleep(delay_seconds) | [
"async",
"def",
"wait_until",
"(",
"time",
":",
"datetime",
".",
"datetime",
",",
"start",
":",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
"=",
"None",
")",
"->",
"None",
":",
"delay",
"=",
"time",
"-",
"(",
"start",
"or",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
")",
"delay_seconds",
"=",
"delay",
".",
"total_seconds",
"(",
")",
"if",
"delay_seconds",
">",
"1.0",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"delay_seconds",
")"
] | Wait until a given time. | [
"Wait",
"until",
"a",
"given",
"time",
"."
] | [
"\"\"\"\n Wait until a given time.\n\n :param time: A datetime.datetime object to wait until.\n :param start: The start from which to calculate the waiting duration. Defaults to UTC time.\n \"\"\"",
"# Incorporate a small delay so we don't rapid-fire the event due to time precision errors"
] | [
{
"param": "time",
"type": "datetime.datetime"
},
{
"param": "start",
"type": "Optional[datetime.datetime]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "time",
"type": "datetime.datetime",
"docstring": "A datetime.datetime object to wait until.",
"docstring_tokens": [
"A",
"datetime",
".",
"datetime",
"object",
"to",
"wait",
"until",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "start",
"type": "Optional[datetime.datetime]",
"docstring": "The start from which to calculate the waiting duration. Defaults to UTC time.",
"docstring_tokens": [
"The",
"start",
"from",
"which",
"to",
"calculate",
"the",
"waiting",
"duration",
".",
"Defaults",
"to",
"UTC",
"time",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import asyncio
import datetime
async def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
delay = time - (start or datetime.datetime.utcnow())
delay_seconds = delay.total_seconds()
if delay_seconds > 1.0:
await asyncio.sleep(delay_seconds) | 610,359 | 985 |
789a047fa6b69f3fff5c5ab5988fc529ad97bd93 | marciogameiro/hysteretic-paths | Hysteretic_Paths/HystereticPaths.py | [
"MIT"
] | Python | reverse_topological_sort | <not_specific> | def reverse_topological_sort(graph):
"""Return list of vertices in reverse topologically sorted order.
"""
result = []
explored = set()
dfs_stack = [(v,0) for v in graph.vertices]
while dfs_stack:
(v,i) = dfs_stack.pop()
if (v,i) in explored: continue
explored.add((v,i))
if i == 0: # preordering visit
dfs_stack.extend([(v,1)] + [(u,0) for u in graph.adjacencies(v)])
elif i == 1: # postordering visit
result.append(v)
return result | Return list of vertices in reverse topologically sorted order.
| Return list of vertices in reverse topologically sorted order. | [
"Return",
"list",
"of",
"vertices",
"in",
"reverse",
"topologically",
"sorted",
"order",
"."
] | def reverse_topological_sort(graph):
result = []
explored = set()
dfs_stack = [(v,0) for v in graph.vertices]
while dfs_stack:
(v,i) = dfs_stack.pop()
if (v,i) in explored: continue
explored.add((v,i))
if i == 0:
dfs_stack.extend([(v,1)] + [(u,0) for u in graph.adjacencies(v)])
elif i == 1:
result.append(v)
return result | [
"def",
"reverse_topological_sort",
"(",
"graph",
")",
":",
"result",
"=",
"[",
"]",
"explored",
"=",
"set",
"(",
")",
"dfs_stack",
"=",
"[",
"(",
"v",
",",
"0",
")",
"for",
"v",
"in",
"graph",
".",
"vertices",
"]",
"while",
"dfs_stack",
":",
"(",
"v",
",",
"i",
")",
"=",
"dfs_stack",
".",
"pop",
"(",
")",
"if",
"(",
"v",
",",
"i",
")",
"in",
"explored",
":",
"continue",
"explored",
".",
"add",
"(",
"(",
"v",
",",
"i",
")",
")",
"if",
"i",
"==",
"0",
":",
"dfs_stack",
".",
"extend",
"(",
"[",
"(",
"v",
",",
"1",
")",
"]",
"+",
"[",
"(",
"u",
",",
"0",
")",
"for",
"u",
"in",
"graph",
".",
"adjacencies",
"(",
"v",
")",
"]",
")",
"elif",
"i",
"==",
"1",
":",
"result",
".",
"append",
"(",
"v",
")",
"return",
"result"
] | Return list of vertices in reverse topologically sorted order. | [
"Return",
"list",
"of",
"vertices",
"in",
"reverse",
"topologically",
"sorted",
"order",
"."
] | [
"\"\"\"Return list of vertices in reverse topologically sorted order.\n \"\"\"",
"# preordering visit",
"# postordering visit"
] | [
{
"param": "graph",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "graph",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def reverse_topological_sort(graph):
result = []
explored = set()
dfs_stack = [(v,0) for v in graph.vertices]
while dfs_stack:
(v,i) = dfs_stack.pop()
if (v,i) in explored: continue
explored.add((v,i))
if i == 0:
dfs_stack.extend([(v,1)] + [(u,0) for u in graph.adjacencies(v)])
elif i == 1:
result.append(v)
return result | 610,360 | 750 |
2f6750c1f45ddc2d70877f2692d25d494776990f | LPD-EPFL/DifferentialByzantine | train.py | [
"MIT"
] | Python | compute_avg_dev | <not_specific> | def compute_avg_dev(values):
""" Compute the arithmetic mean and standard deviation of a list of values.
Args:
values Iterable of values
Returns:
Arithmetic mean, standard deviation
"""
avg = sum(values) / len(values)
var = 0
for value in values:
var += (value - avg) ** 2
var /= len(values) - 1
return avg, math.sqrt(var) | Compute the arithmetic mean and standard deviation of a list of values.
Args:
values Iterable of values
Returns:
Arithmetic mean, standard deviation
| Compute the arithmetic mean and standard deviation of a list of values.
Args:
values Iterable of values
Returns:
Arithmetic mean, standard deviation | [
"Compute",
"the",
"arithmetic",
"mean",
"and",
"standard",
"deviation",
"of",
"a",
"list",
"of",
"values",
".",
"Args",
":",
"values",
"Iterable",
"of",
"values",
"Returns",
":",
"Arithmetic",
"mean",
"standard",
"deviation"
] | def compute_avg_dev(values):
avg = sum(values) / len(values)
var = 0
for value in values:
var += (value - avg) ** 2
var /= len(values) - 1
return avg, math.sqrt(var) | [
"def",
"compute_avg_dev",
"(",
"values",
")",
":",
"avg",
"=",
"sum",
"(",
"values",
")",
"/",
"len",
"(",
"values",
")",
"var",
"=",
"0",
"for",
"value",
"in",
"values",
":",
"var",
"+=",
"(",
"value",
"-",
"avg",
")",
"**",
"2",
"var",
"/=",
"len",
"(",
"values",
")",
"-",
"1",
"return",
"avg",
",",
"math",
".",
"sqrt",
"(",
"var",
")"
] | Compute the arithmetic mean and standard deviation of a list of values. | [
"Compute",
"the",
"arithmetic",
"mean",
"and",
"standard",
"deviation",
"of",
"a",
"list",
"of",
"values",
"."
] | [
"\"\"\" Compute the arithmetic mean and standard deviation of a list of values.\n Args:\n values Iterable of values\n Returns:\n Arithmetic mean, standard deviation\n \"\"\""
] | [
{
"param": "values",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "values",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import math
def compute_avg_dev(values):
avg = sum(values) / len(values)
var = 0
for value in values:
var += (value - avg) ** 2
var /= len(values) - 1
return avg, math.sqrt(var) | 610,361 | 845 |
f3eaa21c9b46c00ae011261c8e51c07273a16c43 | Alig1493/arrow | arrow/util.py | [
"Apache-2.0"
] | Python | is_timestamp | bool | def is_timestamp(value: Any) -> bool:
"""Check if value is a valid timestamp."""
if isinstance(value, bool):
return False
if not isinstance(value, (int, float, str)):
return False
try:
float(value)
return True
except ValueError:
return False | Check if value is a valid timestamp. | Check if value is a valid timestamp. | [
"Check",
"if",
"value",
"is",
"a",
"valid",
"timestamp",
"."
] | def is_timestamp(value: Any) -> bool:
if isinstance(value, bool):
return False
if not isinstance(value, (int, float, str)):
return False
try:
float(value)
return True
except ValueError:
return False | [
"def",
"is_timestamp",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"return",
"False",
"try",
":",
"float",
"(",
"value",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | Check if value is a valid timestamp. | [
"Check",
"if",
"value",
"is",
"a",
"valid",
"timestamp",
"."
] | [
"\"\"\"Check if value is a valid timestamp.\"\"\""
] | [
{
"param": "value",
"type": "Any"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "value",
"type": "Any",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def is_timestamp(value: Any) -> bool:
if isinstance(value, bool):
return False
if not isinstance(value, (int, float, str)):
return False
try:
float(value)
return True
except ValueError:
return False | 610,363 | 395 |
dc79e803218ebb2622ca23609eb6109ad2cb5283 | thailee/VoiceIP | freePBX/html/admin/modules/core/sip_to_pjsip/astconfigparser.py | [
"MIT"
] | Python | try_option | <not_specific> | def try_option(line):
"""Parses the line as an option, returning the key/value pair."""
data = re.split('=>?', line, 1)
# should split in two (key/val), but either way use first two elements
return data[0].rstrip(), data[1].lstrip() | Parses the line as an option, returning the key/value pair. | Parses the line as an option, returning the key/value pair. | [
"Parses",
"the",
"line",
"as",
"an",
"option",
"returning",
"the",
"key",
"/",
"value",
"pair",
"."
] | def try_option(line):
data = re.split('=>?', line, 1)
return data[0].rstrip(), data[1].lstrip() | [
"def",
"try_option",
"(",
"line",
")",
":",
"data",
"=",
"re",
".",
"split",
"(",
"'=>?'",
",",
"line",
",",
"1",
")",
"return",
"data",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
",",
"data",
"[",
"1",
"]",
".",
"lstrip",
"(",
")"
] | Parses the line as an option, returning the key/value pair. | [
"Parses",
"the",
"line",
"as",
"an",
"option",
"returning",
"the",
"key",
"/",
"value",
"pair",
"."
] | [
"\"\"\"Parses the line as an option, returning the key/value pair.\"\"\"",
"# should split in two (key/val), but either way use first two elements"
] | [
{
"param": "line",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "line",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import re
def try_option(line):
data = re.split('=>?', line, 1)
return data[0].rstrip(), data[1].lstrip() | 610,364 | 225 |
01644573328900914e845d0bf65c90c7390628fd | ekr/ietfdb | ietf/ipr/utils.py | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | Python | iprs_from_docs | <not_specific> | def iprs_from_docs(aliases,**kwargs):
"""Returns a list of IPRs related to doc aliases"""
iprdocrels = []
for alias in aliases:
if alias.document.ipr(**kwargs):
iprdocrels += alias.document.ipr(**kwargs)
return list(set([i.disclosure for i in iprdocrels])) | Returns a list of IPRs related to doc aliases | Returns a list of IPRs related to doc aliases | [
"Returns",
"a",
"list",
"of",
"IPRs",
"related",
"to",
"doc",
"aliases"
] | def iprs_from_docs(aliases,**kwargs):
iprdocrels = []
for alias in aliases:
if alias.document.ipr(**kwargs):
iprdocrels += alias.document.ipr(**kwargs)
return list(set([i.disclosure for i in iprdocrels])) | [
"def",
"iprs_from_docs",
"(",
"aliases",
",",
"**",
"kwargs",
")",
":",
"iprdocrels",
"=",
"[",
"]",
"for",
"alias",
"in",
"aliases",
":",
"if",
"alias",
".",
"document",
".",
"ipr",
"(",
"**",
"kwargs",
")",
":",
"iprdocrels",
"+=",
"alias",
".",
"document",
".",
"ipr",
"(",
"**",
"kwargs",
")",
"return",
"list",
"(",
"set",
"(",
"[",
"i",
".",
"disclosure",
"for",
"i",
"in",
"iprdocrels",
"]",
")",
")"
] | Returns a list of IPRs related to doc aliases | [
"Returns",
"a",
"list",
"of",
"IPRs",
"related",
"to",
"doc",
"aliases"
] | [
"\"\"\"Returns a list of IPRs related to doc aliases\"\"\""
] | [
{
"param": "aliases",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "aliases",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def iprs_from_docs(aliases,**kwargs):
iprdocrels = []
for alias in aliases:
if alias.document.ipr(**kwargs):
iprdocrels += alias.document.ipr(**kwargs)
return list(set([i.disclosure for i in iprdocrels])) | 610,365 | 703 |
e5da316ef81f45e6229bbcb98db7a365c360be07 | rosqual/rosdiscover | src/rosdiscover/models/rosdiscover_error_reproducer.py | [
"Apache-2.0"
] | Python | error_reproducer | null | def error_reproducer(c: NodeContext):
"""
This model is intended for evaluation of rosdiscover on
detecting misconfigurations. IT SHOULD NOT BE USED IN GENERAL.
This model subscribes and publishes to topics that are passed
in as parameters. In this way, we can easily construct a node
that can be used to reproduce a configuration error that exists
in our database.
"""
topics = c.read("~topic", [])
for t in topics:
if t["direction"] == 'pub':
c.pub(t["name"], t["type"])
elif t["direction"] == 'sub':
c.sub(t["name"], t["type"]) |
This model is intended for evaluation of rosdiscover on
detecting misconfigurations. IT SHOULD NOT BE USED IN GENERAL.
This model subscribes and publishes to topics that are passed
in as parameters. In this way, we can easily construct a node
that can be used to reproduce a configuration error that exists
in our database.
| This model is intended for evaluation of rosdiscover on
detecting misconfigurations. IT SHOULD NOT BE USED IN GENERAL.
This model subscribes and publishes to topics that are passed
in as parameters. In this way, we can easily construct a node
that can be used to reproduce a configuration error that exists
in our database. | [
"This",
"model",
"is",
"intended",
"for",
"evaluation",
"of",
"rosdiscover",
"on",
"detecting",
"misconfigurations",
".",
"IT",
"SHOULD",
"NOT",
"BE",
"USED",
"IN",
"GENERAL",
".",
"This",
"model",
"subscribes",
"and",
"publishes",
"to",
"topics",
"that",
"are",
"passed",
"in",
"as",
"parameters",
".",
"In",
"this",
"way",
"we",
"can",
"easily",
"construct",
"a",
"node",
"that",
"can",
"be",
"used",
"to",
"reproduce",
"a",
"configuration",
"error",
"that",
"exists",
"in",
"our",
"database",
"."
] | def error_reproducer(c: NodeContext):
topics = c.read("~topic", [])
for t in topics:
if t["direction"] == 'pub':
c.pub(t["name"], t["type"])
elif t["direction"] == 'sub':
c.sub(t["name"], t["type"]) | [
"def",
"error_reproducer",
"(",
"c",
":",
"NodeContext",
")",
":",
"topics",
"=",
"c",
".",
"read",
"(",
"\"~topic\"",
",",
"[",
"]",
")",
"for",
"t",
"in",
"topics",
":",
"if",
"t",
"[",
"\"direction\"",
"]",
"==",
"'pub'",
":",
"c",
".",
"pub",
"(",
"t",
"[",
"\"name\"",
"]",
",",
"t",
"[",
"\"type\"",
"]",
")",
"elif",
"t",
"[",
"\"direction\"",
"]",
"==",
"'sub'",
":",
"c",
".",
"sub",
"(",
"t",
"[",
"\"name\"",
"]",
",",
"t",
"[",
"\"type\"",
"]",
")"
] | This model is intended for evaluation of rosdiscover on
detecting misconfigurations. | [
"This",
"model",
"is",
"intended",
"for",
"evaluation",
"of",
"rosdiscover",
"on",
"detecting",
"misconfigurations",
"."
] | [
"\"\"\"\n This model is intended for evaluation of rosdiscover on\n detecting misconfigurations. IT SHOULD NOT BE USED IN GENERAL.\n\n This model subscribes and publishes to topics that are passed\n in as parameters. In this way, we can easily construct a node\n that can be used to reproduce a configuration error that exists\n in our database.\n \"\"\""
] | [
{
"param": "c",
"type": "NodeContext"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "c",
"type": "NodeContext",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def error_reproducer(c: NodeContext):
topics = c.read("~topic", [])
for t in topics:
if t["direction"] == 'pub':
c.pub(t["name"], t["type"])
elif t["direction"] == 'sub':
c.sub(t["name"], t["type"]) | 610,366 | 240 |
7f679aacf799bef75b10def7cd3858d1edcd83d2 | mauriceDevsM/networking-python-sdk | ibm_cloud_networking_services/user_agent_blocking_rules_v1.py | [
"Apache-2.0"
] | Python | from_dict | 'UseragentRuleObjectConfiguration' | def from_dict(cls, _dict: Dict) -> 'UseragentRuleObjectConfiguration':
"""Initialize a UseragentRuleObjectConfiguration object from a json dictionary."""
args = {}
if 'target' in _dict:
args['target'] = _dict.get('target')
else:
raise ValueError('Required property \'target\' not present in UseragentRuleObjectConfiguration JSON')
if 'value' in _dict:
args['value'] = _dict.get('value')
else:
raise ValueError('Required property \'value\' not present in UseragentRuleObjectConfiguration JSON')
return cls(**args) | Initialize a UseragentRuleObjectConfiguration object from a json dictionary. | Initialize a UseragentRuleObjectConfiguration object from a json dictionary. | [
"Initialize",
"a",
"UseragentRuleObjectConfiguration",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | def from_dict(cls, _dict: Dict) -> 'UseragentRuleObjectConfiguration':
args = {}
if 'target' in _dict:
args['target'] = _dict.get('target')
else:
raise ValueError('Required property \'target\' not present in UseragentRuleObjectConfiguration JSON')
if 'value' in _dict:
args['value'] = _dict.get('value')
else:
raise ValueError('Required property \'value\' not present in UseragentRuleObjectConfiguration JSON')
return cls(**args) | [
"def",
"from_dict",
"(",
"cls",
",",
"_dict",
":",
"Dict",
")",
"->",
"'UseragentRuleObjectConfiguration'",
":",
"args",
"=",
"{",
"}",
"if",
"'target'",
"in",
"_dict",
":",
"args",
"[",
"'target'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'target'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Required property \\'target\\' not present in UseragentRuleObjectConfiguration JSON'",
")",
"if",
"'value'",
"in",
"_dict",
":",
"args",
"[",
"'value'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'value'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Required property \\'value\\' not present in UseragentRuleObjectConfiguration JSON'",
")",
"return",
"cls",
"(",
"**",
"args",
")"
] | Initialize a UseragentRuleObjectConfiguration object from a json dictionary. | [
"Initialize",
"a",
"UseragentRuleObjectConfiguration",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | [
"\"\"\"Initialize a UseragentRuleObjectConfiguration object from a json dictionary.\"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "_dict",
"type": "Dict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "_dict",
"type": "Dict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def from_dict(cls, _dict: Dict) -> 'UseragentRuleObjectConfiguration':
args = {}
if 'target' in _dict:
args['target'] = _dict.get('target')
else:
raise ValueError('Required property \'target\' not present in UseragentRuleObjectConfiguration JSON')
if 'value' in _dict:
args['value'] = _dict.get('value')
else:
raise ValueError('Required property \'value\' not present in UseragentRuleObjectConfiguration JSON')
return cls(**args) | 610,367 | 550 |
639fc70e0a95f5c147500888547ab6da4f169141 | denesbartha/tree-graph-labeling | tree_labeling.py | [
"MIT"
] | Python | sort_tree | null | def sort_tree(t, node):
"""Sorts the given directed tree's branch.
Sorting here means that at every level (starting from the root node) the nodes should follow an increasing order
at the count of their children.
Args:
t: a dictionary that contains the nodes of a labeled tree
node: the actual node of the tree (Node object)
"""
node.ordervect = [len(node.children_list)]
if node.children_list:
# iterate through the children
for n in node.children_list:
sort_tree(t, t[n])
node.ordervect.append(t[n].ordervect)
# if there is more then one children, sort the children list and the ordervect at the same time (the keys are
# the elements of the ordervect)
if len(node.children_list) > 1:
node.children_list, node.ordervect[1:] = (list(x) for x in zip(
*sorted(zip(node.children_list, node.ordervect[1:]), key=lambda pair: t[pair[0]].ordervect))) | Sorts the given directed tree's branch.
Sorting here means that at every level (starting from the root node) the nodes should follow an increasing order
at the count of their children.
Args:
t: a dictionary that contains the nodes of a labeled tree
node: the actual node of the tree (Node object)
| Sorts the given directed tree's branch.
Sorting here means that at every level (starting from the root node) the nodes should follow an increasing order
at the count of their children. | [
"Sorts",
"the",
"given",
"directed",
"tree",
"'",
"s",
"branch",
".",
"Sorting",
"here",
"means",
"that",
"at",
"every",
"level",
"(",
"starting",
"from",
"the",
"root",
"node",
")",
"the",
"nodes",
"should",
"follow",
"an",
"increasing",
"order",
"at",
"the",
"count",
"of",
"their",
"children",
"."
] | def sort_tree(t, node):
node.ordervect = [len(node.children_list)]
if node.children_list:
for n in node.children_list:
sort_tree(t, t[n])
node.ordervect.append(t[n].ordervect)
if len(node.children_list) > 1:
node.children_list, node.ordervect[1:] = (list(x) for x in zip(
*sorted(zip(node.children_list, node.ordervect[1:]), key=lambda pair: t[pair[0]].ordervect))) | [
"def",
"sort_tree",
"(",
"t",
",",
"node",
")",
":",
"node",
".",
"ordervect",
"=",
"[",
"len",
"(",
"node",
".",
"children_list",
")",
"]",
"if",
"node",
".",
"children_list",
":",
"for",
"n",
"in",
"node",
".",
"children_list",
":",
"sort_tree",
"(",
"t",
",",
"t",
"[",
"n",
"]",
")",
"node",
".",
"ordervect",
".",
"append",
"(",
"t",
"[",
"n",
"]",
".",
"ordervect",
")",
"if",
"len",
"(",
"node",
".",
"children_list",
")",
">",
"1",
":",
"node",
".",
"children_list",
",",
"node",
".",
"ordervect",
"[",
"1",
":",
"]",
"=",
"(",
"list",
"(",
"x",
")",
"for",
"x",
"in",
"zip",
"(",
"*",
"sorted",
"(",
"zip",
"(",
"node",
".",
"children_list",
",",
"node",
".",
"ordervect",
"[",
"1",
":",
"]",
")",
",",
"key",
"=",
"lambda",
"pair",
":",
"t",
"[",
"pair",
"[",
"0",
"]",
"]",
".",
"ordervect",
")",
")",
")"
] | Sorts the given directed tree's branch. | [
"Sorts",
"the",
"given",
"directed",
"tree",
"'",
"s",
"branch",
"."
] | [
"\"\"\"Sorts the given directed tree's branch.\n\n Sorting here means that at every level (starting from the root node) the nodes should follow an increasing order\n at the count of their children.\n\n Args:\n t: a dictionary that contains the nodes of a labeled tree\n node: the actual node of the tree (Node object)\n \"\"\"",
"# iterate through the children",
"# if there is more then one children, sort the children list and the ordervect at the same time (the keys are",
"# the elements of the ordervect)"
] | [
{
"param": "t",
"type": null
},
{
"param": "node",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "t",
"type": null,
"docstring": "a dictionary that contains the nodes of a labeled tree",
"docstring_tokens": [
"a",
"dictionary",
"that",
"contains",
"the",
"nodes",
"of",
"a",
"labeled",
"tree"
],
"default": null,
"is_optional": null
},
{
"identifier": "node",
"type": null,
"docstring": "the actual node of the tree (Node object)",
"docstring_tokens": [
"the",
"actual",
"node",
"of",
"the",
"tree",
"(",
"Node",
"object",
")"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def sort_tree(t, node):
node.ordervect = [len(node.children_list)]
if node.children_list:
for n in node.children_list:
sort_tree(t, t[n])
node.ordervect.append(t[n].ordervect)
if len(node.children_list) > 1:
node.children_list, node.ordervect[1:] = (list(x) for x in zip(
*sorted(zip(node.children_list, node.ordervect[1:]), key=lambda pair: t[pair[0]].ordervect))) | 610,368 | 314 |
4b44d61b8c0782d6ea3b771c511fdc97628dfde2 | tlovett/vvp-validation-scripts | ice_validator/tests/utils/network_roles.py | [
"Apache-2.0",
"CC-BY-4.0"
] | Python | is_valid_ipv4_address | <not_specific> | def is_valid_ipv4_address(ip_address):
"""
check if an ip address of the type ipv4
is valid
"""
try:
socket.inet_pton(socket.AF_INET, ip_address)
except AttributeError:
try:
socket.inet_aton(ip_address)
except (OSError, socket.error):
return False
return ip_address.count(".") == 3
except (OSError, socket.error):
return False
return True |
check if an ip address of the type ipv4
is valid
| check if an ip address of the type ipv4
is valid | [
"check",
"if",
"an",
"ip",
"address",
"of",
"the",
"type",
"ipv4",
"is",
"valid"
] | def is_valid_ipv4_address(ip_address):
try:
socket.inet_pton(socket.AF_INET, ip_address)
except AttributeError:
try:
socket.inet_aton(ip_address)
except (OSError, socket.error):
return False
return ip_address.count(".") == 3
except (OSError, socket.error):
return False
return True | [
"def",
"is_valid_ipv4_address",
"(",
"ip_address",
")",
":",
"try",
":",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET",
",",
"ip_address",
")",
"except",
"AttributeError",
":",
"try",
":",
"socket",
".",
"inet_aton",
"(",
"ip_address",
")",
"except",
"(",
"OSError",
",",
"socket",
".",
"error",
")",
":",
"return",
"False",
"return",
"ip_address",
".",
"count",
"(",
"\".\"",
")",
"==",
"3",
"except",
"(",
"OSError",
",",
"socket",
".",
"error",
")",
":",
"return",
"False",
"return",
"True"
] | check if an ip address of the type ipv4
is valid | [
"check",
"if",
"an",
"ip",
"address",
"of",
"the",
"type",
"ipv4",
"is",
"valid"
] | [
"\"\"\"\n check if an ip address of the type ipv4\n is valid\n \"\"\""
] | [
{
"param": "ip_address",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ip_address",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import socket
def is_valid_ipv4_address(ip_address):
try:
socket.inet_pton(socket.AF_INET, ip_address)
except AttributeError:
try:
socket.inet_aton(ip_address)
except (OSError, socket.error):
return False
return ip_address.count(".") == 3
except (OSError, socket.error):
return False
return True | 610,369 | 1,017 |
f77136f0f45cadc21d9054e8e5497112756da897 | sjvs/immunant-c2rust-copy | scripts/test_translator.py | [
"BSD-3-Clause"
] | Python | readable_directory | str | def readable_directory(directory: str) -> str:
"""
Check that a directory is exists and is readable
"""
if not os.path.isdir(directory):
msg = "directory:{0} is not a valid path".format(directory)
raise argparse.ArgumentTypeError(msg)
elif not os.access(directory, os.R_OK):
msg = "directory:{0} cannot be read".format(directory)
raise argparse.ArgumentTypeError(msg)
else:
return directory |
Check that a directory is exists and is readable
| Check that a directory is exists and is readable | [
"Check",
"that",
"a",
"directory",
"is",
"exists",
"and",
"is",
"readable"
] | def readable_directory(directory: str) -> str:
if not os.path.isdir(directory):
msg = "directory:{0} is not a valid path".format(directory)
raise argparse.ArgumentTypeError(msg)
elif not os.access(directory, os.R_OK):
msg = "directory:{0} cannot be read".format(directory)
raise argparse.ArgumentTypeError(msg)
else:
return directory | [
"def",
"readable_directory",
"(",
"directory",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"msg",
"=",
"\"directory:{0} is not a valid path\"",
".",
"format",
"(",
"directory",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
")",
"elif",
"not",
"os",
".",
"access",
"(",
"directory",
",",
"os",
".",
"R_OK",
")",
":",
"msg",
"=",
"\"directory:{0} cannot be read\"",
".",
"format",
"(",
"directory",
")",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"msg",
")",
"else",
":",
"return",
"directory"
] | Check that a directory is exists and is readable | [
"Check",
"that",
"a",
"directory",
"is",
"exists",
"and",
"is",
"readable"
] | [
"\"\"\"\n Check that a directory is exists and is readable\n \"\"\""
] | [
{
"param": "directory",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "directory",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import argparse
import os
def readable_directory(directory: str) -> str:
if not os.path.isdir(directory):
msg = "directory:{0} is not a valid path".format(directory)
raise argparse.ArgumentTypeError(msg)
elif not os.access(directory, os.R_OK):
msg = "directory:{0} cannot be read".format(directory)
raise argparse.ArgumentTypeError(msg)
else:
return directory | 610,370 | 270 |
f8ee921b09888c34ba9f6ba78d8351db425c7660 | GoldJohn/dds | buildscripts/idl/idl/compiler.py | [
"Apache-2.0"
] | Python | _write_dependencies | <not_specific> | def _write_dependencies(spec):
# type: (syntax.IDLSpec) -> None
"""Write a list of dependencies to standard out."""
if not spec.imports:
return
dependencies = sorted(spec.imports.dependencies)
for resolved_file_name in dependencies:
print(resolved_file_name) | Write a list of dependencies to standard out. | Write a list of dependencies to standard out. | [
"Write",
"a",
"list",
"of",
"dependencies",
"to",
"standard",
"out",
"."
] | def _write_dependencies(spec):
if not spec.imports:
return
dependencies = sorted(spec.imports.dependencies)
for resolved_file_name in dependencies:
print(resolved_file_name) | [
"def",
"_write_dependencies",
"(",
"spec",
")",
":",
"if",
"not",
"spec",
".",
"imports",
":",
"return",
"dependencies",
"=",
"sorted",
"(",
"spec",
".",
"imports",
".",
"dependencies",
")",
"for",
"resolved_file_name",
"in",
"dependencies",
":",
"print",
"(",
"resolved_file_name",
")"
] | Write a list of dependencies to standard out. | [
"Write",
"a",
"list",
"of",
"dependencies",
"to",
"standard",
"out",
"."
] | [
"# type: (syntax.IDLSpec) -> None",
"\"\"\"Write a list of dependencies to standard out.\"\"\""
] | [
{
"param": "spec",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "spec",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _write_dependencies(spec):
if not spec.imports:
return
dependencies = sorted(spec.imports.dependencies)
for resolved_file_name in dependencies:
print(resolved_file_name) | 610,371 | 232 |
0d082263c69eba4564d217d6755dbf43d60368f1 | kbren/uwnet | ext/sam/SRC/python/module.py | [
"MIT"
] | Python | to_normal_units_nn_columns | <not_specific> | def to_normal_units_nn_columns(ds):
"""Convert output from uwnet.columns to have proper SI units"""
scales = {
'FQT': 1 / 86400 / 1000,
'FSL': 1 / 86400,
'Q1NN': 1 / 86400 / 1000,
'qt': 1 / 1000,
'qtOBS': 1 / 1000,
'Q2NN': 1 / 86400 / 1000,
}
for key, scale in scales.items():
if key in ds:
ds = ds.assign(**{key: ds[key] * scale})
return ds | Convert output from uwnet.columns to have proper SI units | Convert output from uwnet.columns to have proper SI units | [
"Convert",
"output",
"from",
"uwnet",
".",
"columns",
"to",
"have",
"proper",
"SI",
"units"
] | def to_normal_units_nn_columns(ds):
scales = {
'FQT': 1 / 86400 / 1000,
'FSL': 1 / 86400,
'Q1NN': 1 / 86400 / 1000,
'qt': 1 / 1000,
'qtOBS': 1 / 1000,
'Q2NN': 1 / 86400 / 1000,
}
for key, scale in scales.items():
if key in ds:
ds = ds.assign(**{key: ds[key] * scale})
return ds | [
"def",
"to_normal_units_nn_columns",
"(",
"ds",
")",
":",
"scales",
"=",
"{",
"'FQT'",
":",
"1",
"/",
"86400",
"/",
"1000",
",",
"'FSL'",
":",
"1",
"/",
"86400",
",",
"'Q1NN'",
":",
"1",
"/",
"86400",
"/",
"1000",
",",
"'qt'",
":",
"1",
"/",
"1000",
",",
"'qtOBS'",
":",
"1",
"/",
"1000",
",",
"'Q2NN'",
":",
"1",
"/",
"86400",
"/",
"1000",
",",
"}",
"for",
"key",
",",
"scale",
"in",
"scales",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"ds",
":",
"ds",
"=",
"ds",
".",
"assign",
"(",
"**",
"{",
"key",
":",
"ds",
"[",
"key",
"]",
"*",
"scale",
"}",
")",
"return",
"ds"
] | Convert output from uwnet.columns to have proper SI units | [
"Convert",
"output",
"from",
"uwnet",
".",
"columns",
"to",
"have",
"proper",
"SI",
"units"
] | [
"\"\"\"Convert output from uwnet.columns to have proper SI units\"\"\""
] | [
{
"param": "ds",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ds",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def to_normal_units_nn_columns(ds):
scales = {
'FQT': 1 / 86400 / 1000,
'FSL': 1 / 86400,
'Q1NN': 1 / 86400 / 1000,
'qt': 1 / 1000,
'qtOBS': 1 / 1000,
'Q2NN': 1 / 86400 / 1000,
}
for key, scale in scales.items():
if key in ds:
ds = ds.assign(**{key: ds[key] * scale})
return ds | 610,372 | 142 |
e1829df6d8e7582b37d68bd1aae07127d0fc8386 | albertozurli/mammoth | backbone/__init__.py | [
"MIT"
] | Python | xavier | None | def xavier(m: nn.Module) -> None:
"""
Applies Xavier initialization to linear modules.
:param m: the module to be initialized
Example::
>>> net = nn.Sequential(nn.Linear(10, 10), nn.ReLU())
>>> net.apply(xavier)
"""
if m.__class__.__name__ == 'Linear':
fan_in = m.weight.data.size(1)
fan_out = m.weight.data.size(0)
std = 1.0 * math.sqrt(2.0 / (fan_in + fan_out))
a = math.sqrt(3.0) * std
m.weight.data.uniform_(-a, a)
if m.bias is not None:
m.bias.data.fill_(0.0) |
Applies Xavier initialization to linear modules.
:param m: the module to be initialized
Example::
>>> net = nn.Sequential(nn.Linear(10, 10), nn.ReLU())
>>> net.apply(xavier)
| Applies Xavier initialization to linear modules. | [
"Applies",
"Xavier",
"initialization",
"to",
"linear",
"modules",
"."
] | def xavier(m: nn.Module) -> None:
if m.__class__.__name__ == 'Linear':
fan_in = m.weight.data.size(1)
fan_out = m.weight.data.size(0)
std = 1.0 * math.sqrt(2.0 / (fan_in + fan_out))
a = math.sqrt(3.0) * std
m.weight.data.uniform_(-a, a)
if m.bias is not None:
m.bias.data.fill_(0.0) | [
"def",
"xavier",
"(",
"m",
":",
"nn",
".",
"Module",
")",
"->",
"None",
":",
"if",
"m",
".",
"__class__",
".",
"__name__",
"==",
"'Linear'",
":",
"fan_in",
"=",
"m",
".",
"weight",
".",
"data",
".",
"size",
"(",
"1",
")",
"fan_out",
"=",
"m",
".",
"weight",
".",
"data",
".",
"size",
"(",
"0",
")",
"std",
"=",
"1.0",
"*",
"math",
".",
"sqrt",
"(",
"2.0",
"/",
"(",
"fan_in",
"+",
"fan_out",
")",
")",
"a",
"=",
"math",
".",
"sqrt",
"(",
"3.0",
")",
"*",
"std",
"m",
".",
"weight",
".",
"data",
".",
"uniform_",
"(",
"-",
"a",
",",
"a",
")",
"if",
"m",
".",
"bias",
"is",
"not",
"None",
":",
"m",
".",
"bias",
".",
"data",
".",
"fill_",
"(",
"0.0",
")"
] | Applies Xavier initialization to linear modules. | [
"Applies",
"Xavier",
"initialization",
"to",
"linear",
"modules",
"."
] | [
"\"\"\"\n Applies Xavier initialization to linear modules.\n\n :param m: the module to be initialized\n\n Example::\n >>> net = nn.Sequential(nn.Linear(10, 10), nn.ReLU())\n >>> net.apply(xavier)\n \"\"\""
] | [
{
"param": "m",
"type": "nn.Module"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "m",
"type": "nn.Module",
"docstring": "the module to be initialized\nExample::\n>>> net = nn.Sequential(nn.Linear(10, 10), nn.ReLU())\n>>> net.apply(xavier)",
"docstring_tokens": [
"the",
"module",
"to",
"be",
"initialized",
"Example",
"::",
">>>",
"net",
"=",
"nn",
".",
"Sequential",
"(",
"nn",
".",
"Linear",
"(",
"10",
"10",
")",
"nn",
".",
"ReLU",
"()",
")",
">>>",
"net",
".",
"apply",
"(",
"xavier",
")"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import math
def xavier(m: nn.Module) -> None:
if m.__class__.__name__ == 'Linear':
fan_in = m.weight.data.size(1)
fan_out = m.weight.data.size(0)
std = 1.0 * math.sqrt(2.0 / (fan_in + fan_out))
a = math.sqrt(3.0) * std
m.weight.data.uniform_(-a, a)
if m.bias is not None:
m.bias.data.fill_(0.0) | 610,373 | 644 |
7f76108af694d99daf50e3fbfb90cb68d18e1ffa | florian-lapp/tmcm-lib-py | tmcm_lib/module_3110/motor.py | [
"MIT"
] | Python | __velocity_external | float | def __velocity_external(
cls,
pulse_divisor_exponent : int,
portion : int,
microstep_resolution : int
) -> float :
"""
Converts a velocity of a motor from a pulse divisor exponent and a portion of
`__VELOCITY_PORTIONS` into units of fullsteps per second.
"""
return (
portion * cls.__VELOCITY_DIVIDEND / (
cls.__VELOCITY_PORTIONS *
cls.__DIVISOR_BASE ** pulse_divisor_exponent
) / microstep_resolution
) |
Converts a velocity of a motor from a pulse divisor exponent and a portion of
`__VELOCITY_PORTIONS` into units of fullsteps per second.
| Converts a velocity of a motor from a pulse divisor exponent and a portion of
`__VELOCITY_PORTIONS` into units of fullsteps per second. | [
"Converts",
"a",
"velocity",
"of",
"a",
"motor",
"from",
"a",
"pulse",
"divisor",
"exponent",
"and",
"a",
"portion",
"of",
"`",
"__VELOCITY_PORTIONS",
"`",
"into",
"units",
"of",
"fullsteps",
"per",
"second",
"."
] | def __velocity_external(
cls,
pulse_divisor_exponent : int,
portion : int,
microstep_resolution : int
) -> float :
return (
portion * cls.__VELOCITY_DIVIDEND / (
cls.__VELOCITY_PORTIONS *
cls.__DIVISOR_BASE ** pulse_divisor_exponent
) / microstep_resolution
) | [
"def",
"__velocity_external",
"(",
"cls",
",",
"pulse_divisor_exponent",
":",
"int",
",",
"portion",
":",
"int",
",",
"microstep_resolution",
":",
"int",
")",
"->",
"float",
":",
"return",
"(",
"portion",
"*",
"cls",
".",
"__VELOCITY_DIVIDEND",
"/",
"(",
"cls",
".",
"__VELOCITY_PORTIONS",
"*",
"cls",
".",
"__DIVISOR_BASE",
"**",
"pulse_divisor_exponent",
")",
"/",
"microstep_resolution",
")"
] | Converts a velocity of a motor from a pulse divisor exponent and a portion of
`__VELOCITY_PORTIONS` into units of fullsteps per second. | [
"Converts",
"a",
"velocity",
"of",
"a",
"motor",
"from",
"a",
"pulse",
"divisor",
"exponent",
"and",
"a",
"portion",
"of",
"`",
"__VELOCITY_PORTIONS",
"`",
"into",
"units",
"of",
"fullsteps",
"per",
"second",
"."
] | [
"\"\"\"\r\n Converts a velocity of a motor from a pulse divisor exponent and a portion of\r\n `__VELOCITY_PORTIONS` into units of fullsteps per second.\r\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "pulse_divisor_exponent",
"type": "int"
},
{
"param": "portion",
"type": "int"
},
{
"param": "microstep_resolution",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pulse_divisor_exponent",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "portion",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "microstep_resolution",
"type": "int",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def __velocity_external(
cls,
pulse_divisor_exponent : int,
portion : int,
microstep_resolution : int
) -> float :
return (
portion * cls.__VELOCITY_DIVIDEND / (
cls.__VELOCITY_PORTIONS *
cls.__DIVISOR_BASE ** pulse_divisor_exponent
) / microstep_resolution
) | 610,374 | 308 |
f70d8714e61a4d5271dd1487b84f2e80f3c91e72 | alexbarcelo/daos | src/tests/ftest/util/check_for_pool.py | [
"Apache-2.0"
] | Python | check_for_pool | <not_specific> | def check_for_pool(host, uuid):
"""
Function to check if pool folder exist on server
Args:
host: Server host name
uuid: Pool uuid to check if exists
return:
resp: subprocess return code
"""
cmd = "test -e /mnt/daos/" + uuid
resp = subprocess.call(["ssh", host, cmd])
if resp == 0:
print ('%s exists' %uuid)
else:
print ('%s does not exist' %uuid)
return resp |
Function to check if pool folder exist on server
Args:
host: Server host name
uuid: Pool uuid to check if exists
return:
resp: subprocess return code
| Function to check if pool folder exist on server | [
"Function",
"to",
"check",
"if",
"pool",
"folder",
"exist",
"on",
"server"
] | def check_for_pool(host, uuid):
cmd = "test -e /mnt/daos/" + uuid
resp = subprocess.call(["ssh", host, cmd])
if resp == 0:
print ('%s exists' %uuid)
else:
print ('%s does not exist' %uuid)
return resp | [
"def",
"check_for_pool",
"(",
"host",
",",
"uuid",
")",
":",
"cmd",
"=",
"\"test -e /mnt/daos/\"",
"+",
"uuid",
"resp",
"=",
"subprocess",
".",
"call",
"(",
"[",
"\"ssh\"",
",",
"host",
",",
"cmd",
"]",
")",
"if",
"resp",
"==",
"0",
":",
"print",
"(",
"'%s exists'",
"%",
"uuid",
")",
"else",
":",
"print",
"(",
"'%s does not exist'",
"%",
"uuid",
")",
"return",
"resp"
] | Function to check if pool folder exist on server | [
"Function",
"to",
"check",
"if",
"pool",
"folder",
"exist",
"on",
"server"
] | [
"\"\"\"\n Function to check if pool folder exist on server\n Args:\n host: Server host name\n uuid: Pool uuid to check if exists\n return:\n resp: subprocess return code\n \"\"\""
] | [
{
"param": "host",
"type": null
},
{
"param": "uuid",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "host",
"type": null,
"docstring": "Server host name",
"docstring_tokens": [
"Server",
"host",
"name"
],
"default": null,
"is_optional": null
},
{
"identifier": "uuid",
"type": null,
"docstring": "Pool uuid to check if exists",
"docstring_tokens": [
"Pool",
"uuid",
"to",
"check",
"if",
"exists"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import subprocess
def check_for_pool(host, uuid):
cmd = "test -e /mnt/daos/" + uuid
resp = subprocess.call(["ssh", host, cmd])
if resp == 0:
print ('%s exists' %uuid)
else:
print ('%s does not exist' %uuid)
return resp | 610,376 | 599 |
d77bf1bf9518c9df1151dd647ac04a35bf6a19c2 | drew-loukusa/ID-CAS | tree.py | [
"MIT"
] | Python | must_be | <not_specific> | def must_be(_, c):
"""
NOT IN USE ANYMORE: I changed how my parsing works to not use this.
I should probably have some sort of check, but I'll worry about that
later. It works for now.
Mostly used to ensure if there is an opening brace, then there is
a matching closing brace somewhere in the expression.
This function also saves the location of the last found closing brace
into MatchParenIndex. If we start looking for another closing brace,
then we start looking from MatchParenIndex.
"""
#print("MatchParenIndex",MatchParenIndex)
index = _.NextTokenIndex
if _.MatchParenIndex > _.NextTokenIndex:
index = _.MatchParenIndex
#print("* _.NextToken",_.NextToken)
#print("* NextTokenIndex", NextTokenIndex)
#print("* Index", index)
for i in range(index, len(_.token_stream)):
if _.token_stream[i][1] == c:
_.MatchParenIndex = i
#GetNextToken()
#std.write("Found closing paren")
#print("* _.NextToken",_.NextToken)
#print("* NextTokenIndex", NextTokenIndex)
#print("* Index", index)
return True
raise Exception("Missing closing '{}'".format(c)) |
NOT IN USE ANYMORE: I changed how my parsing works to not use this.
I should probably have some sort of check, but I'll worry about that
later. It works for now.
Mostly used to ensure if there is an opening brace, then there is
a matching closing brace somewhere in the expression.
This function also saves the location of the last found closing brace
into MatchParenIndex. If we start looking for another closing brace,
then we start looking from MatchParenIndex.
|
Mostly used to ensure if there is an opening brace, then there is
a matching closing brace somewhere in the expression.
This function also saves the location of the last found closing brace
into MatchParenIndex. If we start looking for another closing brace,
then we start looking from MatchParenIndex. | [
"Mostly",
"used",
"to",
"ensure",
"if",
"there",
"is",
"an",
"opening",
"brace",
"then",
"there",
"is",
"a",
"matching",
"closing",
"brace",
"somewhere",
"in",
"the",
"expression",
".",
"This",
"function",
"also",
"saves",
"the",
"location",
"of",
"the",
"last",
"found",
"closing",
"brace",
"into",
"MatchParenIndex",
".",
"If",
"we",
"start",
"looking",
"for",
"another",
"closing",
"brace",
"then",
"we",
"start",
"looking",
"from",
"MatchParenIndex",
"."
] | def must_be(_, c):
index = _.NextTokenIndex
if _.MatchParenIndex > _.NextTokenIndex:
index = _.MatchParenIndex
for i in range(index, len(_.token_stream)):
if _.token_stream[i][1] == c:
_.MatchParenIndex = i
return True
raise Exception("Missing closing '{}'".format(c)) | [
"def",
"must_be",
"(",
"_",
",",
"c",
")",
":",
"index",
"=",
"_",
".",
"NextTokenIndex",
"if",
"_",
".",
"MatchParenIndex",
">",
"_",
".",
"NextTokenIndex",
":",
"index",
"=",
"_",
".",
"MatchParenIndex",
"for",
"i",
"in",
"range",
"(",
"index",
",",
"len",
"(",
"_",
".",
"token_stream",
")",
")",
":",
"if",
"_",
".",
"token_stream",
"[",
"i",
"]",
"[",
"1",
"]",
"==",
"c",
":",
"_",
".",
"MatchParenIndex",
"=",
"i",
"return",
"True",
"raise",
"Exception",
"(",
"\"Missing closing '{}'\"",
".",
"format",
"(",
"c",
")",
")"
] | NOT IN USE ANYMORE: I changed how my parsing works to not use this. | [
"NOT",
"IN",
"USE",
"ANYMORE",
":",
"I",
"changed",
"how",
"my",
"parsing",
"works",
"to",
"not",
"use",
"this",
"."
] | [
"\"\"\" \n NOT IN USE ANYMORE: I changed how my parsing works to not use this.\n\n I should probably have some sort of check, but I'll worry about that\n later. It works for now.\n\n Mostly used to ensure if there is an opening brace, then there is \n a matching closing brace somewhere in the expression. \n\n This function also saves the location of the last found closing brace\n into MatchParenIndex. If we start looking for another closing brace, \n then we start looking from MatchParenIndex.\n \"\"\"",
"#print(\"MatchParenIndex\",MatchParenIndex)",
"#print(\"* _.NextToken\",_.NextToken)",
"#print(\"* NextTokenIndex\", NextTokenIndex)",
"#print(\"* Index\", index)",
"#GetNextToken()",
"#std.write(\"Found closing paren\")",
"#print(\"* _.NextToken\",_.NextToken)",
"#print(\"* NextTokenIndex\", NextTokenIndex)",
"#print(\"* Index\", index)"
] | [
{
"param": "_",
"type": null
},
{
"param": "c",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "_",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "c",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def must_be(_, c):
index = _.NextTokenIndex
if _.MatchParenIndex > _.NextTokenIndex:
index = _.MatchParenIndex
for i in range(index, len(_.token_stream)):
if _.token_stream[i][1] == c:
_.MatchParenIndex = i
return True
raise Exception("Missing closing '{}'".format(c)) | 610,377 | 29 |
7870bff228bca4a16194530620b94ddefabda054 | discopop-project/discopop-profiler | discopop_explorer/utils.py | [
"BSD-3-Clause"
] | Python | is_depend_in_out | bool | def is_depend_in_out(var: Variable, in_deps: List[Tuple[str, str, Dependency]],
out_deps: List[Tuple[str, str, Dependency]]) -> bool:
"""there is an in and out dependency
:param var: Variable
:param in_deps: in dependencies
:param out_deps: out dependencies
:return: true if dependency is both in and out
"""
for in_dep in in_deps:
for out_dep in out_deps:
if var.name == in_dep[2].var_name and in_dep[2].var_name == out_dep[2].var_name:
return True
return False | there is an in and out dependency
:param var: Variable
:param in_deps: in dependencies
:param out_deps: out dependencies
:return: true if dependency is both in and out
| there is an in and out dependency | [
"there",
"is",
"an",
"in",
"and",
"out",
"dependency"
] | def is_depend_in_out(var: Variable, in_deps: List[Tuple[str, str, Dependency]],
out_deps: List[Tuple[str, str, Dependency]]) -> bool:
for in_dep in in_deps:
for out_dep in out_deps:
if var.name == in_dep[2].var_name and in_dep[2].var_name == out_dep[2].var_name:
return True
return False | [
"def",
"is_depend_in_out",
"(",
"var",
":",
"Variable",
",",
"in_deps",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"Dependency",
"]",
"]",
",",
"out_deps",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"Dependency",
"]",
"]",
")",
"->",
"bool",
":",
"for",
"in_dep",
"in",
"in_deps",
":",
"for",
"out_dep",
"in",
"out_deps",
":",
"if",
"var",
".",
"name",
"==",
"in_dep",
"[",
"2",
"]",
".",
"var_name",
"and",
"in_dep",
"[",
"2",
"]",
".",
"var_name",
"==",
"out_dep",
"[",
"2",
"]",
".",
"var_name",
":",
"return",
"True",
"return",
"False"
] | there is an in and out dependency | [
"there",
"is",
"an",
"in",
"and",
"out",
"dependency"
] | [
"\"\"\"there is an in and out dependency\n\n :param var: Variable\n :param in_deps: in dependencies\n :param out_deps: out dependencies\n :return: true if dependency is both in and out\n \"\"\""
] | [
{
"param": "var",
"type": "Variable"
},
{
"param": "in_deps",
"type": "List[Tuple[str, str, Dependency]]"
},
{
"param": "out_deps",
"type": "List[Tuple[str, str, Dependency]]"
}
] | {
"returns": [
{
"docstring": "true if dependency is both in and out",
"docstring_tokens": [
"true",
"if",
"dependency",
"is",
"both",
"in",
"and",
"out"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "var",
"type": "Variable",
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
},
{
"identifier": "in_deps",
"type": "List[Tuple[str, str, Dependency]]",
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
},
{
"identifier": "out_deps",
"type": "List[Tuple[str, str, Dependency]]",
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def is_depend_in_out(var: Variable, in_deps: List[Tuple[str, str, Dependency]],
out_deps: List[Tuple[str, str, Dependency]]) -> bool:
for in_dep in in_deps:
for out_dep in out_deps:
if var.name == in_dep[2].var_name and in_dep[2].var_name == out_dep[2].var_name:
return True
return False | 610,378 | 832 |
0bd98deac4297ab61d37a82c9ca0b56409f10fc0 | changusmc/stone | stone/ir/data_types.py | [
"MIT"
] | Python | record_custom_annotation_imports | null | def record_custom_annotation_imports(annotation, namespace):
"""
Records imports for custom annotations in the given namespace.
"""
# first, check the annotation *type*
if annotation.annotation_type.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.annotation_type.namespace,
imported_annotation_type=True)
# second, check if we need to import the annotation itself
# the annotation namespace is currently not actually used in the
# backends, which reconstruct the annotation from the annotation
# type directly. This could be changed in the future, and at
# the IR level it makes sense to include the dependency
if annotation.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.namespace,
imported_annotation=True) |
Records imports for custom annotations in the given namespace.
| Records imports for custom annotations in the given namespace. | [
"Records",
"imports",
"for",
"custom",
"annotations",
"in",
"the",
"given",
"namespace",
"."
] | def record_custom_annotation_imports(annotation, namespace):
if annotation.annotation_type.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.annotation_type.namespace,
imported_annotation_type=True)
if annotation.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.namespace,
imported_annotation=True) | [
"def",
"record_custom_annotation_imports",
"(",
"annotation",
",",
"namespace",
")",
":",
"if",
"annotation",
".",
"annotation_type",
".",
"namespace",
".",
"name",
"!=",
"namespace",
".",
"name",
":",
"namespace",
".",
"add_imported_namespace",
"(",
"annotation",
".",
"annotation_type",
".",
"namespace",
",",
"imported_annotation_type",
"=",
"True",
")",
"if",
"annotation",
".",
"namespace",
".",
"name",
"!=",
"namespace",
".",
"name",
":",
"namespace",
".",
"add_imported_namespace",
"(",
"annotation",
".",
"namespace",
",",
"imported_annotation",
"=",
"True",
")"
] | Records imports for custom annotations in the given namespace. | [
"Records",
"imports",
"for",
"custom",
"annotations",
"in",
"the",
"given",
"namespace",
"."
] | [
"\"\"\"\n Records imports for custom annotations in the given namespace.\n\n \"\"\"",
"# first, check the annotation *type*",
"# second, check if we need to import the annotation itself",
"# the annotation namespace is currently not actually used in the",
"# backends, which reconstruct the annotation from the annotation",
"# type directly. This could be changed in the future, and at",
"# the IR level it makes sense to include the dependency"
] | [
{
"param": "annotation",
"type": null
},
{
"param": "namespace",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "annotation",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "namespace",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def record_custom_annotation_imports(annotation, namespace):
if annotation.annotation_type.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.annotation_type.namespace,
imported_annotation_type=True)
if annotation.namespace.name != namespace.name:
namespace.add_imported_namespace(
annotation.namespace,
imported_annotation=True) | 610,379 | 832 |
a2445768bf596acff7bf73796f395883036cb6c8 | Jamaliela/The-Game-of-Nim | jamalie_alfaro_a05.py | [
"MIT"
] | Python | player_2_turn | <not_specific> | def player_2_turn(num_balls):
"""
This function divides the number of balls remaining by 5 with modulus so that the computer ends up winning by always taking the remainder of the division.
:param num_balls: integer. number of balls that changes as user and computer pick
:return: num_balls
"""
player2 = num_balls % 5 # modulus to calcuate how many balls for the computer to pick
if player2 == 0: # if the result from modulus is 0 then something else happens
player2 = random.randrange(1, 4) # a random number is assigned to player2
num_balls = num_balls - player2 # recalculating the number of balls after the computer picks
print("The computer takes", player2, "balls") # telling user how many balls they pick
print("there are", num_balls, "left") # telling user how many balls are remaining
return num_balls |
This function divides the number of balls remaining by 5 with modulus so that the computer ends up winning by always taking the remainder of the division.
:param num_balls: integer. number of balls that changes as user and computer pick
:return: num_balls
| This function divides the number of balls remaining by 5 with modulus so that the computer ends up winning by always taking the remainder of the division. | [
"This",
"function",
"divides",
"the",
"number",
"of",
"balls",
"remaining",
"by",
"5",
"with",
"modulus",
"so",
"that",
"the",
"computer",
"ends",
"up",
"winning",
"by",
"always",
"taking",
"the",
"remainder",
"of",
"the",
"division",
"."
] | def player_2_turn(num_balls):
player2 = num_balls % 5
if player2 == 0:
player2 = random.randrange(1, 4)
num_balls = num_balls - player2
print("The computer takes", player2, "balls")
print("there are", num_balls, "left")
return num_balls | [
"def",
"player_2_turn",
"(",
"num_balls",
")",
":",
"player2",
"=",
"num_balls",
"%",
"5",
"if",
"player2",
"==",
"0",
":",
"player2",
"=",
"random",
".",
"randrange",
"(",
"1",
",",
"4",
")",
"num_balls",
"=",
"num_balls",
"-",
"player2",
"print",
"(",
"\"The computer takes\"",
",",
"player2",
",",
"\"balls\"",
")",
"print",
"(",
"\"there are\"",
",",
"num_balls",
",",
"\"left\"",
")",
"return",
"num_balls"
] | This function divides the number of balls remaining by 5 with modulus so that the computer ends up winning by always taking the remainder of the division. | [
"This",
"function",
"divides",
"the",
"number",
"of",
"balls",
"remaining",
"by",
"5",
"with",
"modulus",
"so",
"that",
"the",
"computer",
"ends",
"up",
"winning",
"by",
"always",
"taking",
"the",
"remainder",
"of",
"the",
"division",
"."
] | [
"\"\"\"\n This function divides the number of balls remaining by 5 with modulus so that the computer ends up winning by always taking the remainder of the division.\n :param num_balls: integer. number of balls that changes as user and computer pick\n :return: num_balls\n \"\"\"",
"# modulus to calcuate how many balls for the computer to pick",
"# if the result from modulus is 0 then something else happens",
"# a random number is assigned to player2",
"# recalculating the number of balls after the computer picks",
"# telling user how many balls they pick",
"# telling user how many balls are remaining"
] | [
{
"param": "num_balls",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "num_balls",
"type": null,
"docstring": "integer. number of balls that changes as user and computer pick",
"docstring_tokens": [
"integer",
".",
"number",
"of",
"balls",
"that",
"changes",
"as",
"user",
"and",
"computer",
"pick"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import random
def player_2_turn(num_balls):
player2 = num_balls % 5
if player2 == 0:
player2 = random.randrange(1, 4)
num_balls = num_balls - player2
print("The computer takes", player2, "balls")
print("there are", num_balls, "left")
return num_balls | 610,380 | 259 |
02d1eae971e56bfa1d46e28cef9a7dd256607891 | tiero/snet-cli | snet_cli/utils.py | [
"MIT"
] | Python | abi_get_element_by_name | <not_specific> | def abi_get_element_by_name(abi, name):
""" Return element of abi (return None if fails to find) """
if (abi and "abi" in abi):
for a in abi["abi"]:
if ("name" in a and a["name"] == name):
return a
return None | Return element of abi (return None if fails to find) | Return element of abi (return None if fails to find) | [
"Return",
"element",
"of",
"abi",
"(",
"return",
"None",
"if",
"fails",
"to",
"find",
")"
] | def abi_get_element_by_name(abi, name):
if (abi and "abi" in abi):
for a in abi["abi"]:
if ("name" in a and a["name"] == name):
return a
return None | [
"def",
"abi_get_element_by_name",
"(",
"abi",
",",
"name",
")",
":",
"if",
"(",
"abi",
"and",
"\"abi\"",
"in",
"abi",
")",
":",
"for",
"a",
"in",
"abi",
"[",
"\"abi\"",
"]",
":",
"if",
"(",
"\"name\"",
"in",
"a",
"and",
"a",
"[",
"\"name\"",
"]",
"==",
"name",
")",
":",
"return",
"a",
"return",
"None"
] | Return element of abi (return None if fails to find) | [
"Return",
"element",
"of",
"abi",
"(",
"return",
"None",
"if",
"fails",
"to",
"find",
")"
] | [
"\"\"\" Return element of abi (return None if fails to find) \"\"\""
] | [
{
"param": "abi",
"type": null
},
{
"param": "name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "abi",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def abi_get_element_by_name(abi, name):
if (abi and "abi" in abi):
for a in abi["abi"]:
if ("name" in a and a["name"] == name):
return a
return None | 610,381 | 13 |
d6912afe42f431756c06863bf360535402fd25c5 | eichin/thok-ztwitgw | ztwitgw.py | [
"MIT"
] | Python | display_rate_limit | <not_specific> | def display_rate_limit(tag, limit):
"""Display rate limit if it isn't at maximum; return available count for convenience"""
if limit["remaining"] != limit["limit"]:
print(limit["remaining"], "out of", limit["limit"], tag, "queries available")
reset_time = limit["reset"]
print(" Will reset in", reset_time - time.time(), "seconds, at", time.ctime(reset_time))
return limit["remaining"] | Display rate limit if it isn't at maximum; return available count for convenience | Display rate limit if it isn't at maximum; return available count for convenience | [
"Display",
"rate",
"limit",
"if",
"it",
"isn",
"'",
"t",
"at",
"maximum",
";",
"return",
"available",
"count",
"for",
"convenience"
] | def display_rate_limit(tag, limit):
if limit["remaining"] != limit["limit"]:
print(limit["remaining"], "out of", limit["limit"], tag, "queries available")
reset_time = limit["reset"]
print(" Will reset in", reset_time - time.time(), "seconds, at", time.ctime(reset_time))
return limit["remaining"] | [
"def",
"display_rate_limit",
"(",
"tag",
",",
"limit",
")",
":",
"if",
"limit",
"[",
"\"remaining\"",
"]",
"!=",
"limit",
"[",
"\"limit\"",
"]",
":",
"print",
"(",
"limit",
"[",
"\"remaining\"",
"]",
",",
"\"out of\"",
",",
"limit",
"[",
"\"limit\"",
"]",
",",
"tag",
",",
"\"queries available\"",
")",
"reset_time",
"=",
"limit",
"[",
"\"reset\"",
"]",
"print",
"(",
"\" Will reset in\"",
",",
"reset_time",
"-",
"time",
".",
"time",
"(",
")",
",",
"\"seconds, at\"",
",",
"time",
".",
"ctime",
"(",
"reset_time",
")",
")",
"return",
"limit",
"[",
"\"remaining\"",
"]"
] | Display rate limit if it isn't at maximum; return available count for convenience | [
"Display",
"rate",
"limit",
"if",
"it",
"isn",
"'",
"t",
"at",
"maximum",
";",
"return",
"available",
"count",
"for",
"convenience"
] | [
"\"\"\"Display rate limit if it isn't at maximum; return available count for convenience\"\"\""
] | [
{
"param": "tag",
"type": null
},
{
"param": "limit",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "tag",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "limit",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import time
def display_rate_limit(tag, limit):
if limit["remaining"] != limit["limit"]:
print(limit["remaining"], "out of", limit["limit"], tag, "queries available")
reset_time = limit["reset"]
print(" Will reset in", reset_time - time.time(), "seconds, at", time.ctime(reset_time))
return limit["remaining"] | 610,382 | 98 |
d26d7a6f9ce5839d9642d2081579251531f2c276 | fkooman/python-eduvpn | eduvpn/storage.py | [
"Apache-2.0"
] | Python | write_config | null | def write_config(config: str, private_key: str, certificate: str, target: Path):
"""
Write the configuration to target.
"""
with open(target, mode='w+t') as f:
f.writelines(config)
f.writelines(f"\n<key>\n{private_key}\n</key>\n")
f.writelines(f"\n<cert>\n{certificate}\n</cert>\n") |
Write the configuration to target.
| Write the configuration to target. | [
"Write",
"the",
"configuration",
"to",
"target",
"."
] | def write_config(config: str, private_key: str, certificate: str, target: Path):
with open(target, mode='w+t') as f:
f.writelines(config)
f.writelines(f"\n<key>\n{private_key}\n</key>\n")
f.writelines(f"\n<cert>\n{certificate}\n</cert>\n") | [
"def",
"write_config",
"(",
"config",
":",
"str",
",",
"private_key",
":",
"str",
",",
"certificate",
":",
"str",
",",
"target",
":",
"Path",
")",
":",
"with",
"open",
"(",
"target",
",",
"mode",
"=",
"'w+t'",
")",
"as",
"f",
":",
"f",
".",
"writelines",
"(",
"config",
")",
"f",
".",
"writelines",
"(",
"f\"\\n<key>\\n{private_key}\\n</key>\\n\"",
")",
"f",
".",
"writelines",
"(",
"f\"\\n<cert>\\n{certificate}\\n</cert>\\n\"",
")"
] | Write the configuration to target. | [
"Write",
"the",
"configuration",
"to",
"target",
"."
] | [
"\"\"\"\n Write the configuration to target.\n \"\"\""
] | [
{
"param": "config",
"type": "str"
},
{
"param": "private_key",
"type": "str"
},
{
"param": "certificate",
"type": "str"
},
{
"param": "target",
"type": "Path"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "private_key",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "certificate",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "Path",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def write_config(config: str, private_key: str, certificate: str, target: Path):
with open(target, mode='w+t') as f:
f.writelines(config)
f.writelines(f"\n<key>\n{private_key}\n</key>\n")
f.writelines(f"\n<cert>\n{certificate}\n</cert>\n") | 610,383 | 507 |
2e1ba8922cf58bb90287d078e5a54ad5ae1af3bf | matteoNunz/ImmunoPoli | Database/DataBaseGenerator.py | [
"MIT"
] | Python | readSurnames | <not_specific> | def readSurnames():
"""
Method that reads the possible surnames from a file
:return: a list containing the surnames
"""
surnamesRead = []
with open("Files/Surnames.txt", 'r', encoding='utf8') as f:
for line in f:
if line == "\n":
continue
surnamesRead.append(line.rstrip('\n').rstrip().lstrip())
f.close()
return surnamesRead |
Method that reads the possible surnames from a file
:return: a list containing the surnames
| Method that reads the possible surnames from a file | [
"Method",
"that",
"reads",
"the",
"possible",
"surnames",
"from",
"a",
"file"
] | def readSurnames():
surnamesRead = []
with open("Files/Surnames.txt", 'r', encoding='utf8') as f:
for line in f:
if line == "\n":
continue
surnamesRead.append(line.rstrip('\n').rstrip().lstrip())
f.close()
return surnamesRead | [
"def",
"readSurnames",
"(",
")",
":",
"surnamesRead",
"=",
"[",
"]",
"with",
"open",
"(",
"\"Files/Surnames.txt\"",
",",
"'r'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line",
"==",
"\"\\n\"",
":",
"continue",
"surnamesRead",
".",
"append",
"(",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"rstrip",
"(",
")",
".",
"lstrip",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"surnamesRead"
] | Method that reads the possible surnames from a file | [
"Method",
"that",
"reads",
"the",
"possible",
"surnames",
"from",
"a",
"file"
] | [
"\"\"\"\n Method that reads the possible surnames from a file\n :return: a list containing the surnames\n \"\"\""
] | [] | {
"returns": [
{
"docstring": "a list containing the surnames",
"docstring_tokens": [
"a",
"list",
"containing",
"the",
"surnames"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} | def readSurnames():
surnamesRead = []
with open("Files/Surnames.txt", 'r', encoding='utf8') as f:
for line in f:
if line == "\n":
continue
surnamesRead.append(line.rstrip('\n').rstrip().lstrip())
f.close()
return surnamesRead | 610,384 | 35 |
d7c17c92fbe22c08e17a62d517cc379af6e6d031 | hermajan/algorithms | src/algorithms/math/Number.py | [
"MIT"
] | Python | is_odd | <not_specific> | def is_odd(number):
"""
Checks if the number is odd.
:param number: Number.
:return: True if is odd, false if it is even.
"""
return (number % 2 != 0) |
Checks if the number is odd.
:param number: Number.
:return: True if is odd, false if it is even.
| Checks if the number is odd. | [
"Checks",
"if",
"the",
"number",
"is",
"odd",
"."
] | def is_odd(number):
return (number % 2 != 0) | [
"def",
"is_odd",
"(",
"number",
")",
":",
"return",
"(",
"number",
"%",
"2",
"!=",
"0",
")"
] | Checks if the number is odd. | [
"Checks",
"if",
"the",
"number",
"is",
"odd",
"."
] | [
"\"\"\"\n\t\tChecks if the number is odd.\n\t\t:param number: Number.\n\t\t:return: True if is odd, false if it is even.\n\t\t\"\"\""
] | [
{
"param": "number",
"type": null
}
] | {
"returns": [
{
"docstring": "True if is odd, false if it is even.",
"docstring_tokens": [
"True",
"if",
"is",
"odd",
"false",
"if",
"it",
"is",
"even",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "number",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def is_odd(number):
return (number % 2 != 0) | 610,385 | 529 |
9fc18168e0b22faeca6c11a4eb9c2a7ca24a9200 | hutoTUM/MakeAdditions | makeadditions/parse.py | [
"Apache-2.0"
] | Python | check_debugshell_and_makefile | null | def check_debugshell_and_makefile(makeoutput):
"""
Check if the Makefile output can be parsed and transformed automatically.
Raises exceptions, if something looks weird
"""
# makeoutput must start with directory information.
# Reason: The --print-directory flag for make flag was given
if (not makeoutput or
not (makeoutput.startswith("make: Entering directory ") or
makeoutput.startswith("make[1]: Entering directory "))):
raise Exception(
"Directory changes cannot be recognized: " + makeoutput[0:35]) |
Check if the Makefile output can be parsed and transformed automatically.
Raises exceptions, if something looks weird
| Check if the Makefile output can be parsed and transformed automatically.
Raises exceptions, if something looks weird | [
"Check",
"if",
"the",
"Makefile",
"output",
"can",
"be",
"parsed",
"and",
"transformed",
"automatically",
".",
"Raises",
"exceptions",
"if",
"something",
"looks",
"weird"
] | def check_debugshell_and_makefile(makeoutput):
if (not makeoutput or
not (makeoutput.startswith("make: Entering directory ") or
makeoutput.startswith("make[1]: Entering directory "))):
raise Exception(
"Directory changes cannot be recognized: " + makeoutput[0:35]) | [
"def",
"check_debugshell_and_makefile",
"(",
"makeoutput",
")",
":",
"if",
"(",
"not",
"makeoutput",
"or",
"not",
"(",
"makeoutput",
".",
"startswith",
"(",
"\"make: Entering directory \"",
")",
"or",
"makeoutput",
".",
"startswith",
"(",
"\"make[1]: Entering directory \"",
")",
")",
")",
":",
"raise",
"Exception",
"(",
"\"Directory changes cannot be recognized: \"",
"+",
"makeoutput",
"[",
"0",
":",
"35",
"]",
")"
] | Check if the Makefile output can be parsed and transformed automatically. | [
"Check",
"if",
"the",
"Makefile",
"output",
"can",
"be",
"parsed",
"and",
"transformed",
"automatically",
"."
] | [
"\"\"\"\n Check if the Makefile output can be parsed and transformed automatically.\n Raises exceptions, if something looks weird\n \"\"\"",
"# makeoutput must start with directory information.",
"# Reason: The --print-directory flag for make flag was given"
] | [
{
"param": "makeoutput",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "makeoutput",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def check_debugshell_and_makefile(makeoutput):
if (not makeoutput or
not (makeoutput.startswith("make: Entering directory ") or
makeoutput.startswith("make[1]: Entering directory "))):
raise Exception(
"Directory changes cannot be recognized: " + makeoutput[0:35]) | 610,386 | 147 |
fc5586d3025f0b07fd7a7c919dd2b3fb4f742d53 | Gee-3/pygna | pygna/converters.py | [
"MIT"
] | Python | convert_e2s | list | def convert_e2s(cls, geneset: pd.DataFrame, tsv_data: pd.DataFrame, entrez_col: str = "NCBI Gene ID",
symbol_col: str = "Approved symbol") -> list:
"""
Method to convert the entrez genes to symbols
:param tsv_data: the dataframe to work on
:param symbol_col: the column containing the symbols
:param entrez_col: the column containing the entrez ID
:param geneset: column containing the entrez to convert
:return: list containing the string names
Example
_______
>>> gmt_data = rc.ReadGmt(".gmt", True).get_data()
>>> converted = []
>>> for k, d in gmt_data.items():
>>> converted[k] = Converters.convert_e2s(d["genes"], tsv_data,entrez_col, symbol_col)
"""
logging.info("Converting Entrez ID -> Symbols")
unknown_counter = 0
geneset_symbol = []
for i in geneset:
name = tsv_data[tsv_data[entrez_col] == int(i)][symbol_col].values.tolist()
if len(name) > 0:
geneset_symbol.append(str(name[0]))
else:
unknown_counter += 1
geneset_symbol.append("<" + i + ">")
if unknown_counter > 0:
logging.warning("%d/%d terms that couldn't be mapped" % (unknown_counter, len(geneset)))
return geneset_symbol |
Method to convert the entrez genes to symbols
:param tsv_data: the dataframe to work on
:param symbol_col: the column containing the symbols
:param entrez_col: the column containing the entrez ID
:param geneset: column containing the entrez to convert
:return: list containing the string names
Example
_______
>>> gmt_data = rc.ReadGmt(".gmt", True).get_data()
>>> converted = []
>>> for k, d in gmt_data.items():
>>> converted[k] = Converters.convert_e2s(d["genes"], tsv_data,entrez_col, symbol_col)
| Method to convert the entrez genes to symbols | [
"Method",
"to",
"convert",
"the",
"entrez",
"genes",
"to",
"symbols"
] | def convert_e2s(cls, geneset: pd.DataFrame, tsv_data: pd.DataFrame, entrez_col: str = "NCBI Gene ID",
symbol_col: str = "Approved symbol") -> list:
logging.info("Converting Entrez ID -> Symbols")
unknown_counter = 0
geneset_symbol = []
for i in geneset:
name = tsv_data[tsv_data[entrez_col] == int(i)][symbol_col].values.tolist()
if len(name) > 0:
geneset_symbol.append(str(name[0]))
else:
unknown_counter += 1
geneset_symbol.append("<" + i + ">")
if unknown_counter > 0:
logging.warning("%d/%d terms that couldn't be mapped" % (unknown_counter, len(geneset)))
return geneset_symbol | [
"def",
"convert_e2s",
"(",
"cls",
",",
"geneset",
":",
"pd",
".",
"DataFrame",
",",
"tsv_data",
":",
"pd",
".",
"DataFrame",
",",
"entrez_col",
":",
"str",
"=",
"\"NCBI Gene ID\"",
",",
"symbol_col",
":",
"str",
"=",
"\"Approved symbol\"",
")",
"->",
"list",
":",
"logging",
".",
"info",
"(",
"\"Converting Entrez ID -> Symbols\"",
")",
"unknown_counter",
"=",
"0",
"geneset_symbol",
"=",
"[",
"]",
"for",
"i",
"in",
"geneset",
":",
"name",
"=",
"tsv_data",
"[",
"tsv_data",
"[",
"entrez_col",
"]",
"==",
"int",
"(",
"i",
")",
"]",
"[",
"symbol_col",
"]",
".",
"values",
".",
"tolist",
"(",
")",
"if",
"len",
"(",
"name",
")",
">",
"0",
":",
"geneset_symbol",
".",
"append",
"(",
"str",
"(",
"name",
"[",
"0",
"]",
")",
")",
"else",
":",
"unknown_counter",
"+=",
"1",
"geneset_symbol",
".",
"append",
"(",
"\"<\"",
"+",
"i",
"+",
"\">\"",
")",
"if",
"unknown_counter",
">",
"0",
":",
"logging",
".",
"warning",
"(",
"\"%d/%d terms that couldn't be mapped\"",
"%",
"(",
"unknown_counter",
",",
"len",
"(",
"geneset",
")",
")",
")",
"return",
"geneset_symbol"
] | Method to convert the entrez genes to symbols | [
"Method",
"to",
"convert",
"the",
"entrez",
"genes",
"to",
"symbols"
] | [
"\"\"\"\n Method to convert the entrez genes to symbols\n\n :param tsv_data: the dataframe to work on\n :param symbol_col: the column containing the symbols\n :param entrez_col: the column containing the entrez ID\n :param geneset: column containing the entrez to convert\n :return: list containing the string names\n\n Example\n _______\n >>> gmt_data = rc.ReadGmt(\".gmt\", True).get_data()\n >>> converted = []\n >>> for k, d in gmt_data.items():\n >>> converted[k] = Converters.convert_e2s(d[\"genes\"], tsv_data,entrez_col, symbol_col)\n\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "geneset",
"type": "pd.DataFrame"
},
{
"param": "tsv_data",
"type": "pd.DataFrame"
},
{
"param": "entrez_col",
"type": "str"
},
{
"param": "symbol_col",
"type": "str"
}
] | {
"returns": [
{
"docstring": "list containing the string names\nExample\n>>> gmt_data = rc.ReadGmt(\".gmt\", True).get_data()\n>>> converted = []\n>>> for k, d in gmt_data.items():\n>>> converted[k] = Converters.convert_e2s(d[\"genes\"], tsv_data,entrez_col, symbol_col)",
"docstring_tokens": [
"list",
"containing",
"the",
"string",
"names",
"Example",
">>>",
"gmt_data",
"=",
"rc",
".",
"ReadGmt",
"(",
"\"",
".",
"gmt",
"\"",
"True",
")",
".",
"get_data",
"()",
">>>",
"converted",
"=",
"[]",
">>>",
"for",
"k",
"d",
"in",
"gmt_data",
".",
"items",
"()",
":",
">>>",
"converted",
"[",
"k",
"]",
"=",
"Converters",
".",
"convert_e2s",
"(",
"d",
"[",
"\"",
"genes",
"\"",
"]",
"tsv_data",
"entrez_col",
"symbol_col",
")"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "geneset",
"type": "pd.DataFrame",
"docstring": "column containing the entrez to convert",
"docstring_tokens": [
"column",
"containing",
"the",
"entrez",
"to",
"convert"
],
"default": null,
"is_optional": null
},
{
"identifier": "tsv_data",
"type": "pd.DataFrame",
"docstring": "the dataframe to work on",
"docstring_tokens": [
"the",
"dataframe",
"to",
"work",
"on"
],
"default": null,
"is_optional": null
},
{
"identifier": "entrez_col",
"type": "str",
"docstring": "the column containing the entrez ID",
"docstring_tokens": [
"the",
"column",
"containing",
"the",
"entrez",
"ID"
],
"default": null,
"is_optional": null
},
{
"identifier": "symbol_col",
"type": "str",
"docstring": "the column containing the symbols",
"docstring_tokens": [
"the",
"column",
"containing",
"the",
"symbols"
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import logging
def convert_e2s(cls, geneset: pd.DataFrame, tsv_data: pd.DataFrame, entrez_col: str = "NCBI Gene ID",
symbol_col: str = "Approved symbol") -> list:
logging.info("Converting Entrez ID -> Symbols")
unknown_counter = 0
geneset_symbol = []
for i in geneset:
name = tsv_data[tsv_data[entrez_col] == int(i)][symbol_col].values.tolist()
if len(name) > 0:
geneset_symbol.append(str(name[0]))
else:
unknown_counter += 1
geneset_symbol.append("<" + i + ">")
if unknown_counter > 0:
logging.warning("%d/%d terms that couldn't be mapped" % (unknown_counter, len(geneset)))
return geneset_symbol | 610,387 | 54 |
0224f727a16636369024c0b8fb2b16edd5d26e4f | AtharvaPusalkar/MITx-6.00.1x | PSET 4/problem-4.py | [
"MIT"
] | Python | calculateHandlen | <not_specific> | def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
count = 0
for i in hand:
count += hand[i]
return count |
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
| Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer | [
"Returns",
"the",
"length",
"(",
"number",
"of",
"letters",
")",
"in",
"the",
"current",
"hand",
".",
"hand",
":",
"dictionary",
"(",
"string",
"int",
")",
"returns",
":",
"integer"
] | def calculateHandlen(hand):
count = 0
for i in hand:
count += hand[i]
return count | [
"def",
"calculateHandlen",
"(",
"hand",
")",
":",
"count",
"=",
"0",
"for",
"i",
"in",
"hand",
":",
"count",
"+=",
"hand",
"[",
"i",
"]",
"return",
"count"
] | Returns the length (number of letters) in the current hand. | [
"Returns",
"the",
"length",
"(",
"number",
"of",
"letters",
")",
"in",
"the",
"current",
"hand",
"."
] | [
"\"\"\" \n Returns the length (number of letters) in the current hand.\n \n hand: dictionary (string int)\n returns: integer\n \"\"\""
] | [
{
"param": "hand",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hand",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def calculateHandlen(hand):
count = 0
for i in hand:
count += hand[i]
return count | 610,388 | 413 |
59d9d976f42cf0a6cbb0dd903908ba0d941f9d9b | choderalab/fah-xchem | fah_xchem/analysis/extract_work.py | [
"MIT"
] | Python | _get_num_steps | int | def _get_num_steps(df: pd.DataFrame) -> int:
"""
Get the number of steps described in the dataframe
Parameters
----------
df : pandas.DataFrame
The dataframe containing `Step` column
Returns
-------
n_steps : int
The number of steps described in the dataframe
"""
if df.empty:
raise ValueError("Empty dataframe")
step = df["Step"].astype(int)
return int(step.iloc[-1] - step.iloc[0]) |
Get the number of steps described in the dataframe
Parameters
----------
df : pandas.DataFrame
The dataframe containing `Step` column
Returns
-------
n_steps : int
The number of steps described in the dataframe
| Get the number of steps described in the dataframe
Parameters
df : pandas.DataFrame
The dataframe containing `Step` column
Returns
n_steps : int
The number of steps described in the dataframe | [
"Get",
"the",
"number",
"of",
"steps",
"described",
"in",
"the",
"dataframe",
"Parameters",
"df",
":",
"pandas",
".",
"DataFrame",
"The",
"dataframe",
"containing",
"`",
"Step",
"`",
"column",
"Returns",
"n_steps",
":",
"int",
"The",
"number",
"of",
"steps",
"described",
"in",
"the",
"dataframe"
] | def _get_num_steps(df: pd.DataFrame) -> int:
if df.empty:
raise ValueError("Empty dataframe")
step = df["Step"].astype(int)
return int(step.iloc[-1] - step.iloc[0]) | [
"def",
"_get_num_steps",
"(",
"df",
":",
"pd",
".",
"DataFrame",
")",
"->",
"int",
":",
"if",
"df",
".",
"empty",
":",
"raise",
"ValueError",
"(",
"\"Empty dataframe\"",
")",
"step",
"=",
"df",
"[",
"\"Step\"",
"]",
".",
"astype",
"(",
"int",
")",
"return",
"int",
"(",
"step",
".",
"iloc",
"[",
"-",
"1",
"]",
"-",
"step",
".",
"iloc",
"[",
"0",
"]",
")"
] | Get the number of steps described in the dataframe
Parameters | [
"Get",
"the",
"number",
"of",
"steps",
"described",
"in",
"the",
"dataframe",
"Parameters"
] | [
"\"\"\"\n Get the number of steps described in the dataframe\n\n Parameters\n ----------\n df : pandas.DataFrame\n The dataframe containing `Step` column\n\n Returns\n -------\n n_steps : int\n The number of steps described in the dataframe\n\n \"\"\""
] | [
{
"param": "df",
"type": "pd.DataFrame"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": "pd.DataFrame",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _get_num_steps(df: pd.DataFrame) -> int:
if df.empty:
raise ValueError("Empty dataframe")
step = df["Step"].astype(int)
return int(step.iloc[-1] - step.iloc[0]) | 610,389 | 504 |
acb87cb757722d2362b46268c1505ec8458db96d | getslash/confetti | confetti/config.py | [
"BSD-3-Clause"
] | Python | from_string | <not_specific> | def from_string(cls, s, namespace=None):
"""
Initializes the config from a string. The string is expected to contain the config as a variable named ``CONFIG``.
"""
if namespace is None:
namespace = {}
else:
namespace = dict(namespace)
exec(s, namespace)
return cls(namespace['CONFIG']) |
Initializes the config from a string. The string is expected to contain the config as a variable named ``CONFIG``.
| Initializes the config from a string. The string is expected to contain the config as a variable named ``CONFIG``. | [
"Initializes",
"the",
"config",
"from",
"a",
"string",
".",
"The",
"string",
"is",
"expected",
"to",
"contain",
"the",
"config",
"as",
"a",
"variable",
"named",
"`",
"`",
"CONFIG",
"`",
"`",
"."
] | def from_string(cls, s, namespace=None):
if namespace is None:
namespace = {}
else:
namespace = dict(namespace)
exec(s, namespace)
return cls(namespace['CONFIG']) | [
"def",
"from_string",
"(",
"cls",
",",
"s",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"{",
"}",
"else",
":",
"namespace",
"=",
"dict",
"(",
"namespace",
")",
"exec",
"(",
"s",
",",
"namespace",
")",
"return",
"cls",
"(",
"namespace",
"[",
"'CONFIG'",
"]",
")"
] | Initializes the config from a string. | [
"Initializes",
"the",
"config",
"from",
"a",
"string",
"."
] | [
"\"\"\"\n Initializes the config from a string. The string is expected to contain the config as a variable named ``CONFIG``.\n \"\"\""
] | [
{
"param": "cls",
"type": null
},
{
"param": "s",
"type": null
},
{
"param": "namespace",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cls",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "s",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "namespace",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def from_string(cls, s, namespace=None):
if namespace is None:
namespace = {}
else:
namespace = dict(namespace)
exec(s, namespace)
return cls(namespace['CONFIG']) | 610,390 | 127 |
2f88875e58598aa36b9eb07a6b3e26a667cc3692 | Saharae/Final-Project-Group2 | joshua-ting-individual-project/Code/my_other_work.py | [
"MIT"
] | Python | ratio_capital_letters | <not_specific> | def ratio_capital_letters(df, col_name):
'''
Function to get ratio of interesting characters in string
Parameter
---------
df: dataset
col_name: column name to get number of words
Return
df: dataset transformed
'''
df['{}_ratio_capital_letters'.format(col_name)] = df[col_name].map(lambda x: len([i for i in x if i.isupper()])/len([i for i in x]) if isinstance(x, str) else 0)
# print(df[[col_name, '{}_ratio_capital_letters'.format(col_name)]].head())
return df |
Function to get ratio of interesting characters in string
Parameter
---------
df: dataset
col_name: column name to get number of words
Return
df: dataset transformed
| Function to get ratio of interesting characters in string
Parameter
dataset
col_name: column name to get number of words
Return
df: dataset transformed | [
"Function",
"to",
"get",
"ratio",
"of",
"interesting",
"characters",
"in",
"string",
"Parameter",
"dataset",
"col_name",
":",
"column",
"name",
"to",
"get",
"number",
"of",
"words",
"Return",
"df",
":",
"dataset",
"transformed"
] | def ratio_capital_letters(df, col_name):
df['{}_ratio_capital_letters'.format(col_name)] = df[col_name].map(lambda x: len([i for i in x if i.isupper()])/len([i for i in x]) if isinstance(x, str) else 0)
return df | [
"def",
"ratio_capital_letters",
"(",
"df",
",",
"col_name",
")",
":",
"df",
"[",
"'{}_ratio_capital_letters'",
".",
"format",
"(",
"col_name",
")",
"]",
"=",
"df",
"[",
"col_name",
"]",
".",
"map",
"(",
"lambda",
"x",
":",
"len",
"(",
"[",
"i",
"for",
"i",
"in",
"x",
"if",
"i",
".",
"isupper",
"(",
")",
"]",
")",
"/",
"len",
"(",
"[",
"i",
"for",
"i",
"in",
"x",
"]",
")",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
"else",
"0",
")",
"return",
"df"
] | Function to get ratio of interesting characters in string
Parameter | [
"Function",
"to",
"get",
"ratio",
"of",
"interesting",
"characters",
"in",
"string",
"Parameter"
] | [
"'''\n Function to get ratio of interesting characters in string\n\n Parameter\n ---------\n df: dataset\n col_name: column name to get number of words\n\n Return\n df: dataset transformed\n '''",
"# print(df[[col_name, '{}_ratio_capital_letters'.format(col_name)]].head())"
] | [
{
"param": "df",
"type": null
},
{
"param": "col_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "df",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "col_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def ratio_capital_letters(df, col_name):
df['{}_ratio_capital_letters'.format(col_name)] = df[col_name].map(lambda x: len([i for i in x if i.isupper()])/len([i for i in x]) if isinstance(x, str) else 0)
return df | 610,391 | 966 |
1be9aef821fa946560784d3d6616a9b0dc25382e | VMarty/CityEnergyAnalyst | cea/analysis/clustering/sax/sax_optimization.py | [
"MIT"
] | Python | calc_complexity | <not_specific> | def calc_complexity(names_of_clusters):
"""
Calculated according to 'Application of time series discretization using evolutionary programming for classification
of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014
:param names_of_clusters: list containing a word which clusters the time series. e.g., ['abcffs', dddddd'...'svfdab']
:return: level of complexity which penalizes the objective function
"""
single_words_length = len(list(set(names_of_clusters)))
len_timeseries = len(names_of_clusters) # number of observations
result = 1- (single_words_length/ len_timeseries)
return result |
Calculated according to 'Application of time series discretization using evolutionary programming for classification
of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014
:param names_of_clusters: list containing a word which clusters the time series. e.g., ['abcffs', dddddd'...'svfdab']
:return: level of complexity which penalizes the objective function
| Calculated according to 'Application of time series discretization using evolutionary programming for classification
of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014 | [
"Calculated",
"according",
"to",
"'",
"Application",
"of",
"time",
"series",
"discretization",
"using",
"evolutionary",
"programming",
"for",
"classification",
"of",
"precancerous",
"cervical",
"lesions",
"'",
"by",
"H",
".",
"Acosta",
"-",
"Mesa",
"et",
"al",
".",
"2014"
] | def calc_complexity(names_of_clusters):
single_words_length = len(list(set(names_of_clusters)))
len_timeseries = len(names_of_clusters)
result = 1- (single_words_length/ len_timeseries)
return result | [
"def",
"calc_complexity",
"(",
"names_of_clusters",
")",
":",
"single_words_length",
"=",
"len",
"(",
"list",
"(",
"set",
"(",
"names_of_clusters",
")",
")",
")",
"len_timeseries",
"=",
"len",
"(",
"names_of_clusters",
")",
"result",
"=",
"1",
"-",
"(",
"single_words_length",
"/",
"len_timeseries",
")",
"return",
"result"
] | Calculated according to 'Application of time series discretization using evolutionary programming for classification
of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014 | [
"Calculated",
"according",
"to",
"'",
"Application",
"of",
"time",
"series",
"discretization",
"using",
"evolutionary",
"programming",
"for",
"classification",
"of",
"precancerous",
"cervical",
"lesions",
"'",
"by",
"H",
".",
"Acosta",
"-",
"Mesa",
"et",
"al",
".",
"2014"
] | [
"\"\"\"\n Calculated according to 'Application of time series discretization using evolutionary programming for classification\n of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014\n :param names_of_clusters: list containing a word which clusters the time series. e.g., ['abcffs', dddddd'...'svfdab']\n :return: level of complexity which penalizes the objective function\n \"\"\"",
"# number of observations"
] | [
{
"param": "names_of_clusters",
"type": null
}
] | {
"returns": [
{
"docstring": "level of complexity which penalizes the objective function",
"docstring_tokens": [
"level",
"of",
"complexity",
"which",
"penalizes",
"the",
"objective",
"function"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "names_of_clusters",
"type": null,
"docstring": "list containing a word which clusters the time series.",
"docstring_tokens": [
"list",
"containing",
"a",
"word",
"which",
"clusters",
"the",
"time",
"series",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def calc_complexity(names_of_clusters):
single_words_length = len(list(set(names_of_clusters)))
len_timeseries = len(names_of_clusters)
result = 1- (single_words_length/ len_timeseries)
return result | 610,392 | 747 |
28953e59dd04e1ee5ea79c7fa66b4afe72794756 | notapresent/rutracker_rss | feeds.py | [
"Apache-2.0"
] | Python | feed_size | <not_specific> | def feed_size(category):
"""Returns number of feed entries for category"""
if category.key.id() == 'r0': # Root category
return 100
elif category.key.id().startswith('c'): # Level 2 category
return 50
return 25 # category with subcategories | Returns number of feed entries for category | Returns number of feed entries for category | [
"Returns",
"number",
"of",
"feed",
"entries",
"for",
"category"
] | def feed_size(category):
if category.key.id() == 'r0':
return 100
elif category.key.id().startswith('c'):
return 50
return 25 | [
"def",
"feed_size",
"(",
"category",
")",
":",
"if",
"category",
".",
"key",
".",
"id",
"(",
")",
"==",
"'r0'",
":",
"return",
"100",
"elif",
"category",
".",
"key",
".",
"id",
"(",
")",
".",
"startswith",
"(",
"'c'",
")",
":",
"return",
"50",
"return",
"25"
] | Returns number of feed entries for category | [
"Returns",
"number",
"of",
"feed",
"entries",
"for",
"category"
] | [
"\"\"\"Returns number of feed entries for category\"\"\"",
"# Root category",
"# Level 2 category",
"# category with subcategories"
] | [
{
"param": "category",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "category",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def feed_size(category):
if category.key.id() == 'r0':
return 100
elif category.key.id().startswith('c'):
return 50
return 25 | 610,393 | 841 |
d49b427031eeb31006bbdc73c306a216d045bf92 | hsinyy02/Paddy-Field-Segmentation | code/stitching.py | [
"MIT"
] | Python | point_homography | <not_specific> | def point_homography(point, H):
"""Apply projective transformation (homography) on a point.
Parameters:
point: (x, y) tuple.
A point for projective transformation.
H: A homography matrix.
Return:
homo: (x, y) tuple.
The point after projective transformation.
"""
h0, h1, h2 = H[0]
h3, h4, h5 = H[1]
h6, h7, h8 = H[2]
x, y = point
tx = h0*x + h1*y + h2
ty = h3*x + h4*y + h5
tz = h6*x + h7*y + h8
homo = (tx/tz, ty/tz)
return homo | Apply projective transformation (homography) on a point.
Parameters:
point: (x, y) tuple.
A point for projective transformation.
H: A homography matrix.
Return:
homo: (x, y) tuple.
The point after projective transformation.
| Apply projective transformation (homography) on a point. | [
"Apply",
"projective",
"transformation",
"(",
"homography",
")",
"on",
"a",
"point",
"."
] | def point_homography(point, H):
h0, h1, h2 = H[0]
h3, h4, h5 = H[1]
h6, h7, h8 = H[2]
x, y = point
tx = h0*x + h1*y + h2
ty = h3*x + h4*y + h5
tz = h6*x + h7*y + h8
homo = (tx/tz, ty/tz)
return homo | [
"def",
"point_homography",
"(",
"point",
",",
"H",
")",
":",
"h0",
",",
"h1",
",",
"h2",
"=",
"H",
"[",
"0",
"]",
"h3",
",",
"h4",
",",
"h5",
"=",
"H",
"[",
"1",
"]",
"h6",
",",
"h7",
",",
"h8",
"=",
"H",
"[",
"2",
"]",
"x",
",",
"y",
"=",
"point",
"tx",
"=",
"h0",
"*",
"x",
"+",
"h1",
"*",
"y",
"+",
"h2",
"ty",
"=",
"h3",
"*",
"x",
"+",
"h4",
"*",
"y",
"+",
"h5",
"tz",
"=",
"h6",
"*",
"x",
"+",
"h7",
"*",
"y",
"+",
"h8",
"homo",
"=",
"(",
"tx",
"/",
"tz",
",",
"ty",
"/",
"tz",
")",
"return",
"homo"
] | Apply projective transformation (homography) on a point. | [
"Apply",
"projective",
"transformation",
"(",
"homography",
")",
"on",
"a",
"point",
"."
] | [
"\"\"\"Apply projective transformation (homography) on a point.\n\n Parameters:\n point: (x, y) tuple. \n A point for projective transformation.\n\n H: A homography matrix.\n \n Return:\n homo: (x, y) tuple.\n The point after projective transformation.\n \"\"\""
] | [
{
"param": "point",
"type": null
},
{
"param": "H",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "point",
"type": null,
"docstring": "(x, y) tuple.\nA point for projective transformation.",
"docstring_tokens": [
"(",
"x",
"y",
")",
"tuple",
".",
"A",
"point",
"for",
"projective",
"transformation",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "H",
"type": null,
"docstring": "A homography matrix.",
"docstring_tokens": [
"A",
"homography",
"matrix",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def point_homography(point, H):
h0, h1, h2 = H[0]
h3, h4, h5 = H[1]
h6, h7, h8 = H[2]
x, y = point
tx = h0*x + h1*y + h2
ty = h3*x + h4*y + h5
tz = h6*x + h7*y + h8
homo = (tx/tz, ty/tz)
return homo | 610,394 | 281 |
72eec153e741c8731540655b0bff97137fe62117 | hkgopal/tf-test | tcutils/util.py | [
"Apache-2.0"
] | Python | read_config_option | <not_specific> | def read_config_option(config, section, option, default_option):
''' Read the config file. If the option/section is not present, return the default_option
'''
if not config:
return default_option
try:
val = config.get(section, option)
except (configparser.NoOptionError, configparser.NoSectionError):
return default_option
if val.lower() == 'true':
val = True
#elif val.lower() == 'false' or val.lower() == 'none':
elif val.lower() == 'false':
val = False
elif not val:
val = default_option
if type(val) is not bool and val is not None and (
'$__' in val or val.lower() == 'none'):
# ie. having a template value unpopulated(for $__xyz__)
# or None
val = ''
if val == '' :
val = default_option
return val | Read the config file. If the option/section is not present, return the default_option
| Read the config file. If the option/section is not present, return the default_option | [
"Read",
"the",
"config",
"file",
".",
"If",
"the",
"option",
"/",
"section",
"is",
"not",
"present",
"return",
"the",
"default_option"
] | def read_config_option(config, section, option, default_option):
if not config:
return default_option
try:
val = config.get(section, option)
except (configparser.NoOptionError, configparser.NoSectionError):
return default_option
if val.lower() == 'true':
val = True
elif val.lower() == 'false':
val = False
elif not val:
val = default_option
if type(val) is not bool and val is not None and (
'$__' in val or val.lower() == 'none'):
val = ''
if val == '' :
val = default_option
return val | [
"def",
"read_config_option",
"(",
"config",
",",
"section",
",",
"option",
",",
"default_option",
")",
":",
"if",
"not",
"config",
":",
"return",
"default_option",
"try",
":",
"val",
"=",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"except",
"(",
"configparser",
".",
"NoOptionError",
",",
"configparser",
".",
"NoSectionError",
")",
":",
"return",
"default_option",
"if",
"val",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"val",
"=",
"True",
"elif",
"val",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"val",
"=",
"False",
"elif",
"not",
"val",
":",
"val",
"=",
"default_option",
"if",
"type",
"(",
"val",
")",
"is",
"not",
"bool",
"and",
"val",
"is",
"not",
"None",
"and",
"(",
"'$__'",
"in",
"val",
"or",
"val",
".",
"lower",
"(",
")",
"==",
"'none'",
")",
":",
"val",
"=",
"''",
"if",
"val",
"==",
"''",
":",
"val",
"=",
"default_option",
"return",
"val"
] | Read the config file. | [
"Read",
"the",
"config",
"file",
"."
] | [
"''' Read the config file. If the option/section is not present, return the default_option\n '''",
"#elif val.lower() == 'false' or val.lower() == 'none':",
"# ie. having a template value unpopulated(for $__xyz__)",
"# or None"
] | [
{
"param": "config",
"type": null
},
{
"param": "section",
"type": null
},
{
"param": "option",
"type": null
},
{
"param": "default_option",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "section",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "option",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "default_option",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import configparser
def read_config_option(config, section, option, default_option):
if not config:
return default_option
try:
val = config.get(section, option)
except (configparser.NoOptionError, configparser.NoSectionError):
return default_option
if val.lower() == 'true':
val = True
elif val.lower() == 'false':
val = False
elif not val:
val = default_option
if type(val) is not bool and val is not None and (
'$__' in val or val.lower() == 'none'):
val = ''
if val == '' :
val = default_option
return val | 610,395 | 53 |
9b3cfb5734765325ae3a96f1ed3a0f939f9e14ce | lucasb-eyer/datasets | tensorflow_datasets/core/download/kaggle.py | [
"Apache-2.0"
] | Python | _kaggle_dir_name | str | def _kaggle_dir_name(competition_or_dataset: str) -> str:
"""Returns path where the dataset is to be downloaded.
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Path to the dir where the dataset is to be downloaded.
"""
return competition_or_dataset.replace('/', '_') | Returns path where the dataset is to be downloaded.
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Path to the dir where the dataset is to be downloaded.
| Returns path where the dataset is to be downloaded. | [
"Returns",
"path",
"where",
"the",
"dataset",
"is",
"to",
"be",
"downloaded",
"."
] | def _kaggle_dir_name(competition_or_dataset: str) -> str:
return competition_or_dataset.replace('/', '_') | [
"def",
"_kaggle_dir_name",
"(",
"competition_or_dataset",
":",
"str",
")",
"->",
"str",
":",
"return",
"competition_or_dataset",
".",
"replace",
"(",
"'/'",
",",
"'_'",
")"
] | Returns path where the dataset is to be downloaded. | [
"Returns",
"path",
"where",
"the",
"dataset",
"is",
"to",
"be",
"downloaded",
"."
] | [
"\"\"\"Returns path where the dataset is to be downloaded.\n\n Args:\n competition_or_dataset: Name of the kaggle competition/dataset.\n\n Returns:\n Path to the dir where the dataset is to be downloaded.\n \"\"\""
] | [
{
"param": "competition_or_dataset",
"type": "str"
}
] | {
"returns": [
{
"docstring": "Path to the dir where the dataset is to be downloaded.",
"docstring_tokens": [
"Path",
"to",
"the",
"dir",
"where",
"the",
"dataset",
"is",
"to",
"be",
"downloaded",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "competition_or_dataset",
"type": "str",
"docstring": "Name of the kaggle competition/dataset.",
"docstring_tokens": [
"Name",
"of",
"the",
"kaggle",
"competition",
"/",
"dataset",
"."
],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def _kaggle_dir_name(competition_or_dataset: str) -> str:
return competition_or_dataset.replace('/', '_') | 610,396 | 866 |
201f5488d1884708f4227d61239a4105b46eb1a6 | arsinclair/Chromagnon | chromagnon/classicalOutput.py | [
"BSD-3-Clause"
] | Python | classicalOutput | null | def classicalOutput(queryResult, separator="\t"):
"""
Display the data separated by the specified separator
"""
for line in queryResult:
for element in line:
sys.stdout.write(element)
sys.stdout.write(separator)
sys.stdout.write('\n') |
Display the data separated by the specified separator
| Display the data separated by the specified separator | [
"Display",
"the",
"data",
"separated",
"by",
"the",
"specified",
"separator"
] | def classicalOutput(queryResult, separator="\t"):
for line in queryResult:
for element in line:
sys.stdout.write(element)
sys.stdout.write(separator)
sys.stdout.write('\n') | [
"def",
"classicalOutput",
"(",
"queryResult",
",",
"separator",
"=",
"\"\\t\"",
")",
":",
"for",
"line",
"in",
"queryResult",
":",
"for",
"element",
"in",
"line",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"element",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"separator",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")"
] | Display the data separated by the specified separator | [
"Display",
"the",
"data",
"separated",
"by",
"the",
"specified",
"separator"
] | [
"\"\"\"\n Display the data separated by the specified separator\n \"\"\""
] | [
{
"param": "queryResult",
"type": null
},
{
"param": "separator",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "queryResult",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "separator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import sys
def classicalOutput(queryResult, separator="\t"):
for line in queryResult:
for element in line:
sys.stdout.write(element)
sys.stdout.write(separator)
sys.stdout.write('\n') | 610,397 | 905 |
2170655fd1b3b04b7b7bf4abc8519c9dace4bdda | bshephar/directord | directord/iodict.py | [
"Apache-2.0"
] | Python | _get_item_key | <not_specific> | def _get_item_key(path: str):
"""Return the key name from a file object.
:returns: String
"""
try:
key = os.getxattr(path, "user.key")
except OSError:
if not os.path.exists(path):
raise FileNotFoundError(path) from None
return os.path.basename(path)
else:
return key.decode() | Return the key name from a file object.
:returns: String
| Return the key name from a file object. | [
"Return",
"the",
"key",
"name",
"from",
"a",
"file",
"object",
"."
] | def _get_item_key(path: str):
try:
key = os.getxattr(path, "user.key")
except OSError:
if not os.path.exists(path):
raise FileNotFoundError(path) from None
return os.path.basename(path)
else:
return key.decode() | [
"def",
"_get_item_key",
"(",
"path",
":",
"str",
")",
":",
"try",
":",
"key",
"=",
"os",
".",
"getxattr",
"(",
"path",
",",
"\"user.key\"",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"FileNotFoundError",
"(",
"path",
")",
"from",
"None",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"else",
":",
"return",
"key",
".",
"decode",
"(",
")"
] | Return the key name from a file object. | [
"Return",
"the",
"key",
"name",
"from",
"a",
"file",
"object",
"."
] | [
"\"\"\"Return the key name from a file object.\n\n :returns: String\n \"\"\""
] | [
{
"param": "path",
"type": "str"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "path",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def _get_item_key(path: str):
try:
key = os.getxattr(path, "user.key")
except OSError:
if not os.path.exists(path):
raise FileNotFoundError(path) from None
return os.path.basename(path)
else:
return key.decode() | 610,398 | 921 |
8e72fcda175f510d6a24529d813a5c58c67df05f | wezil/principles-computing | 7-word-wrangler.py | [
"MIT"
] | Python | gen_all_strings | <not_specific> | def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
# base case with no length word
if len(word) == 0:
return [""]
# recursive case
head = word[0]
tail = word[1: ]
# keep track of a master list while generating sub list
master_list = []
sub_list = gen_all_strings(tail)
# add sub list to master list
master_list.extend(sub_list)
# for each sub list word add to master list a combination of all
# head character positions in sub word
for sub_word in sub_list:
for index in range(len(sub_word) + 1):
master_list.append(sub_word[:index] + head + sub_word[index: ])
return master_list |
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
| Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive. | [
"Generate",
"all",
"strings",
"that",
"can",
"be",
"composed",
"from",
"the",
"letters",
"in",
"word",
"in",
"any",
"order",
".",
"Returns",
"a",
"list",
"of",
"all",
"strings",
"that",
"can",
"be",
"formed",
"from",
"the",
"letters",
"in",
"word",
".",
"This",
"function",
"should",
"be",
"recursive",
"."
] | def gen_all_strings(word):
if len(word) == 0:
return [""]
head = word[0]
tail = word[1: ]
master_list = []
sub_list = gen_all_strings(tail)
master_list.extend(sub_list)
for sub_word in sub_list:
for index in range(len(sub_word) + 1):
master_list.append(sub_word[:index] + head + sub_word[index: ])
return master_list | [
"def",
"gen_all_strings",
"(",
"word",
")",
":",
"if",
"len",
"(",
"word",
")",
"==",
"0",
":",
"return",
"[",
"\"\"",
"]",
"head",
"=",
"word",
"[",
"0",
"]",
"tail",
"=",
"word",
"[",
"1",
":",
"]",
"master_list",
"=",
"[",
"]",
"sub_list",
"=",
"gen_all_strings",
"(",
"tail",
")",
"master_list",
".",
"extend",
"(",
"sub_list",
")",
"for",
"sub_word",
"in",
"sub_list",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"sub_word",
")",
"+",
"1",
")",
":",
"master_list",
".",
"append",
"(",
"sub_word",
"[",
":",
"index",
"]",
"+",
"head",
"+",
"sub_word",
"[",
"index",
":",
"]",
")",
"return",
"master_list"
] | Generate all strings that can be composed from the letters in word
in any order. | [
"Generate",
"all",
"strings",
"that",
"can",
"be",
"composed",
"from",
"the",
"letters",
"in",
"word",
"in",
"any",
"order",
"."
] | [
"\"\"\"\n Generate all strings that can be composed from the letters in word\n in any order.\n\n Returns a list of all strings that can be formed from the letters\n in word.\n\n This function should be recursive.\n \"\"\"",
"# base case with no length word",
"# recursive case",
"# keep track of a master list while generating sub list",
"# add sub list to master list",
"# for each sub list word add to master list a combination of all",
"# head character positions in sub word"
] | [
{
"param": "word",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "word",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def gen_all_strings(word):
if len(word) == 0:
return [""]
head = word[0]
tail = word[1: ]
master_list = []
sub_list = gen_all_strings(tail)
master_list.extend(sub_list)
for sub_word in sub_list:
for index in range(len(sub_word) + 1):
master_list.append(sub_word[:index] + head + sub_word[index: ])
return master_list | 610,399 | 619 |
e7690ec0872dd31fcd7b0ca82e4142a3b41fbeee | seatim/dwave-system | dwave/embedding/chain_strength.py | [
"Apache-2.0"
] | Python | scaled | <not_specific> | def scaled(bqm, embedding=None, prefactor=1.0):
"""Chain strength that is scaled to the problem bias range.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
A binary quadratic model.
embedding (dict/:class:`.EmbeddedStructure`, default=None):
Included to satisfy the `chain_strength` callable specifications
for `embed_bqm`.
prefactor (float, optional, default=1.0):
Prefactor used for scaling.
Returns:
float: The chain strength, or 1 if chain strength is not applicable.
"""
if bqm.num_interactions > 0:
max_bias = max(max(bqm.linear.max(), -bqm.linear.min()),
max(bqm.quadratic.max(), -bqm.quadratic.min()))
return prefactor * max_bias
else:
return 1 # won't matter (chain strength isn't needed to embed this problem) | Chain strength that is scaled to the problem bias range.
Args:
bqm (:obj:`.BinaryQuadraticModel`):
A binary quadratic model.
embedding (dict/:class:`.EmbeddedStructure`, default=None):
Included to satisfy the `chain_strength` callable specifications
for `embed_bqm`.
prefactor (float, optional, default=1.0):
Prefactor used for scaling.
Returns:
float: The chain strength, or 1 if chain strength is not applicable.
| Chain strength that is scaled to the problem bias range. | [
"Chain",
"strength",
"that",
"is",
"scaled",
"to",
"the",
"problem",
"bias",
"range",
"."
] | def scaled(bqm, embedding=None, prefactor=1.0):
if bqm.num_interactions > 0:
max_bias = max(max(bqm.linear.max(), -bqm.linear.min()),
max(bqm.quadratic.max(), -bqm.quadratic.min()))
return prefactor * max_bias
else:
return 1 | [
"def",
"scaled",
"(",
"bqm",
",",
"embedding",
"=",
"None",
",",
"prefactor",
"=",
"1.0",
")",
":",
"if",
"bqm",
".",
"num_interactions",
">",
"0",
":",
"max_bias",
"=",
"max",
"(",
"max",
"(",
"bqm",
".",
"linear",
".",
"max",
"(",
")",
",",
"-",
"bqm",
".",
"linear",
".",
"min",
"(",
")",
")",
",",
"max",
"(",
"bqm",
".",
"quadratic",
".",
"max",
"(",
")",
",",
"-",
"bqm",
".",
"quadratic",
".",
"min",
"(",
")",
")",
")",
"return",
"prefactor",
"*",
"max_bias",
"else",
":",
"return",
"1"
] | Chain strength that is scaled to the problem bias range. | [
"Chain",
"strength",
"that",
"is",
"scaled",
"to",
"the",
"problem",
"bias",
"range",
"."
] | [
"\"\"\"Chain strength that is scaled to the problem bias range.\n\n Args:\n bqm (:obj:`.BinaryQuadraticModel`):\n A binary quadratic model.\n\n embedding (dict/:class:`.EmbeddedStructure`, default=None):\n Included to satisfy the `chain_strength` callable specifications \n for `embed_bqm`. \n\n prefactor (float, optional, default=1.0):\n Prefactor used for scaling. \n\n Returns:\n float: The chain strength, or 1 if chain strength is not applicable.\n\n \"\"\"",
"# won't matter (chain strength isn't needed to embed this problem)"
] | [
{
"param": "bqm",
"type": null
},
{
"param": "embedding",
"type": null
},
{
"param": "prefactor",
"type": null
}
] | {
"returns": [
{
"docstring": "The chain strength, or 1 if chain strength is not applicable.",
"docstring_tokens": [
"The",
"chain",
"strength",
"or",
"1",
"if",
"chain",
"strength",
"is",
"not",
"applicable",
"."
],
"type": "float"
}
],
"raises": [],
"params": [
{
"identifier": "bqm",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "embedding",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "prefactor",
"type": null,
"docstring": "Prefactor used for scaling.",
"docstring_tokens": [
"Prefactor",
"used",
"for",
"scaling",
"."
],
"default": null,
"is_optional": false
}
],
"outlier_params": [
{
"identifier": "bqm (",
"type": null,
"docstring": "`.BinaryQuadraticModel`):\nA binary quadratic model.",
"docstring_tokens": [
"`",
".",
"BinaryQuadraticModel",
"`",
")",
":",
"A",
"binary",
"quadratic",
"model",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "embedding (dict/",
"type": null,
"docstring": "`.EmbeddedStructure`, default=None):\nIncluded to satisfy the `chain_strength` callable specifications\nfor `embed_bqm`.",
"docstring_tokens": [
"`",
".",
"EmbeddedStructure",
"`",
"default",
"=",
"None",
")",
":",
"Included",
"to",
"satisfy",
"the",
"`",
"chain_strength",
"`",
"callable",
"specifications",
"for",
"`",
"embed_bqm",
"`",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
} | def scaled(bqm, embedding=None, prefactor=1.0):
if bqm.num_interactions > 0:
max_bias = max(max(bqm.linear.max(), -bqm.linear.min()),
max(bqm.quadratic.max(), -bqm.quadratic.min()))
return prefactor * max_bias
else:
return 1 | 610,400 | 674 |
a9a438bf555b78ef0bc4007be4642596f449b0ec | HarshCasper/trankit | trankit/utils/mwt_lemma_utils/seq2seq_utils.py | [
"Apache-2.0"
] | Python | sort | <not_specific> | def sort(packed, ref, reverse=True):
"""
Sort a series of packed list, according to a ref list.
Also return the original index before the sort.
"""
assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list)
packed = [ref] + [range(len(ref))] + list(packed)
sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]
return tuple(sorted_packed[1:]) |
Sort a series of packed list, according to a ref list.
Also return the original index before the sort.
| Sort a series of packed list, according to a ref list.
Also return the original index before the sort. | [
"Sort",
"a",
"series",
"of",
"packed",
"list",
"according",
"to",
"a",
"ref",
"list",
".",
"Also",
"return",
"the",
"original",
"index",
"before",
"the",
"sort",
"."
] | def sort(packed, ref, reverse=True):
assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list)
packed = [ref] + [range(len(ref))] + list(packed)
sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]
return tuple(sorted_packed[1:]) | [
"def",
"sort",
"(",
"packed",
",",
"ref",
",",
"reverse",
"=",
"True",
")",
":",
"assert",
"(",
"isinstance",
"(",
"packed",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"packed",
",",
"list",
")",
")",
"and",
"isinstance",
"(",
"ref",
",",
"list",
")",
"packed",
"=",
"[",
"ref",
"]",
"+",
"[",
"range",
"(",
"len",
"(",
"ref",
")",
")",
"]",
"+",
"list",
"(",
"packed",
")",
"sorted_packed",
"=",
"[",
"list",
"(",
"t",
")",
"for",
"t",
"in",
"zip",
"(",
"*",
"sorted",
"(",
"zip",
"(",
"*",
"packed",
")",
",",
"reverse",
"=",
"reverse",
")",
")",
"]",
"return",
"tuple",
"(",
"sorted_packed",
"[",
"1",
":",
"]",
")"
] | Sort a series of packed list, according to a ref list. | [
"Sort",
"a",
"series",
"of",
"packed",
"list",
"according",
"to",
"a",
"ref",
"list",
"."
] | [
"\"\"\"\r\n Sort a series of packed list, according to a ref list.\r\n Also return the original index before the sort.\r\n \"\"\""
] | [
{
"param": "packed",
"type": null
},
{
"param": "ref",
"type": null
},
{
"param": "reverse",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "packed",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ref",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "reverse",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def sort(packed, ref, reverse=True):
assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list)
packed = [ref] + [range(len(ref))] + list(packed)
sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]
return tuple(sorted_packed[1:]) | 610,401 | 542 |
03fce7299a054f6894e3611b9fd87dae92cf6514 | buffet/sequestrum | sequestrum/logging.py | [
"MIT"
] | Python | print_verbose | null | def print_verbose(error_message):
"""
Prints message with green color to show success
"""
print("\033[1;32mVERBOSE\033[0m {}".format(error_message)) |
Prints message with green color to show success
| Prints message with green color to show success | [
"Prints",
"message",
"with",
"green",
"color",
"to",
"show",
"success"
] | def print_verbose(error_message):
print("\033[1;32mVERBOSE\033[0m {}".format(error_message)) | [
"def",
"print_verbose",
"(",
"error_message",
")",
":",
"print",
"(",
"\"\\033[1;32mVERBOSE\\033[0m {}\"",
".",
"format",
"(",
"error_message",
")",
")"
] | Prints message with green color to show success | [
"Prints",
"message",
"with",
"green",
"color",
"to",
"show",
"success"
] | [
"\"\"\"\n Prints message with green color to show success\n \"\"\""
] | [
{
"param": "error_message",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "error_message",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def print_verbose(error_message):
print("\033[1;32mVERBOSE\033[0m {}".format(error_message)) | 610,402 | 136 |
a8922ba6075898495ae0f13f19d81db683a3c485 | BennettDixon/holbertonschool-higher_level_programming | 0x0B-python-input_output/1-number_of_lines.py | [
"MIT"
] | Python | number_of_lines | <not_specific> | def number_of_lines(filename=""):
"""gets the number of lines from filename
"""
with open(filename, encoding='utf-8') as myFile:
return sum([1 for line in myFile]) | gets the number of lines from filename
| gets the number of lines from filename | [
"gets",
"the",
"number",
"of",
"lines",
"from",
"filename"
] | def number_of_lines(filename=""):
with open(filename, encoding='utf-8') as myFile:
return sum([1 for line in myFile]) | [
"def",
"number_of_lines",
"(",
"filename",
"=",
"\"\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"myFile",
":",
"return",
"sum",
"(",
"[",
"1",
"for",
"line",
"in",
"myFile",
"]",
")"
] | gets the number of lines from filename | [
"gets",
"the",
"number",
"of",
"lines",
"from",
"filename"
] | [
"\"\"\"gets the number of lines from filename\n \"\"\""
] | [
{
"param": "filename",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def number_of_lines(filename=""):
with open(filename, encoding='utf-8') as myFile:
return sum([1 for line in myFile]) | 610,403 | 389 |
d4ed4bc4191a35a42387fbf8a7c93bbc6b9905b2 | screw-pack/Plumbit | plumbit.py | [
"MIT"
] | Python | add | <not_specific> | def add(circuit, current):
"""Ajoute le tuyau courant au circuit"""
for pipe in circuit:
if pipe.rect.topleft == current.rect.topleft:
circuit.remove(pipe)
circuit.append(current)
return circuit | Ajoute le tuyau courant au circuit | Ajoute le tuyau courant au circuit | [
"Ajoute",
"le",
"tuyau",
"courant",
"au",
"circuit"
] | def add(circuit, current):
for pipe in circuit:
if pipe.rect.topleft == current.rect.topleft:
circuit.remove(pipe)
circuit.append(current)
return circuit | [
"def",
"add",
"(",
"circuit",
",",
"current",
")",
":",
"for",
"pipe",
"in",
"circuit",
":",
"if",
"pipe",
".",
"rect",
".",
"topleft",
"==",
"current",
".",
"rect",
".",
"topleft",
":",
"circuit",
".",
"remove",
"(",
"pipe",
")",
"circuit",
".",
"append",
"(",
"current",
")",
"return",
"circuit"
] | Ajoute le tuyau courant au circuit | [
"Ajoute",
"le",
"tuyau",
"courant",
"au",
"circuit"
] | [
"\"\"\"Ajoute le tuyau courant au circuit\"\"\""
] | [
{
"param": "circuit",
"type": null
},
{
"param": "current",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "circuit",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "current",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def add(circuit, current):
for pipe in circuit:
if pipe.rect.topleft == current.rect.topleft:
circuit.remove(pipe)
circuit.append(current)
return circuit | 610,404 | 702 |
339e15552a0da69107e346603283d35cfe72ee68 | fandulu/MPLT | utils.py | [
"MIT"
] | Python | rotate | <not_specific> | def rotate(point, angle):
"""
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
"""
ox, oy = 0, 0
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy |
Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians.
| Rotate a point counterclockwise by a given angle around a given origin.
The angle should be given in radians. | [
"Rotate",
"a",
"point",
"counterclockwise",
"by",
"a",
"given",
"angle",
"around",
"a",
"given",
"origin",
".",
"The",
"angle",
"should",
"be",
"given",
"in",
"radians",
"."
] | def rotate(point, angle):
ox, oy = 0, 0
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy | [
"def",
"rotate",
"(",
"point",
",",
"angle",
")",
":",
"ox",
",",
"oy",
"=",
"0",
",",
"0",
"px",
",",
"py",
"=",
"point",
"qx",
"=",
"ox",
"+",
"math",
".",
"cos",
"(",
"angle",
")",
"*",
"(",
"px",
"-",
"ox",
")",
"-",
"math",
".",
"sin",
"(",
"angle",
")",
"*",
"(",
"py",
"-",
"oy",
")",
"qy",
"=",
"oy",
"+",
"math",
".",
"sin",
"(",
"angle",
")",
"*",
"(",
"px",
"-",
"ox",
")",
"+",
"math",
".",
"cos",
"(",
"angle",
")",
"*",
"(",
"py",
"-",
"oy",
")",
"return",
"qx",
",",
"qy"
] | Rotate a point counterclockwise by a given angle around a given origin. | [
"Rotate",
"a",
"point",
"counterclockwise",
"by",
"a",
"given",
"angle",
"around",
"a",
"given",
"origin",
"."
] | [
"\"\"\"\n Rotate a point counterclockwise by a given angle around a given origin.\n\n The angle should be given in radians.\n \"\"\""
] | [
{
"param": "point",
"type": null
},
{
"param": "angle",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "point",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "angle",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import math
def rotate(point, angle):
ox, oy = 0, 0
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy | 610,405 | 805 |
1f3993bf85cd6d42600fc6b8e82db0bd3ecf0425 | GoogleCloudPlatform/deactivate_tunnel | deactivate_tunnel.py | [
"Apache-2.0"
] | Python | delete_route | <not_specific> | def delete_route(compute, project, route):
""" Deletes an existing route asynchronously."""
route_deleted = compute.routes().delete(project=project,
route=route).execute()
return route_deleted | Deletes an existing route asynchronously. | Deletes an existing route asynchronously. | [
"Deletes",
"an",
"existing",
"route",
"asynchronously",
"."
] | def delete_route(compute, project, route):
route_deleted = compute.routes().delete(project=project,
route=route).execute()
return route_deleted | [
"def",
"delete_route",
"(",
"compute",
",",
"project",
",",
"route",
")",
":",
"route_deleted",
"=",
"compute",
".",
"routes",
"(",
")",
".",
"delete",
"(",
"project",
"=",
"project",
",",
"route",
"=",
"route",
")",
".",
"execute",
"(",
")",
"return",
"route_deleted"
] | Deletes an existing route asynchronously. | [
"Deletes",
"an",
"existing",
"route",
"asynchronously",
"."
] | [
"\"\"\" Deletes an existing route asynchronously.\"\"\""
] | [
{
"param": "compute",
"type": null
},
{
"param": "project",
"type": null
},
{
"param": "route",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "compute",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "project",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "route",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | def delete_route(compute, project, route):
route_deleted = compute.routes().delete(project=project,
route=route).execute()
return route_deleted | 610,406 | 607 |
59e111f6833d68afa0c40e04d48fc2a6407b091c | frictionlessdata/data-quality-cli | data_quality/utilities.py | [
"MIT"
] | Python | resolve_dir_name | <not_specific> | def resolve_dir_name(config_filepath, dir_path):
"""Create an absolute path from the file path and the path given in the config"""
if not os.path.isabs(dir_path):
config_path = os.path.abspath(os.path.dirname(config_filepath))
return os.path.join(config_path, dir_path)
else:
return dir_path | Create an absolute path from the file path and the path given in the config | Create an absolute path from the file path and the path given in the config | [
"Create",
"an",
"absolute",
"path",
"from",
"the",
"file",
"path",
"and",
"the",
"path",
"given",
"in",
"the",
"config"
] | def resolve_dir_name(config_filepath, dir_path):
if not os.path.isabs(dir_path):
config_path = os.path.abspath(os.path.dirname(config_filepath))
return os.path.join(config_path, dir_path)
else:
return dir_path | [
"def",
"resolve_dir_name",
"(",
"config_filepath",
",",
"dir_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"dir_path",
")",
":",
"config_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_filepath",
")",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"config_path",
",",
"dir_path",
")",
"else",
":",
"return",
"dir_path"
] | Create an absolute path from the file path and the path given in the config | [
"Create",
"an",
"absolute",
"path",
"from",
"the",
"file",
"path",
"and",
"the",
"path",
"given",
"in",
"the",
"config"
] | [
"\"\"\"Create an absolute path from the file path and the path given in the config\"\"\""
] | [
{
"param": "config_filepath",
"type": null
},
{
"param": "dir_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config_filepath",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dir_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} | import os
def resolve_dir_name(config_filepath, dir_path):
if not os.path.isabs(dir_path):
config_path = os.path.abspath(os.path.dirname(config_filepath))
return os.path.join(config_path, dir_path)
else:
return dir_path | 610,407 | 830 |