repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
alex-kostirin/pyatomac | atomac/ldtpd/combo_box.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/combo_box.py#L260-L284 | def verifydropdown(self, window_name, object_name):
"""
Verify drop down list / menu poped up
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type i... | [
"def",
"verifydropdown",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"object_handle",
"=",
"self",
".",
"_get_object_handle",
"(",
"window_name",
",",
"object_name",
")",
"if",
"not",
"object_handle",
".",
"AXEnabled",
"or",
"not... | Verify drop down list / menu poped up
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
... | [
"Verify",
"drop",
"down",
"list",
"/",
"menu",
"poped",
"up",
"@param",
"window_name",
":",
"Window",
"name",
"to",
"type",
"in",
"either",
"full",
"name",
"LDTP",
"s",
"name",
"convention",
"or",
"a",
"Unix",
"glob",
".",
"@type",
"window_name",
":",
"s... | python | valid |
hazelcast/hazelcast-python-client | hazelcast/proxy/transactional_set.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/transactional_set.py#L11-L19 | def add(self, item):
"""
Transactional implementation of :func:`Set.add(item) <hazelcast.proxy.set.Set.add>`
:param item: (object), the new item to be added.
:return: (bool), ``true`` if item is added successfully, ``false`` otherwise.
"""
check_not_none(item, "item can'... | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"item can't be none\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"transactional_set_add_codec",
",",
"item",
"=",
"self",
".",
"_to_data",
"(",
"item",
")",
")"... | Transactional implementation of :func:`Set.add(item) <hazelcast.proxy.set.Set.add>`
:param item: (object), the new item to be added.
:return: (bool), ``true`` if item is added successfully, ``false`` otherwise. | [
"Transactional",
"implementation",
"of",
":",
"func",
":",
"Set",
".",
"add",
"(",
"item",
")",
"<hazelcast",
".",
"proxy",
".",
"set",
".",
"Set",
".",
"add",
">"
] | python | train |
daviddrysdale/python-phonenumbers | python/phonenumbers/phonenumberutil.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L836-L846 | def _desc_has_data(desc):
"""Returns true if there is any data set for a particular PhoneNumberDesc."""
if desc is None:
return False
# Checking most properties since we don't know what's present, since a custom build may have
# stripped just one of them (e.g. liteBuild strips exampleNumber). We... | [
"def",
"_desc_has_data",
"(",
"desc",
")",
":",
"if",
"desc",
"is",
"None",
":",
"return",
"False",
"# Checking most properties since we don't know what's present, since a custom build may have",
"# stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking... | Returns true if there is any data set for a particular PhoneNumberDesc. | [
"Returns",
"true",
"if",
"there",
"is",
"any",
"data",
"set",
"for",
"a",
"particular",
"PhoneNumberDesc",
"."
] | python | train |
andreikop/qutepart | qutepart/__init__.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L1329-L1336 | def _onShortcutSelectAndScroll(self, down):
"""Ctrl+Shift+Up/Down pressed.
Select line and scroll viewport
"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.Down if down else QTextCursor.Up, QTextCursor.KeepAnchor)
self.setTextCursor(cursor)
self._onS... | [
"def",
"_onShortcutSelectAndScroll",
"(",
"self",
",",
"down",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"Down",
"if",
"down",
"else",
"QTextCursor",
".",
"Up",
",",
"QTextCursor",
... | Ctrl+Shift+Up/Down pressed.
Select line and scroll viewport | [
"Ctrl",
"+",
"Shift",
"+",
"Up",
"/",
"Down",
"pressed",
".",
"Select",
"line",
"and",
"scroll",
"viewport"
] | python | train |
valsaven/md5hash | md5hash/md5hash.py | https://github.com/valsaven/md5hash/blob/83208769a8e9c74bd9e4ce72ac1df00615af82f2/md5hash/md5hash.py#L70-L93 | def scan(tree):
"""Scan the directory and send the obtained tuple to calculate.
:param tree: path to file or directory"""
tree = os.path.normpath(tree)
assert os.path.exists(tree), "#Error. The path '{}' is" \
" invalid or doesn't exist.".format(str(tree))
... | [
"def",
"scan",
"(",
"tree",
")",
":",
"tree",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"tree",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"tree",
")",
",",
"\"#Error. The path '{}' is\"",
"\" invalid or doesn't exist.\"",
".",
"format",
"("... | Scan the directory and send the obtained tuple to calculate.
:param tree: path to file or directory | [
"Scan",
"the",
"directory",
"and",
"send",
"the",
"obtained",
"tuple",
"to",
"calculate",
".",
":",
"param",
"tree",
":",
"path",
"to",
"file",
"or",
"directory"
] | python | test |
sdispater/eloquent | eloquent/query/builder.py | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1400-L1413 | def merge_wheres(self, wheres, bindings):
"""
Merge a list of where clauses and bindings
:param wheres: A list of where clauses
:type wheres: list
:param bindings: A list of bindings
:type bindings: list
:rtype: None
"""
self.wheres = self.where... | [
"def",
"merge_wheres",
"(",
"self",
",",
"wheres",
",",
"bindings",
")",
":",
"self",
".",
"wheres",
"=",
"self",
".",
"wheres",
"+",
"wheres",
"self",
".",
"_bindings",
"[",
"'where'",
"]",
"=",
"self",
".",
"_bindings",
"[",
"'where'",
"]",
"+",
"b... | Merge a list of where clauses and bindings
:param wheres: A list of where clauses
:type wheres: list
:param bindings: A list of bindings
:type bindings: list
:rtype: None | [
"Merge",
"a",
"list",
"of",
"where",
"clauses",
"and",
"bindings"
] | python | train |
Spirent/py-stcrestclient | stcrestclient/stchttp.py | https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L492-L514 | def connect(self, chassis_list):
"""Establish connection to one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names)
Return:
List of chassis addresses.
"""
self._check_session()
if not isinstance(chassis_list, (list, t... | [
"def",
"connect",
"(",
"self",
",",
"chassis_list",
")",
":",
"self",
".",
"_check_session",
"(",
")",
"if",
"not",
"isinstance",
"(",
"chassis_list",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"dict",
",",
"frozenset",
")",
")",
":",
"chassis_li... | Establish connection to one or more chassis.
Arguments:
chassis_list -- List of chassis (IP addresses or DNS names)
Return:
List of chassis addresses. | [
"Establish",
"connection",
"to",
"one",
"or",
"more",
"chassis",
"."
] | python | train |
saschpe/rapport | rapport/timeframe.py | https://github.com/saschpe/rapport/blob/ccceb8f84bd7e8add88ab5e137cdab6424aa4683/rapport/timeframe.py#L31-L34 | def iso_to_gregorian(iso_year, iso_week, iso_day):
"Gregorian calendar date for the given ISO year, week and day"
year_start = iso_year_start(iso_year)
return year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1) | [
"def",
"iso_to_gregorian",
"(",
"iso_year",
",",
"iso_week",
",",
"iso_day",
")",
":",
"year_start",
"=",
"iso_year_start",
"(",
"iso_year",
")",
"return",
"year_start",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"iso_day",
"-",
"1",
",",
"weeks",
... | Gregorian calendar date for the given ISO year, week and day | [
"Gregorian",
"calendar",
"date",
"for",
"the",
"given",
"ISO",
"year",
"week",
"and",
"day"
] | python | train |
iterative/dvc | dvc/scm/git/tree.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/git/tree.py#L126-L139 | def walk(self, top, topdown=True, ignore_file_handler=None):
"""Directory tree generator.
See `os.walk` for the docs. Differences:
- no support for symlinks
- it could raise exceptions, there is no onerror argument
"""
tree = self.git_object_by_path(top)
if tree... | [
"def",
"walk",
"(",
"self",
",",
"top",
",",
"topdown",
"=",
"True",
",",
"ignore_file_handler",
"=",
"None",
")",
":",
"tree",
"=",
"self",
".",
"git_object_by_path",
"(",
"top",
")",
"if",
"tree",
"is",
"None",
":",
"raise",
"IOError",
"(",
"errno",
... | Directory tree generator.
See `os.walk` for the docs. Differences:
- no support for symlinks
- it could raise exceptions, there is no onerror argument | [
"Directory",
"tree",
"generator",
"."
] | python | train |
ranaroussi/pywallet | pywallet/utils/bip32.py | https://github.com/ranaroussi/pywallet/blob/206ff224389c490d8798f660c9e79fe97ebb64cf/pywallet/utils/bip32.py#L190-L249 | def get_child_for_path(self, path):
"""Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or,... | [
"def",
"get_child_for_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"ensure_str",
"(",
"path",
")",
"if",
"not",
"path",
":",
"raise",
"InvalidPathError",
"(",
"\"%s is not a valid path\"",
"%",
"path",
")",
"# Figure out public/private derivation",
"as_... | Get a child for a given path.
Rather than repeated calls to get_child, children can be found
by a derivation path. Paths look like:
m/0/1'/10
Which is the same as
self.get_child(0).get_child(-1).get_child(10)
Or, in other words, the 10th publicly derived chil... | [
"Get",
"a",
"child",
"for",
"a",
"given",
"path",
"."
] | python | train |
Nic30/ipCorePackager | ipCorePackager/packager.py | https://github.com/Nic30/ipCorePackager/blob/0af4e56ebfdc3749fffa40d50d9ccbf8b5445881/ipCorePackager/packager.py#L194-L202 | def getTypeWidth(self, dtype: "HdlType", do_eval=False) -> Tuple[int, str, bool]:
"""
:return: tuple (current value of width,
string of value (can be ID or int),
Flag which specifies if width of signal is locked
or can be changed by parameter)
"""
rais... | [
"def",
"getTypeWidth",
"(",
"self",
",",
"dtype",
":",
"\"HdlType\"",
",",
"do_eval",
"=",
"False",
")",
"->",
"Tuple",
"[",
"int",
",",
"str",
",",
"bool",
"]",
":",
"raise",
"NotImplementedError",
"(",
"\"Implement this method in your HdlType classes\"",
")"
] | :return: tuple (current value of width,
string of value (can be ID or int),
Flag which specifies if width of signal is locked
or can be changed by parameter) | [
":",
"return",
":",
"tuple",
"(",
"current",
"value",
"of",
"width",
"string",
"of",
"value",
"(",
"can",
"be",
"ID",
"or",
"int",
")",
"Flag",
"which",
"specifies",
"if",
"width",
"of",
"signal",
"is",
"locked",
"or",
"can",
"be",
"changed",
"by",
"... | python | train |
Ex-Mente/auxi.0 | auxi/modelling/process/materials/thermo.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/process/materials/thermo.py#L1513-L1522 | def Hfr(self, Hfr):
"""
Set the enthalpy flow rate of the stream to the specified value, and
recalculate it's temperature.
:param H: The new enthalpy flow rate value. [kWh/h]
"""
self._Hfr = Hfr
self._T = self._calculate_T(Hfr) | [
"def",
"Hfr",
"(",
"self",
",",
"Hfr",
")",
":",
"self",
".",
"_Hfr",
"=",
"Hfr",
"self",
".",
"_T",
"=",
"self",
".",
"_calculate_T",
"(",
"Hfr",
")"
] | Set the enthalpy flow rate of the stream to the specified value, and
recalculate it's temperature.
:param H: The new enthalpy flow rate value. [kWh/h] | [
"Set",
"the",
"enthalpy",
"flow",
"rate",
"of",
"the",
"stream",
"to",
"the",
"specified",
"value",
"and",
"recalculate",
"it",
"s",
"temperature",
"."
] | python | valid |
loli/medpy | medpy/metric/histogram.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/medpy/metric/histogram.py#L117-L126 | def manhattan(h1, h2): # # 7 us @array, 31 us @list \w 100 bins
r"""
Equal to Minowski distance with :math:`p=1`.
See also
--------
minowski
"""
h1, h2 = __prepare_histogram(h1, h2)
return scipy.sum(scipy.absolute(h1 - h2)) | [
"def",
"manhattan",
"(",
"h1",
",",
"h2",
")",
":",
"# # 7 us @array, 31 us @list \\w 100 bins",
"h1",
",",
"h2",
"=",
"__prepare_histogram",
"(",
"h1",
",",
"h2",
")",
"return",
"scipy",
".",
"sum",
"(",
"scipy",
".",
"absolute",
"(",
"h1",
"-",
"h2",
"... | r"""
Equal to Minowski distance with :math:`p=1`.
See also
--------
minowski | [
"r",
"Equal",
"to",
"Minowski",
"distance",
"with",
":",
"math",
":",
"p",
"=",
"1",
".",
"See",
"also",
"--------",
"minowski"
] | python | train |
spyder-ide/spyder | spyder/plugins/console/widgets/internalshell.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/widgets/internalshell.py#L373-L384 | def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
... | [
"def",
"execute_lines",
"(",
"self",
",",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
".",
"splitlines",
"(",
")",
":",
"stripped_line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"stripped_line",
".",
"startswith",
"(",
"'#'",
")",
":",
"continue... | Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands | [
"Execute",
"a",
"set",
"of",
"lines",
"as",
"multiple",
"command",
"lines",
":",
"multiple",
"lines",
"of",
"text",
"to",
"be",
"executed",
"as",
"single",
"commands"
] | python | train |
rbarrois/mpdlcd | mpdlcd/vendor/lcdproc/screen.py | https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L129-L134 | def clear(self):
""" Clear Screen """
widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1)
widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2)
widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3)
widgets.StringWidget(self, ref="_w4_", text=" " * ... | [
"def",
"clear",
"(",
"self",
")",
":",
"widgets",
".",
"StringWidget",
"(",
"self",
",",
"ref",
"=",
"\"_w1_\"",
",",
"text",
"=",
"\" \"",
"*",
"20",
",",
"x",
"=",
"1",
",",
"y",
"=",
"1",
")",
"widgets",
".",
"StringWidget",
"(",
"self",
",",
... | Clear Screen | [
"Clear",
"Screen"
] | python | train |
bioasp/caspo | caspo/core/logicalnetwork.py | https://github.com/bioasp/caspo/blob/a68d1eace75b9b08f23633d1fb5ce6134403959e/caspo/core/logicalnetwork.py#L754-L764 | def formulas_iter(self):
"""
Iterates over all variable-clauses in the logical network
Yields
------
tuple[str,frozenset[caspo.core.clause.Clause]]
The next tuple of the form (variable, set of clauses) in the logical network.
"""
for var in it.ifilter... | [
"def",
"formulas_iter",
"(",
"self",
")",
":",
"for",
"var",
"in",
"it",
".",
"ifilter",
"(",
"self",
".",
"has_node",
",",
"self",
".",
"variables",
"(",
")",
")",
":",
"yield",
"var",
",",
"frozenset",
"(",
"self",
".",
"predecessors",
"(",
"var",
... | Iterates over all variable-clauses in the logical network
Yields
------
tuple[str,frozenset[caspo.core.clause.Clause]]
The next tuple of the form (variable, set of clauses) in the logical network. | [
"Iterates",
"over",
"all",
"variable",
"-",
"clauses",
"in",
"the",
"logical",
"network"
] | python | train |
BD2KGenomics/toil-scripts | src/toil_scripts/spladder_pipeline/spladder_pipeline.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/spladder_pipeline/spladder_pipeline.py#L337-L376 | def consolidate_output_tarballs(job, inputs, vcqc_id, spladder_id):
"""
Combine the contents of separate tarballs into one.
:param JobFunctionWrappingJob job: passed by Toil automatically
:param Namespace inputs: Stores input arguments (see main)
:param str vcqc_id: FileStore ID of variant calling ... | [
"def",
"consolidate_output_tarballs",
"(",
"job",
",",
"inputs",
",",
"vcqc_id",
",",
"spladder_id",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Consolidating files and uploading: {}'",
".",
"format",
"(",
"inputs",
".",
"uuid",
")",
")",
"work... | Combine the contents of separate tarballs into one.
:param JobFunctionWrappingJob job: passed by Toil automatically
:param Namespace inputs: Stores input arguments (see main)
:param str vcqc_id: FileStore ID of variant calling and QC tarball
:param str spladder_id: FileStore ID of spladder tarball | [
"Combine",
"the",
"contents",
"of",
"separate",
"tarballs",
"into",
"one",
"."
] | python | train |
senaite/senaite.core | bika/lims/content/instrumentscheduledtask.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/instrumentscheduledtask.py#L110-L121 | def getTaskTypes(self):
""" Return the current list of task types
"""
types = [
('Calibration', safe_unicode(_('Calibration')).encode('utf-8')),
('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')),
('Preventive', safe_unicode(_('Preventive')).encod... | [
"def",
"getTaskTypes",
"(",
"self",
")",
":",
"types",
"=",
"[",
"(",
"'Calibration'",
",",
"safe_unicode",
"(",
"_",
"(",
"'Calibration'",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"(",
"'Enhancement'",
",",
"safe_unicode",
"(",
"_",
"("... | Return the current list of task types | [
"Return",
"the",
"current",
"list",
"of",
"task",
"types"
] | python | train |
mbedmicro/pyOCD | pyocd/flash/flash_builder.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash_builder.py#L767-L805 | def _scan_pages_for_same(self, progress_cb=_stub_progress):
"""! @brief Read the full page data to determine if it is unchanged.
When this function exits, the same flag will be set to either True or False for
every page. In addition, sectors that need at least one page programmed will h... | [
"def",
"_scan_pages_for_same",
"(",
"self",
",",
"progress_cb",
"=",
"_stub_progress",
")",
":",
"progress",
"=",
"0",
"# Read page data if unknown - after this page.same will be True or False",
"unknown_pages",
"=",
"[",
"page",
"for",
"page",
"in",
"self",
".",
"page_... | ! @brief Read the full page data to determine if it is unchanged.
When this function exits, the same flag will be set to either True or False for
every page. In addition, sectors that need at least one page programmed will have
the same flag set to False for all pages within that sector... | [
"!"
] | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L8609-L8743 | def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
errors='raise', try_cast=False):
"""
Equivalent to public method `where`, except that `other` is not
applied as a function even if callable. Used in __setitem__.
"""
inplace = validate_bool_... | [
"def",
"_where",
"(",
"self",
",",
"cond",
",",
"other",
"=",
"np",
".",
"nan",
",",
"inplace",
"=",
"False",
",",
"axis",
"=",
"None",
",",
"level",
"=",
"None",
",",
"errors",
"=",
"'raise'",
",",
"try_cast",
"=",
"False",
")",
":",
"inplace",
... | Equivalent to public method `where`, except that `other` is not
applied as a function even if callable. Used in __setitem__. | [
"Equivalent",
"to",
"public",
"method",
"where",
"except",
"that",
"other",
"is",
"not",
"applied",
"as",
"a",
"function",
"even",
"if",
"callable",
".",
"Used",
"in",
"__setitem__",
"."
] | python | train |
onjin/runenv | runenv/__init__.py | https://github.com/onjin/runenv/blob/1a1d31bc2d20a48e3c251d8e490bbad485b09e1c/runenv/__init__.py#L17-L41 | def run(*args):
"""Load given `envfile` and run `command` with `params`"""
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ['_RUNENV_WRAPPED'] = '1'
runna... | [
"def",
"run",
"(",
"*",
"args",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"print",
"(",
"'Usage: runenv <envfile> <command> <params>'",
")",
"sys",
".",
"e... | Load given `envfile` and run `command` with `params` | [
"Load",
"given",
"envfile",
"and",
"run",
"command",
"with",
"params"
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/_es2.py#L88-L100 | def glBufferData(target, data, usage):
""" Data can be numpy array or the size of data to allocate.
"""
if isinstance(data, int):
size = data
data = ctypes.c_voidp(0)
else:
if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
data = data.copy('C')
d... | [
"def",
"glBufferData",
"(",
"target",
",",
"data",
",",
"usage",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"size",
"=",
"data",
"data",
"=",
"ctypes",
".",
"c_voidp",
"(",
"0",
")",
"else",
":",
"if",
"not",
"data",
".",
"f... | Data can be numpy array or the size of data to allocate. | [
"Data",
"can",
"be",
"numpy",
"array",
"or",
"the",
"size",
"of",
"data",
"to",
"allocate",
"."
] | python | train |
pandas-dev/pandas | pandas/core/indexes/base.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexes/base.py#L1402-L1420 | def _validate_index_level(self, level):
"""
Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex.
"""
if isinstance(level, int):
if level < 0 and level != -1:
rais... | [
"def",
"_validate_index_level",
"(",
"self",
",",
"level",
")",
":",
"if",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"if",
"level",
"<",
"0",
"and",
"level",
"!=",
"-",
"1",
":",
"raise",
"IndexError",
"(",
"\"Too many levels: Index has only 1 level,... | Validate index level.
For single-level Index getting level number is a no-op, but some
verification must be done like in MultiIndex. | [
"Validate",
"index",
"level",
"."
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1543-L1547 | def help_center_article_translation_show(self, article_id, locale, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#show-translation"
api_path = "/api/v2/help_center/articles/{article_id}/translations/{locale}.json"
api_path = api_path.format(article_id=article_id... | [
"def",
"help_center_article_translation_show",
"(",
"self",
",",
"article_id",
",",
"locale",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/articles/{article_id}/translations/{locale}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
... | https://developer.zendesk.com/rest_api/docs/help_center/translations#show-translation | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"help_center",
"/",
"translations#show",
"-",
"translation"
] | python | train |
sffjunkie/astral | src/astral.py | https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L2213-L2252 | def time_at_elevation_utc(self, elevation, direction, date, latitude, longitude, observer_elevation=0):
"""Calculate the time in the UTC timezone when the sun is at
the specified elevation on the specified date.
Note: This method uses positive elevations for those above the horizon.
:p... | [
"def",
"time_at_elevation_utc",
"(",
"self",
",",
"elevation",
",",
"direction",
",",
"date",
",",
"latitude",
",",
"longitude",
",",
"observer_elevation",
"=",
"0",
")",
":",
"if",
"elevation",
">",
"90.0",
":",
"elevation",
"=",
"180.0",
"-",
"elevation",
... | Calculate the time in the UTC timezone when the sun is at
the specified elevation on the specified date.
Note: This method uses positive elevations for those above the horizon.
:param elevation: Elevation in degrees above the horizon to calculate for.
:type elevation: float
... | [
"Calculate",
"the",
"time",
"in",
"the",
"UTC",
"timezone",
"when",
"the",
"sun",
"is",
"at",
"the",
"specified",
"elevation",
"on",
"the",
"specified",
"date",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/bindings/dxfile_functions.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxfile_functions.py#L621-L708 | def download_folder(project, destdir, folder="/", overwrite=False, chunksize=dxfile.DEFAULT_BUFFER_SIZE,
show_progress=False, **kwargs):
'''
:param project: Project ID to use as context for this download.
:type project: string
:param destdir: Local destination location
:type dest... | [
"def",
"download_folder",
"(",
"project",
",",
"destdir",
",",
"folder",
"=",
"\"/\"",
",",
"overwrite",
"=",
"False",
",",
"chunksize",
"=",
"dxfile",
".",
"DEFAULT_BUFFER_SIZE",
",",
"show_progress",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"def"... | :param project: Project ID to use as context for this download.
:type project: string
:param destdir: Local destination location
:type destdir: string
:param folder: Path to the remote folder to download
:type folder: string
:param overwrite: Overwrite existing files
:type overwrite: boolean... | [
":",
"param",
"project",
":",
"Project",
"ID",
"to",
"use",
"as",
"context",
"for",
"this",
"download",
".",
":",
"type",
"project",
":",
"string",
":",
"param",
"destdir",
":",
"Local",
"destination",
"location",
":",
"type",
"destdir",
":",
"string",
"... | python | train |
bokeh/bokeh | bokeh/io/notebook.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L433-L501 | def show_app(app, state, notebook_url, port=0, **kw):
''' Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_... | [
"def",
"show_app",
"(",
"app",
",",
"state",
",",
"notebook_url",
",",
"port",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"logging",
".",
"basicConfig",
"(",
")",
"from",
"tornado",
".",
"ioloop",
"import",
"IOLoop",
"from",
".",
".",
"server",
".",
... | Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook se... | [
"Embed",
"a",
"Bokeh",
"server",
"application",
"in",
"a",
"Jupyter",
"Notebook",
"output",
"cell",
"."
] | python | train |
Karaage-Cluster/python-tldap | tldap/fields.py | https://github.com/Karaage-Cluster/python-tldap/blob/61f1af74a3648cb6491e7eeb1ee2eb395d67bf59/tldap/fields.py#L316-L326 | def value_to_db(self, value):
""" Returns field's single value prepared for saving into a database. """
assert isinstance(value, datetime.date)
assert not isinstance(value, datetime.datetime)
try:
value = value - datetime.date(year=1970, month=1, day=1)
except Overfl... | [
"def",
"value_to_db",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
"assert",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
"try",
":",
"value",
"=",
"value",
"... | Returns field's single value prepared for saving into a database. | [
"Returns",
"field",
"s",
"single",
"value",
"prepared",
"for",
"saving",
"into",
"a",
"database",
"."
] | python | train |
pyout/pyout | pyout/elements.py | https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/elements.py#L241-L265 | def validate(style):
"""Check `style` against pyout.styling.schema.
Parameters
----------
style : dict
Style object to validate.
Raises
------
StyleValidationError if `style` is not valid.
"""
try:
import jsonschema
except ImportError:
return
try:
... | [
"def",
"validate",
"(",
"style",
")",
":",
"try",
":",
"import",
"jsonschema",
"except",
"ImportError",
":",
"return",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"style",
",",
"schema",
")",
"except",
"jsonschema",
".",
"ValidationError",
"as",
"exc",
... | Check `style` against pyout.styling.schema.
Parameters
----------
style : dict
Style object to validate.
Raises
------
StyleValidationError if `style` is not valid. | [
"Check",
"style",
"against",
"pyout",
".",
"styling",
".",
"schema",
"."
] | python | train |
projectatomic/atomic-reactor | atomic_reactor/plugins/input_path.py | https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/input_path.py#L32-L47 | def run(self):
"""
get json with build config from path
"""
path = self.path or CONTAINER_BUILD_JSON_PATH
try:
with open(path, 'r') as build_cfg_fd:
build_cfg_json = json.load(build_cfg_fd)
except ValueError:
self.log.error("couldn'... | [
"def",
"run",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"path",
"or",
"CONTAINER_BUILD_JSON_PATH",
"try",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"build_cfg_fd",
":",
"build_cfg_json",
"=",
"json",
".",
"load",
"(",
"build_cfg_fd"... | get json with build config from path | [
"get",
"json",
"with",
"build",
"config",
"from",
"path"
] | python | train |
rigetti/quantumflow | quantumflow/states.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/states.py#L329-L345 | def random_density(qubits: Union[int, Qubits]) -> Density:
"""
Returns: A randomly sampled Density from the Hilbert–Schmidt
ensemble of quantum states
Ref: "Induced measures in the space of mixed quantum states" Karol
Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001)
... | [
"def",
"random_density",
"(",
"qubits",
":",
"Union",
"[",
"int",
",",
"Qubits",
"]",
")",
"->",
"Density",
":",
"N",
",",
"qubits",
"=",
"qubits_count_tuple",
"(",
"qubits",
")",
"size",
"=",
"(",
"2",
"**",
"N",
",",
"2",
"**",
"N",
")",
"ginibre... | Returns: A randomly sampled Density from the Hilbert–Schmidt
ensemble of quantum states
Ref: "Induced measures in the space of mixed quantum states" Karol
Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001)
https://arxiv.org/abs/quant-ph/0012101 | [
"Returns",
":",
"A",
"randomly",
"sampled",
"Density",
"from",
"the",
"Hilbert–Schmidt",
"ensemble",
"of",
"quantum",
"states"
] | python | train |
DataBiosphere/dsub | dsub/providers/google_v2_operations.py | https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/providers/google_v2_operations.py#L167-L179 | def get_last_update(op):
"""Return the most recent timestamp in the operation."""
last_update = get_end_time(op)
if not last_update:
last_event = get_last_event(op)
if last_event:
last_update = last_event['timestamp']
if not last_update:
last_update = get_create_time(op)
return last_updat... | [
"def",
"get_last_update",
"(",
"op",
")",
":",
"last_update",
"=",
"get_end_time",
"(",
"op",
")",
"if",
"not",
"last_update",
":",
"last_event",
"=",
"get_last_event",
"(",
"op",
")",
"if",
"last_event",
":",
"last_update",
"=",
"last_event",
"[",
"'timesta... | Return the most recent timestamp in the operation. | [
"Return",
"the",
"most",
"recent",
"timestamp",
"in",
"the",
"operation",
"."
] | python | valid |
log2timeline/plaso | plaso/engine/profilers.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/profilers.py#L125-L138 | def StopTiming(self, profile_name):
"""Stops timing CPU time.
Args:
profile_name (str): name of the profile to sample.
"""
measurements = self._profile_measurements.get(profile_name)
if measurements:
measurements.SampleStop()
sample = '{0:f}\t{1:s}\t{2:f}\n'.format(
mea... | [
"def",
"StopTiming",
"(",
"self",
",",
"profile_name",
")",
":",
"measurements",
"=",
"self",
".",
"_profile_measurements",
".",
"get",
"(",
"profile_name",
")",
"if",
"measurements",
":",
"measurements",
".",
"SampleStop",
"(",
")",
"sample",
"=",
"'{0:f}\\t{... | Stops timing CPU time.
Args:
profile_name (str): name of the profile to sample. | [
"Stops",
"timing",
"CPU",
"time",
"."
] | python | train |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cluster_info/display.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/display.py#L76-L121 | def display_replica_imbalance(cluster_topologies):
"""Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
assert cluster_topologies
rg_ids = list(next(six.itervalues(cluster_topo... | [
"def",
"display_replica_imbalance",
"(",
"cluster_topologies",
")",
":",
"assert",
"cluster_topologies",
"rg_ids",
"=",
"list",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"cluster_topologies",
")",
")",
".",
"rgs",
".",
"keys",
"(",
")",
")",
"assert",
... | Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | [
"Display",
"replica",
"replication",
"-",
"group",
"distribution",
"imbalance",
"statistics",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ntp.py#L109-L123 | def ntp_authentication_key_encryption_type_md5_type_md5(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
authentication_key = ET.SubElement(ntp, "authentication-key")
key... | [
"def",
"ntp_authentication_key_encryption_type_md5_type_md5",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ntp",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ntp\"",
",",
"xmlns",
"=",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
NASA-AMMOS/AIT-Core | ait/core/seq.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L150-L166 | def printText (self, stream=None):
"""Prints a text representation of this sequence to the given stream or
standard output.
"""
if stream is None:
stream = sys.stdout
stream.write('# seqid : %u\n' % self.seqid )
stream.write('# version : %u\n' % self.version )
... | [
"def",
"printText",
"(",
"self",
",",
"stream",
"=",
"None",
")",
":",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"sys",
".",
"stdout",
"stream",
".",
"write",
"(",
"'# seqid : %u\\n'",
"%",
"self",
".",
"seqid",
")",
"stream",
".",
"write",
... | Prints a text representation of this sequence to the given stream or
standard output. | [
"Prints",
"a",
"text",
"representation",
"of",
"this",
"sequence",
"to",
"the",
"given",
"stream",
"or",
"standard",
"output",
"."
] | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L757-L764 | def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cac... | [
"def",
"Match",
"(",
"pattern",
",",
"s",
")",
":",
"# The regexp compilation caching is inlined in both Match and Search for",
"# performance reasons; factoring it out into a separate function turns out",
"# to be noticeably expensive.",
"if",
"pattern",
"not",
"in",
"_regexp_compile_... | Matches the string with the pattern, caching the compiled regexp. | [
"Matches",
"the",
"string",
"with",
"the",
"pattern",
"caching",
"the",
"compiled",
"regexp",
"."
] | python | valid |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L176-L184 | def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s | [
"def",
"_create_socket",
"(",
"self",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
"=",
"ssl",
".",
"wrap_socket",
"(",
"s",
")",
"s",
".",
"connect",
"(",
"(",
"self",
"."... | Creates ssl socket, connects to stream api and
sets timeout. | [
"Creates",
"ssl",
"socket",
"connects",
"to",
"stream",
"api",
"and",
"sets",
"timeout",
"."
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/networking/logical_interconnects.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/logical_interconnects.py#L423-L435 | def create_forwarding_information_base(self, timeout=-1):
"""
Generates the forwarding information base dump file for a logical interconnect.
Args:
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
... | [
"def",
"create_forwarding_information_base",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"uri",
"=",
"\"{}{}\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
",",
"self",
".",
"FORWARDING_INFORMATION_PATH",
")",
"return",
"self",
... | Generates the forwarding information base dump file for a logical interconnect.
Args:
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in
OneView, just stops waiting for its completion.
Returns: Inter... | [
"Generates",
"the",
"forwarding",
"information",
"base",
"dump",
"file",
"for",
"a",
"logical",
"interconnect",
"."
] | python | train |
gabstopper/smc-python | smc/base/util.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/base/util.py#L71-L103 | def element_resolver(elements, do_raise=True):
"""
Element resolver takes either a single class instance
or a list of elements to resolve the href. It does
not assume a specific interface, instead if it's
a class, it just needs an 'href' attribute that should
hold the http url for the resource. ... | [
"def",
"element_resolver",
"(",
"elements",
",",
"do_raise",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"elements",
",",
"list",
")",
":",
"e",
"=",
"[",
"]",
"for",
"element",
"in",
"elements",
":",
"try",
":",
"e",
".",
"append",
"(",
"element... | Element resolver takes either a single class instance
or a list of elements to resolve the href. It does
not assume a specific interface, instead if it's
a class, it just needs an 'href' attribute that should
hold the http url for the resource. If a list is
provided, a list is returned. If you want ... | [
"Element",
"resolver",
"takes",
"either",
"a",
"single",
"class",
"instance",
"or",
"a",
"list",
"of",
"elements",
"to",
"resolve",
"the",
"href",
".",
"It",
"does",
"not",
"assume",
"a",
"specific",
"interface",
"instead",
"if",
"it",
"s",
"a",
"class",
... | python | train |
mitsei/dlkit | dlkit/records/assessment/mecqbank/mecqbank_base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/mecqbank/mecqbank_base_records.py#L449-L456 | def _init_metadata(self):
"""stub"""
SimpleDifficultyItemFormRecord._init_metadata(self)
SourceItemFormRecord._init_metadata(self)
PDFPreviewFormRecord._init_metadata(self)
PublishedFormRecord._init_metadata(self)
ProvenanceFormRecord._init_metadata(self)
super(Me... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"SimpleDifficultyItemFormRecord",
".",
"_init_metadata",
"(",
"self",
")",
"SourceItemFormRecord",
".",
"_init_metadata",
"(",
"self",
")",
"PDFPreviewFormRecord",
".",
"_init_metadata",
"(",
"self",
")",
"PublishedFormR... | stub | [
"stub"
] | python | train |
kellerza/pysma | pysma/__init__.py | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L209-L225 | def new_session(self):
"""Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
self.sma_sid = jmespath.search('result.sid', body)
if self.sma_sid:
return True
msg = 'Could not start session, %s, got {}'.format(body)
... | [
"def",
"new_session",
"(",
"self",
")",
":",
"body",
"=",
"yield",
"from",
"self",
".",
"_fetch_json",
"(",
"URL_LOGIN",
",",
"self",
".",
"_new_session_data",
")",
"self",
".",
"sma_sid",
"=",
"jmespath",
".",
"search",
"(",
"'result.sid'",
",",
"body",
... | Establish a new session. | [
"Establish",
"a",
"new",
"session",
"."
] | python | train |
saltstack/salt | salt/modules/mdadm_raid.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mdadm_raid.py#L174-L259 | def create(name,
level,
devices,
metadata='default',
test_mode=False,
**kwargs):
'''
Create a RAID device.
.. versionchanged:: 2014.7.0
.. warning::
Use with CAUTION, as this function can be very destructive if not used
properly!
... | [
"def",
"create",
"(",
"name",
",",
"level",
",",
"devices",
",",
"metadata",
"=",
"'default'",
",",
"test_mode",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"[",
"]",
"raid_devices",
"=",
"len",
"(",
"devices",
")",
"for",
"key",
... | Create a RAID device.
.. versionchanged:: 2014.7.0
.. warning::
Use with CAUTION, as this function can be very destructive if not used
properly!
CLI Examples:
.. code-block:: bash
salt '*' raid.create /dev/md0 level=1 chunk=256 devices="['/dev/xvdd', '/dev/xvde']" test_mode=... | [
"Create",
"a",
"RAID",
"device",
"."
] | python | train |
threeML/astromodels | astromodels/sources/particle_source.py | https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/sources/particle_source.py#L62-L68 | def get_flux(self, energies):
"""Get the total flux of this particle source at the given energies (summed over the components)"""
results = [component.shape(energies) for component in self.components.values()]
return numpy.sum(results, 0) | [
"def",
"get_flux",
"(",
"self",
",",
"energies",
")",
":",
"results",
"=",
"[",
"component",
".",
"shape",
"(",
"energies",
")",
"for",
"component",
"in",
"self",
".",
"components",
".",
"values",
"(",
")",
"]",
"return",
"numpy",
".",
"sum",
"(",
"r... | Get the total flux of this particle source at the given energies (summed over the components) | [
"Get",
"the",
"total",
"flux",
"of",
"this",
"particle",
"source",
"at",
"the",
"given",
"energies",
"(",
"summed",
"over",
"the",
"components",
")"
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L4612-L4634 | def holiday_day(self, value=None):
"""Corresponds to IDD Field `holiday_day`
Args:
value (str): value for IDD Field `holiday_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
... | [
"def",
"holiday_day",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type str ... | Corresponds to IDD Field `holiday_day`
Args:
value (str): value for IDD Field `holiday_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid val... | [
"Corresponds",
"to",
"IDD",
"Field",
"holiday_day"
] | python | train |
Qiskit/qiskit-terra | qiskit/quantum_info/operators/predicates.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/predicates.py#L74-L83 | def is_diagonal_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if an array is a diagonal matrix"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
mat = np.array(mat)
if mat.ndim != 2:
return False
return np.allclose(mat, np.diag(np.d... | [
"def",
"is_diagonal_matrix",
"(",
"mat",
",",
"rtol",
"=",
"RTOL_DEFAULT",
",",
"atol",
"=",
"ATOL_DEFAULT",
")",
":",
"if",
"atol",
"is",
"None",
":",
"atol",
"=",
"ATOL_DEFAULT",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"RTOL_DEFAULT",
"mat",
"=",... | Test if an array is a diagonal matrix | [
"Test",
"if",
"an",
"array",
"is",
"a",
"diagonal",
"matrix"
] | python | test |
satori-ng/hooker | hooker/hook_list.py | https://github.com/satori-ng/hooker/blob/8ef1fffe1537f06313799d1e5e6f7acc4ab405b4/hooker/hook_list.py#L103-L124 | def isloaded(self, name):
"""Checks if given hook module has been loaded
Args:
name (str): The name of the module to check
Returns:
bool. The return code::
True -- Loaded
False -- Not Loaded
"""
if name is None:
... | [
"def",
"isloaded",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"True",
"if",
"isinstance",
"(",
"name",
",",
"str",
")",
":",
"return",
"(",
"name",
"in",
"[",
"x",
".",
"__module__",
"for",
"x",
"in",
"self",
"... | Checks if given hook module has been loaded
Args:
name (str): The name of the module to check
Returns:
bool. The return code::
True -- Loaded
False -- Not Loaded | [
"Checks",
"if",
"given",
"hook",
"module",
"has",
"been",
"loaded"
] | python | train |
Azure/azure-cosmos-python | samples/IndexManagement/Program.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/samples/IndexManagement/Program.py#L171-L231 | def ExplicitlyExcludeFromIndex(client, database_id):
""" The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added.
There may be scenarios where you want to exclude a specific doc from the index even though all other
documents are being indexed automatically.
... | [
"def",
"ExplicitlyExcludeFromIndex",
"(",
"client",
",",
"database_id",
")",
":",
"try",
":",
"DeleteContainerIfExists",
"(",
"client",
",",
"database_id",
",",
"COLLECTION_ID",
")",
"database_link",
"=",
"GetDatabaseLink",
"(",
"database_id",
")",
"# collections = Qu... | The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added.
There may be scenarios where you want to exclude a specific doc from the index even though all other
documents are being indexed automatically.
This method demonstrates how to use an index directive t... | [
"The",
"default",
"index",
"policy",
"on",
"a",
"DocumentContainer",
"will",
"AUTOMATICALLY",
"index",
"ALL",
"documents",
"added",
".",
"There",
"may",
"be",
"scenarios",
"where",
"you",
"want",
"to",
"exclude",
"a",
"specific",
"doc",
"from",
"the",
"index",... | python | train |
andrea-cuttone/geoplotlib | geoplotlib/__init__.py | https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L263-L280 | def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True):
"""
Values on a uniform grid
:param lon_edges: longitude edges
:param lat_edges: latitude edges
:param values: matrix representing values on th... | [
"def",
"grid",
"(",
"lon_edges",
",",
"lat_edges",
",",
"values",
",",
"cmap",
",",
"alpha",
"=",
"255",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"levels",
"=",
"10",
",",
"colormap_scale",
"=",
"'lin'",
",",
"show_colorbar",
"=",
"Tr... | Values on a uniform grid
:param lon_edges: longitude edges
:param lat_edges: latitude edges
:param values: matrix representing values on the grid
:param cmap: colormap name
:param alpha: color alpha
:param vmin: minimum value for the colormap
:param vmax... | [
"Values",
"on",
"a",
"uniform",
"grid",
":",
"param",
"lon_edges",
":",
"longitude",
"edges",
":",
"param",
"lat_edges",
":",
"latitude",
"edges",
":",
"param",
"values",
":",
"matrix",
"representing",
"values",
"on",
"the",
"grid",
":",
"param",
"cmap",
"... | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/lib/mp_module.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/lib/mp_module.py#L170-L176 | def speed_convert_units(self, val_ms):
'''return a speed in configured units'''
if self.settings.speed_unit == 'knots':
return val_ms * 1.94384
elif self.settings.speed_unit == 'mph':
return val_ms * 2.23694
return val_ms | [
"def",
"speed_convert_units",
"(",
"self",
",",
"val_ms",
")",
":",
"if",
"self",
".",
"settings",
".",
"speed_unit",
"==",
"'knots'",
":",
"return",
"val_ms",
"*",
"1.94384",
"elif",
"self",
".",
"settings",
".",
"speed_unit",
"==",
"'mph'",
":",
"return"... | return a speed in configured units | [
"return",
"a",
"speed",
"in",
"configured",
"units"
] | python | train |
tensorflow/probability | tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L246-L368 | def model_fn(features, labels, mode, params, config):
"""Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionar... | [
"def",
"model_fn",
"(",
"features",
",",
"labels",
",",
"mode",
",",
"params",
",",
"config",
")",
":",
"del",
"labels",
",",
"config",
"# Set up the model's learnable parameters.",
"logit_concentration",
"=",
"tf",
".",
"compat",
".",
"v1",
".",
"get_variable",... | Builds the model function for use in an Estimator.
Arguments:
features: The input features for the Estimator.
labels: The labels, unused here.
mode: Signifies whether it is train or test or predict.
params: Some hyperparameters as a dictionary.
config: The RunConfig, unused here.
Returns:
... | [
"Builds",
"the",
"model",
"function",
"for",
"use",
"in",
"an",
"Estimator",
"."
] | python | test |
michael-lazar/rtv | rtv/page.py | https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/page.py#L72-L99 | def loop(self):
"""
Main control loop runs the following steps:
1. Re-draw the screen
2. Wait for user to press a key (includes terminal resizing)
3. Trigger the method registered to the input key
4. Check if there are any nested pages that need to be loop... | [
"def",
"loop",
"(",
"self",
")",
":",
"self",
".",
"active",
"=",
"True",
"# This needs to be called once before the main loop, in case a subpage",
"# was pre-selected before the loop started. This happens in __main__.py",
"# with ``page.open_submission(url=url)``",
"while",
"self",
... | Main control loop runs the following steps:
1. Re-draw the screen
2. Wait for user to press a key (includes terminal resizing)
3. Trigger the method registered to the input key
4. Check if there are any nested pages that need to be looped over
The loop will run u... | [
"Main",
"control",
"loop",
"runs",
"the",
"following",
"steps",
":",
"1",
".",
"Re",
"-",
"draw",
"the",
"screen",
"2",
".",
"Wait",
"for",
"user",
"to",
"press",
"a",
"key",
"(",
"includes",
"terminal",
"resizing",
")",
"3",
".",
"Trigger",
"the",
"... | python | train |
c-soft/satel_integra | satel_integra/satel_integra.py | https://github.com/c-soft/satel_integra/blob/3b6d2020d1e10dc5aa40f30ee4ecc0f3a053eb3c/satel_integra/satel_integra.py#L31-L47 | def verify_and_strip(resp):
"""Verify checksum and strip header and footer of received frame."""
if resp[0:2] != b'\xFE\xFE':
_LOGGER.error("Houston, we got problem:")
print_hex(resp)
raise Exception("Wrong header - got %X%X" % (resp[0], resp[1]))
if resp[-2:] != b'\xFE\x0D':
... | [
"def",
"verify_and_strip",
"(",
"resp",
")",
":",
"if",
"resp",
"[",
"0",
":",
"2",
"]",
"!=",
"b'\\xFE\\xFE'",
":",
"_LOGGER",
".",
"error",
"(",
"\"Houston, we got problem:\"",
")",
"print_hex",
"(",
"resp",
")",
"raise",
"Exception",
"(",
"\"Wrong header ... | Verify checksum and strip header and footer of received frame. | [
"Verify",
"checksum",
"and",
"strip",
"header",
"and",
"footer",
"of",
"received",
"frame",
"."
] | python | test |
census-instrumentation/opencensus-python | opencensus/trace/propagation/b3_format.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/trace/propagation/b3_format.py#L95-L117 | def to_headers(self, span_context):
"""Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers.
"""... | [
"def",
"to_headers",
"(",
"self",
",",
"span_context",
")",
":",
"if",
"not",
"span_context",
".",
"span_id",
":",
"span_id",
"=",
"INVALID_SPAN_ID",
"else",
":",
"span_id",
"=",
"span_context",
".",
"span_id",
"sampled",
"=",
"span_context",
".",
"trace_optio... | Convert a SpanContext object to B3 propagation headers.
:type span_context:
:class:`~opencensus.trace.span_context.SpanContext`
:param span_context: SpanContext object.
:rtype: dict
:returns: B3 propagation headers. | [
"Convert",
"a",
"SpanContext",
"object",
"to",
"B3",
"propagation",
"headers",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L707-L754 | def _build_command(self):
"""
Command to start the IOU process.
(to be passed to subprocess.Popen())
IOU command line:
Usage: <image> [options] <application id>
<image>: unix-js-m | unix-is-m | unix-i-m | ...
<application id>: instance identifier (0 < id <= 1024)... | [
"def",
"_build_command",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"_path",
"]",
"if",
"len",
"(",
"self",
".",
"_ethernet_adapters",
")",
"!=",
"2",
":",
"command",
".",
"extend",
"(",
"[",
"\"-e\"",
",",
"str",
"(",
"len",
"(",
"se... | Command to start the IOU process.
(to be passed to subprocess.Popen())
IOU command line:
Usage: <image> [options] <application id>
<image>: unix-js-m | unix-is-m | unix-i-m | ...
<application id>: instance identifier (0 < id <= 1024)
Options:
-e <n> Number... | [
"Command",
"to",
"start",
"the",
"IOU",
"process",
".",
"(",
"to",
"be",
"passed",
"to",
"subprocess",
".",
"Popen",
"()",
")"
] | python | train |
biolink/biolink-model | metamodel/generators/dotgen.py | https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/dotgen.py#L101-L103 | def cli(yamlfile, directory, out, classname, format):
""" Generate graphviz representations of the biolink model """
DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out) | [
"def",
"cli",
"(",
"yamlfile",
",",
"directory",
",",
"out",
",",
"classname",
",",
"format",
")",
":",
"DotGenerator",
"(",
"yamlfile",
",",
"format",
")",
".",
"serialize",
"(",
"classname",
"=",
"classname",
",",
"dirname",
"=",
"directory",
",",
"fil... | Generate graphviz representations of the biolink model | [
"Generate",
"graphviz",
"representations",
"of",
"the",
"biolink",
"model"
] | python | train |
saltstack/salt | salt/modules/consul.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L963-L1074 | def agent_service_register(consul_url=None, token=None, **kwargs):
'''
The used to add a new service, with an optional
health check, to the local agent.
:param consul_url: The Consul server URL.
:param name: A name describing the service.
:param address: The address used by the service, default... | [
"def",
"agent_service_register",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"i... | The used to add a new service, with an optional
health check, to the local agent.
:param consul_url: The Consul server URL.
:param name: A name describing the service.
:param address: The address used by the service, defaults
to the address of the agent.
:param port: The port us... | [
"The",
"used",
"to",
"add",
"a",
"new",
"service",
"with",
"an",
"optional",
"health",
"check",
"to",
"the",
"local",
"agent",
"."
] | python | train |
hamstah/ukpostcodeparser | ukpostcodeparser/parser.py | https://github.com/hamstah/ukpostcodeparser/blob/e36d6f07e5d410382641b5599f122d7c1b3dabdd/ukpostcodeparser/parser.py#L66-L146 | def parse_uk_postcode(postcode, strict=True, incode_mandatory=True):
'''Split UK postcode into outcode and incode portions.
Arguments:
postcode The postcode to be split.
strict If true, the postcode will be validated according to
the rules as specified at... | [
"def",
"parse_uk_postcode",
"(",
"postcode",
",",
"strict",
"=",
"True",
",",
"incode_mandatory",
"=",
"True",
")",
":",
"postcode",
"=",
"postcode",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"upper",
"(",
")",
"# Normalize",
"if",
"len",
"(",
"... | Split UK postcode into outcode and incode portions.
Arguments:
postcode The postcode to be split.
strict If true, the postcode will be validated according to
the rules as specified at the Universal Postal Union[1]
and The UK Government... | [
"Split",
"UK",
"postcode",
"into",
"outcode",
"and",
"incode",
"portions",
"."
] | python | train |
revelc/pyaccumulo | pyaccumulo/proxy/AccumuloProxy.py | https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L2259-L2267 | def setProperty(self, login, property, value):
"""
Parameters:
- login
- property
- value
"""
self.send_setProperty(login, property, value)
self.recv_setProperty() | [
"def",
"setProperty",
"(",
"self",
",",
"login",
",",
"property",
",",
"value",
")",
":",
"self",
".",
"send_setProperty",
"(",
"login",
",",
"property",
",",
"value",
")",
"self",
".",
"recv_setProperty",
"(",
")"
] | Parameters:
- login
- property
- value | [
"Parameters",
":",
"-",
"login",
"-",
"property",
"-",
"value"
] | python | train |
geomet/geomet | geomet/wkb.py | https://github.com/geomet/geomet/blob/b82d7118113ab723751eba3de5df98c368423c2b/geomet/wkb.py#L525-L559 | def _dump_multipolygon(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a multipolygon WKB string.
Input parameters and output are similar to :funct:`_dump_point`.
"""
coords = obj['coordinates']
vertex = coords[0][0][0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order ... | [
"def",
"_dump_multipolygon",
"(",
"obj",
",",
"big_endian",
",",
"meta",
")",
":",
"coords",
"=",
"obj",
"[",
"'coordinates'",
"]",
"vertex",
"=",
"coords",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"num_dims",
"=",
"len",
"(",
"vertex",
")",
"w... | Dump a GeoJSON-like `dict` to a multipolygon WKB string.
Input parameters and output are similar to :funct:`_dump_point`. | [
"Dump",
"a",
"GeoJSON",
"-",
"like",
"dict",
"to",
"a",
"multipolygon",
"WKB",
"string",
"."
] | python | train |
moralrecordings/mrcrowbar | mrcrowbar/utils.py | https://github.com/moralrecordings/mrcrowbar/blob/b1ed882c4555552e7656b2d84aca543184577fa3/mrcrowbar/utils.py#L394-L447 | def pixdump_iter( source, start=None, end=None, length=None, width=64, height=None, palette=None ):
"""Return the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading a... | [
"def",
"pixdump_iter",
"(",
"source",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"length",
"=",
"None",
",",
"width",
"=",
"64",
",",
"height",
"=",
"None",
",",
"palette",
"=",
"None",
")",
":",
"assert",
"is_bytes",
"(",
"source",
"... | Return the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Wi... | [
"Return",
"the",
"contents",
"of",
"a",
"byte",
"string",
"as",
"a",
"256",
"colour",
"image",
"."
] | python | train |
yandex/yandex-tank | yandextank/plugins/NeUploader/plugin.py | https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/NeUploader/plugin.py#L81-L93 | def get_uploader(data_session, column_mapping, overall_only=False):
"""
:type column_mapping: dict
:type data_session: DataSession
"""
overall = {col_name: data_session.new_aggregated_metric(name + ' overall')
for col_name, name in column_mapping.items()}
def upload_df(df):
... | [
"def",
"get_uploader",
"(",
"data_session",
",",
"column_mapping",
",",
"overall_only",
"=",
"False",
")",
":",
"overall",
"=",
"{",
"col_name",
":",
"data_session",
".",
"new_aggregated_metric",
"(",
"name",
"+",
"' overall'",
")",
"for",
"col_name",
",",
"na... | :type column_mapping: dict
:type data_session: DataSession | [
":",
"type",
"column_mapping",
":",
"dict",
":",
"type",
"data_session",
":",
"DataSession"
] | python | test |
hhatto/autopep8 | autopep8.py | https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L3479-L3489 | def global_fixes():
"""Yield multiple (code, function) tuples."""
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = _get_parameters(function)
if arguments[:1] != ['source']:
continue
code = extract_code_from_functi... | [
"def",
"global_fixes",
"(",
")",
":",
"for",
"function",
"in",
"list",
"(",
"globals",
"(",
")",
".",
"values",
"(",
")",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"function",
")",
":",
"arguments",
"=",
"_get_parameters",
"(",
"function",
")"... | Yield multiple (code, function) tuples. | [
"Yield",
"multiple",
"(",
"code",
"function",
")",
"tuples",
"."
] | python | train |
eyeseast/python-metalsmyth | metalsmyth/__init__.py | https://github.com/eyeseast/python-metalsmyth/blob/8c99746d4987ab8ec88d6ba84b6092c51dfbbe3e/metalsmyth/__init__.py#L99-L126 | def build(self, dest=None):
"Build out results to dest directory (creating if needed)"
# dest can be set here or on init
if not dest:
dest = self.dest
# raise an error if dest is None
if dest is None:
raise ValueError('destination directory must not be No... | [
"def",
"build",
"(",
"self",
",",
"dest",
"=",
"None",
")",
":",
"# dest can be set here or on init",
"if",
"not",
"dest",
":",
"dest",
"=",
"self",
".",
"dest",
"# raise an error if dest is None",
"if",
"dest",
"is",
"None",
":",
"raise",
"ValueError",
"(",
... | Build out results to dest directory (creating if needed) | [
"Build",
"out",
"results",
"to",
"dest",
"directory",
"(",
"creating",
"if",
"needed",
")"
] | python | train |
quantopian/pgcontents | pgcontents/query.py | https://github.com/quantopian/pgcontents/blob/ed36268b7917332d16868208e1e565742a8753e1/pgcontents/query.py#L201-L216 | def _dir_exists(db, user_id, db_dirname):
"""
Internal implementation of dir_exists.
Expects a db-style path name.
"""
return db.execute(
select(
[func.count(directories.c.name)],
).where(
and_(
directories.c.user_id == user_id,
... | [
"def",
"_dir_exists",
"(",
"db",
",",
"user_id",
",",
"db_dirname",
")",
":",
"return",
"db",
".",
"execute",
"(",
"select",
"(",
"[",
"func",
".",
"count",
"(",
"directories",
".",
"c",
".",
"name",
")",
"]",
",",
")",
".",
"where",
"(",
"and_",
... | Internal implementation of dir_exists.
Expects a db-style path name. | [
"Internal",
"implementation",
"of",
"dir_exists",
"."
] | python | test |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L2233-L2251 | def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.Sub... | [
"def",
"get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_brief_info",
"=",
"ET",
".",
"Element",
"(",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/models/mtf_resnet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_resnet.py#L333-L376 | def mtf_resnet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 32
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-way model-parallelism
hpa... | [
"def",
"mtf_resnet_base",
"(",
")",
":",
"hparams",
"=",
"common_hparams",
".",
"basic_params1",
"(",
")",
"hparams",
".",
"no_data_parallelism",
"=",
"True",
"hparams",
".",
"use_fixed_batch_size",
"=",
"True",
"hparams",
".",
"batch_size",
"=",
"32",
"hparams"... | Set of hyperparameters. | [
"Set",
"of",
"hyperparameters",
"."
] | python | train |
roboogle/gtkmvc3 | gtkmvco/gtkmvc3/adapters/basic.py | https://github.com/roboogle/gtkmvc3/blob/63405fd8d2056be26af49103b13a8d5e57fe4dff/gtkmvco/gtkmvc3/adapters/basic.py#L257-L292 | def _connect_model(self, model):
"""
Used internally to connect the property into the model, and
register self as a value observer for that property"""
parts = self._prop_name.split(".")
if len(parts) > 1:
# identifies the model
models = parts[:-1]
... | [
"def",
"_connect_model",
"(",
"self",
",",
"model",
")",
":",
"parts",
"=",
"self",
".",
"_prop_name",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"parts",
")",
">",
"1",
":",
"# identifies the model",
"models",
"=",
"parts",
"[",
":",
"-",
"1... | Used internally to connect the property into the model, and
register self as a value observer for that property | [
"Used",
"internally",
"to",
"connect",
"the",
"property",
"into",
"the",
"model",
"and",
"register",
"self",
"as",
"a",
"value",
"observer",
"for",
"that",
"property"
] | python | train |
cgarciae/phi | phi/dsl.py | https://github.com/cgarciae/phi/blob/87fd7100a76f823232f4fd8360498b4b80675265/phi/dsl.py#L675-L680 | def Then5(self, f, arg1, arg2, arg3, arg4, *args, **kwargs):
"""
`Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information.
"""
args = (arg1, arg2, arg3, arg4) + args
return self.ThenAt(5, f, *args, **kwargs) | [
"def",
"Then5",
"(",
"self",
",",
"f",
",",
"arg1",
",",
"arg2",
",",
"arg3",
",",
"arg4",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"arg1",
",",
"arg2",
",",
"arg3",
",",
"arg4",
")",
"+",
"args",
"return",
"self... | `Then5(f, ...)` is equivalent to `ThenAt(5, f, ...)`. Checkout `phi.builder.Builder.ThenAt` for more information. | [
"Then5",
"(",
"f",
"...",
")",
"is",
"equivalent",
"to",
"ThenAt",
"(",
"5",
"f",
"...",
")",
".",
"Checkout",
"phi",
".",
"builder",
".",
"Builder",
".",
"ThenAt",
"for",
"more",
"information",
"."
] | python | train |
linzhonghong/zapi | zapi/core/db.py | https://github.com/linzhonghong/zapi/blob/ac55c3ddbc4153561472faaf59fb72ef794f13a5/zapi/core/db.py#L524-L544 | def _escape_identifiers(self, item):
"""
This function escapes column and table names
@param item:
"""
if self._escape_char == '':
return item
for field in self._reserved_identifiers:
if item.find('.%s' % field) != -1:
_str = "%s%s... | [
"def",
"_escape_identifiers",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"_escape_char",
"==",
"''",
":",
"return",
"item",
"for",
"field",
"in",
"self",
".",
"_reserved_identifiers",
":",
"if",
"item",
".",
"find",
"(",
"'.%s'",
"%",
"field"... | This function escapes column and table names
@param item: | [
"This",
"function",
"escapes",
"column",
"and",
"table",
"names"
] | python | train |
koenedaele/skosprovider_oe | skosprovider_oe/providers.py | https://github.com/koenedaele/skosprovider_oe/blob/099b23cccd3884b06354102955dbc71f59d8fdb0/skosprovider_oe/providers.py#L277-L306 | def get_children_display(self, id, **kwargs):
'''
Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a la... | [
"def",
"get_children_display",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"language",
"=",
"self",
".",
"_get_language",
"(",
"*",
"*",
"kwargs",
")",
"item",
"=",
"self",
".",
"get_by_id",
"(",
"id",
")",
"res",
"=",
"[",
"]",
"if"... | Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a label. The label is determined by looking at
the `**kwar... | [
"Return",
"a",
"list",
"of",
"concepts",
"or",
"collections",
"that",
"should",
"be",
"displayed",
"under",
"this",
"concept",
"or",
"collection",
"."
] | python | train |
pvizeli/ha-ffmpeg | haffmpeg/tools.py | https://github.com/pvizeli/ha-ffmpeg/blob/fce1d4b77e76b9cb07d814bcb858b89657e1f32b/haffmpeg/tools.py#L57-L85 | async def get_version(self, timeout: int = 15) -> Optional[str]:
"""Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus
"""
command = ["-version"]
# open input for capture 1 frame
is_open = await self.open(cm... | [
"async",
"def",
"get_version",
"(",
"self",
",",
"timeout",
":",
"int",
"=",
"15",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"command",
"=",
"[",
"\"-version\"",
"]",
"# open input for capture 1 frame",
"is_open",
"=",
"await",
"self",
".",
"open",
"(",... | Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus | [
"Execute",
"FFmpeg",
"process",
"and",
"parse",
"the",
"version",
"information",
"."
] | python | train |
gem/oq-engine | openquake/commands/plot_agg_curve.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot_agg_curve.py#L42-L50 | def plot_ac(calc_id):
"""
Aggregate loss curves plotter.
"""
# read the hazard data
dstore = util.read(calc_id)
agg_curve = dstore['agg_curve-rlzs']
plt = make_figure(agg_curve)
plt.show() | [
"def",
"plot_ac",
"(",
"calc_id",
")",
":",
"# read the hazard data",
"dstore",
"=",
"util",
".",
"read",
"(",
"calc_id",
")",
"agg_curve",
"=",
"dstore",
"[",
"'agg_curve-rlzs'",
"]",
"plt",
"=",
"make_figure",
"(",
"agg_curve",
")",
"plt",
".",
"show",
"... | Aggregate loss curves plotter. | [
"Aggregate",
"loss",
"curves",
"plotter",
"."
] | python | train |
ibm-watson-iot/iot-python | src/wiotp/sdk/api/registry/devices.py | https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/src/wiotp/sdk/api/registry/devices.py#L482-L498 | def delete(self, devices):
"""
Delete one or more devices, each request can contain a maximum of 512Kb
It accepts accepts a list of devices (List of Dictionary of Devices)
In case of failure it throws APIException
"""
if not isinstance(devices, list):
listOfDe... | [
"def",
"delete",
"(",
"self",
",",
"devices",
")",
":",
"if",
"not",
"isinstance",
"(",
"devices",
",",
"list",
")",
":",
"listOfDevices",
"=",
"[",
"devices",
"]",
"else",
":",
"listOfDevices",
"=",
"devices",
"r",
"=",
"self",
".",
"_apiClient",
".",... | Delete one or more devices, each request can contain a maximum of 512Kb
It accepts accepts a list of devices (List of Dictionary of Devices)
In case of failure it throws APIException | [
"Delete",
"one",
"or",
"more",
"devices",
"each",
"request",
"can",
"contain",
"a",
"maximum",
"of",
"512Kb",
"It",
"accepts",
"accepts",
"a",
"list",
"of",
"devices",
"(",
"List",
"of",
"Dictionary",
"of",
"Devices",
")",
"In",
"case",
"of",
"failure",
... | python | test |
DataDog/integrations-core | datadog_checks_base/datadog_checks/base/utils/subprocess_output.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/utils/subprocess_output.py#L28-L69 | def get_subprocess_output(command, log, raise_on_empty_output=True, log_debug=True):
"""
Run the given subprocess command and return its output. Raise an Exception
if an error occurs.
:param command: The command to run. Using a list of strings is recommended. The command
will be run... | [
"def",
"get_subprocess_output",
"(",
"command",
",",
"log",
",",
"raise_on_empty_output",
"=",
"True",
",",
"log_debug",
"=",
"True",
")",
":",
"cmd_args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"command",
",",
"string_types",
")",
":",
"for",
"arg",
"in"... | Run the given subprocess command and return its output. Raise an Exception
if an error occurs.
:param command: The command to run. Using a list of strings is recommended. The command
will be run in a subprocess without using a shell, as such shell features like
shell pip... | [
"Run",
"the",
"given",
"subprocess",
"command",
"and",
"return",
"its",
"output",
".",
"Raise",
"an",
"Exception",
"if",
"an",
"error",
"occurs",
"."
] | python | train |
bokeh/bokeh | bokeh/server/tornado.py | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L425-L441 | def start(self):
''' Start the Bokeh Server application.
Starting the Bokeh Server Tornado application will run periodic
callbacks for stats logging, cleanup, pinging, etc. Additionally, any
startup hooks defined by the configured Bokeh applications will be run.
'''
sel... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_stats_job",
".",
"start",
"(",
")",
"if",
"self",
".",
"_mem_job",
"is",
"not",
"None",
":",
"self",
".",
"_mem_job",
".",
"start",
"(",
")",
"self",
".",
"_cleanup_job",
".",
"start",
"(",
")",... | Start the Bokeh Server application.
Starting the Bokeh Server Tornado application will run periodic
callbacks for stats logging, cleanup, pinging, etc. Additionally, any
startup hooks defined by the configured Bokeh applications will be run. | [
"Start",
"the",
"Bokeh",
"Server",
"application",
"."
] | python | train |
coursera/courseraoauth2client | courseraoauth2client/oauth2.py | https://github.com/coursera/courseraoauth2client/blob/4edd991defe26bfc768ab28a30368cace40baf44/courseraoauth2client/oauth2.py#L417-L434 | def _exchange_refresh_tokens(self):
'Exchanges a refresh token for an access token'
if self.token_cache is not None and 'refresh' in self.token_cache:
# Attempt to use the refresh token to get a new access token.
refresh_form = {
'grant_type': 'refresh_token',
... | [
"def",
"_exchange_refresh_tokens",
"(",
"self",
")",
":",
"if",
"self",
".",
"token_cache",
"is",
"not",
"None",
"and",
"'refresh'",
"in",
"self",
".",
"token_cache",
":",
"# Attempt to use the refresh token to get a new access token.",
"refresh_form",
"=",
"{",
"'gra... | Exchanges a refresh token for an access token | [
"Exchanges",
"a",
"refresh",
"token",
"for",
"an",
"access",
"token"
] | python | train |
SmokinCaterpillar/pypet | examples/example_24_large_scale_brian2_simulation/clusternet.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L287-L325 | def pre_build(self, traj, brian_list, network_dict):
"""Pre-builds the connections.
Pre-build is only performed if none of the
relevant parameters is explored and the relevant neuron groups
exist.
:param traj: Trajectory container
:param brian_list:
List o... | [
"def",
"pre_build",
"(",
"self",
",",
"traj",
",",
"brian_list",
",",
"network_dict",
")",
":",
"self",
".",
"_pre_build",
"=",
"not",
"_explored_parameters_in_group",
"(",
"traj",
",",
"traj",
".",
"parameters",
".",
"connections",
")",
"self",
".",
"_pre_b... | Pre-builds the connections.
Pre-build is only performed if none of the
relevant parameters is explored and the relevant neuron groups
exist.
:param traj: Trajectory container
:param brian_list:
List of objects passed to BRIAN network constructor.
Adds... | [
"Pre",
"-",
"builds",
"the",
"connections",
"."
] | python | test |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L408-L411 | def p_ioport(self, p):
'ioport : sigtypes portname'
p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_ioport",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"create_ioport",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"2",
")",
")",
"p",
".",
"set_lineno",... | ioport : sigtypes portname | [
"ioport",
":",
"sigtypes",
"portname"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L4792-L4799 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'credential_id') and self.credential_id is not None:
_dict['credential_id'] = self.credential_id
if hasattr(self, 'status') and self.status is not None:
_dict['... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'credential_id'",
")",
"and",
"self",
".",
"credential_id",
"is",
"not",
"None",
":",
"_dict",
"[",
"'credential_id'",
"]",
"=",
"self",
".",
"credent... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
hubo1016/namedstruct | namedstruct/namedstruct.py | https://github.com/hubo1016/namedstruct/blob/5039026e0df4ce23003d212358918dbe1a6e1d76/namedstruct/namedstruct.py#L1246-L1255 | def parse(self, buffer, inlineparent = None):
'''
Compatible to Parser.parse()
'''
if len(buffer) < self.struct.size:
return None
try:
return (self.struct.unpack(buffer[:self.struct.size])[0], self.struct.size)
except struct.error as exc:
... | [
"def",
"parse",
"(",
"self",
",",
"buffer",
",",
"inlineparent",
"=",
"None",
")",
":",
"if",
"len",
"(",
"buffer",
")",
"<",
"self",
".",
"struct",
".",
"size",
":",
"return",
"None",
"try",
":",
"return",
"(",
"self",
".",
"struct",
".",
"unpack"... | Compatible to Parser.parse() | [
"Compatible",
"to",
"Parser",
".",
"parse",
"()"
] | python | train |
amzn/ion-python | amazon/ion/reader.py | https://github.com/amzn/ion-python/blob/0b21fa3ba7755f55f745e4aa970d86343b82449d/amazon/ion/reader.py#L43-L59 | def _narrow_unichr(code_point):
"""Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalcula... | [
"def",
"_narrow_unichr",
"(",
"code_point",
")",
":",
"try",
":",
"if",
"len",
"(",
"code_point",
".",
"char",
")",
">",
"1",
":",
"return",
"code_point",
".",
"char",
"except",
"AttributeError",
":",
"pass",
"return",
"six",
".",
"unichr",
"(",
"code_po... | Retrieves the unicode character representing any given code point, in a way that won't break on narrow builds.
This is necessary because the built-in unichr function will fail for ordinals above 0xFFFF on narrow builds (UCS2);
ordinals above 0xFFFF would require recalculating and combining surrogate pairs. Thi... | [
"Retrieves",
"the",
"unicode",
"character",
"representing",
"any",
"given",
"code",
"point",
"in",
"a",
"way",
"that",
"won",
"t",
"break",
"on",
"narrow",
"builds",
"."
] | python | train |
log2timeline/plaso | plaso/analysis/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/interface.py#L314-L333 | def EstimateTimeRemaining(self):
"""Estimates how long until all hashes have been analyzed.
Returns:
int: estimated number of seconds until all hashes have been analyzed.
"""
number_of_hashes = self.hash_queue.qsize()
hashes_per_batch = self._analyzer.hashes_per_batch
wait_time_per_batch ... | [
"def",
"EstimateTimeRemaining",
"(",
"self",
")",
":",
"number_of_hashes",
"=",
"self",
".",
"hash_queue",
".",
"qsize",
"(",
")",
"hashes_per_batch",
"=",
"self",
".",
"_analyzer",
".",
"hashes_per_batch",
"wait_time_per_batch",
"=",
"self",
".",
"_analyzer",
"... | Estimates how long until all hashes have been analyzed.
Returns:
int: estimated number of seconds until all hashes have been analyzed. | [
"Estimates",
"how",
"long",
"until",
"all",
"hashes",
"have",
"been",
"analyzed",
"."
] | python | train |
astropy/regions | regions/io/ds9/read.py | https://github.com/astropy/regions/blob/452d962c417e4ff20d1268f99535c6ff89c83437/regions/io/ds9/read.py#L235-L279 | def parse_line(self, line):
"""
Parse one line
"""
log.debug('Parsing {}'.format(line))
# Skip blanks
if line == '':
return
# Skip comments
if line[0] == '#':
return
# Special case / header: parse global parameters into m... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"log",
".",
"debug",
"(",
"'Parsing {}'",
".",
"format",
"(",
"line",
")",
")",
"# Skip blanks",
"if",
"line",
"==",
"''",
":",
"return",
"# Skip comments",
"if",
"line",
"[",
"0",
"]",
"==",
"... | Parse one line | [
"Parse",
"one",
"line"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/gb/grain.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/gb/grain.py#L729-L1169 | def get_trans_mat(r_axis, angle, normal=False, trans_cry=np.eye(3), lat_type='c',
ratio=None, surface=None, max_search=20, quick_gen=False):
"""
Find the two transformation matrix for each grain from given rotation axis,
GB plane, rotation angle and corresponding ratio (see... | [
"def",
"get_trans_mat",
"(",
"r_axis",
",",
"angle",
",",
"normal",
"=",
"False",
",",
"trans_cry",
"=",
"np",
".",
"eye",
"(",
"3",
")",
",",
"lat_type",
"=",
"'c'",
",",
"ratio",
"=",
"None",
",",
"surface",
"=",
"None",
",",
"max_search",
"=",
"... | Find the two transformation matrix for each grain from given rotation axis,
GB plane, rotation angle and corresponding ratio (see explanation for ratio
below).
The structure of each grain can be obtained by applying the corresponding
transformation matrix to the conventional cell.
... | [
"Find",
"the",
"two",
"transformation",
"matrix",
"for",
"each",
"grain",
"from",
"given",
"rotation",
"axis",
"GB",
"plane",
"rotation",
"angle",
"and",
"corresponding",
"ratio",
"(",
"see",
"explanation",
"for",
"ratio",
"below",
")",
".",
"The",
"structure"... | python | train |
yprez/django-useful | useful/helpers/json_response.py | https://github.com/yprez/django-useful/blob/288aa46df6f40fb0323c3d0c0efcded887472538/useful/helpers/json_response.py#L9-L17 | def json_response(data, status=200, serializer=None):
"""
Returns an HttpResponse object containing JSON serialized data.
The mime-type is set to application/json, and the charset to UTF-8.
"""
return HttpResponse(json.dumps(data, default=serializer),
status=status,
... | [
"def",
"json_response",
"(",
"data",
",",
"status",
"=",
"200",
",",
"serializer",
"=",
"None",
")",
":",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"data",
",",
"default",
"=",
"serializer",
")",
",",
"status",
"=",
"status",
",",
"cont... | Returns an HttpResponse object containing JSON serialized data.
The mime-type is set to application/json, and the charset to UTF-8. | [
"Returns",
"an",
"HttpResponse",
"object",
"containing",
"JSON",
"serialized",
"data",
"."
] | python | train |
Cadasta/django-tutelary | tutelary/mixins.py | https://github.com/Cadasta/django-tutelary/blob/66bb05de7098777c0a383410c287bf48433cde87/tutelary/mixins.py#L146-L180 | def check_permissions(self, request):
"""Permission checking for DRF."""
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
... | [
"def",
"check_permissions",
"(",
"self",
",",
"request",
")",
":",
"objs",
"=",
"[",
"None",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'get_perms_objects'",
")",
":",
"objs",
"=",
"self",
".",
"get_perms_objects",
"(",
")",
"else",
":",
"if",
"hasattr",
... | Permission checking for DRF. | [
"Permission",
"checking",
"for",
"DRF",
"."
] | python | train |
OpenTreeOfLife/peyotl | peyotl/git_storage/git_action.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/git_storage/git_action.py#L143-L149 | def path_for_doc(self, doc_id):
"""Returns doc_dir and doc_filepath for doc_id.
"""
full_path = self.path_for_doc_fn(self.repo, doc_id)
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))
# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc re... | [
"def",
"path_for_doc",
"(",
"self",
",",
"doc_id",
")",
":",
"full_path",
"=",
"self",
".",
"path_for_doc_fn",
"(",
"self",
".",
"repo",
",",
"doc_id",
")",
"# _LOG.debug('>>>>>>>>>> GitActionBase.path_for_doc_fn: {}'.format(self.path_for_doc_fn))",
"# _LOG.debug('>>>>>>>>>... | Returns doc_dir and doc_filepath for doc_id. | [
"Returns",
"doc_dir",
"and",
"doc_filepath",
"for",
"doc_id",
"."
] | python | train |
pyBookshelf/bookshelf | bookshelf/api_v2/os_helpers.py | https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v2/os_helpers.py#L35-L58 | def dir_attribs(location, mode=None, owner=None,
group=None, recursive=False, use_sudo=False):
""" cuisine dir_attribs doesn't do sudo, so we implement our own
Updates the mode/owner/group for the given remote directory."""
args = ''
if recursive:
args = args + ' -R '
if... | [
"def",
"dir_attribs",
"(",
"location",
",",
"mode",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"use_sudo",
"=",
"False",
")",
":",
"args",
"=",
"''",
"if",
"recursive",
":",
"args",
"=",
... | cuisine dir_attribs doesn't do sudo, so we implement our own
Updates the mode/owner/group for the given remote directory. | [
"cuisine",
"dir_attribs",
"doesn",
"t",
"do",
"sudo",
"so",
"we",
"implement",
"our",
"own",
"Updates",
"the",
"mode",
"/",
"owner",
"/",
"group",
"for",
"the",
"given",
"remote",
"directory",
"."
] | python | train |
eykd/paved | paved/docs.py | https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L119-L138 | def showhtml():
"""Open your web browser and display the generated html documentation.
"""
import webbrowser
# copy from paver
opts = options
docroot = path(opts.get('docroot', 'docs'))
if not docroot.exists():
raise BuildFailure("Sphinx documentation root (%s) does not exist."
... | [
"def",
"showhtml",
"(",
")",
":",
"import",
"webbrowser",
"# copy from paver",
"opts",
"=",
"options",
"docroot",
"=",
"path",
"(",
"opts",
".",
"get",
"(",
"'docroot'",
",",
"'docs'",
")",
")",
"if",
"not",
"docroot",
".",
"exists",
"(",
")",
":",
"ra... | Open your web browser and display the generated html documentation. | [
"Open",
"your",
"web",
"browser",
"and",
"display",
"the",
"generated",
"html",
"documentation",
"."
] | python | valid |
tensorflow/tensor2tensor | tensor2tensor/models/transformer.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L2416-L2425 | def transformer_tpu_range(rhp):
"""Small range of hyperparameters."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.3, 3.0, scale=rhp.LOG_SCALE)
rhp.set_discrete("learning_rate_warmup_steps",
[1000, 2000, 4000, 8000, 16000])
rhp.set_float("i... | [
"def",
"transformer_tpu_range",
"(",
"rhp",
")",
":",
"# After starting from base, set intervals for some parameters.",
"rhp",
".",
"set_float",
"(",
"\"learning_rate\"",
",",
"0.3",
",",
"3.0",
",",
"scale",
"=",
"rhp",
".",
"LOG_SCALE",
")",
"rhp",
".",
"set_discr... | Small range of hyperparameters. | [
"Small",
"range",
"of",
"hyperparameters",
"."
] | python | train |
gem/oq-engine | openquake/calculators/views.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/views.py#L145-L170 | def sum_tbl(tbl, kfield, vfields):
"""
Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3])
"""
... | [
"def",
"sum_tbl",
"(",
"tbl",
",",
"kfield",
",",
"vfields",
")",
":",
"pairs",
"=",
"[",
"(",
"n",
",",
"tbl",
".",
"dtype",
"[",
"n",
"]",
")",
"for",
"n",
"in",
"[",
"kfield",
"]",
"+",
"vfields",
"]",
"dt",
"=",
"numpy",
".",
"dtype",
"("... | Aggregate a composite array and compute the totals on a given key.
>>> dt = numpy.dtype([('name', (bytes, 10)), ('value', int)])
>>> tbl = numpy.array([('a', 1), ('a', 2), ('b', 3)], dt)
>>> sum_tbl(tbl, 'name', ['value'])['value']
array([3, 3]) | [
"Aggregate",
"a",
"composite",
"array",
"and",
"compute",
"the",
"totals",
"on",
"a",
"given",
"key",
"."
] | python | train |
scopus-api/scopus | scopus/abstract_retrieval.py | https://github.com/scopus-api/scopus/blob/27ce02dd3095bfdab9d3e8475543d7c17767d1ab/scopus/abstract_retrieval.py#L639-L676 | def get_bibtex(self):
"""Bibliographic entry in BibTeX format.
Raises
------
ValueError
If the item's aggregationType is not Journal.
"""
if self.aggregationType != 'Journal':
raise ValueError('Only Journal articles supported.')
# Item key... | [
"def",
"get_bibtex",
"(",
"self",
")",
":",
"if",
"self",
".",
"aggregationType",
"!=",
"'Journal'",
":",
"raise",
"ValueError",
"(",
"'Only Journal articles supported.'",
")",
"# Item key",
"year",
"=",
"self",
".",
"coverDate",
"[",
"0",
":",
"4",
"]",
"fi... | Bibliographic entry in BibTeX format.
Raises
------
ValueError
If the item's aggregationType is not Journal. | [
"Bibliographic",
"entry",
"in",
"BibTeX",
"format",
"."
] | python | train |
manns/pyspread | pyspread/src/gui/_dialogs.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_dialogs.py#L1163-L1171 | def _set_properties(self):
"""Setup title and label"""
self.SetTitle(_("About pyspread"))
label = _("pyspread {version}\nCopyright Martin Manns")
label = label.format(version=VERSION)
self.about_label.SetLabel(label) | [
"def",
"_set_properties",
"(",
"self",
")",
":",
"self",
".",
"SetTitle",
"(",
"_",
"(",
"\"About pyspread\"",
")",
")",
"label",
"=",
"_",
"(",
"\"pyspread {version}\\nCopyright Martin Manns\"",
")",
"label",
"=",
"label",
".",
"format",
"(",
"version",
"=",
... | Setup title and label | [
"Setup",
"title",
"and",
"label"
] | python | train |
projecthamster/hamster | src/hamster/lib/graphics.py | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L688-L700 | def traverse(self, attr_name = None, attr_value = None):
"""traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute
"""
for sprite in self.sprites:
... | [
"def",
"traverse",
"(",
"self",
",",
"attr_name",
"=",
"None",
",",
"attr_value",
"=",
"None",
")",
":",
"for",
"sprite",
"in",
"self",
".",
"sprites",
":",
"if",
"(",
"attr_name",
"is",
"None",
")",
"or",
"(",
"attr_value",
"is",
"None",
"and",
"has... | traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute | [
"traverse",
"the",
"whole",
"sprite",
"tree",
"and",
"return",
"child",
"sprites",
"which",
"have",
"the",
"attribute",
"and",
"it",
"s",
"set",
"to",
"the",
"specified",
"value",
".",
"If",
"falue",
"is",
"None",
"will",
"return",
"all",
"sprites",
"that"... | python | train |
data-8/datascience | datascience/tables.py | https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L384-L387 | def move_to_start(self, column_label):
"""Move a column to the first in order."""
self._columns.move_to_end(column_label, last=False)
return self | [
"def",
"move_to_start",
"(",
"self",
",",
"column_label",
")",
":",
"self",
".",
"_columns",
".",
"move_to_end",
"(",
"column_label",
",",
"last",
"=",
"False",
")",
"return",
"self"
] | Move a column to the first in order. | [
"Move",
"a",
"column",
"to",
"the",
"first",
"in",
"order",
"."
] | python | train |
google/transitfeed | examples/google_random_queries.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/examples/google_random_queries.py#L87-L91 | def GetRandomDatetime():
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0) | [
"def",
"GetRandomDatetime",
"(",
")",
":",
"seconds_offset",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
")",
"dt",
"=",
"datetime",
".",
"today",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"seconds_offse... | Return a datetime in the next week. | [
"Return",
"a",
"datetime",
"in",
"the",
"next",
"week",
"."
] | python | train |
hubo1016/vlcp | vlcp/config/config.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/config/config.py#L411-L427 | def config(key):
"""
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
... | [
"def",
"config",
"(",
"key",
")",
":",
"def",
"decorator",
"(",
"cls",
")",
":",
"parent",
"=",
"cls",
".",
"getConfigurableParent",
"(",
")",
"if",
"parent",
"is",
"None",
":",
"parentbase",
"=",
"None",
"else",
":",
"parentbase",
"=",
"getattr",
"(",... | Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping. | [
"Decorator",
"to",
"map",
"this",
"class",
"directly",
"to",
"a",
"configuration",
"node",
".",
"It",
"uses",
"<parentbase",
">",
".",
"key",
"for",
"configuration",
"base",
"and",
"configuration",
"mapping",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L3681-L3714 | def delete_gradebook_column(self, gradebook_column_id):
"""Deletes the ``GradebookColumn`` identified by the given ``Id``.
arg: gradebook_column_id (osid.id.Id): the ``Id`` of the
``GradebookColumn`` to delete
raise: NotFound - a ``GradebookColumn`` was not found
... | [
"def",
"delete_gradebook_column",
"(",
"self",
",",
"gradebook_column_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"gradebook_column_id",
",",
"ABCId",
")",
":",
"raise",
"errors",
".",
"InvalidArgument",
"(",
"'the argument is not a valid OSID Id'",
")",
"# check t... | Deletes the ``GradebookColumn`` identified by the given ``Id``.
arg: gradebook_column_id (osid.id.Id): the ``Id`` of the
``GradebookColumn`` to delete
raise: NotFound - a ``GradebookColumn`` was not found
identified by the given ``Id``
raise: NullArgument - ... | [
"Deletes",
"the",
"GradebookColumn",
"identified",
"by",
"the",
"given",
"Id",
"."
] | python | train |
google/grr | grr/server/grr_response_server/flows/general/administrative.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flows/general/administrative.py#L137-L232 | def ProcessMessages(self, msgs=None, token=None):
"""Processes this event."""
nanny_msg = ""
for crash_details in msgs:
client_urn = crash_details.client_id
client_id = client_urn.Basename()
# The session id of the flow that crashed.
session_id = crash_details.session_id
# L... | [
"def",
"ProcessMessages",
"(",
"self",
",",
"msgs",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"nanny_msg",
"=",
"\"\"",
"for",
"crash_details",
"in",
"msgs",
":",
"client_urn",
"=",
"crash_details",
".",
"client_id",
"client_id",
"=",
"client_urn",
... | Processes this event. | [
"Processes",
"this",
"event",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.