nwo
stringlengths 5
106
| sha
stringlengths 40
40
| path
stringlengths 4
174
| language
stringclasses 1
value | identifier
stringlengths 1
140
| parameters
stringlengths 0
87.7k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
426k
| docstring
stringlengths 0
64.3k
| docstring_summary
stringlengths 0
26.3k
| docstring_tokens
list | function
stringlengths 18
4.83M
| function_tokens
list | url
stringlengths 83
304
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pynag/pynag
|
e72cf7ce2395263e2b3080cae0ece2b03dbbfa27
|
pynag/Model/__init__.py
|
python
|
Host.get_effective_hostgroups
|
(self)
|
return list(map(get_object, list_of_shortnames))
|
Returns a list of all Hostgroup that belong to this Host
|
Returns a list of all Hostgroup that belong to this Host
|
[
"Returns",
"a",
"list",
"of",
"all",
"Hostgroup",
"that",
"belong",
"to",
"this",
"Host"
] |
def get_effective_hostgroups(self):
""" Returns a list of all Hostgroup that belong to this Host """
get_object = lambda x: Hostgroup.objects.get_by_shortname(x, cache_only=True)
list_of_shortnames = sorted(ObjectRelations.host_hostgroups[self.host_name])
return list(map(get_object, list_of_shortnames))
|
[
"def",
"get_effective_hostgroups",
"(",
"self",
")",
":",
"get_object",
"=",
"lambda",
"x",
":",
"Hostgroup",
".",
"objects",
".",
"get_by_shortname",
"(",
"x",
",",
"cache_only",
"=",
"True",
")",
"list_of_shortnames",
"=",
"sorted",
"(",
"ObjectRelations",
".",
"host_hostgroups",
"[",
"self",
".",
"host_name",
"]",
")",
"return",
"list",
"(",
"map",
"(",
"get_object",
",",
"list_of_shortnames",
")",
")"
] |
https://github.com/pynag/pynag/blob/e72cf7ce2395263e2b3080cae0ece2b03dbbfa27/pynag/Model/__init__.py#L1637-L1641
|
|
great-expectations/great_expectations
|
45224cb890aeae725af25905923d0dbbab2d969d
|
great_expectations/validator/validator.py
|
python
|
Validator.__init__
|
(
self,
execution_engine: ExecutionEngine,
interactive_evaluation: bool = True,
expectation_suite: Optional[ExpectationSuite] = None,
expectation_suite_name: Optional[str] = None,
data_context: Optional[
Any
] = None, # Cannot type DataContext due to circular import
batches: Optional[List[Batch]] = None,
**kwargs,
)
|
Validator is the key object used to create Expectations, validate Expectations,
and get Metrics for Expectations.
Additionally, note that Validators are used by Checkpoints under-the-hood.
:param execution_engine (ExecutionEngine):
:param interactive_evaluation (bool):
:param expectation_suite (Optional[ExpectationSuite]):
:param expectation_suite_name (Optional[str]):
:param data_context (Optional[DataContext]):
:param batches (Optional[List[Batch]]):
|
Validator is the key object used to create Expectations, validate Expectations,
and get Metrics for Expectations.
|
[
"Validator",
"is",
"the",
"key",
"object",
"used",
"to",
"create",
"Expectations",
"validate",
"Expectations",
"and",
"get",
"Metrics",
"for",
"Expectations",
"."
] |
def __init__(
self,
execution_engine: ExecutionEngine,
interactive_evaluation: bool = True,
expectation_suite: Optional[ExpectationSuite] = None,
expectation_suite_name: Optional[str] = None,
data_context: Optional[
Any
] = None, # Cannot type DataContext due to circular import
batches: Optional[List[Batch]] = None,
**kwargs,
):
"""
Validator is the key object used to create Expectations, validate Expectations,
and get Metrics for Expectations.
Additionally, note that Validators are used by Checkpoints under-the-hood.
:param execution_engine (ExecutionEngine):
:param interactive_evaluation (bool):
:param expectation_suite (Optional[ExpectationSuite]):
:param expectation_suite_name (Optional[str]):
:param data_context (Optional[DataContext]):
:param batches (Optional[List[Batch]]):
"""
self._data_context = data_context
self._execution_engine = execution_engine
self._expose_dataframe_methods = False
self._validator_config = {}
if batches is None:
batches = []
self._batches = {}
self._active_batch_id = None
self.load_batch_list(batches)
if len(batches) > 1:
logger.debug(
f"{len(batches)} batches will be added to this Validator. The batch_identifiers for the active "
f"batch are {self.active_batch.batch_definition['batch_identifiers'].items()}"
)
self.interactive_evaluation = interactive_evaluation
self._initialize_expectations(
expectation_suite=expectation_suite,
expectation_suite_name=expectation_suite_name,
)
self._default_expectation_args = copy.deepcopy(
Validator.DEFAULT_RUNTIME_CONFIGURATION
)
self._validator_config = {}
# This special state variable tracks whether a validation run is going on, which will disable
# saving expectation config objects
self._active_validation = False
if self._data_context and hasattr(
self._data_context, "_expectation_explorer_manager"
):
# TODO: verify flow of default expectation arguments
self.set_default_expectation_argument("include_config", True)
|
[
"def",
"__init__",
"(",
"self",
",",
"execution_engine",
":",
"ExecutionEngine",
",",
"interactive_evaluation",
":",
"bool",
"=",
"True",
",",
"expectation_suite",
":",
"Optional",
"[",
"ExpectationSuite",
"]",
"=",
"None",
",",
"expectation_suite_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"data_context",
":",
"Optional",
"[",
"Any",
"]",
"=",
"None",
",",
"# Cannot type DataContext due to circular import",
"batches",
":",
"Optional",
"[",
"List",
"[",
"Batch",
"]",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
":",
"self",
".",
"_data_context",
"=",
"data_context",
"self",
".",
"_execution_engine",
"=",
"execution_engine",
"self",
".",
"_expose_dataframe_methods",
"=",
"False",
"self",
".",
"_validator_config",
"=",
"{",
"}",
"if",
"batches",
"is",
"None",
":",
"batches",
"=",
"[",
"]",
"self",
".",
"_batches",
"=",
"{",
"}",
"self",
".",
"_active_batch_id",
"=",
"None",
"self",
".",
"load_batch_list",
"(",
"batches",
")",
"if",
"len",
"(",
"batches",
")",
">",
"1",
":",
"logger",
".",
"debug",
"(",
"f\"{len(batches)} batches will be added to this Validator. The batch_identifiers for the active \"",
"f\"batch are {self.active_batch.batch_definition['batch_identifiers'].items()}\"",
")",
"self",
".",
"interactive_evaluation",
"=",
"interactive_evaluation",
"self",
".",
"_initialize_expectations",
"(",
"expectation_suite",
"=",
"expectation_suite",
",",
"expectation_suite_name",
"=",
"expectation_suite_name",
",",
")",
"self",
".",
"_default_expectation_args",
"=",
"copy",
".",
"deepcopy",
"(",
"Validator",
".",
"DEFAULT_RUNTIME_CONFIGURATION",
")",
"self",
".",
"_validator_config",
"=",
"{",
"}",
"# This special state variable tracks whether a validation run is going on, which will disable",
"# saving expectation config objects",
"self",
".",
"_active_validation",
"=",
"False",
"if",
"self",
".",
"_data_context",
"and",
"hasattr",
"(",
"self",
".",
"_data_context",
",",
"\"_expectation_explorer_manager\"",
")",
":",
"# TODO: verify flow of default expectation arguments",
"self",
".",
"set_default_expectation_argument",
"(",
"\"include_config\"",
",",
"True",
")"
] |
https://github.com/great-expectations/great_expectations/blob/45224cb890aeae725af25905923d0dbbab2d969d/great_expectations/validator/validator.py#L123-L185
|
||
CvvT/dumpDex
|
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
|
python/idaapi.py
|
python
|
dbg_get_registers
|
(*args)
|
return _idaapi.dbg_get_registers(*args)
|
dbg_get_registers() -> PyObject *
This function returns the register definition from the currently loaded debugger.
Basically, it returns an array of structure similar to to idd.hpp / register_info_t
@return:
None if no debugger is loaded
tuple(name, flags, class, dtyp, bit_strings, bit_strings_default_mask)
The bit_strings can be a tuple of strings or None (if the register does not have bit_strings)
|
dbg_get_registers() -> PyObject *
|
[
"dbg_get_registers",
"()",
"-",
">",
"PyObject",
"*"
] |
def dbg_get_registers(*args):
"""
dbg_get_registers() -> PyObject *
This function returns the register definition from the currently loaded debugger.
Basically, it returns an array of structure similar to to idd.hpp / register_info_t
@return:
None if no debugger is loaded
tuple(name, flags, class, dtyp, bit_strings, bit_strings_default_mask)
The bit_strings can be a tuple of strings or None (if the register does not have bit_strings)
"""
return _idaapi.dbg_get_registers(*args)
|
[
"def",
"dbg_get_registers",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"dbg_get_registers",
"(",
"*",
"args",
")"
] |
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L3442-L3454
|
|
QUANTAXIS/QUANTAXIS
|
d6eccb97c8385854aa596d6ba8d70ec0655519ff
|
QUANTAXIS/QAData/QABlockStruct.py
|
python
|
QA_DataStruct_Stock_block.view_code
|
(self)
|
return self.data.groupby(level=1).apply(
lambda x:
[item for item in x.index.remove_unused_levels().levels[0]]
)
|
按股票排列的查看blockname的视图
Returns:
[type] -- [description]
|
按股票排列的查看blockname的视图
|
[
"按股票排列的查看blockname的视图"
] |
def view_code(self):
"""按股票排列的查看blockname的视图
Returns:
[type] -- [description]
"""
return self.data.groupby(level=1).apply(
lambda x:
[item for item in x.index.remove_unused_levels().levels[0]]
)
|
[
"def",
"view_code",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"groupby",
"(",
"level",
"=",
"1",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"[",
"item",
"for",
"item",
"in",
"x",
".",
"index",
".",
"remove_unused_levels",
"(",
")",
".",
"levels",
"[",
"0",
"]",
"]",
")"
] |
https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QAData/QABlockStruct.py#L94-L104
|
|
twilio/twilio-python
|
6e1e811ea57a1edfadd5161ace87397c563f6915
|
twilio/rest/api/v2010/account/available_phone_number/__init__.py
|
python
|
AvailablePhoneNumberCountryList.stream
|
(self, limit=None, page_size=None)
|
return self._version.stream(page, limits['limit'])
|
Streams AvailablePhoneNumberCountryInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance]
|
Streams AvailablePhoneNumberCountryInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
|
[
"Streams",
"AvailablePhoneNumberCountryInstance",
"records",
"from",
"the",
"API",
"as",
"a",
"generator",
"stream",
".",
"This",
"operation",
"lazily",
"loads",
"records",
"as",
"efficiently",
"as",
"possible",
"until",
"the",
"limit",
"is",
"reached",
".",
"The",
"results",
"are",
"returned",
"as",
"a",
"generator",
"so",
"this",
"operation",
"is",
"memory",
"efficient",
"."
] |
def stream(self, limit=None, page_size=None):
"""
Streams AvailablePhoneNumberCountryInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.available_phone_number.AvailablePhoneNumberCountryInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(page_size=limits['page_size'], )
return self._version.stream(page, limits['limit'])
|
[
"def",
"stream",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"limits",
"=",
"self",
".",
"_version",
".",
"read_limits",
"(",
"limit",
",",
"page_size",
")",
"page",
"=",
"self",
".",
"page",
"(",
"page_size",
"=",
"limits",
"[",
"'page_size'",
"]",
",",
")",
"return",
"self",
".",
"_version",
".",
"stream",
"(",
"page",
",",
"limits",
"[",
"'limit'",
"]",
")"
] |
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/available_phone_number/__init__.py#L41-L62
|
|
trigger/trigger
|
c089f761a150f537f7e3201422a3964ec52ff245
|
trigger/utils/cli.py
|
python
|
proceed
|
()
|
return raw_input('\nDo you wish to proceed? [y/N] ').lower().startswith('y')
|
Present a proceed prompt. Return ``True`` if Y, else ``False``
|
Present a proceed prompt. Return ``True`` if Y, else ``False``
|
[
"Present",
"a",
"proceed",
"prompt",
".",
"Return",
"True",
"if",
"Y",
"else",
"False"
] |
def proceed():
"""Present a proceed prompt. Return ``True`` if Y, else ``False``"""
return raw_input('\nDo you wish to proceed? [y/N] ').lower().startswith('y')
|
[
"def",
"proceed",
"(",
")",
":",
"return",
"raw_input",
"(",
"'\\nDo you wish to proceed? [y/N] '",
")",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'y'",
")"
] |
https://github.com/trigger/trigger/blob/c089f761a150f537f7e3201422a3964ec52ff245/trigger/utils/cli.py#L90-L92
|
|
ilius/pyglossary
|
d599b3beda3ae17642af5debd83bb991148e6425
|
pyglossary/ui/ui_cmd_interactive.py
|
python
|
UI.getOptionValueCompleter
|
(self, option: "option.Option")
|
return None
|
[] |
def getOptionValueCompleter(self, option: "option.Option"):
values = self.getOptionValueSuggestValues(option)
if values:
return WordCompleter(
values,
ignore_case=True,
match_middle=True,
sentence=True,
)
return None
|
[
"def",
"getOptionValueCompleter",
"(",
"self",
",",
"option",
":",
"\"option.Option\"",
")",
":",
"values",
"=",
"self",
".",
"getOptionValueSuggestValues",
"(",
"option",
")",
"if",
"values",
":",
"return",
"WordCompleter",
"(",
"values",
",",
"ignore_case",
"=",
"True",
",",
"match_middle",
"=",
"True",
",",
"sentence",
"=",
"True",
",",
")",
"return",
"None"
] |
https://github.com/ilius/pyglossary/blob/d599b3beda3ae17642af5debd83bb991148e6425/pyglossary/ui/ui_cmd_interactive.py#L534-L543
|
|||
pwndbg/pwndbg
|
136b3b6a80d94f494dcb00a614af1c24ca706700
|
pwndbg/commands/next.py
|
python
|
stepsyscall
|
()
|
Breaks at the next syscall by taking branches.
|
Breaks at the next syscall by taking branches.
|
[
"Breaks",
"at",
"the",
"next",
"syscall",
"by",
"taking",
"branches",
"."
] |
def stepsyscall():
"""
Breaks at the next syscall by taking branches.
"""
while pwndbg.proc.alive and not pwndbg.next.break_next_interrupt() and pwndbg.next.break_next_branch():
# Here we are e.g. on a CALL instruction (temporarily breakpointed by `break_next_branch`)
# We need to step so that we take this branch instead of ignoring it
gdb.execute('si')
continue
if pwndbg.proc.alive:
pwndbg.commands.context.context()
|
[
"def",
"stepsyscall",
"(",
")",
":",
"while",
"pwndbg",
".",
"proc",
".",
"alive",
"and",
"not",
"pwndbg",
".",
"next",
".",
"break_next_interrupt",
"(",
")",
"and",
"pwndbg",
".",
"next",
".",
"break_next_branch",
"(",
")",
":",
"# Here we are e.g. on a CALL instruction (temporarily breakpointed by `break_next_branch`)",
"# We need to step so that we take this branch instead of ignoring it",
"gdb",
".",
"execute",
"(",
"'si'",
")",
"continue",
"if",
"pwndbg",
".",
"proc",
".",
"alive",
":",
"pwndbg",
".",
"commands",
".",
"context",
".",
"context",
"(",
")"
] |
https://github.com/pwndbg/pwndbg/blob/136b3b6a80d94f494dcb00a614af1c24ca706700/pwndbg/commands/next.py#L87-L98
|
||
veusz/veusz
|
5a1e2af5f24df0eb2a2842be51f2997c4999c7fb
|
veusz/dataimport/fits_hdf5_helpers.py
|
python
|
convertFITSDataFormat
|
(fmt)
|
return code, nlen
|
Convert FITS TFORM codes into:
(code, nlen)
code is 'invalid', 'numeric' or 'text'
nlen is number of entries for column
|
Convert FITS TFORM codes into:
|
[
"Convert",
"FITS",
"TFORM",
"codes",
"into",
":"
] |
def convertFITSDataFormat(fmt):
"""Convert FITS TFORM codes into:
(code, nlen)
code is 'invalid', 'numeric' or 'text'
nlen is number of entries for column
"""
# match the fits format text code [r]F[w[.d]]
m = re.match(r'^([0-9]*)([A-Za-z])([0-9]*)(\.[0-9]+)?$', fmt)
if not m:
return (None, 'invalid', ())
grps = m.groups()
# length of array
try:
nlen = int(grps[0])
except ValueError:
nlen = 1
fcode = grps[1].upper()
width = grps[2]
if fcode == 'A' and not width:
# note: we can't handle 2d text arrays, so we handle as invalid
code = 'text'
# even though strings are N characters, they are handled as singles
nlen = 1
elif fcode in 'LXBIJKED':
code = 'numeric'
else:
code = 'invalid'
return code, nlen
|
[
"def",
"convertFITSDataFormat",
"(",
"fmt",
")",
":",
"# match the fits format text code [r]F[w[.d]]",
"m",
"=",
"re",
".",
"match",
"(",
"r'^([0-9]*)([A-Za-z])([0-9]*)(\\.[0-9]+)?$'",
",",
"fmt",
")",
"if",
"not",
"m",
":",
"return",
"(",
"None",
",",
"'invalid'",
",",
"(",
")",
")",
"grps",
"=",
"m",
".",
"groups",
"(",
")",
"# length of array",
"try",
":",
"nlen",
"=",
"int",
"(",
"grps",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"nlen",
"=",
"1",
"fcode",
"=",
"grps",
"[",
"1",
"]",
".",
"upper",
"(",
")",
"width",
"=",
"grps",
"[",
"2",
"]",
"if",
"fcode",
"==",
"'A'",
"and",
"not",
"width",
":",
"# note: we can't handle 2d text arrays, so we handle as invalid",
"code",
"=",
"'text'",
"# even though strings are N characters, they are handled as singles",
"nlen",
"=",
"1",
"elif",
"fcode",
"in",
"'LXBIJKED'",
":",
"code",
"=",
"'numeric'",
"else",
":",
"code",
"=",
"'invalid'",
"return",
"code",
",",
"nlen"
] |
https://github.com/veusz/veusz/blob/5a1e2af5f24df0eb2a2842be51f2997c4999c7fb/veusz/dataimport/fits_hdf5_helpers.py#L217-L252
|
|
cgat-developers/ruffus
|
fc8fa8dcf7b5f4b877e5bb712146e87abd26d046
|
doc/static_data/example_scripts/intermediate_example.py
|
python
|
generate_statistical_summary_params
|
()
|
Custom function to summarising simulation results files per gene / gwas file pair
|
Custom function to summarising simulation results files per gene / gwas file pair
|
[
"Custom",
"function",
"to",
"summarising",
"simulation",
"results",
"files",
"per",
"gene",
"/",
"gwas",
"file",
"pair"
] |
def generate_statistical_summary_params():
"""
Custom function to summarising simulation results files per gene / gwas file pair
"""
gene_gwas_file_pairs, gene_gwas_file_roots = get_gene_gwas_file_pairs()
for (gene, gwas), gene_file_root in izip(gene_gwas_file_pairs, gene_gwas_file_roots):
result_glob_spec = "%s.*.simulation_res" % (gene_file_root)
result_files = glob.glob(os.path.join(working_dir, "simulation_results", result_glob_spec))
summary_file = os.path.join(working_dir, gene_file_root + ".mean")
yield result_files, summary_file
|
[
"def",
"generate_statistical_summary_params",
"(",
")",
":",
"gene_gwas_file_pairs",
",",
"gene_gwas_file_roots",
"=",
"get_gene_gwas_file_pairs",
"(",
")",
"for",
"(",
"gene",
",",
"gwas",
")",
",",
"gene_file_root",
"in",
"izip",
"(",
"gene_gwas_file_pairs",
",",
"gene_gwas_file_roots",
")",
":",
"result_glob_spec",
"=",
"\"%s.*.simulation_res\"",
"%",
"(",
"gene_file_root",
")",
"result_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"\"simulation_results\"",
",",
"result_glob_spec",
")",
")",
"summary_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"gene_file_root",
"+",
"\".mean\"",
")",
"yield",
"result_files",
",",
"summary_file"
] |
https://github.com/cgat-developers/ruffus/blob/fc8fa8dcf7b5f4b877e5bb712146e87abd26d046/doc/static_data/example_scripts/intermediate_example.py#L261-L272
|
||
tbertinmahieux/MSongsDB
|
0c276e289606d5bd6f3991f713e7e9b1d4384e44
|
Tasks_Demos/Preview7digital/player_7digital.py
|
python
|
die_with_usage
|
()
|
HELP MENU
|
HELP MENU
|
[
"HELP",
"MENU"
] |
def die_with_usage():
""" HELP MENU """
print 'player_7digital.py'
print ' by T. Bertin-Mahieux (2011) Columbia University'
print ' [email protected]'
print 'Small interface to the 7digital service.'
print 'INPUT'
print ' python player_7digital.py track_metadata.db'
print 'REQUIREMENTS'
print ' * 7digital key in your environment as: DIGITAL7_API_KEY'
print ' * pyao'
print ' * pymad'
print ' * Tkinter for python'
print ' * track_metadata.db (new one with 7digital ids, check website)'
sys.exit(0)
|
[
"def",
"die_with_usage",
"(",
")",
":",
"print",
"'player_7digital.py'",
"print",
"' by T. Bertin-Mahieux (2011) Columbia University'",
"print",
"' [email protected]'",
"print",
"'Small interface to the 7digital service.'",
"print",
"'INPUT'",
"print",
"' python player_7digital.py track_metadata.db'",
"print",
"'REQUIREMENTS'",
"print",
"' * 7digital key in your environment as: DIGITAL7_API_KEY'",
"print",
"' * pyao'",
"print",
"' * pymad'",
"print",
"' * Tkinter for python'",
"print",
"' * track_metadata.db (new one with 7digital ids, check website)'",
"sys",
".",
"exit",
"(",
"0",
")"
] |
https://github.com/tbertinmahieux/MSongsDB/blob/0c276e289606d5bd6f3991f713e7e9b1d4384e44/Tasks_Demos/Preview7digital/player_7digital.py#L279-L293
|
||
decisionforce/TPN
|
117a4d187517f51ea914b17be8ac59ef1a36b594
|
mmaction/utils/misc.py
|
python
|
rsetattr
|
(obj, attr, val)
|
return setattr(rgetattr(obj, pre) if pre else obj, post, val)
|
See:
https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
|
See:
https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
|
[
"See",
":",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"31174295",
"/",
"getattr",
"-",
"and",
"-",
"setattr",
"-",
"on",
"-",
"nested",
"-",
"objects"
] |
def rsetattr(obj, attr, val):
'''
See:
https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
'''
pre, _, post = attr.rpartition('.')
return setattr(rgetattr(obj, pre) if pre else obj, post, val)
|
[
"def",
"rsetattr",
"(",
"obj",
",",
"attr",
",",
"val",
")",
":",
"pre",
",",
"_",
",",
"post",
"=",
"attr",
".",
"rpartition",
"(",
"'.'",
")",
"return",
"setattr",
"(",
"rgetattr",
"(",
"obj",
",",
"pre",
")",
"if",
"pre",
"else",
"obj",
",",
"post",
",",
"val",
")"
] |
https://github.com/decisionforce/TPN/blob/117a4d187517f51ea914b17be8ac59ef1a36b594/mmaction/utils/misc.py#L6-L12
|
|
Kozea/cairocffi
|
2473d1bb82a52ca781edec595a95951509db2969
|
cairocffi/context.py
|
python
|
Context.scale
|
(self, sx, sy=None)
|
Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
If :obj:`sy` is omitted, it is the same as :obj:`sx`
so that scaling preserves aspect ratios.
:param sx: Scale factor in the X direction.
:param sy: Scale factor in the Y direction.
:type sx: float
:type sy: float
|
Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
|
[
"Modifies",
"the",
"current",
"transformation",
"matrix",
"(",
"CTM",
")",
"by",
"scaling",
"the",
"X",
"and",
"Y",
"user",
"-",
"space",
"axes",
"by",
":",
"obj",
":",
"sx",
"and",
":",
"obj",
":",
"sy",
"respectively",
".",
"The",
"scaling",
"of",
"the",
"axes",
"takes",
"place",
"after",
"any",
"existing",
"transformation",
"of",
"user",
"space",
"."
] |
def scale(self, sx, sy=None):
"""Modifies the current transformation matrix (CTM)
by scaling the X and Y user-space axes
by :obj:`sx` and :obj:`sy` respectively.
The scaling of the axes takes place after
any existing transformation of user space.
If :obj:`sy` is omitted, it is the same as :obj:`sx`
so that scaling preserves aspect ratios.
:param sx: Scale factor in the X direction.
:param sy: Scale factor in the Y direction.
:type sx: float
:type sy: float
"""
if sy is None:
sy = sx
cairo.cairo_scale(self._pointer, sx, sy)
self._check_status()
|
[
"def",
"scale",
"(",
"self",
",",
"sx",
",",
"sy",
"=",
"None",
")",
":",
"if",
"sy",
"is",
"None",
":",
"sy",
"=",
"sx",
"cairo",
".",
"cairo_scale",
"(",
"self",
".",
"_pointer",
",",
"sx",
",",
"sy",
")",
"self",
".",
"_check_status",
"(",
")"
] |
https://github.com/Kozea/cairocffi/blob/2473d1bb82a52ca781edec595a95951509db2969/cairocffi/context.py#L687-L706
|
||
bendmorris/static-python
|
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
|
Lib/lib2to3/pytree.py
|
python
|
Node.set_child
|
(self, i, child)
|
Equivalent to 'node.children[i] = child'. This method also sets the
child's parent attribute appropriately.
|
Equivalent to 'node.children[i] = child'. This method also sets the
child's parent attribute appropriately.
|
[
"Equivalent",
"to",
"node",
".",
"children",
"[",
"i",
"]",
"=",
"child",
".",
"This",
"method",
"also",
"sets",
"the",
"child",
"s",
"parent",
"attribute",
"appropriately",
"."
] |
def set_child(self, i, child):
"""
Equivalent to 'node.children[i] = child'. This method also sets the
child's parent attribute appropriately.
"""
child.parent = self
self.children[i].parent = None
self.children[i] = child
self.changed()
|
[
"def",
"set_child",
"(",
"self",
",",
"i",
",",
"child",
")",
":",
"child",
".",
"parent",
"=",
"self",
"self",
".",
"children",
"[",
"i",
"]",
".",
"parent",
"=",
"None",
"self",
".",
"children",
"[",
"i",
"]",
"=",
"child",
"self",
".",
"changed",
"(",
")"
] |
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/lib2to3/pytree.py#L299-L307
|
||
lbryio/torba
|
190304344c0ff68f8a24cf50272307a11bf7f62b
|
torba/rpc/jsonrpc.py
|
python
|
JSONRPCv1.request_payload
|
(cls, request, request_id)
|
return {
'method': request.method,
'params': request.args,
'id': request_id
}
|
JSON v1 request (or notification) payload.
|
JSON v1 request (or notification) payload.
|
[
"JSON",
"v1",
"request",
"(",
"or",
"notification",
")",
"payload",
"."
] |
def request_payload(cls, request, request_id):
"""JSON v1 request (or notification) payload."""
if isinstance(request.args, dict):
raise ProtocolError.invalid_args(
'JSONRPCv1 does not support named arguments')
return {
'method': request.method,
'params': request.args,
'id': request_id
}
|
[
"def",
"request_payload",
"(",
"cls",
",",
"request",
",",
"request_id",
")",
":",
"if",
"isinstance",
"(",
"request",
".",
"args",
",",
"dict",
")",
":",
"raise",
"ProtocolError",
".",
"invalid_args",
"(",
"'JSONRPCv1 does not support named arguments'",
")",
"return",
"{",
"'method'",
":",
"request",
".",
"method",
",",
"'params'",
":",
"request",
".",
"args",
",",
"'id'",
":",
"request_id",
"}"
] |
https://github.com/lbryio/torba/blob/190304344c0ff68f8a24cf50272307a11bf7f62b/torba/rpc/jsonrpc.py#L394-L403
|
|
securesystemslab/zippy
|
ff0e84ac99442c2c55fe1d285332cfd4e185e089
|
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/dense.py
|
python
|
DenseMatrix.__pow__
|
(self, other)
|
return super(DenseMatrix, self).__pow__(other)
|
[] |
def __pow__(self, other):
return super(DenseMatrix, self).__pow__(other)
|
[
"def",
"__pow__",
"(",
"self",
",",
"other",
")",
":",
"return",
"super",
"(",
"DenseMatrix",
",",
"self",
")",
".",
"__pow__",
"(",
"other",
")"
] |
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/dense.py#L562-L563
|
|||
openedx/edx-platform
|
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
|
lms/djangoapps/experiments/flags.py
|
python
|
ExperimentWaffleFlag._is_enrollment_inside_date_bounds
|
(self, experiment_values, user, course_key)
|
return True
|
Returns True if the user's enrollment (if any) is valid for the configured experiment date range
|
Returns True if the user's enrollment (if any) is valid for the configured experiment date range
|
[
"Returns",
"True",
"if",
"the",
"user",
"s",
"enrollment",
"(",
"if",
"any",
")",
"is",
"valid",
"for",
"the",
"configured",
"experiment",
"date",
"range"
] |
def _is_enrollment_inside_date_bounds(self, experiment_values, user, course_key):
""" Returns True if the user's enrollment (if any) is valid for the configured experiment date range """
from common.djangoapps.student.models import CourseEnrollment
enrollment_start = experiment_values.get('enrollment_start')
enrollment_end = experiment_values.get('enrollment_end')
if not enrollment_start and not enrollment_end:
return True # early exit just to avoid any further lookups
now = datetime.datetime.now(pytz.utc)
enrollment = CourseEnrollment.get_enrollment(user, course_key)
# If the user isn't enrolled, act like they would enroll right now (this keeps the pre-enroll and post-enroll
# experiences the same, if they decide to enroll right now)
enrollment_creation_date = enrollment.created if enrollment else now
# Enrollment must be after any enrollment_start date, if specified
if enrollment_start:
try:
start_date = dateutil.parser.parse(enrollment_start).replace(tzinfo=pytz.UTC)
except ValueError:
log.exception('Could not parse enrollment start date for experiment %d', self.experiment_id)
return False
if enrollment_creation_date < start_date:
return False
# Enrollment must be before any enrollment_end date, if specified
if enrollment_end:
try:
end_date = dateutil.parser.parse(enrollment_end).replace(tzinfo=pytz.UTC)
except ValueError:
log.exception('Could not parse enrollment end date for experiment %d', self.experiment_id)
return False
if enrollment_creation_date >= end_date:
return False
# All good! Either because the key was not set or because the enrollment was valid
return True
|
[
"def",
"_is_enrollment_inside_date_bounds",
"(",
"self",
",",
"experiment_values",
",",
"user",
",",
"course_key",
")",
":",
"from",
"common",
".",
"djangoapps",
".",
"student",
".",
"models",
"import",
"CourseEnrollment",
"enrollment_start",
"=",
"experiment_values",
".",
"get",
"(",
"'enrollment_start'",
")",
"enrollment_end",
"=",
"experiment_values",
".",
"get",
"(",
"'enrollment_end'",
")",
"if",
"not",
"enrollment_start",
"and",
"not",
"enrollment_end",
":",
"return",
"True",
"# early exit just to avoid any further lookups",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"pytz",
".",
"utc",
")",
"enrollment",
"=",
"CourseEnrollment",
".",
"get_enrollment",
"(",
"user",
",",
"course_key",
")",
"# If the user isn't enrolled, act like they would enroll right now (this keeps the pre-enroll and post-enroll",
"# experiences the same, if they decide to enroll right now)",
"enrollment_creation_date",
"=",
"enrollment",
".",
"created",
"if",
"enrollment",
"else",
"now",
"# Enrollment must be after any enrollment_start date, if specified",
"if",
"enrollment_start",
":",
"try",
":",
"start_date",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"enrollment_start",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"UTC",
")",
"except",
"ValueError",
":",
"log",
".",
"exception",
"(",
"'Could not parse enrollment start date for experiment %d'",
",",
"self",
".",
"experiment_id",
")",
"return",
"False",
"if",
"enrollment_creation_date",
"<",
"start_date",
":",
"return",
"False",
"# Enrollment must be before any enrollment_end date, if specified",
"if",
"enrollment_end",
":",
"try",
":",
"end_date",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"enrollment_end",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"UTC",
")",
"except",
"ValueError",
":",
"log",
".",
"exception",
"(",
"'Could not parse enrollment end date for experiment %d'",
",",
"self",
".",
"experiment_id",
")",
"return",
"False",
"if",
"enrollment_creation_date",
">=",
"end_date",
":",
"return",
"False",
"# All good! Either because the key was not set or because the enrollment was valid",
"return",
"True"
] |
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/experiments/flags.py#L116-L153
|
|
mfessenden/SceneGraph
|
0fa3429059c77c881d1b58b28e89dcb44c609909
|
ui/attributes.py
|
python
|
ColorPicker.initializeEditor
|
(self)
|
Set the widgets nodes values.
|
Set the widgets nodes values.
|
[
"Set",
"the",
"widgets",
"nodes",
"values",
"."
] |
def initializeEditor(self):
"""
Set the widgets nodes values.
"""
if not self.nodes or not self.attribute:
return
editor_value = self.default_value
node_values = self.values
if node_values:
if len(node_values) > 1:
pass
elif len(node_values) == 1:
if node_values[0]:
editor_value = node_values[0]
# set the editor value
self.colorSwatch.setColor(editor_value)
|
[
"def",
"initializeEditor",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"nodes",
"or",
"not",
"self",
".",
"attribute",
":",
"return",
"editor_value",
"=",
"self",
".",
"default_value",
"node_values",
"=",
"self",
".",
"values",
"if",
"node_values",
":",
"if",
"len",
"(",
"node_values",
")",
">",
"1",
":",
"pass",
"elif",
"len",
"(",
"node_values",
")",
"==",
"1",
":",
"if",
"node_values",
"[",
"0",
"]",
":",
"editor_value",
"=",
"node_values",
"[",
"0",
"]",
"# set the editor value",
"self",
".",
"colorSwatch",
".",
"setColor",
"(",
"editor_value",
")"
] |
https://github.com/mfessenden/SceneGraph/blob/0fa3429059c77c881d1b58b28e89dcb44c609909/ui/attributes.py#L1946-L1965
|
||
roclark/sportsipy
|
c19f545d3376d62ded6304b137dc69238ac620a9
|
sportsipy/mlb/schedule.py
|
python
|
Game.loser
|
(self)
|
return self._loser
|
Returns a ``string`` of the name of the losing pitcher.
|
Returns a ``string`` of the name of the losing pitcher.
|
[
"Returns",
"a",
"string",
"of",
"the",
"name",
"of",
"the",
"losing",
"pitcher",
"."
] |
def loser(self):
"""
Returns a ``string`` of the name of the losing pitcher.
"""
return self._loser
|
[
"def",
"loser",
"(",
"self",
")",
":",
"return",
"self",
".",
"_loser"
] |
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/mlb/schedule.py#L318-L322
|
|
ahmetcemturan/SFACT
|
7576e29ba72b33e5058049b77b7b558875542747
|
skeinforge_application/skeinforge_utilities/skeinforge_profile.py
|
python
|
ProfileListboxSetting.focusIn
|
(self, event)
|
The root has gained focus.
|
The root has gained focus.
|
[
"The",
"root",
"has",
"gained",
"focus",
"."
] |
def focusIn(self, event):
"The root has gained focus."
settings.getReadRepository(self.repository)
self.setStateToValue()
|
[
"def",
"focusIn",
"(",
"self",
",",
"event",
")",
":",
"settings",
".",
"getReadRepository",
"(",
"self",
".",
"repository",
")",
"self",
".",
"setStateToValue",
"(",
")"
] |
https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/skeinforge_application/skeinforge_utilities/skeinforge_profile.py#L260-L263
|
||
apple/coremltools
|
141a83af482fcbdd5179807c9eaff9a7999c2c49
|
coremltools/models/neural_network/builder.py
|
python
|
NeuralNetworkBuilder.add_logical
|
(self, name, input_names, output_name, mode)
|
return spec_layer
|
Add a logical layer to the model that performs element-wise logical
and/or/xor/not operation. Broadcasting is supported.
Refer to the ``LogicalOrLayerParams``, ``LogicalNotLayerParams``,
``LogicalNotLayerParams``, and ``LogicalAndLayerParam`` messages in the specification
(NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_names: list of str
The input blob names of this layer.
output_name: str
The output blob name of this layer.
mode: str
Logical operation mode in [AND | OR | XOR | NOT].
|
Add a logical layer to the model that performs element-wise logical
and/or/xor/not operation. Broadcasting is supported.
Refer to the ``LogicalOrLayerParams``, ``LogicalNotLayerParams``,
``LogicalNotLayerParams``, and ``LogicalAndLayerParam`` messages in the specification
(NeuralNetwork.proto) for more details.
|
[
"Add",
"a",
"logical",
"layer",
"to",
"the",
"model",
"that",
"performs",
"element",
"-",
"wise",
"logical",
"and",
"/",
"or",
"/",
"xor",
"/",
"not",
"operation",
".",
"Broadcasting",
"is",
"supported",
".",
"Refer",
"to",
"the",
"LogicalOrLayerParams",
"LogicalNotLayerParams",
"LogicalNotLayerParams",
"and",
"LogicalAndLayerParam",
"messages",
"in",
"the",
"specification",
"(",
"NeuralNetwork",
".",
"proto",
")",
"for",
"more",
"details",
"."
] |
def add_logical(self, name, input_names, output_name, mode):
"""
Add a logical layer to the model that performs element-wise logical
and/or/xor/not operation. Broadcasting is supported.
Refer to the ``LogicalOrLayerParams``, ``LogicalNotLayerParams``,
``LogicalNotLayerParams``, and ``LogicalAndLayerParam`` messages in the specification
(NeuralNetwork.proto) for more details.
Parameters
----------
name: str
The name of this layer.
input_names: list of str
The input blob names of this layer.
output_name: str
The output blob name of this layer.
mode: str
Logical operation mode in [AND | OR | XOR | NOT].
"""
if isinstance(input_names, str):
input_names = [input_names]
spec_layer = self._add_generic_layer(name, input_names, [output_name])
if mode in ["AND", "OR", "XOR"] and len(input_names) != 2:
raise ValueError('Logical operation "%s" requires 2 inputs' % name)
if mode in ["NOT"] and len(input_names) != 1:
raise ValueError('Logical operation "%s" requires 1 input' % name)
if mode == "AND":
spec_layer.logicalAnd.MergeFromString(b"")
elif mode == "OR":
spec_layer.logicalOr.MergeFromString(b"")
elif mode == "XOR":
spec_layer.logicalXor.MergeFromString(b"")
elif mode == "NOT":
spec_layer.logicalNot.MergeFromString(b"")
else:
raise ValueError('Logical operation "%s" is not supported' % mode)
return spec_layer
|
[
"def",
"add_logical",
"(",
"self",
",",
"name",
",",
"input_names",
",",
"output_name",
",",
"mode",
")",
":",
"if",
"isinstance",
"(",
"input_names",
",",
"str",
")",
":",
"input_names",
"=",
"[",
"input_names",
"]",
"spec_layer",
"=",
"self",
".",
"_add_generic_layer",
"(",
"name",
",",
"input_names",
",",
"[",
"output_name",
"]",
")",
"if",
"mode",
"in",
"[",
"\"AND\"",
",",
"\"OR\"",
",",
"\"XOR\"",
"]",
"and",
"len",
"(",
"input_names",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Logical operation \"%s\" requires 2 inputs'",
"%",
"name",
")",
"if",
"mode",
"in",
"[",
"\"NOT\"",
"]",
"and",
"len",
"(",
"input_names",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Logical operation \"%s\" requires 1 input'",
"%",
"name",
")",
"if",
"mode",
"==",
"\"AND\"",
":",
"spec_layer",
".",
"logicalAnd",
".",
"MergeFromString",
"(",
"b\"\"",
")",
"elif",
"mode",
"==",
"\"OR\"",
":",
"spec_layer",
".",
"logicalOr",
".",
"MergeFromString",
"(",
"b\"\"",
")",
"elif",
"mode",
"==",
"\"XOR\"",
":",
"spec_layer",
".",
"logicalXor",
".",
"MergeFromString",
"(",
"b\"\"",
")",
"elif",
"mode",
"==",
"\"NOT\"",
":",
"spec_layer",
".",
"logicalNot",
".",
"MergeFromString",
"(",
"b\"\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Logical operation \"%s\" is not supported'",
"%",
"mode",
")",
"return",
"spec_layer"
] |
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/models/neural_network/builder.py#L6324-L6365
|
|
openshift/openshift-tools
|
1188778e728a6e4781acf728123e5b356380fe6f
|
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_secret.py
|
python
|
OpenShiftCLI._list_pods
|
(self, node=None, selector=None, pod_selector=None)
|
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided
|
perform oadm list pods
|
[
"perform",
"oadm",
"list",
"pods"
] |
def _list_pods(self, node=None, selector=None, pod_selector=None):
''' perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided
'''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
|
[
"def",
"_list_pods",
"(",
"self",
",",
"node",
"=",
"None",
",",
"selector",
"=",
"None",
",",
"pod_selector",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'manage-node'",
"]",
"if",
"node",
":",
"cmd",
".",
"extend",
"(",
"node",
")",
"else",
":",
"cmd",
".",
"append",
"(",
"'--selector={}'",
".",
"format",
"(",
"selector",
")",
")",
"if",
"pod_selector",
":",
"cmd",
".",
"append",
"(",
"'--pod-selector={}'",
".",
"format",
"(",
"pod_selector",
")",
")",
"cmd",
".",
"extend",
"(",
"[",
"'--list-pods'",
",",
"'-o'",
",",
"'json'",
"]",
")",
"return",
"self",
".",
"openshift_cmd",
"(",
"cmd",
",",
"oadm",
"=",
"True",
",",
"output",
"=",
"True",
",",
"output_type",
"=",
"'raw'",
")"
] |
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_secret.py#L1084-L1102
|
|
smart-mobile-software/gitstack
|
d9fee8f414f202143eb6e620529e8e5539a2af56
|
python/Lib/site-packages/django/views/generic/list_detail.py
|
python
|
object_list
|
(request, queryset, paginate_by=None, page=None,
allow_empty=True, template_name=None, template_loader=loader,
extra_context=None, context_processors=None, template_object_name='object',
mimetype=None)
|
return HttpResponse(t.render(c), mimetype=mimetype)
|
Generic list of objects.
Templates: ``<app_label>/<model_name>_list.html``
Context:
object_list
list of objects
is_paginated
are the results paginated?
results_per_page
number of objects per page (if paginated)
has_next
is there a next page?
has_previous
is there a prev page?
page
the current page
next
the next page
previous
the previous page
pages
number of pages, total
hits
number of objects, total
last_on_page
the result number of the last of object in the
object_list (1-indexed)
first_on_page
the result number of the first object in the
object_list (1-indexed)
page_range:
A list of the page numbers (1-indexed).
|
Generic list of objects.
|
[
"Generic",
"list",
"of",
"objects",
"."
] |
def object_list(request, queryset, paginate_by=None, page=None,
allow_empty=True, template_name=None, template_loader=loader,
extra_context=None, context_processors=None, template_object_name='object',
mimetype=None):
"""
Generic list of objects.
Templates: ``<app_label>/<model_name>_list.html``
Context:
object_list
list of objects
is_paginated
are the results paginated?
results_per_page
number of objects per page (if paginated)
has_next
is there a next page?
has_previous
is there a prev page?
page
the current page
next
the next page
previous
the previous page
pages
number of pages, total
hits
number of objects, total
last_on_page
the result number of the last of object in the
object_list (1-indexed)
first_on_page
the result number of the first object in the
object_list (1-indexed)
page_range:
A list of the page numbers (1-indexed).
"""
if extra_context is None: extra_context = {}
queryset = queryset._clone()
if paginate_by:
paginator = Paginator(queryset, paginate_by, allow_empty_first_page=allow_empty)
if not page:
page = request.GET.get('page', 1)
try:
page_number = int(page)
except ValueError:
if page == 'last':
page_number = paginator.num_pages
else:
# Page is not 'last', nor can it be converted to an int.
raise Http404
try:
page_obj = paginator.page(page_number)
except InvalidPage:
raise Http404
c = RequestContext(request, {
'%s_list' % template_object_name: page_obj.object_list,
'paginator': paginator,
'page_obj': page_obj,
'is_paginated': page_obj.has_other_pages(),
# Legacy template context stuff. New templates should use page_obj
# to access this instead.
'results_per_page': paginator.per_page,
'has_next': page_obj.has_next(),
'has_previous': page_obj.has_previous(),
'page': page_obj.number,
'next': page_obj.next_page_number(),
'previous': page_obj.previous_page_number(),
'first_on_page': page_obj.start_index(),
'last_on_page': page_obj.end_index(),
'pages': paginator.num_pages,
'hits': paginator.count,
'page_range': paginator.page_range,
}, context_processors)
else:
c = RequestContext(request, {
'%s_list' % template_object_name: queryset,
'paginator': None,
'page_obj': None,
'is_paginated': False,
}, context_processors)
if not allow_empty and len(queryset) == 0:
raise Http404
for key, value in extra_context.items():
if callable(value):
c[key] = value()
else:
c[key] = value
if not template_name:
model = queryset.model
template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower())
t = template_loader.get_template(template_name)
return HttpResponse(t.render(c), mimetype=mimetype)
|
[
"def",
"object_list",
"(",
"request",
",",
"queryset",
",",
"paginate_by",
"=",
"None",
",",
"page",
"=",
"None",
",",
"allow_empty",
"=",
"True",
",",
"template_name",
"=",
"None",
",",
"template_loader",
"=",
"loader",
",",
"extra_context",
"=",
"None",
",",
"context_processors",
"=",
"None",
",",
"template_object_name",
"=",
"'object'",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"extra_context",
"is",
"None",
":",
"extra_context",
"=",
"{",
"}",
"queryset",
"=",
"queryset",
".",
"_clone",
"(",
")",
"if",
"paginate_by",
":",
"paginator",
"=",
"Paginator",
"(",
"queryset",
",",
"paginate_by",
",",
"allow_empty_first_page",
"=",
"allow_empty",
")",
"if",
"not",
"page",
":",
"page",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
",",
"1",
")",
"try",
":",
"page_number",
"=",
"int",
"(",
"page",
")",
"except",
"ValueError",
":",
"if",
"page",
"==",
"'last'",
":",
"page_number",
"=",
"paginator",
".",
"num_pages",
"else",
":",
"# Page is not 'last', nor can it be converted to an int.",
"raise",
"Http404",
"try",
":",
"page_obj",
"=",
"paginator",
".",
"page",
"(",
"page_number",
")",
"except",
"InvalidPage",
":",
"raise",
"Http404",
"c",
"=",
"RequestContext",
"(",
"request",
",",
"{",
"'%s_list'",
"%",
"template_object_name",
":",
"page_obj",
".",
"object_list",
",",
"'paginator'",
":",
"paginator",
",",
"'page_obj'",
":",
"page_obj",
",",
"'is_paginated'",
":",
"page_obj",
".",
"has_other_pages",
"(",
")",
",",
"# Legacy template context stuff. New templates should use page_obj",
"# to access this instead.",
"'results_per_page'",
":",
"paginator",
".",
"per_page",
",",
"'has_next'",
":",
"page_obj",
".",
"has_next",
"(",
")",
",",
"'has_previous'",
":",
"page_obj",
".",
"has_previous",
"(",
")",
",",
"'page'",
":",
"page_obj",
".",
"number",
",",
"'next'",
":",
"page_obj",
".",
"next_page_number",
"(",
")",
",",
"'previous'",
":",
"page_obj",
".",
"previous_page_number",
"(",
")",
",",
"'first_on_page'",
":",
"page_obj",
".",
"start_index",
"(",
")",
",",
"'last_on_page'",
":",
"page_obj",
".",
"end_index",
"(",
")",
",",
"'pages'",
":",
"paginator",
".",
"num_pages",
",",
"'hits'",
":",
"paginator",
".",
"count",
",",
"'page_range'",
":",
"paginator",
".",
"page_range",
",",
"}",
",",
"context_processors",
")",
"else",
":",
"c",
"=",
"RequestContext",
"(",
"request",
",",
"{",
"'%s_list'",
"%",
"template_object_name",
":",
"queryset",
",",
"'paginator'",
":",
"None",
",",
"'page_obj'",
":",
"None",
",",
"'is_paginated'",
":",
"False",
",",
"}",
",",
"context_processors",
")",
"if",
"not",
"allow_empty",
"and",
"len",
"(",
"queryset",
")",
"==",
"0",
":",
"raise",
"Http404",
"for",
"key",
",",
"value",
"in",
"extra_context",
".",
"items",
"(",
")",
":",
"if",
"callable",
"(",
"value",
")",
":",
"c",
"[",
"key",
"]",
"=",
"value",
"(",
")",
"else",
":",
"c",
"[",
"key",
"]",
"=",
"value",
"if",
"not",
"template_name",
":",
"model",
"=",
"queryset",
".",
"model",
"template_name",
"=",
"\"%s/%s_list.html\"",
"%",
"(",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
")",
"t",
"=",
"template_loader",
".",
"get_template",
"(",
"template_name",
")",
"return",
"HttpResponse",
"(",
"t",
".",
"render",
"(",
"c",
")",
",",
"mimetype",
"=",
"mimetype",
")"
] |
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/views/generic/list_detail.py#L14-L108
|
|
Arelle/Arelle
|
20f3d8a8afd41668e1520799acd333349ce0ba17
|
arelle/ModelInstanceObject.py
|
python
|
ModelInlineValueObject.stringValue
|
(self)
|
return self.value
|
(str) -- override xml-level stringValue for transformed value descendants text
will raise any value errors if transforming string or numeric has an error
|
(str) -- override xml-level stringValue for transformed value descendants text
will raise any value errors if transforming string or numeric has an error
|
[
"(",
"str",
")",
"--",
"override",
"xml",
"-",
"level",
"stringValue",
"for",
"transformed",
"value",
"descendants",
"text",
"will",
"raise",
"any",
"value",
"errors",
"if",
"transforming",
"string",
"or",
"numeric",
"has",
"an",
"error"
] |
def stringValue(self):
"""(str) -- override xml-level stringValue for transformed value descendants text
will raise any value errors if transforming string or numeric has an error
"""
return self.value
|
[
"def",
"stringValue",
"(",
"self",
")",
":",
"return",
"self",
".",
"value"
] |
https://github.com/Arelle/Arelle/blob/20f3d8a8afd41668e1520799acd333349ce0ba17/arelle/ModelInstanceObject.py#L697-L701
|
|
mtianyan/VueDjangoAntdProBookShop
|
fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2
|
third_party/social_core/backends/saml.py
|
python
|
SAMLAuth.get_user_id
|
(self, details, response)
|
return '{0}:{1}'.format(idp.name, uid)
|
Get the permanent ID for this user from the response.
We prefix each ID with the name of the IdP so that we can
connect multiple IdPs to this user.
|
Get the permanent ID for this user from the response.
We prefix each ID with the name of the IdP so that we can
connect multiple IdPs to this user.
|
[
"Get",
"the",
"permanent",
"ID",
"for",
"this",
"user",
"from",
"the",
"response",
".",
"We",
"prefix",
"each",
"ID",
"with",
"the",
"name",
"of",
"the",
"IdP",
"so",
"that",
"we",
"can",
"connect",
"multiple",
"IdPs",
"to",
"this",
"user",
"."
] |
def get_user_id(self, details, response):
"""
Get the permanent ID for this user from the response.
We prefix each ID with the name of the IdP so that we can
connect multiple IdPs to this user.
"""
idp = self.get_idp(response['idp_name'])
uid = idp.get_user_permanent_id(response['attributes'])
return '{0}:{1}'.format(idp.name, uid)
|
[
"def",
"get_user_id",
"(",
"self",
",",
"details",
",",
"response",
")",
":",
"idp",
"=",
"self",
".",
"get_idp",
"(",
"response",
"[",
"'idp_name'",
"]",
")",
"uid",
"=",
"idp",
".",
"get_user_permanent_id",
"(",
"response",
"[",
"'attributes'",
"]",
")",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"idp",
".",
"name",
",",
"uid",
")"
] |
https://github.com/mtianyan/VueDjangoAntdProBookShop/blob/fd8fa2151c81edde2f8b8e6df8e1ddd799f940c2/third_party/social_core/backends/saml.py#L282-L290
|
|
SBCV/Blender-Addon-Photogrammetry-Importer
|
d964ef04cefde73320749cc346113e16be5bd73b
|
photogrammetry_importer/opengl/draw_manager.py
|
python
|
DrawManager.register_points_draw_callback
|
(
self, object_anchor, coords, colors, point_size
)
|
Register a callback to draw a point cloud.
|
Register a callback to draw a point cloud.
|
[
"Register",
"a",
"callback",
"to",
"draw",
"a",
"point",
"cloud",
"."
] |
def register_points_draw_callback(
self, object_anchor, coords, colors, point_size
):
"""Register a callback to draw a point cloud."""
draw_callback_handler = _DrawCallBackHandler()
draw_callback_handler.register_points_draw_callback(
self, object_anchor, coords, colors, point_size
)
self._anchor_to_draw_callback_handler[
object_anchor
] = draw_callback_handler
self._anchor_to_point_coords[object_anchor] = coords
self._anchor_to_point_colors[object_anchor] = colors
|
[
"def",
"register_points_draw_callback",
"(",
"self",
",",
"object_anchor",
",",
"coords",
",",
"colors",
",",
"point_size",
")",
":",
"draw_callback_handler",
"=",
"_DrawCallBackHandler",
"(",
")",
"draw_callback_handler",
".",
"register_points_draw_callback",
"(",
"self",
",",
"object_anchor",
",",
"coords",
",",
"colors",
",",
"point_size",
")",
"self",
".",
"_anchor_to_draw_callback_handler",
"[",
"object_anchor",
"]",
"=",
"draw_callback_handler",
"self",
".",
"_anchor_to_point_coords",
"[",
"object_anchor",
"]",
"=",
"coords",
"self",
".",
"_anchor_to_point_colors",
"[",
"object_anchor",
"]",
"=",
"colors"
] |
https://github.com/SBCV/Blender-Addon-Photogrammetry-Importer/blob/d964ef04cefde73320749cc346113e16be5bd73b/photogrammetry_importer/opengl/draw_manager.py#L51-L63
|
||
OUCMachineLearning/OUCML
|
5b54337d7c0316084cb1a74befda2bba96137d4a
|
One_Day_One_GAN/day18/Self-Supervised-GANs-master/utils.py
|
python
|
STL.getNextBatch2
|
(self, batch_num=0, batch_size=100)
|
return self.train_data_list[(batch_num % self.ro_num) * batch_size: (batch_num % self.ro_num + 1) * batch_size]
|
[] |
def getNextBatch2(self, batch_num=0, batch_size=100):
return self.train_data_list[(batch_num % self.ro_num) * batch_size: (batch_num % self.ro_num + 1) * batch_size]
|
[
"def",
"getNextBatch2",
"(",
"self",
",",
"batch_num",
"=",
"0",
",",
"batch_size",
"=",
"100",
")",
":",
"return",
"self",
".",
"train_data_list",
"[",
"(",
"batch_num",
"%",
"self",
".",
"ro_num",
")",
"*",
"batch_size",
":",
"(",
"batch_num",
"%",
"self",
".",
"ro_num",
"+",
"1",
")",
"*",
"batch_size",
"]"
] |
https://github.com/OUCMachineLearning/OUCML/blob/5b54337d7c0316084cb1a74befda2bba96137d4a/One_Day_One_GAN/day18/Self-Supervised-GANs-master/utils.py#L71-L72
|
|||
napari/napari
|
dbf4158e801fa7a429de8ef1cdee73bf6d64c61e
|
napari/components/dims.py
|
python
|
reorder_after_dim_reduction
|
(order)
|
return tuple(arr)
|
Ensure current dimension order is preserved after dims are dropped.
Parameters
----------
order : tuple
The data to reorder.
Returns
-------
arr : tuple
The original array with the unneeded dimension
thrown away.
|
Ensure current dimension order is preserved after dims are dropped.
|
[
"Ensure",
"current",
"dimension",
"order",
"is",
"preserved",
"after",
"dims",
"are",
"dropped",
"."
] |
def reorder_after_dim_reduction(order):
"""Ensure current dimension order is preserved after dims are dropped.
Parameters
----------
order : tuple
The data to reorder.
Returns
-------
arr : tuple
The original array with the unneeded dimension
thrown away.
"""
arr = sorted(range(len(order)), key=lambda x: order[x])
return tuple(arr)
|
[
"def",
"reorder_after_dim_reduction",
"(",
"order",
")",
":",
"arr",
"=",
"sorted",
"(",
"range",
"(",
"len",
"(",
"order",
")",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"order",
"[",
"x",
"]",
")",
"return",
"tuple",
"(",
"arr",
")"
] |
https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/components/dims.py#L406-L421
|
|
ebroecker/canmatrix
|
219a19adf4639b0b4fd5328f039563c6d4060887
|
src/canmatrix/utils.py
|
python
|
escape_aware_split
|
(string, delimiter)
|
[] |
def escape_aware_split(string, delimiter):
if len(delimiter) != 1:
raise ValueError('Invalid delimiter: ' + delimiter)
ln = len(string)
i = 0
j = 0
while j < ln:
if string[j] == '\\':
if j + 1 >= ln:
yield string[i:j]
return
j += 1
elif string[j] == delimiter:
yield string[i:j]
i = j + 1
j += 1
yield string[i:j]
|
[
"def",
"escape_aware_split",
"(",
"string",
",",
"delimiter",
")",
":",
"if",
"len",
"(",
"delimiter",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Invalid delimiter: '",
"+",
"delimiter",
")",
"ln",
"=",
"len",
"(",
"string",
")",
"i",
"=",
"0",
"j",
"=",
"0",
"while",
"j",
"<",
"ln",
":",
"if",
"string",
"[",
"j",
"]",
"==",
"'\\\\'",
":",
"if",
"j",
"+",
"1",
">=",
"ln",
":",
"yield",
"string",
"[",
"i",
":",
"j",
"]",
"return",
"j",
"+=",
"1",
"elif",
"string",
"[",
"j",
"]",
"==",
"delimiter",
":",
"yield",
"string",
"[",
"i",
":",
"j",
"]",
"i",
"=",
"j",
"+",
"1",
"j",
"+=",
"1",
"yield",
"string",
"[",
"i",
":",
"j",
"]"
] |
https://github.com/ebroecker/canmatrix/blob/219a19adf4639b0b4fd5328f039563c6d4060887/src/canmatrix/utils.py#L25-L41
|
||||
aws/sagemaker-python-sdk
|
9d259b316f7f43838c16f35c10e98a110b56735b
|
src/sagemaker/utils.py
|
python
|
sagemaker_short_timestamp
|
()
|
return time.strftime("%y%m%d-%H%M")
|
Return a timestamp that is relatively short in length
|
Return a timestamp that is relatively short in length
|
[
"Return",
"a",
"timestamp",
"that",
"is",
"relatively",
"short",
"in",
"length"
] |
def sagemaker_short_timestamp():
"""Return a timestamp that is relatively short in length"""
return time.strftime("%y%m%d-%H%M")
|
[
"def",
"sagemaker_short_timestamp",
"(",
")",
":",
"return",
"time",
".",
"strftime",
"(",
"\"%y%m%d-%H%M\"",
")"
] |
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/utils.py#L126-L128
|
|
aerosol/django-dilla
|
90a53a6e383e79f805a55fdc7b6c89d2e549ca58
|
dilla/spammers.py
|
python
|
random_datetime
|
(record, field)
|
return datetime.datetime.now() + datetime.timedelta(minutes=random_minutes)
|
Calculate random datetime object between last and next month.
Django interface is pretty tollerant at this point, so three
decorators instead of three handlers here.
|
Calculate random datetime object between last and next month.
Django interface is pretty tollerant at this point, so three
decorators instead of three handlers here.
|
[
"Calculate",
"random",
"datetime",
"object",
"between",
"last",
"and",
"next",
"month",
".",
"Django",
"interface",
"is",
"pretty",
"tollerant",
"at",
"this",
"point",
"so",
"three",
"decorators",
"instead",
"of",
"three",
"handlers",
"here",
"."
] |
def random_datetime(record, field):
"""
Calculate random datetime object between last and next month.
Django interface is pretty tollerant at this point, so three
decorators instead of three handlers here.
"""
# 1 month ~= 30d ~= 720h ~= 43200min
random_minutes = random.randint(-43200, 43200)
return datetime.datetime.now() + datetime.timedelta(minutes=random_minutes)
|
[
"def",
"random_datetime",
"(",
"record",
",",
"field",
")",
":",
"# 1 month ~= 30d ~= 720h ~= 43200min",
"random_minutes",
"=",
"random",
".",
"randint",
"(",
"-",
"43200",
",",
"43200",
")",
"return",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"random_minutes",
")"
] |
https://github.com/aerosol/django-dilla/blob/90a53a6e383e79f805a55fdc7b6c89d2e549ca58/dilla/spammers.py#L111-L120
|
|
cbrgm/telegram-robot-rss
|
58fe98de427121fdc152c8df0721f1891174e6c9
|
venv/lib/python2.7/site-packages/libfuturize/fixes/fix_absolute_import.py
|
python
|
FixAbsoluteImport.probably_a_local_import
|
(self, imp_name)
|
return False
|
Like the corresponding method in the base class, but this also
supports Cython modules.
|
Like the corresponding method in the base class, but this also
supports Cython modules.
|
[
"Like",
"the",
"corresponding",
"method",
"in",
"the",
"base",
"class",
"but",
"this",
"also",
"supports",
"Cython",
"modules",
"."
] |
def probably_a_local_import(self, imp_name):
"""
Like the corresponding method in the base class, but this also
supports Cython modules.
"""
if imp_name.startswith(u"."):
# Relative imports are certainly not local imports.
return False
imp_name = imp_name.split(u".", 1)[0]
base_path = dirname(self.filename)
base_path = join(base_path, imp_name)
# If there is no __init__.py next to the file its not in a package
# so can't be a relative import.
if not exists(join(dirname(base_path), "__init__.py")):
return False
for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd", ".pyx"]:
if exists(base_path + ext):
return True
return False
|
[
"def",
"probably_a_local_import",
"(",
"self",
",",
"imp_name",
")",
":",
"if",
"imp_name",
".",
"startswith",
"(",
"u\".\"",
")",
":",
"# Relative imports are certainly not local imports.",
"return",
"False",
"imp_name",
"=",
"imp_name",
".",
"split",
"(",
"u\".\"",
",",
"1",
")",
"[",
"0",
"]",
"base_path",
"=",
"dirname",
"(",
"self",
".",
"filename",
")",
"base_path",
"=",
"join",
"(",
"base_path",
",",
"imp_name",
")",
"# If there is no __init__.py next to the file its not in a package",
"# so can't be a relative import.",
"if",
"not",
"exists",
"(",
"join",
"(",
"dirname",
"(",
"base_path",
")",
",",
"\"__init__.py\"",
")",
")",
":",
"return",
"False",
"for",
"ext",
"in",
"[",
"\".py\"",
",",
"sep",
",",
"\".pyc\"",
",",
"\".so\"",
",",
"\".sl\"",
",",
"\".pyd\"",
",",
"\".pyx\"",
"]",
":",
"if",
"exists",
"(",
"base_path",
"+",
"ext",
")",
":",
"return",
"True",
"return",
"False"
] |
https://github.com/cbrgm/telegram-robot-rss/blob/58fe98de427121fdc152c8df0721f1891174e6c9/venv/lib/python2.7/site-packages/libfuturize/fixes/fix_absolute_import.py#L73-L91
|
|
jhultman/vision3d
|
8d73f4fe2b9037bc428b7cf7040c563110f2f0a7
|
vision3d/core/geometry.py
|
python
|
PointsInCuboids.__call__
|
(self, boxes)
|
return points
|
Return list of points in each box.
|
Return list of points in each box.
|
[
"Return",
"list",
"of",
"points",
"in",
"each",
"box",
"."
] |
def __call__(self, boxes):
"""Return list of points in each box."""
mask = self._get_mask(boxes).T
points = list(map(self.points.__getitem__, mask))
return points
|
[
"def",
"__call__",
"(",
"self",
",",
"boxes",
")",
":",
"mask",
"=",
"self",
".",
"_get_mask",
"(",
"boxes",
")",
".",
"T",
"points",
"=",
"list",
"(",
"map",
"(",
"self",
".",
"points",
".",
"__getitem__",
",",
"mask",
")",
")",
"return",
"points"
] |
https://github.com/jhultman/vision3d/blob/8d73f4fe2b9037bc428b7cf7040c563110f2f0a7/vision3d/core/geometry.py#L47-L51
|
|
makerbot/ReplicatorG
|
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
|
skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/temperature.py
|
python
|
TemperatureSkein.parseInitialization
|
(self)
|
Parse gcode initialization and store the parameters.
|
Parse gcode initialization and store the parameters.
|
[
"Parse",
"gcode",
"initialization",
"and",
"store",
"the",
"parameters",
"."
] |
def parseInitialization(self):
'Parse gcode initialization and store the parameters.'
for self.lineIndex in xrange(len(self.lines)):
line = self.lines[self.lineIndex]
splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
firstWord = gcodec.getFirstWord(splitLine)
self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
if firstWord == '(</extruderInitialization>)':
self.distanceFeedRate.addLine('(<procedureDone> temperature </procedureDone>)')
return
elif firstWord == '(<perimeterWidth>':
self.distanceFeedRate.addTagBracketedLine('coolingRate', self.repository.coolingRate.value )
self.distanceFeedRate.addTagBracketedLine('heatingRate', self.repository.heatingRate.value )
self.distanceFeedRate.addTagBracketedLine('baseTemperature', self.repository.baseTemperature.value )
self.distanceFeedRate.addTagBracketedLine('interfaceTemperature', self.repository.interfaceTemperature.value )
self.distanceFeedRate.addTagBracketedLine('objectFirstLayerInfillTemperature', self.repository.objectFirstLayerInfillTemperature.value )
self.distanceFeedRate.addTagBracketedLine('objectFirstLayerPerimeterTemperature', self.repository.objectFirstLayerPerimeterTemperature.value )
self.distanceFeedRate.addTagBracketedLine('objectNextLayersTemperature', self.repository.objectNextLayersTemperature.value )
self.distanceFeedRate.addTagBracketedLine('supportLayersTemperature', self.repository.supportLayersTemperature.value )
self.distanceFeedRate.addTagBracketedLine('supportedLayersTemperature', self.repository.supportedLayersTemperature.value )
self.distanceFeedRate.addLine(line)
|
[
"def",
"parseInitialization",
"(",
"self",
")",
":",
"for",
"self",
".",
"lineIndex",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"lines",
")",
")",
":",
"line",
"=",
"self",
".",
"lines",
"[",
"self",
".",
"lineIndex",
"]",
"splitLine",
"=",
"gcodec",
".",
"getSplitLineBeforeBracketSemicolon",
"(",
"line",
")",
"firstWord",
"=",
"gcodec",
".",
"getFirstWord",
"(",
"splitLine",
")",
"self",
".",
"distanceFeedRate",
".",
"parseSplitLine",
"(",
"firstWord",
",",
"splitLine",
")",
"if",
"firstWord",
"==",
"'(</extruderInitialization>)'",
":",
"self",
".",
"distanceFeedRate",
".",
"addLine",
"(",
"'(<procedureDone> temperature </procedureDone>)'",
")",
"return",
"elif",
"firstWord",
"==",
"'(<perimeterWidth>'",
":",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'coolingRate'",
",",
"self",
".",
"repository",
".",
"coolingRate",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'heatingRate'",
",",
"self",
".",
"repository",
".",
"heatingRate",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'baseTemperature'",
",",
"self",
".",
"repository",
".",
"baseTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'interfaceTemperature'",
",",
"self",
".",
"repository",
".",
"interfaceTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'objectFirstLayerInfillTemperature'",
",",
"self",
".",
"repository",
".",
"objectFirstLayerInfillTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'objectFirstLayerPerimeterTemperature'",
",",
"self",
".",
"repository",
".",
"objectFirstLayerPerimeterTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'objectNextLayersTemperature'",
",",
"self",
".",
"repository",
".",
"objectNextLayersTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'supportLayersTemperature'",
",",
"self",
".",
"repository",
".",
"supportLayersTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addTagBracketedLine",
"(",
"'supportedLayersTemperature'",
",",
"self",
".",
"repository",
".",
"supportedLayersTemperature",
".",
"value",
")",
"self",
".",
"distanceFeedRate",
".",
"addLine",
"(",
"line",
")"
] |
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/craft_plugins/temperature.py#L190-L210
|
||
n1nj4sec/pupy
|
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
|
pupy/network/lib/buffer.py
|
python
|
Buffer.drain
|
(self, n=-1)
|
Drain 'n' bytes from the buffer.
If 'n' is negative, drain the whole buffer.
If 'n' is larger than the size of the buffer, drain the whole
buffer.
|
Drain 'n' bytes from the buffer.
|
[
"Drain",
"n",
"bytes",
"from",
"the",
"buffer",
"."
] |
def drain(self, n=-1):
"""
Drain 'n' bytes from the buffer.
If 'n' is negative, drain the whole buffer.
If 'n' is larger than the size of the buffer, drain the whole
buffer.
"""
if n < 0 or n > self._len:
n = self._len
if n == 0:
return
elif n == self._len:
del self._data[:]
self._len = 0
self._bofft = 0
elif n < len(self._data[0]) - self._bofft:
self._bofft += n
self._len -= n
else:
todel = 0
for idx, chunk in enumerate(self._data):
lchunk = len(chunk)
if idx == 0 and self._bofft:
lchunk -= self._bofft
if n >= lchunk:
self._len -= lchunk
self._bofft = 0
todel += 1
n -= lchunk
else:
self._bofft = n
self._len -= n
break
del self._data[:todel]
|
[
"def",
"drain",
"(",
"self",
",",
"n",
"=",
"-",
"1",
")",
":",
"if",
"n",
"<",
"0",
"or",
"n",
">",
"self",
".",
"_len",
":",
"n",
"=",
"self",
".",
"_len",
"if",
"n",
"==",
"0",
":",
"return",
"elif",
"n",
"==",
"self",
".",
"_len",
":",
"del",
"self",
".",
"_data",
"[",
":",
"]",
"self",
".",
"_len",
"=",
"0",
"self",
".",
"_bofft",
"=",
"0",
"elif",
"n",
"<",
"len",
"(",
"self",
".",
"_data",
"[",
"0",
"]",
")",
"-",
"self",
".",
"_bofft",
":",
"self",
".",
"_bofft",
"+=",
"n",
"self",
".",
"_len",
"-=",
"n",
"else",
":",
"todel",
"=",
"0",
"for",
"idx",
",",
"chunk",
"in",
"enumerate",
"(",
"self",
".",
"_data",
")",
":",
"lchunk",
"=",
"len",
"(",
"chunk",
")",
"if",
"idx",
"==",
"0",
"and",
"self",
".",
"_bofft",
":",
"lchunk",
"-=",
"self",
".",
"_bofft",
"if",
"n",
">=",
"lchunk",
":",
"self",
".",
"_len",
"-=",
"lchunk",
"self",
".",
"_bofft",
"=",
"0",
"todel",
"+=",
"1",
"n",
"-=",
"lchunk",
"else",
":",
"self",
".",
"_bofft",
"=",
"n",
"self",
".",
"_len",
"-=",
"n",
"break",
"del",
"self",
".",
"_data",
"[",
":",
"todel",
"]"
] |
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/network/lib/buffer.py#L410-L451
|
||
rembo10/headphones
|
b3199605be1ebc83a7a8feab6b1e99b64014187c
|
lib/configobj.py
|
python
|
Builder.build_Getattr
|
(self, o)
|
return getattr(parent, o.attrname)
|
[] |
def build_Getattr(self, o):
parent = self.build(o.expr)
return getattr(parent, o.attrname)
|
[
"def",
"build_Getattr",
"(",
"self",
",",
"o",
")",
":",
"parent",
"=",
"self",
".",
"build",
"(",
"o",
".",
"expr",
")",
"return",
"getattr",
"(",
"parent",
",",
"o",
".",
"attrname",
")"
] |
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/configobj.py#L200-L202
|
|||
phaethon/kamene
|
bf679a65d456411942ee4a907818ba3d6a183bfe
|
kamene/utils.py
|
python
|
RawPcapWriter._write_packet
|
(self, packet, sec=None, usec=None, caplen=None, wirelen=None)
|
writes a single packet to the pcap file
|
writes a single packet to the pcap file
|
[
"writes",
"a",
"single",
"packet",
"to",
"the",
"pcap",
"file"
] |
def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
"""writes a single packet to the pcap file
"""
if caplen is None:
caplen = len(packet)
if wirelen is None:
wirelen = caplen
if sec is None or usec is None:
t=time.time()
it = int(t)
if sec is None:
sec = it
if usec is None:
usec = int(round((t-it)*1000000))
self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen))
self.f.write(packet)
if self.gz and self.sync:
self.f.flush()
|
[
"def",
"_write_packet",
"(",
"self",
",",
"packet",
",",
"sec",
"=",
"None",
",",
"usec",
"=",
"None",
",",
"caplen",
"=",
"None",
",",
"wirelen",
"=",
"None",
")",
":",
"if",
"caplen",
"is",
"None",
":",
"caplen",
"=",
"len",
"(",
"packet",
")",
"if",
"wirelen",
"is",
"None",
":",
"wirelen",
"=",
"caplen",
"if",
"sec",
"is",
"None",
"or",
"usec",
"is",
"None",
":",
"t",
"=",
"time",
".",
"time",
"(",
")",
"it",
"=",
"int",
"(",
"t",
")",
"if",
"sec",
"is",
"None",
":",
"sec",
"=",
"it",
"if",
"usec",
"is",
"None",
":",
"usec",
"=",
"int",
"(",
"round",
"(",
"(",
"t",
"-",
"it",
")",
"*",
"1000000",
")",
")",
"self",
".",
"f",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"self",
".",
"endian",
"+",
"\"IIII\"",
",",
"sec",
",",
"usec",
",",
"caplen",
",",
"wirelen",
")",
")",
"self",
".",
"f",
".",
"write",
"(",
"packet",
")",
"if",
"self",
".",
"gz",
"and",
"self",
".",
"sync",
":",
"self",
".",
"f",
".",
"flush",
"(",
")"
] |
https://github.com/phaethon/kamene/blob/bf679a65d456411942ee4a907818ba3d6a183bfe/kamene/utils.py#L905-L922
|
||
holoviz/holoviews
|
cc6b27f01710402fdfee2aeef1507425ca78c91f
|
holoviews/core/boundingregion.py
|
python
|
AARectangle.lbrt
|
(self)
|
return self._left, self._bottom, self._right, self._top
|
Return (left,bottom,right,top) as a tuple.
|
Return (left,bottom,right,top) as a tuple.
|
[
"Return",
"(",
"left",
"bottom",
"right",
"top",
")",
"as",
"a",
"tuple",
"."
] |
def lbrt(self):
"""Return (left,bottom,right,top) as a tuple."""
return self._left, self._bottom, self._right, self._top
|
[
"def",
"lbrt",
"(",
"self",
")",
":",
"return",
"self",
".",
"_left",
",",
"self",
".",
"_bottom",
",",
"self",
".",
"_right",
",",
"self",
".",
"_top"
] |
https://github.com/holoviz/holoviews/blob/cc6b27f01710402fdfee2aeef1507425ca78c91f/holoviews/core/boundingregion.py#L298-L300
|
|
itailang/SampleNet
|
442459abc54f9e14f0966a169a094a98febd32eb
|
reconstruction/external/python_plyfile/plyfile.py
|
python
|
PlyData.__iter__
|
(self)
|
return iter(self.elements)
|
[] |
def __iter__(self):
return iter(self.elements)
|
[
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"elements",
")"
] |
https://github.com/itailang/SampleNet/blob/442459abc54f9e14f0966a169a094a98febd32eb/reconstruction/external/python_plyfile/plyfile.py#L333-L334
|
|||
EnterpriseDB/barman
|
487bad92edec72712531ead4746fad72bb310270
|
barman/server.py
|
python
|
Server.check_archiver_errors
|
(self, check_strategy)
|
Checks the presence of archiving errors
:param CheckStrategy check_strategy: the strategy for the management
of the results of the check
|
Checks the presence of archiving errors
|
[
"Checks",
"the",
"presence",
"of",
"archiving",
"errors"
] |
def check_archiver_errors(self, check_strategy):
"""
Checks the presence of archiving errors
:param CheckStrategy check_strategy: the strategy for the management
of the results of the check
"""
check_strategy.init_check("archiver errors")
if os.path.isdir(self.config.errors_directory):
errors = os.listdir(self.config.errors_directory)
else:
errors = []
check_strategy.result(
self.config.name,
len(errors) == 0,
hint=WalArchiver.summarise_error_files(errors),
)
|
[
"def",
"check_archiver_errors",
"(",
"self",
",",
"check_strategy",
")",
":",
"check_strategy",
".",
"init_check",
"(",
"\"archiver errors\"",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"config",
".",
"errors_directory",
")",
":",
"errors",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"config",
".",
"errors_directory",
")",
"else",
":",
"errors",
"=",
"[",
"]",
"check_strategy",
".",
"result",
"(",
"self",
".",
"config",
".",
"name",
",",
"len",
"(",
"errors",
")",
"==",
"0",
",",
"hint",
"=",
"WalArchiver",
".",
"summarise_error_files",
"(",
"errors",
")",
",",
")"
] |
https://github.com/EnterpriseDB/barman/blob/487bad92edec72712531ead4746fad72bb310270/barman/server.py#L1021-L1038
|
||
mcahny/vps
|
138503edbc9e70de744dc0c9fa4b71c799a94d5d
|
tools/dataset/viper.py
|
python
|
Viper._vpq_compute_single_core
|
(proc_id, gt_jsons_set, pred_jsons_set, gt_pans_set, pred_pans_set, gt_image_jsons_set, categories, nframes=2)
|
return vpq_stat
|
[] |
def _vpq_compute_single_core(proc_id, gt_jsons_set, pred_jsons_set, gt_pans_set, pred_pans_set, gt_image_jsons_set, categories, nframes=2):
OFFSET = 256 * 256 * 256
VOID = 0
SIZE_THR = 32**2
vpq_stat = PQStat()
for idx in range(0, len(pred_pans_set)-nframes+1): # nframes:2 ==> i: 0~58
start_idx = time.time()
vid_pan_gt = []
vid_pan_pred = []
gt_segms_list = []
pred_segms_list = []
sub_ann_set = \
zip(gt_jsons_set[idx:idx+nframes],
pred_jsons_set[idx:idx+nframes],
gt_pans_set[idx:idx+nframes],
pred_pans_set[idx:idx+nframes],
gt_image_jsons_set[idx:idx+nframes])
#### Output VPQ value for "nframe" volume.
# Step1. to merge jsons and pan maps in the volume.
for gt_json, pred_json, gt_pan, pred_pan, gt_image_json in sub_ann_set:
gt_pan, pred_pan = np.uint32(gt_pan), np.uint32(pred_pan)
pan_gt = gt_pan[:, :, 0] + gt_pan[:, :, 1] * 256 + gt_pan[:, :, 2] * 256 * 256
pan_pred = pred_pan[:, :, 0] + pred_pan[:, :, 1] * 256 + pred_pan[:, :, 2] * 256 * 256
gt_segms = {el['id']: el for el in gt_json['segments_info']}
pred_segms = {el['id']: el for el in pred_json['segments_info']}
# predicted segments area calculation + prediction sanity checks
pred_labels_set = set(el['id'] for el in pred_json['segments_info'])
labels, labels_cnt = np.unique(pan_pred, return_counts=True)
for label, label_cnt in zip(labels, labels_cnt):
if label not in pred_segms:
if label == VOID:
continue
raise KeyError('In the image with ID {} segment with ID {} is presented in PNG and not presented in JSON.'.format(gt_ann['image_id'], label))
pred_segms[label]['area'] = label_cnt
pred_labels_set.remove(label)
if pred_segms[label]['category_id'] not in categories:
raise KeyError('In the image with ID {} segment with ID {} has unknown category_id {}.'.format(gt_ann['image_id'], label, pred_segms[label]['category_id']))
if len(pred_labels_set) != 0:
raise KeyError(
'In the image with ID {} the following segment IDs {} are presented in JSON and not presented in PNG.'.format(gt_ann['image_id'], list(pred_labels_set)))
#### Collect frame-lavel pan_map, jsons, etc.
vid_pan_gt.append(pan_gt)
vid_pan_pred.append(pan_pred)
gt_segms_list.append(gt_segms)
pred_segms_list.append(pred_segms)
# Step 2. stack the collected elements ==> this is a unit
vid_pan_gt = np.stack(vid_pan_gt) # [nf,1080,1920]
vid_pan_pred = np.stack(vid_pan_pred) # [nf,1080,1920]
vid_gt_segms, vid_pred_segms = {}, {}
for gt_segms, pred_segms in zip(gt_segms_list, pred_segms_list):
# merge 'area' only for gt_segms
for k in gt_segms.keys():
if not k in vid_gt_segms:
vid_gt_segms[k] = gt_segms[k]
else:
vid_gt_segms[k]['area'] += gt_segms[k]['area']
# merge 'area' only for pred_segms
for k in pred_segms.keys():
if not k in vid_pred_segms:
vid_pred_segms[k] = pred_segms[k]
else:
vid_pred_segms[k]['area'] += pred_segms[k]['area']
# Step3. Confusion matrix calculation
vid_pan_gt_pred = vid_pan_gt.astype(np.uint64) * OFFSET + vid_pan_pred.astype(np.uint64)
gt_pred_map = {}
labels, labels_cnt = np.unique(vid_pan_gt_pred, return_counts=True)
for label, intersection in zip(labels, labels_cnt):
gt_id = label // OFFSET
pred_id = label % OFFSET
gt_pred_map[(gt_id, pred_id)] = intersection
# count all matched pairs
gt_small = set()
gt_matched = set()
pred_matched = set()
tp = 0
fp = 0
fn = 0
for label_tuple, intersection in gt_pred_map.items():
gt_label, pred_label = label_tuple
pred_area = (vid_pan_pred == pred_label).sum()
gt_area = (vid_pan_gt == gt_label).sum()
#### SKIP SMALL OBJECTS FIRST
if gt_area < SIZE_THR:
gt_small.add(gt_label)
continue
if gt_label not in vid_gt_segms:
continue
if pred_label not in vid_pred_segms:
continue
if vid_gt_segms[gt_label]['iscrowd'] == 1:
continue
if vid_gt_segms[gt_label]['category_id'] != \
vid_pred_segms[pred_label]['category_id']:
continue
union = pred_area + gt_area - intersection - gt_pred_map.get((VOID, pred_label),0)
iou = intersection / union
# ignore invalid iou value
assert iou <= 1.0, 'INVALID IOU VALUE : %d'%(gt_label)
if iou > 0.5:
vpq_stat[vid_gt_segms[gt_label]['category_id']].tp += 1
vpq_stat[vid_gt_segms[gt_label]['category_id']].iou += iou
gt_matched.add(gt_label)
pred_matched.add(pred_label)
tp += 1
# count false positives
crowd_labels_dict = {}
for gt_label, gt_info in vid_gt_segms.items():
if gt_label in gt_matched:
continue
# crowd segments are ignored
if gt_info['iscrowd'] == 1:
crowd_labels_dict[gt_info['category_id']] = gt_label
continue
if gt_label in gt_small:
continue
vpq_stat[gt_info['category_id']].fn += 1
fn += 1
# count false positives
for pred_label, pred_info in vid_pred_segms.items():
if pred_label in pred_matched:
continue
# intersection of the segment with VOID
intersection = gt_pred_map.get((VOID, pred_label), 0)
# plus intersection with corresponding CROWD region if it exists
if pred_info['category_id'] in crowd_labels_dict:
intersection += gt_pred_map.get((crowd_labels_dict[pred_info['category_id']], pred_label), 0)
# predicted segment is ignored if more than half of the segment correspond to VOID and CROWD regions
if intersection / pred_info['area'] > 0.5:
continue
vpq_stat[pred_info['category_id']].fp += 1
fp += 1
# print('Core %d ==> frame %d, took: %4f sec.'%(proc_id, idx, time.time()-start_idx))
print('Core: {}, all {} images processed'.format(proc_id, len(pred_pans_set)))
return vpq_stat
|
[
"def",
"_vpq_compute_single_core",
"(",
"proc_id",
",",
"gt_jsons_set",
",",
"pred_jsons_set",
",",
"gt_pans_set",
",",
"pred_pans_set",
",",
"gt_image_jsons_set",
",",
"categories",
",",
"nframes",
"=",
"2",
")",
":",
"OFFSET",
"=",
"256",
"*",
"256",
"*",
"256",
"VOID",
"=",
"0",
"SIZE_THR",
"=",
"32",
"**",
"2",
"vpq_stat",
"=",
"PQStat",
"(",
")",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"pred_pans_set",
")",
"-",
"nframes",
"+",
"1",
")",
":",
"# nframes:2 ==> i: 0~58",
"start_idx",
"=",
"time",
".",
"time",
"(",
")",
"vid_pan_gt",
"=",
"[",
"]",
"vid_pan_pred",
"=",
"[",
"]",
"gt_segms_list",
"=",
"[",
"]",
"pred_segms_list",
"=",
"[",
"]",
"sub_ann_set",
"=",
"zip",
"(",
"gt_jsons_set",
"[",
"idx",
":",
"idx",
"+",
"nframes",
"]",
",",
"pred_jsons_set",
"[",
"idx",
":",
"idx",
"+",
"nframes",
"]",
",",
"gt_pans_set",
"[",
"idx",
":",
"idx",
"+",
"nframes",
"]",
",",
"pred_pans_set",
"[",
"idx",
":",
"idx",
"+",
"nframes",
"]",
",",
"gt_image_jsons_set",
"[",
"idx",
":",
"idx",
"+",
"nframes",
"]",
")",
"#### Output VPQ value for \"nframe\" volume.",
"# Step1. to merge jsons and pan maps in the volume.",
"for",
"gt_json",
",",
"pred_json",
",",
"gt_pan",
",",
"pred_pan",
",",
"gt_image_json",
"in",
"sub_ann_set",
":",
"gt_pan",
",",
"pred_pan",
"=",
"np",
".",
"uint32",
"(",
"gt_pan",
")",
",",
"np",
".",
"uint32",
"(",
"pred_pan",
")",
"pan_gt",
"=",
"gt_pan",
"[",
":",
",",
":",
",",
"0",
"]",
"+",
"gt_pan",
"[",
":",
",",
":",
",",
"1",
"]",
"*",
"256",
"+",
"gt_pan",
"[",
":",
",",
":",
",",
"2",
"]",
"*",
"256",
"*",
"256",
"pan_pred",
"=",
"pred_pan",
"[",
":",
",",
":",
",",
"0",
"]",
"+",
"pred_pan",
"[",
":",
",",
":",
",",
"1",
"]",
"*",
"256",
"+",
"pred_pan",
"[",
":",
",",
":",
",",
"2",
"]",
"*",
"256",
"*",
"256",
"gt_segms",
"=",
"{",
"el",
"[",
"'id'",
"]",
":",
"el",
"for",
"el",
"in",
"gt_json",
"[",
"'segments_info'",
"]",
"}",
"pred_segms",
"=",
"{",
"el",
"[",
"'id'",
"]",
":",
"el",
"for",
"el",
"in",
"pred_json",
"[",
"'segments_info'",
"]",
"}",
"# predicted segments area calculation + prediction sanity checks",
"pred_labels_set",
"=",
"set",
"(",
"el",
"[",
"'id'",
"]",
"for",
"el",
"in",
"pred_json",
"[",
"'segments_info'",
"]",
")",
"labels",
",",
"labels_cnt",
"=",
"np",
".",
"unique",
"(",
"pan_pred",
",",
"return_counts",
"=",
"True",
")",
"for",
"label",
",",
"label_cnt",
"in",
"zip",
"(",
"labels",
",",
"labels_cnt",
")",
":",
"if",
"label",
"not",
"in",
"pred_segms",
":",
"if",
"label",
"==",
"VOID",
":",
"continue",
"raise",
"KeyError",
"(",
"'In the image with ID {} segment with ID {} is presented in PNG and not presented in JSON.'",
".",
"format",
"(",
"gt_ann",
"[",
"'image_id'",
"]",
",",
"label",
")",
")",
"pred_segms",
"[",
"label",
"]",
"[",
"'area'",
"]",
"=",
"label_cnt",
"pred_labels_set",
".",
"remove",
"(",
"label",
")",
"if",
"pred_segms",
"[",
"label",
"]",
"[",
"'category_id'",
"]",
"not",
"in",
"categories",
":",
"raise",
"KeyError",
"(",
"'In the image with ID {} segment with ID {} has unknown category_id {}.'",
".",
"format",
"(",
"gt_ann",
"[",
"'image_id'",
"]",
",",
"label",
",",
"pred_segms",
"[",
"label",
"]",
"[",
"'category_id'",
"]",
")",
")",
"if",
"len",
"(",
"pred_labels_set",
")",
"!=",
"0",
":",
"raise",
"KeyError",
"(",
"'In the image with ID {} the following segment IDs {} are presented in JSON and not presented in PNG.'",
".",
"format",
"(",
"gt_ann",
"[",
"'image_id'",
"]",
",",
"list",
"(",
"pred_labels_set",
")",
")",
")",
"#### Collect frame-lavel pan_map, jsons, etc.",
"vid_pan_gt",
".",
"append",
"(",
"pan_gt",
")",
"vid_pan_pred",
".",
"append",
"(",
"pan_pred",
")",
"gt_segms_list",
".",
"append",
"(",
"gt_segms",
")",
"pred_segms_list",
".",
"append",
"(",
"pred_segms",
")",
"# Step 2. stack the collected elements ==> this is a unit",
"vid_pan_gt",
"=",
"np",
".",
"stack",
"(",
"vid_pan_gt",
")",
"# [nf,1080,1920]",
"vid_pan_pred",
"=",
"np",
".",
"stack",
"(",
"vid_pan_pred",
")",
"# [nf,1080,1920]",
"vid_gt_segms",
",",
"vid_pred_segms",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"gt_segms",
",",
"pred_segms",
"in",
"zip",
"(",
"gt_segms_list",
",",
"pred_segms_list",
")",
":",
"# merge 'area' only for gt_segms",
"for",
"k",
"in",
"gt_segms",
".",
"keys",
"(",
")",
":",
"if",
"not",
"k",
"in",
"vid_gt_segms",
":",
"vid_gt_segms",
"[",
"k",
"]",
"=",
"gt_segms",
"[",
"k",
"]",
"else",
":",
"vid_gt_segms",
"[",
"k",
"]",
"[",
"'area'",
"]",
"+=",
"gt_segms",
"[",
"k",
"]",
"[",
"'area'",
"]",
"# merge 'area' only for pred_segms",
"for",
"k",
"in",
"pred_segms",
".",
"keys",
"(",
")",
":",
"if",
"not",
"k",
"in",
"vid_pred_segms",
":",
"vid_pred_segms",
"[",
"k",
"]",
"=",
"pred_segms",
"[",
"k",
"]",
"else",
":",
"vid_pred_segms",
"[",
"k",
"]",
"[",
"'area'",
"]",
"+=",
"pred_segms",
"[",
"k",
"]",
"[",
"'area'",
"]",
"# Step3. Confusion matrix calculation",
"vid_pan_gt_pred",
"=",
"vid_pan_gt",
".",
"astype",
"(",
"np",
".",
"uint64",
")",
"*",
"OFFSET",
"+",
"vid_pan_pred",
".",
"astype",
"(",
"np",
".",
"uint64",
")",
"gt_pred_map",
"=",
"{",
"}",
"labels",
",",
"labels_cnt",
"=",
"np",
".",
"unique",
"(",
"vid_pan_gt_pred",
",",
"return_counts",
"=",
"True",
")",
"for",
"label",
",",
"intersection",
"in",
"zip",
"(",
"labels",
",",
"labels_cnt",
")",
":",
"gt_id",
"=",
"label",
"//",
"OFFSET",
"pred_id",
"=",
"label",
"%",
"OFFSET",
"gt_pred_map",
"[",
"(",
"gt_id",
",",
"pred_id",
")",
"]",
"=",
"intersection",
"# count all matched pairs",
"gt_small",
"=",
"set",
"(",
")",
"gt_matched",
"=",
"set",
"(",
")",
"pred_matched",
"=",
"set",
"(",
")",
"tp",
"=",
"0",
"fp",
"=",
"0",
"fn",
"=",
"0",
"for",
"label_tuple",
",",
"intersection",
"in",
"gt_pred_map",
".",
"items",
"(",
")",
":",
"gt_label",
",",
"pred_label",
"=",
"label_tuple",
"pred_area",
"=",
"(",
"vid_pan_pred",
"==",
"pred_label",
")",
".",
"sum",
"(",
")",
"gt_area",
"=",
"(",
"vid_pan_gt",
"==",
"gt_label",
")",
".",
"sum",
"(",
")",
"#### SKIP SMALL OBJECTS FIRST",
"if",
"gt_area",
"<",
"SIZE_THR",
":",
"gt_small",
".",
"add",
"(",
"gt_label",
")",
"continue",
"if",
"gt_label",
"not",
"in",
"vid_gt_segms",
":",
"continue",
"if",
"pred_label",
"not",
"in",
"vid_pred_segms",
":",
"continue",
"if",
"vid_gt_segms",
"[",
"gt_label",
"]",
"[",
"'iscrowd'",
"]",
"==",
"1",
":",
"continue",
"if",
"vid_gt_segms",
"[",
"gt_label",
"]",
"[",
"'category_id'",
"]",
"!=",
"vid_pred_segms",
"[",
"pred_label",
"]",
"[",
"'category_id'",
"]",
":",
"continue",
"union",
"=",
"pred_area",
"+",
"gt_area",
"-",
"intersection",
"-",
"gt_pred_map",
".",
"get",
"(",
"(",
"VOID",
",",
"pred_label",
")",
",",
"0",
")",
"iou",
"=",
"intersection",
"/",
"union",
"# ignore invalid iou value",
"assert",
"iou",
"<=",
"1.0",
",",
"'INVALID IOU VALUE : %d'",
"%",
"(",
"gt_label",
")",
"if",
"iou",
">",
"0.5",
":",
"vpq_stat",
"[",
"vid_gt_segms",
"[",
"gt_label",
"]",
"[",
"'category_id'",
"]",
"]",
".",
"tp",
"+=",
"1",
"vpq_stat",
"[",
"vid_gt_segms",
"[",
"gt_label",
"]",
"[",
"'category_id'",
"]",
"]",
".",
"iou",
"+=",
"iou",
"gt_matched",
".",
"add",
"(",
"gt_label",
")",
"pred_matched",
".",
"add",
"(",
"pred_label",
")",
"tp",
"+=",
"1",
"# count false positives",
"crowd_labels_dict",
"=",
"{",
"}",
"for",
"gt_label",
",",
"gt_info",
"in",
"vid_gt_segms",
".",
"items",
"(",
")",
":",
"if",
"gt_label",
"in",
"gt_matched",
":",
"continue",
"# crowd segments are ignored",
"if",
"gt_info",
"[",
"'iscrowd'",
"]",
"==",
"1",
":",
"crowd_labels_dict",
"[",
"gt_info",
"[",
"'category_id'",
"]",
"]",
"=",
"gt_label",
"continue",
"if",
"gt_label",
"in",
"gt_small",
":",
"continue",
"vpq_stat",
"[",
"gt_info",
"[",
"'category_id'",
"]",
"]",
".",
"fn",
"+=",
"1",
"fn",
"+=",
"1",
"# count false positives",
"for",
"pred_label",
",",
"pred_info",
"in",
"vid_pred_segms",
".",
"items",
"(",
")",
":",
"if",
"pred_label",
"in",
"pred_matched",
":",
"continue",
"# intersection of the segment with VOID",
"intersection",
"=",
"gt_pred_map",
".",
"get",
"(",
"(",
"VOID",
",",
"pred_label",
")",
",",
"0",
")",
"# plus intersection with corresponding CROWD region if it exists",
"if",
"pred_info",
"[",
"'category_id'",
"]",
"in",
"crowd_labels_dict",
":",
"intersection",
"+=",
"gt_pred_map",
".",
"get",
"(",
"(",
"crowd_labels_dict",
"[",
"pred_info",
"[",
"'category_id'",
"]",
"]",
",",
"pred_label",
")",
",",
"0",
")",
"# predicted segment is ignored if more than half of the segment correspond to VOID and CROWD regions",
"if",
"intersection",
"/",
"pred_info",
"[",
"'area'",
"]",
">",
"0.5",
":",
"continue",
"vpq_stat",
"[",
"pred_info",
"[",
"'category_id'",
"]",
"]",
".",
"fp",
"+=",
"1",
"fp",
"+=",
"1",
"# print('Core %d ==> frame %d, took: %4f sec.'%(proc_id, idx, time.time()-start_idx))",
"print",
"(",
"'Core: {}, all {} images processed'",
".",
"format",
"(",
"proc_id",
",",
"len",
"(",
"pred_pans_set",
")",
")",
")",
"return",
"vpq_stat"
] |
https://github.com/mcahny/vps/blob/138503edbc9e70de744dc0c9fa4b71c799a94d5d/tools/dataset/viper.py#L363-L503
|
|||
paypal/support
|
0c88c3d32644c897c30e12de8c8db00d065a76ea
|
support/connection_mgr.py
|
python
|
ConnectionManager.get_all_addrs
|
(self, name)
|
return address_list
|
Returns the all addresses which the logical name would resolve to,
or raises NameNotFound if there is no known address for the given name.
|
Returns the all addresses which the logical name would resolve to,
or raises NameNotFound if there is no known address for the given name.
|
[
"Returns",
"the",
"all",
"addresses",
"which",
"the",
"logical",
"name",
"would",
"resolve",
"to",
"or",
"raises",
"NameNotFound",
"if",
"there",
"is",
"no",
"known",
"address",
"for",
"the",
"given",
"name",
"."
] |
def get_all_addrs(self, name):
'''
Returns the all addresses which the logical name would resolve to,
or raises NameNotFound if there is no known address for the given name.
'''
ctx = context.get_context()
address_groups = self.address_groups or ctx.address_groups
try:
address_list = list(address_groups[name])
except KeyError:
err_str = "no address found for name {0}".format(name)
if ctx.stage_ip is None:
err_str += " (no stage communication configured; did you forget?)"
raise NameNotFound(err_str)
return address_list
|
[
"def",
"get_all_addrs",
"(",
"self",
",",
"name",
")",
":",
"ctx",
"=",
"context",
".",
"get_context",
"(",
")",
"address_groups",
"=",
"self",
".",
"address_groups",
"or",
"ctx",
".",
"address_groups",
"try",
":",
"address_list",
"=",
"list",
"(",
"address_groups",
"[",
"name",
"]",
")",
"except",
"KeyError",
":",
"err_str",
"=",
"\"no address found for name {0}\"",
".",
"format",
"(",
"name",
")",
"if",
"ctx",
".",
"stage_ip",
"is",
"None",
":",
"err_str",
"+=",
"\" (no stage communication configured; did you forget?)\"",
"raise",
"NameNotFound",
"(",
"err_str",
")",
"return",
"address_list"
] |
https://github.com/paypal/support/blob/0c88c3d32644c897c30e12de8c8db00d065a76ea/support/connection_mgr.py#L157-L171
|
|
openshift/openshift-tools
|
1188778e728a6e4781acf728123e5b356380fe6f
|
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/lib/route.py
|
python
|
Route.get_weight
|
(self)
|
return self.get(Route.weight_path)
|
return service weight
|
return service weight
|
[
"return",
"service",
"weight"
] |
def get_weight(self):
''' return service weight '''
return self.get(Route.weight_path)
|
[
"def",
"get_weight",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"Route",
".",
"weight_path",
")"
] |
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/lib/route.py#L123-L125
|
|
termius/termius-cli
|
2664d0c70d3d682ad931b885b4965447b156c280
|
termius/core/models/terminal.py
|
python
|
SshKey.file_path
|
(self, command)
|
return ssh_keys_path / self.label
|
Return path object to private key file.
|
Return path object to private key file.
|
[
"Return",
"path",
"object",
"to",
"private",
"key",
"file",
"."
] |
def file_path(self, command):
"""Return path object to private key file."""
ssh_keys_path = command.config.ssh_key_dir_path
return ssh_keys_path / self.label
|
[
"def",
"file_path",
"(",
"self",
",",
"command",
")",
":",
"ssh_keys_path",
"=",
"command",
".",
"config",
".",
"ssh_key_dir_path",
"return",
"ssh_keys_path",
"/",
"self",
".",
"label"
] |
https://github.com/termius/termius-cli/blob/2664d0c70d3d682ad931b885b4965447b156c280/termius/core/models/terminal.py#L41-L44
|
|
Toufool/Auto-Split
|
4edbef54f82fd250cec81118d6eff893c33907c5
|
src/compare.py
|
python
|
compare_l2_norm_masked
|
(source, capture, mask)
|
return 1 - (error / max_error)
|
Compares two images by calculating the L2 Error (square-root
of sum of squared error)
@param source: Image of any given shape
@param capture: Image matching the dimensions of the source
@param mask: An image matching the dimensions of the source, but 1 channel grayscale
@return: The similarity between the images as a number 0 to 1.
|
Compares two images by calculating the L2 Error (square-root
of sum of squared error)
|
[
"Compares",
"two",
"images",
"by",
"calculating",
"the",
"L2",
"Error",
"(",
"square",
"-",
"root",
"of",
"sum",
"of",
"squared",
"error",
")"
] |
def compare_l2_norm_masked(source, capture, mask) -> float:
"""
Compares two images by calculating the L2 Error (square-root
of sum of squared error)
@param source: Image of any given shape
@param capture: Image matching the dimensions of the source
@param mask: An image matching the dimensions of the source, but 1 channel grayscale
@return: The similarity between the images as a number 0 to 1.
"""
error = cv2.norm(source, capture, cv2.NORM_L2, mask)
# The L2 Error is summed across all pixels, so this normalizes
max_error = (3 * np.count_nonzero(mask) * 255 * 255) ** 0.5
return 1 - (error / max_error)
|
[
"def",
"compare_l2_norm_masked",
"(",
"source",
",",
"capture",
",",
"mask",
")",
"->",
"float",
":",
"error",
"=",
"cv2",
".",
"norm",
"(",
"source",
",",
"capture",
",",
"cv2",
".",
"NORM_L2",
",",
"mask",
")",
"# The L2 Error is summed across all pixels, so this normalizes",
"max_error",
"=",
"(",
"3",
"*",
"np",
".",
"count_nonzero",
"(",
"mask",
")",
"*",
"255",
"*",
"255",
")",
"**",
"0.5",
"return",
"1",
"-",
"(",
"error",
"/",
"max_error",
")"
] |
https://github.com/Toufool/Auto-Split/blob/4edbef54f82fd250cec81118d6eff893c33907c5/src/compare.py#L59-L75
|
|
owtf/owtf
|
22d6d35fb2a232fcc56bf5ed504ec52fd65f15b6
|
owtf/managers/target.py
|
python
|
TargetManager.get_target_url
|
(self)
|
return self.get_val("target_url")
|
Return target URL
:return: Target URL
:rtype: `str`
|
Return target URL
:return: Target URL
:rtype: `str`
|
[
"Return",
"target",
"URL",
":",
"return",
":",
"Target",
"URL",
":",
"rtype",
":",
"str"
] |
def get_target_url(self):
"""Return target URL
:return: Target URL
:rtype: `str`
"""
return self.get_val("target_url")
|
[
"def",
"get_target_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_val",
"(",
"\"target_url\"",
")"
] |
https://github.com/owtf/owtf/blob/22d6d35fb2a232fcc56bf5ed504ec52fd65f15b6/owtf/managers/target.py#L179-L184
|
|
usnistgov/fipy
|
6809b180b41a11de988a48655575df7e142c93b9
|
fipy/meshes/topologies/meshTopology.py
|
python
|
_Mesh2DTopology._cellTopology
|
(self)
|
return cellTopology
|
return a map of the topology of each cell
|
return a map of the topology of each cell
|
[
"return",
"a",
"map",
"of",
"the",
"topology",
"of",
"each",
"cell"
] |
def _cellTopology(self):
"""return a map of the topology of each cell"""
cellTopology = numerix.empty((self.mesh.numberOfCells,), dtype=numerix.ubyte)
t = self._elementTopology
cellTopology[:] = t["polygon"]
facesPerCell = self.mesh._facesPerCell
cellTopology[facesPerCell == 3] = t["triangle"]
cellTopology[facesPerCell == 4] = t["quadrangle"]
return cellTopology
|
[
"def",
"_cellTopology",
"(",
"self",
")",
":",
"cellTopology",
"=",
"numerix",
".",
"empty",
"(",
"(",
"self",
".",
"mesh",
".",
"numberOfCells",
",",
")",
",",
"dtype",
"=",
"numerix",
".",
"ubyte",
")",
"t",
"=",
"self",
".",
"_elementTopology",
"cellTopology",
"[",
":",
"]",
"=",
"t",
"[",
"\"polygon\"",
"]",
"facesPerCell",
"=",
"self",
".",
"mesh",
".",
"_facesPerCell",
"cellTopology",
"[",
"facesPerCell",
"==",
"3",
"]",
"=",
"t",
"[",
"\"triangle\"",
"]",
"cellTopology",
"[",
"facesPerCell",
"==",
"4",
"]",
"=",
"t",
"[",
"\"quadrangle\"",
"]",
"return",
"cellTopology"
] |
https://github.com/usnistgov/fipy/blob/6809b180b41a11de988a48655575df7e142c93b9/fipy/meshes/topologies/meshTopology.py#L91-L102
|
|
Source-Python-Dev-Team/Source.Python
|
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
|
addons/source-python/Python3/imghdr.py
|
python
|
test_ppm
|
(h, f)
|
PPM (portable pixmap)
|
PPM (portable pixmap)
|
[
"PPM",
"(",
"portable",
"pixmap",
")"
] |
def test_ppm(h, f):
"""PPM (portable pixmap)"""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r':
return 'ppm'
|
[
"def",
"test_ppm",
"(",
"h",
",",
"f",
")",
":",
"if",
"len",
"(",
"h",
")",
">=",
"3",
"and",
"h",
"[",
"0",
"]",
"==",
"ord",
"(",
"b'P'",
")",
"and",
"h",
"[",
"1",
"]",
"in",
"b'36'",
"and",
"h",
"[",
"2",
"]",
"in",
"b' \\t\\n\\r'",
":",
"return",
"'ppm'"
] |
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/imghdr.py#L87-L91
|
||
plasticityai/magnitude
|
7ac0baeaf181263b661c3ae00643d21e3fd90216
|
pymagnitude/third_party/_pysqlite/__init__.py
|
python
|
Magnitude.most_similar
|
(self, positive, negative=[], topn=10, min_similarity=None,
return_similarities=True)
|
return self._db_query_similarity(
positive=positive,
negative=negative,
min_similarity=min_similarity,
topn=topn,
exclude_keys=self._exclude_set(
positive,
negative),
return_similarities=return_similarities,
method='distance')
|
Finds the topn most similar vectors under or equal
to max distance.
|
Finds the topn most similar vectors under or equal
to max distance.
|
[
"Finds",
"the",
"topn",
"most",
"similar",
"vectors",
"under",
"or",
"equal",
"to",
"max",
"distance",
"."
] |
def most_similar(self, positive, negative=[], topn=10, min_similarity=None,
return_similarities=True):
"""Finds the topn most similar vectors under or equal
to max distance.
"""
positive, negative = self._handle_pos_neg_args(positive, negative)
return self._db_query_similarity(
positive=positive,
negative=negative,
min_similarity=min_similarity,
topn=topn,
exclude_keys=self._exclude_set(
positive,
negative),
return_similarities=return_similarities,
method='distance')
|
[
"def",
"most_similar",
"(",
"self",
",",
"positive",
",",
"negative",
"=",
"[",
"]",
",",
"topn",
"=",
"10",
",",
"min_similarity",
"=",
"None",
",",
"return_similarities",
"=",
"True",
")",
":",
"positive",
",",
"negative",
"=",
"self",
".",
"_handle_pos_neg_args",
"(",
"positive",
",",
"negative",
")",
"return",
"self",
".",
"_db_query_similarity",
"(",
"positive",
"=",
"positive",
",",
"negative",
"=",
"negative",
",",
"min_similarity",
"=",
"min_similarity",
",",
"topn",
"=",
"topn",
",",
"exclude_keys",
"=",
"self",
".",
"_exclude_set",
"(",
"positive",
",",
"negative",
")",
",",
"return_similarities",
"=",
"return_similarities",
",",
"method",
"=",
"'distance'",
")"
] |
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/_pysqlite/__init__.py#L1142-L1158
|
|
django-nonrel/django-nonrel
|
4fbfe7344481a5eab8698f79207f09124310131b
|
django/utils/html.py
|
python
|
urlize
|
(text, trim_url_limit=None, nofollow=False, autoescape=False)
|
return u''.join(words)
|
Converts any URLs in text into clickable links.
Works on http://, https://, www. links and links ending in .org, .net or
.com. Links can have trailing punctuation (periods, commas, close-parens)
and leading punctuation (opening parens) and it'll still do the right
thing.
If trim_url_limit is not None, the URLs in link text longer than this limit
will truncated to trim_url_limit-3 characters and appended with an elipsis.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If autoescape is True, the link text and URLs will get autoescaped.
|
Converts any URLs in text into clickable links.
|
[
"Converts",
"any",
"URLs",
"in",
"text",
"into",
"clickable",
"links",
"."
] |
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
"""
Converts any URLs in text into clickable links.
Works on http://, https://, www. links and links ending in .org, .net or
.com. Links can have trailing punctuation (periods, commas, close-parens)
and leading punctuation (opening parens) and it'll still do the right
thing.
If trim_url_limit is not None, the URLs in link text longer than this limit
will truncated to trim_url_limit-3 characters and appended with an elipsis.
If nofollow is True, the URLs in link text will get a rel="nofollow"
attribute.
If autoescape is True, the link text and URLs will get autoescaped.
"""
trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_unicode(text))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
for i, word in enumerate(words):
match = None
if '.' in word or '@' in word or ':' in word:
match = punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
# Make URL we want to point to.
url = None
if middle.startswith('http://') or middle.startswith('https://'):
url = urlquote(middle, safe='/&=:;#?+*')
elif middle.startswith('www.') or ('@' not in middle and \
middle and middle[0] in string.ascii_letters + string.digits and \
(middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
url = 'mailto:%s' % middle
nofollow_attr = ''
# Make link.
if url:
trimmed = trim_url(middle)
if autoescape and not safe_input:
lead, trail = escape(lead), escape(trail)
url, trimmed = escape(url), escape(trimmed)
middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
else:
if safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
elif safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
return u''.join(words)
|
[
"def",
"urlize",
"(",
"text",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"autoescape",
"=",
"False",
")",
":",
"trim_url",
"=",
"lambda",
"x",
",",
"limit",
"=",
"trim_url_limit",
":",
"limit",
"is",
"not",
"None",
"and",
"(",
"len",
"(",
"x",
")",
">",
"limit",
"and",
"(",
"'%s...'",
"%",
"x",
"[",
":",
"max",
"(",
"0",
",",
"limit",
"-",
"3",
")",
"]",
")",
")",
"or",
"x",
"safe_input",
"=",
"isinstance",
"(",
"text",
",",
"SafeData",
")",
"words",
"=",
"word_split_re",
".",
"split",
"(",
"force_unicode",
"(",
"text",
")",
")",
"nofollow_attr",
"=",
"nofollow",
"and",
"' rel=\"nofollow\"'",
"or",
"''",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"words",
")",
":",
"match",
"=",
"None",
"if",
"'.'",
"in",
"word",
"or",
"'@'",
"in",
"word",
"or",
"':'",
"in",
"word",
":",
"match",
"=",
"punctuation_re",
".",
"match",
"(",
"word",
")",
"if",
"match",
":",
"lead",
",",
"middle",
",",
"trail",
"=",
"match",
".",
"groups",
"(",
")",
"# Make URL we want to point to.",
"url",
"=",
"None",
"if",
"middle",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"middle",
".",
"startswith",
"(",
"'https://'",
")",
":",
"url",
"=",
"urlquote",
"(",
"middle",
",",
"safe",
"=",
"'/&=:;#?+*'",
")",
"elif",
"middle",
".",
"startswith",
"(",
"'www.'",
")",
"or",
"(",
"'@'",
"not",
"in",
"middle",
"and",
"middle",
"and",
"middle",
"[",
"0",
"]",
"in",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
"and",
"(",
"middle",
".",
"endswith",
"(",
"'.org'",
")",
"or",
"middle",
".",
"endswith",
"(",
"'.net'",
")",
"or",
"middle",
".",
"endswith",
"(",
"'.com'",
")",
")",
")",
":",
"url",
"=",
"urlquote",
"(",
"'http://%s'",
"%",
"middle",
",",
"safe",
"=",
"'/&=:;#?+*'",
")",
"elif",
"'@'",
"in",
"middle",
"and",
"not",
"':'",
"in",
"middle",
"and",
"simple_email_re",
".",
"match",
"(",
"middle",
")",
":",
"url",
"=",
"'mailto:%s'",
"%",
"middle",
"nofollow_attr",
"=",
"''",
"# Make link.",
"if",
"url",
":",
"trimmed",
"=",
"trim_url",
"(",
"middle",
")",
"if",
"autoescape",
"and",
"not",
"safe_input",
":",
"lead",
",",
"trail",
"=",
"escape",
"(",
"lead",
")",
",",
"escape",
"(",
"trail",
")",
"url",
",",
"trimmed",
"=",
"escape",
"(",
"url",
")",
",",
"escape",
"(",
"trimmed",
")",
"middle",
"=",
"'<a href=\"%s\"%s>%s</a>'",
"%",
"(",
"url",
",",
"nofollow_attr",
",",
"trimmed",
")",
"words",
"[",
"i",
"]",
"=",
"mark_safe",
"(",
"'%s%s%s'",
"%",
"(",
"lead",
",",
"middle",
",",
"trail",
")",
")",
"else",
":",
"if",
"safe_input",
":",
"words",
"[",
"i",
"]",
"=",
"mark_safe",
"(",
"word",
")",
"elif",
"autoescape",
":",
"words",
"[",
"i",
"]",
"=",
"escape",
"(",
"word",
")",
"elif",
"safe_input",
":",
"words",
"[",
"i",
"]",
"=",
"mark_safe",
"(",
"word",
")",
"elif",
"autoescape",
":",
"words",
"[",
"i",
"]",
"=",
"escape",
"(",
"word",
")",
"return",
"u''",
".",
"join",
"(",
"words",
")"
] |
https://github.com/django-nonrel/django-nonrel/blob/4fbfe7344481a5eab8698f79207f09124310131b/django/utils/html.py#L102-L157
|
|
uber-research/PPLM
|
e236b8989322128360182d29a79944627957ad47
|
paper_code/pytorch_pretrained_bert/modeling_transfo_xl.py
|
python
|
TransfoXLPreTrainedModel.init_weights
|
(self, m)
|
Initialize the weights.
|
Initialize the weights.
|
[
"Initialize",
"the",
"weights",
"."
] |
def init_weights(self, m):
""" Initialize the weights.
"""
classname = m.__class__.__name__
if classname.find('Linear') != -1:
if hasattr(m, 'weight') and m.weight is not None:
self.init_weight(m.weight)
if hasattr(m, 'bias') and m.bias is not None:
self.init_bias(m.bias)
elif classname.find('AdaptiveEmbedding') != -1:
if hasattr(m, 'emb_projs'):
for i in range(len(m.emb_projs)):
if m.emb_projs[i] is not None:
nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
elif classname.find('Embedding') != -1:
if hasattr(m, 'weight'):
self.init_weight(m.weight)
elif classname.find('ProjectedAdaptiveLogSoftmax') != -1:
if hasattr(m, 'cluster_weight') and m.cluster_weight is not None:
self.init_weight(m.cluster_weight)
if hasattr(m, 'cluster_bias') and m.cluster_bias is not None:
self.init_bias(m.cluster_bias)
if hasattr(m, 'out_projs'):
for i in range(len(m.out_projs)):
if m.out_projs[i] is not None:
nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
elif classname.find('LayerNorm') != -1:
if hasattr(m, 'weight'):
nn.init.normal_(m.weight, 1.0, self.config.init_std)
if hasattr(m, 'bias') and m.bias is not None:
self.init_bias(m.bias)
elif classname.find('TransformerLM') != -1:
if hasattr(m, 'r_emb'):
self.init_weight(m.r_emb)
if hasattr(m, 'r_w_bias'):
self.init_weight(m.r_w_bias)
if hasattr(m, 'r_r_bias'):
self.init_weight(m.r_r_bias)
if hasattr(m, 'r_bias'):
self.init_bias(m.r_bias)
|
[
"def",
"init_weights",
"(",
"self",
",",
"m",
")",
":",
"classname",
"=",
"m",
".",
"__class__",
".",
"__name__",
"if",
"classname",
".",
"find",
"(",
"'Linear'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'weight'",
")",
"and",
"m",
".",
"weight",
"is",
"not",
"None",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"weight",
")",
"if",
"hasattr",
"(",
"m",
",",
"'bias'",
")",
"and",
"m",
".",
"bias",
"is",
"not",
"None",
":",
"self",
".",
"init_bias",
"(",
"m",
".",
"bias",
")",
"elif",
"classname",
".",
"find",
"(",
"'AdaptiveEmbedding'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'emb_projs'",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"m",
".",
"emb_projs",
")",
")",
":",
"if",
"m",
".",
"emb_projs",
"[",
"i",
"]",
"is",
"not",
"None",
":",
"nn",
".",
"init",
".",
"normal_",
"(",
"m",
".",
"emb_projs",
"[",
"i",
"]",
",",
"0.0",
",",
"self",
".",
"config",
".",
"proj_init_std",
")",
"elif",
"classname",
".",
"find",
"(",
"'Embedding'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'weight'",
")",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"weight",
")",
"elif",
"classname",
".",
"find",
"(",
"'ProjectedAdaptiveLogSoftmax'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'cluster_weight'",
")",
"and",
"m",
".",
"cluster_weight",
"is",
"not",
"None",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"cluster_weight",
")",
"if",
"hasattr",
"(",
"m",
",",
"'cluster_bias'",
")",
"and",
"m",
".",
"cluster_bias",
"is",
"not",
"None",
":",
"self",
".",
"init_bias",
"(",
"m",
".",
"cluster_bias",
")",
"if",
"hasattr",
"(",
"m",
",",
"'out_projs'",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"m",
".",
"out_projs",
")",
")",
":",
"if",
"m",
".",
"out_projs",
"[",
"i",
"]",
"is",
"not",
"None",
":",
"nn",
".",
"init",
".",
"normal_",
"(",
"m",
".",
"out_projs",
"[",
"i",
"]",
",",
"0.0",
",",
"self",
".",
"config",
".",
"proj_init_std",
")",
"elif",
"classname",
".",
"find",
"(",
"'LayerNorm'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'weight'",
")",
":",
"nn",
".",
"init",
".",
"normal_",
"(",
"m",
".",
"weight",
",",
"1.0",
",",
"self",
".",
"config",
".",
"init_std",
")",
"if",
"hasattr",
"(",
"m",
",",
"'bias'",
")",
"and",
"m",
".",
"bias",
"is",
"not",
"None",
":",
"self",
".",
"init_bias",
"(",
"m",
".",
"bias",
")",
"elif",
"classname",
".",
"find",
"(",
"'TransformerLM'",
")",
"!=",
"-",
"1",
":",
"if",
"hasattr",
"(",
"m",
",",
"'r_emb'",
")",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"r_emb",
")",
"if",
"hasattr",
"(",
"m",
",",
"'r_w_bias'",
")",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"r_w_bias",
")",
"if",
"hasattr",
"(",
"m",
",",
"'r_r_bias'",
")",
":",
"self",
".",
"init_weight",
"(",
"m",
".",
"r_r_bias",
")",
"if",
"hasattr",
"(",
"m",
",",
"'r_bias'",
")",
":",
"self",
".",
"init_bias",
"(",
"m",
".",
"r_bias",
")"
] |
https://github.com/uber-research/PPLM/blob/e236b8989322128360182d29a79944627957ad47/paper_code/pytorch_pretrained_bert/modeling_transfo_xl.py#L854-L893
|
||
out0fmemory/GoAgent-Always-Available
|
c4254984fea633ce3d1893fe5901debd9f22c2a9
|
server/lib/google/appengine/tools/backends_xml_parser.py
|
python
|
BackendsXmlParser.ProcessXml
|
(self, xml_str)
|
Parses XML string and returns object representation of relevant info.
Args:
xml_str: The XML string.
Returns:
A list of Backend object containg information about backends from the XML.
Raises:
AppEngineConfigException: In case of malformed XML or illegal inputs.
|
Parses XML string and returns object representation of relevant info.
|
[
"Parses",
"XML",
"string",
"and",
"returns",
"object",
"representation",
"of",
"relevant",
"info",
"."
] |
def ProcessXml(self, xml_str):
"""Parses XML string and returns object representation of relevant info.
Args:
xml_str: The XML string.
Returns:
A list of Backend object containg information about backends from the XML.
Raises:
AppEngineConfigException: In case of malformed XML or illegal inputs.
"""
try:
self.backends = []
self.errors = []
xml_root = ElementTree.fromstring(xml_str)
for child in xml_root.getchildren():
self.ProcessBackendNode(child)
if self.errors:
raise AppEngineConfigException('\n'.join(self.errors))
return self.backends
except ElementTree.ParseError:
raise AppEngineConfigException('Bad input -- not valid XML')
|
[
"def",
"ProcessXml",
"(",
"self",
",",
"xml_str",
")",
":",
"try",
":",
"self",
".",
"backends",
"=",
"[",
"]",
"self",
".",
"errors",
"=",
"[",
"]",
"xml_root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"xml_str",
")",
"for",
"child",
"in",
"xml_root",
".",
"getchildren",
"(",
")",
":",
"self",
".",
"ProcessBackendNode",
"(",
"child",
")",
"if",
"self",
".",
"errors",
":",
"raise",
"AppEngineConfigException",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"errors",
")",
")",
"return",
"self",
".",
"backends",
"except",
"ElementTree",
".",
"ParseError",
":",
"raise",
"AppEngineConfigException",
"(",
"'Bad input -- not valid XML'",
")"
] |
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/tools/backends_xml_parser.py#L46-L69
|
||
Project-Platypus/Platypus
|
a4e56410a772798e905407e99f80d03b86296ad3
|
platypus/core.py
|
python
|
Mutation.evolve
|
(self, parents)
|
[] |
def evolve(self, parents):
if hasattr(parents, "__iter__"):
return list(map(self.mutate, parents))
else:
return self.mutate(parents)
|
[
"def",
"evolve",
"(",
"self",
",",
"parents",
")",
":",
"if",
"hasattr",
"(",
"parents",
",",
"\"__iter__\"",
")",
":",
"return",
"list",
"(",
"map",
"(",
"self",
".",
"mutate",
",",
"parents",
")",
")",
"else",
":",
"return",
"self",
".",
"mutate",
"(",
"parents",
")"
] |
https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/platypus/core.py#L242-L246
|
||||
wandb/client
|
3963364d8112b7dedb928fa423b6878ea1b467d9
|
wandb/sdk/integration_utils/data_logging.py
|
python
|
ValidationDataLogger.make_predictions
|
(
self, predict_fn: Callable
)
|
return predict_fn(self.validation_inputs)
|
Produces predictions by passing `validation_inputs` to `predict_fn`.
Args:
predict_fn (Callable): Any function which can accept `validation_inputs` and produce
a list of vectors or dictionary of lists of vectors
Returns:
(Sequence | Dict[str, Sequence]): The returned value of predict_fn
|
Produces predictions by passing `validation_inputs` to `predict_fn`.
|
[
"Produces",
"predictions",
"by",
"passing",
"validation_inputs",
"to",
"predict_fn",
"."
] |
def make_predictions(
self, predict_fn: Callable
) -> Union[Sequence, Dict[str, Sequence]]:
"""Produces predictions by passing `validation_inputs` to `predict_fn`.
Args:
predict_fn (Callable): Any function which can accept `validation_inputs` and produce
a list of vectors or dictionary of lists of vectors
Returns:
(Sequence | Dict[str, Sequence]): The returned value of predict_fn
"""
return predict_fn(self.validation_inputs)
|
[
"def",
"make_predictions",
"(",
"self",
",",
"predict_fn",
":",
"Callable",
")",
"->",
"Union",
"[",
"Sequence",
",",
"Dict",
"[",
"str",
",",
"Sequence",
"]",
"]",
":",
"return",
"predict_fn",
"(",
"self",
".",
"validation_inputs",
")"
] |
https://github.com/wandb/client/blob/3963364d8112b7dedb928fa423b6878ea1b467d9/wandb/sdk/integration_utils/data_logging.py#L144-L156
|
|
edisonlz/fastor
|
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
|
base/site-packages/tencentcloud/vpc/v20170312/models.py
|
python
|
DescribeVpcsResponse.__init__
|
(self)
|
:param TotalCount: 符合条件的对象数。
:type TotalCount: int
:param VpcSet: VPC对象。
:type VpcSet: list of Vpc
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str
|
:param TotalCount: 符合条件的对象数。
:type TotalCount: int
:param VpcSet: VPC对象。
:type VpcSet: list of Vpc
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str
|
[
":",
"param",
"TotalCount",
":",
"符合条件的对象数。",
":",
"type",
"TotalCount",
":",
"int",
":",
"param",
"VpcSet",
":",
"VPC对象。",
":",
"type",
"VpcSet",
":",
"list",
"of",
"Vpc",
":",
"param",
"RequestId",
":",
"唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。",
":",
"type",
"RequestId",
":",
"str"
] |
def __init__(self):
"""
:param TotalCount: 符合条件的对象数。
:type TotalCount: int
:param VpcSet: VPC对象。
:type VpcSet: list of Vpc
:param RequestId: 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.VpcSet = None
self.RequestId = None
|
[
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TotalCount",
"=",
"None",
"self",
".",
"VpcSet",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] |
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/vpc/v20170312/models.py#L2626-L2637
|
||
glitchdotcom/WebPutty
|
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
|
ziplibs/markdown/odict.py
|
python
|
OrderedDict.index
|
(self, key)
|
return self.keyOrder.index(key)
|
Return the index of a given key.
|
Return the index of a given key.
|
[
"Return",
"the",
"index",
"of",
"a",
"given",
"key",
"."
] |
def index(self, key):
""" Return the index of a given key. """
return self.keyOrder.index(key)
|
[
"def",
"index",
"(",
"self",
",",
"key",
")",
":",
"return",
"self",
".",
"keyOrder",
".",
"index",
"(",
"key",
")"
] |
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/markdown/odict.py#L118-L120
|
|
pyansys/pymapdl
|
c07291fc062b359abf0e92b95a92d753a95ef3d7
|
ansys/mapdl/core/_commands/database/working_plane.py
|
python
|
WorkingPlane.wpcsys
|
(self, wn="", kcn="", **kwargs)
|
return self.run(command, **kwargs)
|
Defines the working plane location based on a coordinate system.
APDL Command: WPCSYS
Parameters
----------
wn
Window number whose viewing direction will be modified to be normal
to the working plane (defaults to 1). If WN is a negative value,
the viewing direction will not be modified.
kcn
Coordinate system number. KCN may be 0,1,2 or any previously
defined local coordinate system number (defaults to the active
system).
Notes
-----
Defines a working plane location and orientation based on an existing
coordinate system. If a Cartesian system is used as the basis (KCN)
for the working plane, the working plane will also be Cartesian, in the
X-Y plane of the base system. If a cylindrical, spherical, or toroidal
base system is used, the working plane will be a polar system in the
R-θ plane of the base system.
If working plane tracking has been activated (CSYS,WP or CSYS,4), the
updated active coordinate system will be of a similar type, except that
a toroidal system will be updated to a cylindrical system. See the
Modeling and Meshing Guide for more information on working plane
tracking.
This command is valid in any processor.
Some primitive generation commands will not honor R-theta
transformations for non-cartesian coordinate systems. Refer to the
primitive commands table for more information.
|
Defines the working plane location based on a coordinate system.
|
[
"Defines",
"the",
"working",
"plane",
"location",
"based",
"on",
"a",
"coordinate",
"system",
"."
] |
def wpcsys(self, wn="", kcn="", **kwargs):
"""Defines the working plane location based on a coordinate system.
APDL Command: WPCSYS
Parameters
----------
wn
Window number whose viewing direction will be modified to be normal
to the working plane (defaults to 1). If WN is a negative value,
the viewing direction will not be modified.
kcn
Coordinate system number. KCN may be 0,1,2 or any previously
defined local coordinate system number (defaults to the active
system).
Notes
-----
Defines a working plane location and orientation based on an existing
coordinate system. If a Cartesian system is used as the basis (KCN)
for the working plane, the working plane will also be Cartesian, in the
X-Y plane of the base system. If a cylindrical, spherical, or toroidal
base system is used, the working plane will be a polar system in the
R-θ plane of the base system.
If working plane tracking has been activated (CSYS,WP or CSYS,4), the
updated active coordinate system will be of a similar type, except that
a toroidal system will be updated to a cylindrical system. See the
Modeling and Meshing Guide for more information on working plane
tracking.
This command is valid in any processor.
Some primitive generation commands will not honor R-theta
transformations for non-cartesian coordinate systems. Refer to the
primitive commands table for more information.
"""
command = f"WPCSYS,{wn},{kcn}"
return self.run(command, **kwargs)
|
[
"def",
"wpcsys",
"(",
"self",
",",
"wn",
"=",
"\"\"",
",",
"kcn",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"f\"WPCSYS,{wn},{kcn}\"",
"return",
"self",
".",
"run",
"(",
"command",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/database/working_plane.py#L201-L240
|
|
nlloyd/SubliminalCollaborator
|
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
|
libs/twisted/names/dns.py
|
python
|
DNSDatagramProtocol.datagramReceived
|
(self, data, addr)
|
Read a datagram, extract the message in it and trigger the associated
Deferred.
|
Read a datagram, extract the message in it and trigger the associated
Deferred.
|
[
"Read",
"a",
"datagram",
"extract",
"the",
"message",
"in",
"it",
"and",
"trigger",
"the",
"associated",
"Deferred",
"."
] |
def datagramReceived(self, data, addr):
"""
Read a datagram, extract the message in it and trigger the associated
Deferred.
"""
m = Message()
try:
m.fromStr(data)
except EOFError:
log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
return
except:
# Nothing should trigger this, but since we're potentially
# invoking a lot of different decoding methods, we might as well
# be extra cautious. Anything that triggers this is itself
# buggy.
log.err(failure.Failure(), "Unexpected decoding error")
return
if m.id in self.liveMessages:
d, canceller = self.liveMessages[m.id]
del self.liveMessages[m.id]
canceller.cancel()
# XXX we shouldn't need this hack of catching exception on callback()
try:
d.callback(m)
except:
log.err()
else:
if m.id not in self.resends:
self.controller.messageReceived(m, self, addr)
|
[
"def",
"datagramReceived",
"(",
"self",
",",
"data",
",",
"addr",
")",
":",
"m",
"=",
"Message",
"(",
")",
"try",
":",
"m",
".",
"fromStr",
"(",
"data",
")",
"except",
"EOFError",
":",
"log",
".",
"msg",
"(",
"\"Truncated packet (%d bytes) from %s\"",
"%",
"(",
"len",
"(",
"data",
")",
",",
"addr",
")",
")",
"return",
"except",
":",
"# Nothing should trigger this, but since we're potentially",
"# invoking a lot of different decoding methods, we might as well",
"# be extra cautious. Anything that triggers this is itself",
"# buggy.",
"log",
".",
"err",
"(",
"failure",
".",
"Failure",
"(",
")",
",",
"\"Unexpected decoding error\"",
")",
"return",
"if",
"m",
".",
"id",
"in",
"self",
".",
"liveMessages",
":",
"d",
",",
"canceller",
"=",
"self",
".",
"liveMessages",
"[",
"m",
".",
"id",
"]",
"del",
"self",
".",
"liveMessages",
"[",
"m",
".",
"id",
"]",
"canceller",
".",
"cancel",
"(",
")",
"# XXX we shouldn't need this hack of catching exception on callback()",
"try",
":",
"d",
".",
"callback",
"(",
"m",
")",
"except",
":",
"log",
".",
"err",
"(",
")",
"else",
":",
"if",
"m",
".",
"id",
"not",
"in",
"self",
".",
"resends",
":",
"self",
".",
"controller",
".",
"messageReceived",
"(",
"m",
",",
"self",
",",
"addr",
")"
] |
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/names/dns.py#L1808-L1838
|
||
microsoft/azure-devops-python-api
|
451cade4c475482792cbe9e522c1fee32393139e
|
azure-devops/azure/devops/v6_0/nuget/nuget_client.py
|
python
|
NuGetClient.download_package
|
(self, feed_id, package_name, package_version, project=None, source_protocol_version=None, **kwargs)
|
return self._client.stream_download(response, callback=callback)
|
DownloadPackage.
[Preview API] Download a package version directly.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package.
:param str package_version: Version of the package.
:param str project: Project ID or project name
:param str source_protocol_version: Unused
:rtype: object
|
DownloadPackage.
[Preview API] Download a package version directly.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package.
:param str package_version: Version of the package.
:param str project: Project ID or project name
:param str source_protocol_version: Unused
:rtype: object
|
[
"DownloadPackage",
".",
"[",
"Preview",
"API",
"]",
"Download",
"a",
"package",
"version",
"directly",
".",
":",
"param",
"str",
"feed_id",
":",
"Name",
"or",
"ID",
"of",
"the",
"feed",
".",
":",
"param",
"str",
"package_name",
":",
"Name",
"of",
"the",
"package",
".",
":",
"param",
"str",
"package_version",
":",
"Version",
"of",
"the",
"package",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"str",
"source_protocol_version",
":",
"Unused",
":",
"rtype",
":",
"object"
] |
def download_package(self, feed_id, package_name, package_version, project=None, source_protocol_version=None, **kwargs):
"""DownloadPackage.
[Preview API] Download a package version directly.
:param str feed_id: Name or ID of the feed.
:param str package_name: Name of the package.
:param str package_version: Version of the package.
:param str project: Project ID or project name
:param str source_protocol_version: Unused
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if feed_id is not None:
route_values['feedId'] = self._serialize.url('feed_id', feed_id, 'str')
if package_name is not None:
route_values['packageName'] = self._serialize.url('package_name', package_name, 'str')
if package_version is not None:
route_values['packageVersion'] = self._serialize.url('package_version', package_version, 'str')
query_parameters = {}
if source_protocol_version is not None:
query_parameters['sourceProtocolVersion'] = self._serialize.query('source_protocol_version', source_protocol_version, 'str')
response = self._send(http_method='GET',
location_id='6ea81b8c-7386-490b-a71f-6cf23c80b388',
version='6.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
|
[
"def",
"download_package",
"(",
"self",
",",
"feed_id",
",",
"package_name",
",",
"package_version",
",",
"project",
"=",
"None",
",",
"source_protocol_version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'",
",",
"project",
",",
"'str'",
")",
"if",
"feed_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'feedId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'feed_id'",
",",
"feed_id",
",",
"'str'",
")",
"if",
"package_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'packageName'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'package_name'",
",",
"package_name",
",",
"'str'",
")",
"if",
"package_version",
"is",
"not",
"None",
":",
"route_values",
"[",
"'packageVersion'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'package_version'",
",",
"package_version",
",",
"'str'",
")",
"query_parameters",
"=",
"{",
"}",
"if",
"source_protocol_version",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'sourceProtocolVersion'",
"]",
"=",
"self",
".",
"_serialize",
".",
"query",
"(",
"'source_protocol_version'",
",",
"source_protocol_version",
",",
"'str'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'6ea81b8c-7386-490b-a71f-6cf23c80b388'",
",",
"version",
"=",
"'6.0-preview.1'",
",",
"route_values",
"=",
"route_values",
",",
"query_parameters",
"=",
"query_parameters",
",",
"accept_media_type",
"=",
"'application/octet-stream'",
")",
"if",
"\"callback\"",
"in",
"kwargs",
":",
"callback",
"=",
"kwargs",
"[",
"\"callback\"",
"]",
"else",
":",
"callback",
"=",
"None",
"return",
"self",
".",
"_client",
".",
"stream_download",
"(",
"response",
",",
"callback",
"=",
"callback",
")"
] |
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/nuget/nuget_client.py#L28-L60
|
|
entropy1337/infernal-twin
|
10995cd03312e39a48ade0f114ebb0ae3a711bb8
|
Modules/build/reportlab/build/lib.linux-i686-2.7/reportlab/pdfgen/canvas.py
|
python
|
Canvas.drawString
|
(self, x, y, text, mode=None, charSpace=0)
|
Draws a string in the current text styles.
|
Draws a string in the current text styles.
|
[
"Draws",
"a",
"string",
"in",
"the",
"current",
"text",
"styles",
"."
] |
def drawString(self, x, y, text, mode=None, charSpace=0):
"""Draws a string in the current text styles."""
if sys.version_info[0] == 3 and not isinstance(text, str):
text = text.decode('utf-8')
#we could inline this for speed if needed
t = self.beginText(x, y)
if mode is not None: t.setTextRenderMode(mode)
if charSpace: t.setCharSpace(charSpace)
t.textLine(text)
if charSpace: t.setCharSpace(0)
if mode is not None: t.setTextRenderMode(0)
self.drawText(t)
|
[
"def",
"drawString",
"(",
"self",
",",
"x",
",",
"y",
",",
"text",
",",
"mode",
"=",
"None",
",",
"charSpace",
"=",
"0",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
"and",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"#we could inline this for speed if needed",
"t",
"=",
"self",
".",
"beginText",
"(",
"x",
",",
"y",
")",
"if",
"mode",
"is",
"not",
"None",
":",
"t",
".",
"setTextRenderMode",
"(",
"mode",
")",
"if",
"charSpace",
":",
"t",
".",
"setCharSpace",
"(",
"charSpace",
")",
"t",
".",
"textLine",
"(",
"text",
")",
"if",
"charSpace",
":",
"t",
".",
"setCharSpace",
"(",
"0",
")",
"if",
"mode",
"is",
"not",
"None",
":",
"t",
".",
"setTextRenderMode",
"(",
"0",
")",
"self",
".",
"drawText",
"(",
"t",
")"
] |
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/reportlab/build/lib.linux-i686-2.7/reportlab/pdfgen/canvas.py#L1500-L1511
|
||
theislab/anndata
|
664e32b0aa6625fe593370d37174384c05abfd4e
|
anndata/experimental/multi_files/_anncollection.py
|
python
|
AnnCollection.to_adata
|
(self)
|
return adata
|
Convert this AnnCollection object to an AnnData object.
The AnnData object won't have `.X`, only `.obs` and `.obsm`.
|
Convert this AnnCollection object to an AnnData object.
|
[
"Convert",
"this",
"AnnCollection",
"object",
"to",
"an",
"AnnData",
"object",
"."
] |
def to_adata(self):
"""Convert this AnnCollection object to an AnnData object.
The AnnData object won't have `.X`, only `.obs` and `.obsm`.
"""
if "obs" in self._view_attrs_keys or "obsm" in self._view_attrs_keys:
concat_view = self[self.obs_names]
if "obsm" in self._view_attrs_keys:
obsm = (
concat_view.obsm.to_dict(use_convert=False)
if concat_view.obsm is not None
else None
)
else:
obsm = self.obsm.copy()
obs = self.obs.copy()
if "obs" in self._view_attrs_keys and concat_view.obs is not None:
for key, value in concat_view.obs.to_dict(use_convert=False).items():
obs[key] = value
adata = AnnData(X=None, obs=obs, obsm=obsm, shape=self.shape)
adata.obs_names = self.obs_names
adata.var_names = self.var_names
return adata
|
[
"def",
"to_adata",
"(",
"self",
")",
":",
"if",
"\"obs\"",
"in",
"self",
".",
"_view_attrs_keys",
"or",
"\"obsm\"",
"in",
"self",
".",
"_view_attrs_keys",
":",
"concat_view",
"=",
"self",
"[",
"self",
".",
"obs_names",
"]",
"if",
"\"obsm\"",
"in",
"self",
".",
"_view_attrs_keys",
":",
"obsm",
"=",
"(",
"concat_view",
".",
"obsm",
".",
"to_dict",
"(",
"use_convert",
"=",
"False",
")",
"if",
"concat_view",
".",
"obsm",
"is",
"not",
"None",
"else",
"None",
")",
"else",
":",
"obsm",
"=",
"self",
".",
"obsm",
".",
"copy",
"(",
")",
"obs",
"=",
"self",
".",
"obs",
".",
"copy",
"(",
")",
"if",
"\"obs\"",
"in",
"self",
".",
"_view_attrs_keys",
"and",
"concat_view",
".",
"obs",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"concat_view",
".",
"obs",
".",
"to_dict",
"(",
"use_convert",
"=",
"False",
")",
".",
"items",
"(",
")",
":",
"obs",
"[",
"key",
"]",
"=",
"value",
"adata",
"=",
"AnnData",
"(",
"X",
"=",
"None",
",",
"obs",
"=",
"obs",
",",
"obsm",
"=",
"obsm",
",",
"shape",
"=",
"self",
".",
"shape",
")",
"adata",
".",
"obs_names",
"=",
"self",
".",
"obs_names",
"adata",
".",
"var_names",
"=",
"self",
".",
"var_names",
"return",
"adata"
] |
https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/experimental/multi_files/_anncollection.py#L856-L881
|
|
mlcommons/inference
|
078e21f2bc0a37c7fd0e435d64f5a49760dca823
|
vision/medical_imaging/3d-unet-kits19/pytorch_checkpoint_SUT.py
|
python
|
_3DUNET_PyTorch_CHECKPOINT_SUT.from_tensor
|
(self, my_tensor)
|
return my_tensor.cpu().numpy().astype(np.float)
|
Transform Torch tensor into numpy array
|
Transform Torch tensor into numpy array
|
[
"Transform",
"Torch",
"tensor",
"into",
"numpy",
"array"
] |
def from_tensor(self, my_tensor):
"""
Transform Torch tensor into numpy array
"""
return my_tensor.cpu().numpy().astype(np.float)
|
[
"def",
"from_tensor",
"(",
"self",
",",
"my_tensor",
")",
":",
"return",
"my_tensor",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
".",
"astype",
"(",
"np",
".",
"float",
")"
] |
https://github.com/mlcommons/inference/blob/078e21f2bc0a37c7fd0e435d64f5a49760dca823/vision/medical_imaging/3d-unet-kits19/pytorch_checkpoint_SUT.py#L276-L280
|
|
firedrakeproject/firedrake
|
06ab4975c14c0d4dcb79be55821f8b9e41554125
|
firedrake/function.py
|
python
|
Function.__init__
|
(self, function_space, val=None, name=None, dtype=ScalarType)
|
r"""
:param function_space: the :class:`.FunctionSpace`,
or :class:`.MixedFunctionSpace` on which to build this :class:`Function`.
Alternatively, another :class:`Function` may be passed here and its function space
will be used to build this :class:`Function`. In this
case, the function values are copied.
:param val: NumPy array-like (or :class:`pyop2.Dat`) providing initial values (optional).
If val is an existing :class:`Function`, then the data will be shared.
:param name: user-defined name for this :class:`Function` (optional).
:param dtype: optional data type for this :class:`Function`
(defaults to ``ScalarType``).
|
r"""
:param function_space: the :class:`.FunctionSpace`,
or :class:`.MixedFunctionSpace` on which to build this :class:`Function`.
Alternatively, another :class:`Function` may be passed here and its function space
will be used to build this :class:`Function`. In this
case, the function values are copied.
:param val: NumPy array-like (or :class:`pyop2.Dat`) providing initial values (optional).
If val is an existing :class:`Function`, then the data will be shared.
:param name: user-defined name for this :class:`Function` (optional).
:param dtype: optional data type for this :class:`Function`
(defaults to ``ScalarType``).
|
[
"r",
":",
"param",
"function_space",
":",
"the",
":",
"class",
":",
".",
"FunctionSpace",
"or",
":",
"class",
":",
".",
"MixedFunctionSpace",
"on",
"which",
"to",
"build",
"this",
":",
"class",
":",
"Function",
".",
"Alternatively",
"another",
":",
"class",
":",
"Function",
"may",
"be",
"passed",
"here",
"and",
"its",
"function",
"space",
"will",
"be",
"used",
"to",
"build",
"this",
":",
"class",
":",
"Function",
".",
"In",
"this",
"case",
"the",
"function",
"values",
"are",
"copied",
".",
":",
"param",
"val",
":",
"NumPy",
"array",
"-",
"like",
"(",
"or",
":",
"class",
":",
"pyop2",
".",
"Dat",
")",
"providing",
"initial",
"values",
"(",
"optional",
")",
".",
"If",
"val",
"is",
"an",
"existing",
":",
"class",
":",
"Function",
"then",
"the",
"data",
"will",
"be",
"shared",
".",
":",
"param",
"name",
":",
"user",
"-",
"defined",
"name",
"for",
"this",
":",
"class",
":",
"Function",
"(",
"optional",
")",
".",
":",
"param",
"dtype",
":",
"optional",
"data",
"type",
"for",
"this",
":",
"class",
":",
"Function",
"(",
"defaults",
"to",
"ScalarType",
")",
"."
] |
def __init__(self, function_space, val=None, name=None, dtype=ScalarType):
r"""
:param function_space: the :class:`.FunctionSpace`,
or :class:`.MixedFunctionSpace` on which to build this :class:`Function`.
Alternatively, another :class:`Function` may be passed here and its function space
will be used to build this :class:`Function`. In this
case, the function values are copied.
:param val: NumPy array-like (or :class:`pyop2.Dat`) providing initial values (optional).
If val is an existing :class:`Function`, then the data will be shared.
:param name: user-defined name for this :class:`Function` (optional).
:param dtype: optional data type for this :class:`Function`
(defaults to ``ScalarType``).
"""
V = function_space
if isinstance(V, Function):
V = V.function_space()
elif not isinstance(V, functionspaceimpl.WithGeometry):
raise NotImplementedError("Can't make a Function defined on a "
+ str(type(function_space)))
if isinstance(val, (Function, CoordinatelessFunction)):
val = val.topological
if val.function_space() != V.topological:
raise ValueError("Function values have wrong function space.")
self._data = val
else:
self._data = CoordinatelessFunction(V.topological,
val=val, name=name, dtype=dtype)
self._function_space = V
ufl.Coefficient.__init__(self, self.function_space().ufl_function_space())
if cachetools:
# LRU cache for expressions assembled onto this function
self._expression_cache = cachetools.LRUCache(maxsize=50)
else:
self._expression_cache = None
if isinstance(function_space, Function):
self.assign(function_space)
|
[
"def",
"__init__",
"(",
"self",
",",
"function_space",
",",
"val",
"=",
"None",
",",
"name",
"=",
"None",
",",
"dtype",
"=",
"ScalarType",
")",
":",
"V",
"=",
"function_space",
"if",
"isinstance",
"(",
"V",
",",
"Function",
")",
":",
"V",
"=",
"V",
".",
"function_space",
"(",
")",
"elif",
"not",
"isinstance",
"(",
"V",
",",
"functionspaceimpl",
".",
"WithGeometry",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Can't make a Function defined on a \"",
"+",
"str",
"(",
"type",
"(",
"function_space",
")",
")",
")",
"if",
"isinstance",
"(",
"val",
",",
"(",
"Function",
",",
"CoordinatelessFunction",
")",
")",
":",
"val",
"=",
"val",
".",
"topological",
"if",
"val",
".",
"function_space",
"(",
")",
"!=",
"V",
".",
"topological",
":",
"raise",
"ValueError",
"(",
"\"Function values have wrong function space.\"",
")",
"self",
".",
"_data",
"=",
"val",
"else",
":",
"self",
".",
"_data",
"=",
"CoordinatelessFunction",
"(",
"V",
".",
"topological",
",",
"val",
"=",
"val",
",",
"name",
"=",
"name",
",",
"dtype",
"=",
"dtype",
")",
"self",
".",
"_function_space",
"=",
"V",
"ufl",
".",
"Coefficient",
".",
"__init__",
"(",
"self",
",",
"self",
".",
"function_space",
"(",
")",
".",
"ufl_function_space",
"(",
")",
")",
"if",
"cachetools",
":",
"# LRU cache for expressions assembled onto this function",
"self",
".",
"_expression_cache",
"=",
"cachetools",
".",
"LRUCache",
"(",
"maxsize",
"=",
"50",
")",
"else",
":",
"self",
".",
"_expression_cache",
"=",
"None",
"if",
"isinstance",
"(",
"function_space",
",",
"Function",
")",
":",
"self",
".",
"assign",
"(",
"function_space",
")"
] |
https://github.com/firedrakeproject/firedrake/blob/06ab4975c14c0d4dcb79be55821f8b9e41554125/firedrake/function.py#L231-L271
|
||
plotly/plotly.py
|
cfad7862594b35965c0e000813bd7805e8494a5b
|
packages/python/plotly/plotly/graph_objs/treemap/_stream.py
|
python
|
Stream.__init__
|
(self, arg=None, maxpoints=None, token=None, **kwargs)
|
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
|
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
|
[
"Construct",
"a",
"new",
"Stream",
"object",
"Parameters",
"----------",
"arg",
"dict",
"of",
"properties",
"compatible",
"with",
"this",
"constructor",
"or",
"an",
"instance",
"of",
":",
"class",
":",
"plotly",
".",
"graph_objs",
".",
"treemap",
".",
"Stream",
"maxpoints",
"Sets",
"the",
"maximum",
"number",
"of",
"points",
"to",
"keep",
"on",
"the",
"plots",
"from",
"an",
"incoming",
"stream",
".",
"If",
"maxpoints",
"is",
"set",
"to",
"50",
"only",
"the",
"newest",
"50",
"points",
"will",
"be",
"displayed",
"on",
"the",
"plot",
".",
"token",
"The",
"stream",
"id",
"number",
"links",
"a",
"data",
"trace",
"on",
"a",
"plot",
"with",
"a",
"stream",
".",
"See",
"https",
":",
"//",
"chart",
"-",
"studio",
".",
"plotly",
".",
"com",
"/",
"settings",
"for",
"more",
"details",
"."
] |
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.treemap.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
"""
super(Stream, self).__init__("stream")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.treemap.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.treemap.Stream`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("maxpoints", None)
_v = maxpoints if maxpoints is not None else _v
if _v is not None:
self["maxpoints"] = _v
_v = arg.pop("token", None)
_v = token if token is not None else _v
if _v is not None:
self["token"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
|
[
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"maxpoints",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Stream",
",",
"self",
")",
".",
"__init__",
"(",
"\"stream\"",
")",
"if",
"\"_parent\"",
"in",
"kwargs",
":",
"self",
".",
"_parent",
"=",
"kwargs",
"[",
"\"_parent\"",
"]",
"return",
"# Validate arg",
"# ------------",
"if",
"arg",
"is",
"None",
":",
"arg",
"=",
"{",
"}",
"elif",
"isinstance",
"(",
"arg",
",",
"self",
".",
"__class__",
")",
":",
"arg",
"=",
"arg",
".",
"to_plotly_json",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"arg",
"=",
"_copy",
".",
"copy",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"\"\"\\\nThe first argument to the plotly.graph_objs.treemap.Stream \nconstructor must be a dict or \nan instance of :class:`plotly.graph_objs.treemap.Stream`\"\"\"",
")",
"# Handle skip_invalid",
"# -------------------",
"self",
".",
"_skip_invalid",
"=",
"kwargs",
".",
"pop",
"(",
"\"skip_invalid\"",
",",
"False",
")",
"self",
".",
"_validate",
"=",
"kwargs",
".",
"pop",
"(",
"\"_validate\"",
",",
"True",
")",
"# Populate data dict with properties",
"# ----------------------------------",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"maxpoints\"",
",",
"None",
")",
"_v",
"=",
"maxpoints",
"if",
"maxpoints",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"maxpoints\"",
"]",
"=",
"_v",
"_v",
"=",
"arg",
".",
"pop",
"(",
"\"token\"",
",",
"None",
")",
"_v",
"=",
"token",
"if",
"token",
"is",
"not",
"None",
"else",
"_v",
"if",
"_v",
"is",
"not",
"None",
":",
"self",
"[",
"\"token\"",
"]",
"=",
"_v",
"# Process unknown kwargs",
"# ----------------------",
"self",
".",
"_process_kwargs",
"(",
"*",
"*",
"dict",
"(",
"arg",
",",
"*",
"*",
"kwargs",
")",
")",
"# Reset skip_invalid",
"# ------------------",
"self",
".",
"_skip_invalid",
"=",
"False"
] |
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/treemap/_stream.py#L73-L141
|
||
hatRiot/zarp
|
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
|
src/lib/libmproxy/contrib/jsbeautifier/__init__.py
|
python
|
Beautifier.handle_word
|
(self, token_text)
|
[] |
def handle_word(self, token_text):
if self.do_block_just_closed:
self.append(' ')
self.append(token_text)
self.append(' ')
self.do_block_just_closed = False
return
if token_text == 'function':
if self.flags.var_line:
self.flags.var_line_reindented = not self.opts.keep_function_indentation
if (self.just_added_newline or self.last_text == ';') and self.last_text != '{':
# make sure there is a nice clean space of at least one blank line
# before a new function definition
have_newlines = self.n_newlines
if not self.just_added_newline:
have_newlines = 0
if not self.opts.preserve_newlines:
have_newlines = 1
for i in range(2 - have_newlines):
self.append_newline(False)
if token_text in ['case', 'default']:
if self.last_text == ':':
self.remove_indent()
else:
self.flags.indentation_level -= 1
self.append_newline()
self.flags.indentation_level += 1
self.append(token_text)
self.flags.in_case = True
return
prefix = 'NONE'
if self.last_type == 'TK_END_BLOCK':
if token_text not in ['else', 'catch', 'finally']:
prefix = 'NEWLINE'
else:
if self.opts.brace_style in ['expand', 'end-expand']:
prefix = 'NEWLINE'
else:
prefix = 'SPACE'
self.append(' ')
elif self.last_type == 'TK_SEMICOLON' and self.flags.mode in ['BLOCK', 'DO_BLOCK']:
prefix = 'NEWLINE'
elif self.last_type == 'TK_SEMICOLON' and self.is_expression(self.flags.mode):
prefix = 'SPACE'
elif self.last_type == 'TK_STRING':
prefix = 'NEWLINE'
elif self.last_type == 'TK_WORD':
if self.last_text == 'else':
# eat newlines between ...else *** some_op...
# won't preserve extra newlines in this place (if any), but don't care that much
self.trim_output(True)
prefix = 'SPACE'
elif self.last_type == 'TK_START_BLOCK':
prefix = 'NEWLINE'
elif self.last_type == 'TK_END_EXPR':
self.append(' ')
prefix = 'NEWLINE'
if self.flags.if_line and self.last_type == 'TK_END_EXPR':
self.flags.if_line = False
if token_text in self.line_starters:
if self.last_text == 'else':
prefix = 'SPACE'
else:
prefix = 'NEWLINE'
if token_text == 'function' and self.last_text in ['get', 'set']:
prefix = 'SPACE'
if token_text in ['else', 'catch', 'finally']:
if self.last_type != 'TK_END_BLOCK' \
or self.opts.brace_style == 'expand' \
or self.opts.brace_style == 'end-expand':
self.append_newline()
else:
self.trim_output(True)
self.append(' ')
elif prefix == 'NEWLINE':
if token_text == 'function' and (self.last_type == 'TK_START_EXPR' or self.last_text in '=,'):
# no need to force newline on "function" -
# (function...
pass
elif token_text == 'function' and self.last_text == 'new':
self.append(' ')
elif self.is_special_word(self.last_text):
# no newline between return nnn
self.append(' ')
elif self.last_type != 'TK_END_EXPR':
if (self.last_type != 'TK_START_EXPR' or token_text != 'var') and self.last_text != ':':
# no need to force newline on VAR -
# for (var x = 0...
if token_text == 'if' and self.last_word == 'else' and self.last_text != '{':
self.append(' ')
else:
self.flags.var_line = False
self.flags.var_line_reindented = False
self.append_newline()
elif token_text in self.line_starters and self.last_text != ')':
self.flags.var_line = False
self.flags.var_line_reindented = False
self.append_newline()
elif self.is_array(self.flags.mode) and self.last_text == ',' and self.last_last_text == '}':
self.append_newline() # }, in lists get a newline
elif prefix == 'SPACE':
self.append(' ')
self.append(token_text)
self.last_word = token_text
if token_text == 'var':
self.flags.var_line = True
self.flags.var_line_reindented = False
self.flags.var_line_tainted = False
if token_text == 'if':
self.flags.if_line = True
if token_text == 'else':
self.flags.if_line = False
|
[
"def",
"handle_word",
"(",
"self",
",",
"token_text",
")",
":",
"if",
"self",
".",
"do_block_just_closed",
":",
"self",
".",
"append",
"(",
"' '",
")",
"self",
".",
"append",
"(",
"token_text",
")",
"self",
".",
"append",
"(",
"' '",
")",
"self",
".",
"do_block_just_closed",
"=",
"False",
"return",
"if",
"token_text",
"==",
"'function'",
":",
"if",
"self",
".",
"flags",
".",
"var_line",
":",
"self",
".",
"flags",
".",
"var_line_reindented",
"=",
"not",
"self",
".",
"opts",
".",
"keep_function_indentation",
"if",
"(",
"self",
".",
"just_added_newline",
"or",
"self",
".",
"last_text",
"==",
"';'",
")",
"and",
"self",
".",
"last_text",
"!=",
"'{'",
":",
"# make sure there is a nice clean space of at least one blank line",
"# before a new function definition",
"have_newlines",
"=",
"self",
".",
"n_newlines",
"if",
"not",
"self",
".",
"just_added_newline",
":",
"have_newlines",
"=",
"0",
"if",
"not",
"self",
".",
"opts",
".",
"preserve_newlines",
":",
"have_newlines",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"2",
"-",
"have_newlines",
")",
":",
"self",
".",
"append_newline",
"(",
"False",
")",
"if",
"token_text",
"in",
"[",
"'case'",
",",
"'default'",
"]",
":",
"if",
"self",
".",
"last_text",
"==",
"':'",
":",
"self",
".",
"remove_indent",
"(",
")",
"else",
":",
"self",
".",
"flags",
".",
"indentation_level",
"-=",
"1",
"self",
".",
"append_newline",
"(",
")",
"self",
".",
"flags",
".",
"indentation_level",
"+=",
"1",
"self",
".",
"append",
"(",
"token_text",
")",
"self",
".",
"flags",
".",
"in_case",
"=",
"True",
"return",
"prefix",
"=",
"'NONE'",
"if",
"self",
".",
"last_type",
"==",
"'TK_END_BLOCK'",
":",
"if",
"token_text",
"not",
"in",
"[",
"'else'",
",",
"'catch'",
",",
"'finally'",
"]",
":",
"prefix",
"=",
"'NEWLINE'",
"else",
":",
"if",
"self",
".",
"opts",
".",
"brace_style",
"in",
"[",
"'expand'",
",",
"'end-expand'",
"]",
":",
"prefix",
"=",
"'NEWLINE'",
"else",
":",
"prefix",
"=",
"'SPACE'",
"self",
".",
"append",
"(",
"' '",
")",
"elif",
"self",
".",
"last_type",
"==",
"'TK_SEMICOLON'",
"and",
"self",
".",
"flags",
".",
"mode",
"in",
"[",
"'BLOCK'",
",",
"'DO_BLOCK'",
"]",
":",
"prefix",
"=",
"'NEWLINE'",
"elif",
"self",
".",
"last_type",
"==",
"'TK_SEMICOLON'",
"and",
"self",
".",
"is_expression",
"(",
"self",
".",
"flags",
".",
"mode",
")",
":",
"prefix",
"=",
"'SPACE'",
"elif",
"self",
".",
"last_type",
"==",
"'TK_STRING'",
":",
"prefix",
"=",
"'NEWLINE'",
"elif",
"self",
".",
"last_type",
"==",
"'TK_WORD'",
":",
"if",
"self",
".",
"last_text",
"==",
"'else'",
":",
"# eat newlines between ...else *** some_op...",
"# won't preserve extra newlines in this place (if any), but don't care that much",
"self",
".",
"trim_output",
"(",
"True",
")",
"prefix",
"=",
"'SPACE'",
"elif",
"self",
".",
"last_type",
"==",
"'TK_START_BLOCK'",
":",
"prefix",
"=",
"'NEWLINE'",
"elif",
"self",
".",
"last_type",
"==",
"'TK_END_EXPR'",
":",
"self",
".",
"append",
"(",
"' '",
")",
"prefix",
"=",
"'NEWLINE'",
"if",
"self",
".",
"flags",
".",
"if_line",
"and",
"self",
".",
"last_type",
"==",
"'TK_END_EXPR'",
":",
"self",
".",
"flags",
".",
"if_line",
"=",
"False",
"if",
"token_text",
"in",
"self",
".",
"line_starters",
":",
"if",
"self",
".",
"last_text",
"==",
"'else'",
":",
"prefix",
"=",
"'SPACE'",
"else",
":",
"prefix",
"=",
"'NEWLINE'",
"if",
"token_text",
"==",
"'function'",
"and",
"self",
".",
"last_text",
"in",
"[",
"'get'",
",",
"'set'",
"]",
":",
"prefix",
"=",
"'SPACE'",
"if",
"token_text",
"in",
"[",
"'else'",
",",
"'catch'",
",",
"'finally'",
"]",
":",
"if",
"self",
".",
"last_type",
"!=",
"'TK_END_BLOCK'",
"or",
"self",
".",
"opts",
".",
"brace_style",
"==",
"'expand'",
"or",
"self",
".",
"opts",
".",
"brace_style",
"==",
"'end-expand'",
":",
"self",
".",
"append_newline",
"(",
")",
"else",
":",
"self",
".",
"trim_output",
"(",
"True",
")",
"self",
".",
"append",
"(",
"' '",
")",
"elif",
"prefix",
"==",
"'NEWLINE'",
":",
"if",
"token_text",
"==",
"'function'",
"and",
"(",
"self",
".",
"last_type",
"==",
"'TK_START_EXPR'",
"or",
"self",
".",
"last_text",
"in",
"'=,'",
")",
":",
"# no need to force newline on \"function\" -",
"# (function...",
"pass",
"elif",
"token_text",
"==",
"'function'",
"and",
"self",
".",
"last_text",
"==",
"'new'",
":",
"self",
".",
"append",
"(",
"' '",
")",
"elif",
"self",
".",
"is_special_word",
"(",
"self",
".",
"last_text",
")",
":",
"# no newline between return nnn",
"self",
".",
"append",
"(",
"' '",
")",
"elif",
"self",
".",
"last_type",
"!=",
"'TK_END_EXPR'",
":",
"if",
"(",
"self",
".",
"last_type",
"!=",
"'TK_START_EXPR'",
"or",
"token_text",
"!=",
"'var'",
")",
"and",
"self",
".",
"last_text",
"!=",
"':'",
":",
"# no need to force newline on VAR -",
"# for (var x = 0...",
"if",
"token_text",
"==",
"'if'",
"and",
"self",
".",
"last_word",
"==",
"'else'",
"and",
"self",
".",
"last_text",
"!=",
"'{'",
":",
"self",
".",
"append",
"(",
"' '",
")",
"else",
":",
"self",
".",
"flags",
".",
"var_line",
"=",
"False",
"self",
".",
"flags",
".",
"var_line_reindented",
"=",
"False",
"self",
".",
"append_newline",
"(",
")",
"elif",
"token_text",
"in",
"self",
".",
"line_starters",
"and",
"self",
".",
"last_text",
"!=",
"')'",
":",
"self",
".",
"flags",
".",
"var_line",
"=",
"False",
"self",
".",
"flags",
".",
"var_line_reindented",
"=",
"False",
"self",
".",
"append_newline",
"(",
")",
"elif",
"self",
".",
"is_array",
"(",
"self",
".",
"flags",
".",
"mode",
")",
"and",
"self",
".",
"last_text",
"==",
"','",
"and",
"self",
".",
"last_last_text",
"==",
"'}'",
":",
"self",
".",
"append_newline",
"(",
")",
"# }, in lists get a newline",
"elif",
"prefix",
"==",
"'SPACE'",
":",
"self",
".",
"append",
"(",
"' '",
")",
"self",
".",
"append",
"(",
"token_text",
")",
"self",
".",
"last_word",
"=",
"token_text",
"if",
"token_text",
"==",
"'var'",
":",
"self",
".",
"flags",
".",
"var_line",
"=",
"True",
"self",
".",
"flags",
".",
"var_line_reindented",
"=",
"False",
"self",
".",
"flags",
".",
"var_line_tainted",
"=",
"False",
"if",
"token_text",
"==",
"'if'",
":",
"self",
".",
"flags",
".",
"if_line",
"=",
"True",
"if",
"token_text",
"==",
"'else'",
":",
"self",
".",
"flags",
".",
"if_line",
"=",
"False"
] |
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/contrib/jsbeautifier/__init__.py#L773-L899
|
||||
salabim/salabim
|
e0de846b042daf2dc71aaf43d8adc6486b57f376
|
sample models/Elevator animated.py
|
python
|
Car.process
|
(self)
|
[] |
def process(self):
dooropen = False
self.floor = floors[0]
self.direction = still
dooropen = False
while True:
if self.direction == still:
if not requests:
yield self.passivate(mode="Idle")
if self.count_to_floor(self.floor) > 0:
yield self.hold(dooropen_time, mode="Door open")
dooropen = True
for visitor in self.visitors:
if visitor.tofloor == self.floor:
visitor.leave(self.visitors)
visitor.activate()
yield self.hold(exit_time, mode="Let exit")
if self.direction == still:
self.direction = up # just random
for self.direction in (self.direction, -self.direction):
if (self.floor, self.direction) in requests:
del requests[self.floor, self.direction]
if not dooropen:
yield self.hold(dooropen_time, mode="Door open")
dooropen = True
for visitor in self.floor.visitors:
if visitor.direction == self.direction:
if len(self.visitors) < self.capacity:
visitor.leave(self.floor.visitors)
visitor.enter(self.visitors)
yield self.hold(enter_time, mode="Let in")
if self.floor.count_in_direction(self.direction) > 0:
if not (self.floor, self.direction) in requests:
requests[self.floor, self.direction] = self.env.now()
if self.visitors:
break
else:
if requests:
earliest = sim.inf
for (floor, direction) in requests:
if requests[floor, direction] < earliest:
self.direction = getdirection(self.floor, floor)
earliest = requests[floor, direction]
else:
self.direction = still
if dooropen:
yield self.hold(doorclose_time, mode="Door close")
dooropen = False
if self.direction != still:
self.nextfloor = floors[self.floor.n + self.direction]
yield self.hold(move_time, mode="Move")
self.floor = self.nextfloor
|
[
"def",
"process",
"(",
"self",
")",
":",
"dooropen",
"=",
"False",
"self",
".",
"floor",
"=",
"floors",
"[",
"0",
"]",
"self",
".",
"direction",
"=",
"still",
"dooropen",
"=",
"False",
"while",
"True",
":",
"if",
"self",
".",
"direction",
"==",
"still",
":",
"if",
"not",
"requests",
":",
"yield",
"self",
".",
"passivate",
"(",
"mode",
"=",
"\"Idle\"",
")",
"if",
"self",
".",
"count_to_floor",
"(",
"self",
".",
"floor",
")",
">",
"0",
":",
"yield",
"self",
".",
"hold",
"(",
"dooropen_time",
",",
"mode",
"=",
"\"Door open\"",
")",
"dooropen",
"=",
"True",
"for",
"visitor",
"in",
"self",
".",
"visitors",
":",
"if",
"visitor",
".",
"tofloor",
"==",
"self",
".",
"floor",
":",
"visitor",
".",
"leave",
"(",
"self",
".",
"visitors",
")",
"visitor",
".",
"activate",
"(",
")",
"yield",
"self",
".",
"hold",
"(",
"exit_time",
",",
"mode",
"=",
"\"Let exit\"",
")",
"if",
"self",
".",
"direction",
"==",
"still",
":",
"self",
".",
"direction",
"=",
"up",
"# just random",
"for",
"self",
".",
"direction",
"in",
"(",
"self",
".",
"direction",
",",
"-",
"self",
".",
"direction",
")",
":",
"if",
"(",
"self",
".",
"floor",
",",
"self",
".",
"direction",
")",
"in",
"requests",
":",
"del",
"requests",
"[",
"self",
".",
"floor",
",",
"self",
".",
"direction",
"]",
"if",
"not",
"dooropen",
":",
"yield",
"self",
".",
"hold",
"(",
"dooropen_time",
",",
"mode",
"=",
"\"Door open\"",
")",
"dooropen",
"=",
"True",
"for",
"visitor",
"in",
"self",
".",
"floor",
".",
"visitors",
":",
"if",
"visitor",
".",
"direction",
"==",
"self",
".",
"direction",
":",
"if",
"len",
"(",
"self",
".",
"visitors",
")",
"<",
"self",
".",
"capacity",
":",
"visitor",
".",
"leave",
"(",
"self",
".",
"floor",
".",
"visitors",
")",
"visitor",
".",
"enter",
"(",
"self",
".",
"visitors",
")",
"yield",
"self",
".",
"hold",
"(",
"enter_time",
",",
"mode",
"=",
"\"Let in\"",
")",
"if",
"self",
".",
"floor",
".",
"count_in_direction",
"(",
"self",
".",
"direction",
")",
">",
"0",
":",
"if",
"not",
"(",
"self",
".",
"floor",
",",
"self",
".",
"direction",
")",
"in",
"requests",
":",
"requests",
"[",
"self",
".",
"floor",
",",
"self",
".",
"direction",
"]",
"=",
"self",
".",
"env",
".",
"now",
"(",
")",
"if",
"self",
".",
"visitors",
":",
"break",
"else",
":",
"if",
"requests",
":",
"earliest",
"=",
"sim",
".",
"inf",
"for",
"(",
"floor",
",",
"direction",
")",
"in",
"requests",
":",
"if",
"requests",
"[",
"floor",
",",
"direction",
"]",
"<",
"earliest",
":",
"self",
".",
"direction",
"=",
"getdirection",
"(",
"self",
".",
"floor",
",",
"floor",
")",
"earliest",
"=",
"requests",
"[",
"floor",
",",
"direction",
"]",
"else",
":",
"self",
".",
"direction",
"=",
"still",
"if",
"dooropen",
":",
"yield",
"self",
".",
"hold",
"(",
"doorclose_time",
",",
"mode",
"=",
"\"Door close\"",
")",
"dooropen",
"=",
"False",
"if",
"self",
".",
"direction",
"!=",
"still",
":",
"self",
".",
"nextfloor",
"=",
"floors",
"[",
"self",
".",
"floor",
".",
"n",
"+",
"self",
".",
"direction",
"]",
"yield",
"self",
".",
"hold",
"(",
"move_time",
",",
"mode",
"=",
"\"Move\"",
")",
"self",
".",
"floor",
"=",
"self",
".",
"nextfloor"
] |
https://github.com/salabim/salabim/blob/e0de846b042daf2dc71aaf43d8adc6486b57f376/sample models/Elevator animated.py#L294-L350
|
||||
linkchecker/linkchecker
|
d1078ed8480e5cfc4264d0dbf026b45b45aede4d
|
linkcheck/log.py
|
python
|
exception
|
(logname, msg, *args, **kwargs)
|
Log an exception.
return: None
|
Log an exception.
|
[
"Log",
"an",
"exception",
"."
] |
def exception(logname, msg, *args, **kwargs):
"""Log an exception.
return: None
"""
log = logging.getLogger(logname)
if log.isEnabledFor(logging.ERROR):
_log(log.exception, msg, args, **kwargs)
|
[
"def",
"exception",
"(",
"logname",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logname",
")",
"if",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"ERROR",
")",
":",
"_log",
"(",
"log",
".",
"exception",
",",
"msg",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
https://github.com/linkchecker/linkchecker/blob/d1078ed8480e5cfc4264d0dbf026b45b45aede4d/linkcheck/log.py#L125-L132
|
||
natashamjaques/neural_chat
|
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
|
ParlAI/parlai/core/torch_generator_agent.py
|
python
|
TreeSearch.get_output_from_current_step
|
(self)
|
return self.outputs[-1]
|
Get the outputput at the current step.
|
Get the outputput at the current step.
|
[
"Get",
"the",
"outputput",
"at",
"the",
"current",
"step",
"."
] |
def get_output_from_current_step(self):
"""Get the outputput at the current step."""
return self.outputs[-1]
|
[
"def",
"get_output_from_current_step",
"(",
"self",
")",
":",
"return",
"self",
".",
"outputs",
"[",
"-",
"1",
"]"
] |
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/core/torch_generator_agent.py#L813-L815
|
|
modflowpy/flopy
|
eecd1ad193c5972093c9712e5c4b7a83284f0688
|
flopy/utils/geospatial_utils.py
|
python
|
GeoSpatialCollection.geojson
|
(self)
|
return self._geojson
|
Property that returns a geojson.GeometryCollection object to the user
Returns
-------
geojson.GeometryCollection
|
Property that returns a geojson.GeometryCollection object to the user
|
[
"Property",
"that",
"returns",
"a",
"geojson",
".",
"GeometryCollection",
"object",
"to",
"the",
"user"
] |
def geojson(self):
"""
Property that returns a geojson.GeometryCollection object to the user
Returns
-------
geojson.GeometryCollection
"""
geojson = import_optional_dependency("geojson")
self._geojson = geojson.GeometryCollection(
[i.geojson for i in self.__collection]
)
return self._geojson
|
[
"def",
"geojson",
"(",
"self",
")",
":",
"geojson",
"=",
"import_optional_dependency",
"(",
"\"geojson\"",
")",
"self",
".",
"_geojson",
"=",
"geojson",
".",
"GeometryCollection",
"(",
"[",
"i",
".",
"geojson",
"for",
"i",
"in",
"self",
".",
"__collection",
"]",
")",
"return",
"self",
".",
"_geojson"
] |
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/utils/geospatial_utils.py#L393-L405
|
|
RasaHQ/rasa
|
54823b68c1297849ba7ae841a4246193cd1223a1
|
rasa/graph_components/validators/default_recipe_validator.py
|
python
|
DefaultV1RecipeValidator._validate_policy_priorities
|
(self)
|
Checks if every policy has a valid priority value.
A policy must have a priority value. The priority values of
the policies used in the configuration should be unique.
Raises:
`InvalidConfigException` if any of the policies doesn't have a priority
|
Checks if every policy has a valid priority value.
|
[
"Checks",
"if",
"every",
"policy",
"has",
"a",
"valid",
"priority",
"value",
"."
] |
def _validate_policy_priorities(self) -> None:
"""Checks if every policy has a valid priority value.
A policy must have a priority value. The priority values of
the policies used in the configuration should be unique.
Raises:
`InvalidConfigException` if any of the policies doesn't have a priority
"""
priority_dict = defaultdict(list)
for schema_node in self._policy_schema_nodes:
default_config = schema_node.uses.get_default_config()
if POLICY_PRIORITY not in default_config:
raise InvalidConfigException(
f"Found a policy {schema_node.uses.__name__} which has no "
f"priority. Every policy must have a priority value which you "
f"can set in the `get_default_config` method of your policy."
)
default_priority = default_config[POLICY_PRIORITY]
priority = schema_node.config.get(POLICY_PRIORITY, default_priority)
priority_dict[priority].append(schema_node.uses)
for k, v in priority_dict.items():
if len(v) > 1:
rasa.shared.utils.io.raise_warning(
f"Found policies {_types_to_str(v)} with same priority {k} "
f"in PolicyEnsemble. When personalizing "
f"priorities, be sure to give all policies "
f"different priorities.",
docs=DOCS_URL_POLICIES,
)
|
[
"def",
"_validate_policy_priorities",
"(",
"self",
")",
"->",
"None",
":",
"priority_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"schema_node",
"in",
"self",
".",
"_policy_schema_nodes",
":",
"default_config",
"=",
"schema_node",
".",
"uses",
".",
"get_default_config",
"(",
")",
"if",
"POLICY_PRIORITY",
"not",
"in",
"default_config",
":",
"raise",
"InvalidConfigException",
"(",
"f\"Found a policy {schema_node.uses.__name__} which has no \"",
"f\"priority. Every policy must have a priority value which you \"",
"f\"can set in the `get_default_config` method of your policy.\"",
")",
"default_priority",
"=",
"default_config",
"[",
"POLICY_PRIORITY",
"]",
"priority",
"=",
"schema_node",
".",
"config",
".",
"get",
"(",
"POLICY_PRIORITY",
",",
"default_priority",
")",
"priority_dict",
"[",
"priority",
"]",
".",
"append",
"(",
"schema_node",
".",
"uses",
")",
"for",
"k",
",",
"v",
"in",
"priority_dict",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"v",
")",
">",
"1",
":",
"rasa",
".",
"shared",
".",
"utils",
".",
"io",
".",
"raise_warning",
"(",
"f\"Found policies {_types_to_str(v)} with same priority {k} \"",
"f\"in PolicyEnsemble. When personalizing \"",
"f\"priorities, be sure to give all policies \"",
"f\"different priorities.\"",
",",
"docs",
"=",
"DOCS_URL_POLICIES",
",",
")"
] |
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/graph_components/validators/default_recipe_validator.py#L447-L477
|
||
AppScale/gts
|
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
|
AppServer/lib/django-1.3/django/db/models/query.py
|
python
|
QuerySet.__getstate__
|
(self)
|
return obj_dict
|
Allows the QuerySet to be pickled.
|
Allows the QuerySet to be pickled.
|
[
"Allows",
"the",
"QuerySet",
"to",
"be",
"pickled",
"."
] |
def __getstate__(self):
"""
Allows the QuerySet to be pickled.
"""
# Force the cache to be fully populated.
len(self)
obj_dict = self.__dict__.copy()
obj_dict['_iter'] = None
return obj_dict
|
[
"def",
"__getstate__",
"(",
"self",
")",
":",
"# Force the cache to be fully populated.",
"len",
"(",
"self",
")",
"obj_dict",
"=",
"self",
".",
"__dict__",
".",
"copy",
"(",
")",
"obj_dict",
"[",
"'_iter'",
"]",
"=",
"None",
"return",
"obj_dict"
] |
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/db/models/query.py#L57-L66
|
|
oracle/graalpython
|
577e02da9755d916056184ec441c26e00b70145c
|
graalpython/lib-python/3/tarfile.py
|
python
|
nti
|
(s)
|
return n
|
Convert a number field to a python number.
|
Convert a number field to a python number.
|
[
"Convert",
"a",
"number",
"field",
"to",
"a",
"python",
"number",
"."
] |
def nti(s):
"""Convert a number field to a python number.
"""
# There are two possible encodings for a number field, see
# itn() below.
if s[0] in (0o200, 0o377):
n = 0
for i in range(len(s) - 1):
n <<= 8
n += s[i + 1]
if s[0] == 0o377:
n = -(256 ** (len(s) - 1) - n)
else:
try:
s = nts(s, "ascii", "strict")
n = int(s.strip() or "0", 8)
except ValueError:
raise InvalidHeaderError("invalid header")
return n
|
[
"def",
"nti",
"(",
"s",
")",
":",
"# There are two possible encodings for a number field, see",
"# itn() below.",
"if",
"s",
"[",
"0",
"]",
"in",
"(",
"0o200",
",",
"0o377",
")",
":",
"n",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
"-",
"1",
")",
":",
"n",
"<<=",
"8",
"n",
"+=",
"s",
"[",
"i",
"+",
"1",
"]",
"if",
"s",
"[",
"0",
"]",
"==",
"0o377",
":",
"n",
"=",
"-",
"(",
"256",
"**",
"(",
"len",
"(",
"s",
")",
"-",
"1",
")",
"-",
"n",
")",
"else",
":",
"try",
":",
"s",
"=",
"nts",
"(",
"s",
",",
"\"ascii\"",
",",
"\"strict\"",
")",
"n",
"=",
"int",
"(",
"s",
".",
"strip",
"(",
")",
"or",
"\"0\"",
",",
"8",
")",
"except",
"ValueError",
":",
"raise",
"InvalidHeaderError",
"(",
"\"invalid header\"",
")",
"return",
"n"
] |
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/tarfile.py#L172-L190
|
|
PyCQA/pylint
|
3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb
|
pylint/pyreverse/mermaidjs_printer.py
|
python
|
MermaidJSPrinter._close_graph
|
(self)
|
Emit the lines needed to properly close the graph.
|
Emit the lines needed to properly close the graph.
|
[
"Emit",
"the",
"lines",
"needed",
"to",
"properly",
"close",
"the",
"graph",
"."
] |
def _close_graph(self) -> None:
"""Emit the lines needed to properly close the graph."""
self._dec_indent()
|
[
"def",
"_close_graph",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_dec_indent",
"(",
")"
] |
https://github.com/PyCQA/pylint/blob/3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb/pylint/pyreverse/mermaidjs_printer.py#L79-L81
|
||
oracle/oci-python-sdk
|
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
|
src/oci/integration/integration_instance_client.py
|
python
|
IntegrationInstanceClient.stop_integration_instance
|
(self, integration_instance_id, **kwargs)
|
Stop an integration instance that was previously in an ACTIVE state
:param str integration_instance_id: (required)
Unique Integration Instance identifier.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call
for a resource, set the `if-match` parameter to the value of the
etag from a previous GET or POST response for that resource.
The resource will be updated or deleted only if the etag you
provide matches the resource's current etag value.
:param str opc_request_id: (optional)
The client request ID for tracing.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case
of a timeout or server error without risk of executing that same action
again. Retry tokens expire after 24 hours, but can be invalidated before
then due to conflicting operations. For example, if a resource has been
deleted and purged from the system, then a retry of the original creation
request might be rejected.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/integration/stop_integration_instance.py.html>`__ to see an example of how to use stop_integration_instance API.
|
Stop an integration instance that was previously in an ACTIVE state
|
[
"Stop",
"an",
"integration",
"instance",
"that",
"was",
"previously",
"in",
"an",
"ACTIVE",
"state"
] |
def stop_integration_instance(self, integration_instance_id, **kwargs):
"""
Stop an integration instance that was previously in an ACTIVE state
:param str integration_instance_id: (required)
Unique Integration Instance identifier.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call
for a resource, set the `if-match` parameter to the value of the
etag from a previous GET or POST response for that resource.
The resource will be updated or deleted only if the etag you
provide matches the resource's current etag value.
:param str opc_request_id: (optional)
The client request ID for tracing.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case
of a timeout or server error without risk of executing that same action
again. Retry tokens expire after 24 hours, but can be invalidated before
then due to conflicting operations. For example, if a resource has been
deleted and purged from the system, then a retry of the original creation
request might be rejected.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/integration/stop_integration_instance.py.html>`__ to see an example of how to use stop_integration_instance API.
"""
resource_path = "/integrationInstances/{integrationInstanceId}/actions/stop"
method = "POST"
# Don't accept unknown kwargs
expected_kwargs = [
"retry_strategy",
"if_match",
"opc_request_id",
"opc_retry_token"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"stop_integration_instance got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"integrationInstanceId": integration_instance_id
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
for (k, v) in six.iteritems(path_params):
if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0):
raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"if-match": kwargs.get("if_match", missing),
"opc-request-id": kwargs.get("opc_request_id", missing),
"opc-retry-token": kwargs.get("opc_retry_token", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_retry_token_if_needed(header_params)
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params)
|
[
"def",
"stop_integration_instance",
"(",
"self",
",",
"integration_instance_id",
",",
"*",
"*",
"kwargs",
")",
":",
"resource_path",
"=",
"\"/integrationInstances/{integrationInstanceId}/actions/stop\"",
"method",
"=",
"\"POST\"",
"# Don't accept unknown kwargs",
"expected_kwargs",
"=",
"[",
"\"retry_strategy\"",
",",
"\"if_match\"",
",",
"\"opc_request_id\"",
",",
"\"opc_retry_token\"",
"]",
"extra_kwargs",
"=",
"[",
"_key",
"for",
"_key",
"in",
"six",
".",
"iterkeys",
"(",
"kwargs",
")",
"if",
"_key",
"not",
"in",
"expected_kwargs",
"]",
"if",
"extra_kwargs",
":",
"raise",
"ValueError",
"(",
"\"stop_integration_instance got unknown kwargs: {!r}\"",
".",
"format",
"(",
"extra_kwargs",
")",
")",
"path_params",
"=",
"{",
"\"integrationInstanceId\"",
":",
"integration_instance_id",
"}",
"path_params",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"path_params",
")",
"if",
"v",
"is",
"not",
"missing",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"path_params",
")",
":",
"if",
"v",
"is",
"None",
"or",
"(",
"isinstance",
"(",
"v",
",",
"six",
".",
"string_types",
")",
"and",
"len",
"(",
"v",
".",
"strip",
"(",
")",
")",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'Parameter {} cannot be None, whitespace or empty string'",
".",
"format",
"(",
"k",
")",
")",
"header_params",
"=",
"{",
"\"accept\"",
":",
"\"application/json\"",
",",
"\"content-type\"",
":",
"\"application/json\"",
",",
"\"if-match\"",
":",
"kwargs",
".",
"get",
"(",
"\"if_match\"",
",",
"missing",
")",
",",
"\"opc-request-id\"",
":",
"kwargs",
".",
"get",
"(",
"\"opc_request_id\"",
",",
"missing",
")",
",",
"\"opc-retry-token\"",
":",
"kwargs",
".",
"get",
"(",
"\"opc_retry_token\"",
",",
"missing",
")",
"}",
"header_params",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"header_params",
")",
"if",
"v",
"is",
"not",
"missing",
"and",
"v",
"is",
"not",
"None",
"}",
"retry_strategy",
"=",
"self",
".",
"base_client",
".",
"get_preferred_retry_strategy",
"(",
"operation_retry_strategy",
"=",
"kwargs",
".",
"get",
"(",
"'retry_strategy'",
")",
",",
"client_retry_strategy",
"=",
"self",
".",
"retry_strategy",
")",
"if",
"retry_strategy",
":",
"if",
"not",
"isinstance",
"(",
"retry_strategy",
",",
"retry",
".",
"NoneRetryStrategy",
")",
":",
"self",
".",
"base_client",
".",
"add_opc_retry_token_if_needed",
"(",
"header_params",
")",
"self",
".",
"base_client",
".",
"add_opc_client_retries_header",
"(",
"header_params",
")",
"retry_strategy",
".",
"add_circuit_breaker_callback",
"(",
"self",
".",
"circuit_breaker_callback",
")",
"return",
"retry_strategy",
".",
"make_retrying_call",
"(",
"self",
".",
"base_client",
".",
"call_api",
",",
"resource_path",
"=",
"resource_path",
",",
"method",
"=",
"method",
",",
"path_params",
"=",
"path_params",
",",
"header_params",
"=",
"header_params",
")",
"else",
":",
"return",
"self",
".",
"base_client",
".",
"call_api",
"(",
"resource_path",
"=",
"resource_path",
",",
"method",
"=",
"method",
",",
"path_params",
"=",
"path_params",
",",
"header_params",
"=",
"header_params",
")"
] |
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/integration/integration_instance_client.py#L1147-L1242
|
||
pencil1/ApiTestManage
|
851a54d5629456b7e967e15186244409ddf783cc
|
app/util/httprunner/runner.py
|
python
|
Runner.__clear_test_data
|
(self)
|
clear request and response data
|
clear request and response data
|
[
"clear",
"request",
"and",
"response",
"data"
] |
def __clear_test_data(self):
""" clear request and response data
"""
if not isinstance(self.http_client_session, HttpSession):
return
self.validation_results = []
self.http_client_session.init_meta_data()
|
[
"def",
"__clear_test_data",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"http_client_session",
",",
"HttpSession",
")",
":",
"return",
"self",
".",
"validation_results",
"=",
"[",
"]",
"self",
".",
"http_client_session",
".",
"init_meta_data",
"(",
")"
] |
https://github.com/pencil1/ApiTestManage/blob/851a54d5629456b7e967e15186244409ddf783cc/app/util/httprunner/runner.py#L71-L78
|
||
emesene/emesene
|
4548a4098310e21b16437bb36223a7f632a4f7bc
|
emesene/e3/xmpp/pyfb/pyfb/pyfb.py
|
python
|
Pyfb.get_user_by_id
|
(self, id=None, params=None)
|
return self._client.get_one(id, "FBUser", params=params)
|
Gets an user by the id
|
Gets an user by the id
|
[
"Gets",
"an",
"user",
"by",
"the",
"id"
] |
def get_user_by_id(self, id=None, params=None):
"""
Gets an user by the id
"""
if id is None:
id = "me"
return self._client.get_one(id, "FBUser", params=params)
|
[
"def",
"get_user_by_id",
"(",
"self",
",",
"id",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"id",
"is",
"None",
":",
"id",
"=",
"\"me\"",
"return",
"self",
".",
"_client",
".",
"get_one",
"(",
"id",
",",
"\"FBUser\"",
",",
"params",
"=",
"params",
")"
] |
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/xmpp/pyfb/pyfb/pyfb.py#L89-L95
|
|
Xilinx/brevitas
|
32cc847fc7cd6ca4c0201fd6b7d185c1103ae088
|
src/brevitas/function/ops_ste.py
|
python
|
binary_sign_ste
|
(x: Tensor)
|
return fn_prefix.binary_sign_ste_impl(x)
|
Function that implements :func:`~brevitas.function.ops.binary_sign` with a straight-through
gradient estimator.
Notes:
Wrapper for either :func:`~brevitas.function.autograd_ste_ops.binary_sign_ste_impl` (with
env ``BREVITAS_JIT=0``) or its native just-in-time compiled variant (with
``BREVITAS_JIT=1``).
Examples:
>>> x = torch.tensor([1.7, 0.0, -0.5], requires_grad=True)
>>> y = binary_sign_ste(x)
>>> y
tensor([ 1., 1., -1.], grad_fn=<BinarySignSteFnBackward>)
>>> grad = torch.tensor([0.1, 0.2, -0.1])
>>> y.backward(grad)
>>> (x.grad == grad).all().item()
True
|
Function that implements :func:`~brevitas.function.ops.binary_sign` with a straight-through
gradient estimator.
|
[
"Function",
"that",
"implements",
":",
"func",
":",
"~brevitas",
".",
"function",
".",
"ops",
".",
"binary_sign",
"with",
"a",
"straight",
"-",
"through",
"gradient",
"estimator",
"."
] |
def binary_sign_ste(x: Tensor) -> Tensor:
"""
Function that implements :func:`~brevitas.function.ops.binary_sign` with a straight-through
gradient estimator.
Notes:
Wrapper for either :func:`~brevitas.function.autograd_ste_ops.binary_sign_ste_impl` (with
env ``BREVITAS_JIT=0``) or its native just-in-time compiled variant (with
``BREVITAS_JIT=1``).
Examples:
>>> x = torch.tensor([1.7, 0.0, -0.5], requires_grad=True)
>>> y = binary_sign_ste(x)
>>> y
tensor([ 1., 1., -1.], grad_fn=<BinarySignSteFnBackward>)
>>> grad = torch.tensor([0.1, 0.2, -0.1])
>>> y.backward(grad)
>>> (x.grad == grad).all().item()
True
"""
return fn_prefix.binary_sign_ste_impl(x)
|
[
"def",
"binary_sign_ste",
"(",
"x",
":",
"Tensor",
")",
"->",
"Tensor",
":",
"return",
"fn_prefix",
".",
"binary_sign_ste_impl",
"(",
"x",
")"
] |
https://github.com/Xilinx/brevitas/blob/32cc847fc7cd6ca4c0201fd6b7d185c1103ae088/src/brevitas/function/ops_ste.py#L265-L285
|
|
KalleHallden/AutoTimer
|
2d954216700c4930baa154e28dbddc34609af7ce
|
env/lib/python2.7/site-packages/objc/_properties.py
|
python
|
array_property.__init__
|
(self, name=None,
read_only=False, copy=True, dynamic=False,
ivar=None, depends_on=None)
|
[] |
def __init__(self, name=None,
read_only=False, copy=True, dynamic=False,
ivar=None, depends_on=None):
super(array_property, self).__init__(name,
read_only=read_only,
copy=copy, dynamic=dynamic,
ivar=ivar, depends_on=depends_on)
|
[
"def",
"__init__",
"(",
"self",
",",
"name",
"=",
"None",
",",
"read_only",
"=",
"False",
",",
"copy",
"=",
"True",
",",
"dynamic",
"=",
"False",
",",
"ivar",
"=",
"None",
",",
"depends_on",
"=",
"None",
")",
":",
"super",
"(",
"array_property",
",",
"self",
")",
".",
"__init__",
"(",
"name",
",",
"read_only",
"=",
"read_only",
",",
"copy",
"=",
"copy",
",",
"dynamic",
"=",
"dynamic",
",",
"ivar",
"=",
"ivar",
",",
"depends_on",
"=",
"depends_on",
")"
] |
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/objc/_properties.py#L620-L626
|
||||
SheffieldML/GPy
|
bb1bc5088671f9316bc92a46d356734e34c2d5c0
|
GPy/core/svgp.py
|
python
|
SVGP.set_data
|
(self, X, Y)
|
Set the data without calling parameters_changed to avoid wasted computation
If this is called by the stochastic_grad function this will immediately update the gradients
|
Set the data without calling parameters_changed to avoid wasted computation
If this is called by the stochastic_grad function this will immediately update the gradients
|
[
"Set",
"the",
"data",
"without",
"calling",
"parameters_changed",
"to",
"avoid",
"wasted",
"computation",
"If",
"this",
"is",
"called",
"by",
"the",
"stochastic_grad",
"function",
"this",
"will",
"immediately",
"update",
"the",
"gradients"
] |
def set_data(self, X, Y):
"""
Set the data without calling parameters_changed to avoid wasted computation
If this is called by the stochastic_grad function this will immediately update the gradients
"""
assert X.shape[1]==self.Z.shape[1]
self.X, self.Y = X, Y
|
[
"def",
"set_data",
"(",
"self",
",",
"X",
",",
"Y",
")",
":",
"assert",
"X",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"Z",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"X",
",",
"self",
".",
"Y",
"=",
"X",
",",
"Y"
] |
https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/core/svgp.py#L80-L86
|
||
LumaPictures/pymel
|
fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72
|
pymel/internal/parsers.py
|
python
|
XmlApiDocParser._parseEnum_func
|
(self, enumData)
|
return {'values': enumValues, 'docs': {}, 'name': enumName}
|
Parse an OPENMAYA_ENUM style enum declaration
|
Parse an OPENMAYA_ENUM style enum declaration
|
[
"Parse",
"an",
"OPENMAYA_ENUM",
"style",
"enum",
"declaration"
] |
def _parseEnum_func(self, enumData):
'''Parse an OPENMAYA_ENUM style enum declaration'''
enumName = None
# use OrderedDict so that the first-parsed name for a given int-enum-
# value will become the default. This seems as good a pick as any for
# the default, and it will make python2+3 behavior consistent
enumValues = OrderedDict()
self.currentMethodName = 'OPENMAYA_ENUM' # placeholder
self.xprint("ENUM", enumName)
for param in enumData.findall("./param"):
enumKey = param.find('type')
if enumKey is None:
raise ValueError("Unable to process OPENMAYA_ENUM - one of the"
" params had no type tag: {}".format(enumData))
enumKey = xmlText(enumKey)
if enumName is None:
# the first param is actually the enum name
enumName = enumKey
self.currentMethodName = enumName
continue
try:
enumVal = getattr(self.apiClass, enumKey)
except:
_logger.warning("%s.%s of enum %s does not exist" % (self.apiClassName, enumKey, self.currentMethodName))
continue
enumValues[enumKey] = enumVal
if enumName is None:
raise ValueError(
"Unable to process OPENMAYA_ENUM - no name found: {}".format(
enumData))
# it seems that OPENMAYA_ENUM style enums never have docs for
# enum values - as an example, see M3dView::TextPosition - in
# the 2019 docs, we can see a description of each enum value:
# http://help.autodesk.com/cloudhelp/2019/CHS/Maya-SDK-MERGED/cpp_ref/class_m3d_view.html#a8e0d441725a81d2bbdebbea09078260e
# ...but nothing similar can be found in 2020 docs:
# http://help.autodesk.com/view/MAYAUL/2020/ENU/?guid=Maya_SDK_MERGED_cpp_ref_class_m3d_view_html
return {'values': enumValues, 'docs': {}, 'name': enumName}
|
[
"def",
"_parseEnum_func",
"(",
"self",
",",
"enumData",
")",
":",
"enumName",
"=",
"None",
"# use OrderedDict so that the first-parsed name for a given int-enum-",
"# value will become the default. This seems as good a pick as any for",
"# the default, and it will make python2+3 behavior consistent",
"enumValues",
"=",
"OrderedDict",
"(",
")",
"self",
".",
"currentMethodName",
"=",
"'OPENMAYA_ENUM'",
"# placeholder",
"self",
".",
"xprint",
"(",
"\"ENUM\"",
",",
"enumName",
")",
"for",
"param",
"in",
"enumData",
".",
"findall",
"(",
"\"./param\"",
")",
":",
"enumKey",
"=",
"param",
".",
"find",
"(",
"'type'",
")",
"if",
"enumKey",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to process OPENMAYA_ENUM - one of the\"",
"\" params had no type tag: {}\"",
".",
"format",
"(",
"enumData",
")",
")",
"enumKey",
"=",
"xmlText",
"(",
"enumKey",
")",
"if",
"enumName",
"is",
"None",
":",
"# the first param is actually the enum name",
"enumName",
"=",
"enumKey",
"self",
".",
"currentMethodName",
"=",
"enumName",
"continue",
"try",
":",
"enumVal",
"=",
"getattr",
"(",
"self",
".",
"apiClass",
",",
"enumKey",
")",
"except",
":",
"_logger",
".",
"warning",
"(",
"\"%s.%s of enum %s does not exist\"",
"%",
"(",
"self",
".",
"apiClassName",
",",
"enumKey",
",",
"self",
".",
"currentMethodName",
")",
")",
"continue",
"enumValues",
"[",
"enumKey",
"]",
"=",
"enumVal",
"if",
"enumName",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to process OPENMAYA_ENUM - no name found: {}\"",
".",
"format",
"(",
"enumData",
")",
")",
"# it seems that OPENMAYA_ENUM style enums never have docs for",
"# enum values - as an example, see M3dView::TextPosition - in",
"# the 2019 docs, we can see a description of each enum value:",
"# http://help.autodesk.com/cloudhelp/2019/CHS/Maya-SDK-MERGED/cpp_ref/class_m3d_view.html#a8e0d441725a81d2bbdebbea09078260e",
"# ...but nothing similar can be found in 2020 docs:",
"# http://help.autodesk.com/view/MAYAUL/2020/ENU/?guid=Maya_SDK_MERGED_cpp_ref_class_m3d_view_html",
"return",
"{",
"'values'",
":",
"enumValues",
",",
"'docs'",
":",
"{",
"}",
",",
"'name'",
":",
"enumName",
"}"
] |
https://github.com/LumaPictures/pymel/blob/fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72/pymel/internal/parsers.py#L1521-L1563
|
|
triaquae/triaquae
|
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
|
TriAquae/models/django/contrib/gis/geos/geometry.py
|
python
|
GEOSGeometry.__deepcopy__
|
(self, memodict)
|
return self.clone()
|
The `deepcopy` routine is used by the `Node` class of django.utils.tree;
thus, the protocol routine needs to be implemented to return correct
copies (clones) of these GEOS objects, which use C pointers.
|
The `deepcopy` routine is used by the `Node` class of django.utils.tree;
thus, the protocol routine needs to be implemented to return correct
copies (clones) of these GEOS objects, which use C pointers.
|
[
"The",
"deepcopy",
"routine",
"is",
"used",
"by",
"the",
"Node",
"class",
"of",
"django",
".",
"utils",
".",
"tree",
";",
"thus",
"the",
"protocol",
"routine",
"needs",
"to",
"be",
"implemented",
"to",
"return",
"correct",
"copies",
"(",
"clones",
")",
"of",
"these",
"GEOS",
"objects",
"which",
"use",
"C",
"pointers",
"."
] |
def __deepcopy__(self, memodict):
"""
The `deepcopy` routine is used by the `Node` class of django.utils.tree;
thus, the protocol routine needs to be implemented to return correct
copies (clones) of these GEOS objects, which use C pointers.
"""
return self.clone()
|
[
"def",
"__deepcopy__",
"(",
"self",
",",
"memodict",
")",
":",
"return",
"self",
".",
"clone",
"(",
")"
] |
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/gis/geos/geometry.py#L125-L131
|
|
dimagi/commcare-hq
|
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
|
corehq/apps/data_interfaces/views.py
|
python
|
AutomaticUpdateRuleListView.total
|
(self)
|
return self._rules().count()
|
[] |
def total(self):
return self._rules().count()
|
[
"def",
"total",
"(",
"self",
")",
":",
"return",
"self",
".",
"_rules",
"(",
")",
".",
"count",
"(",
")"
] |
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/data_interfaces/views.py#L675-L676
|
|||
peplin/pygatt
|
70c68684ca5a2c5cbd8c4f6f039503fe9b848d24
|
pygatt/backends/bgapi/packets.py
|
python
|
BGAPICommandPacketBuilder.attclient_read_by_group_type
|
(connection, start, end, uuid)
|
return pack('<4BBHHB%dB' % len(uuid), 0, 6 + len(uuid), 4, 1,
connection, start, end, len(uuid), *uuid)
|
[] |
def attclient_read_by_group_type(connection, start, end, uuid):
return pack('<4BBHHB%dB' % len(uuid), 0, 6 + len(uuid), 4, 1,
connection, start, end, len(uuid), *uuid)
|
[
"def",
"attclient_read_by_group_type",
"(",
"connection",
",",
"start",
",",
"end",
",",
"uuid",
")",
":",
"return",
"pack",
"(",
"'<4BBHHB%dB'",
"%",
"len",
"(",
"uuid",
")",
",",
"0",
",",
"6",
"+",
"len",
"(",
"uuid",
")",
",",
"4",
",",
"1",
",",
"connection",
",",
"start",
",",
"end",
",",
"len",
"(",
"uuid",
")",
",",
"*",
"uuid",
")"
] |
https://github.com/peplin/pygatt/blob/70c68684ca5a2c5cbd8c4f6f039503fe9b848d24/pygatt/backends/bgapi/packets.py#L183-L185
|
|||
inspurer/WorkAttendanceSystem
|
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
|
V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py
|
python
|
_dnsname_match
|
(dn, hostname, max_wildcards=1)
|
return pat.match(hostname)
|
Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
|
Matching according to RFC 6125, section 6.4.3
|
[
"Matching",
"according",
"to",
"RFC",
"6125",
"section",
"6",
".",
"4",
".",
"3"
] |
def _dnsname_match(dn, hostname, max_wildcards=1):
"""Matching according to RFC 6125, section 6.4.3
http://tools.ietf.org/html/rfc6125#section-6.4.3
"""
pats = []
if not dn:
return False
# Ported from python3-syntax:
# leftmost, *remainder = dn.split(r'.')
parts = dn.split(r'.')
leftmost = parts[0]
remainder = parts[1:]
wildcards = leftmost.count('*')
if wildcards > max_wildcards:
# Issue #17980: avoid denials of service by refusing more
# than one wildcard per fragment. A survey of established
# policy among SSL implementations showed it to be a
# reasonable choice.
raise CertificateError(
"too many wildcards in certificate DNS name: " + repr(dn))
# speed up common case w/o wildcards
if not wildcards:
return dn.lower() == hostname.lower()
# RFC 6125, section 6.4.3, subitem 1.
# The client SHOULD NOT attempt to match a presented identifier in which
# the wildcard character comprises a label other than the left-most label.
if leftmost == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.
pats.append('[^.]+')
elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
else:
# Otherwise, '*' matches any dotless string, e.g. www*
pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
return pat.match(hostname)
|
[
"def",
"_dnsname_match",
"(",
"dn",
",",
"hostname",
",",
"max_wildcards",
"=",
"1",
")",
":",
"pats",
"=",
"[",
"]",
"if",
"not",
"dn",
":",
"return",
"False",
"# Ported from python3-syntax:",
"# leftmost, *remainder = dn.split(r'.')",
"parts",
"=",
"dn",
".",
"split",
"(",
"r'.'",
")",
"leftmost",
"=",
"parts",
"[",
"0",
"]",
"remainder",
"=",
"parts",
"[",
"1",
":",
"]",
"wildcards",
"=",
"leftmost",
".",
"count",
"(",
"'*'",
")",
"if",
"wildcards",
">",
"max_wildcards",
":",
"# Issue #17980: avoid denials of service by refusing more",
"# than one wildcard per fragment. A survey of established",
"# policy among SSL implementations showed it to be a",
"# reasonable choice.",
"raise",
"CertificateError",
"(",
"\"too many wildcards in certificate DNS name: \"",
"+",
"repr",
"(",
"dn",
")",
")",
"# speed up common case w/o wildcards",
"if",
"not",
"wildcards",
":",
"return",
"dn",
".",
"lower",
"(",
")",
"==",
"hostname",
".",
"lower",
"(",
")",
"# RFC 6125, section 6.4.3, subitem 1.",
"# The client SHOULD NOT attempt to match a presented identifier in which",
"# the wildcard character comprises a label other than the left-most label.",
"if",
"leftmost",
"==",
"'*'",
":",
"# When '*' is a fragment by itself, it matches a non-empty dotless",
"# fragment.",
"pats",
".",
"append",
"(",
"'[^.]+'",
")",
"elif",
"leftmost",
".",
"startswith",
"(",
"'xn--'",
")",
"or",
"hostname",
".",
"startswith",
"(",
"'xn--'",
")",
":",
"# RFC 6125, section 6.4.3, subitem 3.",
"# The client SHOULD NOT attempt to match a presented identifier",
"# where the wildcard character is embedded within an A-label or",
"# U-label of an internationalized domain name.",
"pats",
".",
"append",
"(",
"re",
".",
"escape",
"(",
"leftmost",
")",
")",
"else",
":",
"# Otherwise, '*' matches any dotless string, e.g. www*",
"pats",
".",
"append",
"(",
"re",
".",
"escape",
"(",
"leftmost",
")",
".",
"replace",
"(",
"r'\\*'",
",",
"'[^.]*'",
")",
")",
"# add the remaining fragments, ignore any wildcards",
"for",
"frag",
"in",
"remainder",
":",
"pats",
".",
"append",
"(",
"re",
".",
"escape",
"(",
"frag",
")",
")",
"pat",
"=",
"re",
".",
"compile",
"(",
"r'\\A'",
"+",
"r'\\.'",
".",
"join",
"(",
"pats",
")",
"+",
"r'\\Z'",
",",
"re",
".",
"IGNORECASE",
")",
"return",
"pat",
".",
"match",
"(",
"hostname",
")"
] |
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V1.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py#L14-L64
|
|
drckf/paysage
|
85ef951be2750e13c0b42121b40e530689bdc1f4
|
paysage/batch/shuffle.py
|
python
|
DataShuffler.shuffle_table
|
(self, key)
|
Shuffle a table in the HDFStore, write to a new file.
Args:
key (str): the key of the table to shuffle.
Returns:
None
|
Shuffle a table in the HDFStore, write to a new file.
|
[
"Shuffle",
"a",
"table",
"in",
"the",
"HDFStore",
"write",
"to",
"a",
"new",
"file",
"."
] |
def shuffle_table(self, key):
"""
Shuffle a table in the HDFStore, write to a new file.
Args:
key (str): the key of the table to shuffle.
Returns:
None
"""
# split up the table into chunks
num_chunks, chunk_keys, chunk_counts = self.divide_table_into_chunks(key)
# if there is one chunk, move it and finish
if num_chunks == 1:
self.shuffled_store.put(key, self.chunk_store[chunk_keys[0]],
format='table')
return
self.reassemble_table(key, num_chunks, chunk_keys, chunk_counts)
|
[
"def",
"shuffle_table",
"(",
"self",
",",
"key",
")",
":",
"# split up the table into chunks",
"num_chunks",
",",
"chunk_keys",
",",
"chunk_counts",
"=",
"self",
".",
"divide_table_into_chunks",
"(",
"key",
")",
"# if there is one chunk, move it and finish",
"if",
"num_chunks",
"==",
"1",
":",
"self",
".",
"shuffled_store",
".",
"put",
"(",
"key",
",",
"self",
".",
"chunk_store",
"[",
"chunk_keys",
"[",
"0",
"]",
"]",
",",
"format",
"=",
"'table'",
")",
"return",
"self",
".",
"reassemble_table",
"(",
"key",
",",
"num_chunks",
",",
"chunk_keys",
",",
"chunk_counts",
")"
] |
https://github.com/drckf/paysage/blob/85ef951be2750e13c0b42121b40e530689bdc1f4/paysage/batch/shuffle.py#L120-L140
|
||
jookies/jasmin
|
16c54261a6a1a82db64311ee2a235f6c966c14ab
|
jasmin/routing/jasminApi.py
|
python
|
User.disable
|
(self)
|
Related to #306: disable/enable user
|
Related to #306: disable/enable user
|
[
"Related",
"to",
"#306",
":",
"disable",
"/",
"enable",
"user"
] |
def disable(self):
"""Related to #306: disable/enable user"""
self.enabled = False
|
[
"def",
"disable",
"(",
"self",
")",
":",
"self",
".",
"enabled",
"=",
"False"
] |
https://github.com/jookies/jasmin/blob/16c54261a6a1a82db64311ee2a235f6c966c14ab/jasmin/routing/jasminApi.py#L301-L303
|
||
kuri65536/python-for-android
|
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
|
python-build/python-libs/gdata/src/gdata/youtube/service.py
|
python
|
YouTubeService.DeletePlaylist
|
(self, playlist_uri)
|
return self.Delete(playlist_uri)
|
Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
|
Delete a playlist from the currently authenticated users playlists.
|
[
"Delete",
"a",
"playlist",
"from",
"the",
"currently",
"authenticated",
"users",
"playlists",
"."
] |
def DeletePlaylist(self, playlist_uri):
"""Delete a playlist from the currently authenticated users playlists.
Needs authentication.
Args:
playlist_uri: A string representing the URI of the playlist that is
to be deleted.
Returns:
True if successfully deleted.
"""
return self.Delete(playlist_uri)
|
[
"def",
"DeletePlaylist",
"(",
"self",
",",
"playlist_uri",
")",
":",
"return",
"self",
".",
"Delete",
"(",
"playlist_uri",
")"
] |
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-build/python-libs/gdata/src/gdata/youtube/service.py#L968-L980
|
|
machinalis/iepy
|
d7353e18d647d1657010d15fad09a4ea8d570089
|
iepy/preprocess/stanford_preprocess.py
|
python
|
StanfordAnalysis.get_entity_occurrences
|
(self)
|
return found_entities
|
Returns a list of tuples (i, j, kind) such that `i` is the start
offset of an entity occurrence, `j` is the end offset and `kind` is the
entity kind of the entity.
|
Returns a list of tuples (i, j, kind) such that `i` is the start
offset of an entity occurrence, `j` is the end offset and `kind` is the
entity kind of the entity.
|
[
"Returns",
"a",
"list",
"of",
"tuples",
"(",
"i",
"j",
"kind",
")",
"such",
"that",
"i",
"is",
"the",
"start",
"offset",
"of",
"an",
"entity",
"occurrence",
"j",
"is",
"the",
"end",
"offset",
"and",
"kind",
"is",
"the",
"entity",
"kind",
"of",
"the",
"entity",
"."
] |
def get_entity_occurrences(self):
"""
Returns a list of tuples (i, j, kind) such that `i` is the start
offset of an entity occurrence, `j` is the end offset and `kind` is the
entity kind of the entity.
"""
found_entities = []
offset = 0
for words in self.sentences:
for kind, group in groupby(enumerate(words), key=lambda x: x[1]["NER"]):
if kind == "O":
continue
ix = [i for i, word in group]
i = ix[0] + offset
j = ix[-1] + 1 + offset
found_entities.append((i, j, kind))
offset += len(words)
return found_entities
|
[
"def",
"get_entity_occurrences",
"(",
"self",
")",
":",
"found_entities",
"=",
"[",
"]",
"offset",
"=",
"0",
"for",
"words",
"in",
"self",
".",
"sentences",
":",
"for",
"kind",
",",
"group",
"in",
"groupby",
"(",
"enumerate",
"(",
"words",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
"[",
"\"NER\"",
"]",
")",
":",
"if",
"kind",
"==",
"\"O\"",
":",
"continue",
"ix",
"=",
"[",
"i",
"for",
"i",
",",
"word",
"in",
"group",
"]",
"i",
"=",
"ix",
"[",
"0",
"]",
"+",
"offset",
"j",
"=",
"ix",
"[",
"-",
"1",
"]",
"+",
"1",
"+",
"offset",
"found_entities",
".",
"append",
"(",
"(",
"i",
",",
"j",
",",
"kind",
")",
")",
"offset",
"+=",
"len",
"(",
"words",
")",
"return",
"found_entities"
] |
https://github.com/machinalis/iepy/blob/d7353e18d647d1657010d15fad09a4ea8d570089/iepy/preprocess/stanford_preprocess.py#L317-L334
|
|
inkandswitch/livebook
|
93c8d467734787366ad084fc3566bf5cbe249c51
|
public/pypyjs/modules/numpy/random/mtrand.py
|
python
|
RandomState.binomial
|
(self, n, p, size=None)
|
return discnp_array(self.internal_state, _mtrand.rk_binomial, size, on, op)
|
binomial(n, p, size=None)
Draw samples from a binomial distribution.
Samples are drawn from a Binomial distribution with specified
parameters, n trials and p probability of success where
n an integer >= 0 and p is in the interval [0,1]. (n may be
input as a float, but it is truncated to an integer in use)
Parameters
----------
n : float (but truncated to an integer)
parameter, >= 0.
p : float
parameter, >= 0 and <=1.
size : {tuple, int}
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn.
Returns
-------
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also
--------
scipy.stats.distributions.binom : probability density function,
distribution or cumulative density function, etc.
Notes
-----
The probability density for the Binomial distribution is
.. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N},
where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.
When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
Wolfram Web Resource.
http://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial-distribution",
http://en.wikipedia.org/wiki/Binomial_distribution
Examples
--------
Draw samples from the distribution:
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
|
binomial(n, p, size=None)
|
[
"binomial",
"(",
"n",
"p",
"size",
"=",
"None",
")"
] |
def binomial(self, n, p, size=None):
"""
binomial(n, p, size=None)
Draw samples from a binomial distribution.
Samples are drawn from a Binomial distribution with specified
parameters, n trials and p probability of success where
n an integer >= 0 and p is in the interval [0,1]. (n may be
input as a float, but it is truncated to an integer in use)
Parameters
----------
n : float (but truncated to an integer)
parameter, >= 0.
p : float
parameter, >= 0 and <=1.
size : {tuple, int}
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn.
Returns
-------
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also
--------
scipy.stats.distributions.binom : probability density function,
distribution or cumulative density function, etc.
Notes
-----
The probability density for the Binomial distribution is
.. math:: P(N) = \\binom{n}{N}p^N(1-p)^{n-N},
where :math:`n` is the number of trials, :math:`p` is the probability
of success, and :math:`N` is the number of successes.
When estimating the standard error of a proportion in a population by
using a random sample, the normal distribution works well unless the
product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used
instead. For example, a sample of 15 people shows 4 who are left
handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4,
so the binomial distribution should be used in this case.
References
----------
.. [1] Dalgaard, Peter, "Introductory Statistics with R",
Springer-Verlag, 2002.
.. [2] Glantz, Stanton A. "Primer of Biostatistics.", McGraw-Hill,
Fifth Edition, 2002.
.. [3] Lentner, Marvin, "Elementary Applied Statistics", Bogden
and Quigley, 1972.
.. [4] Weisstein, Eric W. "Binomial Distribution." From MathWorld--A
Wolfram Web Resource.
http://mathworld.wolfram.com/BinomialDistribution.html
.. [5] Wikipedia, "Binomial-distribution",
http://en.wikipedia.org/wiki/Binomial_distribution
Examples
--------
Draw samples from the distribution:
>>> n, p = 10, .5 # number of trials, probability of each trial
>>> s = np.random.binomial(n, p, 1000)
# result of flipping a coin 10 times, tested 1000 times.
A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
"""
try:
fp = float(p)
ln = long(n)
except:
pass
else:
if ln < 0:
raise ValueError("n < 0")
if fp < 0:
raise ValueError("p < 0")
elif fp > 1:
raise ValueError("p > 1")
elif np.isnan(fp):
raise ValueError("p is nan")
return discnp_array_sc(self.internal_state, _mtrand.rk_binomial, size, ln, fp)
on = np.array(n, np.long) # aligned?
op = np.array(p, np.float64) # aligned?
if np.any(np.less(n, 0)):
raise ValueError("n < 0")
if np.any(np.less(p, 0)):
raise ValueError("p < 0")
if np.any(np.greater(p, 1)):
raise ValueError("p > 1")
return discnp_array(self.internal_state, _mtrand.rk_binomial, size, on, op)
|
[
"def",
"binomial",
"(",
"self",
",",
"n",
",",
"p",
",",
"size",
"=",
"None",
")",
":",
"try",
":",
"fp",
"=",
"float",
"(",
"p",
")",
"ln",
"=",
"long",
"(",
"n",
")",
"except",
":",
"pass",
"else",
":",
"if",
"ln",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"n < 0\"",
")",
"if",
"fp",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"p < 0\"",
")",
"elif",
"fp",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"p > 1\"",
")",
"elif",
"np",
".",
"isnan",
"(",
"fp",
")",
":",
"raise",
"ValueError",
"(",
"\"p is nan\"",
")",
"return",
"discnp_array_sc",
"(",
"self",
".",
"internal_state",
",",
"_mtrand",
".",
"rk_binomial",
",",
"size",
",",
"ln",
",",
"fp",
")",
"on",
"=",
"np",
".",
"array",
"(",
"n",
",",
"np",
".",
"long",
")",
"# aligned?",
"op",
"=",
"np",
".",
"array",
"(",
"p",
",",
"np",
".",
"float64",
")",
"# aligned?",
"if",
"np",
".",
"any",
"(",
"np",
".",
"less",
"(",
"n",
",",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"n < 0\"",
")",
"if",
"np",
".",
"any",
"(",
"np",
".",
"less",
"(",
"p",
",",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"p < 0\"",
")",
"if",
"np",
".",
"any",
"(",
"np",
".",
"greater",
"(",
"p",
",",
"1",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"p > 1\"",
")",
"return",
"discnp_array",
"(",
"self",
".",
"internal_state",
",",
"_mtrand",
".",
"rk_binomial",
",",
"size",
",",
"on",
",",
"op",
")"
] |
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/random/mtrand.py#L2939-L3044
|
|
nortikin/sverchok
|
7b460f01317c15f2681bfa3e337c5e7346f3711b
|
utils/pulga_physics_modular_core.py
|
python
|
calc_rest_length
|
(np_verts, np_springs)
|
return dist_rest
|
calculate edges length
|
calculate edges length
|
[
"calculate",
"edges",
"length"
] |
def calc_rest_length(np_verts, np_springs):
'''calculate edges length'''
pairs_springs = np_verts[np_springs, :]
vect_rest = (pairs_springs[:, 0, :] - pairs_springs[:, 1, :])
dist_rest = np.linalg.norm(vect_rest, axis=1)
return dist_rest
|
[
"def",
"calc_rest_length",
"(",
"np_verts",
",",
"np_springs",
")",
":",
"pairs_springs",
"=",
"np_verts",
"[",
"np_springs",
",",
":",
"]",
"vect_rest",
"=",
"(",
"pairs_springs",
"[",
":",
",",
"0",
",",
":",
"]",
"-",
"pairs_springs",
"[",
":",
",",
"1",
",",
":",
"]",
")",
"dist_rest",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"vect_rest",
",",
"axis",
"=",
"1",
")",
"return",
"dist_rest"
] |
https://github.com/nortikin/sverchok/blob/7b460f01317c15f2681bfa3e337c5e7346f3711b/utils/pulga_physics_modular_core.py#L91-L96
|
|
shidenggui/easyquotation
|
01d7f8795a460b284ff1af8221903156d23b335f
|
easyquotation/jsl.py
|
python
|
Jsl.etfindex
|
(
self, index_id="", min_volume=0, max_discount=None, min_discount=None
)
|
return self.__etfindex
|
以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:return: {"fund_id":{}}
|
以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:return: {"fund_id":{}}
|
[
"以字典形式返回",
"指数ETF",
"数据",
":",
"param",
"index_id",
":",
"获取指定的指数",
":",
"param",
"min_volume",
":",
"最小成交量",
":",
"param",
"min_discount",
":",
"最低溢价率",
"适用于溢价套利",
"格式",
"-",
"1",
".",
"2%",
"-",
"1",
".",
"2",
"-",
"0",
".",
"012",
"三种均可",
":",
"param",
"max_discount",
":",
"最高溢价率",
"适用于折价套利",
"格式",
"-",
"1",
".",
"2%",
"-",
"1",
".",
"2",
"-",
"0",
".",
"012",
"三种均可",
":",
"return",
":",
"{",
"fund_id",
":",
"{}",
"}"
] |
def etfindex(
self, index_id="", min_volume=0, max_discount=None, min_discount=None
):
"""
以字典形式返回 指数ETF 数据
:param index_id: 获取指定的指数
:param min_volume: 最小成交量
:param min_discount: 最低溢价率, 适用于溢价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:param max_discount: 最高溢价率, 适用于折价套利, 格式 "-1.2%", "-1.2", -0.012 三种均可
:return: {"fund_id":{}}
"""
# 添加当前的ctime
etf_index_url = self.__etf_index_url.format(ctime=int(time.time()))
# 请求数据
etf_json = requests.get(etf_index_url).json()
# 格式化返回的json字符串
data = self.formatetfindexjson(etf_json)
# 过滤
if index_id:
# 指定跟踪的指数代码
data = {
fund_id: cell
for fund_id, cell in data.items()
if cell["index_id"] == index_id
}
if min_volume:
# 过滤小于指定交易量的数据
data = {
fund_id: cell
for fund_id, cell in data.items()
if float(cell["volume"]) >= min_volume
}
if min_discount is not None:
# 指定最小溢价率
if isinstance(min_discount, str):
if min_discount.endswith("%"):
# 如果是字符串形式,先转为浮点形式
min_discount = self.percentage2float(min_discount)
else:
min_discount = float(min_discount) / 100.
data = {
fund_id: cell
for fund_id, cell in data.items()
if self.percentage2float(cell["discount_rt"]) >= min_discount
}
if max_discount is not None:
# 指定最大溢价率
if isinstance(max_discount, str):
if max_discount.endswith("%"):
# 如果是字符串形式,先转为浮点形式
max_discount = self.percentage2float(max_discount)
else:
max_discount = float(max_discount) / 100.
data = {
fund_id: cell
for fund_id, cell in data.items()
if self.percentage2float(cell["discount_rt"]) <= max_discount
}
self.__etfindex = data
return self.__etfindex
|
[
"def",
"etfindex",
"(",
"self",
",",
"index_id",
"=",
"\"\"",
",",
"min_volume",
"=",
"0",
",",
"max_discount",
"=",
"None",
",",
"min_discount",
"=",
"None",
")",
":",
"# 添加当前的ctime",
"etf_index_url",
"=",
"self",
".",
"__etf_index_url",
".",
"format",
"(",
"ctime",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"# 请求数据",
"etf_json",
"=",
"requests",
".",
"get",
"(",
"etf_index_url",
")",
".",
"json",
"(",
")",
"# 格式化返回的json字符串",
"data",
"=",
"self",
".",
"formatetfindexjson",
"(",
"etf_json",
")",
"# 过滤",
"if",
"index_id",
":",
"# 指定跟踪的指数代码",
"data",
"=",
"{",
"fund_id",
":",
"cell",
"for",
"fund_id",
",",
"cell",
"in",
"data",
".",
"items",
"(",
")",
"if",
"cell",
"[",
"\"index_id\"",
"]",
"==",
"index_id",
"}",
"if",
"min_volume",
":",
"# 过滤小于指定交易量的数据",
"data",
"=",
"{",
"fund_id",
":",
"cell",
"for",
"fund_id",
",",
"cell",
"in",
"data",
".",
"items",
"(",
")",
"if",
"float",
"(",
"cell",
"[",
"\"volume\"",
"]",
")",
">=",
"min_volume",
"}",
"if",
"min_discount",
"is",
"not",
"None",
":",
"# 指定最小溢价率",
"if",
"isinstance",
"(",
"min_discount",
",",
"str",
")",
":",
"if",
"min_discount",
".",
"endswith",
"(",
"\"%\"",
")",
":",
"# 如果是字符串形式,先转为浮点形式",
"min_discount",
"=",
"self",
".",
"percentage2float",
"(",
"min_discount",
")",
"else",
":",
"min_discount",
"=",
"float",
"(",
"min_discount",
")",
"/",
"100.",
"data",
"=",
"{",
"fund_id",
":",
"cell",
"for",
"fund_id",
",",
"cell",
"in",
"data",
".",
"items",
"(",
")",
"if",
"self",
".",
"percentage2float",
"(",
"cell",
"[",
"\"discount_rt\"",
"]",
")",
">=",
"min_discount",
"}",
"if",
"max_discount",
"is",
"not",
"None",
":",
"# 指定最大溢价率",
"if",
"isinstance",
"(",
"max_discount",
",",
"str",
")",
":",
"if",
"max_discount",
".",
"endswith",
"(",
"\"%\"",
")",
":",
"# 如果是字符串形式,先转为浮点形式",
"max_discount",
"=",
"self",
".",
"percentage2float",
"(",
"max_discount",
")",
"else",
":",
"max_discount",
"=",
"float",
"(",
"max_discount",
")",
"/",
"100.",
"data",
"=",
"{",
"fund_id",
":",
"cell",
"for",
"fund_id",
",",
"cell",
"in",
"data",
".",
"items",
"(",
")",
"if",
"self",
".",
"percentage2float",
"(",
"cell",
"[",
"\"discount_rt\"",
"]",
")",
"<=",
"max_discount",
"}",
"self",
".",
"__etfindex",
"=",
"data",
"return",
"self",
".",
"__etfindex"
] |
https://github.com/shidenggui/easyquotation/blob/01d7f8795a460b284ff1af8221903156d23b335f/easyquotation/jsl.py#L327-L389
|
|
omz/PythonistaAppTemplate
|
f560f93f8876d82a21d108977f90583df08d55af
|
PythonistaAppTemplate/PythonistaKit.framework/pylib/fractions.py
|
python
|
Fraction._richcmp
|
(self, other, op)
|
Helper for comparison operators, for internal use only.
Implement comparison between a Rational instance `self`, and
either another Rational instance or a float `other`. If
`other` is not a Rational instance or a float, return
NotImplemented. `op` should be one of the six standard
comparison operators.
|
Helper for comparison operators, for internal use only.
|
[
"Helper",
"for",
"comparison",
"operators",
"for",
"internal",
"use",
"only",
"."
] |
def _richcmp(self, other, op):
"""Helper for comparison operators, for internal use only.
Implement comparison between a Rational instance `self`, and
either another Rational instance or a float `other`. If
`other` is not a Rational instance or a float, return
NotImplemented. `op` should be one of the six standard
comparison operators.
"""
# convert other to a Rational instance where reasonable.
if isinstance(other, Rational):
return op(self._numerator * other.denominator,
self._denominator * other.numerator)
# comparisons with complex should raise a TypeError, for consistency
# with int<->complex, float<->complex, and complex<->complex comparisons.
if isinstance(other, complex):
raise TypeError("no ordering relation is defined for complex numbers")
if isinstance(other, float):
if math.isnan(other) or math.isinf(other):
return op(0.0, other)
else:
return op(self, self.from_float(other))
else:
return NotImplemented
|
[
"def",
"_richcmp",
"(",
"self",
",",
"other",
",",
"op",
")",
":",
"# convert other to a Rational instance where reasonable.",
"if",
"isinstance",
"(",
"other",
",",
"Rational",
")",
":",
"return",
"op",
"(",
"self",
".",
"_numerator",
"*",
"other",
".",
"denominator",
",",
"self",
".",
"_denominator",
"*",
"other",
".",
"numerator",
")",
"# comparisons with complex should raise a TypeError, for consistency",
"# with int<->complex, float<->complex, and complex<->complex comparisons.",
"if",
"isinstance",
"(",
"other",
",",
"complex",
")",
":",
"raise",
"TypeError",
"(",
"\"no ordering relation is defined for complex numbers\"",
")",
"if",
"isinstance",
"(",
"other",
",",
"float",
")",
":",
"if",
"math",
".",
"isnan",
"(",
"other",
")",
"or",
"math",
".",
"isinf",
"(",
"other",
")",
":",
"return",
"op",
"(",
"0.0",
",",
"other",
")",
"else",
":",
"return",
"op",
"(",
"self",
",",
"self",
".",
"from_float",
"(",
"other",
")",
")",
"else",
":",
"return",
"NotImplemented"
] |
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/fractions.py#L546-L570
|
||
ACloudGuru/AdvancedCloudFormation
|
6831cfbff1888951c9b2ede6cb87eeb71cfd8bf5
|
206-LambdaCustomEnhancements/autosubnet/requests/packages/urllib3/filepost.py
|
python
|
encode_multipart_formdata
|
(fields, boundary=None)
|
return body.getvalue(), content_type
|
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`.
|
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
|
[
"Encode",
"a",
"dictionary",
"of",
"fields",
"using",
"the",
"multipart",
"/",
"form",
"-",
"data",
"MIME",
"format",
"."
] |
def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`mimetools.choose_boundary`.
"""
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for field in iter_field_objects(fields):
body.write(b('--%s\r\n' % (boundary)))
writer(body).write(field.render_headers())
data = field.data
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b'\r\n')
body.write(b('--%s--\r\n' % (boundary)))
content_type = str('multipart/form-data; boundary=%s' % boundary)
return body.getvalue(), content_type
|
[
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
"fields",
")",
":",
"body",
".",
"write",
"(",
"b",
"(",
"'--%s\\r\\n'",
"%",
"(",
"boundary",
")",
")",
")",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"field",
".",
"render_headers",
"(",
")",
")",
"data",
"=",
"field",
".",
"data",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# Backwards compatibility",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"data",
")",
"else",
":",
"body",
".",
"write",
"(",
"data",
")",
"body",
".",
"write",
"(",
"b'\\r\\n'",
")",
"body",
".",
"write",
"(",
"b",
"(",
"'--%s--\\r\\n'",
"%",
"(",
"boundary",
")",
")",
")",
"content_type",
"=",
"str",
"(",
"'multipart/form-data; boundary=%s'",
"%",
"boundary",
")",
"return",
"body",
".",
"getvalue",
"(",
")",
",",
"content_type"
] |
https://github.com/ACloudGuru/AdvancedCloudFormation/blob/6831cfbff1888951c9b2ede6cb87eeb71cfd8bf5/206-LambdaCustomEnhancements/autosubnet/requests/packages/urllib3/filepost.py#L59-L94
|
|
cgrok/selfbot.py
|
72311ca0de1130c8c57febe1a9a8dd92614165c4
|
cogs/misc.py
|
python
|
Misc.validate_emojis
|
(self, ctx, reactions)
|
Checks if an emoji is valid otherwise,
tries to convert it into a custom emoji
|
Checks if an emoji is valid otherwise,
tries to convert it into a custom emoji
|
[
"Checks",
"if",
"an",
"emoji",
"is",
"valid",
"otherwise",
"tries",
"to",
"convert",
"it",
"into",
"a",
"custom",
"emoji"
] |
async def validate_emojis(self, ctx, reactions):
'''
Checks if an emoji is valid otherwise,
tries to convert it into a custom emoji
'''
for emote in reactions.split():
if emote in emoji.UNICODE_EMOJI:
yield emote
else:
try:
yield await self.emoji_converter.convert(ctx, emote)
except commands.BadArgument:
pass
|
[
"async",
"def",
"validate_emojis",
"(",
"self",
",",
"ctx",
",",
"reactions",
")",
":",
"for",
"emote",
"in",
"reactions",
".",
"split",
"(",
")",
":",
"if",
"emote",
"in",
"emoji",
".",
"UNICODE_EMOJI",
":",
"yield",
"emote",
"else",
":",
"try",
":",
"yield",
"await",
"self",
".",
"emoji_converter",
".",
"convert",
"(",
"ctx",
",",
"emote",
")",
"except",
"commands",
".",
"BadArgument",
":",
"pass"
] |
https://github.com/cgrok/selfbot.py/blob/72311ca0de1130c8c57febe1a9a8dd92614165c4/cogs/misc.py#L325-L337
|
||
realpython/book2-exercises
|
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
|
py2manager/gluon/rewrite.py
|
python
|
MapUrlIn.arg0
|
(self)
|
return self.args(0)
|
Returns first arg
|
Returns first arg
|
[
"Returns",
"first",
"arg"
] |
def arg0(self):
"""Returns first arg"""
return self.args(0)
|
[
"def",
"arg0",
"(",
"self",
")",
":",
"return",
"self",
".",
"args",
"(",
"0",
")"
] |
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/rewrite.py#L1109-L1111
|
|
makerbot/ReplicatorG
|
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
|
skein_engines/skeinforge-47/fabmetheus_utilities/xml_simple_reader.py
|
python
|
getElementsByLocalName
|
(childNodes, localName)
|
return elementsByLocalName
|
Get the descendents which have the given local name.
|
Get the descendents which have the given local name.
|
[
"Get",
"the",
"descendents",
"which",
"have",
"the",
"given",
"local",
"name",
"."
] |
def getElementsByLocalName(childNodes, localName):
'Get the descendents which have the given local name.'
elementsByLocalName = getChildElementsByLocalName(childNodes, localName)
for childNode in childNodes:
if childNode.getNodeType() == 1:
elementsByLocalName += childNode.getElementsByLocalName(localName)
return elementsByLocalName
|
[
"def",
"getElementsByLocalName",
"(",
"childNodes",
",",
"localName",
")",
":",
"elementsByLocalName",
"=",
"getChildElementsByLocalName",
"(",
"childNodes",
",",
"localName",
")",
"for",
"childNode",
"in",
"childNodes",
":",
"if",
"childNode",
".",
"getNodeType",
"(",
")",
"==",
"1",
":",
"elementsByLocalName",
"+=",
"childNode",
".",
"getElementsByLocalName",
"(",
"localName",
")",
"return",
"elementsByLocalName"
] |
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/xml_simple_reader.py#L77-L83
|
|
ottogroup/palladium
|
3e7bd7d8f38b8ad1a175d0cd387fe5959acbfe2e
|
palladium/dataset.py
|
python
|
ScheduledDatasetLoader.__init__
|
(self,
impl,
update_cache_rrule,
)
|
:param palladium.interfaces.DatasetLoader impl:
The underlying (decorated) dataset loader object.
:param dict update_cache_rrule:
Keyword arguments for a :class:`dateutil.rrule.rrule` that
determines when the cache will be updated. See
:class:`~palladium.util.RruleThread` for details.
|
:param palladium.interfaces.DatasetLoader impl:
The underlying (decorated) dataset loader object.
|
[
":",
"param",
"palladium",
".",
"interfaces",
".",
"DatasetLoader",
"impl",
":",
"The",
"underlying",
"(",
"decorated",
")",
"dataset",
"loader",
"object",
"."
] |
def __init__(self,
impl,
update_cache_rrule,
):
"""
:param palladium.interfaces.DatasetLoader impl:
The underlying (decorated) dataset loader object.
:param dict update_cache_rrule:
Keyword arguments for a :class:`dateutil.rrule.rrule` that
determines when the cache will be updated. See
:class:`~palladium.util.RruleThread` for details.
"""
self.impl = impl
self.update_cache_rrule = update_cache_rrule
|
[
"def",
"__init__",
"(",
"self",
",",
"impl",
",",
"update_cache_rrule",
",",
")",
":",
"self",
".",
"impl",
"=",
"impl",
"self",
".",
"update_cache_rrule",
"=",
"update_cache_rrule"
] |
https://github.com/ottogroup/palladium/blob/3e7bd7d8f38b8ad1a175d0cd387fe5959acbfe2e/palladium/dataset.py#L164-L178
|
||
mozillazg/pypy
|
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
|
rpython/jit/backend/tool/viewcode.py
|
python
|
Graph.display
|
(self)
|
Display a graph page locally.
|
Display a graph page locally.
|
[
"Display",
"a",
"graph",
"page",
"locally",
"."
] |
def display(self):
"Display a graph page locally."
display_page(_Page(self))
|
[
"def",
"display",
"(",
"self",
")",
":",
"display_page",
"(",
"_Page",
"(",
"self",
")",
")"
] |
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/jit/backend/tool/viewcode.py#L395-L397
|
||
maraoz/proofofexistence
|
10703675824e989f59a8d36fd8c06394e71a2c25
|
babel/numbers.py
|
python
|
format_number
|
(number, locale=LC_NUMERIC)
|
return format_decimal(number, locale=locale)
|
u"""Return the given number formatted for a specific locale.
>>> format_number(1099, locale='en_US')
u'1,099'
>>> format_number(1099, locale='de_DE')
u'1.099'
:param number: the number to format
:param locale: the `Locale` object or locale identifier
|
u"""Return the given number formatted for a specific locale.
|
[
"u",
"Return",
"the",
"given",
"number",
"formatted",
"for",
"a",
"specific",
"locale",
"."
] |
def format_number(number, locale=LC_NUMERIC):
u"""Return the given number formatted for a specific locale.
>>> format_number(1099, locale='en_US')
u'1,099'
>>> format_number(1099, locale='de_DE')
u'1.099'
:param number: the number to format
:param locale: the `Locale` object or locale identifier
"""
# Do we really need this one?
return format_decimal(number, locale=locale)
|
[
"def",
"format_number",
"(",
"number",
",",
"locale",
"=",
"LC_NUMERIC",
")",
":",
"# Do we really need this one?",
"return",
"format_decimal",
"(",
"number",
",",
"locale",
"=",
"locale",
")"
] |
https://github.com/maraoz/proofofexistence/blob/10703675824e989f59a8d36fd8c06394e71a2c25/babel/numbers.py#L207-L220
|
|
IronLanguages/main
|
a949455434b1fda8c783289e897e78a9a0caabb5
|
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/inspect.py
|
python
|
trace
|
(context=1)
|
return getinnerframes(sys.exc_info()[2], context)
|
Return a list of records for the stack below the current exception.
|
Return a list of records for the stack below the current exception.
|
[
"Return",
"a",
"list",
"of",
"records",
"for",
"the",
"stack",
"below",
"the",
"current",
"exception",
"."
] |
def trace(context=1):
"""Return a list of records for the stack below the current exception."""
return getinnerframes(sys.exc_info()[2], context)
|
[
"def",
"trace",
"(",
"context",
"=",
"1",
")",
":",
"return",
"getinnerframes",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
",",
"context",
")"
] |
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/inspect.py#L1062-L1064
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.