nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
SFTtech/openage | d6a08c53c48dc1e157807471df92197f6ca9e04d | openage/convert/processor/conversion/swgbcc/nyan_subprocessor.py | python | SWGBCCNyanSubprocessor.convert | (cls, gamedata) | Create nyan objects from the given dataset. | Create nyan objects from the given dataset. | [
"Create",
"nyan",
"objects",
"from",
"the",
"given",
"dataset",
"."
] | def convert(cls, gamedata):
"""
Create nyan objects from the given dataset.
"""
cls._process_game_entities(gamedata)
cls._create_nyan_objects(gamedata)
cls._create_nyan_members(gamedata)
cls._check_objects(gamedata) | [
"def",
"convert",
"(",
"cls",
",",
"gamedata",
")",
":",
"cls",
".",
"_process_game_entities",
"(",
"gamedata",
")",
"cls",
".",
"_create_nyan_objects",
"(",
"gamedata",
")",
"cls",
".",
"_create_nyan_members",
"(",
"gamedata",
")",
"cls",
".",
"_check_objects",
"(",
"gamedata",
")"
] | https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/swgbcc/nyan_subprocessor.py#L32-L40 | ||
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/app.py | python | SaveWindowSize | (section,rect,state="") | Writes a rectangle to an INI file
Args: section = section name in the applications INI file
rect = a rectangle in a (cy, cx, y, x) tuple
(same format as CREATESTRUCT position tuples). | Writes a rectangle to an INI file
Args: section = section name in the applications INI file
rect = a rectangle in a (cy, cx, y, x) tuple
(same format as CREATESTRUCT position tuples). | [
"Writes",
"a",
"rectangle",
"to",
"an",
"INI",
"file",
"Args",
":",
"section",
"=",
"section",
"name",
"in",
"the",
"applications",
"INI",
"file",
"rect",
"=",
"a",
"rectangle",
"in",
"a",
"(",
"cy",
"cx",
"y",
"x",
")",
"tuple",
"(",
"same",
"format",
"as",
"CREATESTRUCT",
"position",
"tuples",
")",
"."
] | def SaveWindowSize(section,rect,state=""):
""" Writes a rectangle to an INI file
Args: section = section name in the applications INI file
rect = a rectangle in a (cy, cx, y, x) tuple
(same format as CREATESTRUCT position tuples)."""
left, top, right, bottom = rect
if state: state = state + " "
win32ui.WriteProfileVal(section,state+"left",left)
win32ui.WriteProfileVal(section,state+"top",top)
win32ui.WriteProfileVal(section,state+"right",right)
win32ui.WriteProfileVal(section,state+"bottom",bottom) | [
"def",
"SaveWindowSize",
"(",
"section",
",",
"rect",
",",
"state",
"=",
"\"\"",
")",
":",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"=",
"rect",
"if",
"state",
":",
"state",
"=",
"state",
"+",
"\" \"",
"win32ui",
".",
"WriteProfileVal",
"(",
"section",
",",
"state",
"+",
"\"left\"",
",",
"left",
")",
"win32ui",
".",
"WriteProfileVal",
"(",
"section",
",",
"state",
"+",
"\"top\"",
",",
"top",
")",
"win32ui",
".",
"WriteProfileVal",
"(",
"section",
",",
"state",
"+",
"\"right\"",
",",
"right",
")",
"win32ui",
".",
"WriteProfileVal",
"(",
"section",
",",
"state",
"+",
"\"bottom\"",
",",
"bottom",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/app.py#L37-L47 | ||
hpi-xnor/BMXNet | ed0b201da6667887222b8e4b5f997c4f6b61943d | example/ssd/train.py | python | parse_class_names | (args) | return class_names | parse # classes and class_names if applicable | parse # classes and class_names if applicable | [
"parse",
"#",
"classes",
"and",
"class_names",
"if",
"applicable"
] | def parse_class_names(args):
""" parse # classes and class_names if applicable """
num_class = args.num_class
if len(args.class_names) > 0:
if os.path.isfile(args.class_names):
# try to open it to read class names
with open(args.class_names, 'r') as f:
class_names = [l.strip() for l in f.readlines()]
else:
class_names = [c.strip() for c in args.class_names.split(',')]
assert len(class_names) == num_class, str(len(class_names))
for name in class_names:
assert len(name) > 0
else:
class_names = None
return class_names | [
"def",
"parse_class_names",
"(",
"args",
")",
":",
"num_class",
"=",
"args",
".",
"num_class",
"if",
"len",
"(",
"args",
".",
"class_names",
")",
">",
"0",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"class_names",
")",
":",
"# try to open it to read class names",
"with",
"open",
"(",
"args",
".",
"class_names",
",",
"'r'",
")",
"as",
"f",
":",
"class_names",
"=",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
"else",
":",
"class_names",
"=",
"[",
"c",
".",
"strip",
"(",
")",
"for",
"c",
"in",
"args",
".",
"class_names",
".",
"split",
"(",
"','",
")",
"]",
"assert",
"len",
"(",
"class_names",
")",
"==",
"num_class",
",",
"str",
"(",
"len",
"(",
"class_names",
")",
")",
"for",
"name",
"in",
"class_names",
":",
"assert",
"len",
"(",
"name",
")",
">",
"0",
"else",
":",
"class_names",
"=",
"None",
"return",
"class_names"
] | https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/train.py#L107-L122 | |
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | lldb/third_party/Python/module/pexpect-4.6/pexpect/pxssh.py | python | pxssh.set_unique_prompt | (self) | return True | This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands.
Alternatively, you may use your own prompt pattern. In this case you
should call :meth:`login` with ``auto_prompt_reset=False``; then set the
:attr:`PROMPT` attribute to a regular expression. After that, the
:meth:`prompt` method will try to match your prompt pattern. | This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands. | [
"This",
"sets",
"the",
"remote",
"prompt",
"to",
"something",
"more",
"unique",
"than",
"#",
"or",
"$",
".",
"This",
"makes",
"it",
"easier",
"for",
"the",
":",
"meth",
":",
"prompt",
"method",
"to",
"match",
"the",
"shell",
"prompt",
"unambiguously",
".",
"This",
"method",
"is",
"called",
"automatically",
"by",
"the",
":",
"meth",
":",
"login",
"method",
"but",
"you",
"may",
"want",
"to",
"call",
"it",
"manually",
"if",
"you",
"somehow",
"reset",
"the",
"shell",
"prompt",
".",
"For",
"example",
"if",
"you",
"su",
"to",
"a",
"different",
"user",
"then",
"you",
"will",
"need",
"to",
"manually",
"reset",
"the",
"prompt",
".",
"This",
"sends",
"shell",
"commands",
"to",
"the",
"remote",
"host",
"to",
"set",
"the",
"prompt",
"so",
"this",
"assumes",
"the",
"remote",
"host",
"is",
"ready",
"to",
"receive",
"commands",
"."
] | def set_unique_prompt(self):
'''This sets the remote prompt to something more unique than ``#`` or ``$``.
This makes it easier for the :meth:`prompt` method to match the shell prompt
unambiguously. This method is called automatically by the :meth:`login`
method, but you may want to call it manually if you somehow reset the
shell prompt. For example, if you 'su' to a different user then you
will need to manually reset the prompt. This sends shell commands to
the remote host to set the prompt, so this assumes the remote host is
ready to receive commands.
Alternatively, you may use your own prompt pattern. In this case you
should call :meth:`login` with ``auto_prompt_reset=False``; then set the
:attr:`PROMPT` attribute to a regular expression. After that, the
:meth:`prompt` method will try to match your prompt pattern.
'''
self.sendline("unset PROMPT_COMMAND")
self.sendline(self.PROMPT_SET_SH) # sh-style
i = self.expect ([TIMEOUT, self.PROMPT], timeout=10)
if i == 0: # csh-style
self.sendline(self.PROMPT_SET_CSH)
i = self.expect([TIMEOUT, self.PROMPT], timeout=10)
if i == 0:
return False
return True | [
"def",
"set_unique_prompt",
"(",
"self",
")",
":",
"self",
".",
"sendline",
"(",
"\"unset PROMPT_COMMAND\"",
")",
"self",
".",
"sendline",
"(",
"self",
".",
"PROMPT_SET_SH",
")",
"# sh-style",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"TIMEOUT",
",",
"self",
".",
"PROMPT",
"]",
",",
"timeout",
"=",
"10",
")",
"if",
"i",
"==",
"0",
":",
"# csh-style",
"self",
".",
"sendline",
"(",
"self",
".",
"PROMPT_SET_CSH",
")",
"i",
"=",
"self",
".",
"expect",
"(",
"[",
"TIMEOUT",
",",
"self",
".",
"PROMPT",
"]",
",",
"timeout",
"=",
"10",
")",
"if",
"i",
"==",
"0",
":",
"return",
"False",
"return",
"True"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/lldb/third_party/Python/module/pexpect-4.6/pexpect/pxssh.py#L473-L497 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/handler.py | python | ErrorHandler.fatalError | (self, exception) | Handle a non-recoverable error. | Handle a non-recoverable error. | [
"Handle",
"a",
"non",
"-",
"recoverable",
"error",
"."
] | def fatalError(self, exception):
"Handle a non-recoverable error."
raise exception | [
"def",
"fatalError",
"(",
"self",
",",
"exception",
")",
":",
"raise",
"exception"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/xml/sax/handler.py#L36-L38 | ||
mantidproject/mantid | 03deeb89254ec4289edb8771e0188c2090a02f32 | scripts/reduction_gui/reduction/reflectometer/refl_data_series.py | python | DataSeries.from_xml | (self, xml_str) | Read in data from XML
@param xml_str: text to read the data from | Read in data from XML | [
"Read",
"in",
"data",
"from",
"XML"
] | def from_xml(self, xml_str):
"""
Read in data from XML
@param xml_str: text to read the data from
"""
self.reset()
self.data_sets = []
dom = xml.dom.minidom.parseString(xml_str)
# # Get Mantid version
# mtd_version = BaseScriptElement.getMantidBuildVersion(dom)
self._data_class = REFLDataSets
element_list = dom.getElementsByTagName("Data")
if len(element_list)==0:
element_list = dom.getElementsByTagName("RefLData")
if len(element_list)>0:
for item in element_list:
if item is not None:
data_set = self._data_class()
data_set.from_xml_element(item)
self.data_sets.append(data_set)
if len(self.data_sets)==0:
self.data_sets = [self._data_class()] | [
"def",
"from_xml",
"(",
"self",
",",
"xml_str",
")",
":",
"self",
".",
"reset",
"(",
")",
"self",
".",
"data_sets",
"=",
"[",
"]",
"dom",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parseString",
"(",
"xml_str",
")",
"# # Get Mantid version",
"# mtd_version = BaseScriptElement.getMantidBuildVersion(dom)",
"self",
".",
"_data_class",
"=",
"REFLDataSets",
"element_list",
"=",
"dom",
".",
"getElementsByTagName",
"(",
"\"Data\"",
")",
"if",
"len",
"(",
"element_list",
")",
"==",
"0",
":",
"element_list",
"=",
"dom",
".",
"getElementsByTagName",
"(",
"\"RefLData\"",
")",
"if",
"len",
"(",
"element_list",
")",
">",
"0",
":",
"for",
"item",
"in",
"element_list",
":",
"if",
"item",
"is",
"not",
"None",
":",
"data_set",
"=",
"self",
".",
"_data_class",
"(",
")",
"data_set",
".",
"from_xml_element",
"(",
"item",
")",
"self",
".",
"data_sets",
".",
"append",
"(",
"data_set",
")",
"if",
"len",
"(",
"self",
".",
"data_sets",
")",
"==",
"0",
":",
"self",
".",
"data_sets",
"=",
"[",
"self",
".",
"_data_class",
"(",
")",
"]"
] | https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/reduction_gui/reduction/reflectometer/refl_data_series.py#L50-L75 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan.Day | (*args, **kwargs) | return _misc_.DateSpan_Day(*args, **kwargs) | Day() -> DateSpan | Day() -> DateSpan | [
"Day",
"()",
"-",
">",
"DateSpan"
] | def Day(*args, **kwargs):
"""Day() -> DateSpan"""
return _misc_.DateSpan_Day(*args, **kwargs) | [
"def",
"Day",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Day",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4618-L4620 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/py2/scipy/special/_generate_pyx.py | python | npy_cdouble_from_double_complex | (var) | return res | Cast a cython double complex to a numpy cdouble. | Cast a cython double complex to a numpy cdouble. | [
"Cast",
"a",
"cython",
"double",
"complex",
"to",
"a",
"numpy",
"cdouble",
"."
] | def npy_cdouble_from_double_complex(var):
"""Cast a cython double complex to a numpy cdouble."""
res = "_complexstuff.npy_cdouble_from_double_complex({})".format(var)
return res | [
"def",
"npy_cdouble_from_double_complex",
"(",
"var",
")",
":",
"res",
"=",
"\"_complexstuff.npy_cdouble_from_double_complex({})\"",
".",
"format",
"(",
"var",
")",
"return",
"res"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/special/_generate_pyx.py#L449-L452 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_misc.py | python | DateSpan.Month | (*args, **kwargs) | return _misc_.DateSpan_Month(*args, **kwargs) | Month() -> DateSpan | Month() -> DateSpan | [
"Month",
"()",
"-",
">",
"DateSpan"
] | def Month(*args, **kwargs):
"""Month() -> DateSpan"""
return _misc_.DateSpan_Month(*args, **kwargs) | [
"def",
"Month",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_misc_",
".",
"DateSpan_Month",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L4638-L4640 | |
google/earthenterprise | 0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9 | earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py | python | MethodDescriptor.__init__ | (self, name, full_name, index, containing_service,
input_type, output_type, options=None) | The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary. | The arguments are as described in the description of MethodDescriptor
attributes above. | [
"The",
"arguments",
"are",
"as",
"described",
"in",
"the",
"description",
"of",
"MethodDescriptor",
"attributes",
"above",
"."
] | def __init__(self, name, full_name, index, containing_service,
input_type, output_type, options=None):
"""The arguments are as described in the description of MethodDescriptor
attributes above.
Note that containing_service may be None, and may be set later if necessary.
"""
super(MethodDescriptor, self).__init__(options, 'MethodOptions')
self.name = name
self.full_name = full_name
self.index = index
self.containing_service = containing_service
self.input_type = input_type
self.output_type = output_type | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"full_name",
",",
"index",
",",
"containing_service",
",",
"input_type",
",",
"output_type",
",",
"options",
"=",
"None",
")",
":",
"super",
"(",
"MethodDescriptor",
",",
"self",
")",
".",
"__init__",
"(",
"options",
",",
"'MethodOptions'",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"full_name",
"=",
"full_name",
"self",
".",
"index",
"=",
"index",
"self",
".",
"containing_service",
"=",
"containing_service",
"self",
".",
"input_type",
"=",
"input_type",
"self",
".",
"output_type",
"=",
"output_type"
] | https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/google/protobuf-py/google/protobuf/descriptor.py#L544-L557 | ||
NREL/EnergyPlus | fadc5973b85c70e8cc923efb69c144e808a26078 | src/EnergyPlus/api/datatransfer.py | python | DataExchange.list_available_api_data_csv | (self, state: c_void_p) | return self.api.listAllAPIDataCSV(state) | Lists out all API data stuff in an easily parseable CSV form
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:return: Returns a raw bytes CSV representation of the available API data | Lists out all API data stuff in an easily parseable CSV form | [
"Lists",
"out",
"all",
"API",
"data",
"stuff",
"in",
"an",
"easily",
"parseable",
"CSV",
"form"
] | def list_available_api_data_csv(self, state: c_void_p) -> bytes:
"""
Lists out all API data stuff in an easily parseable CSV form
:param state: An active EnergyPlus "state" that is returned from a call to `api.state_manager.new_state()`.
:return: Returns a raw bytes CSV representation of the available API data
"""
return self.api.listAllAPIDataCSV(state) | [
"def",
"list_available_api_data_csv",
"(",
"self",
",",
"state",
":",
"c_void_p",
")",
"->",
"bytes",
":",
"return",
"self",
".",
"api",
".",
"listAllAPIDataCSV",
"(",
"state",
")"
] | https://github.com/NREL/EnergyPlus/blob/fadc5973b85c70e8cc923efb69c144e808a26078/src/EnergyPlus/api/datatransfer.py#L251-L258 | |
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/dataset/movielens.py | python | UserInfo.value | (self) | return [self.index, 0 if self.is_male else 1, self.age, self.job_id] | Get information from a user. | Get information from a user. | [
"Get",
"information",
"from",
"a",
"user",
"."
] | def value(self):
"""
Get information from a user.
"""
return [self.index, 0 if self.is_male else 1, self.age, self.job_id] | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"index",
",",
"0",
"if",
"self",
".",
"is_male",
"else",
"1",
",",
"self",
".",
"age",
",",
"self",
".",
"job_id",
"]"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/dataset/movielens.py#L84-L88 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/debug/cli/debugger_cli_common.py | python | CommandHandlerRegistry._get_help_for_command_prefix | (self, cmd_prefix) | return lines | Compile the help information for a given command prefix.
Args:
cmd_prefix: Command prefix, as the prefix itself or one of its
aliases.
Returns:
A list of str as the help information fo cmd_prefix. If the cmd_prefix
does not exist, the returned list of str will indicate that. | Compile the help information for a given command prefix. | [
"Compile",
"the",
"help",
"information",
"for",
"a",
"given",
"command",
"prefix",
"."
] | def _get_help_for_command_prefix(self, cmd_prefix):
"""Compile the help information for a given command prefix.
Args:
cmd_prefix: Command prefix, as the prefix itself or one of its
aliases.
Returns:
A list of str as the help information fo cmd_prefix. If the cmd_prefix
does not exist, the returned list of str will indicate that.
"""
lines = []
resolved_prefix = self._resolve_prefix(cmd_prefix)
if not resolved_prefix:
lines.append("Invalid command prefix: \"%s\"" % cmd_prefix)
return lines
lines.append(resolved_prefix)
if resolved_prefix in self._prefix_to_aliases:
lines.append(HELP_INDENT + "Aliases: " + ", ".join(
self._prefix_to_aliases[resolved_prefix]))
lines.append("")
help_lines = self._prefix_to_help[resolved_prefix].split("\n")
for line in help_lines:
lines.append(HELP_INDENT + line)
return lines | [
"def",
"_get_help_for_command_prefix",
"(",
"self",
",",
"cmd_prefix",
")",
":",
"lines",
"=",
"[",
"]",
"resolved_prefix",
"=",
"self",
".",
"_resolve_prefix",
"(",
"cmd_prefix",
")",
"if",
"not",
"resolved_prefix",
":",
"lines",
".",
"append",
"(",
"\"Invalid command prefix: \\\"%s\\\"\"",
"%",
"cmd_prefix",
")",
"return",
"lines",
"lines",
".",
"append",
"(",
"resolved_prefix",
")",
"if",
"resolved_prefix",
"in",
"self",
".",
"_prefix_to_aliases",
":",
"lines",
".",
"append",
"(",
"HELP_INDENT",
"+",
"\"Aliases: \"",
"+",
"\", \"",
".",
"join",
"(",
"self",
".",
"_prefix_to_aliases",
"[",
"resolved_prefix",
"]",
")",
")",
"lines",
".",
"append",
"(",
"\"\"",
")",
"help_lines",
"=",
"self",
".",
"_prefix_to_help",
"[",
"resolved_prefix",
"]",
".",
"split",
"(",
"\"\\n\"",
")",
"for",
"line",
"in",
"help_lines",
":",
"lines",
".",
"append",
"(",
"HELP_INDENT",
"+",
"line",
")",
"return",
"lines"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/debug/cli/debugger_cli_common.py#L783-L812 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py | python | urlencode | (query, doseq=0) | return '&'.join(l) | Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input. | Encode a sequence of two-element tuples or dictionary into a URL query string. | [
"Encode",
"a",
"sequence",
"of",
"two",
"-",
"element",
"tuples",
"or",
"dictionary",
"into",
"a",
"URL",
"query",
"string",
"."
] | def urlencode(query, doseq=0):
"""Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.
"""
if hasattr(query,"items"):
# mapping objects
query = query.items()
else:
# it's a bother at times that strings and string-like objects are
# sequences...
try:
# non-sequence items should not work with len()
# non-empty strings will fail this
if len(query) and not isinstance(query[0], tuple):
raise TypeError
# zero-length sequences of all types will get here and succeed,
# but that's a minor nit - since the original implementation
# allowed empty dicts that type of behavior probably should be
# preserved for consistency
except TypeError:
ty,va,tb = sys.exc_info()
raise TypeError, "not a valid non-string sequence or mapping object", tb
l = []
if not doseq:
# preserve old behavior
for k, v in query:
k = quote_plus(str(k))
v = quote_plus(str(v))
l.append(k + '=' + v)
else:
for k, v in query:
k = quote_plus(str(k))
if isinstance(v, str):
v = quote_plus(v)
l.append(k + '=' + v)
elif _is_unicode(v):
# is there a reasonable way to convert to ASCII?
# encode generates a string, but "replace" or "ignore"
# lose information and "strict" can raise UnicodeError
v = quote_plus(v.encode("ASCII","replace"))
l.append(k + '=' + v)
else:
try:
# is this a sufficient test for sequence-ness?
len(v)
except TypeError:
# not a sequence
v = quote_plus(str(v))
l.append(k + '=' + v)
else:
# loop over the sequence
for elt in v:
l.append(k + '=' + quote_plus(str(elt)))
return '&'.join(l) | [
"def",
"urlencode",
"(",
"query",
",",
"doseq",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"query",
",",
"\"items\"",
")",
":",
"# mapping objects",
"query",
"=",
"query",
".",
"items",
"(",
")",
"else",
":",
"# it's a bother at times that strings and string-like objects are",
"# sequences...",
"try",
":",
"# non-sequence items should not work with len()",
"# non-empty strings will fail this",
"if",
"len",
"(",
"query",
")",
"and",
"not",
"isinstance",
"(",
"query",
"[",
"0",
"]",
",",
"tuple",
")",
":",
"raise",
"TypeError",
"# zero-length sequences of all types will get here and succeed,",
"# but that's a minor nit - since the original implementation",
"# allowed empty dicts that type of behavior probably should be",
"# preserved for consistency",
"except",
"TypeError",
":",
"ty",
",",
"va",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise",
"TypeError",
",",
"\"not a valid non-string sequence or mapping object\"",
",",
"tb",
"l",
"=",
"[",
"]",
"if",
"not",
"doseq",
":",
"# preserve old behavior",
"for",
"k",
",",
"v",
"in",
"query",
":",
"k",
"=",
"quote_plus",
"(",
"str",
"(",
"k",
")",
")",
"v",
"=",
"quote_plus",
"(",
"str",
"(",
"v",
")",
")",
"l",
".",
"append",
"(",
"k",
"+",
"'='",
"+",
"v",
")",
"else",
":",
"for",
"k",
",",
"v",
"in",
"query",
":",
"k",
"=",
"quote_plus",
"(",
"str",
"(",
"k",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"str",
")",
":",
"v",
"=",
"quote_plus",
"(",
"v",
")",
"l",
".",
"append",
"(",
"k",
"+",
"'='",
"+",
"v",
")",
"elif",
"_is_unicode",
"(",
"v",
")",
":",
"# is there a reasonable way to convert to ASCII?",
"# encode generates a string, but \"replace\" or \"ignore\"",
"# lose information and \"strict\" can raise UnicodeError",
"v",
"=",
"quote_plus",
"(",
"v",
".",
"encode",
"(",
"\"ASCII\"",
",",
"\"replace\"",
")",
")",
"l",
".",
"append",
"(",
"k",
"+",
"'='",
"+",
"v",
")",
"else",
":",
"try",
":",
"# is this a sufficient test for sequence-ness?",
"len",
"(",
"v",
")",
"except",
"TypeError",
":",
"# not a sequence",
"v",
"=",
"quote_plus",
"(",
"str",
"(",
"v",
")",
")",
"l",
".",
"append",
"(",
"k",
"+",
"'='",
"+",
"v",
")",
"else",
":",
"# loop over the sequence",
"for",
"elt",
"in",
"v",
":",
"l",
".",
"append",
"(",
"k",
"+",
"'='",
"+",
"quote_plus",
"(",
"str",
"(",
"elt",
")",
")",
")",
"return",
"'&'",
".",
"join",
"(",
"l",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/urllib.py#L1291-L1352 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/cryptotools.py | python | make_public_key_h_file | (signing_key,key_name) | This file generate the public key header file
to be included into the bootloader build. | This file generate the public key header file
to be included into the bootloader build. | [
"This",
"file",
"generate",
"the",
"public",
"key",
"header",
"file",
"to",
"be",
"included",
"into",
"the",
"bootloader",
"build",
"."
] | def make_public_key_h_file(signing_key,key_name):
"""
This file generate the public key header file
to be included into the bootloader build.
"""
public_key_c='\n'
for i,c in enumerate(signing_key.verify_key.encode(encoder=nacl.encoding.RawEncoder)):
public_key_c+= hex(c)
public_key_c+= ', '
if((i+1)%8==0):
public_key_c+= '\n'
with open(key_name+'.pub' ,mode='w') as f:
f.write("//Public key to verify signed binaries")
f.write(public_key_c) | [
"def",
"make_public_key_h_file",
"(",
"signing_key",
",",
"key_name",
")",
":",
"public_key_c",
"=",
"'\\n'",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"signing_key",
".",
"verify_key",
".",
"encode",
"(",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"RawEncoder",
")",
")",
":",
"public_key_c",
"+=",
"hex",
"(",
"c",
")",
"public_key_c",
"+=",
"', '",
"if",
"(",
"(",
"i",
"+",
"1",
")",
"%",
"8",
"==",
"0",
")",
":",
"public_key_c",
"+=",
"'\\n'",
"with",
"open",
"(",
"key_name",
"+",
"'.pub'",
",",
"mode",
"=",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"\"//Public key to verify signed binaries\"",
")",
"f",
".",
"write",
"(",
"public_key_c",
")"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/cryptotools.py#L14-L27 | ||
bristolcrypto/SPDZ-2 | 721abfae849625a02ea49aabc534f9cf41ca643f | Compiler/program.py | python | Tape.reset_registers | (self) | Reset register values to zero. | Reset register values to zero. | [
"Reset",
"register",
"values",
"to",
"zero",
"."
] | def reset_registers(self):
""" Reset register values to zero. """
self.reg_values = RegType.create_dict(lambda: [0] * INIT_REG_MAX) | [
"def",
"reset_registers",
"(",
"self",
")",
":",
"self",
".",
"reg_values",
"=",
"RegType",
".",
"create_dict",
"(",
"lambda",
":",
"[",
"0",
"]",
"*",
"INIT_REG_MAX",
")"
] | https://github.com/bristolcrypto/SPDZ-2/blob/721abfae849625a02ea49aabc534f9cf41ca643f/Compiler/program.py#L698-L700 | ||
Harick1/caffe-yolo | eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3 | tools/extra/extract_seconds.py | python | get_log_created_year | (input_file) | return log_created_year | Get year from log file system timestamp | Get year from log file system timestamp | [
"Get",
"year",
"from",
"log",
"file",
"system",
"timestamp"
] | def get_log_created_year(input_file):
"""Get year from log file system timestamp
"""
log_created_time = os.path.getctime(input_file)
log_created_year = datetime.datetime.fromtimestamp(log_created_time).year
return log_created_year | [
"def",
"get_log_created_year",
"(",
"input_file",
")",
":",
"log_created_time",
"=",
"os",
".",
"path",
".",
"getctime",
"(",
"input_file",
")",
"log_created_year",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"log_created_time",
")",
".",
"year",
"return",
"log_created_year"
] | https://github.com/Harick1/caffe-yolo/blob/eea92bf3ddfe4d0ff6b0b3ba9b15c029a83ed9a3/tools/extra/extract_seconds.py#L22-L28 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/hook.py | python | HookModule.resource_group | (self) | return self.__resource_group | The resource group that implements the hook, if any. | The resource group that implements the hook, if any. | [
"The",
"resource",
"group",
"that",
"implements",
"the",
"hook",
"if",
"any",
"."
] | def resource_group(self):
"""The resource group that implements the hook, if any."""
return self.__resource_group | [
"def",
"resource_group",
"(",
"self",
")",
":",
"return",
"self",
".",
"__resource_group"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/resource_manager/hook.py#L215-L217 | |
cms-sw/cmssw | fd9de012d503d3405420bcbeec0ec879baa57cf2 | FWCore/ParameterSet/python/Mixins.py | python | _Parameterizable.parameters_ | (self) | return result | Returns a dictionary of copies of the user-set parameters | Returns a dictionary of copies of the user-set parameters | [
"Returns",
"a",
"dictionary",
"of",
"copies",
"of",
"the",
"user",
"-",
"set",
"parameters"
] | def parameters_(self):
"""Returns a dictionary of copies of the user-set parameters"""
import copy
result = dict()
for name in self.parameterNames_():
result[name]=copy.deepcopy(self.__dict__[name])
return result | [
"def",
"parameters_",
"(",
"self",
")",
":",
"import",
"copy",
"result",
"=",
"dict",
"(",
")",
"for",
"name",
"in",
"self",
".",
"parameterNames_",
"(",
")",
":",
"result",
"[",
"name",
"]",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"__dict__",
"[",
"name",
"]",
")",
"return",
"result"
] | https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/FWCore/ParameterSet/python/Mixins.py#L227-L233 | |
NVIDIA/DALI | bf16cc86ba8f091b145f91962f21fe1b6aff243d | dali/python/nvidia/dali/plugin/mxnet.py | python | _DALIMXNetIteratorBase.next | (self) | return self.__next__() | Returns the next batch of data. | Returns the next batch of data. | [
"Returns",
"the",
"next",
"batch",
"of",
"data",
"."
] | def next(self):
"""
Returns the next batch of data.
"""
return self.__next__() | [
"def",
"next",
"(",
"self",
")",
":",
"return",
"self",
".",
"__next__",
"(",
")"
] | https://github.com/NVIDIA/DALI/blob/bf16cc86ba8f091b145f91962f21fe1b6aff243d/dali/python/nvidia/dali/plugin/mxnet.py#L99-L103 | |
toggl-open-source/toggldesktop | 91865205885531cc8fd9e8d613dad49d625d56e7 | third_party/cpplint/cpplint.py | python | _SetOutputFormat | (output_format) | Sets the module's output format. | Sets the module's output format. | [
"Sets",
"the",
"module",
"s",
"output",
"format",
"."
] | def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format) | [
"def",
"_SetOutputFormat",
"(",
"output_format",
")",
":",
"_cpplint_state",
".",
"SetOutputFormat",
"(",
"output_format",
")"
] | https://github.com/toggl-open-source/toggldesktop/blob/91865205885531cc8fd9e8d613dad49d625d56e7/third_party/cpplint/cpplint.py#L856-L858 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/server/TNonblockingServer.py | python | Connection.read | (self) | Reads data from stream and switch state. | Reads data from stream and switch state. | [
"Reads",
"data",
"from",
"stream",
"and",
"switch",
"state",
"."
] | def read(self):
"""Reads data from stream and switch state."""
assert self.status in (WAIT_LEN, WAIT_MESSAGE)
assert not self.received
buf_size = 8192
first = True
done = False
while not done:
read = self.socket.recv(buf_size)
rlen = len(read)
done = rlen < buf_size
self._rbuf += read
if first and rlen == 0:
if self.status != WAIT_LEN or self._rbuf:
logger.error('could not read frame from socket')
else:
logger.debug('read zero length. client might have disconnected')
self.close()
while len(self._rbuf) >= self._reading.end:
if self._reading.is_header:
mlen, = struct.unpack('!i', self._rbuf[:4])
self._reading = Message(self._reading.end, mlen, False)
self.status = WAIT_MESSAGE
else:
self._reading.buffer = self._rbuf
self.received.append(self._reading)
self._rbuf = self._rbuf[self._reading.end:]
self._reading = Message(0, 4, True)
first = False
if self.received:
self.status = WAIT_PROCESS
break
self.remaining = not done | [
"def",
"read",
"(",
"self",
")",
":",
"assert",
"self",
".",
"status",
"in",
"(",
"WAIT_LEN",
",",
"WAIT_MESSAGE",
")",
"assert",
"not",
"self",
".",
"received",
"buf_size",
"=",
"8192",
"first",
"=",
"True",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"read",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"buf_size",
")",
"rlen",
"=",
"len",
"(",
"read",
")",
"done",
"=",
"rlen",
"<",
"buf_size",
"self",
".",
"_rbuf",
"+=",
"read",
"if",
"first",
"and",
"rlen",
"==",
"0",
":",
"if",
"self",
".",
"status",
"!=",
"WAIT_LEN",
"or",
"self",
".",
"_rbuf",
":",
"logger",
".",
"error",
"(",
"'could not read frame from socket'",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'read zero length. client might have disconnected'",
")",
"self",
".",
"close",
"(",
")",
"while",
"len",
"(",
"self",
".",
"_rbuf",
")",
">=",
"self",
".",
"_reading",
".",
"end",
":",
"if",
"self",
".",
"_reading",
".",
"is_header",
":",
"mlen",
",",
"=",
"struct",
".",
"unpack",
"(",
"'!i'",
",",
"self",
".",
"_rbuf",
"[",
":",
"4",
"]",
")",
"self",
".",
"_reading",
"=",
"Message",
"(",
"self",
".",
"_reading",
".",
"end",
",",
"mlen",
",",
"False",
")",
"self",
".",
"status",
"=",
"WAIT_MESSAGE",
"else",
":",
"self",
".",
"_reading",
".",
"buffer",
"=",
"self",
".",
"_rbuf",
"self",
".",
"received",
".",
"append",
"(",
"self",
".",
"_reading",
")",
"self",
".",
"_rbuf",
"=",
"self",
".",
"_rbuf",
"[",
"self",
".",
"_reading",
".",
"end",
":",
"]",
"self",
".",
"_reading",
"=",
"Message",
"(",
"0",
",",
"4",
",",
"True",
")",
"first",
"=",
"False",
"if",
"self",
".",
"received",
":",
"self",
".",
"status",
"=",
"WAIT_PROCESS",
"break",
"self",
".",
"remaining",
"=",
"not",
"done"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/thrift/server/TNonblockingServer.py#L133-L165 | ||
mongodb/mongo-cxx-driver | eb86512b05be20d2f51d53ba9b860c709e0799b3 | etc/clang_format.py | python | callo | (args) | return check_output(args) | Call a program, and capture its output | Call a program, and capture its output | [
"Call",
"a",
"program",
"and",
"capture",
"its",
"output"
] | def callo(args):
"""Call a program, and capture its output
"""
return check_output(args) | [
"def",
"callo",
"(",
"args",
")",
":",
"return",
"check_output",
"(",
"args",
")"
] | https://github.com/mongodb/mongo-cxx-driver/blob/eb86512b05be20d2f51d53ba9b860c709e0799b3/etc/clang_format.py#L110-L113 | |
wesnoth/wesnoth | 6ccac5a5e8ff75303c9190c0da60580925cb32c0 | data/tools/wesnoth/wmlparser.py | python | Parser.parse_stream | (self, stream, binary = False) | Set the parser to parse from a file object. | Set the parser to parse from a file object. | [
"Set",
"the",
"parser",
"to",
"parse",
"from",
"a",
"file",
"object",
"."
] | def parse_stream(self, stream, binary = False):
"""
Set the parser to parse from a file object.
"""
text = stream.read()
if not binary:
text = text.replace("\r\n", "\n").replace("\t", " ").replace("\r", "\n")
self.push_text("inline", text) | [
"def",
"parse_stream",
"(",
"self",
",",
"stream",
",",
"binary",
"=",
"False",
")",
":",
"text",
"=",
"stream",
".",
"read",
"(",
")",
"if",
"not",
"binary",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"\"\\r\\n\"",
",",
"\"\\n\"",
")",
".",
"replace",
"(",
"\"\\t\"",
",",
"\" \"",
")",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\\n\"",
")",
"self",
".",
"push_text",
"(",
"\"inline\"",
",",
"text",
")"
] | https://github.com/wesnoth/wesnoth/blob/6ccac5a5e8ff75303c9190c0da60580925cb32c0/data/tools/wesnoth/wmlparser.py#L134-L141 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/hooks.py | python | BaseEventHooks.register_first | (self, event_name, handler, unique_id=None,
unique_id_uses_count=False) | Register an event handler to be called first for an event.
All event handlers registered with ``register_first()`` will
be called before handlers registered with ``register()`` and
``register_last()``. | Register an event handler to be called first for an event. | [
"Register",
"an",
"event",
"handler",
"to",
"be",
"called",
"first",
"for",
"an",
"event",
"."
] | def register_first(self, event_name, handler, unique_id=None,
unique_id_uses_count=False):
"""Register an event handler to be called first for an event.
All event handlers registered with ``register_first()`` will
be called before handlers registered with ``register()`` and
``register_last()``.
"""
self._verify_and_register(event_name, handler, unique_id,
register_method=self._register_first,
unique_id_uses_count=unique_id_uses_count) | [
"def",
"register_first",
"(",
"self",
",",
"event_name",
",",
"handler",
",",
"unique_id",
"=",
"None",
",",
"unique_id_uses_count",
"=",
"False",
")",
":",
"self",
".",
"_verify_and_register",
"(",
"event_name",
",",
"handler",
",",
"unique_id",
",",
"register_method",
"=",
"self",
".",
"_register_first",
",",
"unique_id_uses_count",
"=",
"unique_id_uses_count",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/botocore/hooks.py#L103-L114 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/piectrl.py | python | PieCtrl.DrawParts | (self, dc, cx, cy, w, h) | Draws the :class:`PieCtrl` external edges.
:param `dc`: an instance of :class:`DC`;
:param `cx`: the part `x` coordinate;
:param `cy`: the part `y` coordinate;
:param `w`: the control's width;
:param `h`: the control's height. | Draws the :class:`PieCtrl` external edges. | [
"Draws",
"the",
":",
"class",
":",
"PieCtrl",
"external",
"edges",
"."
] | def DrawParts(self, dc, cx, cy, w, h):
"""
Draws the :class:`PieCtrl` external edges.
:param `dc`: an instance of :class:`DC`;
:param `cx`: the part `x` coordinate;
:param `cy`: the part `y` coordinate;
:param `w`: the control's width;
:param `h`: the control's height.
"""
angles = self.GetPartAngles()
oldpen = dc.GetPen()
if self._showedges:
dc.SetPen(wx.BLACK_PEN)
for ii in xrange(len(angles)):
if ii > 0:
if not self._showedges:
dc.SetPen(wx.Pen(self._series[ii-1].GetColour()))
dc.SetBrush(wx.Brush(self._series[ii-1].GetColour()))
if angles[ii-1] != angles[ii]:
dc.DrawEllipticArc(0, int((1-sin(self._angle))*(h/2)+cy), w,
int(h*sin(self._angle)),
angles[ii-1]+self._rotationangle/pi*180,
angles[ii]+self._rotationangle/pi*180)
if len(self._series) == 1:
dc.SetBrush(wx.Brush(self._series[0].GetColour()))
dc.DrawEllipticArc(0, int((1-sin(self._angle))*(h/2)+cy), w,
int(h*sin(self._angle)), 0, 360)
dc.SetPen(oldpen) | [
"def",
"DrawParts",
"(",
"self",
",",
"dc",
",",
"cx",
",",
"cy",
",",
"w",
",",
"h",
")",
":",
"angles",
"=",
"self",
".",
"GetPartAngles",
"(",
")",
"oldpen",
"=",
"dc",
".",
"GetPen",
"(",
")",
"if",
"self",
".",
"_showedges",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"BLACK_PEN",
")",
"for",
"ii",
"in",
"xrange",
"(",
"len",
"(",
"angles",
")",
")",
":",
"if",
"ii",
">",
"0",
":",
"if",
"not",
"self",
".",
"_showedges",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"self",
".",
"_series",
"[",
"ii",
"-",
"1",
"]",
".",
"GetColour",
"(",
")",
")",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"self",
".",
"_series",
"[",
"ii",
"-",
"1",
"]",
".",
"GetColour",
"(",
")",
")",
")",
"if",
"angles",
"[",
"ii",
"-",
"1",
"]",
"!=",
"angles",
"[",
"ii",
"]",
":",
"dc",
".",
"DrawEllipticArc",
"(",
"0",
",",
"int",
"(",
"(",
"1",
"-",
"sin",
"(",
"self",
".",
"_angle",
")",
")",
"*",
"(",
"h",
"/",
"2",
")",
"+",
"cy",
")",
",",
"w",
",",
"int",
"(",
"h",
"*",
"sin",
"(",
"self",
".",
"_angle",
")",
")",
",",
"angles",
"[",
"ii",
"-",
"1",
"]",
"+",
"self",
".",
"_rotationangle",
"/",
"pi",
"*",
"180",
",",
"angles",
"[",
"ii",
"]",
"+",
"self",
".",
"_rotationangle",
"/",
"pi",
"*",
"180",
")",
"if",
"len",
"(",
"self",
".",
"_series",
")",
"==",
"1",
":",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"self",
".",
"_series",
"[",
"0",
"]",
".",
"GetColour",
"(",
")",
")",
")",
"dc",
".",
"DrawEllipticArc",
"(",
"0",
",",
"int",
"(",
"(",
"1",
"-",
"sin",
"(",
"self",
".",
"_angle",
")",
")",
"*",
"(",
"h",
"/",
"2",
")",
"+",
"cy",
")",
",",
"w",
",",
"int",
"(",
"h",
"*",
"sin",
"(",
"self",
".",
"_angle",
")",
")",
",",
"0",
",",
"360",
")",
"dc",
".",
"SetPen",
"(",
"oldpen",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/piectrl.py#L650-L689 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/package_index.py | python | ContentChecker.is_valid | (self) | return True | Check the hash. Return False if validation fails. | Check the hash. Return False if validation fails. | [
"Check",
"the",
"hash",
".",
"Return",
"False",
"if",
"validation",
"fails",
"."
] | def is_valid(self):
"""
Check the hash. Return False if validation fails.
"""
return True | [
"def",
"is_valid",
"(",
"self",
")",
":",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/package_index.py#L252-L256 | |
bigartm/bigartm | 47e37f982de87aa67bfd475ff1f39da696b181b3 | 3rdparty/protobuf-3.0.0/python/google/protobuf/internal/python_message.py | python | _DefaultValueConstructorForField | (field) | return MakeScalarDefault | Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference. | Returns a function which returns a default value for a field. | [
"Returns",
"a",
"function",
"which",
"returns",
"a",
"default",
"value",
"for",
"a",
"field",
"."
] | def _DefaultValueConstructorForField(field):
"""Returns a function which returns a default value for a field.
Args:
field: FieldDescriptor object for this field.
The returned function has one argument:
message: Message instance containing this field, or a weakref proxy
of same.
That function in turn returns a default value for this field. The default
value may refer back to |message| via a weak reference.
"""
if _IsMapField(field):
return _GetInitializeDefaultForMap(field)
if field.label == _FieldDescriptor.LABEL_REPEATED:
if field.has_default_value and field.default_value != []:
raise ValueError('Repeated field default value not empty list: %s' % (
field.default_value))
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# We can't look at _concrete_class yet since it might not have
# been set. (Depends on order in which we initialize the classes).
message_type = field.message_type
def MakeRepeatedMessageDefault(message):
return containers.RepeatedCompositeFieldContainer(
message._listener_for_children, field.message_type)
return MakeRepeatedMessageDefault
else:
type_checker = type_checkers.GetTypeChecker(field)
def MakeRepeatedScalarDefault(message):
return containers.RepeatedScalarFieldContainer(
message._listener_for_children, type_checker)
return MakeRepeatedScalarDefault
if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
# _concrete_class may not yet be initialized.
message_type = field.message_type
def MakeSubMessageDefault(message):
result = message_type._concrete_class()
result._SetListener(
_OneofListener(message, field)
if field.containing_oneof is not None
else message._listener_for_children)
return result
return MakeSubMessageDefault
def MakeScalarDefault(message):
# TODO(protobuf-team): This may be broken since there may not be
# default_value. Combine with has_default_value somehow.
return field.default_value
return MakeScalarDefault | [
"def",
"_DefaultValueConstructorForField",
"(",
"field",
")",
":",
"if",
"_IsMapField",
"(",
"field",
")",
":",
"return",
"_GetInitializeDefaultForMap",
"(",
"field",
")",
"if",
"field",
".",
"label",
"==",
"_FieldDescriptor",
".",
"LABEL_REPEATED",
":",
"if",
"field",
".",
"has_default_value",
"and",
"field",
".",
"default_value",
"!=",
"[",
"]",
":",
"raise",
"ValueError",
"(",
"'Repeated field default value not empty list: %s'",
"%",
"(",
"field",
".",
"default_value",
")",
")",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# We can't look at _concrete_class yet since it might not have",
"# been set. (Depends on order in which we initialize the classes).",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeRepeatedMessageDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedCompositeFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"field",
".",
"message_type",
")",
"return",
"MakeRepeatedMessageDefault",
"else",
":",
"type_checker",
"=",
"type_checkers",
".",
"GetTypeChecker",
"(",
"field",
")",
"def",
"MakeRepeatedScalarDefault",
"(",
"message",
")",
":",
"return",
"containers",
".",
"RepeatedScalarFieldContainer",
"(",
"message",
".",
"_listener_for_children",
",",
"type_checker",
")",
"return",
"MakeRepeatedScalarDefault",
"if",
"field",
".",
"cpp_type",
"==",
"_FieldDescriptor",
".",
"CPPTYPE_MESSAGE",
":",
"# _concrete_class may not yet be initialized.",
"message_type",
"=",
"field",
".",
"message_type",
"def",
"MakeSubMessageDefault",
"(",
"message",
")",
":",
"result",
"=",
"message_type",
".",
"_concrete_class",
"(",
")",
"result",
".",
"_SetListener",
"(",
"_OneofListener",
"(",
"message",
",",
"field",
")",
"if",
"field",
".",
"containing_oneof",
"is",
"not",
"None",
"else",
"message",
".",
"_listener_for_children",
")",
"return",
"result",
"return",
"MakeSubMessageDefault",
"def",
"MakeScalarDefault",
"(",
"message",
")",
":",
"# TODO(protobuf-team): This may be broken since there may not be",
"# default_value. Combine with has_default_value somehow.",
"return",
"field",
".",
"default_value",
"return",
"MakeScalarDefault"
] | https://github.com/bigartm/bigartm/blob/47e37f982de87aa67bfd475ff1f39da696b181b3/3rdparty/protobuf-3.0.0/python/google/protobuf/internal/python_message.py#L392-L444 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/cherrypy/lib/sessions.py | python | save | () | Save any changed session data. | Save any changed session data. | [
"Save",
"any",
"changed",
"session",
"data",
"."
] | def save():
"""Save any changed session data."""
if not hasattr(cherrypy.serving, "session"):
return
request = cherrypy.serving.request
response = cherrypy.serving.response
# Guard against running twice
if hasattr(request, "_sessionsaved"):
return
request._sessionsaved = True
if response.stream:
# If the body is being streamed, we have to save the data
# *after* the response has been written out
request.hooks.attach('on_end_request', cherrypy.session.save)
else:
# If the body is not being streamed, we save the data now
# (so we can release the lock).
if isinstance(response.body, types.GeneratorType):
response.collapse_body()
cherrypy.session.save() | [
"def",
"save",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"cherrypy",
".",
"serving",
",",
"\"session\"",
")",
":",
"return",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"response",
"=",
"cherrypy",
".",
"serving",
".",
"response",
"# Guard against running twice",
"if",
"hasattr",
"(",
"request",
",",
"\"_sessionsaved\"",
")",
":",
"return",
"request",
".",
"_sessionsaved",
"=",
"True",
"if",
"response",
".",
"stream",
":",
"# If the body is being streamed, we have to save the data",
"# *after* the response has been written out",
"request",
".",
"hooks",
".",
"attach",
"(",
"'on_end_request'",
",",
"cherrypy",
".",
"session",
".",
"save",
")",
"else",
":",
"# If the body is not being streamed, we save the data now",
"# (so we can release the lock).",
"if",
"isinstance",
"(",
"response",
".",
"body",
",",
"types",
".",
"GeneratorType",
")",
":",
"response",
".",
"collapse_body",
"(",
")",
"cherrypy",
".",
"session",
".",
"save",
"(",
")"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/cherrypy/lib/sessions.py#L676-L698 | ||
priyankchheda/algorithms | c361aa9071573fa9966d5b02d05e524815abcf2b | segment_tree/segment_tree.py | python | SegmentTree.range_query | (self, query_left, query_right) | return _range_sum(query_left, query_right, 0, self.size - 1, 0) | returns result for range queries | returns result for range queries | [
"returns",
"result",
"for",
"range",
"queries"
] | def range_query(self, query_left, query_right):
""" returns result for range queries """
def _range_sum(query_left, query_right, node_left, node_right, node_index):
""" internal recursive function """
if node_left > node_right:
return 0
if node_right < query_left or node_left > query_right:
return 0
if query_left <= node_left and query_right >= node_right:
return self.seg_tree[node_index]
mid = node_left + (node_right - node_left) // 2
left_child = node_index * 2 + 1
right_child = node_index * 2 + 2
left = _range_sum(query_left, query_right, node_left, mid, left_child)
right = _range_sum(query_left, query_right, mid + 1, node_right, right_child)
return self.func(left, right)
return _range_sum(query_left, query_right, 0, self.size - 1, 0) | [
"def",
"range_query",
"(",
"self",
",",
"query_left",
",",
"query_right",
")",
":",
"def",
"_range_sum",
"(",
"query_left",
",",
"query_right",
",",
"node_left",
",",
"node_right",
",",
"node_index",
")",
":",
"\"\"\" internal recursive function \"\"\"",
"if",
"node_left",
">",
"node_right",
":",
"return",
"0",
"if",
"node_right",
"<",
"query_left",
"or",
"node_left",
">",
"query_right",
":",
"return",
"0",
"if",
"query_left",
"<=",
"node_left",
"and",
"query_right",
">=",
"node_right",
":",
"return",
"self",
".",
"seg_tree",
"[",
"node_index",
"]",
"mid",
"=",
"node_left",
"+",
"(",
"node_right",
"-",
"node_left",
")",
"//",
"2",
"left_child",
"=",
"node_index",
"*",
"2",
"+",
"1",
"right_child",
"=",
"node_index",
"*",
"2",
"+",
"2",
"left",
"=",
"_range_sum",
"(",
"query_left",
",",
"query_right",
",",
"node_left",
",",
"mid",
",",
"left_child",
")",
"right",
"=",
"_range_sum",
"(",
"query_left",
",",
"query_right",
",",
"mid",
"+",
"1",
",",
"node_right",
",",
"right_child",
")",
"return",
"self",
".",
"func",
"(",
"left",
",",
"right",
")",
"return",
"_range_sum",
"(",
"query_left",
",",
"query_right",
",",
"0",
",",
"self",
".",
"size",
"-",
"1",
",",
"0",
")"
] | https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/segment_tree/segment_tree.py#L36-L57 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/richtext.py | python | RichTextObject.Dump | (*args, **kwargs) | return _richtext.RichTextObject_Dump(*args, **kwargs) | Dump(self) -> String | Dump(self) -> String | [
"Dump",
"(",
"self",
")",
"-",
">",
"String"
] | def Dump(*args, **kwargs):
"""Dump(self) -> String"""
return _richtext.RichTextObject_Dump(*args, **kwargs) | [
"def",
"Dump",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextObject_Dump",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L1250-L1252 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/polynomial/chebyshev.py | python | chebint | (cs, m=1, k=[], lbnd=0, scl=1) | return cs | Integrate a Chebyshev series.
Returns, as a C-series, the input C-series `cs`, integrated `m` times
from `lbnd` to `x`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `cs` is a sequence of
coefficients, from lowest order C-series "term" to highest, e.g.,
[1,2,3] represents the series :math:`T_0(x) + 2T_1(x) + 3T_2(x)`.
Parameters
----------
cs : array_like
1-d array of C-series coefficients, ordered from low to high.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
Returns
-------
S : ndarray
C-series coefficients of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or
``np.isscalar(scl) == False``.
See Also
--------
chebder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to :math:`1/a`
- perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "re-projected" onto the C-series basis set. Thus, typically,
the result of this function is "un-intuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> cs = (1,2,3)
>>> C.chebint(cs)
array([ 0.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,3)
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667,
0.00625 ])
>>> C.chebint(cs, k=3)
array([ 3.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,lbnd=-2)
array([ 8.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,scl=-2)
array([-1., 1., -1., -1.]) | Integrate a Chebyshev series. | [
"Integrate",
"a",
"Chebyshev",
"series",
"."
] | def chebint(cs, m=1, k=[], lbnd=0, scl=1):
"""
Integrate a Chebyshev series.
Returns, as a C-series, the input C-series `cs`, integrated `m` times
from `lbnd` to `x`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `cs` is a sequence of
coefficients, from lowest order C-series "term" to highest, e.g.,
[1,2,3] represents the series :math:`T_0(x) + 2T_1(x) + 3T_2(x)`.
Parameters
----------
cs : array_like
1-d array of C-series coefficients, ordered from low to high.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at zero
is the first value in the list, the value of the second integral
at zero is the second value, etc. If ``k == []`` (the default),
all constants are set to zero. If ``m == 1``, a single scalar can
be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
Returns
-------
S : ndarray
C-series coefficients of the integral.
Raises
------
ValueError
If ``m < 1``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or
``np.isscalar(scl) == False``.
See Also
--------
chebder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
:math:`dx = du/a`, so one will need to set `scl` equal to :math:`1/a`
- perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "re-projected" onto the C-series basis set. Thus, typically,
the result of this function is "un-intuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial import chebyshev as C
>>> cs = (1,2,3)
>>> C.chebint(cs)
array([ 0.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,3)
array([ 0.03125 , -0.1875 , 0.04166667, -0.05208333, 0.01041667,
0.00625 ])
>>> C.chebint(cs, k=3)
array([ 3.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,lbnd=-2)
array([ 8.5, -0.5, 0.5, 0.5])
>>> C.chebint(cs,scl=-2)
array([-1., 1., -1., -1.])
"""
cnt = int(m)
if not np.iterable(k):
k = [k]
if cnt != m:
raise ValueError, "The order of integration must be integer"
if cnt < 0 :
raise ValueError, "The order of integration must be non-negative"
if len(k) > cnt :
raise ValueError, "Too many integration constants"
# cs is a trimmed copy
[cs] = pu.as_series([cs])
if cnt == 0:
return cs
k = list(k) + [0]*(cnt - len(k))
for i in range(cnt) :
n = len(cs)
cs *= scl
if n == 1 and cs[0] == 0:
cs[0] += k[i]
else:
zs = _cseries_to_zseries(cs)
zs = _zseries_int(zs)
cs = _zseries_to_cseries(zs)
cs[0] += k[i] - chebval(lbnd, cs)
return cs | [
"def",
"chebint",
"(",
"cs",
",",
"m",
"=",
"1",
",",
"k",
"=",
"[",
"]",
",",
"lbnd",
"=",
"0",
",",
"scl",
"=",
"1",
")",
":",
"cnt",
"=",
"int",
"(",
"m",
")",
"if",
"not",
"np",
".",
"iterable",
"(",
"k",
")",
":",
"k",
"=",
"[",
"k",
"]",
"if",
"cnt",
"!=",
"m",
":",
"raise",
"ValueError",
",",
"\"The order of integration must be integer\"",
"if",
"cnt",
"<",
"0",
":",
"raise",
"ValueError",
",",
"\"The order of integration must be non-negative\"",
"if",
"len",
"(",
"k",
")",
">",
"cnt",
":",
"raise",
"ValueError",
",",
"\"Too many integration constants\"",
"# cs is a trimmed copy",
"[",
"cs",
"]",
"=",
"pu",
".",
"as_series",
"(",
"[",
"cs",
"]",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"cs",
"k",
"=",
"list",
"(",
"k",
")",
"+",
"[",
"0",
"]",
"*",
"(",
"cnt",
"-",
"len",
"(",
"k",
")",
")",
"for",
"i",
"in",
"range",
"(",
"cnt",
")",
":",
"n",
"=",
"len",
"(",
"cs",
")",
"cs",
"*=",
"scl",
"if",
"n",
"==",
"1",
"and",
"cs",
"[",
"0",
"]",
"==",
"0",
":",
"cs",
"[",
"0",
"]",
"+=",
"k",
"[",
"i",
"]",
"else",
":",
"zs",
"=",
"_cseries_to_zseries",
"(",
"cs",
")",
"zs",
"=",
"_zseries_int",
"(",
"zs",
")",
"cs",
"=",
"_zseries_to_cseries",
"(",
"zs",
")",
"cs",
"[",
"0",
"]",
"+=",
"k",
"[",
"i",
"]",
"-",
"chebval",
"(",
"lbnd",
",",
"cs",
")",
"return",
"cs"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/polynomial/chebyshev.py#L912-L1016 | |
OpenGenus/cosmos | 1a94e8880068e51d571543be179c323936bd0936 | code/data_structures/src/hashs/bloom_filter/bloom_filter.py | python | bloomFilter.__init__ | (self, size=1000, hashFunctions=None) | Construct a bloom filter with size bits(default: 1000) and the associated hashFunctions.
Default hash function is i.e. hash(e)%size. | Construct a bloom filter with size bits(default: 1000) and the associated hashFunctions.
Default hash function is i.e. hash(e)%size. | [
"Construct",
"a",
"bloom",
"filter",
"with",
"size",
"bits",
"(",
"default",
":",
"1000",
")",
"and",
"the",
"associated",
"hashFunctions",
".",
"Default",
"hash",
"function",
"is",
"i",
".",
"e",
".",
"hash",
"(",
"e",
")",
"%size",
"."
] | def __init__(self, size=1000, hashFunctions=None):
""" Construct a bloom filter with size bits(default: 1000) and the associated hashFunctions.
Default hash function is i.e. hash(e)%size.
"""
self.bits = 0
self.M = size
if hashFunctions is None:
self.k = 1
self.hashFunctions = [lambda e, size: hash(e) % size]
else:
self.k = len(hashFunctions)
self.hashFunctions = hashFunctions | [
"def",
"__init__",
"(",
"self",
",",
"size",
"=",
"1000",
",",
"hashFunctions",
"=",
"None",
")",
":",
"self",
".",
"bits",
"=",
"0",
"self",
".",
"M",
"=",
"size",
"if",
"hashFunctions",
"is",
"None",
":",
"self",
".",
"k",
"=",
"1",
"self",
".",
"hashFunctions",
"=",
"[",
"lambda",
"e",
",",
"size",
":",
"hash",
"(",
"e",
")",
"%",
"size",
"]",
"else",
":",
"self",
".",
"k",
"=",
"len",
"(",
"hashFunctions",
")",
"self",
".",
"hashFunctions",
"=",
"hashFunctions"
] | https://github.com/OpenGenus/cosmos/blob/1a94e8880068e51d571543be179c323936bd0936/code/data_structures/src/hashs/bloom_filter/bloom_filter.py#L7-L18 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py | python | ParseResults.asXML | ( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ) | return "".join(out) | (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. | (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. | [
"(",
"Deprecated",
")",
"Returns",
"the",
"parse",
"results",
"as",
"XML",
".",
"Tags",
"are",
"created",
"for",
"tokens",
"and",
"lists",
"that",
"have",
"defined",
"results",
"names",
"."
] | def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
"""
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
"""
nl = "\n"
out = []
namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist)
nextLevelIndent = indent + " "
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
out += [ nl, indent, "<", selfTag, ">" ]
for i,res in enumerate(self.__toklist):
if isinstance(res,ParseResults):
if i in namedItems:
out += [ res.asXML(namedItems[i],
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
out += [ res.asXML(None,
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
# individual token, see if there is a name for it
resTag = None
if i in namedItems:
resTag = namedItems[i]
if not resTag:
if namedItemsOnly:
continue
else:
resTag = "ITEM"
xmlBodyText = _xml_escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
out += [ nl, indent, "</", selfTag, ">" ]
return "".join(out) | [
"def",
"asXML",
"(",
"self",
",",
"doctag",
"=",
"None",
",",
"namedItemsOnly",
"=",
"False",
",",
"indent",
"=",
"\"\"",
",",
"formatted",
"=",
"True",
")",
":",
"nl",
"=",
"\"\\n\"",
"out",
"=",
"[",
"]",
"namedItems",
"=",
"dict",
"(",
"(",
"v",
"[",
"1",
"]",
",",
"k",
")",
"for",
"(",
"k",
",",
"vlist",
")",
"in",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
"for",
"v",
"in",
"vlist",
")",
"nextLevelIndent",
"=",
"indent",
"+",
"\" \"",
"# collapse out indents if formatting is not desired",
"if",
"not",
"formatted",
":",
"indent",
"=",
"\"\"",
"nextLevelIndent",
"=",
"\"\"",
"nl",
"=",
"\"\"",
"selfTag",
"=",
"None",
"if",
"doctag",
"is",
"not",
"None",
":",
"selfTag",
"=",
"doctag",
"else",
":",
"if",
"self",
".",
"__name",
":",
"selfTag",
"=",
"self",
".",
"__name",
"if",
"not",
"selfTag",
":",
"if",
"namedItemsOnly",
":",
"return",
"\"\"",
"else",
":",
"selfTag",
"=",
"\"ITEM\"",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"<\"",
",",
"selfTag",
",",
"\">\"",
"]",
"for",
"i",
",",
"res",
"in",
"enumerate",
"(",
"self",
".",
"__toklist",
")",
":",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
":",
"if",
"i",
"in",
"namedItems",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"namedItems",
"[",
"i",
"]",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"None",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"# individual token, see if there is a name for it",
"resTag",
"=",
"None",
"if",
"i",
"in",
"namedItems",
":",
"resTag",
"=",
"namedItems",
"[",
"i",
"]",
"if",
"not",
"resTag",
":",
"if",
"namedItemsOnly",
":",
"continue",
"else",
":",
"resTag",
"=",
"\"ITEM\"",
"xmlBodyText",
"=",
"_xml_escape",
"(",
"_ustr",
"(",
"res",
")",
")",
"out",
"+=",
"[",
"nl",
",",
"nextLevelIndent",
",",
"\"<\"",
",",
"resTag",
",",
"\">\"",
",",
"xmlBodyText",
",",
"\"</\"",
",",
"resTag",
",",
"\">\"",
"]",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"</\"",
",",
"selfTag",
",",
"\">\"",
"]",
"return",
"\"\"",
".",
"join",
"(",
"out",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/setuptools/_vendor/pyparsing.py#L766-L825 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/_core.py | python | TextEntryBase.AutoCompleteFileNames | (*args, **kwargs) | return _core_.TextEntryBase_AutoCompleteFileNames(*args, **kwargs) | AutoCompleteFileNames(self) -> bool | AutoCompleteFileNames(self) -> bool | [
"AutoCompleteFileNames",
"(",
"self",
")",
"-",
">",
"bool"
] | def AutoCompleteFileNames(*args, **kwargs):
"""AutoCompleteFileNames(self) -> bool"""
return _core_.TextEntryBase_AutoCompleteFileNames(*args, **kwargs) | [
"def",
"AutoCompleteFileNames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"TextEntryBase_AutoCompleteFileNames",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13320-L13322 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | tools/telemetry/third_party/pyserial/serial/serialwin32.py | python | Win32Serial.setXON | (self, level=True) | \
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms! | \
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms! | [
"\\",
"Manually",
"control",
"flow",
"-",
"when",
"software",
"flow",
"control",
"is",
"enabled",
".",
"This",
"will",
"send",
"XON",
"(",
"true",
")",
"and",
"XOFF",
"(",
"false",
")",
"to",
"the",
"other",
"device",
".",
"WARNING",
":",
"this",
"function",
"is",
"not",
"portable",
"to",
"different",
"platforms!"
] | def setXON(self, level=True):
"""\
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
WARNING: this function is not portable to different platforms!
"""
if not self.hComPort: raise portNotOpenError
if level:
win32.EscapeCommFunction(self.hComPort, win32.SETXON)
else:
win32.EscapeCommFunction(self.hComPort, win32.SETXOFF) | [
"def",
"setXON",
"(",
"self",
",",
"level",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"hComPort",
":",
"raise",
"portNotOpenError",
"if",
"level",
":",
"win32",
".",
"EscapeCommFunction",
"(",
"self",
".",
"hComPort",
",",
"win32",
".",
"SETXON",
")",
"else",
":",
"win32",
".",
"EscapeCommFunction",
"(",
"self",
".",
"hComPort",
",",
"win32",
".",
"SETXOFF",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/serialwin32.py#L399-L409 | ||
baidu/tera | dbcd28af792d879d961bf9fc7eb60de81b437646 | src/sdk/python/TeraSdk.py | python | RowReader.ValueInt64 | (self) | return long(lib.tera_row_reader_value_int64(self.reader)) | Returns:
(long) 当前cell对应的value | Returns:
(long) 当前cell对应的value | [
"Returns",
":",
"(",
"long",
")",
"当前cell对应的value"
] | def ValueInt64(self):
"""
Returns:
(long) 当前cell对应的value
"""
return long(lib.tera_row_reader_value_int64(self.reader)) | [
"def",
"ValueInt64",
"(",
"self",
")",
":",
"return",
"long",
"(",
"lib",
".",
"tera_row_reader_value_int64",
"(",
"self",
".",
"reader",
")",
")"
] | https://github.com/baidu/tera/blob/dbcd28af792d879d961bf9fc7eb60de81b437646/src/sdk/python/TeraSdk.py#L773-L778 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py | python | Context.logical_and | (self, a, b) | return a.logical_and(b, context=self) | Applies the logical operation 'and' between each operand's digits.
The operands must be both logical numbers.
>>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Decimal('1')
>>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Decimal('1000')
>>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Decimal('10')
>>> ExtendedContext.logical_and(110, 1101)
Decimal('100')
>>> ExtendedContext.logical_and(Decimal(110), 1101)
Decimal('100')
>>> ExtendedContext.logical_and(110, Decimal(1101))
Decimal('100') | Applies the logical operation 'and' between each operand's digits. | [
"Applies",
"the",
"logical",
"operation",
"and",
"between",
"each",
"operand",
"s",
"digits",
"."
] | def logical_and(self, a, b):
"""Applies the logical operation 'and' between each operand's digits.
The operands must be both logical numbers.
>>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Decimal('0')
>>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Decimal('1')
>>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Decimal('1000')
>>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Decimal('10')
>>> ExtendedContext.logical_and(110, 1101)
Decimal('100')
>>> ExtendedContext.logical_and(Decimal(110), 1101)
Decimal('100')
>>> ExtendedContext.logical_and(110, Decimal(1101))
Decimal('100')
"""
a = _convert_other(a, raiseit=True)
return a.logical_and(b, context=self) | [
"def",
"logical_and",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"a",
"=",
"_convert_other",
"(",
"a",
",",
"raiseit",
"=",
"True",
")",
"return",
"a",
".",
"logical_and",
"(",
"b",
",",
"context",
"=",
"self",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/decimal.py#L4562-L4587 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/scipy/scipy/stats/_multivariate.py | python | invwishart_gen.mode | (self, df, scale) | return _squeeze_output(out) | Mode of the inverse Wishart distribution
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mode : float
The Mode of the distribution | Mode of the inverse Wishart distribution | [
"Mode",
"of",
"the",
"inverse",
"Wishart",
"distribution"
] | def mode(self, df, scale):
"""
Mode of the inverse Wishart distribution
Parameters
----------
%(_doc_default_callparams)s
Returns
-------
mode : float
The Mode of the distribution
"""
dim, df, scale = self._process_parameters(df, scale)
out = self._mode(dim, df, scale)
return _squeeze_output(out) | [
"def",
"mode",
"(",
"self",
",",
"df",
",",
"scale",
")",
":",
"dim",
",",
"df",
",",
"scale",
"=",
"self",
".",
"_process_parameters",
"(",
"df",
",",
"scale",
")",
"out",
"=",
"self",
".",
"_mode",
"(",
"dim",
",",
"df",
",",
"scale",
")",
"return",
"_squeeze_output",
"(",
"out",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/scipy/stats/_multivariate.py#L2422-L2438 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/telemetry/core/cros_interface.py | python | CrOSInterface.GetDeviceTypeName | (self) | return self.LsbReleaseValue(key='DEVICETYPE', default='CHROMEBOOK') | DEVICETYPE in /etc/lsb-release is CHROMEBOOK, CHROMEBIT, etc. | DEVICETYPE in /etc/lsb-release is CHROMEBOOK, CHROMEBIT, etc. | [
"DEVICETYPE",
"in",
"/",
"etc",
"/",
"lsb",
"-",
"release",
"is",
"CHROMEBOOK",
"CHROMEBIT",
"etc",
"."
] | def GetDeviceTypeName(self):
"""DEVICETYPE in /etc/lsb-release is CHROMEBOOK, CHROMEBIT, etc."""
return self.LsbReleaseValue(key='DEVICETYPE', default='CHROMEBOOK') | [
"def",
"GetDeviceTypeName",
"(",
"self",
")",
":",
"return",
"self",
".",
"LsbReleaseValue",
"(",
"key",
"=",
"'DEVICETYPE'",
",",
"default",
"=",
"'CHROMEBOOK'",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/telemetry/core/cros_interface.py#L520-L522 | |
scanner-research/scanner | 04a0c4b4196341995985acd729c0788aab823e1c | python/scannerpy/storage.py | python | StoredStream.committed | (self) | Check if a stream is completely materialized in storage.
A stream may exist, but not be committed if a Scanner job was run that was supposed to
output the stream, but the job failed for any reason. | Check if a stream is completely materialized in storage. | [
"Check",
"if",
"a",
"stream",
"is",
"completely",
"materialized",
"in",
"storage",
"."
] | def committed(self) -> bool:
"""Check if a stream is completely materialized in storage.
A stream may exist, but not be committed if a Scanner job was run that was supposed to
output the stream, but the job failed for any reason.
"""
raise NotImplementedError | [
"def",
"committed",
"(",
"self",
")",
"->",
"bool",
":",
"raise",
"NotImplementedError"
] | https://github.com/scanner-research/scanner/blob/04a0c4b4196341995985acd729c0788aab823e1c/python/scannerpy/storage.py#L102-L108 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/lib/io/file_io.py | python | FileIO.readline | (self) | return self._prepare_value(self._read_buf.readline()) | r"""Reads the next line, keeping \n. At EOF, returns ''. | r"""Reads the next line, keeping \n. At EOF, returns ''. | [
"r",
"Reads",
"the",
"next",
"line",
"keeping",
"\\",
"n",
".",
"At",
"EOF",
"returns",
"."
] | def readline(self):
r"""Reads the next line, keeping \n. At EOF, returns ''."""
self._preread_check()
return self._prepare_value(self._read_buf.readline()) | [
"def",
"readline",
"(",
"self",
")",
":",
"self",
".",
"_preread_check",
"(",
")",
"return",
"self",
".",
"_prepare_value",
"(",
"self",
".",
"_read_buf",
".",
"readline",
"(",
")",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/lib/io/file_io.py#L165-L168 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py | python | DNNLinearCombinedClassifier.__init__ | (self, # _joint_linear_weights pylint: disable=invalid-name
model_dir=None,
n_classes=2,
weight_column_name=None,
linear_feature_columns=None,
linear_optimizer=None,
_joint_linear_weights=False,
dnn_feature_columns=None,
dnn_optimizer=None,
dnn_hidden_units=None,
dnn_activation_fn=nn.relu,
dnn_dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
embedding_lr_multipliers=None,
input_layer_min_slice_size=None,
label_keys=None,
fix_global_step_increment_bug=False) | Constructs a DNNLinearCombinedClassifier instance.
Note: New users must set `fix_global_step_increment_bug=True` when creating
an estimator.
Args:
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator
to continue training a previously saved model.
n_classes: number of label classes. Default is binary classification.
Note that class labels are integers representing the class index (i.e.
values from 0 to n_classes-1). For arbitrary label values (e.g. string
labels), convert to class indices first.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training.
It will be multiplied by the loss of the example.
linear_feature_columns: An iterable containing all the feature columns
used by linear part of the model. All items in the set must be
instances of classes derived from `FeatureColumn`.
linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the linear part of the model. If `None`, will use a FTRL optimizer.
_joint_linear_weights: If True a single (possibly partitioned) variable
will be used to store the linear model weights. It's faster, but
requires all columns are sparse and have the 'sum' combiner.
dnn_feature_columns: An iterable containing all the feature columns used
by deep part of the model. All items in the set must be instances of
classes derived from `FeatureColumn`.
dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the deep part of the model. If `None`, will use an Adagrad optimizer.
dnn_hidden_units: List of hidden units per layer. All layers are fully
connected.
dnn_activation_fn: Activation function applied to each layer. If `None`,
will use `tf.nn.relu`.
dnn_dropout: When not None, the probability we will drop out
a given coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
tf.clip_by_global_norm for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: RunConfig object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and returns features and
labels which will be fed into the model.
embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to
a `float` multiplier. Multiplier will be used to multiply with
learning rate for the embedding variables.
input_layer_min_slice_size: Optional. The min slice size of input layer
partitions. If not provided, will use the default of 64M.
label_keys: Optional list of strings with size `[n_classes]` defining the
label vocabulary. Only supported for `n_classes` > 2.
fix_global_step_increment_bug: If `False`, the estimator needs two fit
steps to optimize both linear and dnn parts. If `True`, this bug is
fixed. New users must set this to `True`, but it the default value is
`False` for backwards compatibility.
Raises:
ValueError: If `n_classes` < 2.
ValueError: If both `linear_feature_columns` and `dnn_features_columns`
are empty at the same time. | Constructs a DNNLinearCombinedClassifier instance. | [
"Constructs",
"a",
"DNNLinearCombinedClassifier",
"instance",
"."
] | def __init__(self, # _joint_linear_weights pylint: disable=invalid-name
model_dir=None,
n_classes=2,
weight_column_name=None,
linear_feature_columns=None,
linear_optimizer=None,
_joint_linear_weights=False,
dnn_feature_columns=None,
dnn_optimizer=None,
dnn_hidden_units=None,
dnn_activation_fn=nn.relu,
dnn_dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
embedding_lr_multipliers=None,
input_layer_min_slice_size=None,
label_keys=None,
fix_global_step_increment_bug=False):
"""Constructs a DNNLinearCombinedClassifier instance.
Note: New users must set `fix_global_step_increment_bug=True` when creating
an estimator.
Args:
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator
to continue training a previously saved model.
n_classes: number of label classes. Default is binary classification.
Note that class labels are integers representing the class index (i.e.
values from 0 to n_classes-1). For arbitrary label values (e.g. string
labels), convert to class indices first.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training.
It will be multiplied by the loss of the example.
linear_feature_columns: An iterable containing all the feature columns
used by linear part of the model. All items in the set must be
instances of classes derived from `FeatureColumn`.
linear_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the linear part of the model. If `None`, will use a FTRL optimizer.
_joint_linear_weights: If True a single (possibly partitioned) variable
will be used to store the linear model weights. It's faster, but
requires all columns are sparse and have the 'sum' combiner.
dnn_feature_columns: An iterable containing all the feature columns used
by deep part of the model. All items in the set must be instances of
classes derived from `FeatureColumn`.
dnn_optimizer: An instance of `tf.Optimizer` used to apply gradients to
the deep part of the model. If `None`, will use an Adagrad optimizer.
dnn_hidden_units: List of hidden units per layer. All layers are fully
connected.
dnn_activation_fn: Activation function applied to each layer. If `None`,
will use `tf.nn.relu`.
dnn_dropout: When not None, the probability we will drop out
a given coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
tf.clip_by_global_norm for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: RunConfig object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and returns features and
labels which will be fed into the model.
embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to
a `float` multiplier. Multiplier will be used to multiply with
learning rate for the embedding variables.
input_layer_min_slice_size: Optional. The min slice size of input layer
partitions. If not provided, will use the default of 64M.
label_keys: Optional list of strings with size `[n_classes]` defining the
label vocabulary. Only supported for `n_classes` > 2.
fix_global_step_increment_bug: If `False`, the estimator needs two fit
steps to optimize both linear and dnn parts. If `True`, this bug is
fixed. New users must set this to `True`, but it the default value is
`False` for backwards compatibility.
Raises:
ValueError: If `n_classes` < 2.
ValueError: If both `linear_feature_columns` and `dnn_features_columns`
are empty at the same time.
"""
head = head_lib.multi_class_head(
n_classes=n_classes,
weight_column_name=weight_column_name,
enable_centered_bias=enable_centered_bias,
label_keys=label_keys)
linear_feature_columns = tuple(linear_feature_columns or [])
dnn_feature_columns = tuple(dnn_feature_columns or [])
self._feature_columns = linear_feature_columns + dnn_feature_columns
if not self._feature_columns:
raise ValueError("Either linear_feature_columns or dnn_feature_columns "
"must be defined.")
# TODO(b/35922130): Replace with `input_layer_partitioner` arg.
input_layer_partitioner = None
if input_layer_min_slice_size is not None:
input_layer_partitioner = (
partitioned_variables.min_max_variable_partitioner(
max_partitions=config.num_ps_replicas if config else 0,
min_slice_size=input_layer_min_slice_size))
super(DNNLinearCombinedClassifier, self).__init__(
model_fn=_dnn_linear_combined_model_fn,
model_dir=model_dir,
config=config,
params={
"head": head,
"linear_feature_columns": linear_feature_columns,
"linear_optimizer": linear_optimizer,
"joint_linear_weights": _joint_linear_weights,
"dnn_feature_columns": dnn_feature_columns,
"dnn_optimizer": dnn_optimizer,
"dnn_hidden_units": dnn_hidden_units,
"dnn_activation_fn": dnn_activation_fn,
"dnn_dropout": dnn_dropout,
"gradient_clip_norm": gradient_clip_norm,
"embedding_lr_multipliers": embedding_lr_multipliers,
"input_layer_partitioner": input_layer_partitioner,
"fix_global_step_increment_bug": fix_global_step_increment_bug,
},
feature_engineering_fn=feature_engineering_fn) | [
"def",
"__init__",
"(",
"self",
",",
"# _joint_linear_weights pylint: disable=invalid-name",
"model_dir",
"=",
"None",
",",
"n_classes",
"=",
"2",
",",
"weight_column_name",
"=",
"None",
",",
"linear_feature_columns",
"=",
"None",
",",
"linear_optimizer",
"=",
"None",
",",
"_joint_linear_weights",
"=",
"False",
",",
"dnn_feature_columns",
"=",
"None",
",",
"dnn_optimizer",
"=",
"None",
",",
"dnn_hidden_units",
"=",
"None",
",",
"dnn_activation_fn",
"=",
"nn",
".",
"relu",
",",
"dnn_dropout",
"=",
"None",
",",
"gradient_clip_norm",
"=",
"None",
",",
"enable_centered_bias",
"=",
"False",
",",
"config",
"=",
"None",
",",
"feature_engineering_fn",
"=",
"None",
",",
"embedding_lr_multipliers",
"=",
"None",
",",
"input_layer_min_slice_size",
"=",
"None",
",",
"label_keys",
"=",
"None",
",",
"fix_global_step_increment_bug",
"=",
"False",
")",
":",
"head",
"=",
"head_lib",
".",
"multi_class_head",
"(",
"n_classes",
"=",
"n_classes",
",",
"weight_column_name",
"=",
"weight_column_name",
",",
"enable_centered_bias",
"=",
"enable_centered_bias",
",",
"label_keys",
"=",
"label_keys",
")",
"linear_feature_columns",
"=",
"tuple",
"(",
"linear_feature_columns",
"or",
"[",
"]",
")",
"dnn_feature_columns",
"=",
"tuple",
"(",
"dnn_feature_columns",
"or",
"[",
"]",
")",
"self",
".",
"_feature_columns",
"=",
"linear_feature_columns",
"+",
"dnn_feature_columns",
"if",
"not",
"self",
".",
"_feature_columns",
":",
"raise",
"ValueError",
"(",
"\"Either linear_feature_columns or dnn_feature_columns \"",
"\"must be defined.\"",
")",
"# TODO(b/35922130): Replace with `input_layer_partitioner` arg.",
"input_layer_partitioner",
"=",
"None",
"if",
"input_layer_min_slice_size",
"is",
"not",
"None",
":",
"input_layer_partitioner",
"=",
"(",
"partitioned_variables",
".",
"min_max_variable_partitioner",
"(",
"max_partitions",
"=",
"config",
".",
"num_ps_replicas",
"if",
"config",
"else",
"0",
",",
"min_slice_size",
"=",
"input_layer_min_slice_size",
")",
")",
"super",
"(",
"DNNLinearCombinedClassifier",
",",
"self",
")",
".",
"__init__",
"(",
"model_fn",
"=",
"_dnn_linear_combined_model_fn",
",",
"model_dir",
"=",
"model_dir",
",",
"config",
"=",
"config",
",",
"params",
"=",
"{",
"\"head\"",
":",
"head",
",",
"\"linear_feature_columns\"",
":",
"linear_feature_columns",
",",
"\"linear_optimizer\"",
":",
"linear_optimizer",
",",
"\"joint_linear_weights\"",
":",
"_joint_linear_weights",
",",
"\"dnn_feature_columns\"",
":",
"dnn_feature_columns",
",",
"\"dnn_optimizer\"",
":",
"dnn_optimizer",
",",
"\"dnn_hidden_units\"",
":",
"dnn_hidden_units",
",",
"\"dnn_activation_fn\"",
":",
"dnn_activation_fn",
",",
"\"dnn_dropout\"",
":",
"dnn_dropout",
",",
"\"gradient_clip_norm\"",
":",
"gradient_clip_norm",
",",
"\"embedding_lr_multipliers\"",
":",
"embedding_lr_multipliers",
",",
"\"input_layer_partitioner\"",
":",
"input_layer_partitioner",
",",
"\"fix_global_step_increment_bug\"",
":",
"fix_global_step_increment_bug",
",",
"}",
",",
"feature_engineering_fn",
"=",
"feature_engineering_fn",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py#L590-L711 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/plan/robotcspace.py | python | RobotCSpace.sendPathToController | (self,path,controller) | Given a planned CSpace path 'path' and a SimRobotController 'controller',
sends the path so that it is executed correctly by the controller (this assumes
a fully actuated robot). | Given a planned CSpace path 'path' and a SimRobotController 'controller',
sends the path so that it is executed correctly by the controller (this assumes
a fully actuated robot). | [
"Given",
"a",
"planned",
"CSpace",
"path",
"path",
"and",
"a",
"SimRobotController",
"controller",
"sends",
"the",
"path",
"so",
"that",
"it",
"is",
"executed",
"correctly",
"by",
"the",
"controller",
"(",
"this",
"assumes",
"a",
"fully",
"actuated",
"robot",
")",
"."
] | def sendPathToController(self,path,controller):
"""Given a planned CSpace path 'path' and a SimRobotController 'controller',
sends the path so that it is executed correctly by the controller (this assumes
a fully actuated robot)."""
controller.setMilestone(path[0])
for q in path[1:]:
controller.appendMilestoneLinear(q) | [
"def",
"sendPathToController",
"(",
"self",
",",
"path",
",",
"controller",
")",
":",
"controller",
".",
"setMilestone",
"(",
"path",
"[",
"0",
"]",
")",
"for",
"q",
"in",
"path",
"[",
"1",
":",
"]",
":",
"controller",
".",
"appendMilestoneLinear",
"(",
"q",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/plan/robotcspace.py#L123-L129 | ||
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/shutil.py | python | copy | (src, dst) | Copy data and mode bits ("cp src dst").
The destination may be a directory. | Copy data and mode bits ("cp src dst"). | [
"Copy",
"data",
"and",
"mode",
"bits",
"(",
"cp",
"src",
"dst",
")",
"."
] | def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dst",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
")",
")",
"copyfile",
"(",
"src",
",",
"dst",
")",
"copymode",
"(",
"src",
",",
"dst",
")"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/shutil.py#L130-L139 | ||
microsoft/ivy | 9f3c7ecc0b2383129fdd0953e10890d98d09a82d | ivy/ui_extensions_api.py | python | ExtensionPoint.__call__ | (self, context, *args, **kwargs) | return results | Run all callbacks, return a list with results.
Exceptions in callbacks are printed using IPython's
showtraceback, and their result is ignored.
If not running under IPython, exceptions are raised. | Run all callbacks, return a list with results. | [
"Run",
"all",
"callbacks",
"return",
"a",
"list",
"with",
"results",
"."
] | def __call__(self, context, *args, **kwargs):
"""
Run all callbacks, return a list with results.
Exceptions in callbacks are printed using IPython's
showtraceback, and their result is ignored.
If not running under IPython, exceptions are raised.
"""
set_context(context)
results = []
for function in self.callbacks:
try:
result = function(*args, **kwargs)
except Exception:
ip = get_ipython()
if ip is None or True: # always raise, for development
raise
else:
ip.showtraceback()
else:
results.append(result)
return results | [
"def",
"__call__",
"(",
"self",
",",
"context",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"set_context",
"(",
"context",
")",
"results",
"=",
"[",
"]",
"for",
"function",
"in",
"self",
".",
"callbacks",
":",
"try",
":",
"result",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"ip",
"is",
"None",
"or",
"True",
":",
"# always raise, for development",
"raise",
"else",
":",
"ip",
".",
"showtraceback",
"(",
")",
"else",
":",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results"
] | https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ui_extensions_api.py#L80-L102 | |
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/virtualenv/files/virtualenv_support/site.py | python | force_global_eggs_after_local_site_packages | () | Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around. | Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around. | [
"Force",
"easy_installed",
"eggs",
"in",
"the",
"global",
"environment",
"to",
"get",
"placed",
"in",
"sys",
".",
"path",
"after",
"all",
"packages",
"inside",
"the",
"virtualenv",
".",
"This",
"maintains",
"the",
"least",
"surprise",
"result",
"that",
"packages",
"in",
"the",
"virtualenv",
"always",
"mask",
"global",
"packages",
"never",
"the",
"other",
"way",
"around",
"."
] | def force_global_eggs_after_local_site_packages():
"""
Force easy_installed eggs in the global environment to get placed
in sys.path after all packages inside the virtualenv. This
maintains the "least surprise" result that packages in the
virtualenv always mask global packages, never the other way
around.
"""
egginsert = getattr(sys, '__egginsert', 0)
for i, path in enumerate(sys.path):
if i > egginsert and path.startswith(sys.prefix):
egginsert = i
sys.__egginsert = egginsert + 1 | [
"def",
"force_global_eggs_after_local_site_packages",
"(",
")",
":",
"egginsert",
"=",
"getattr",
"(",
"sys",
",",
"'__egginsert'",
",",
"0",
")",
"for",
"i",
",",
"path",
"in",
"enumerate",
"(",
"sys",
".",
"path",
")",
":",
"if",
"i",
">",
"egginsert",
"and",
"path",
".",
"startswith",
"(",
"sys",
".",
"prefix",
")",
":",
"egginsert",
"=",
"i",
"sys",
".",
"__egginsert",
"=",
"egginsert",
"+",
"1"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/virtualenv/files/virtualenv_support/site.py#L601-L614 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/missing.py | python | check_value_size | (value, mask: np.ndarray, length: int) | return value | Validate the size of the values passed to ExtensionArray.fillna. | Validate the size of the values passed to ExtensionArray.fillna. | [
"Validate",
"the",
"size",
"of",
"the",
"values",
"passed",
"to",
"ExtensionArray",
".",
"fillna",
"."
] | def check_value_size(value, mask: np.ndarray, length: int):
"""
Validate the size of the values passed to ExtensionArray.fillna.
"""
if is_array_like(value):
if len(value) != length:
raise ValueError(
f"Length of 'value' does not match. Got ({len(value)}) "
f" expected {length}"
)
value = value[mask]
return value | [
"def",
"check_value_size",
"(",
"value",
",",
"mask",
":",
"np",
".",
"ndarray",
",",
"length",
":",
"int",
")",
":",
"if",
"is_array_like",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"length",
":",
"raise",
"ValueError",
"(",
"f\"Length of 'value' does not match. Got ({len(value)}) \"",
"f\" expected {length}\"",
")",
"value",
"=",
"value",
"[",
"mask",
"]",
"return",
"value"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/missing.py#L45-L57 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/gtk/propgrid.py | python | PropertyGridIteratorBase.Next | (*args, **kwargs) | return _propgrid.PropertyGridIteratorBase_Next(*args, **kwargs) | Next(self, bool iterateChildren=True) | Next(self, bool iterateChildren=True) | [
"Next",
"(",
"self",
"bool",
"iterateChildren",
"=",
"True",
")"
] | def Next(*args, **kwargs):
"""Next(self, bool iterateChildren=True)"""
return _propgrid.PropertyGridIteratorBase_Next(*args, **kwargs) | [
"def",
"Next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_propgrid",
".",
"PropertyGridIteratorBase_Next",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L950-L952 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/versionpredicate.py | python | VersionPredicate.__init__ | (self, versionPredicateStr) | Parse a version predicate string. | Parse a version predicate string. | [
"Parse",
"a",
"version",
"predicate",
"string",
"."
] | def __init__(self, versionPredicateStr):
"""Parse a version predicate string.
"""
# Fields:
# name: package name
# pred: list of (comparison string, StrictVersion)
versionPredicateStr = versionPredicateStr.strip()
if not versionPredicateStr:
raise ValueError("empty package restriction")
match = re_validPackage.match(versionPredicateStr)
if not match:
raise ValueError("bad package name in %r" % versionPredicateStr)
self.name, paren = match.groups()
paren = paren.strip()
if paren:
match = re_paren.match(paren)
if not match:
raise ValueError("expected parenthesized list: %r" % paren)
str = match.groups()[0]
self.pred = [splitUp(aPred) for aPred in str.split(",")]
if not self.pred:
raise ValueError("empty parenthesized list in %r"
% versionPredicateStr)
else:
self.pred = [] | [
"def",
"__init__",
"(",
"self",
",",
"versionPredicateStr",
")",
":",
"# Fields:",
"# name: package name",
"# pred: list of (comparison string, StrictVersion)",
"versionPredicateStr",
"=",
"versionPredicateStr",
".",
"strip",
"(",
")",
"if",
"not",
"versionPredicateStr",
":",
"raise",
"ValueError",
"(",
"\"empty package restriction\"",
")",
"match",
"=",
"re_validPackage",
".",
"match",
"(",
"versionPredicateStr",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"\"bad package name in %r\"",
"%",
"versionPredicateStr",
")",
"self",
".",
"name",
",",
"paren",
"=",
"match",
".",
"groups",
"(",
")",
"paren",
"=",
"paren",
".",
"strip",
"(",
")",
"if",
"paren",
":",
"match",
"=",
"re_paren",
".",
"match",
"(",
"paren",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"\"expected parenthesized list: %r\"",
"%",
"paren",
")",
"str",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"self",
".",
"pred",
"=",
"[",
"splitUp",
"(",
"aPred",
")",
"for",
"aPred",
"in",
"str",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"not",
"self",
".",
"pred",
":",
"raise",
"ValueError",
"(",
"\"empty parenthesized list in %r\"",
"%",
"versionPredicateStr",
")",
"else",
":",
"self",
".",
"pred",
"=",
"[",
"]"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/distutils/versionpredicate.py#L95-L120 | ||
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/macresource.py | python | open_pathname | (pathname, verbose=0) | Open a resource file given by pathname, possibly decoding an
AppleSingle file | Open a resource file given by pathname, possibly decoding an
AppleSingle file | [
"Open",
"a",
"resource",
"file",
"given",
"by",
"pathname",
"possibly",
"decoding",
"an",
"AppleSingle",
"file"
] | def open_pathname(pathname, verbose=0):
"""Open a resource file given by pathname, possibly decoding an
AppleSingle file"""
# No resource fork. We may be on OSX, and this may be either
# a data-fork based resource file or a AppleSingle file
# from the CVS repository.
try:
refno = Res.FSOpenResourceFile(pathname, u'', 1)
except Res.Error, arg:
if arg[0] != -199:
# -199 is "bad resource map"
raise
else:
return refno
# Finally try decoding an AppleSingle file
pathname = _decode(pathname, verbose=verbose)
refno = Res.FSOpenResourceFile(pathname, u'', 1) | [
"def",
"open_pathname",
"(",
"pathname",
",",
"verbose",
"=",
"0",
")",
":",
"# No resource fork. We may be on OSX, and this may be either",
"# a data-fork based resource file or a AppleSingle file",
"# from the CVS repository.",
"try",
":",
"refno",
"=",
"Res",
".",
"FSOpenResourceFile",
"(",
"pathname",
",",
"u''",
",",
"1",
")",
"except",
"Res",
".",
"Error",
",",
"arg",
":",
"if",
"arg",
"[",
"0",
"]",
"!=",
"-",
"199",
":",
"# -199 is \"bad resource map\"",
"raise",
"else",
":",
"return",
"refno",
"# Finally try decoding an AppleSingle file",
"pathname",
"=",
"_decode",
"(",
"pathname",
",",
"verbose",
"=",
"verbose",
")",
"refno",
"=",
"Res",
".",
"FSOpenResourceFile",
"(",
"pathname",
",",
"u''",
",",
"1",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/macresource.py#L77-L93 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py | python | NDFrame._check_inplace_setting | (self, value) | return True | check whether we allow in-place setting with this type of value | check whether we allow in-place setting with this type of value | [
"check",
"whether",
"we",
"allow",
"in",
"-",
"place",
"setting",
"with",
"this",
"type",
"of",
"value"
] | def _check_inplace_setting(self, value) -> bool_t:
""" check whether we allow in-place setting with this type of value """
if self._is_mixed_type:
if not self._is_numeric_mixed_type:
# allow an actual np.nan thru
if is_float(value) and np.isnan(value):
return True
raise TypeError(
"Cannot do inplace boolean setting on "
"mixed-types with a non np.nan value"
)
return True | [
"def",
"_check_inplace_setting",
"(",
"self",
",",
"value",
")",
"->",
"bool_t",
":",
"if",
"self",
".",
"_is_mixed_type",
":",
"if",
"not",
"self",
".",
"_is_numeric_mixed_type",
":",
"# allow an actual np.nan thru",
"if",
"is_float",
"(",
"value",
")",
"and",
"np",
".",
"isnan",
"(",
"value",
")",
":",
"return",
"True",
"raise",
"TypeError",
"(",
"\"Cannot do inplace boolean setting on \"",
"\"mixed-types with a non np.nan value\"",
")",
"return",
"True"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/generic.py#L5386-L5401 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py | python | EveryN.step_begin | (self, step) | return [] | Overrides `BaseMonitor.step_begin`.
When overriding this method, you must call the super implementation.
Args:
step: `int`, the current value of the global step.
Returns:
A `list`, the result of every_n_step_begin, if that was called this step,
or an empty list otherwise.
Raises:
ValueError: if called more than once during a step. | Overrides `BaseMonitor.step_begin`. | [
"Overrides",
"BaseMonitor",
".",
"step_begin",
"."
] | def step_begin(self, step):
"""Overrides `BaseMonitor.step_begin`.
When overriding this method, you must call the super implementation.
Args:
step: `int`, the current value of the global step.
Returns:
A `list`, the result of every_n_step_begin, if that was called this step,
or an empty list otherwise.
Raises:
ValueError: if called more than once during a step.
"""
super(EveryN, self).step_begin(step)
if (step <= self._first_n_steps or
step >= (self._every_n_steps + self._last_active_step) or
step == self._max_steps): # Note: max_steps can be None here.
self._every_n_step_begin_called = True
return self.every_n_step_begin(step)
self._every_n_step_begin_called = False
return [] | [
"def",
"step_begin",
"(",
"self",
",",
"step",
")",
":",
"super",
"(",
"EveryN",
",",
"self",
")",
".",
"step_begin",
"(",
"step",
")",
"if",
"(",
"step",
"<=",
"self",
".",
"_first_n_steps",
"or",
"step",
">=",
"(",
"self",
".",
"_every_n_steps",
"+",
"self",
".",
"_last_active_step",
")",
"or",
"step",
"==",
"self",
".",
"_max_steps",
")",
":",
"# Note: max_steps can be None here.",
"self",
".",
"_every_n_step_begin_called",
"=",
"True",
"return",
"self",
".",
"every_n_step_begin",
"(",
"step",
")",
"self",
".",
"_every_n_step_begin_called",
"=",
"False",
"return",
"[",
"]"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/learn/python/learn/monitors.py#L329-L350 | |
google-ar/WebARonTango | e86965d2cbc652156b480e0fcf77c716745578cd | chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py | python | GENnHandler.WriteGLES2ImplementationUnitTest | (self, func, f) | Overrriden from TypeHandler. | Overrriden from TypeHandler. | [
"Overrriden",
"from",
"TypeHandler",
"."
] | def WriteGLES2ImplementationUnitTest(self, func, f):
"""Overrriden from TypeHandler."""
code = """
TEST_F(GLES2ImplementationTest, %(name)s) {
GLuint ids[2] = { 0, };
struct Cmds {
cmds::%(name)sImmediate gen;
GLuint data[2];
};
Cmds expected;
expected.gen.Init(arraysize(ids), &ids[0]);
expected.data[0] = k%(types)sStartId;
expected.data[1] = k%(types)sStartId + 1;
gl_->%(name)s(arraysize(ids), &ids[0]);
EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
EXPECT_EQ(k%(types)sStartId, ids[0]);
EXPECT_EQ(k%(types)sStartId + 1, ids[1]);
}
"""
f.write(code % {
'name': func.name,
'types': func.GetInfo('resource_types'),
}) | [
"def",
"WriteGLES2ImplementationUnitTest",
"(",
"self",
",",
"func",
",",
"f",
")",
":",
"code",
"=",
"\"\"\"\nTEST_F(GLES2ImplementationTest, %(name)s) {\n GLuint ids[2] = { 0, };\n struct Cmds {\n cmds::%(name)sImmediate gen;\n GLuint data[2];\n };\n Cmds expected;\n expected.gen.Init(arraysize(ids), &ids[0]);\n expected.data[0] = k%(types)sStartId;\n expected.data[1] = k%(types)sStartId + 1;\n gl_->%(name)s(arraysize(ids), &ids[0]);\n EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));\n EXPECT_EQ(k%(types)sStartId, ids[0]);\n EXPECT_EQ(k%(types)sStartId + 1, ids[1]);\n}\n\"\"\"",
"f",
".",
"write",
"(",
"code",
"%",
"{",
"'name'",
":",
"func",
".",
"name",
",",
"'types'",
":",
"func",
".",
"GetInfo",
"(",
"'resource_types'",
")",
",",
"}",
")"
] | https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L6046-L6068 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py3/pandas/core/base.py | python | IndexOpsMixin._map_values | (self, mapper, na_action=None) | return new_values | An internal function that maps values using the input
correspondence (which can be a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
The input correspondence object
na_action : {None, 'ignore'}
If 'ignore', propagate NA values, without passing them to the
mapping function
Returns
-------
Union[Index, MultiIndex], inferred
The output of the mapping function applied to the index.
If the function returns a tuple with more than one element
a MultiIndex will be returned. | An internal function that maps values using the input
correspondence (which can be a dict, Series, or function). | [
"An",
"internal",
"function",
"that",
"maps",
"values",
"using",
"the",
"input",
"correspondence",
"(",
"which",
"can",
"be",
"a",
"dict",
"Series",
"or",
"function",
")",
"."
] | def _map_values(self, mapper, na_action=None):
"""
An internal function that maps values using the input
correspondence (which can be a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
The input correspondence object
na_action : {None, 'ignore'}
If 'ignore', propagate NA values, without passing them to the
mapping function
Returns
-------
Union[Index, MultiIndex], inferred
The output of the mapping function applied to the index.
If the function returns a tuple with more than one element
a MultiIndex will be returned.
"""
# we can fastpath dict/Series to an efficient map
# as we know that we are not going to have to yield
# python types
if is_dict_like(mapper):
if isinstance(mapper, dict) and hasattr(mapper, "__missing__"):
# If a dictionary subclass defines a default value method,
# convert mapper to a lookup function (GH #15999).
dict_with_default = mapper
mapper = lambda x: dict_with_default[x]
else:
# Dictionary does not have a default. Thus it's safe to
# convert to an Series for efficiency.
# we specify the keys here to handle the
# possibility that they are tuples
# The return value of mapping with an empty mapper is
# expected to be pd.Series(np.nan, ...). As np.nan is
# of dtype float64 the return value of this method should
# be float64 as well
mapper = create_series_with_explicit_dtype(
mapper, dtype_if_empty=np.float64
)
if isinstance(mapper, ABCSeries):
# Since values were input this means we came from either
# a dict or a series and mapper should be an index
if is_categorical_dtype(self.dtype):
# use the built in categorical series mapper which saves
# time by mapping the categories instead of all values
cat = cast("Categorical", self._values)
return cat.map(mapper)
values = self._values
indexer = mapper.index.get_indexer(values)
new_values = algorithms.take_nd(mapper._values, indexer)
return new_values
# we must convert to python types
if is_extension_array_dtype(self.dtype) and hasattr(self._values, "map"):
# GH#23179 some EAs do not have `map`
values = self._values
if na_action is not None:
raise NotImplementedError
map_f = lambda values, f: values.map(f)
else:
values = self._values.astype(object)
if na_action == "ignore":
map_f = lambda values, f: lib.map_infer_mask(
values, f, isna(values).view(np.uint8)
)
elif na_action is None:
map_f = lib.map_infer
else:
msg = (
"na_action must either be 'ignore' or None, "
f"{na_action} was passed"
)
raise ValueError(msg)
# mapper is a function
new_values = map_f(values, mapper)
return new_values | [
"def",
"_map_values",
"(",
"self",
",",
"mapper",
",",
"na_action",
"=",
"None",
")",
":",
"# we can fastpath dict/Series to an efficient map",
"# as we know that we are not going to have to yield",
"# python types",
"if",
"is_dict_like",
"(",
"mapper",
")",
":",
"if",
"isinstance",
"(",
"mapper",
",",
"dict",
")",
"and",
"hasattr",
"(",
"mapper",
",",
"\"__missing__\"",
")",
":",
"# If a dictionary subclass defines a default value method,",
"# convert mapper to a lookup function (GH #15999).",
"dict_with_default",
"=",
"mapper",
"mapper",
"=",
"lambda",
"x",
":",
"dict_with_default",
"[",
"x",
"]",
"else",
":",
"# Dictionary does not have a default. Thus it's safe to",
"# convert to an Series for efficiency.",
"# we specify the keys here to handle the",
"# possibility that they are tuples",
"# The return value of mapping with an empty mapper is",
"# expected to be pd.Series(np.nan, ...). As np.nan is",
"# of dtype float64 the return value of this method should",
"# be float64 as well",
"mapper",
"=",
"create_series_with_explicit_dtype",
"(",
"mapper",
",",
"dtype_if_empty",
"=",
"np",
".",
"float64",
")",
"if",
"isinstance",
"(",
"mapper",
",",
"ABCSeries",
")",
":",
"# Since values were input this means we came from either",
"# a dict or a series and mapper should be an index",
"if",
"is_categorical_dtype",
"(",
"self",
".",
"dtype",
")",
":",
"# use the built in categorical series mapper which saves",
"# time by mapping the categories instead of all values",
"cat",
"=",
"cast",
"(",
"\"Categorical\"",
",",
"self",
".",
"_values",
")",
"return",
"cat",
".",
"map",
"(",
"mapper",
")",
"values",
"=",
"self",
".",
"_values",
"indexer",
"=",
"mapper",
".",
"index",
".",
"get_indexer",
"(",
"values",
")",
"new_values",
"=",
"algorithms",
".",
"take_nd",
"(",
"mapper",
".",
"_values",
",",
"indexer",
")",
"return",
"new_values",
"# we must convert to python types",
"if",
"is_extension_array_dtype",
"(",
"self",
".",
"dtype",
")",
"and",
"hasattr",
"(",
"self",
".",
"_values",
",",
"\"map\"",
")",
":",
"# GH#23179 some EAs do not have `map`",
"values",
"=",
"self",
".",
"_values",
"if",
"na_action",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"map_f",
"=",
"lambda",
"values",
",",
"f",
":",
"values",
".",
"map",
"(",
"f",
")",
"else",
":",
"values",
"=",
"self",
".",
"_values",
".",
"astype",
"(",
"object",
")",
"if",
"na_action",
"==",
"\"ignore\"",
":",
"map_f",
"=",
"lambda",
"values",
",",
"f",
":",
"lib",
".",
"map_infer_mask",
"(",
"values",
",",
"f",
",",
"isna",
"(",
"values",
")",
".",
"view",
"(",
"np",
".",
"uint8",
")",
")",
"elif",
"na_action",
"is",
"None",
":",
"map_f",
"=",
"lib",
".",
"map_infer",
"else",
":",
"msg",
"=",
"(",
"\"na_action must either be 'ignore' or None, \"",
"f\"{na_action} was passed\"",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"# mapper is a function",
"new_values",
"=",
"map_f",
"(",
"values",
",",
"mapper",
")",
"return",
"new_values"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/base.py#L787-L872 | |
openthread/openthread | 9fcdbed9c526c70f1556d1ed84099c1535c7cd32 | tools/harness-automation/autothreadharness/harness_case.py | python | HarnessCase._wait_dialog | (self) | Wait for dialogs and handle them until done. | Wait for dialogs and handle them until done. | [
"Wait",
"for",
"dialogs",
"and",
"handle",
"them",
"until",
"done",
"."
] | def _wait_dialog(self):
"""Wait for dialogs and handle them until done.
"""
logger.debug('waiting for dialog')
done = False
error = False
logger.info('self timeout %d', self.timeout)
while not done and self.timeout:
try:
dialog = self._browser.find_element_by_id('RemoteConfirm')
except BaseException:
logger.exception('Failed to get dialog.')
else:
if dialog and dialog.get_attribute('aria-hidden') == 'false':
title = dialog.find_element_by_class_name('modal-title').text
time.sleep(1)
logger.info('Handling dialog[%s]', title)
try:
done = self._handle_dialog(dialog, title)
except BaseException:
logger.exception('Error handling dialog: %s', title)
error = True
if done is None:
raise FailError('Unexpected dialog occurred')
dialog.find_element_by_id('ConfirmOk').click()
time.sleep(1)
try:
stop_button = self._browser.find_element_by_id('stopTest')
if done:
stop_button.click()
# wait for stop procedure end
time.sleep(10)
except NoSuchElementException:
logger.info('Test stopped')
time.sleep(5)
done = True
self.timeout -= 1
# check if already ended capture
if self.timeout % 10 == 0:
lines = self._hc.tail()
if 'SUCCESS: The process "dumpcap.exe" with PID ' in lines:
logger.info('Tshark should be ended now, lets wait at most 30 seconds.')
if not wait_until(lambda: 'tshark.exe' not in subprocess.check_output('tasklist'), 30):
res = subprocess.check_output('taskkill /t /f /im tshark.exe',
stderr=subprocess.STDOUT,
shell=True)
logger.info(res)
# Wait until case really stopped
wait_until(lambda: self._browser.find_element_by_id('runTest') and True, 30)
if error:
raise FailError('Fail for previous exceptions') | [
"def",
"_wait_dialog",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'waiting for dialog'",
")",
"done",
"=",
"False",
"error",
"=",
"False",
"logger",
".",
"info",
"(",
"'self timeout %d'",
",",
"self",
".",
"timeout",
")",
"while",
"not",
"done",
"and",
"self",
".",
"timeout",
":",
"try",
":",
"dialog",
"=",
"self",
".",
"_browser",
".",
"find_element_by_id",
"(",
"'RemoteConfirm'",
")",
"except",
"BaseException",
":",
"logger",
".",
"exception",
"(",
"'Failed to get dialog.'",
")",
"else",
":",
"if",
"dialog",
"and",
"dialog",
".",
"get_attribute",
"(",
"'aria-hidden'",
")",
"==",
"'false'",
":",
"title",
"=",
"dialog",
".",
"find_element_by_class_name",
"(",
"'modal-title'",
")",
".",
"text",
"time",
".",
"sleep",
"(",
"1",
")",
"logger",
".",
"info",
"(",
"'Handling dialog[%s]'",
",",
"title",
")",
"try",
":",
"done",
"=",
"self",
".",
"_handle_dialog",
"(",
"dialog",
",",
"title",
")",
"except",
"BaseException",
":",
"logger",
".",
"exception",
"(",
"'Error handling dialog: %s'",
",",
"title",
")",
"error",
"=",
"True",
"if",
"done",
"is",
"None",
":",
"raise",
"FailError",
"(",
"'Unexpected dialog occurred'",
")",
"dialog",
".",
"find_element_by_id",
"(",
"'ConfirmOk'",
")",
".",
"click",
"(",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"try",
":",
"stop_button",
"=",
"self",
".",
"_browser",
".",
"find_element_by_id",
"(",
"'stopTest'",
")",
"if",
"done",
":",
"stop_button",
".",
"click",
"(",
")",
"# wait for stop procedure end",
"time",
".",
"sleep",
"(",
"10",
")",
"except",
"NoSuchElementException",
":",
"logger",
".",
"info",
"(",
"'Test stopped'",
")",
"time",
".",
"sleep",
"(",
"5",
")",
"done",
"=",
"True",
"self",
".",
"timeout",
"-=",
"1",
"# check if already ended capture",
"if",
"self",
".",
"timeout",
"%",
"10",
"==",
"0",
":",
"lines",
"=",
"self",
".",
"_hc",
".",
"tail",
"(",
")",
"if",
"'SUCCESS: The process \"dumpcap.exe\" with PID '",
"in",
"lines",
":",
"logger",
".",
"info",
"(",
"'Tshark should be ended now, lets wait at most 30 seconds.'",
")",
"if",
"not",
"wait_until",
"(",
"lambda",
":",
"'tshark.exe'",
"not",
"in",
"subprocess",
".",
"check_output",
"(",
"'tasklist'",
")",
",",
"30",
")",
":",
"res",
"=",
"subprocess",
".",
"check_output",
"(",
"'taskkill /t /f /im tshark.exe'",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
",",
"shell",
"=",
"True",
")",
"logger",
".",
"info",
"(",
"res",
")",
"# Wait until case really stopped",
"wait_until",
"(",
"lambda",
":",
"self",
".",
"_browser",
".",
"find_element_by_id",
"(",
"'runTest'",
")",
"and",
"True",
",",
"30",
")",
"if",
"error",
":",
"raise",
"FailError",
"(",
"'Fail for previous exceptions'",
")"
] | https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/harness-automation/autothreadharness/harness_case.py#L869-L929 | ||
weolar/miniblink49 | 1c4678db0594a4abde23d3ebbcc7cd13c3170777 | third_party/jinja2/environment.py | python | Environment.list_templates | (self, extensions=None, filter_func=None) | return x | Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4 | Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method. | [
"Returns",
"a",
"list",
"of",
"templates",
"for",
"this",
"environment",
".",
"This",
"requires",
"that",
"the",
"loader",
"supports",
"the",
"loader",
"s",
":",
"meth",
":",
"~BaseLoader",
".",
"list_templates",
"method",
"."
] | def list_templates(self, extensions=None, filter_func=None):
"""Returns a list of templates for this environment. This requires
that the loader supports the loader's
:meth:`~BaseLoader.list_templates` method.
If there are other files in the template folder besides the
actual templates, the returned list can be filtered. There are two
ways: either `extensions` is set to a list of file extensions for
templates, or a `filter_func` can be provided which is a callable that
is passed a template name and should return `True` if it should end up
in the result list.
If the loader does not support that, a :exc:`TypeError` is raised.
.. versionadded:: 2.4
"""
x = self.loader.list_templates()
if extensions is not None:
if filter_func is not None:
raise TypeError('either extensions or filter_func '
'can be passed, but not both')
filter_func = lambda x: '.' in x and \
x.rsplit('.', 1)[1] in extensions
if filter_func is not None:
x = ifilter(filter_func, x)
return x | [
"def",
"list_templates",
"(",
"self",
",",
"extensions",
"=",
"None",
",",
"filter_func",
"=",
"None",
")",
":",
"x",
"=",
"self",
".",
"loader",
".",
"list_templates",
"(",
")",
"if",
"extensions",
"is",
"not",
"None",
":",
"if",
"filter_func",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"'either extensions or filter_func '",
"'can be passed, but not both'",
")",
"filter_func",
"=",
"lambda",
"x",
":",
"'.'",
"in",
"x",
"and",
"x",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"1",
"]",
"in",
"extensions",
"if",
"filter_func",
"is",
"not",
"None",
":",
"x",
"=",
"ifilter",
"(",
"filter_func",
",",
"x",
")",
"return",
"x"
] | https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/environment.py#L695-L720 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | DC.GetCharHeight | (*args, **kwargs) | return _gdi_.DC_GetCharHeight(*args, **kwargs) | GetCharHeight(self) -> int
Gets the character height of the currently set font. | GetCharHeight(self) -> int | [
"GetCharHeight",
"(",
"self",
")",
"-",
">",
"int"
] | def GetCharHeight(*args, **kwargs):
"""
GetCharHeight(self) -> int
Gets the character height of the currently set font.
"""
return _gdi_.DC_GetCharHeight(*args, **kwargs) | [
"def",
"GetCharHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetCharHeight",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L4092-L4098 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/urllib/request.py | python | urlcleanup | () | Clean up temporary files from urlretrieve calls. | Clean up temporary files from urlretrieve calls. | [
"Clean",
"up",
"temporary",
"files",
"from",
"urlretrieve",
"calls",
"."
] | def urlcleanup():
"""Clean up temporary files from urlretrieve calls."""
for temp_file in _url_tempfiles:
try:
os.unlink(temp_file)
except OSError:
pass
del _url_tempfiles[:]
global _opener
if _opener:
_opener = None | [
"def",
"urlcleanup",
"(",
")",
":",
"for",
"temp_file",
"in",
"_url_tempfiles",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"temp_file",
")",
"except",
"OSError",
":",
"pass",
"del",
"_url_tempfiles",
"[",
":",
"]",
"global",
"_opener",
"if",
"_opener",
":",
"_opener",
"=",
"None"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/urllib/request.py#L284-L295 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | dom/bindings/parser/WebIDL.py | python | Parser.p_NonAnyTypeDate | (self, p) | NonAnyType : DATE TypeSuffix | NonAnyType : DATE TypeSuffix | [
"NonAnyType",
":",
"DATE",
"TypeSuffix"
] | def p_NonAnyTypeDate(self, p):
"""
NonAnyType : DATE TypeSuffix
"""
p[0] = self.handleModifiers(BuiltinTypes[IDLBuiltinType.Types.date],
p[2]) | [
"def",
"p_NonAnyTypeDate",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"handleModifiers",
"(",
"BuiltinTypes",
"[",
"IDLBuiltinType",
".",
"Types",
".",
"date",
"]",
",",
"p",
"[",
"2",
"]",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/dom/bindings/parser/WebIDL.py#L5288-L5293 | ||
mindspore-ai/mindspore | fb8fd3338605bb34fa5cea054e535a8b1d753fab | mindspore/python/mindspore/profiler/parser/aicpu_data_parser.py | python | DataPreProcessParser._get_source_file | (self) | return file_name | Get log file name, which was created by ada service. | Get log file name, which was created by ada service. | [
"Get",
"log",
"file",
"name",
"which",
"was",
"created",
"by",
"ada",
"service",
"."
] | def _get_source_file(self):
"""Get log file name, which was created by ada service."""
file_name = get_file_join_name(self._input_path, self._source_file_target)
if not file_name:
file_name = get_file_join_name(self._input_path, self._source_file_target_old)
if not file_name:
data_path = os.path.join(self._input_path, "data")
file_name = get_file_join_name(data_path, self._source_file_target)
if not file_name:
file_name = get_file_join_name(data_path, self._source_file_target_old)
return file_name | [
"def",
"_get_source_file",
"(",
"self",
")",
":",
"file_name",
"=",
"get_file_join_name",
"(",
"self",
".",
"_input_path",
",",
"self",
".",
"_source_file_target",
")",
"if",
"not",
"file_name",
":",
"file_name",
"=",
"get_file_join_name",
"(",
"self",
".",
"_input_path",
",",
"self",
".",
"_source_file_target_old",
")",
"if",
"not",
"file_name",
":",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_input_path",
",",
"\"data\"",
")",
"file_name",
"=",
"get_file_join_name",
"(",
"data_path",
",",
"self",
".",
"_source_file_target",
")",
"if",
"not",
"file_name",
":",
"file_name",
"=",
"get_file_join_name",
"(",
"data_path",
",",
"self",
".",
"_source_file_target_old",
")",
"return",
"file_name"
] | https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/profiler/parser/aicpu_data_parser.py#L98-L108 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py | python | VocabularyListCategoricalColumn.name | (self) | return self.key | See `FeatureColumn` base class. | See `FeatureColumn` base class. | [
"See",
"FeatureColumn",
"base",
"class",
"."
] | def name(self):
"""See `FeatureColumn` base class."""
return self.key | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"key"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/feature_column/feature_column_v2.py#L3691-L3693 | |
ARM-software/armnn | 5e9965cae1cc6162649910f423ebd86001fc1931 | python/pyarmnn/examples/image_classification/example_utils.py | python | download_file | (url: str, force: bool = False, filename: str = None) | return filename | Downloads a file.
Args:
url (str): File url.
force (bool): Forces to download the file even if it exists.
filename (str): Renames the file when set.
Raises:
RuntimeError: If for some reason download fails.
Returns:
str: Path to the downloaded file. | Downloads a file. | [
"Downloads",
"a",
"file",
"."
] | def download_file(url: str, force: bool = False, filename: str = None):
"""Downloads a file.
Args:
url (str): File url.
force (bool): Forces to download the file even if it exists.
filename (str): Renames the file when set.
Raises:
RuntimeError: If for some reason download fails.
Returns:
str: Path to the downloaded file.
"""
try:
if filename is None: # extract filename from url when None
filename = urlparse(url)
filename = os.path.basename(filename.path)
print("Downloading '{0}' from '{1}' ...".format(filename, url))
if not os.path.exists(filename) or force is True:
r = requests.get(url)
with open(filename, 'wb') as f:
f.write(r.content)
print("Finished.")
else:
print("File already exists.")
except:
raise RuntimeError("Unable to download file.")
return filename | [
"def",
"download_file",
"(",
"url",
":",
"str",
",",
"force",
":",
"bool",
"=",
"False",
",",
"filename",
":",
"str",
"=",
"None",
")",
":",
"try",
":",
"if",
"filename",
"is",
"None",
":",
"# extract filename from url when None",
"filename",
"=",
"urlparse",
"(",
"url",
")",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
".",
"path",
")",
"print",
"(",
"\"Downloading '{0}' from '{1}' ...\"",
".",
"format",
"(",
"filename",
",",
"url",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
"or",
"force",
"is",
"True",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"r",
".",
"content",
")",
"print",
"(",
"\"Finished.\"",
")",
"else",
":",
"print",
"(",
"\"File already exists.\"",
")",
"except",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to download file.\"",
")",
"return",
"filename"
] | https://github.com/ARM-software/armnn/blob/5e9965cae1cc6162649910f423ebd86001fc1931/python/pyarmnn/examples/image_classification/example_utils.py#L241-L271 | |
adobe/chromium | cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7 | third_party/closure_linter/closure_linter/ecmalintrules.py | python | EcmaScriptLintRules.Initialize | (self, checker, limited_doc_checks, is_html) | Initialize this lint rule object before parsing a new file. | Initialize this lint rule object before parsing a new file. | [
"Initialize",
"this",
"lint",
"rule",
"object",
"before",
"parsing",
"a",
"new",
"file",
"."
] | def Initialize(self, checker, limited_doc_checks, is_html):
"""Initialize this lint rule object before parsing a new file."""
checkerbase.LintRulesBase.Initialize(self, checker, limited_doc_checks,
is_html)
self._indentation = indentation.IndentationRules() | [
"def",
"Initialize",
"(",
"self",
",",
"checker",
",",
"limited_doc_checks",
",",
"is_html",
")",
":",
"checkerbase",
".",
"LintRulesBase",
".",
"Initialize",
"(",
"self",
",",
"checker",
",",
"limited_doc_checks",
",",
"is_html",
")",
"self",
".",
"_indentation",
"=",
"indentation",
".",
"IndentationRules",
"(",
")"
] | https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/ecmalintrules.py#L95-L99 | ||
miyosuda/TensorFlowAndroidDemo | 35903e0221aa5f109ea2dbef27f20b52e317f42d | jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py | python | load_csv | (filename, target_dtype, target_column=-1, has_header=True) | Load dataset from CSV file. | Load dataset from CSV file. | [
"Load",
"dataset",
"from",
"CSV",
"file",
"."
] | def load_csv(filename, target_dtype, target_column=-1, has_header=True):
"""Load dataset from CSV file."""
if has_header:
return load_csv_with_header(filename=filename,
target_dtype=target_dtype,
features_dtype=np.float64,
target_column=target_column)
else:
return load_csv_without_header(filename=filename,
target_dtype=target_dtype,
features_dtype=np.float64,
target_column=target_column) | [
"def",
"load_csv",
"(",
"filename",
",",
"target_dtype",
",",
"target_column",
"=",
"-",
"1",
",",
"has_header",
"=",
"True",
")",
":",
"if",
"has_header",
":",
"return",
"load_csv_with_header",
"(",
"filename",
"=",
"filename",
",",
"target_dtype",
"=",
"target_dtype",
",",
"features_dtype",
"=",
"np",
".",
"float64",
",",
"target_column",
"=",
"target_column",
")",
"else",
":",
"return",
"load_csv_without_header",
"(",
"filename",
"=",
"filename",
",",
"target_dtype",
"=",
"target_dtype",
",",
"features_dtype",
"=",
"np",
".",
"float64",
",",
"target_column",
"=",
"target_column",
")"
] | https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/learn/python/learn/datasets/base.py#L39-L50 | ||
assimp/assimp | 97c7e084c2f7f8c9355ea42f73605890481bddc5 | port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py | python | GLRenderer.recursive_render | (self, node) | Main recursive rendering method. | Main recursive rendering method. | [
"Main",
"recursive",
"rendering",
"method",
"."
] | def recursive_render(self, node):
""" Main recursive rendering method.
"""
# save model matrix and apply node transformation
glPushMatrix()
m = node.transformation.transpose() # OpenGL row major
glMultMatrixf(m)
for mesh in node.meshes:
self.apply_material(mesh.material)
glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["vertices"])
glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT, 0, None)
glBindBuffer(GL_ARRAY_BUFFER, mesh.gl["normals"])
glEnableClientState(GL_NORMAL_ARRAY)
glNormalPointer(GL_FLOAT, 0, None)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.gl["triangles"])
glDrawElements(GL_TRIANGLES,len(mesh.faces) * 3, GL_UNSIGNED_INT, None)
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_NORMAL_ARRAY)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
for child in node.children:
self.recursive_render(child)
glPopMatrix() | [
"def",
"recursive_render",
"(",
"self",
",",
"node",
")",
":",
"# save model matrix and apply node transformation",
"glPushMatrix",
"(",
")",
"m",
"=",
"node",
".",
"transformation",
".",
"transpose",
"(",
")",
"# OpenGL row major",
"glMultMatrixf",
"(",
"m",
")",
"for",
"mesh",
"in",
"node",
".",
"meshes",
":",
"self",
".",
"apply_material",
"(",
"mesh",
".",
"material",
")",
"glBindBuffer",
"(",
"GL_ARRAY_BUFFER",
",",
"mesh",
".",
"gl",
"[",
"\"vertices\"",
"]",
")",
"glEnableClientState",
"(",
"GL_VERTEX_ARRAY",
")",
"glVertexPointer",
"(",
"3",
",",
"GL_FLOAT",
",",
"0",
",",
"None",
")",
"glBindBuffer",
"(",
"GL_ARRAY_BUFFER",
",",
"mesh",
".",
"gl",
"[",
"\"normals\"",
"]",
")",
"glEnableClientState",
"(",
"GL_NORMAL_ARRAY",
")",
"glNormalPointer",
"(",
"GL_FLOAT",
",",
"0",
",",
"None",
")",
"glBindBuffer",
"(",
"GL_ELEMENT_ARRAY_BUFFER",
",",
"mesh",
".",
"gl",
"[",
"\"triangles\"",
"]",
")",
"glDrawElements",
"(",
"GL_TRIANGLES",
",",
"len",
"(",
"mesh",
".",
"faces",
")",
"*",
"3",
",",
"GL_UNSIGNED_INT",
",",
"None",
")",
"glDisableClientState",
"(",
"GL_VERTEX_ARRAY",
")",
"glDisableClientState",
"(",
"GL_NORMAL_ARRAY",
")",
"glBindBuffer",
"(",
"GL_ARRAY_BUFFER",
",",
"0",
")",
"glBindBuffer",
"(",
"GL_ELEMENT_ARRAY_BUFFER",
",",
"0",
")",
"for",
"child",
"in",
"node",
".",
"children",
":",
"self",
".",
"recursive_render",
"(",
"child",
")",
"glPopMatrix",
"(",
")"
] | https://github.com/assimp/assimp/blob/97c7e084c2f7f8c9355ea42f73605890481bddc5/port/PyAssimp/scripts/fixed_pipeline_3d_viewer.py#L251-L283 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/passmanagers.py | python | PassManager.add_global_optimizer_pass | (self) | See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer. | See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer. | [
"See",
"http",
":",
"//",
"llvm",
".",
"org",
"/",
"docs",
"/",
"Passes",
".",
"html#globalopt",
"-",
"global",
"-",
"variable",
"-",
"optimizer",
"."
] | def add_global_optimizer_pass(self):
"""See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer."""
ffi.lib.LLVMPY_AddGlobalOptimizerPass(self) | [
"def",
"add_global_optimizer_pass",
"(",
"self",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_AddGlobalOptimizerPass",
"(",
"self",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/llvmlite/binding/passmanagers.py#L41-L43 | ||
briantrice/slate-language | a0daf5c8a40ba3e5d5368e34ab651284d803e570 | src/profiler/gprof2dot.py | python | Profile.validate | (self) | Validate the edges. | Validate the edges. | [
"Validate",
"the",
"edges",
"."
] | def validate(self):
"""Validate the edges."""
for function in self.functions.itervalues():
for callee_id in function.calls.keys():
assert function.calls[callee_id].callee_id == callee_id
if callee_id not in self.functions:
sys.stderr.write('warning: call to undefined function %s from function %s\n' % (str(callee_id), function.name))
del function.calls[callee_id] | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"function",
"in",
"self",
".",
"functions",
".",
"itervalues",
"(",
")",
":",
"for",
"callee_id",
"in",
"function",
".",
"calls",
".",
"keys",
"(",
")",
":",
"assert",
"function",
".",
"calls",
"[",
"callee_id",
"]",
".",
"callee_id",
"==",
"callee_id",
"if",
"callee_id",
"not",
"in",
"self",
".",
"functions",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'warning: call to undefined function %s from function %s\\n'",
"%",
"(",
"str",
"(",
"callee_id",
")",
",",
"function",
".",
"name",
")",
")",
"del",
"function",
".",
"calls",
"[",
"callee_id",
"]"
] | https://github.com/briantrice/slate-language/blob/a0daf5c8a40ba3e5d5368e34ab651284d803e570/src/profiler/gprof2dot.py#L234-L242 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/ebmlib/cmenumgr.py | python | ContextMenuManager.GetUserData | (self, key) | return self._userdata.get(key, None) | Get user data
@param key: data id key | Get user data
@param key: data id key | [
"Get",
"user",
"data",
"@param",
"key",
":",
"data",
"id",
"key"
] | def GetUserData(self, key):
"""Get user data
@param key: data id key
"""
return self._userdata.get(key, None) | [
"def",
"GetUserData",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"_userdata",
".",
"get",
"(",
"key",
",",
"None",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/ebmlib/cmenumgr.py#L86-L91 | |
panda3d/panda3d | 833ad89ebad58395d0af0b7ec08538e5e4308265 | direct/src/showbase/PythonUtil.py | python | reduceAngle | (deg) | return ((deg + 180.) % 360.) - 180. | Reduces an angle (in degrees) to a value in [-180..180) | Reduces an angle (in degrees) to a value in [-180..180) | [
"Reduces",
"an",
"angle",
"(",
"in",
"degrees",
")",
"to",
"a",
"value",
"in",
"[",
"-",
"180",
"..",
"180",
")"
] | def reduceAngle(deg):
"""
Reduces an angle (in degrees) to a value in [-180..180)
"""
return ((deg + 180.) % 360.) - 180. | [
"def",
"reduceAngle",
"(",
"deg",
")",
":",
"return",
"(",
"(",
"deg",
"+",
"180.",
")",
"%",
"360.",
")",
"-",
"180."
] | https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/showbase/PythonUtil.py#L481-L485 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py | python | easy_install._set_fetcher_options | (self, base) | When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well. | When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well. | [
"When",
"easy_install",
"is",
"about",
"to",
"run",
"bdist_egg",
"on",
"a",
"source",
"dist",
"that",
"source",
"dist",
"might",
"have",
"setup_requires",
"directives",
"requiring",
"additional",
"fetching",
".",
"Ensure",
"the",
"fetcher",
"options",
"given",
"to",
"easy_install",
"are",
"available",
"to",
"that",
"command",
"as",
"well",
"."
] | def _set_fetcher_options(self, base):
"""
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
"""
# find the fetch options from easy_install and write them out
# to the setup.cfg file.
ei_opts = self.distribution.get_option_dict('easy_install').copy()
fetch_directives = (
'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts',
)
fetch_options = {}
for key, val in ei_opts.items():
if key not in fetch_directives:
continue
fetch_options[key.replace('_', '-')] = val[1]
# create a settings dictionary suitable for `edit_config`
settings = dict(easy_install=fetch_options)
cfg_filename = os.path.join(base, 'setup.cfg')
setopt.edit_config(cfg_filename, settings) | [
"def",
"_set_fetcher_options",
"(",
"self",
",",
"base",
")",
":",
"# find the fetch options from easy_install and write them out",
"# to the setup.cfg file.",
"ei_opts",
"=",
"self",
".",
"distribution",
".",
"get_option_dict",
"(",
"'easy_install'",
")",
".",
"copy",
"(",
")",
"fetch_directives",
"=",
"(",
"'find_links'",
",",
"'site_dirs'",
",",
"'index_url'",
",",
"'optimize'",
",",
"'allow_hosts'",
",",
")",
"fetch_options",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"ei_opts",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"fetch_directives",
":",
"continue",
"fetch_options",
"[",
"key",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"]",
"=",
"val",
"[",
"1",
"]",
"# create a settings dictionary suitable for `edit_config`",
"settings",
"=",
"dict",
"(",
"easy_install",
"=",
"fetch_options",
")",
"cfg_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"'setup.cfg'",
")",
"setopt",
".",
"edit_config",
"(",
"cfg_filename",
",",
"settings",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/command/easy_install.py#L1185-L1206 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/richtext.py | python | RichTextCtrl.BeginBatchUndo | (*args, **kwargs) | return _richtext.RichTextCtrl_BeginBatchUndo(*args, **kwargs) | BeginBatchUndo(self, String cmdName) -> bool
Start batching undo history for commands | BeginBatchUndo(self, String cmdName) -> bool | [
"BeginBatchUndo",
"(",
"self",
"String",
"cmdName",
")",
"-",
">",
"bool"
] | def BeginBatchUndo(*args, **kwargs):
"""
BeginBatchUndo(self, String cmdName) -> bool
Start batching undo history for commands
"""
return _richtext.RichTextCtrl_BeginBatchUndo(*args, **kwargs) | [
"def",
"BeginBatchUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_BeginBatchUndo",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/richtext.py#L3841-L3847 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py | python | Message.set_default_type | (self, ctype) | Set the `default' content type.
ctype should be either "text/plain" or "message/rfc822", although this
is not enforced. The default content type is not stored in the
Content-Type header. | Set the `default' content type. | [
"Set",
"the",
"default",
"content",
"type",
"."
] | def set_default_type(self, ctype):
"""Set the `default' content type.
ctype should be either "text/plain" or "message/rfc822", although this
is not enforced. The default content type is not stored in the
Content-Type header.
"""
self._default_type = ctype | [
"def",
"set_default_type",
"(",
"self",
",",
"ctype",
")",
":",
"self",
".",
"_default_type",
"=",
"ctype"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/email/message.py#L483-L490 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py | python | Issue.update | (self, fields=None, update=None, async=None, jira=None, notify=True, **fieldargs) | Update this issue on the server.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments
will be ignored.
JIRA projects may contain many different issue types. Some issue screens have different requirements for
fields in an issue. This information is available through the :py:meth:`.JIRA.editmeta` method. Further examples
are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues
:param fields: a dict containing field names and the values to use
:param update: a dict containing update operations to apply
keyword arguments will generally be merged into fields, except lists, which will be merged into updates | Update this issue on the server. | [
"Update",
"this",
"issue",
"on",
"the",
"server",
"."
] | def update(self, fields=None, update=None, async=None, jira=None, notify=True, **fieldargs):
"""Update this issue on the server.
Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value
is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments
will be ignored.
JIRA projects may contain many different issue types. Some issue screens have different requirements for
fields in an issue. This information is available through the :py:meth:`.JIRA.editmeta` method. Further examples
are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Edit+issues
:param fields: a dict containing field names and the values to use
:param update: a dict containing update operations to apply
keyword arguments will generally be merged into fields, except lists, which will be merged into updates
"""
data = {}
if fields is not None:
fields_dict = fields
else:
fields_dict = {}
data['fields'] = fields_dict
if update is not None:
update_dict = update
else:
update_dict = {}
data['update'] = update_dict
for field in sorted(fieldargs.keys()):
value = fieldargs[field]
# apply some heuristics to make certain changes easier
if isinstance(value, string_types):
if field == 'assignee' or field == 'reporter':
fields_dict['assignee'] = {'name': value}
elif field == 'comment':
if 'comment' not in update_dict:
update_dict['comment'] = []
update_dict['comment'].append({
'add': {'body': value}})
else:
fields_dict[field] = value
elif isinstance(value, list):
if field not in update_dict:
update_dict[field] = []
update_dict[field].extend(value)
else:
fields_dict[field] = value
super(Issue, self).update(async=async, jira=jira, notify=notify, fields=data) | [
"def",
"update",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"update",
"=",
"None",
",",
"async",
"=",
"None",
",",
"jira",
"=",
"None",
",",
"notify",
"=",
"True",
",",
"*",
"*",
"fieldargs",
")",
":",
"data",
"=",
"{",
"}",
"if",
"fields",
"is",
"not",
"None",
":",
"fields_dict",
"=",
"fields",
"else",
":",
"fields_dict",
"=",
"{",
"}",
"data",
"[",
"'fields'",
"]",
"=",
"fields_dict",
"if",
"update",
"is",
"not",
"None",
":",
"update_dict",
"=",
"update",
"else",
":",
"update_dict",
"=",
"{",
"}",
"data",
"[",
"'update'",
"]",
"=",
"update_dict",
"for",
"field",
"in",
"sorted",
"(",
"fieldargs",
".",
"keys",
"(",
")",
")",
":",
"value",
"=",
"fieldargs",
"[",
"field",
"]",
"# apply some heuristics to make certain changes easier",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"if",
"field",
"==",
"'assignee'",
"or",
"field",
"==",
"'reporter'",
":",
"fields_dict",
"[",
"'assignee'",
"]",
"=",
"{",
"'name'",
":",
"value",
"}",
"elif",
"field",
"==",
"'comment'",
":",
"if",
"'comment'",
"not",
"in",
"update_dict",
":",
"update_dict",
"[",
"'comment'",
"]",
"=",
"[",
"]",
"update_dict",
"[",
"'comment'",
"]",
".",
"append",
"(",
"{",
"'add'",
":",
"{",
"'body'",
":",
"value",
"}",
"}",
")",
"else",
":",
"fields_dict",
"[",
"field",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"if",
"field",
"not",
"in",
"update_dict",
":",
"update_dict",
"[",
"field",
"]",
"=",
"[",
"]",
"update_dict",
"[",
"field",
"]",
".",
"extend",
"(",
"value",
")",
"else",
":",
"fields_dict",
"[",
"field",
"]",
"=",
"value",
"super",
"(",
"Issue",
",",
"self",
")",
".",
"update",
"(",
"async",
"=",
"async",
",",
"jira",
"=",
"jira",
",",
"notify",
"=",
"notify",
",",
"fields",
"=",
"data",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/jira/resources.py#L435-L483 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/framework/ops.py | python | _EagerTensorBase._shape_tuple | (self) | The shape of this Tensor, as a tuple.
This is more performant than tuple(shape().as_list()) as it avoids
two list and one object creation. Marked private for now as from an API
perspective, it would be better to have a single performant way of
getting a shape rather than exposing shape() and shape_tuple()
(and heaven forbid, shape_list() etc. as well!). Punting on that for now,
but ideally one would work things out and remove the need for this method.
Returns:
tuple with the shape. | The shape of this Tensor, as a tuple. | [
"The",
"shape",
"of",
"this",
"Tensor",
"as",
"a",
"tuple",
"."
] | def _shape_tuple(self):
"""The shape of this Tensor, as a tuple.
This is more performant than tuple(shape().as_list()) as it avoids
two list and one object creation. Marked private for now as from an API
perspective, it would be better to have a single performant way of
getting a shape rather than exposing shape() and shape_tuple()
(and heaven forbid, shape_list() etc. as well!). Punting on that for now,
but ideally one would work things out and remove the need for this method.
Returns:
tuple with the shape.
"""
raise NotImplementedError() | [
"def",
"_shape_tuple",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/framework/ops.py#L644-L657 | ||
p4lang/behavioral-model | 81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9 | mininet/p4_mininet.py | python | P4Switch.stop | (self) | Terminate P4 switch. | Terminate P4 switch. | [
"Terminate",
"P4",
"switch",
"."
] | def stop(self):
"Terminate P4 switch."
self.output.flush()
self.cmd('kill %' + self.sw_path)
self.cmd('wait')
self.deleteIntfs() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"output",
".",
"flush",
"(",
")",
"self",
".",
"cmd",
"(",
"'kill %'",
"+",
"self",
".",
"sw_path",
")",
"self",
".",
"cmd",
"(",
"'wait'",
")",
"self",
".",
"deleteIntfs",
"(",
")"
] | https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/mininet/p4_mininet.py#L146-L151 | ||
zhuli19901106/leetcode-zhuli | 0f8fc29ccb8c33ea91149ecb2d4e961024c11db7 | explore/fun-with-arrays/3157_move-zeros_1_AC.py | python | Solution.moveZeroes | (self, nums: List[int]) | Do not return anything, modify nums in-place instead. | Do not return anything, modify nums in-place instead. | [
"Do",
"not",
"return",
"anything",
"modify",
"nums",
"in",
"-",
"place",
"instead",
"."
] | def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
a = nums
n = len(a)
j = 0
for i in range(n):
if a[i] != 0:
a[j] = a[i]
j += 1
while j < n:
a[j] = 0
j += 1 | [
"def",
"moveZeroes",
"(",
"self",
",",
"nums",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"a",
"=",
"nums",
"n",
"=",
"len",
"(",
"a",
")",
"j",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"if",
"a",
"[",
"i",
"]",
"!=",
"0",
":",
"a",
"[",
"j",
"]",
"=",
"a",
"[",
"i",
"]",
"j",
"+=",
"1",
"while",
"j",
"<",
"n",
":",
"a",
"[",
"j",
"]",
"=",
"0",
"j",
"+=",
"1"
] | https://github.com/zhuli19901106/leetcode-zhuli/blob/0f8fc29ccb8c33ea91149ecb2d4e961024c11db7/explore/fun-with-arrays/3157_move-zeros_1_AC.py#L4-L17 | ||
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/prt/wxgui.py | python | WxGui.on_update_decompressors | (self, event=None) | Update all decompressors (determine detector edge) | Update all decompressors (determine detector edge) | [
"Update",
"all",
"decompressors",
"(",
"determine",
"detector",
"edge",
")"
] | def on_update_decompressors(self, event=None):
"""Update all decompressors (determine detector edge)"""
self._prtservice.decompressors.update_all()
self._mainframe.browse_obj(self._prtservice.decompressors) | [
"def",
"on_update_decompressors",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"self",
".",
"_prtservice",
".",
"decompressors",
".",
"update_all",
"(",
")",
"self",
".",
"_mainframe",
".",
"browse_obj",
"(",
"self",
".",
"_prtservice",
".",
"decompressors",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/prt/wxgui.py#L450-L453 | ||
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | python/caffe/detector.py | python | Detector.detect_windows | (self, images_windows) | return detections | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts. | Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net. | [
"Do",
"windowed",
"detection",
"over",
"given",
"images",
"and",
"windows",
".",
"Windows",
"are",
"extracted",
"then",
"warped",
"to",
"the",
"input",
"dimensions",
"of",
"the",
"net",
"."
] | def detect_windows(self, images_windows):
"""
Do windowed detection over given images and windows. Windows are
extracted then warped to the input dimensions of the net.
Parameters
----------
images_windows: (image filename, window list) iterable.
context_crop: size of context border to crop in pixels.
Returns
-------
detections: list of {filename: image filename, window: crop coordinates,
predictions: prediction vector} dicts.
"""
# Extract windows.
window_inputs = []
for image_fname, windows in images_windows:
image = caffe.io.load_image(image_fname).astype(np.float32)
for window in windows:
window_inputs.append(self.crop(image, window))
# Run through the net (warping windows to input dimensions).
in_ = self.inputs[0]
caffe_in = np.zeros((len(window_inputs), window_inputs[0].shape[2])
+ self.blobs[in_].data.shape[2:],
dtype=np.float32)
for ix, window_in in enumerate(window_inputs):
caffe_in[ix] = self.transformer.preprocess(in_, window_in)
out = self.forward_all(**{in_: caffe_in})
predictions = out[self.outputs[0]]
# Package predictions with images and windows.
detections = []
ix = 0
for image_fname, windows in images_windows:
for window in windows:
detections.append({
'window': window,
'prediction': predictions[ix],
'filename': image_fname
})
ix += 1
return detections | [
"def",
"detect_windows",
"(",
"self",
",",
"images_windows",
")",
":",
"# Extract windows.",
"window_inputs",
"=",
"[",
"]",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"image",
"=",
"caffe",
".",
"io",
".",
"load_image",
"(",
"image_fname",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")",
"for",
"window",
"in",
"windows",
":",
"window_inputs",
".",
"append",
"(",
"self",
".",
"crop",
"(",
"image",
",",
"window",
")",
")",
"# Run through the net (warping windows to input dimensions).",
"in_",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
"caffe_in",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"window_inputs",
")",
",",
"window_inputs",
"[",
"0",
"]",
".",
"shape",
"[",
"2",
"]",
")",
"+",
"self",
".",
"blobs",
"[",
"in_",
"]",
".",
"data",
".",
"shape",
"[",
"2",
":",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"ix",
",",
"window_in",
"in",
"enumerate",
"(",
"window_inputs",
")",
":",
"caffe_in",
"[",
"ix",
"]",
"=",
"self",
".",
"transformer",
".",
"preprocess",
"(",
"in_",
",",
"window_in",
")",
"out",
"=",
"self",
".",
"forward_all",
"(",
"*",
"*",
"{",
"in_",
":",
"caffe_in",
"}",
")",
"predictions",
"=",
"out",
"[",
"self",
".",
"outputs",
"[",
"0",
"]",
"]",
"# Package predictions with images and windows.",
"detections",
"=",
"[",
"]",
"ix",
"=",
"0",
"for",
"image_fname",
",",
"windows",
"in",
"images_windows",
":",
"for",
"window",
"in",
"windows",
":",
"detections",
".",
"append",
"(",
"{",
"'window'",
":",
"window",
",",
"'prediction'",
":",
"predictions",
"[",
"ix",
"]",
",",
"'filename'",
":",
"image_fname",
"}",
")",
"ix",
"+=",
"1",
"return",
"detections"
] | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/python/caffe/detector.py#L56-L99 | |
MVIG-SJTU/RMPE | 5188c230ec800c12be7369c3619615bc9b020aa4 | scripts/cpp_lint.py | python | GetLineWidth | (line) | Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters. | Determines the width of the line in column positions. | [
"Determines",
"the",
"width",
"of",
"the",
"line",
"in",
"column",
"positions",
"."
] | def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line) | [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"unicodedata",
".",
"east_asian_width",
"(",
"uc",
")",
"in",
"(",
"'W'",
",",
"'F'",
")",
":",
"width",
"+=",
"2",
"elif",
"not",
"unicodedata",
".",
"combining",
"(",
"uc",
")",
":",
"width",
"+=",
"1",
"return",
"width",
"else",
":",
"return",
"len",
"(",
"line",
")"
] | https://github.com/MVIG-SJTU/RMPE/blob/5188c230ec800c12be7369c3619615bc9b020aa4/scripts/cpp_lint.py#L3441-L3460 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | GBSpan.__ne__ | (*args, **kwargs) | return _core_.GBSpan___ne__(*args, **kwargs) | __ne__(self, PyObject other) -> bool
Compare GBSpan for inequality. | __ne__(self, PyObject other) -> bool | [
"__ne__",
"(",
"self",
"PyObject",
"other",
")",
"-",
">",
"bool"
] | def __ne__(*args, **kwargs):
"""
__ne__(self, PyObject other) -> bool
Compare GBSpan for inequality.
"""
return _core_.GBSpan___ne__(*args, **kwargs) | [
"def",
"__ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"GBSpan___ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L15680-L15686 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/_pydecimal.py | python | _convert_other | (other, raiseit=False, allow_float=False) | return NotImplemented | Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
If allow_float is true, allow conversion from float; this
is used in the comparison methods (__eq__ and friends). | Convert other to Decimal. | [
"Convert",
"other",
"to",
"Decimal",
"."
] | def _convert_other(other, raiseit=False, allow_float=False):
"""Convert other to Decimal.
Verifies that it's ok to use in an implicit construction.
If allow_float is true, allow conversion from float; this
is used in the comparison methods (__eq__ and friends).
"""
if isinstance(other, Decimal):
return other
if isinstance(other, int):
return Decimal(other)
if allow_float and isinstance(other, float):
return Decimal.from_float(other)
if raiseit:
raise TypeError("Unable to convert %s to Decimal" % other)
return NotImplemented | [
"def",
"_convert_other",
"(",
"other",
",",
"raiseit",
"=",
"False",
",",
"allow_float",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Decimal",
")",
":",
"return",
"other",
"if",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"return",
"Decimal",
"(",
"other",
")",
"if",
"allow_float",
"and",
"isinstance",
"(",
"other",
",",
"float",
")",
":",
"return",
"Decimal",
".",
"from_float",
"(",
"other",
")",
"if",
"raiseit",
":",
"raise",
"TypeError",
"(",
"\"Unable to convert %s to Decimal\"",
"%",
"other",
")",
"return",
"NotImplemented"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pydecimal.py#L6013-L6030 | |
Kitware/ParaView | f760af9124ff4634b23ebbeab95a4f56e0261955 | ThirdParty/cinema/paraview/tpl/cinema_python/database/raster_wrangler.py | python | RasterWrangler.enableVTK | (self) | Try to turn on VTK file IO support | Try to turn on VTK file IO support | [
"Try",
"to",
"turn",
"on",
"VTK",
"file",
"IO",
"support"
] | def enableVTK(self):
"""Try to turn on VTK file IO support"""
if vtkEnabled:
self.backends.add("VTK")
else:
warnings.warn("VTK module not found", ImportWarning) | [
"def",
"enableVTK",
"(",
"self",
")",
":",
"if",
"vtkEnabled",
":",
"self",
".",
"backends",
".",
"add",
"(",
"\"VTK\"",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"VTK module not found\"",
",",
"ImportWarning",
")"
] | https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/ThirdParty/cinema/paraview/tpl/cinema_python/database/raster_wrangler.py#L102-L107 | ||
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/android/loading/chrome_cache.py | python | _EnsureCleanCacheDirectory | (directory_dest_path) | Ensure that a cache directory is created and clean.
Args:
directory_dest_path: Path of the cache directory to ensure cleanliness. | Ensure that a cache directory is created and clean. | [
"Ensure",
"that",
"a",
"cache",
"directory",
"is",
"created",
"and",
"clean",
"."
] | def _EnsureCleanCacheDirectory(directory_dest_path):
"""Ensure that a cache directory is created and clean.
Args:
directory_dest_path: Path of the cache directory to ensure cleanliness.
"""
if os.path.isdir(directory_dest_path):
shutil.rmtree(directory_dest_path)
elif not os.path.isdir(os.path.dirname(directory_dest_path)):
os.makedirs(os.path.dirname(directory_dest_path))
assert not os.path.exists(directory_dest_path) | [
"def",
"_EnsureCleanCacheDirectory",
"(",
"directory_dest_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"directory_dest_path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"directory_dest_path",
")",
"elif",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"directory_dest_path",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"directory_dest_path",
")",
")",
"assert",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory_dest_path",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/android/loading/chrome_cache.py#L38-L48 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/ftplib.py | python | FTP.retrlines | (self, cmd, callback = None) | return self.voidresp() | Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, or NLST command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code. | Retrieve data in line mode. A new port is created for you. | [
"Retrieve",
"data",
"in",
"line",
"mode",
".",
"A",
"new",
"port",
"is",
"created",
"for",
"you",
"."
] | def retrlines(self, cmd, callback = None):
"""Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, or NLST command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code.
"""
if callback is None:
callback = print_line
resp = self.sendcmd('TYPE A')
with self.transfercmd(cmd) as conn, \
conn.makefile('r', encoding=self.encoding) as fp:
while 1:
line = fp.readline(self.maxline + 1)
if len(line) > self.maxline:
raise Error("got more than %d bytes" % self.maxline)
if self.debugging > 2:
print('*retr*', repr(line))
if not line:
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] == '\n':
line = line[:-1]
callback(line)
# shutdown ssl layer
if _SSLSocket is not None and isinstance(conn, _SSLSocket):
conn.unwrap()
return self.voidresp() | [
"def",
"retrlines",
"(",
"self",
",",
"cmd",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"print_line",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'TYPE A'",
")",
"with",
"self",
".",
"transfercmd",
"(",
"cmd",
")",
"as",
"conn",
",",
"conn",
".",
"makefile",
"(",
"'r'",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"as",
"fp",
":",
"while",
"1",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
"self",
".",
"maxline",
"+",
"1",
")",
"if",
"len",
"(",
"line",
")",
">",
"self",
".",
"maxline",
":",
"raise",
"Error",
"(",
"\"got more than %d bytes\"",
"%",
"self",
".",
"maxline",
")",
"if",
"self",
".",
"debugging",
">",
"2",
":",
"print",
"(",
"'*retr*'",
",",
"repr",
"(",
"line",
")",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"CRLF",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"elif",
"line",
"[",
"-",
"1",
":",
"]",
"==",
"'\\n'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"callback",
"(",
"line",
")",
"# shutdown ssl layer",
"if",
"_SSLSocket",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"conn",
",",
"_SSLSocket",
")",
":",
"conn",
".",
"unwrap",
"(",
")",
"return",
"self",
".",
"voidresp",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ftplib.py#L453-L486 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/build/waf-1.7.13/waflib/Tools/ruby.py | python | init_rubyext | (self) | Add required variables for ruby extensions | Add required variables for ruby extensions | [
"Add",
"required",
"variables",
"for",
"ruby",
"extensions"
] | def init_rubyext(self):
"""
Add required variables for ruby extensions
"""
self.install_path = '${ARCHDIR_RUBY}'
self.uselib = self.to_list(getattr(self, 'uselib', ''))
if not 'RUBY' in self.uselib:
self.uselib.append('RUBY')
if not 'RUBYEXT' in self.uselib:
self.uselib.append('RUBYEXT') | [
"def",
"init_rubyext",
"(",
"self",
")",
":",
"self",
".",
"install_path",
"=",
"'${ARCHDIR_RUBY}'",
"self",
".",
"uselib",
"=",
"self",
".",
"to_list",
"(",
"getattr",
"(",
"self",
",",
"'uselib'",
",",
"''",
")",
")",
"if",
"not",
"'RUBY'",
"in",
"self",
".",
"uselib",
":",
"self",
".",
"uselib",
".",
"append",
"(",
"'RUBY'",
")",
"if",
"not",
"'RUBYEXT'",
"in",
"self",
".",
"uselib",
":",
"self",
".",
"uselib",
".",
"append",
"(",
"'RUBYEXT'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/ruby.py#L32-L41 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py | python | WorkingSet.subscribe | (self, callback, existing=True) | Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well. | Invoke `callback` for all distributions | [
"Invoke",
"callback",
"for",
"all",
"distributions"
] | def subscribe(self, callback, existing=True):
"""Invoke `callback` for all distributions
If `existing=True` (default),
call on all existing ones, as well.
"""
if callback in self.callbacks:
return
self.callbacks.append(callback)
if not existing:
return
for dist in self:
callback(dist) | [
"def",
"subscribe",
"(",
"self",
",",
"callback",
",",
"existing",
"=",
"True",
")",
":",
"if",
"callback",
"in",
"self",
".",
"callbacks",
":",
"return",
"self",
".",
"callbacks",
".",
"append",
"(",
"callback",
")",
"if",
"not",
"existing",
":",
"return",
"for",
"dist",
"in",
"self",
":",
"callback",
"(",
"dist",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L907-L919 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBAttachInfo.SetEffectiveUserID | (self, uid) | return _lldb.SBAttachInfo_SetEffectiveUserID(self, uid) | SetEffectiveUserID(SBAttachInfo self, uint32_t uid) | SetEffectiveUserID(SBAttachInfo self, uint32_t uid) | [
"SetEffectiveUserID",
"(",
"SBAttachInfo",
"self",
"uint32_t",
"uid",
")"
] | def SetEffectiveUserID(self, uid):
"""SetEffectiveUserID(SBAttachInfo self, uint32_t uid)"""
return _lldb.SBAttachInfo_SetEffectiveUserID(self, uid) | [
"def",
"SetEffectiveUserID",
"(",
"self",
",",
"uid",
")",
":",
"return",
"_lldb",
".",
"SBAttachInfo_SetEffectiveUserID",
"(",
"self",
",",
"uid",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L1172-L1174 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/debug/wrappers/local_cli_wrapper.py | python | LocalCLIDebugWrapperSession._run_handler | (self, args, screen_info=None) | Command handler for "run" command during on-run-start. | Command handler for "run" command during on-run-start. | [
"Command",
"handler",
"for",
"run",
"command",
"during",
"on",
"-",
"run",
"-",
"start",
"."
] | def _run_handler(self, args, screen_info=None):
"""Command handler for "run" command during on-run-start."""
del screen_info # Currently unused.
parsed = self._argparsers["run"].parse_args(args)
parsed.node_name_filter = parsed.node_name_filter or None
parsed.op_type_filter = parsed.op_type_filter or None
parsed.tensor_dtype_filter = parsed.tensor_dtype_filter or None
if parsed.filter_exclude_node_names and not parsed.till_filter_pass:
raise ValueError(
"The --filter_exclude_node_names (or -feon) flag is valid only if "
"the --till_filter_pass (or -f) flag is used.")
if parsed.profile:
raise debugger_cli_common.CommandLineExit(
exit_token=framework.OnRunStartResponse(
framework.OnRunStartAction.PROFILE_RUN, []))
self._skip_debug = parsed.no_debug
self._run_through_times = parsed.times
if parsed.times > 1 or parsed.no_debug:
# If requested -t times > 1, the very next run will be a non-debug run.
action = framework.OnRunStartAction.NON_DEBUG_RUN
debug_urls = []
else:
action = framework.OnRunStartAction.DEBUG_RUN
debug_urls = self._get_run_debug_urls()
run_start_response = framework.OnRunStartResponse(
action,
debug_urls,
node_name_regex_allowlist=parsed.node_name_filter,
op_type_regex_allowlist=parsed.op_type_filter,
tensor_dtype_regex_allowlist=parsed.tensor_dtype_filter)
if parsed.till_filter_pass:
# For the run-till-filter-pass (run -f) mode, use the DEBUG_RUN
# option to access the intermediate tensors, and set the corresponding
# state flag of the class itself to True.
if parsed.till_filter_pass in self._tensor_filters:
action = framework.OnRunStartAction.DEBUG_RUN
self._active_tensor_filter = parsed.till_filter_pass
self._active_filter_exclude_node_names = (
parsed.filter_exclude_node_names)
self._active_tensor_filter_run_start_response = run_start_response
else:
# Handle invalid filter name.
return debugger_cli_common.RichTextLines(
["ERROR: tensor filter \"%s\" does not exist." %
parsed.till_filter_pass])
# Raise CommandLineExit exception to cause the CLI to exit.
raise debugger_cli_common.CommandLineExit(exit_token=run_start_response) | [
"def",
"_run_handler",
"(",
"self",
",",
"args",
",",
"screen_info",
"=",
"None",
")",
":",
"del",
"screen_info",
"# Currently unused.",
"parsed",
"=",
"self",
".",
"_argparsers",
"[",
"\"run\"",
"]",
".",
"parse_args",
"(",
"args",
")",
"parsed",
".",
"node_name_filter",
"=",
"parsed",
".",
"node_name_filter",
"or",
"None",
"parsed",
".",
"op_type_filter",
"=",
"parsed",
".",
"op_type_filter",
"or",
"None",
"parsed",
".",
"tensor_dtype_filter",
"=",
"parsed",
".",
"tensor_dtype_filter",
"or",
"None",
"if",
"parsed",
".",
"filter_exclude_node_names",
"and",
"not",
"parsed",
".",
"till_filter_pass",
":",
"raise",
"ValueError",
"(",
"\"The --filter_exclude_node_names (or -feon) flag is valid only if \"",
"\"the --till_filter_pass (or -f) flag is used.\"",
")",
"if",
"parsed",
".",
"profile",
":",
"raise",
"debugger_cli_common",
".",
"CommandLineExit",
"(",
"exit_token",
"=",
"framework",
".",
"OnRunStartResponse",
"(",
"framework",
".",
"OnRunStartAction",
".",
"PROFILE_RUN",
",",
"[",
"]",
")",
")",
"self",
".",
"_skip_debug",
"=",
"parsed",
".",
"no_debug",
"self",
".",
"_run_through_times",
"=",
"parsed",
".",
"times",
"if",
"parsed",
".",
"times",
">",
"1",
"or",
"parsed",
".",
"no_debug",
":",
"# If requested -t times > 1, the very next run will be a non-debug run.",
"action",
"=",
"framework",
".",
"OnRunStartAction",
".",
"NON_DEBUG_RUN",
"debug_urls",
"=",
"[",
"]",
"else",
":",
"action",
"=",
"framework",
".",
"OnRunStartAction",
".",
"DEBUG_RUN",
"debug_urls",
"=",
"self",
".",
"_get_run_debug_urls",
"(",
")",
"run_start_response",
"=",
"framework",
".",
"OnRunStartResponse",
"(",
"action",
",",
"debug_urls",
",",
"node_name_regex_allowlist",
"=",
"parsed",
".",
"node_name_filter",
",",
"op_type_regex_allowlist",
"=",
"parsed",
".",
"op_type_filter",
",",
"tensor_dtype_regex_allowlist",
"=",
"parsed",
".",
"tensor_dtype_filter",
")",
"if",
"parsed",
".",
"till_filter_pass",
":",
"# For the run-till-filter-pass (run -f) mode, use the DEBUG_RUN",
"# option to access the intermediate tensors, and set the corresponding",
"# state flag of the class itself to True.",
"if",
"parsed",
".",
"till_filter_pass",
"in",
"self",
".",
"_tensor_filters",
":",
"action",
"=",
"framework",
".",
"OnRunStartAction",
".",
"DEBUG_RUN",
"self",
".",
"_active_tensor_filter",
"=",
"parsed",
".",
"till_filter_pass",
"self",
".",
"_active_filter_exclude_node_names",
"=",
"(",
"parsed",
".",
"filter_exclude_node_names",
")",
"self",
".",
"_active_tensor_filter_run_start_response",
"=",
"run_start_response",
"else",
":",
"# Handle invalid filter name.",
"return",
"debugger_cli_common",
".",
"RichTextLines",
"(",
"[",
"\"ERROR: tensor filter \\\"%s\\\" does not exist.\"",
"%",
"parsed",
".",
"till_filter_pass",
"]",
")",
"# Raise CommandLineExit exception to cause the CLI to exit.",
"raise",
"debugger_cli_common",
".",
"CommandLineExit",
"(",
"exit_token",
"=",
"run_start_response",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/debug/wrappers/local_cli_wrapper.py#L518-L572 | ||
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/mox.py | python | ContainsKeyValue.equals | (self, rhs) | Check whether the given key/value pair is in the rhs dict.
Returns:
bool | Check whether the given key/value pair is in the rhs dict. | [
"Check",
"whether",
"the",
"given",
"key",
"/",
"value",
"pair",
"is",
"in",
"the",
"rhs",
"dict",
"."
] | def equals(self, rhs):
"""Check whether the given key/value pair is in the rhs dict.
Returns:
bool
"""
try:
return rhs[self._key] == self._value
except Exception:
return False | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"try",
":",
"return",
"rhs",
"[",
"self",
".",
"_key",
"]",
"==",
"self",
".",
"_value",
"except",
"Exception",
":",
"return",
"False"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/mox.py#L989-L999 | ||
Evolving-AI-Lab/fooling | 66f097dd6bd2eb6794ade3e187a7adfdf1887688 | caffe/scripts/cpp_lint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] | https://github.com/Evolving-AI-Lab/fooling/blob/66f097dd6bd2eb6794ade3e187a7adfdf1887688/caffe/scripts/cpp_lint.py#L929-L941 | |
klzgrad/naiveproxy | ed2c513637c77b18721fe428d7ed395b4d284c83 | src/third_party/abseil-cpp/absl/abseil.podspec.gen.py | python | write_indented_list | (f, leading, values) | Writes leading values in an indented style. | Writes leading values in an indented style. | [
"Writes",
"leading",
"values",
"in",
"an",
"indented",
"style",
"."
] | def write_indented_list(f, leading, values):
"""Writes leading values in an indented style."""
f.write(leading)
f.write((",\n" + " " * len(leading)).join("'{}'".format(v) for v in values))
f.write("\n") | [
"def",
"write_indented_list",
"(",
"f",
",",
"leading",
",",
"values",
")",
":",
"f",
".",
"write",
"(",
"leading",
")",
"f",
".",
"write",
"(",
"(",
"\",\\n\"",
"+",
"\" \"",
"*",
"len",
"(",
"leading",
")",
")",
".",
"join",
"(",
"\"'{}'\"",
".",
"format",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
")",
"f",
".",
"write",
"(",
"\"\\n\"",
")"
] | https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/third_party/abseil-cpp/absl/abseil.podspec.gen.py#L193-L197 | ||
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/ops/math_grad.py | python | _PolygammaGrad | (op, grad) | Returns gradient of psi(n, x) with respect to n and x. | Returns gradient of psi(n, x) with respect to n and x. | [
"Returns",
"gradient",
"of",
"psi",
"(",
"n",
"x",
")",
"with",
"respect",
"to",
"n",
"and",
"x",
"."
] | def _PolygammaGrad(op, grad):
"""Returns gradient of psi(n, x) with respect to n and x."""
# TODO(tillahoffmann): Add derivative with respect to n
n = op.inputs[0]
x = op.inputs[1]
# Broadcast gradients
sn = array_ops.shape(n)
sx = array_ops.shape(x)
# pylint: disable=protected-access
unused_rn, rx = gen_array_ops._broadcast_gradient_args(sn, sx)
# pylint: enable=protected-access
# Evaluate gradient
with ops.control_dependencies([grad]):
n = math_ops.conj(n)
x = math_ops.conj(x)
partial_x = math_ops.polygamma(n + 1, x)
# TODO(b/36815900): Mark None return values as NotImplemented
return (None,
array_ops.reshape(math_ops.reduce_sum(partial_x * grad, rx), sx)) | [
"def",
"_PolygammaGrad",
"(",
"op",
",",
"grad",
")",
":",
"# TODO(tillahoffmann): Add derivative with respect to n",
"n",
"=",
"op",
".",
"inputs",
"[",
"0",
"]",
"x",
"=",
"op",
".",
"inputs",
"[",
"1",
"]",
"# Broadcast gradients",
"sn",
"=",
"array_ops",
".",
"shape",
"(",
"n",
")",
"sx",
"=",
"array_ops",
".",
"shape",
"(",
"x",
")",
"# pylint: disable=protected-access",
"unused_rn",
",",
"rx",
"=",
"gen_array_ops",
".",
"_broadcast_gradient_args",
"(",
"sn",
",",
"sx",
")",
"# pylint: enable=protected-access",
"# Evaluate gradient",
"with",
"ops",
".",
"control_dependencies",
"(",
"[",
"grad",
"]",
")",
":",
"n",
"=",
"math_ops",
".",
"conj",
"(",
"n",
")",
"x",
"=",
"math_ops",
".",
"conj",
"(",
"x",
")",
"partial_x",
"=",
"math_ops",
".",
"polygamma",
"(",
"n",
"+",
"1",
",",
"x",
")",
"# TODO(b/36815900): Mark None return values as NotImplemented",
"return",
"(",
"None",
",",
"array_ops",
".",
"reshape",
"(",
"math_ops",
".",
"reduce_sum",
"(",
"partial_x",
"*",
"grad",
",",
"rx",
")",
",",
"sx",
")",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/math_grad.py#L571-L589 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py | python | PanedWindow.sash | (self, *args) | return self._getints(
self.tk.call((self._w, 'sash') + args)) or () | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def sash(self, *args):
"""Internal function."""
return self._getints(
self.tk.call((self._w, 'sash') + args)) or () | [
"def",
"sash",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"self",
".",
"_getints",
"(",
"self",
".",
"tk",
".",
"call",
"(",
"(",
"self",
".",
"_w",
",",
"'sash'",
")",
"+",
"args",
")",
")",
"or",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3865-L3868 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteMacBundleResources | (self, resources, bundle_depends) | return xcassets | Writes ninja edges for 'mac_bundle_resources'. | Writes ninja edges for 'mac_bundle_resources'. | [
"Writes",
"ninja",
"edges",
"for",
"mac_bundle_resources",
"."
] | def WriteMacBundleResources(self, resources, bundle_depends):
"""Writes ninja edges for 'mac_bundle_resources'."""
xcassets = []
extra_env = self.xcode_settings.GetPerTargetSettings()
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
for output, res in gyp.xcode_emulation.GetMacBundleResources(
generator_default_variables['PRODUCT_DIR'],
self.xcode_settings, map(self.GypPathToNinja, resources)):
output = self.ExpandSpecial(output)
if os.path.splitext(output)[-1] != '.xcassets':
self.ninja.build(output, 'mac_tool', res,
variables=[('mactool_cmd', 'copy-bundle-resource'), \
('env', env), ('binary', isBinary)])
bundle_depends.append(output)
else:
xcassets.append(res)
return xcassets | [
"def",
"WriteMacBundleResources",
"(",
"self",
",",
"resources",
",",
"bundle_depends",
")",
":",
"xcassets",
"=",
"[",
"]",
"extra_env",
"=",
"self",
".",
"xcode_settings",
".",
"GetPerTargetSettings",
"(",
")",
"env",
"=",
"self",
".",
"GetSortedXcodeEnv",
"(",
"additional_settings",
"=",
"extra_env",
")",
"env",
"=",
"self",
".",
"ComputeExportEnvString",
"(",
"env",
")",
"isBinary",
"=",
"self",
".",
"xcode_settings",
".",
"IsBinaryOutputFormat",
"(",
"self",
".",
"config_name",
")",
"for",
"output",
",",
"res",
"in",
"gyp",
".",
"xcode_emulation",
".",
"GetMacBundleResources",
"(",
"generator_default_variables",
"[",
"'PRODUCT_DIR'",
"]",
",",
"self",
".",
"xcode_settings",
",",
"map",
"(",
"self",
".",
"GypPathToNinja",
",",
"resources",
")",
")",
":",
"output",
"=",
"self",
".",
"ExpandSpecial",
"(",
"output",
")",
"if",
"os",
".",
"path",
".",
"splitext",
"(",
"output",
")",
"[",
"-",
"1",
"]",
"!=",
"'.xcassets'",
":",
"self",
".",
"ninja",
".",
"build",
"(",
"output",
",",
"'mac_tool'",
",",
"res",
",",
"variables",
"=",
"[",
"(",
"'mactool_cmd'",
",",
"'copy-bundle-resource'",
")",
",",
"(",
"'env'",
",",
"env",
")",
",",
"(",
"'binary'",
",",
"isBinary",
")",
"]",
")",
"bundle_depends",
".",
"append",
"(",
"output",
")",
"else",
":",
"xcassets",
".",
"append",
"(",
"res",
")",
"return",
"xcassets"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/ninja.py#L767-L787 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mutex.py | python | mutex.lock | (self, function, argument) | Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue. | Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue. | [
"Lock",
"a",
"mutex",
"call",
"the",
"function",
"with",
"supplied",
"argument",
"when",
"it",
"is",
"acquired",
".",
"If",
"the",
"mutex",
"is",
"already",
"locked",
"place",
"function",
"and",
"argument",
"in",
"the",
"queue",
"."
] | def lock(self, function, argument):
"""Lock a mutex, call the function with supplied argument
when it is acquired. If the mutex is already locked, place
function and argument in the queue."""
if self.testandset():
function(argument)
else:
self.queue.append((function, argument)) | [
"def",
"lock",
"(",
"self",
",",
"function",
",",
"argument",
")",
":",
"if",
"self",
".",
"testandset",
"(",
")",
":",
"function",
"(",
"argument",
")",
"else",
":",
"self",
".",
"queue",
".",
"append",
"(",
"(",
"function",
",",
"argument",
")",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/mutex.py#L39-L46 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/pandas/py2/pandas/core/series.py | python | Series.drop_duplicates | (self, keep='first', inplace=False) | return super(Series, self).drop_duplicates(keep=keep, inplace=inplace) | Return Series with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except for the last occurrence.
- ``False`` : Drop all duplicates.
inplace : boolean, default ``False``
If ``True``, performs operation inplace and returns None.
Returns
-------
deduplicated : Series
See Also
--------
Index.drop_duplicates : Equivalent method on Index.
DataFrame.drop_duplicates : Equivalent method on DataFrame.
Series.duplicated : Related method on Series, indicating duplicate
Series values.
Examples
--------
Generate an Series with duplicated entries.
>>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'],
... name='animal')
>>> s
0 lama
1 cow
2 lama
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
With the 'keep' parameter, the selection behaviour of duplicated values
can be changed. The value 'first' keeps the first occurrence for each
set of duplicated entries. The default value of keep is 'first'.
>>> s.drop_duplicates()
0 lama
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
The value 'last' for parameter 'keep' keeps the last occurrence for
each set of duplicated entries.
>>> s.drop_duplicates(keep='last')
1 cow
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
The value ``False`` for parameter 'keep' discards all sets of
duplicated entries. Setting the value of 'inplace' to ``True`` performs
the operation inplace and returns ``None``.
>>> s.drop_duplicates(keep=False, inplace=True)
>>> s
1 cow
3 beetle
5 hippo
Name: animal, dtype: object | Return Series with duplicate values removed. | [
"Return",
"Series",
"with",
"duplicate",
"values",
"removed",
"."
] | def drop_duplicates(self, keep='first', inplace=False):
"""
Return Series with duplicate values removed.
Parameters
----------
keep : {'first', 'last', ``False``}, default 'first'
- 'first' : Drop duplicates except for the first occurrence.
- 'last' : Drop duplicates except for the last occurrence.
- ``False`` : Drop all duplicates.
inplace : boolean, default ``False``
If ``True``, performs operation inplace and returns None.
Returns
-------
deduplicated : Series
See Also
--------
Index.drop_duplicates : Equivalent method on Index.
DataFrame.drop_duplicates : Equivalent method on DataFrame.
Series.duplicated : Related method on Series, indicating duplicate
Series values.
Examples
--------
Generate an Series with duplicated entries.
>>> s = pd.Series(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo'],
... name='animal')
>>> s
0 lama
1 cow
2 lama
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
With the 'keep' parameter, the selection behaviour of duplicated values
can be changed. The value 'first' keeps the first occurrence for each
set of duplicated entries. The default value of keep is 'first'.
>>> s.drop_duplicates()
0 lama
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
The value 'last' for parameter 'keep' keeps the last occurrence for
each set of duplicated entries.
>>> s.drop_duplicates(keep='last')
1 cow
3 beetle
4 lama
5 hippo
Name: animal, dtype: object
The value ``False`` for parameter 'keep' discards all sets of
duplicated entries. Setting the value of 'inplace' to ``True`` performs
the operation inplace and returns ``None``.
>>> s.drop_duplicates(keep=False, inplace=True)
>>> s
1 cow
3 beetle
5 hippo
Name: animal, dtype: object
"""
return super(Series, self).drop_duplicates(keep=keep, inplace=inplace) | [
"def",
"drop_duplicates",
"(",
"self",
",",
"keep",
"=",
"'first'",
",",
"inplace",
"=",
"False",
")",
":",
"return",
"super",
"(",
"Series",
",",
"self",
")",
".",
"drop_duplicates",
"(",
"keep",
"=",
"keep",
",",
"inplace",
"=",
"inplace",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/series.py#L1670-L1741 | |
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/vis/glprogram.py | python | GLProgram.reshape | (self,w,h) | Asks to resize the GL window | Asks to resize the GL window | [
"Asks",
"to",
"resize",
"the",
"GL",
"window"
] | def reshape(self,w,h):
"""Asks to resize the GL window"""
if self.window:
return self.window.reshape(w,h)
else:
self.view.w,self.view.h = w,h | [
"def",
"reshape",
"(",
"self",
",",
"w",
",",
"h",
")",
":",
"if",
"self",
".",
"window",
":",
"return",
"self",
".",
"window",
".",
"reshape",
"(",
"w",
",",
"h",
")",
"else",
":",
"self",
".",
"view",
".",
"w",
",",
"self",
".",
"view",
".",
"h",
"=",
"w",
",",
"h"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/vis/glprogram.py#L83-L88 | ||
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/common_shapes.py | python | get2d_conv_output_size | (input_height, input_width, filter_height,
filter_width, row_stride, col_stride, padding_type) | return get_conv_output_size((input_height, input_width),
(filter_height, filter_width),
(row_stride, col_stride), padding_type) | Returns the number of rows and columns in a convolution/pooling output. | Returns the number of rows and columns in a convolution/pooling output. | [
"Returns",
"the",
"number",
"of",
"rows",
"and",
"columns",
"in",
"a",
"convolution",
"/",
"pooling",
"output",
"."
] | def get2d_conv_output_size(input_height, input_width, filter_height,
filter_width, row_stride, col_stride, padding_type):
"""Returns the number of rows and columns in a convolution/pooling output."""
return get_conv_output_size((input_height, input_width),
(filter_height, filter_width),
(row_stride, col_stride), padding_type) | [
"def",
"get2d_conv_output_size",
"(",
"input_height",
",",
"input_width",
",",
"filter_height",
",",
"filter_width",
",",
"row_stride",
",",
"col_stride",
",",
"padding_type",
")",
":",
"return",
"get_conv_output_size",
"(",
"(",
"input_height",
",",
"input_width",
")",
",",
"(",
"filter_height",
",",
"filter_width",
")",
",",
"(",
"row_stride",
",",
"col_stride",
")",
",",
"padding_type",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/common_shapes.py#L160-L165 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/common.py | python | pipe | (obj, func, *args, **kwargs) | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, str)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
*args : iterable, optional
Positional arguments passed into ``func``.
**kwargs : dict, optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``. | Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple. | [
"Apply",
"a",
"function",
"func",
"to",
"object",
"obj",
"either",
"by",
"passing",
"obj",
"as",
"the",
"first",
"argument",
"to",
"the",
"function",
"or",
"in",
"the",
"case",
"that",
"the",
"func",
"is",
"a",
"tuple",
"interpret",
"the",
"first",
"element",
"of",
"the",
"tuple",
"as",
"a",
"function",
"and",
"pass",
"the",
"obj",
"to",
"that",
"function",
"as",
"a",
"keyword",
"argument",
"whose",
"key",
"is",
"the",
"value",
"of",
"the",
"second",
"element",
"of",
"the",
"tuple",
"."
] | def pipe(obj, func, *args, **kwargs):
"""
Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument whose key is the value of the second
element of the tuple.
Parameters
----------
func : callable or tuple of (callable, str)
Function to apply to this object or, alternatively, a
``(callable, data_keyword)`` tuple where ``data_keyword`` is a
string indicating the keyword of `callable`` that expects the
object.
*args : iterable, optional
Positional arguments passed into ``func``.
**kwargs : dict, optional
A dictionary of keyword arguments passed into ``func``.
Returns
-------
object : the return type of ``func``.
"""
if isinstance(func, tuple):
func, target = func
if target in kwargs:
msg = f"{target} is both the pipe target and a keyword argument"
raise ValueError(msg)
kwargs[target] = obj
return func(*args, **kwargs)
else:
return func(obj, *args, **kwargs) | [
"def",
"pipe",
"(",
"obj",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"tuple",
")",
":",
"func",
",",
"target",
"=",
"func",
"if",
"target",
"in",
"kwargs",
":",
"msg",
"=",
"f\"{target} is both the pipe target and a keyword argument\"",
"raise",
"ValueError",
"(",
"msg",
")",
"kwargs",
"[",
"target",
"]",
"=",
"obj",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"func",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/common.py#L429-L461 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.