nwo stringlengths 5 86 | sha stringlengths 40 40 | path stringlengths 4 189 | language stringclasses 1 value | identifier stringlengths 1 94 | parameters stringlengths 2 4.03k | argument_list stringclasses 1 value | return_statement stringlengths 0 11.5k | docstring stringlengths 1 33.2k | docstring_summary stringlengths 0 5.15k | docstring_tokens list | function stringlengths 34 151k | function_tokens list | url stringlengths 90 278 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
OpenLightingProject/ola | d1433a1bed73276fbe55ce18c03b1c208237decc | tools/rdm/DMXSender.py | python | DMXSender.SendComplete | (self, state) | Called when the DMX send completes. | Called when the DMX send completes. | [
"Called",
"when",
"the",
"DMX",
"send",
"completes",
"."
] | def SendComplete(self, state):
"""Called when the DMX send completes.""" | [
"def",
"SendComplete",
"(",
"self",
",",
"state",
")",
":"
] | https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/tools/rdm/DMXSender.py#L62-L63 | ||
krishauser/Klampt | 972cc83ea5befac3f653c1ba20f80155768ad519 | Python/klampt/math/autodiff/ad.py | python | ADFunctionCall.eval | (self,**kwargs) | return self._eval([],kwargs) | Evaluate a function call with bound values given by the keyword
arguments. Example::
print((3*var('x')**2 - 2*var('x')).eval(x=1.5)) | Evaluate a function call with bound values given by the keyword
arguments. Example:: | [
"Evaluate",
"a",
"function",
"call",
"with",
"bound",
"values",
"given",
"by",
"the",
"keyword",
"arguments",
".",
"Example",
"::"
] | def eval(self,**kwargs):
"""Evaluate a function call with bound values given by the keyword
arguments. Example::
print((3*var('x')**2 - 2*var('x')).eval(x=1.5))
"""
self._clear_cache('eval_result','eval_context','eval_instantiated_args')
return self._eval([],kwargs) | [
"def",
"eval",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_clear_cache",
"(",
"'eval_result'",
",",
"'eval_context'",
",",
"'eval_instantiated_args'",
")",
"return",
"self",
".",
"_eval",
"(",
"[",
"]",
",",
"kwargs",
")"
] | https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/math/autodiff/ad.py#L491-L499 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/ParticleMechanicsApplication/python_scripts/particle_gid_output_process.py | python | ParticleGiDOutputProcess._get_variable | (self, my_string) | return self._get_attribute(my_string, KratosMultiphysics.KratosGlobals.GetVariable, "Variable") | Return the python object of a Variable named by the string argument.
Examples:
recommended usage:
variable = self._get_variable("MP_VELOCITY")
deprecated:
variable = self._get_variables("KratosMultiphysics.ParticleMechanicsApplication.MP_VELOCITY") | Return the python object of a Variable named by the string argument. | [
"Return",
"the",
"python",
"object",
"of",
"a",
"Variable",
"named",
"by",
"the",
"string",
"argument",
"."
] | def _get_variable(self, my_string):
"""Return the python object of a Variable named by the string argument.
Examples:
recommended usage:
variable = self._get_variable("MP_VELOCITY")
deprecated:
variable = self._get_variables("KratosMultiphysics.ParticleMechanicsApplication.MP_VELOCITY")
"""
return self._get_attribute(my_string, KratosMultiphysics.KratosGlobals.GetVariable, "Variable") | [
"def",
"_get_variable",
"(",
"self",
",",
"my_string",
")",
":",
"return",
"self",
".",
"_get_attribute",
"(",
"my_string",
",",
"KratosMultiphysics",
".",
"KratosGlobals",
".",
"GetVariable",
",",
"\"Variable\"",
")"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/ParticleMechanicsApplication/python_scripts/particle_gid_output_process.py#L201-L210 | |
benoitsteiner/tensorflow-opencl | cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5 | tensorflow/python/keras/_impl/keras/engine/training.py | python | Model.predict | (self, x, batch_size=None, verbose=0, steps=None) | return self._predict_loop(
f, ins, batch_size=batch_size, verbose=verbose, steps=steps) | Generates output predictions for the input samples.
Computation is done in batches.
Arguments:
x: The input data, as a Numpy array
(or list of Numpy arrays if the model has multiple outputs).
batch_size: Integer. If unspecified, it will default to 32.
verbose: Verbosity mode, 0 or 1.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`.
Returns:
Numpy array(s) of predictions.
Raises:
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size. | Generates output predictions for the input samples. | [
"Generates",
"output",
"predictions",
"for",
"the",
"input",
"samples",
"."
] | def predict(self, x, batch_size=None, verbose=0, steps=None):
"""Generates output predictions for the input samples.
Computation is done in batches.
Arguments:
x: The input data, as a Numpy array
(or list of Numpy arrays if the model has multiple outputs).
batch_size: Integer. If unspecified, it will default to 32.
verbose: Verbosity mode, 0 or 1.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`.
Returns:
Numpy array(s) of predictions.
Raises:
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
# Backwards compatibility.
if batch_size is None and steps is None:
batch_size = 32
if x is None and steps is None:
raise ValueError('If predicting from data tensors, '
'you should specify the `steps` '
'argument.')
# Validate user data.
x = _standardize_input_data(
x,
self._feed_input_names,
self._feed_input_shapes,
check_batch_axis=False)
if self.stateful:
if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:
raise ValueError('In a stateful network, '
'you should only pass inputs with '
'a number of samples that can be '
'divided by the batch size. Found: ' +
str(x[0].shape[0]) + ' samples. '
'Batch size: ' + str(batch_size) + '.')
# Prepare inputs, delegate logic to `_predict_loop`.
if self.uses_learning_phase and not isinstance(K.learning_phase(), int):
ins = x + [0.]
else:
ins = x
self._make_predict_function()
f = self.predict_function
return self._predict_loop(
f, ins, batch_size=batch_size, verbose=verbose, steps=steps) | [
"def",
"predict",
"(",
"self",
",",
"x",
",",
"batch_size",
"=",
"None",
",",
"verbose",
"=",
"0",
",",
"steps",
"=",
"None",
")",
":",
"# Backwards compatibility.",
"if",
"batch_size",
"is",
"None",
"and",
"steps",
"is",
"None",
":",
"batch_size",
"=",
"32",
"if",
"x",
"is",
"None",
"and",
"steps",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'If predicting from data tensors, '",
"'you should specify the `steps` '",
"'argument.'",
")",
"# Validate user data.",
"x",
"=",
"_standardize_input_data",
"(",
"x",
",",
"self",
".",
"_feed_input_names",
",",
"self",
".",
"_feed_input_shapes",
",",
"check_batch_axis",
"=",
"False",
")",
"if",
"self",
".",
"stateful",
":",
"if",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
">",
"batch_size",
"and",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
"%",
"batch_size",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"'In a stateful network, '",
"'you should only pass inputs with '",
"'a number of samples that can be '",
"'divided by the batch size. Found: '",
"+",
"str",
"(",
"x",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
"+",
"' samples. '",
"'Batch size: '",
"+",
"str",
"(",
"batch_size",
")",
"+",
"'.'",
")",
"# Prepare inputs, delegate logic to `_predict_loop`.",
"if",
"self",
".",
"uses_learning_phase",
"and",
"not",
"isinstance",
"(",
"K",
".",
"learning_phase",
"(",
")",
",",
"int",
")",
":",
"ins",
"=",
"x",
"+",
"[",
"0.",
"]",
"else",
":",
"ins",
"=",
"x",
"self",
".",
"_make_predict_function",
"(",
")",
"f",
"=",
"self",
".",
"predict_function",
"return",
"self",
".",
"_predict_loop",
"(",
"f",
",",
"ins",
",",
"batch_size",
"=",
"batch_size",
",",
"verbose",
"=",
"verbose",
",",
"steps",
"=",
"steps",
")"
] | https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/keras/_impl/keras/engine/training.py#L1686-L1739 | |
amd/OpenCL-caffe | 638543108517265366c18ae5821f3096cf5cf34a | tools/extra/resize_and_crop_images.py | python | PILResizeCrop.resize_and_crop_image | (self, input_file, output_file, output_side_length = 256, fit = True) | Downsample the image. | Downsample the image. | [
"Downsample",
"the",
"image",
"."
] | def resize_and_crop_image(self, input_file, output_file, output_side_length = 256, fit = True):
'''Downsample the image.
'''
img = Image.open(input_file)
box = (output_side_length, output_side_length)
#preresize image with factor 2, 4, 8 and fast algorithm
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
#calculate the cropping box and get the cropped part
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = int(y2/2-box[1]*wRatio/2)
y2 = int(y2/2+box[1]*wRatio/2)
else:
x1 = int(x2/2-box[0]*hRatio/2)
x2 = int(x2/2+box[0]*hRatio/2)
img = img.crop((x1,y1,x2,y2))
#Resize the image with best quality algorithm ANTI-ALIAS
img.thumbnail(box, Image.ANTIALIAS)
#save it into a file-like object
with open(output_file, 'wb') as out:
img.save(out, 'JPEG', quality=75) | [
"def",
"resize_and_crop_image",
"(",
"self",
",",
"input_file",
",",
"output_file",
",",
"output_side_length",
"=",
"256",
",",
"fit",
"=",
"True",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"input_file",
")",
"box",
"=",
"(",
"output_side_length",
",",
"output_side_length",
")",
"#preresize image with factor 2, 4, 8 and fast algorithm",
"factor",
"=",
"1",
"while",
"img",
".",
"size",
"[",
"0",
"]",
"/",
"factor",
">",
"2",
"*",
"box",
"[",
"0",
"]",
"and",
"img",
".",
"size",
"[",
"1",
"]",
"*",
"2",
"/",
"factor",
">",
"2",
"*",
"box",
"[",
"1",
"]",
":",
"factor",
"*=",
"2",
"if",
"factor",
">",
"1",
":",
"img",
".",
"thumbnail",
"(",
"(",
"img",
".",
"size",
"[",
"0",
"]",
"/",
"factor",
",",
"img",
".",
"size",
"[",
"1",
"]",
"/",
"factor",
")",
",",
"Image",
".",
"NEAREST",
")",
"#calculate the cropping box and get the cropped part",
"if",
"fit",
":",
"x1",
"=",
"y1",
"=",
"0",
"x2",
",",
"y2",
"=",
"img",
".",
"size",
"wRatio",
"=",
"1.0",
"*",
"x2",
"/",
"box",
"[",
"0",
"]",
"hRatio",
"=",
"1.0",
"*",
"y2",
"/",
"box",
"[",
"1",
"]",
"if",
"hRatio",
">",
"wRatio",
":",
"y1",
"=",
"int",
"(",
"y2",
"/",
"2",
"-",
"box",
"[",
"1",
"]",
"*",
"wRatio",
"/",
"2",
")",
"y2",
"=",
"int",
"(",
"y2",
"/",
"2",
"+",
"box",
"[",
"1",
"]",
"*",
"wRatio",
"/",
"2",
")",
"else",
":",
"x1",
"=",
"int",
"(",
"x2",
"/",
"2",
"-",
"box",
"[",
"0",
"]",
"*",
"hRatio",
"/",
"2",
")",
"x2",
"=",
"int",
"(",
"x2",
"/",
"2",
"+",
"box",
"[",
"0",
"]",
"*",
"hRatio",
"/",
"2",
")",
"img",
"=",
"img",
".",
"crop",
"(",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
")",
"#Resize the image with best quality algorithm ANTI-ALIAS",
"img",
".",
"thumbnail",
"(",
"box",
",",
"Image",
".",
"ANTIALIAS",
")",
"#save it into a file-like object",
"with",
"open",
"(",
"output_file",
",",
"'wb'",
")",
"as",
"out",
":",
"img",
".",
"save",
"(",
"out",
",",
"'JPEG'",
",",
"quality",
"=",
"75",
")"
] | https://github.com/amd/OpenCL-caffe/blob/638543108517265366c18ae5821f3096cf5cf34a/tools/extra/resize_and_crop_images.py#L40-L71 | ||
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/internal/well_known_types.py | python | FieldMask.Union | (self, mask1, mask2) | Merges mask1 and mask2 into this FieldMask. | Merges mask1 and mask2 into this FieldMask. | [
"Merges",
"mask1",
"and",
"mask2",
"into",
"this",
"FieldMask",
"."
] | def Union(self, mask1, mask2):
"""Merges mask1 and mask2 into this FieldMask."""
_CheckFieldMaskMessage(mask1)
_CheckFieldMaskMessage(mask2)
tree = _FieldMaskTree(mask1)
tree.MergeFromFieldMask(mask2)
tree.ToFieldMask(self) | [
"def",
"Union",
"(",
"self",
",",
"mask1",
",",
"mask2",
")",
":",
"_CheckFieldMaskMessage",
"(",
"mask1",
")",
"_CheckFieldMaskMessage",
"(",
"mask2",
")",
"tree",
"=",
"_FieldMaskTree",
"(",
"mask1",
")",
"tree",
".",
"MergeFromFieldMask",
"(",
"mask2",
")",
"tree",
".",
"ToFieldMask",
"(",
"self",
")"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/internal/well_known_types.py#L461-L467 | ||
vusec/vuzzer64 | 2b1b0ed757a3dca114db0192fa4ab1add92348bc | fuzzer-code/gautils.py | python | create_files | (num) | return 0 | This function creates num number of files in the input directory. This is called if we do not have enough initial population.
Addition: once a new file is created by mutation/cossover, we query MOSTCOMMON dict to find offsets that replace values at those offsets in the new files. Int he case of mutation, we also use taintmap of the parent input to get other offsets that are used in CMP and change them. For crossover, as there are two parents invlived, we cannot query just one, so we do a random change on those offsets from any of the parents in resulting children. | This function creates num number of files in the input directory. This is called if we do not have enough initial population.
Addition: once a new file is created by mutation/cossover, we query MOSTCOMMON dict to find offsets that replace values at those offsets in the new files. Int he case of mutation, we also use taintmap of the parent input to get other offsets that are used in CMP and change them. For crossover, as there are two parents invlived, we cannot query just one, so we do a random change on those offsets from any of the parents in resulting children. | [
"This",
"function",
"creates",
"num",
"number",
"of",
"files",
"in",
"the",
"input",
"directory",
".",
"This",
"is",
"called",
"if",
"we",
"do",
"not",
"have",
"enough",
"initial",
"population",
".",
"Addition",
":",
"once",
"a",
"new",
"file",
"is",
"created",
"by",
"mutation",
"/",
"cossover",
"we",
"query",
"MOSTCOMMON",
"dict",
"to",
"find",
"offsets",
"that",
"replace",
"values",
"at",
"those",
"offsets",
"in",
"the",
"new",
"files",
".",
"Int",
"he",
"case",
"of",
"mutation",
"we",
"also",
"use",
"taintmap",
"of",
"the",
"parent",
"input",
"to",
"get",
"other",
"offsets",
"that",
"are",
"used",
"in",
"CMP",
"and",
"change",
"them",
".",
"For",
"crossover",
"as",
"there",
"are",
"two",
"parents",
"invlived",
"we",
"cannot",
"query",
"just",
"one",
"so",
"we",
"do",
"a",
"random",
"change",
"on",
"those",
"offsets",
"from",
"any",
"of",
"the",
"parents",
"in",
"resulting",
"children",
"."
] | def create_files(num):
''' This function creates num number of files in the input directory. This is called if we do not have enough initial population.
Addition: once a new file is created by mutation/cossover, we query MOSTCOMMON dict to find offsets that replace values at those offsets in the new files. Int he case of mutation, we also use taintmap of the parent input to get other offsets that are used in CMP and change them. For crossover, as there are two parents invlived, we cannot query just one, so we do a random change on those offsets from any of the parents in resulting children.
'''
#files=os.listdir(config.INPUTD)
files=os.listdir(config.INITIALD)
ga=operators.GAoperator(random.Random(),config.ALLSTRINGS)
while (num != 0):
if random.uniform(0.1,1.0)>(1.0 - config.PROBCROSS) and (num >1):
#we are going to use crossover, so we get two parents.
par=random.sample(files, 2)
bn, ext = splitFilename(par[0])
#fp1=os.path.join(config.INPUTD,par[0])
#fp2=os.path.join(config.INPUTD,par[1])
fp1=os.path.join(config.INITIALD,par[0])
fp2=os.path.join(config.INITIALD,par[1])
p1=readFile(fp1)
p2=readFile(fp2)
ch1,ch2 = ga.crossover(p1,p2)#,par[0],par[1])
# now we make changes according to taintflow info.
ch1=taint_based_change(ch1,par[0])
ch2=taint_based_change(ch2,par[1])
np1=os.path.join(config.INPUTD,"ex-%d.%s"%(num,ext))
np2=os.path.join(config.INPUTD,"ex-%d.%s"%(num-1,ext))
writeFile(np1,ch1)
writeFile(np2,ch2)
num -= 2
else:
fl=random.choice(files)
bn, ext = splitFilename(fl)
#fp=os.path.join(config.INPUTD,fl)
fp=os.path.join(config.INITIALD,fl)
p1=readFile(fp)
ch1= ga.mutate(p1,fl)
ch1=taint_based_change(ch1,fl)
np1=os.path.join(config.INPUTD,"ex-%d.%s"%(num,ext))
writeFile(np1,ch1)
num -= 1
return 0 | [
"def",
"create_files",
"(",
"num",
")",
":",
"#files=os.listdir(config.INPUTD)",
"files",
"=",
"os",
".",
"listdir",
"(",
"config",
".",
"INITIALD",
")",
"ga",
"=",
"operators",
".",
"GAoperator",
"(",
"random",
".",
"Random",
"(",
")",
",",
"config",
".",
"ALLSTRINGS",
")",
"while",
"(",
"num",
"!=",
"0",
")",
":",
"if",
"random",
".",
"uniform",
"(",
"0.1",
",",
"1.0",
")",
">",
"(",
"1.0",
"-",
"config",
".",
"PROBCROSS",
")",
"and",
"(",
"num",
">",
"1",
")",
":",
"#we are going to use crossover, so we get two parents.",
"par",
"=",
"random",
".",
"sample",
"(",
"files",
",",
"2",
")",
"bn",
",",
"ext",
"=",
"splitFilename",
"(",
"par",
"[",
"0",
"]",
")",
"#fp1=os.path.join(config.INPUTD,par[0])",
"#fp2=os.path.join(config.INPUTD,par[1])",
"fp1",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INITIALD",
",",
"par",
"[",
"0",
"]",
")",
"fp2",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INITIALD",
",",
"par",
"[",
"1",
"]",
")",
"p1",
"=",
"readFile",
"(",
"fp1",
")",
"p2",
"=",
"readFile",
"(",
"fp2",
")",
"ch1",
",",
"ch2",
"=",
"ga",
".",
"crossover",
"(",
"p1",
",",
"p2",
")",
"#,par[0],par[1])",
"# now we make changes according to taintflow info.",
"ch1",
"=",
"taint_based_change",
"(",
"ch1",
",",
"par",
"[",
"0",
"]",
")",
"ch2",
"=",
"taint_based_change",
"(",
"ch2",
",",
"par",
"[",
"1",
"]",
")",
"np1",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INPUTD",
",",
"\"ex-%d.%s\"",
"%",
"(",
"num",
",",
"ext",
")",
")",
"np2",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INPUTD",
",",
"\"ex-%d.%s\"",
"%",
"(",
"num",
"-",
"1",
",",
"ext",
")",
")",
"writeFile",
"(",
"np1",
",",
"ch1",
")",
"writeFile",
"(",
"np2",
",",
"ch2",
")",
"num",
"-=",
"2",
"else",
":",
"fl",
"=",
"random",
".",
"choice",
"(",
"files",
")",
"bn",
",",
"ext",
"=",
"splitFilename",
"(",
"fl",
")",
"#fp=os.path.join(config.INPUTD,fl)",
"fp",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INITIALD",
",",
"fl",
")",
"p1",
"=",
"readFile",
"(",
"fp",
")",
"ch1",
"=",
"ga",
".",
"mutate",
"(",
"p1",
",",
"fl",
")",
"ch1",
"=",
"taint_based_change",
"(",
"ch1",
",",
"fl",
")",
"np1",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config",
".",
"INPUTD",
",",
"\"ex-%d.%s\"",
"%",
"(",
"num",
",",
"ext",
")",
")",
"writeFile",
"(",
"np1",
",",
"ch1",
")",
"num",
"-=",
"1",
"return",
"0"
] | https://github.com/vusec/vuzzer64/blob/2b1b0ed757a3dca114db0192fa4ab1add92348bc/fuzzer-code/gautils.py#L197-L235 | |
PX4/PX4-Autopilot | 0b9f60a0370be53d683352c63fd92db3d6586e18 | Tools/px4airframes/srcparser.py | python | SourceParser.Validate | (self) | return True | Validates the airframe meta data. | Validates the airframe meta data. | [
"Validates",
"the",
"airframe",
"meta",
"data",
"."
] | def Validate(self):
"""
Validates the airframe meta data.
"""
seenParamNames = []
for group in self.GetParamGroups():
for param in group.GetParams():
name = param.GetName()
board = param.GetFieldValue("board")
# Check for duplicates
name_plus_board = name + "+" + board
for seenParamName in seenParamNames:
if seenParamName == name_plus_board:
sys.stderr.write("Duplicate parameter definition: {0}\n".format(name_plus_board))
return False
seenParamNames.append(name_plus_board)
return True | [
"def",
"Validate",
"(",
"self",
")",
":",
"seenParamNames",
"=",
"[",
"]",
"for",
"group",
"in",
"self",
".",
"GetParamGroups",
"(",
")",
":",
"for",
"param",
"in",
"group",
".",
"GetParams",
"(",
")",
":",
"name",
"=",
"param",
".",
"GetName",
"(",
")",
"board",
"=",
"param",
".",
"GetFieldValue",
"(",
"\"board\"",
")",
"# Check for duplicates",
"name_plus_board",
"=",
"name",
"+",
"\"+\"",
"+",
"board",
"for",
"seenParamName",
"in",
"seenParamNames",
":",
"if",
"seenParamName",
"==",
"name_plus_board",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Duplicate parameter definition: {0}\\n\"",
".",
"format",
"(",
"name_plus_board",
")",
")",
"return",
"False",
"seenParamNames",
".",
"append",
"(",
"name_plus_board",
")",
"return",
"True"
] | https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/px4airframes/srcparser.py#L471-L488 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBAttachInfo.SetWaitForLaunch | (self, *args) | return _lldb.SBAttachInfo_SetWaitForLaunch(self, *args) | SetWaitForLaunch(self, bool b)
SetWaitForLaunch(self, bool b, bool async) | SetWaitForLaunch(self, bool b)
SetWaitForLaunch(self, bool b, bool async) | [
"SetWaitForLaunch",
"(",
"self",
"bool",
"b",
")",
"SetWaitForLaunch",
"(",
"self",
"bool",
"b",
"bool",
"async",
")"
] | def SetWaitForLaunch(self, *args):
"""
SetWaitForLaunch(self, bool b)
SetWaitForLaunch(self, bool b, bool async)
"""
return _lldb.SBAttachInfo_SetWaitForLaunch(self, *args) | [
"def",
"SetWaitForLaunch",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBAttachInfo_SetWaitForLaunch",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L1051-L1056 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/training/training_util.py | python | get_or_create_global_step | (graph=None) | return global_step_tensor | Returns and create (if necessary) the global step tensor.
Args:
graph: The graph in which to create the global step tensor. If missing, use
default graph.
Returns:
The global step tensor.
@compatibility(TF2)
With the deprecation of global graphs, TF no longer tracks variables in
collections. In other words, there are no global variables in TF2. Thus, the
global step functions have been removed (`get_or_create_global_step`,
`create_global_step`, `get_global_step`) . You have two options for migrating:
1. Create a Keras optimizer, which generates an `iterations` variable. This
variable is automatically incremented when calling `apply_gradients`.
2. Manually create and increment a `tf.Variable`.
Below is an example of migrating away from using a global step to using a
Keras optimizer:
Define a dummy model and loss:
>>> def compute_loss(x):
... v = tf.Variable(3.0)
... y = x * v
... loss = x * 5 - x * v
... return loss, [v]
Before migrating:
>>> g = tf.Graph()
>>> with g.as_default():
... x = tf.compat.v1.placeholder(tf.float32, [])
... loss, var_list = compute_loss(x)
... global_step = tf.compat.v1.train.get_or_create_global_step()
... global_init = tf.compat.v1.global_variables_initializer()
... optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
... train_op = optimizer.minimize(loss, global_step, var_list)
>>> sess = tf.compat.v1.Session(graph=g)
>>> sess.run(global_init)
>>> print("before training:", sess.run(global_step))
before training: 0
>>> sess.run(train_op, feed_dict={x: 3})
>>> print("after training:", sess.run(global_step))
after training: 1
Migrating to a Keras optimizer:
>>> optimizer = tf.keras.optimizers.SGD(.01)
>>> print("before training:", optimizer.iterations.numpy())
before training: 0
>>> with tf.GradientTape() as tape:
... loss, var_list = compute_loss(3)
... grads = tape.gradient(loss, var_list)
... optimizer.apply_gradients(zip(grads, var_list))
>>> print("after training:", optimizer.iterations.numpy())
after training: 1
@end_compatibility | Returns and create (if necessary) the global step tensor. | [
"Returns",
"and",
"create",
"(",
"if",
"necessary",
")",
"the",
"global",
"step",
"tensor",
"."
] | def get_or_create_global_step(graph=None):
"""Returns and create (if necessary) the global step tensor.
Args:
graph: The graph in which to create the global step tensor. If missing, use
default graph.
Returns:
The global step tensor.
@compatibility(TF2)
With the deprecation of global graphs, TF no longer tracks variables in
collections. In other words, there are no global variables in TF2. Thus, the
global step functions have been removed (`get_or_create_global_step`,
`create_global_step`, `get_global_step`) . You have two options for migrating:
1. Create a Keras optimizer, which generates an `iterations` variable. This
variable is automatically incremented when calling `apply_gradients`.
2. Manually create and increment a `tf.Variable`.
Below is an example of migrating away from using a global step to using a
Keras optimizer:
Define a dummy model and loss:
>>> def compute_loss(x):
... v = tf.Variable(3.0)
... y = x * v
... loss = x * 5 - x * v
... return loss, [v]
Before migrating:
>>> g = tf.Graph()
>>> with g.as_default():
... x = tf.compat.v1.placeholder(tf.float32, [])
... loss, var_list = compute_loss(x)
... global_step = tf.compat.v1.train.get_or_create_global_step()
... global_init = tf.compat.v1.global_variables_initializer()
... optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
... train_op = optimizer.minimize(loss, global_step, var_list)
>>> sess = tf.compat.v1.Session(graph=g)
>>> sess.run(global_init)
>>> print("before training:", sess.run(global_step))
before training: 0
>>> sess.run(train_op, feed_dict={x: 3})
>>> print("after training:", sess.run(global_step))
after training: 1
Migrating to a Keras optimizer:
>>> optimizer = tf.keras.optimizers.SGD(.01)
>>> print("before training:", optimizer.iterations.numpy())
before training: 0
>>> with tf.GradientTape() as tape:
... loss, var_list = compute_loss(3)
... grads = tape.gradient(loss, var_list)
... optimizer.apply_gradients(zip(grads, var_list))
>>> print("after training:", optimizer.iterations.numpy())
after training: 1
@end_compatibility
"""
graph = graph or ops.get_default_graph()
global_step_tensor = get_global_step(graph)
if global_step_tensor is None:
global_step_tensor = create_global_step(graph)
return global_step_tensor | [
"def",
"get_or_create_global_step",
"(",
"graph",
"=",
"None",
")",
":",
"graph",
"=",
"graph",
"or",
"ops",
".",
"get_default_graph",
"(",
")",
"global_step_tensor",
"=",
"get_global_step",
"(",
"graph",
")",
"if",
"global_step_tensor",
"is",
"None",
":",
"global_step_tensor",
"=",
"create_global_step",
"(",
"graph",
")",
"return",
"global_step_tensor"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/training_util.py#L256-L323 | |
okex/V3-Open-API-SDK | c5abb0db7e2287718e0055e17e57672ce0ec7fd9 | okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/models/link.py | python | Link.is_artifact | (self) | return True | Determines if this points to an actual artifact (e.g. a tarball) or if
it points to an "abstract" thing like a path or a VCS location. | Determines if this points to an actual artifact (e.g. a tarball) or if
it points to an "abstract" thing like a path or a VCS location. | [
"Determines",
"if",
"this",
"points",
"to",
"an",
"actual",
"artifact",
"(",
"e",
".",
"g",
".",
"a",
"tarball",
")",
"or",
"if",
"it",
"points",
"to",
"an",
"abstract",
"thing",
"like",
"a",
"path",
"or",
"a",
"VCS",
"location",
"."
] | def is_artifact(self):
# type: () -> bool
"""
Determines if this points to an actual artifact (e.g. a tarball) or if
it points to an "abstract" thing like a path or a VCS location.
"""
from pip._internal.vcs import vcs
if self.scheme in vcs.all_schemes:
return False
return True | [
"def",
"is_artifact",
"(",
"self",
")",
":",
"# type: () -> bool",
"from",
"pip",
".",
"_internal",
".",
"vcs",
"import",
"vcs",
"if",
"self",
".",
"scheme",
"in",
"vcs",
".",
"all_schemes",
":",
"return",
"False",
"return",
"True"
] | https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_internal/models/link.py#L152-L163 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/asyncio/locks.py | python | Condition.wait | (self) | Wait until notified.
If the calling coroutine has not acquired the lock when this
method is called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks
until it is awakened by a notify() or notify_all() call for
the same condition variable in another coroutine. Once
awakened, it re-acquires the lock and returns True. | Wait until notified. | [
"Wait",
"until",
"notified",
"."
] | async def wait(self):
"""Wait until notified.
If the calling coroutine has not acquired the lock when this
method is called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks
until it is awakened by a notify() or notify_all() call for
the same condition variable in another coroutine. Once
awakened, it re-acquires the lock and returns True.
"""
if not self.locked():
raise RuntimeError('cannot wait on un-acquired lock')
self.release()
try:
fut = self._loop.create_future()
self._waiters.append(fut)
try:
await fut
return True
finally:
self._waiters.remove(fut)
finally:
# Must reacquire lock even if wait is cancelled
cancelled = False
while True:
try:
await self.acquire()
break
except exceptions.CancelledError:
cancelled = True
if cancelled:
raise exceptions.CancelledError | [
"async",
"def",
"wait",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"locked",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'cannot wait on un-acquired lock'",
")",
"self",
".",
"release",
"(",
")",
"try",
":",
"fut",
"=",
"self",
".",
"_loop",
".",
"create_future",
"(",
")",
"self",
".",
"_waiters",
".",
"append",
"(",
"fut",
")",
"try",
":",
"await",
"fut",
"return",
"True",
"finally",
":",
"self",
".",
"_waiters",
".",
"remove",
"(",
"fut",
")",
"finally",
":",
"# Must reacquire lock even if wait is cancelled",
"cancelled",
"=",
"False",
"while",
"True",
":",
"try",
":",
"await",
"self",
".",
"acquire",
"(",
")",
"break",
"except",
"exceptions",
".",
"CancelledError",
":",
"cancelled",
"=",
"True",
"if",
"cancelled",
":",
"raise",
"exceptions",
".",
"CancelledError"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/asyncio/locks.py#L271-L306 | ||
stellar-deprecated/stellard | 67eabb2217bdfa9a6ea317f62338fb6bca458c90 | src/protobuf/python/google/protobuf/message_factory.py | python | MessageFactory.__init__ | (self) | Initializes a new factory. | Initializes a new factory. | [
"Initializes",
"a",
"new",
"factory",
"."
] | def __init__(self):
"""Initializes a new factory."""
self._classes = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_classes",
"=",
"{",
"}"
] | https://github.com/stellar-deprecated/stellard/blob/67eabb2217bdfa9a6ea317f62338fb6bca458c90/src/protobuf/python/google/protobuf/message_factory.py#L44-L46 | ||
msitt/blpapi-python | bebcf43668c9e5f5467b1f685f9baebbfc45bc87 | src/blpapi/element.py | python | Element.getChoice | (self) | return Element(res[1], self._getDataHolder()) | Returns:
Element: The selection name of this element as :class:`Element`.
Raises:
Exception: If ``datatype() != DataType.CHOICE`` | Returns:
Element: The selection name of this element as :class:`Element`. | [
"Returns",
":",
"Element",
":",
"The",
"selection",
"name",
"of",
"this",
"element",
"as",
":",
"class",
":",
"Element",
"."
] | def getChoice(self):
"""
Returns:
Element: The selection name of this element as :class:`Element`.
Raises:
Exception: If ``datatype() != DataType.CHOICE``
"""
self.__assertIsValid()
res = internals.blpapi_Element_getChoice(self.__handle)
_ExceptionUtil.raiseOnError(res[0])
return Element(res[1], self._getDataHolder()) | [
"def",
"getChoice",
"(",
"self",
")",
":",
"self",
".",
"__assertIsValid",
"(",
")",
"res",
"=",
"internals",
".",
"blpapi_Element_getChoice",
"(",
"self",
".",
"__handle",
")",
"_ExceptionUtil",
".",
"raiseOnError",
"(",
"res",
"[",
"0",
"]",
")",
"return",
"Element",
"(",
"res",
"[",
"1",
"]",
",",
"self",
".",
"_getDataHolder",
"(",
")",
")"
] | https://github.com/msitt/blpapi-python/blob/bebcf43668c9e5f5467b1f685f9baebbfc45bc87/src/blpapi/element.py#L637-L649 | |
intel/caffe | 3f494b442ee3f9d17a07b09ecbd5fa2bbda00836 | examples/faster-rcnn/lib/fast_rcnn/config.py | python | cfg_from_file | (filename) | Load a config file and merge it into the default options. | Load a config file and merge it into the default options. | [
"Load",
"a",
"config",
"file",
"and",
"merge",
"it",
"into",
"the",
"default",
"options",
"."
] | def cfg_from_file(filename):
"""Load a config file and merge it into the default options."""
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C) | [
"def",
"cfg_from_file",
"(",
"filename",
")",
":",
"import",
"yaml",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"yaml_cfg",
"=",
"edict",
"(",
"yaml",
".",
"load",
"(",
"f",
")",
")",
"_merge_a_into_b",
"(",
"yaml_cfg",
",",
"__C",
")"
] | https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/examples/faster-rcnn/lib/fast_rcnn/config.py#L257-L263 | ||
yuxng/PoseCNN | 9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04 | lib/gt_data_layer/layer.py | python | GtDataLayer.forward | (self) | return blobs | Get blobs and copy them into this layer's top blob vector. | Get blobs and copy them into this layer's top blob vector. | [
"Get",
"blobs",
"and",
"copy",
"them",
"into",
"this",
"layer",
"s",
"top",
"blob",
"vector",
"."
] | def forward(self):
"""Get blobs and copy them into this layer's top blob vector."""
blobs = self._get_next_minibatch()
return blobs | [
"def",
"forward",
"(",
"self",
")",
":",
"blobs",
"=",
"self",
".",
"_get_next_minibatch",
"(",
")",
"return",
"blobs"
] | https://github.com/yuxng/PoseCNN/blob/9f3dd7b7bce21dcafc05e8f18ccc90da3caabd04/lib/gt_data_layer/layer.py#L63-L67 | |
Xilinx/Vitis-AI | fc74d404563d9951b57245443c73bef389f3657f | tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/params_ops.py | python | Li | (lo, hi) | return int(math.floor(math.exp(random.uniform(math.log(lo),
math.log(hi+1-1e-5))))) | Log-uniform distributed integer, inclusive limits. | Log-uniform distributed integer, inclusive limits. | [
"Log",
"-",
"uniform",
"distributed",
"integer",
"inclusive",
"limits",
"."
] | def Li(lo, hi):
"""Log-uniform distributed integer, inclusive limits."""
return int(math.floor(math.exp(random.uniform(math.log(lo),
math.log(hi+1-1e-5))))) | [
"def",
"Li",
"(",
"lo",
",",
"hi",
")",
":",
"return",
"int",
"(",
"math",
".",
"floor",
"(",
"math",
".",
"exp",
"(",
"random",
".",
"uniform",
"(",
"math",
".",
"log",
"(",
"lo",
")",
",",
"math",
".",
"log",
"(",
"hi",
"+",
"1",
"-",
"1e-5",
")",
")",
")",
")",
")"
] | https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/specs/python/params_ops.py#L76-L79 | |
KratosMultiphysics/Kratos | 0000833054ed0503424eb28205d6508d9ca6cbbc | applications/FluidDynamicsApplication/python_scripts/navier_stokes_compressible_explicit_solver.py | python | NavierStokesCompressibleExplicitSolver._CreateEstimateDtUtility | (self) | return estimate_dt_utility | This method overloads FluidSolver in order to enforce:
```
self.settings["time_stepping"]["consider_compressibility_in_CFL"] == True
``` | This method overloads FluidSolver in order to enforce:
```
self.settings["time_stepping"]["consider_compressibility_in_CFL"] == True
``` | [
"This",
"method",
"overloads",
"FluidSolver",
"in",
"order",
"to",
"enforce",
":",
"self",
".",
"settings",
"[",
"time_stepping",
"]",
"[",
"consider_compressibility_in_CFL",
"]",
"==",
"True"
] | def _CreateEstimateDtUtility(self):
"""This method overloads FluidSolver in order to enforce:
```
self.settings["time_stepping"]["consider_compressibility_in_CFL"] == True
```
"""
if self.settings["time_stepping"].Has("consider_compressibility_in_CFL"):
KratosMultiphysics.Logger.PrintWarning("", "User-specifed consider_compressibility_in_CFL will be overriden with TRUE")
else:
self.settings["time_stepping"].AddEmptyValue("consider_compressibility_in_CFL")
self.settings["time_stepping"]["consider_compressibility_in_CFL"].SetBool(True)
estimate_dt_utility = KratosFluid.EstimateDtUtility(
self.GetComputingModelPart(),
self.settings["time_stepping"])
return estimate_dt_utility | [
"def",
"_CreateEstimateDtUtility",
"(",
"self",
")",
":",
"if",
"self",
".",
"settings",
"[",
"\"time_stepping\"",
"]",
".",
"Has",
"(",
"\"consider_compressibility_in_CFL\"",
")",
":",
"KratosMultiphysics",
".",
"Logger",
".",
"PrintWarning",
"(",
"\"\"",
",",
"\"User-specifed consider_compressibility_in_CFL will be overriden with TRUE\"",
")",
"else",
":",
"self",
".",
"settings",
"[",
"\"time_stepping\"",
"]",
".",
"AddEmptyValue",
"(",
"\"consider_compressibility_in_CFL\"",
")",
"self",
".",
"settings",
"[",
"\"time_stepping\"",
"]",
"[",
"\"consider_compressibility_in_CFL\"",
"]",
".",
"SetBool",
"(",
"True",
")",
"estimate_dt_utility",
"=",
"KratosFluid",
".",
"EstimateDtUtility",
"(",
"self",
".",
"GetComputingModelPart",
"(",
")",
",",
"self",
".",
"settings",
"[",
"\"time_stepping\"",
"]",
")",
"return",
"estimate_dt_utility"
] | https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/FluidDynamicsApplication/python_scripts/navier_stokes_compressible_explicit_solver.py#L151-L168 | |
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/getpass.py | python | unix_getpass | (prompt='Password: ', stream=None) | return passwd | Prompt for a password, with echo turned off.
Args:
prompt: Written on stream to ask for the input. Default: 'Password: '
stream: A writable file object to display the prompt. Defaults to
the tty. If no tty is available defaults to sys.stderr.
Returns:
The seKr3t input.
Raises:
EOFError: If our input tty or stdin was closed.
GetPassWarning: When we were unable to turn echo off on the input.
Always restores terminal settings before returning. | Prompt for a password, with echo turned off. | [
"Prompt",
"for",
"a",
"password",
"with",
"echo",
"turned",
"off",
"."
] | def unix_getpass(prompt='Password: ', stream=None):
"""Prompt for a password, with echo turned off.
Args:
prompt: Written on stream to ask for the input. Default: 'Password: '
stream: A writable file object to display the prompt. Defaults to
the tty. If no tty is available defaults to sys.stderr.
Returns:
The seKr3t input.
Raises:
EOFError: If our input tty or stdin was closed.
GetPassWarning: When we were unable to turn echo off on the input.
Always restores terminal settings before returning.
"""
fd = None
tty = None
try:
# Always try reading and writing directly on the tty first.
fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
tty = os.fdopen(fd, 'w+', 1)
input = tty
if not stream:
stream = tty
except EnvironmentError, e:
# If that fails, see if stdin can be controlled.
try:
fd = sys.stdin.fileno()
except:
passwd = fallback_getpass(prompt, stream)
input = sys.stdin
if not stream:
stream = sys.stderr
if fd is not None:
passwd = None
try:
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] &= ~(termios.ECHO|termios.ISIG) # 3 == 'lflags'
tcsetattr_flags = termios.TCSAFLUSH
if hasattr(termios, 'TCSASOFT'):
tcsetattr_flags |= termios.TCSASOFT
try:
termios.tcsetattr(fd, tcsetattr_flags, new)
passwd = _raw_input(prompt, stream, input=input)
finally:
termios.tcsetattr(fd, tcsetattr_flags, old)
stream.flush() # issue7208
except termios.error, e:
if passwd is not None:
# _raw_input succeeded. The final tcsetattr failed. Reraise
# instead of leaving the terminal in an unknown state.
raise
# We can't control the tty or stdin. Give up and use normal IO.
# fallback_getpass() raises an appropriate warning.
del input, tty # clean up unused file objects before blocking
passwd = fallback_getpass(prompt, stream)
stream.write('\n')
return passwd | [
"def",
"unix_getpass",
"(",
"prompt",
"=",
"'Password: '",
",",
"stream",
"=",
"None",
")",
":",
"fd",
"=",
"None",
"tty",
"=",
"None",
"try",
":",
"# Always try reading and writing directly on the tty first.",
"fd",
"=",
"os",
".",
"open",
"(",
"'/dev/tty'",
",",
"os",
".",
"O_RDWR",
"|",
"os",
".",
"O_NOCTTY",
")",
"tty",
"=",
"os",
".",
"fdopen",
"(",
"fd",
",",
"'w+'",
",",
"1",
")",
"input",
"=",
"tty",
"if",
"not",
"stream",
":",
"stream",
"=",
"tty",
"except",
"EnvironmentError",
",",
"e",
":",
"# If that fails, see if stdin can be controlled.",
"try",
":",
"fd",
"=",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
"except",
":",
"passwd",
"=",
"fallback_getpass",
"(",
"prompt",
",",
"stream",
")",
"input",
"=",
"sys",
".",
"stdin",
"if",
"not",
"stream",
":",
"stream",
"=",
"sys",
".",
"stderr",
"if",
"fd",
"is",
"not",
"None",
":",
"passwd",
"=",
"None",
"try",
":",
"old",
"=",
"termios",
".",
"tcgetattr",
"(",
"fd",
")",
"# a copy to save",
"new",
"=",
"old",
"[",
":",
"]",
"new",
"[",
"3",
"]",
"&=",
"~",
"(",
"termios",
".",
"ECHO",
"|",
"termios",
".",
"ISIG",
")",
"# 3 == 'lflags'",
"tcsetattr_flags",
"=",
"termios",
".",
"TCSAFLUSH",
"if",
"hasattr",
"(",
"termios",
",",
"'TCSASOFT'",
")",
":",
"tcsetattr_flags",
"|=",
"termios",
".",
"TCSASOFT",
"try",
":",
"termios",
".",
"tcsetattr",
"(",
"fd",
",",
"tcsetattr_flags",
",",
"new",
")",
"passwd",
"=",
"_raw_input",
"(",
"prompt",
",",
"stream",
",",
"input",
"=",
"input",
")",
"finally",
":",
"termios",
".",
"tcsetattr",
"(",
"fd",
",",
"tcsetattr_flags",
",",
"old",
")",
"stream",
".",
"flush",
"(",
")",
"# issue7208",
"except",
"termios",
".",
"error",
",",
"e",
":",
"if",
"passwd",
"is",
"not",
"None",
":",
"# _raw_input succeeded. The final tcsetattr failed. Reraise",
"# instead of leaving the terminal in an unknown state.",
"raise",
"# We can't control the tty or stdin. Give up and use normal IO.",
"# fallback_getpass() raises an appropriate warning.",
"del",
"input",
",",
"tty",
"# clean up unused file objects before blocking",
"passwd",
"=",
"fallback_getpass",
"(",
"prompt",
",",
"stream",
")",
"stream",
".",
"write",
"(",
"'\\n'",
")",
"return",
"passwd"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/getpass.py#L26-L86 | |
dmlc/treelite | df56babb6a4a2d7c29d719c28ce53acfa7dbab3c | python/treelite/sklearn/common.py | python | SKLConverterBase.process_tree | (cls, sklearn_tree, sklearn_model) | return treelite_tree | Process a scikit-learn Tree object | Process a scikit-learn Tree object | [
"Process",
"a",
"scikit",
"-",
"learn",
"Tree",
"object"
] | def process_tree(cls, sklearn_tree, sklearn_model):
"""Process a scikit-learn Tree object"""
treelite_tree = treelite.ModelBuilder.Tree(
threshold_type='float64', leaf_output_type='float64')
# Iterate over each node: node ID ranges from 0 to [node_count]-1
for node_id in range(sklearn_tree.node_count):
cls.process_node(treelite_tree, sklearn_tree, node_id, sklearn_model)
# Node #0 is always root for scikit-learn decision trees
treelite_tree[0].set_root()
return treelite_tree | [
"def",
"process_tree",
"(",
"cls",
",",
"sklearn_tree",
",",
"sklearn_model",
")",
":",
"treelite_tree",
"=",
"treelite",
".",
"ModelBuilder",
".",
"Tree",
"(",
"threshold_type",
"=",
"'float64'",
",",
"leaf_output_type",
"=",
"'float64'",
")",
"# Iterate over each node: node ID ranges from 0 to [node_count]-1",
"for",
"node_id",
"in",
"range",
"(",
"sklearn_tree",
".",
"node_count",
")",
":",
"cls",
".",
"process_node",
"(",
"treelite_tree",
",",
"sklearn_tree",
",",
"node_id",
",",
"sklearn_model",
")",
"# Node #0 is always root for scikit-learn decision trees",
"treelite_tree",
"[",
"0",
"]",
".",
"set_root",
"(",
")",
"return",
"treelite_tree"
] | https://github.com/dmlc/treelite/blob/df56babb6a4a2d7c29d719c28ce53acfa7dbab3c/python/treelite/sklearn/common.py#L10-L22 | |
nyuwireless-unipd/ns3-mmwave | 4ff9e87e8079764e04cbeccd8e85bff15ae16fb3 | utils/grid.py | python | GraphicRenderer.__x_pixel | (self, x, width) | return new_x | ! X Pixel
@param self this object
@param x x
@param width width
@return x pixel | ! X Pixel | [
"!",
"X",
"Pixel"
] | def __x_pixel(self, x, width):
"""! X Pixel
@param self this object
@param x x
@param width width
@return x pixel
"""
new_x = (x - self.__start) * width / (self.__end - self.__start)
return new_x | [
"def",
"__x_pixel",
"(",
"self",
",",
"x",
",",
"width",
")",
":",
"new_x",
"=",
"(",
"x",
"-",
"self",
".",
"__start",
")",
"*",
"width",
"/",
"(",
"self",
".",
"__end",
"-",
"self",
".",
"__start",
")",
"return",
"new_x"
] | https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/utils/grid.py#L1121-L1129 | |
ArduPilot/ardupilot | 6e684b3496122b8158ac412b609d00004b7ac306 | Tools/scripts/build_sizes/build_sizes.py | python | write_footer | (h) | write html footer | write html footer | [
"write",
"html",
"footer"
] | def write_footer(h):
'''write html footer'''
h.write('''
</div>
</body>
</html>
''') | [
"def",
"write_footer",
"(",
"h",
")",
":",
"h",
".",
"write",
"(",
"'''\n</div>\n</body>\n</html>\n'''",
")"
] | https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/Tools/scripts/build_sizes/build_sizes.py#L105-L111 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/dataview.py | python | DataViewIndexListModel.RowsDeleted | (*args, **kwargs) | return _dataview.DataViewIndexListModel_RowsDeleted(*args, **kwargs) | RowsDeleted(self, wxArrayInt rows)
Call this after rows have been deleted. The array will internally get
copied and sorted in descending order so that the rows with the
highest position will be deleted first. | RowsDeleted(self, wxArrayInt rows) | [
"RowsDeleted",
"(",
"self",
"wxArrayInt",
"rows",
")"
] | def RowsDeleted(*args, **kwargs):
"""
RowsDeleted(self, wxArrayInt rows)
Call this after rows have been deleted. The array will internally get
copied and sorted in descending order so that the rows with the
highest position will be deleted first.
"""
return _dataview.DataViewIndexListModel_RowsDeleted(*args, **kwargs) | [
"def",
"RowsDeleted",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_dataview",
".",
"DataViewIndexListModel_RowsDeleted",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/dataview.py#L874-L882 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/nntplib.py | python | _NNTPBase._getline | (self, strip_crlf=True) | return line | Internal: return one line from the server, stripping _CRLF.
Raise EOFError if the connection is closed.
Returns a bytes object. | Internal: return one line from the server, stripping _CRLF.
Raise EOFError if the connection is closed.
Returns a bytes object. | [
"Internal",
":",
"return",
"one",
"line",
"from",
"the",
"server",
"stripping",
"_CRLF",
".",
"Raise",
"EOFError",
"if",
"the",
"connection",
"is",
"closed",
".",
"Returns",
"a",
"bytes",
"object",
"."
] | def _getline(self, strip_crlf=True):
"""Internal: return one line from the server, stripping _CRLF.
Raise EOFError if the connection is closed.
Returns a bytes object."""
line = self.file.readline(_MAXLINE +1)
if len(line) > _MAXLINE:
raise NNTPDataError('line too long')
if self.debugging > 1:
print('*get*', repr(line))
if not line: raise EOFError
if strip_crlf:
if line[-2:] == _CRLF:
line = line[:-2]
elif line[-1:] in _CRLF:
line = line[:-1]
return line | [
"def",
"_getline",
"(",
"self",
",",
"strip_crlf",
"=",
"True",
")",
":",
"line",
"=",
"self",
".",
"file",
".",
"readline",
"(",
"_MAXLINE",
"+",
"1",
")",
"if",
"len",
"(",
"line",
")",
">",
"_MAXLINE",
":",
"raise",
"NNTPDataError",
"(",
"'line too long'",
")",
"if",
"self",
".",
"debugging",
">",
"1",
":",
"print",
"(",
"'*get*'",
",",
"repr",
"(",
"line",
")",
")",
"if",
"not",
"line",
":",
"raise",
"EOFError",
"if",
"strip_crlf",
":",
"if",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"_CRLF",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"elif",
"line",
"[",
"-",
"1",
":",
"]",
"in",
"_CRLF",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"return",
"line"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/nntplib.py#L428-L443 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/lib/agw/aui/tabart.py | python | AuiDefaultTabArt.DrawTab | (self, dc, wnd, page, in_rect, close_button_state, paint_control=False) | return out_tab_rect, out_button_rect, x_extent | Draws a single tab.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` instance object;
:param `page`: the tab control page associated with the tab;
:param Rect `in_rect`: rectangle the tab should be confined to;
:param integer `close_button_state`: the state of the close button on the tab;
:param bool `paint_control`: whether to draw the control inside a tab (if any) on a :class:`MemoryDC`. | Draws a single tab. | [
"Draws",
"a",
"single",
"tab",
"."
] | def DrawTab(self, dc, wnd, page, in_rect, close_button_state, paint_control=False):
"""
Draws a single tab.
:param `dc`: a :class:`DC` device context;
:param `wnd`: a :class:`Window` instance object;
:param `page`: the tab control page associated with the tab;
:param Rect `in_rect`: rectangle the tab should be confined to;
:param integer `close_button_state`: the state of the close button on the tab;
:param bool `paint_control`: whether to draw the control inside a tab (if any) on a :class:`MemoryDC`.
"""
# if the caption is empty, measure some temporary text
caption = page.caption
if not caption:
caption = "Xj"
dc.SetFont(self._selected_font)
selected_textx, selected_texty, dummy = dc.GetMultiLineTextExtent(caption)
dc.SetFont(self._normal_font)
normal_textx, normal_texty, dummy = dc.GetMultiLineTextExtent(caption)
control = page.control
# figure out the size of the tab
tab_size, x_extent = self.GetTabSize(dc, wnd, page.caption, page.bitmap,
page.active, close_button_state, control)
tab_height = self._tab_ctrl_height - 3
tab_width = tab_size[0]
tab_x = in_rect.x
tab_y = in_rect.y + in_rect.height - tab_height
caption = page.caption
# select pen, brush and font for the tab to be drawn
if page.active:
dc.SetFont(self._selected_font)
textx, texty = selected_textx, selected_texty
else:
dc.SetFont(self._normal_font)
textx, texty = normal_textx, normal_texty
if not page.enabled:
dc.SetTextForeground(self._tab_disabled_text_colour)
pagebitmap = page.dis_bitmap
else:
dc.SetTextForeground(self._tab_text_colour(page))
pagebitmap = page.bitmap
# create points that will make the tab outline
clip_width = tab_width
if tab_x + clip_width > in_rect.x + in_rect.width:
clip_width = in_rect.x + in_rect.width - tab_x
# since the above code above doesn't play well with WXDFB or WXCOCOA,
# we'll just use a rectangle for the clipping region for now --
dc.SetClippingRegion(tab_x, tab_y, clip_width+1, tab_height-3)
border_points = [wx.Point() for i in xrange(6)]
agwFlags = self.GetAGWFlags()
if agwFlags & AUI_NB_BOTTOM:
border_points[0] = wx.Point(tab_x, tab_y)
border_points[1] = wx.Point(tab_x, tab_y+tab_height-6)
border_points[2] = wx.Point(tab_x+2, tab_y+tab_height-4)
border_points[3] = wx.Point(tab_x+tab_width-2, tab_y+tab_height-4)
border_points[4] = wx.Point(tab_x+tab_width, tab_y+tab_height-6)
border_points[5] = wx.Point(tab_x+tab_width, tab_y)
else: #if (agwFlags & AUI_NB_TOP)
border_points[0] = wx.Point(tab_x, tab_y+tab_height-4)
border_points[1] = wx.Point(tab_x, tab_y+2)
border_points[2] = wx.Point(tab_x+2, tab_y)
border_points[3] = wx.Point(tab_x+tab_width-2, tab_y)
border_points[4] = wx.Point(tab_x+tab_width, tab_y+2)
border_points[5] = wx.Point(tab_x+tab_width, tab_y+tab_height-4)
# TODO: else if (agwFlags & AUI_NB_LEFT)
# TODO: else if (agwFlags & AUI_NB_RIGHT)
drawn_tab_yoff = border_points[1].y
drawn_tab_height = border_points[0].y - border_points[1].y
if page.active:
# draw active tab
# draw base background colour
r = wx.Rect(tab_x, tab_y, tab_width, tab_height)
dc.SetPen(self._base_colour_pen)
dc.SetBrush(self._base_colour_brush)
dc.DrawRectangle(r.x+1, r.y+1, r.width-1, r.height-4)
# this white helps fill out the gradient at the top of the tab
dc.SetPen( wx.Pen(self._tab_gradient_highlight_colour) )
dc.SetBrush( wx.Brush(self._tab_gradient_highlight_colour) )
dc.DrawRectangle(r.x+2, r.y+1, r.width-3, r.height-4)
# these two points help the rounded corners appear more antialiased
dc.SetPen(self._base_colour_pen)
dc.DrawPoint(r.x+2, r.y+1)
dc.DrawPoint(r.x+r.width-2, r.y+1)
# set rectangle down a bit for gradient drawing
r.SetHeight(r.GetHeight()/2)
r.x += 2
r.width -= 2
r.y += r.height
r.y -= 2
# draw gradient background
top_colour = self._tab_bottom_colour
bottom_colour = self._tab_top_colour
dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
else:
# draw inactive tab
r = wx.Rect(tab_x, tab_y+1, tab_width, tab_height-3)
# start the gradent up a bit and leave the inside border inset
# by a pixel for a 3D look. Only the top half of the inactive
# tab will have a slight gradient
r.x += 3
r.y += 1
r.width -= 4
r.height /= 2
r.height -= 1
# -- draw top gradient fill for glossy look
top_colour = self._tab_inactive_top_colour
bottom_colour = self._tab_inactive_bottom_colour
dc.GradientFillLinear(r, bottom_colour, top_colour, wx.NORTH)
r.y += r.height
r.y -= 1
# -- draw bottom fill for glossy look
top_colour = self._tab_inactive_bottom_colour
bottom_colour = self._tab_inactive_bottom_colour
dc.GradientFillLinear(r, top_colour, bottom_colour, wx.SOUTH)
# draw tab outline
dc.SetPen(self._border_pen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.DrawPolygon(border_points)
# there are two horizontal grey lines at the bottom of the tab control,
# this gets rid of the top one of those lines in the tab control
if page.active:
if agwFlags & AUI_NB_BOTTOM:
dc.SetPen(wx.Pen(self._background_bottom_colour))
# TODO: else if (agwFlags & AUI_NB_LEFT)
# TODO: else if (agwFlags & AUI_NB_RIGHT)
else: # for AUI_NB_TOP
dc.SetPen(self._base_colour_pen)
dc.DrawLine(border_points[0].x+1,
border_points[0].y,
border_points[5].x,
border_points[5].y)
text_offset = tab_x + 8
close_button_width = 0
if close_button_state != AUI_BUTTON_STATE_HIDDEN:
close_button_width = self._active_close_bmp.GetWidth()
if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
text_offset += close_button_width - 5
bitmap_offset = 0
if pagebitmap.IsOk():
bitmap_offset = tab_x + 8
if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width:
bitmap_offset += close_button_width - 5
# draw bitmap
dc.DrawBitmap(pagebitmap,
bitmap_offset,
drawn_tab_yoff + (drawn_tab_height/2) - (pagebitmap.GetHeight()/2),
True)
text_offset = bitmap_offset + pagebitmap.GetWidth()
text_offset += 3 # bitmap padding
else:
if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == 0 or not close_button_width:
text_offset = tab_x + 8
draw_text = ChopText(dc, caption, tab_width - (text_offset-tab_x) - close_button_width)
ypos = drawn_tab_yoff + (drawn_tab_height)/2 - (texty/2) - 1
offset_focus = text_offset
if control is not None:
try:
if control.GetPosition() != wx.Point(text_offset+1, ypos):
control.SetPosition(wx.Point(text_offset+1, ypos))
if not control.IsShown():
control.Show()
if paint_control:
bmp = TakeScreenShot(control.GetScreenRect())
dc.DrawBitmap(bmp, text_offset+1, ypos, True)
controlW, controlH = control.GetSize()
text_offset += controlW + 4
textx += controlW + 4
except wx.PyDeadObjectError:
pass
# draw tab text
rectx, recty, dummy = dc.GetMultiLineTextExtent(draw_text)
dc.DrawLabel(draw_text, wx.Rect(text_offset, ypos, rectx, recty))
# draw focus rectangle
if (agwFlags & AUI_NB_NO_TAB_FOCUS) == 0:
self.DrawFocusRectangle(dc, page, wnd, draw_text, offset_focus, bitmap_offset, drawn_tab_yoff, drawn_tab_height, rectx, recty)
out_button_rect = wx.Rect()
# draw close button if necessary
if close_button_state != AUI_BUTTON_STATE_HIDDEN:
bmp = self._disabled_close_bmp
if close_button_state == AUI_BUTTON_STATE_HOVER:
bmp = self._hover_close_bmp
elif close_button_state == AUI_BUTTON_STATE_PRESSED:
bmp = self._pressed_close_bmp
shift = (agwFlags & AUI_NB_BOTTOM and [1] or [0])[0]
if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT:
rect = wx.Rect(tab_x + 4, tab_y + (tab_height - bmp.GetHeight())/2 - shift,
close_button_width, tab_height)
else:
rect = wx.Rect(tab_x + tab_width - close_button_width - 1,
tab_y + (tab_height - bmp.GetHeight())/2 - shift,
close_button_width, tab_height)
rect = IndentPressedBitmap(rect, close_button_state)
dc.DrawBitmap(bmp, rect.x, rect.y, True)
out_button_rect = rect
out_tab_rect = wx.Rect(tab_x, tab_y, tab_width, tab_height)
dc.DestroyClippingRegion()
return out_tab_rect, out_button_rect, x_extent | [
"def",
"DrawTab",
"(",
"self",
",",
"dc",
",",
"wnd",
",",
"page",
",",
"in_rect",
",",
"close_button_state",
",",
"paint_control",
"=",
"False",
")",
":",
"# if the caption is empty, measure some temporary text",
"caption",
"=",
"page",
".",
"caption",
"if",
"not",
"caption",
":",
"caption",
"=",
"\"Xj\"",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_selected_font",
")",
"selected_textx",
",",
"selected_texty",
",",
"dummy",
"=",
"dc",
".",
"GetMultiLineTextExtent",
"(",
"caption",
")",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_normal_font",
")",
"normal_textx",
",",
"normal_texty",
",",
"dummy",
"=",
"dc",
".",
"GetMultiLineTextExtent",
"(",
"caption",
")",
"control",
"=",
"page",
".",
"control",
"# figure out the size of the tab",
"tab_size",
",",
"x_extent",
"=",
"self",
".",
"GetTabSize",
"(",
"dc",
",",
"wnd",
",",
"page",
".",
"caption",
",",
"page",
".",
"bitmap",
",",
"page",
".",
"active",
",",
"close_button_state",
",",
"control",
")",
"tab_height",
"=",
"self",
".",
"_tab_ctrl_height",
"-",
"3",
"tab_width",
"=",
"tab_size",
"[",
"0",
"]",
"tab_x",
"=",
"in_rect",
".",
"x",
"tab_y",
"=",
"in_rect",
".",
"y",
"+",
"in_rect",
".",
"height",
"-",
"tab_height",
"caption",
"=",
"page",
".",
"caption",
"# select pen, brush and font for the tab to be drawn",
"if",
"page",
".",
"active",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_selected_font",
")",
"textx",
",",
"texty",
"=",
"selected_textx",
",",
"selected_texty",
"else",
":",
"dc",
".",
"SetFont",
"(",
"self",
".",
"_normal_font",
")",
"textx",
",",
"texty",
"=",
"normal_textx",
",",
"normal_texty",
"if",
"not",
"page",
".",
"enabled",
":",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"_tab_disabled_text_colour",
")",
"pagebitmap",
"=",
"page",
".",
"dis_bitmap",
"else",
":",
"dc",
".",
"SetTextForeground",
"(",
"self",
".",
"_tab_text_colour",
"(",
"page",
")",
")",
"pagebitmap",
"=",
"page",
".",
"bitmap",
"# create points that will make the tab outline",
"clip_width",
"=",
"tab_width",
"if",
"tab_x",
"+",
"clip_width",
">",
"in_rect",
".",
"x",
"+",
"in_rect",
".",
"width",
":",
"clip_width",
"=",
"in_rect",
".",
"x",
"+",
"in_rect",
".",
"width",
"-",
"tab_x",
"# since the above code above doesn't play well with WXDFB or WXCOCOA,",
"# we'll just use a rectangle for the clipping region for now --",
"dc",
".",
"SetClippingRegion",
"(",
"tab_x",
",",
"tab_y",
",",
"clip_width",
"+",
"1",
",",
"tab_height",
"-",
"3",
")",
"border_points",
"=",
"[",
"wx",
".",
"Point",
"(",
")",
"for",
"i",
"in",
"xrange",
"(",
"6",
")",
"]",
"agwFlags",
"=",
"self",
".",
"GetAGWFlags",
"(",
")",
"if",
"agwFlags",
"&",
"AUI_NB_BOTTOM",
":",
"border_points",
"[",
"0",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
",",
"tab_y",
")",
"border_points",
"[",
"1",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
",",
"tab_y",
"+",
"tab_height",
"-",
"6",
")",
"border_points",
"[",
"2",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"2",
",",
"tab_y",
"+",
"tab_height",
"-",
"4",
")",
"border_points",
"[",
"3",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
"-",
"2",
",",
"tab_y",
"+",
"tab_height",
"-",
"4",
")",
"border_points",
"[",
"4",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
",",
"tab_y",
"+",
"tab_height",
"-",
"6",
")",
"border_points",
"[",
"5",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
",",
"tab_y",
")",
"else",
":",
"#if (agwFlags & AUI_NB_TOP) ",
"border_points",
"[",
"0",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
",",
"tab_y",
"+",
"tab_height",
"-",
"4",
")",
"border_points",
"[",
"1",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
",",
"tab_y",
"+",
"2",
")",
"border_points",
"[",
"2",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"2",
",",
"tab_y",
")",
"border_points",
"[",
"3",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
"-",
"2",
",",
"tab_y",
")",
"border_points",
"[",
"4",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
",",
"tab_y",
"+",
"2",
")",
"border_points",
"[",
"5",
"]",
"=",
"wx",
".",
"Point",
"(",
"tab_x",
"+",
"tab_width",
",",
"tab_y",
"+",
"tab_height",
"-",
"4",
")",
"# TODO: else if (agwFlags & AUI_NB_LEFT) ",
"# TODO: else if (agwFlags & AUI_NB_RIGHT) ",
"drawn_tab_yoff",
"=",
"border_points",
"[",
"1",
"]",
".",
"y",
"drawn_tab_height",
"=",
"border_points",
"[",
"0",
"]",
".",
"y",
"-",
"border_points",
"[",
"1",
"]",
".",
"y",
"if",
"page",
".",
"active",
":",
"# draw active tab",
"# draw base background colour",
"r",
"=",
"wx",
".",
"Rect",
"(",
"tab_x",
",",
"tab_y",
",",
"tab_width",
",",
"tab_height",
")",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_base_colour_pen",
")",
"dc",
".",
"SetBrush",
"(",
"self",
".",
"_base_colour_brush",
")",
"dc",
".",
"DrawRectangle",
"(",
"r",
".",
"x",
"+",
"1",
",",
"r",
".",
"y",
"+",
"1",
",",
"r",
".",
"width",
"-",
"1",
",",
"r",
".",
"height",
"-",
"4",
")",
"# this white helps fill out the gradient at the top of the tab",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"self",
".",
"_tab_gradient_highlight_colour",
")",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"Brush",
"(",
"self",
".",
"_tab_gradient_highlight_colour",
")",
")",
"dc",
".",
"DrawRectangle",
"(",
"r",
".",
"x",
"+",
"2",
",",
"r",
".",
"y",
"+",
"1",
",",
"r",
".",
"width",
"-",
"3",
",",
"r",
".",
"height",
"-",
"4",
")",
"# these two points help the rounded corners appear more antialiased",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_base_colour_pen",
")",
"dc",
".",
"DrawPoint",
"(",
"r",
".",
"x",
"+",
"2",
",",
"r",
".",
"y",
"+",
"1",
")",
"dc",
".",
"DrawPoint",
"(",
"r",
".",
"x",
"+",
"r",
".",
"width",
"-",
"2",
",",
"r",
".",
"y",
"+",
"1",
")",
"# set rectangle down a bit for gradient drawing",
"r",
".",
"SetHeight",
"(",
"r",
".",
"GetHeight",
"(",
")",
"/",
"2",
")",
"r",
".",
"x",
"+=",
"2",
"r",
".",
"width",
"-=",
"2",
"r",
".",
"y",
"+=",
"r",
".",
"height",
"r",
".",
"y",
"-=",
"2",
"# draw gradient background",
"top_colour",
"=",
"self",
".",
"_tab_bottom_colour",
"bottom_colour",
"=",
"self",
".",
"_tab_top_colour",
"dc",
".",
"GradientFillLinear",
"(",
"r",
",",
"bottom_colour",
",",
"top_colour",
",",
"wx",
".",
"NORTH",
")",
"else",
":",
"# draw inactive tab",
"r",
"=",
"wx",
".",
"Rect",
"(",
"tab_x",
",",
"tab_y",
"+",
"1",
",",
"tab_width",
",",
"tab_height",
"-",
"3",
")",
"# start the gradent up a bit and leave the inside border inset",
"# by a pixel for a 3D look. Only the top half of the inactive",
"# tab will have a slight gradient",
"r",
".",
"x",
"+=",
"3",
"r",
".",
"y",
"+=",
"1",
"r",
".",
"width",
"-=",
"4",
"r",
".",
"height",
"/=",
"2",
"r",
".",
"height",
"-=",
"1",
"# -- draw top gradient fill for glossy look",
"top_colour",
"=",
"self",
".",
"_tab_inactive_top_colour",
"bottom_colour",
"=",
"self",
".",
"_tab_inactive_bottom_colour",
"dc",
".",
"GradientFillLinear",
"(",
"r",
",",
"bottom_colour",
",",
"top_colour",
",",
"wx",
".",
"NORTH",
")",
"r",
".",
"y",
"+=",
"r",
".",
"height",
"r",
".",
"y",
"-=",
"1",
"# -- draw bottom fill for glossy look",
"top_colour",
"=",
"self",
".",
"_tab_inactive_bottom_colour",
"bottom_colour",
"=",
"self",
".",
"_tab_inactive_bottom_colour",
"dc",
".",
"GradientFillLinear",
"(",
"r",
",",
"top_colour",
",",
"bottom_colour",
",",
"wx",
".",
"SOUTH",
")",
"# draw tab outline",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_border_pen",
")",
"dc",
".",
"SetBrush",
"(",
"wx",
".",
"TRANSPARENT_BRUSH",
")",
"dc",
".",
"DrawPolygon",
"(",
"border_points",
")",
"# there are two horizontal grey lines at the bottom of the tab control,",
"# this gets rid of the top one of those lines in the tab control",
"if",
"page",
".",
"active",
":",
"if",
"agwFlags",
"&",
"AUI_NB_BOTTOM",
":",
"dc",
".",
"SetPen",
"(",
"wx",
".",
"Pen",
"(",
"self",
".",
"_background_bottom_colour",
")",
")",
"# TODO: else if (agwFlags & AUI_NB_LEFT) ",
"# TODO: else if (agwFlags & AUI_NB_RIGHT) ",
"else",
":",
"# for AUI_NB_TOP",
"dc",
".",
"SetPen",
"(",
"self",
".",
"_base_colour_pen",
")",
"dc",
".",
"DrawLine",
"(",
"border_points",
"[",
"0",
"]",
".",
"x",
"+",
"1",
",",
"border_points",
"[",
"0",
"]",
".",
"y",
",",
"border_points",
"[",
"5",
"]",
".",
"x",
",",
"border_points",
"[",
"5",
"]",
".",
"y",
")",
"text_offset",
"=",
"tab_x",
"+",
"8",
"close_button_width",
"=",
"0",
"if",
"close_button_state",
"!=",
"AUI_BUTTON_STATE_HIDDEN",
":",
"close_button_width",
"=",
"self",
".",
"_active_close_bmp",
".",
"GetWidth",
"(",
")",
"if",
"agwFlags",
"&",
"AUI_NB_CLOSE_ON_TAB_LEFT",
":",
"text_offset",
"+=",
"close_button_width",
"-",
"5",
"bitmap_offset",
"=",
"0",
"if",
"pagebitmap",
".",
"IsOk",
"(",
")",
":",
"bitmap_offset",
"=",
"tab_x",
"+",
"8",
"if",
"agwFlags",
"&",
"AUI_NB_CLOSE_ON_TAB_LEFT",
"and",
"close_button_width",
":",
"bitmap_offset",
"+=",
"close_button_width",
"-",
"5",
"# draw bitmap",
"dc",
".",
"DrawBitmap",
"(",
"pagebitmap",
",",
"bitmap_offset",
",",
"drawn_tab_yoff",
"+",
"(",
"drawn_tab_height",
"/",
"2",
")",
"-",
"(",
"pagebitmap",
".",
"GetHeight",
"(",
")",
"/",
"2",
")",
",",
"True",
")",
"text_offset",
"=",
"bitmap_offset",
"+",
"pagebitmap",
".",
"GetWidth",
"(",
")",
"text_offset",
"+=",
"3",
"# bitmap padding",
"else",
":",
"if",
"agwFlags",
"&",
"AUI_NB_CLOSE_ON_TAB_LEFT",
"==",
"0",
"or",
"not",
"close_button_width",
":",
"text_offset",
"=",
"tab_x",
"+",
"8",
"draw_text",
"=",
"ChopText",
"(",
"dc",
",",
"caption",
",",
"tab_width",
"-",
"(",
"text_offset",
"-",
"tab_x",
")",
"-",
"close_button_width",
")",
"ypos",
"=",
"drawn_tab_yoff",
"+",
"(",
"drawn_tab_height",
")",
"/",
"2",
"-",
"(",
"texty",
"/",
"2",
")",
"-",
"1",
"offset_focus",
"=",
"text_offset",
"if",
"control",
"is",
"not",
"None",
":",
"try",
":",
"if",
"control",
".",
"GetPosition",
"(",
")",
"!=",
"wx",
".",
"Point",
"(",
"text_offset",
"+",
"1",
",",
"ypos",
")",
":",
"control",
".",
"SetPosition",
"(",
"wx",
".",
"Point",
"(",
"text_offset",
"+",
"1",
",",
"ypos",
")",
")",
"if",
"not",
"control",
".",
"IsShown",
"(",
")",
":",
"control",
".",
"Show",
"(",
")",
"if",
"paint_control",
":",
"bmp",
"=",
"TakeScreenShot",
"(",
"control",
".",
"GetScreenRect",
"(",
")",
")",
"dc",
".",
"DrawBitmap",
"(",
"bmp",
",",
"text_offset",
"+",
"1",
",",
"ypos",
",",
"True",
")",
"controlW",
",",
"controlH",
"=",
"control",
".",
"GetSize",
"(",
")",
"text_offset",
"+=",
"controlW",
"+",
"4",
"textx",
"+=",
"controlW",
"+",
"4",
"except",
"wx",
".",
"PyDeadObjectError",
":",
"pass",
"# draw tab text",
"rectx",
",",
"recty",
",",
"dummy",
"=",
"dc",
".",
"GetMultiLineTextExtent",
"(",
"draw_text",
")",
"dc",
".",
"DrawLabel",
"(",
"draw_text",
",",
"wx",
".",
"Rect",
"(",
"text_offset",
",",
"ypos",
",",
"rectx",
",",
"recty",
")",
")",
"# draw focus rectangle",
"if",
"(",
"agwFlags",
"&",
"AUI_NB_NO_TAB_FOCUS",
")",
"==",
"0",
":",
"self",
".",
"DrawFocusRectangle",
"(",
"dc",
",",
"page",
",",
"wnd",
",",
"draw_text",
",",
"offset_focus",
",",
"bitmap_offset",
",",
"drawn_tab_yoff",
",",
"drawn_tab_height",
",",
"rectx",
",",
"recty",
")",
"out_button_rect",
"=",
"wx",
".",
"Rect",
"(",
")",
"# draw close button if necessary",
"if",
"close_button_state",
"!=",
"AUI_BUTTON_STATE_HIDDEN",
":",
"bmp",
"=",
"self",
".",
"_disabled_close_bmp",
"if",
"close_button_state",
"==",
"AUI_BUTTON_STATE_HOVER",
":",
"bmp",
"=",
"self",
".",
"_hover_close_bmp",
"elif",
"close_button_state",
"==",
"AUI_BUTTON_STATE_PRESSED",
":",
"bmp",
"=",
"self",
".",
"_pressed_close_bmp",
"shift",
"=",
"(",
"agwFlags",
"&",
"AUI_NB_BOTTOM",
"and",
"[",
"1",
"]",
"or",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"if",
"agwFlags",
"&",
"AUI_NB_CLOSE_ON_TAB_LEFT",
":",
"rect",
"=",
"wx",
".",
"Rect",
"(",
"tab_x",
"+",
"4",
",",
"tab_y",
"+",
"(",
"tab_height",
"-",
"bmp",
".",
"GetHeight",
"(",
")",
")",
"/",
"2",
"-",
"shift",
",",
"close_button_width",
",",
"tab_height",
")",
"else",
":",
"rect",
"=",
"wx",
".",
"Rect",
"(",
"tab_x",
"+",
"tab_width",
"-",
"close_button_width",
"-",
"1",
",",
"tab_y",
"+",
"(",
"tab_height",
"-",
"bmp",
".",
"GetHeight",
"(",
")",
")",
"/",
"2",
"-",
"shift",
",",
"close_button_width",
",",
"tab_height",
")",
"rect",
"=",
"IndentPressedBitmap",
"(",
"rect",
",",
"close_button_state",
")",
"dc",
".",
"DrawBitmap",
"(",
"bmp",
",",
"rect",
".",
"x",
",",
"rect",
".",
"y",
",",
"True",
")",
"out_button_rect",
"=",
"rect",
"out_tab_rect",
"=",
"wx",
".",
"Rect",
"(",
"tab_x",
",",
"tab_y",
",",
"tab_width",
",",
"tab_height",
")",
"dc",
".",
"DestroyClippingRegion",
"(",
")",
"return",
"out_tab_rect",
",",
"out_button_rect",
",",
"x_extent"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/tabart.py#L343-L611 | |
CanalTP/navitia | cb84ce9859070187e708818b058e6a7e0b7f891b | source/jormungandr/jormungandr/interfaces/v1/JSONSchema.py | python | Schema.get | (self) | return JsonSchemaEndpointsSerializer(path).data, 200 | endpoint to get the swagger schema of Navitia | endpoint to get the swagger schema of Navitia | [
"endpoint",
"to",
"get",
"the",
"swagger",
"schema",
"of",
"Navitia"
] | def get(self):
"""
endpoint to get the swagger schema of Navitia
"""
path = get_all_described_paths()
return JsonSchemaEndpointsSerializer(path).data, 200 | [
"def",
"get",
"(",
"self",
")",
":",
"path",
"=",
"get_all_described_paths",
"(",
")",
"return",
"JsonSchemaEndpointsSerializer",
"(",
"path",
")",
".",
"data",
",",
"200"
] | https://github.com/CanalTP/navitia/blob/cb84ce9859070187e708818b058e6a7e0b7f891b/source/jormungandr/jormungandr/interfaces/v1/JSONSchema.py#L137-L143 | |
google/pienoon | a721180de4d9de3696af3b3734d1ad269975b111 | scripts/export.py | python | main | () | return 0 | Zips up all files needed to run the game.
Zips up all files listed in EXPORT_FILES, all directories listed in
EXPORT_DIRECTORIES, and the binary executables `pie_noon` and `flatc`, which
have different locations when built using different tool chains.
Returns:
0 on success, 1 otherwise. | Zips up all files needed to run the game. | [
"Zips",
"up",
"all",
"files",
"needed",
"to",
"run",
"the",
"game",
"."
] | def main():
"""Zips up all files needed to run the game.
Zips up all files listed in EXPORT_FILES, all directories listed in
EXPORT_DIRECTORIES, and the binary executables `pie_noon` and `flatc`, which
have different locations when built using different tool chains.
Returns:
0 on success, 1 otherwise.
"""
dir_name = os.path.basename(os.getcwd())
zip_file_name = dir_name + '.zip'
try:
zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
except IOError as error:
sys.stderr.write(
'Could not open %s for writing. (%s)\n' % (zip_file_name, str(error)))
return 1
# glob cannot recurse into subdirectories, so just use os.walk instead.
for relative_path in EXPORT_DIRECTORIES:
for root, _, filenames in os.walk(relative_path):
for filename in filenames:
input_path = os.path.join(root, filename)
output_path = os.path.join(dir_name, root, filename)
try:
zip_file.write(input_path, output_path)
except IOError as error:
handle_io_error(error, filename)
return 1
for filename in EXPORT_FILES:
output_path = os.path.join(dir_name, filename)
try:
zip_file.write(filename, output_path)
except IOError as error:
handle_io_error(error, filename)
return 1
try:
zip_binary(zip_file, 'bin', 'pie_noon', dir_name)
zip_binary(zip_file, 'bin', 'flatc', dir_name)
if platform.system() == 'Windows':
zip_binary(zip_file, 'bin', 'SDL2.dll', dir_name)
except MissingBinaryError as error:
sys.stderr.write('Could not find %s binary\n' % error.filename)
return 1
except IOError as error:
handle_io_error(error, error.filename)
return 1
zip_file.close()
return 0 | [
"def",
"main",
"(",
")",
":",
"dir_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"zip_file_name",
"=",
"dir_name",
"+",
"'.zip'",
"try",
":",
"zip_file",
"=",
"zipfile",
".",
"ZipFile",
"(",
"zip_file_name",
",",
"'w'",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"except",
"IOError",
"as",
"error",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Could not open %s for writing. (%s)\\n'",
"%",
"(",
"zip_file_name",
",",
"str",
"(",
"error",
")",
")",
")",
"return",
"1",
"# glob cannot recurse into subdirectories, so just use os.walk instead.",
"for",
"relative_path",
"in",
"EXPORT_DIRECTORIES",
":",
"for",
"root",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"relative_path",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"input_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_name",
",",
"root",
",",
"filename",
")",
"try",
":",
"zip_file",
".",
"write",
"(",
"input_path",
",",
"output_path",
")",
"except",
"IOError",
"as",
"error",
":",
"handle_io_error",
"(",
"error",
",",
"filename",
")",
"return",
"1",
"for",
"filename",
"in",
"EXPORT_FILES",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir_name",
",",
"filename",
")",
"try",
":",
"zip_file",
".",
"write",
"(",
"filename",
",",
"output_path",
")",
"except",
"IOError",
"as",
"error",
":",
"handle_io_error",
"(",
"error",
",",
"filename",
")",
"return",
"1",
"try",
":",
"zip_binary",
"(",
"zip_file",
",",
"'bin'",
",",
"'pie_noon'",
",",
"dir_name",
")",
"zip_binary",
"(",
"zip_file",
",",
"'bin'",
",",
"'flatc'",
",",
"dir_name",
")",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"zip_binary",
"(",
"zip_file",
",",
"'bin'",
",",
"'SDL2.dll'",
",",
"dir_name",
")",
"except",
"MissingBinaryError",
"as",
"error",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Could not find %s binary\\n'",
"%",
"error",
".",
"filename",
")",
"return",
"1",
"except",
"IOError",
"as",
"error",
":",
"handle_io_error",
"(",
"error",
",",
"error",
".",
"filename",
")",
"return",
"1",
"zip_file",
".",
"close",
"(",
")",
"return",
"0"
] | https://github.com/google/pienoon/blob/a721180de4d9de3696af3b3734d1ad269975b111/scripts/export.py#L93-L146 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py | python | FTP.retrlines | (self, cmd, callback = None) | return self.voidresp() | Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code. | Retrieve data in line mode. A new port is created for you. | [
"Retrieve",
"data",
"in",
"line",
"mode",
".",
"A",
"new",
"port",
"is",
"created",
"for",
"you",
"."
] | def retrlines(self, cmd, callback = None):
"""Retrieve data in line mode. A new port is created for you.
Args:
cmd: A RETR, LIST, NLST, or MLSD command.
callback: An optional single parameter callable that is called
for each line with the trailing CRLF stripped.
[default: print_line()]
Returns:
The response code.
"""
if callback is None: callback = print_line
resp = self.sendcmd('TYPE A')
conn = self.transfercmd(cmd)
fp = conn.makefile('rb')
while 1:
line = fp.readline()
if self.debugging > 2: print '*retr*', repr(line)
if not line:
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] == '\n':
line = line[:-1]
callback(line)
fp.close()
conn.close()
return self.voidresp() | [
"def",
"retrlines",
"(",
"self",
",",
"cmd",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"print_line",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'TYPE A'",
")",
"conn",
"=",
"self",
".",
"transfercmd",
"(",
"cmd",
")",
"fp",
"=",
"conn",
".",
"makefile",
"(",
"'rb'",
")",
"while",
"1",
":",
"line",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"self",
".",
"debugging",
">",
"2",
":",
"print",
"'*retr*'",
",",
"repr",
"(",
"line",
")",
"if",
"not",
"line",
":",
"break",
"if",
"line",
"[",
"-",
"2",
":",
"]",
"==",
"CRLF",
":",
"line",
"=",
"line",
"[",
":",
"-",
"2",
"]",
"elif",
"line",
"[",
"-",
"1",
":",
"]",
"==",
"'\\n'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"callback",
"(",
"line",
")",
"fp",
".",
"close",
"(",
")",
"conn",
".",
"close",
"(",
")",
"return",
"self",
".",
"voidresp",
"(",
")"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/ftplib.py#L418-L446 | |
Polidea/SiriusObfuscator | b0e590d8130e97856afe578869b83a209e2b19be | SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py | python | SBFrame.IsEqual | (self, *args) | return _lldb.SBFrame_IsEqual(self, *args) | IsEqual(self, SBFrame rhs) -> bool | IsEqual(self, SBFrame rhs) -> bool | [
"IsEqual",
"(",
"self",
"SBFrame",
"rhs",
")",
"-",
">",
"bool"
] | def IsEqual(self, *args):
"""IsEqual(self, SBFrame rhs) -> bool"""
return _lldb.SBFrame_IsEqual(self, *args) | [
"def",
"IsEqual",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_lldb",
".",
"SBFrame_IsEqual",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L4500-L4502 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/keras/backend.py | python | set_learning_phase | (value) | Sets the learning phase to a fixed value.
The backend learning phase affects any code that calls
`backend.learning_phase()`
In particular, all Keras built-in layers use the learning phase as the default
for the `training` arg to `Layer.__call__`.
User-written layers and models can achieve the same behavior with code that
looks like:
```python
def call(self, inputs, training=None):
if training is None:
training = backend.learning_phase()
```
Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`. | Sets the learning phase to a fixed value. | [
"Sets",
"the",
"learning",
"phase",
"to",
"a",
"fixed",
"value",
"."
] | def set_learning_phase(value):
"""Sets the learning phase to a fixed value.
The backend learning phase affects any code that calls
`backend.learning_phase()`
In particular, all Keras built-in layers use the learning phase as the default
for the `training` arg to `Layer.__call__`.
User-written layers and models can achieve the same behavior with code that
looks like:
```python
def call(self, inputs, training=None):
if training is None:
training = backend.learning_phase()
```
Args:
value: Learning phase value, either 0 or 1 (integers).
0 = test, 1 = train
Raises:
ValueError: if `value` is neither `0` nor `1`.
"""
warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and '
'will be removed after 2020-10-11. To update it, simply '
'pass a True/False value to the `training` argument of the '
'`__call__` method of your layer or model.')
deprecated_internal_set_learning_phase(value) | [
"def",
"set_learning_phase",
"(",
"value",
")",
":",
"warnings",
".",
"warn",
"(",
"'`tf.keras.backend.set_learning_phase` is deprecated and '",
"'will be removed after 2020-10-11. To update it, simply '",
"'pass a True/False value to the `training` argument of the '",
"'`__call__` method of your layer or model.'",
")",
"deprecated_internal_set_learning_phase",
"(",
"value",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L413-L441 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/_core.py | python | ThreadEvent.SetExtraLong | (*args, **kwargs) | return _core_.ThreadEvent_SetExtraLong(*args, **kwargs) | SetExtraLong(self, long extraLong) | SetExtraLong(self, long extraLong) | [
"SetExtraLong",
"(",
"self",
"long",
"extraLong",
")"
] | def SetExtraLong(*args, **kwargs):
"""SetExtraLong(self, long extraLong)"""
return _core_.ThreadEvent_SetExtraLong(*args, **kwargs) | [
"def",
"SetExtraLong",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core_",
".",
"ThreadEvent_SetExtraLong",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5394-L5396 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py | python | _Flavour.join_parsed_parts | (self, drv, root, parts, drv2, root2, parts2) | return drv2, root2, parts2 | Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple. | Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple. | [
"Join",
"the",
"two",
"paths",
"represented",
"by",
"the",
"respective",
"(",
"drive",
"root",
"parts",
")",
"tuples",
".",
"Return",
"a",
"new",
"(",
"drive",
"root",
"parts",
")",
"tuple",
"."
] | def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
"""
Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
"""
if root2:
if not drv2 and drv:
return drv, root2, [drv + root2] + parts2[1:]
elif drv2:
if drv2 == drv or self.casefold(drv2) == self.casefold(drv):
# Same drive => second path is relative to the first
return drv, root, parts + parts2[1:]
else:
# Second path is non-anchored (common case)
return drv, root, parts + parts2
return drv2, root2, parts2 | [
"def",
"join_parsed_parts",
"(",
"self",
",",
"drv",
",",
"root",
",",
"parts",
",",
"drv2",
",",
"root2",
",",
"parts2",
")",
":",
"if",
"root2",
":",
"if",
"not",
"drv2",
"and",
"drv",
":",
"return",
"drv",
",",
"root2",
",",
"[",
"drv",
"+",
"root2",
"]",
"+",
"parts2",
"[",
"1",
":",
"]",
"elif",
"drv2",
":",
"if",
"drv2",
"==",
"drv",
"or",
"self",
".",
"casefold",
"(",
"drv2",
")",
"==",
"self",
".",
"casefold",
"(",
"drv",
")",
":",
"# Same drive => second path is relative to the first",
"return",
"drv",
",",
"root",
",",
"parts",
"+",
"parts2",
"[",
"1",
":",
"]",
"else",
":",
"# Second path is non-anchored (common case)",
"return",
"drv",
",",
"root",
",",
"parts",
"+",
"parts2",
"return",
"drv2",
",",
"root2",
",",
"parts2"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py#L101-L116 | |
baidu-research/tensorflow-allreduce | 66d5b855e90b0949e9fa5cca5599fd729a70e874 | tensorflow/contrib/graph_editor/transform.py | python | Transformer.__init__ | (self) | Transformer constructor.
The following members can be modified:
transform_op_handler: handle the transformation of a `tf.Operation`.
This handler defaults to a simple copy.
assign_collections_handler: handle the assignment of collections.
This handler defaults to assigning new collections created under the
given name-scope.
transform_external_input_handler: handle the transform of the inputs to
the given subgraph. This handler defaults to creating placeholders
instead of the ops just before the input tensors of the subgraph.
transform_external_hidden_input_handler: handle the transform of the
hidden inputs of the subgraph, that is, the inputs which are not listed
in sgv.inputs. This handler defaults to a transform which keep the same
input if the source and destination graphs are the same, otherwise
use placeholders.
transform_original_op_handler: handle the transform of original_op. This
handler defaults to transforming original_op only if they are in the
subgraph, otherwise they are ignored. | Transformer constructor. | [
"Transformer",
"constructor",
"."
] | def __init__(self):
"""Transformer constructor.
The following members can be modified:
transform_op_handler: handle the transformation of a `tf.Operation`.
This handler defaults to a simple copy.
assign_collections_handler: handle the assignment of collections.
This handler defaults to assigning new collections created under the
given name-scope.
transform_external_input_handler: handle the transform of the inputs to
the given subgraph. This handler defaults to creating placeholders
instead of the ops just before the input tensors of the subgraph.
transform_external_hidden_input_handler: handle the transform of the
hidden inputs of the subgraph, that is, the inputs which are not listed
in sgv.inputs. This handler defaults to a transform which keep the same
input if the source and destination graphs are the same, otherwise
use placeholders.
transform_original_op_handler: handle the transform of original_op. This
handler defaults to transforming original_op only if they are in the
subgraph, otherwise they are ignored.
"""
# handlers
self.transform_op_handler = copy_op_handler
self.transform_control_input_handler = transform_op_if_inside_handler
self.assign_collections_handler = assign_renamed_collections_handler
self.transform_external_input_handler = replace_t_with_placeholder_handler
self.transform_external_hidden_input_handler = keep_t_if_possible_handler
self.transform_original_op_handler = transform_op_if_inside_handler | [
"def",
"__init__",
"(",
"self",
")",
":",
"# handlers",
"self",
".",
"transform_op_handler",
"=",
"copy_op_handler",
"self",
".",
"transform_control_input_handler",
"=",
"transform_op_if_inside_handler",
"self",
".",
"assign_collections_handler",
"=",
"assign_renamed_collections_handler",
"self",
".",
"transform_external_input_handler",
"=",
"replace_t_with_placeholder_handler",
"self",
".",
"transform_external_hidden_input_handler",
"=",
"keep_t_if_possible_handler",
"self",
".",
"transform_original_op_handler",
"=",
"transform_op_if_inside_handler"
] | https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/graph_editor/transform.py#L360-L388 | ||
apple/turicreate | cce55aa5311300e3ce6af93cb45ba791fd1bdf49 | src/python/turicreate/toolkits/sound_classifier/sound_classifier.py | python | SoundClassifier.__repr__ | (self) | return out | Print a string description of the model when the model name is entered
in the terminal. | Print a string description of the model when the model name is entered
in the terminal. | [
"Print",
"a",
"string",
"description",
"of",
"the",
"model",
"when",
"the",
"model",
"name",
"is",
"entered",
"in",
"the",
"terminal",
"."
] | def __repr__(self):
"""
Print a string description of the model when the model name is entered
in the terminal.
"""
import turicreate.toolkits._internal_utils as tkutl
width = 40
sections, section_titles = self._get_summary_struct()
out = tkutl._toolkit_repr_print(self, sections, section_titles, width=width)
return out | [
"def",
"__repr__",
"(",
"self",
")",
":",
"import",
"turicreate",
".",
"toolkits",
".",
"_internal_utils",
"as",
"tkutl",
"width",
"=",
"40",
"sections",
",",
"section_titles",
"=",
"self",
".",
"_get_summary_struct",
"(",
")",
"out",
"=",
"tkutl",
".",
"_toolkit_repr_print",
"(",
"self",
",",
"sections",
",",
"section_titles",
",",
"width",
"=",
"width",
")",
"return",
"out"
] | https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/sound_classifier/sound_classifier.py#L580-L591 | |
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/data/experimental/ops/map_defun.py | python | map_defun | (fn,
elems,
output_dtypes,
output_shapes,
max_intra_op_parallelism=1) | return gen_dataset_ops.map_defun(elems, concrete_fn.captured_inputs,
output_dtypes, output_shapes, concrete_fn,
max_intra_op_parallelism) | Map a function on the list of tensors unpacked from `elems` on dimension 0.
Args:
fn: A function (`function.defun`) that takes a list of tensors and returns
another list of tensors. The output list has the same types as
output_dtypes. The elements of the output list have the same dimension 0
as `elems`, and the remaining dimensions correspond to those of
`fn_output_shapes`.
elems: A list of tensors.
output_dtypes: A list of dtypes corresponding to the output types of the
function.
output_shapes: A list of `TensorShape`s corresponding to the output shapes
from each invocation of the function on slices of inputs.
max_intra_op_parallelism: An integer. If positive, sets the max parallelism
limit of each function call to this.
Raises:
ValueError: if any of the inputs are malformed.
Returns:
A list of `Tensor` objects with the same types as `output_dtypes`. | Map a function on the list of tensors unpacked from `elems` on dimension 0. | [
"Map",
"a",
"function",
"on",
"the",
"list",
"of",
"tensors",
"unpacked",
"from",
"elems",
"on",
"dimension",
"0",
"."
] | def map_defun(fn,
elems,
output_dtypes,
output_shapes,
max_intra_op_parallelism=1):
"""Map a function on the list of tensors unpacked from `elems` on dimension 0.
Args:
fn: A function (`function.defun`) that takes a list of tensors and returns
another list of tensors. The output list has the same types as
output_dtypes. The elements of the output list have the same dimension 0
as `elems`, and the remaining dimensions correspond to those of
`fn_output_shapes`.
elems: A list of tensors.
output_dtypes: A list of dtypes corresponding to the output types of the
function.
output_shapes: A list of `TensorShape`s corresponding to the output shapes
from each invocation of the function on slices of inputs.
max_intra_op_parallelism: An integer. If positive, sets the max parallelism
limit of each function call to this.
Raises:
ValueError: if any of the inputs are malformed.
Returns:
A list of `Tensor` objects with the same types as `output_dtypes`.
"""
if not isinstance(elems, list):
raise ValueError(f"`elems` must be a list of tensors, but was {elems}.")
if not isinstance(output_dtypes, list):
raise ValueError("`output_dtypes` must be a list of `tf.DType` objects, "
f"but was {output_dtypes}.")
if not isinstance(output_shapes, list):
raise ValueError("`output_shapes` must be a list of `tf.TensorShape` "
f"objects, but was {output_shapes}.")
concrete_fn = fn._get_concrete_function_internal() # pylint: disable=protected-access
# TODO(shivaniagrawal/rachelim): what about functions created without
# input_signature.
elems = [ops.convert_to_tensor(e) for e in elems]
output_shapes = [tensor_shape.TensorShape(s) for s in output_shapes]
return gen_dataset_ops.map_defun(elems, concrete_fn.captured_inputs,
output_dtypes, output_shapes, concrete_fn,
max_intra_op_parallelism) | [
"def",
"map_defun",
"(",
"fn",
",",
"elems",
",",
"output_dtypes",
",",
"output_shapes",
",",
"max_intra_op_parallelism",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"elems",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"f\"`elems` must be a list of tensors, but was {elems}.\"",
")",
"if",
"not",
"isinstance",
"(",
"output_dtypes",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"`output_dtypes` must be a list of `tf.DType` objects, \"",
"f\"but was {output_dtypes}.\"",
")",
"if",
"not",
"isinstance",
"(",
"output_shapes",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"`output_shapes` must be a list of `tf.TensorShape` \"",
"f\"objects, but was {output_shapes}.\"",
")",
"concrete_fn",
"=",
"fn",
".",
"_get_concrete_function_internal",
"(",
")",
"# pylint: disable=protected-access",
"# TODO(shivaniagrawal/rachelim): what about functions created without",
"# input_signature.",
"elems",
"=",
"[",
"ops",
".",
"convert_to_tensor",
"(",
"e",
")",
"for",
"e",
"in",
"elems",
"]",
"output_shapes",
"=",
"[",
"tensor_shape",
".",
"TensorShape",
"(",
"s",
")",
"for",
"s",
"in",
"output_shapes",
"]",
"return",
"gen_dataset_ops",
".",
"map_defun",
"(",
"elems",
",",
"concrete_fn",
".",
"captured_inputs",
",",
"output_dtypes",
",",
"output_shapes",
",",
"concrete_fn",
",",
"max_intra_op_parallelism",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/data/experimental/ops/map_defun.py#L22-L65 | |
lyxok1/Tiny-DSOD | 94d15450699bea0dd3720e75e2d273e476174fba | scripts/cpp_lint.py | python | FileInfo.Split | (self) | return (project,) + os.path.splitext(rest) | Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension). | Splits the file into the directory, basename, and extension. | [
"Splits",
"the",
"file",
"into",
"the",
"directory",
"basename",
"and",
"extension",
"."
] | def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest) | [
"def",
"Split",
"(",
"self",
")",
":",
"googlename",
"=",
"self",
".",
"RepositoryName",
"(",
")",
"project",
",",
"rest",
"=",
"os",
".",
"path",
".",
"split",
"(",
"googlename",
")",
"return",
"(",
"project",
",",
")",
"+",
"os",
".",
"path",
".",
"splitext",
"(",
"rest",
")"
] | https://github.com/lyxok1/Tiny-DSOD/blob/94d15450699bea0dd3720e75e2d273e476174fba/scripts/cpp_lint.py#L930-L942 | |
protocolbuffers/protobuf | b5ab0b7a18b7336c60130f4ddb2d97c51792f896 | python/google/protobuf/text_format.py | python | ParseInteger | (text, is_signed=False, is_long=False) | return result | Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer. | Parses an integer. | [
"Parses",
"an",
"integer",
"."
] | def ParseInteger(text, is_signed=False, is_long=False):
"""Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
result = _ParseAbstractInteger(text)
# Check if the integer is sane. Exceptions handled by callers.
checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
checker.CheckValue(result)
return result | [
"def",
"ParseInteger",
"(",
"text",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"False",
")",
":",
"# Do the actual parsing. Exception handling is propagated to caller.",
"result",
"=",
"_ParseAbstractInteger",
"(",
"text",
")",
"# Check if the integer is sane. Exceptions handled by callers.",
"checker",
"=",
"_INTEGER_CHECKERS",
"[",
"2",
"*",
"int",
"(",
"is_long",
")",
"+",
"int",
"(",
"is_signed",
")",
"]",
"checker",
".",
"CheckValue",
"(",
"result",
")",
"return",
"result"
] | https://github.com/protocolbuffers/protobuf/blob/b5ab0b7a18b7336c60130f4ddb2d97c51792f896/python/google/protobuf/text_format.py#L1659-L1679 | |
apiaryio/drafter | 4634ebd07f6c6f257cc656598ccd535492fdfb55 | tools/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.WriteMacInfoPlist | (self, partial_info_plist, bundle_depends) | Write build rules for bundle Info.plist files. | Write build rules for bundle Info.plist files. | [
"Write",
"build",
"rules",
"for",
"bundle",
"Info",
".",
"plist",
"files",
"."
] | def WriteMacInfoPlist(self, partial_info_plist, bundle_depends):
"""Write build rules for bundle Info.plist files."""
info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist(
generator_default_variables['PRODUCT_DIR'],
self.xcode_settings, self.GypPathToNinja)
if not info_plist:
return
out = self.ExpandSpecial(out)
if defines:
# Create an intermediate file to store preprocessed results.
intermediate_plist = self.GypPathToUniqueOutput(
os.path.basename(info_plist))
defines = ' '.join([Define(d, self.flavor) for d in defines])
info_plist = self.ninja.build(
intermediate_plist, 'preprocess_infoplist', info_plist,
variables=[('defines',defines)])
env = self.GetSortedXcodeEnv(additional_settings=extra_env)
env = self.ComputeExportEnvString(env)
if partial_info_plist:
intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist')
info_plist = self.ninja.build(
intermediate_plist, 'merge_infoplist',
[partial_info_plist, info_plist])
keys = self.xcode_settings.GetExtraPlistItems(self.config_name)
keys = QuoteShellArgument(json.dumps(keys), self.flavor)
isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name)
self.ninja.build(out, 'copy_infoplist', info_plist,
variables=[('env', env), ('keys', keys),
('binary', isBinary)])
bundle_depends.append(out) | [
"def",
"WriteMacInfoPlist",
"(",
"self",
",",
"partial_info_plist",
",",
"bundle_depends",
")",
":",
"info_plist",
",",
"out",
",",
"defines",
",",
"extra_env",
"=",
"gyp",
".",
"xcode_emulation",
".",
"GetMacInfoPlist",
"(",
"generator_default_variables",
"[",
"'PRODUCT_DIR'",
"]",
",",
"self",
".",
"xcode_settings",
",",
"self",
".",
"GypPathToNinja",
")",
"if",
"not",
"info_plist",
":",
"return",
"out",
"=",
"self",
".",
"ExpandSpecial",
"(",
"out",
")",
"if",
"defines",
":",
"# Create an intermediate file to store preprocessed results.",
"intermediate_plist",
"=",
"self",
".",
"GypPathToUniqueOutput",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"info_plist",
")",
")",
"defines",
"=",
"' '",
".",
"join",
"(",
"[",
"Define",
"(",
"d",
",",
"self",
".",
"flavor",
")",
"for",
"d",
"in",
"defines",
"]",
")",
"info_plist",
"=",
"self",
".",
"ninja",
".",
"build",
"(",
"intermediate_plist",
",",
"'preprocess_infoplist'",
",",
"info_plist",
",",
"variables",
"=",
"[",
"(",
"'defines'",
",",
"defines",
")",
"]",
")",
"env",
"=",
"self",
".",
"GetSortedXcodeEnv",
"(",
"additional_settings",
"=",
"extra_env",
")",
"env",
"=",
"self",
".",
"ComputeExportEnvString",
"(",
"env",
")",
"if",
"partial_info_plist",
":",
"intermediate_plist",
"=",
"self",
".",
"GypPathToUniqueOutput",
"(",
"'merged_info.plist'",
")",
"info_plist",
"=",
"self",
".",
"ninja",
".",
"build",
"(",
"intermediate_plist",
",",
"'merge_infoplist'",
",",
"[",
"partial_info_plist",
",",
"info_plist",
"]",
")",
"keys",
"=",
"self",
".",
"xcode_settings",
".",
"GetExtraPlistItems",
"(",
"self",
".",
"config_name",
")",
"keys",
"=",
"QuoteShellArgument",
"(",
"json",
".",
"dumps",
"(",
"keys",
")",
",",
"self",
".",
"flavor",
")",
"isBinary",
"=",
"self",
".",
"xcode_settings",
".",
"IsBinaryOutputFormat",
"(",
"self",
".",
"config_name",
")",
"self",
".",
"ninja",
".",
"build",
"(",
"out",
",",
"'copy_infoplist'",
",",
"info_plist",
",",
"variables",
"=",
"[",
"(",
"'env'",
",",
"env",
")",
",",
"(",
"'keys'",
",",
"keys",
")",
",",
"(",
"'binary'",
",",
"isBinary",
")",
"]",
")",
"bundle_depends",
".",
"append",
"(",
"out",
")"
] | https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/ninja.py#L835-L867 | ||
apple/swift-lldb | d74be846ef3e62de946df343e8c234bde93a8912 | scripts/Python/static-binding/lldb.py | python | SBValue.SetPreferDynamicValue | (self, use_dynamic) | return _lldb.SBValue_SetPreferDynamicValue(self, use_dynamic) | SetPreferDynamicValue(SBValue self, lldb::DynamicValueType use_dynamic) | SetPreferDynamicValue(SBValue self, lldb::DynamicValueType use_dynamic) | [
"SetPreferDynamicValue",
"(",
"SBValue",
"self",
"lldb",
"::",
"DynamicValueType",
"use_dynamic",
")"
] | def SetPreferDynamicValue(self, use_dynamic):
"""SetPreferDynamicValue(SBValue self, lldb::DynamicValueType use_dynamic)"""
return _lldb.SBValue_SetPreferDynamicValue(self, use_dynamic) | [
"def",
"SetPreferDynamicValue",
"(",
"self",
",",
"use_dynamic",
")",
":",
"return",
"_lldb",
".",
"SBValue_SetPreferDynamicValue",
"(",
"self",
",",
"use_dynamic",
")"
] | https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L14299-L14301 | |
microsoft/TSS.MSR | 0f2516fca2cd9929c31d5450e39301c9bde43688 | TSS.Py/src/Tpm.py | python | Tpm.VerifySignature | (self, keyHandle, digest, signature) | return res.validation if res else None | This command uses loaded keys to validate a signature on a message
with the message digest passed to the TPM.
Args:
keyHandle (TPM_HANDLE): Handle of public key that will be used in
the validation
Auth Index: None
digest (bytes): Digest of the signed message
signature (TPMU_SIGNATURE): Signature to be tested
One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS,
TPMS_SIGNATURE_ECDSA, TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2,
TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, TPMS_SCHEME_HASH,
TPMS_NULL_SIGNATURE.
Returns:
validation - This ticket is produced by TPM2_VerifySignature(). This
formulation is used for multiple ticket uses. The
ticket provides evidence that the TPM has validated
that a digest was signed by a key with the Name of
keyName. The ticket is computed by | This command uses loaded keys to validate a signature on a message
with the message digest passed to the TPM. | [
"This",
"command",
"uses",
"loaded",
"keys",
"to",
"validate",
"a",
"signature",
"on",
"a",
"message",
"with",
"the",
"message",
"digest",
"passed",
"to",
"the",
"TPM",
"."
] | def VerifySignature(self, keyHandle, digest, signature):
""" This command uses loaded keys to validate a signature on a message
with the message digest passed to the TPM.
Args:
keyHandle (TPM_HANDLE): Handle of public key that will be used in
the validation
Auth Index: None
digest (bytes): Digest of the signed message
signature (TPMU_SIGNATURE): Signature to be tested
One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS,
TPMS_SIGNATURE_ECDSA, TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2,
TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, TPMS_SCHEME_HASH,
TPMS_NULL_SIGNATURE.
Returns:
validation - This ticket is produced by TPM2_VerifySignature(). This
formulation is used for multiple ticket uses. The
ticket provides evidence that the TPM has validated
that a digest was signed by a key with the Name of
keyName. The ticket is computed by
"""
req = TPM2_VerifySignature_REQUEST(keyHandle, digest, signature)
respBuf = self.dispatchCommand(TPM_CC.VerifySignature, req)
res = self.processResponse(respBuf, VerifySignatureResponse)
return res.validation if res else None | [
"def",
"VerifySignature",
"(",
"self",
",",
"keyHandle",
",",
"digest",
",",
"signature",
")",
":",
"req",
"=",
"TPM2_VerifySignature_REQUEST",
"(",
"keyHandle",
",",
"digest",
",",
"signature",
")",
"respBuf",
"=",
"self",
".",
"dispatchCommand",
"(",
"TPM_CC",
".",
"VerifySignature",
",",
"req",
")",
"res",
"=",
"self",
".",
"processResponse",
"(",
"respBuf",
",",
"VerifySignatureResponse",
")",
"return",
"res",
".",
"validation",
"if",
"res",
"else",
"None"
] | https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L1195-L1220 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | catboost/python-package/catboost/core.py | python | Pool._check_data_type | (self, data) | Check type of data. | Check type of data. | [
"Check",
"type",
"of",
"data",
"."
] | def _check_data_type(self, data):
"""
Check type of data.
"""
if not isinstance(data, (PATH_TYPES, ARRAY_TYPES, SPARSE_MATRIX_TYPES, FeaturesData)):
raise CatBoostError(
"Invalid data type={}: data must be list(), np.ndarray(), DataFrame(), Series(), FeaturesData " +
" scipy.sparse matrix or filename str() or pathlib.Path().".format(type(data))
) | [
"def",
"_check_data_type",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"PATH_TYPES",
",",
"ARRAY_TYPES",
",",
"SPARSE_MATRIX_TYPES",
",",
"FeaturesData",
")",
")",
":",
"raise",
"CatBoostError",
"(",
"\"Invalid data type={}: data must be list(), np.ndarray(), DataFrame(), Series(), FeaturesData \"",
"+",
"\" scipy.sparse matrix or filename str() or pathlib.Path().\"",
".",
"format",
"(",
"type",
"(",
"data",
")",
")",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/catboost/python-package/catboost/core.py#L814-L822 | ||
tensorflow/tensorflow | 419e3a6b650ea4bd1b0cba23c4348f8a69f3272e | tensorflow/python/eager/context.py | python | Context.enable_xla_devices | (self) | Enables XLA:CPU and XLA:GPU devices registration. | Enables XLA:CPU and XLA:GPU devices registration. | [
"Enables",
"XLA",
":",
"CPU",
"and",
"XLA",
":",
"GPU",
"devices",
"registration",
"."
] | def enable_xla_devices(self):
"""Enables XLA:CPU and XLA:GPU devices registration."""
pywrap_tfe.TF_EnableXlaDevices() | [
"def",
"enable_xla_devices",
"(",
"self",
")",
":",
"pywrap_tfe",
".",
"TF_EnableXlaDevices",
"(",
")"
] | https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L1702-L1704 | ||
ceph/ceph | 959663007321a369c83218414a29bd9dbc8bda3a | src/ceph-volume/ceph_volume/devices/lvm/zap.py | python | Zap.zap_raw_device | (self, device) | Any whole (raw) device passed in as input will be processed here,
checking for LVM membership and partitions (if any).
Device example: /dev/sda
Requirements: None | Any whole (raw) device passed in as input will be processed here,
checking for LVM membership and partitions (if any). | [
"Any",
"whole",
"(",
"raw",
")",
"device",
"passed",
"in",
"as",
"input",
"will",
"be",
"processed",
"here",
"checking",
"for",
"LVM",
"membership",
"and",
"partitions",
"(",
"if",
"any",
")",
"."
] | def zap_raw_device(self, device):
"""
Any whole (raw) device passed in as input will be processed here,
checking for LVM membership and partitions (if any).
Device example: /dev/sda
Requirements: None
"""
if not self.args.destroy:
# the use of dd on a raw device causes the partition table to be
# destroyed
mlogger.warning(
'--destroy was not specified, but zapping a whole device will remove the partition table'
)
# look for partitions and zap those
for part_name in device.sys_api.get('partitions', {}).keys():
self.zap_partition(Device('/dev/%s' % part_name))
wipefs(device.abspath)
zap_data(device.abspath) | [
"def",
"zap_raw_device",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"args",
".",
"destroy",
":",
"# the use of dd on a raw device causes the partition table to be",
"# destroyed",
"mlogger",
".",
"warning",
"(",
"'--destroy was not specified, but zapping a whole device will remove the partition table'",
")",
"# look for partitions and zap those",
"for",
"part_name",
"in",
"device",
".",
"sys_api",
".",
"get",
"(",
"'partitions'",
",",
"{",
"}",
")",
".",
"keys",
"(",
")",
":",
"self",
".",
"zap_partition",
"(",
"Device",
"(",
"'/dev/%s'",
"%",
"part_name",
")",
")",
"wipefs",
"(",
"device",
".",
"abspath",
")",
"zap_data",
"(",
"device",
".",
"abspath",
")"
] | https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/ceph-volume/ceph_volume/devices/lvm/zap.py#L241-L261 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py | python | indentedBlock | (blockStatementExpr, indentStack, indent=True) | return smExpr.setName('indented block') | Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=C{True})
A valid block must contain at least one C{blockStatement}.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group( funcDecl + func_body )
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << ( funcDef | assignment | identifier )
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] | [] | def indentedBlock(blockStatementExpr, indentStack, indent=True):
"""
Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=C{True})
A valid block must contain at least one C{blockStatement}.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group( funcDecl + func_body )
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << ( funcDef | assignment | identifier )
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
"""
def checkPeerIndent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if curCol != indentStack[-1]:
if curCol > indentStack[-1]:
raise ParseFatalException(s,l,"illegal nesting")
raise ParseException(s,l,"not a peer entry")
def checkSubIndent(s,l,t):
curCol = col(l,s)
if curCol > indentStack[-1]:
indentStack.append( curCol )
else:
raise ParseException(s,l,"not a subentry")
def checkUnindent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
raise ParseException(s,l,"not an unindent")
indentStack.pop()
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
PEER = Empty().setParseAction(checkPeerIndent).setName('')
UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
if indent:
smExpr = Group( Optional(NL) +
#~ FollowedBy(blockStatementExpr) +
INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
else:
smExpr = Group( Optional(NL) +
(OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
blockStatementExpr.ignore(_bslash + LineEnd())
return smExpr.setName('indented block') | [
"def",
"indentedBlock",
"(",
"blockStatementExpr",
",",
"indentStack",
",",
"indent",
"=",
"True",
")",
":",
"def",
"checkPeerIndent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"l",
">=",
"len",
"(",
"s",
")",
":",
"return",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"curCol",
"!=",
"indentStack",
"[",
"-",
"1",
"]",
":",
"if",
"curCol",
">",
"indentStack",
"[",
"-",
"1",
"]",
":",
"raise",
"ParseFatalException",
"(",
"s",
",",
"l",
",",
"\"illegal nesting\"",
")",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not a peer entry\"",
")",
"def",
"checkSubIndent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"curCol",
">",
"indentStack",
"[",
"-",
"1",
"]",
":",
"indentStack",
".",
"append",
"(",
"curCol",
")",
"else",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not a subentry\"",
")",
"def",
"checkUnindent",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"l",
">=",
"len",
"(",
"s",
")",
":",
"return",
"curCol",
"=",
"col",
"(",
"l",
",",
"s",
")",
"if",
"not",
"(",
"indentStack",
"and",
"curCol",
"<",
"indentStack",
"[",
"-",
"1",
"]",
"and",
"curCol",
"<=",
"indentStack",
"[",
"-",
"2",
"]",
")",
":",
"raise",
"ParseException",
"(",
"s",
",",
"l",
",",
"\"not an unindent\"",
")",
"indentStack",
".",
"pop",
"(",
")",
"NL",
"=",
"OneOrMore",
"(",
"LineEnd",
"(",
")",
".",
"setWhitespaceChars",
"(",
"\"\\t \"",
")",
".",
"suppress",
"(",
")",
")",
"INDENT",
"=",
"(",
"Empty",
"(",
")",
"+",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkSubIndent",
")",
")",
".",
"setName",
"(",
"'INDENT'",
")",
"PEER",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkPeerIndent",
")",
".",
"setName",
"(",
"''",
")",
"UNDENT",
"=",
"Empty",
"(",
")",
".",
"setParseAction",
"(",
"checkUnindent",
")",
".",
"setName",
"(",
"'UNINDENT'",
")",
"if",
"indent",
":",
"smExpr",
"=",
"Group",
"(",
"Optional",
"(",
"NL",
")",
"+",
"#~ FollowedBy(blockStatementExpr) +",
"INDENT",
"+",
"(",
"OneOrMore",
"(",
"PEER",
"+",
"Group",
"(",
"blockStatementExpr",
")",
"+",
"Optional",
"(",
"NL",
")",
")",
")",
"+",
"UNDENT",
")",
"else",
":",
"smExpr",
"=",
"Group",
"(",
"Optional",
"(",
"NL",
")",
"+",
"(",
"OneOrMore",
"(",
"PEER",
"+",
"Group",
"(",
"blockStatementExpr",
")",
"+",
"Optional",
"(",
"NL",
")",
")",
")",
")",
"blockStatementExpr",
".",
"ignore",
"(",
"_bslash",
"+",
"LineEnd",
"(",
")",
")",
"return",
"smExpr",
".",
"setName",
"(",
"'indented block'",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L10493-L10717 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | python/mxnet/recordio.py | python | MXIndexedRecordIO.read_idx | (self, idx) | return self.read() | Returns the record at given index.
Examples
---------
>>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w')
>>> for i in range(5):
... record.write_idx(i, 'record_%d'%i)
>>> record.close()
>>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'r')
>>> record.read_idx(3)
record_3 | Returns the record at given index. | [
"Returns",
"the",
"record",
"at",
"given",
"index",
"."
] | def read_idx(self, idx):
"""Returns the record at given index.
Examples
---------
>>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'w')
>>> for i in range(5):
... record.write_idx(i, 'record_%d'%i)
>>> record.close()
>>> record = mx.recordio.MXIndexedRecordIO('tmp.idx', 'tmp.rec', 'r')
>>> record.read_idx(3)
record_3
"""
self.seek(idx)
return self.read() | [
"def",
"read_idx",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"seek",
"(",
"idx",
")",
"return",
"self",
".",
"read",
"(",
")"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/recordio.py#L304-L318 | |
natanielruiz/android-yolo | 1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f | jni-build/jni/include/tensorflow/python/summary/event_accumulator.py | python | EventAccumulator.CompressedHistograms | (self, tag) | return self._compressed_histograms.Items(tag) | Given a summary tag, return all associated compressed histograms.
Args:
tag: A string tag associated with the events.
Raises:
KeyError: If the tag is not found.
Returns:
An array of `CompressedHistogramEvent`s. | Given a summary tag, return all associated compressed histograms. | [
"Given",
"a",
"summary",
"tag",
"return",
"all",
"associated",
"compressed",
"histograms",
"."
] | def CompressedHistograms(self, tag):
"""Given a summary tag, return all associated compressed histograms.
Args:
tag: A string tag associated with the events.
Raises:
KeyError: If the tag is not found.
Returns:
An array of `CompressedHistogramEvent`s.
"""
return self._compressed_histograms.Items(tag) | [
"def",
"CompressedHistograms",
"(",
"self",
",",
"tag",
")",
":",
"return",
"self",
".",
"_compressed_histograms",
".",
"Items",
"(",
"tag",
")"
] | https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/summary/event_accumulator.py#L338-L350 | |
LiquidPlayer/LiquidCore | 9405979363f2353ac9a71ad8ab59685dd7f919c9 | deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetDefFile | (self, gyp_to_build_path) | return None | Returns the .def file from sources, if any. Otherwise returns None. | Returns the .def file from sources, if any. Otherwise returns None. | [
"Returns",
"the",
".",
"def",
"file",
"from",
"sources",
"if",
"any",
".",
"Otherwise",
"returns",
"None",
"."
] | def GetDefFile(self, gyp_to_build_path):
"""Returns the .def file from sources, if any. Otherwise returns None."""
spec = self.spec
if spec['type'] in ('shared_library', 'loadable_module', 'executable'):
def_files = [s for s in spec.get('sources', []) if s.endswith('.def')]
if len(def_files) == 1:
return gyp_to_build_path(def_files[0])
elif len(def_files) > 1:
raise Exception("Multiple .def files")
return None | [
"def",
"GetDefFile",
"(",
"self",
",",
"gyp_to_build_path",
")",
":",
"spec",
"=",
"self",
".",
"spec",
"if",
"spec",
"[",
"'type'",
"]",
"in",
"(",
"'shared_library'",
",",
"'loadable_module'",
",",
"'executable'",
")",
":",
"def_files",
"=",
"[",
"s",
"for",
"s",
"in",
"spec",
".",
"get",
"(",
"'sources'",
",",
"[",
"]",
")",
"if",
"s",
".",
"endswith",
"(",
"'.def'",
")",
"]",
"if",
"len",
"(",
"def_files",
")",
"==",
"1",
":",
"return",
"gyp_to_build_path",
"(",
"def_files",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"def_files",
")",
">",
"1",
":",
"raise",
"Exception",
"(",
"\"Multiple .def files\"",
")",
"return",
"None"
] | https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L527-L536 | |
MegEngine/MegEngine | ce9ad07a27ec909fb8db4dd67943d24ba98fb93a | imperative/python/megengine/quantization/quantize.py | python | enable_fake_quant | (module: Module) | r"""Recursively enable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
Args:
module: root module to do enable fake quantization recursively. | r"""Recursively enable ``module`` fake quantization in QATModule through :meth:`~.Module.apply` | [
"r",
"Recursively",
"enable",
"module",
"fake",
"quantization",
"in",
"QATModule",
"through",
":",
"meth",
":",
"~",
".",
"Module",
".",
"apply"
] | def enable_fake_quant(module: Module):
r"""Recursively enable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
Args:
module: root module to do enable fake quantization recursively.
"""
_propagate(module, "set_fake_quant", True) | [
"def",
"enable_fake_quant",
"(",
"module",
":",
"Module",
")",
":",
"_propagate",
"(",
"module",
",",
"\"set_fake_quant\"",
",",
"True",
")"
] | https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/quantization/quantize.py#L288-L295 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | wx/tools/Editra/src/eclib/colorsetter.py | python | HexValidator.Clone | (self) | return HexValidator() | Clones the current validator
@return: clone of this object | Clones the current validator
@return: clone of this object | [
"Clones",
"the",
"current",
"validator",
"@return",
":",
"clone",
"of",
"this",
"object"
] | def Clone(self):
"""Clones the current validator
@return: clone of this object
"""
return HexValidator() | [
"def",
"Clone",
"(",
"self",
")",
":",
"return",
"HexValidator",
"(",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/colorsetter.py#L231-L236 | |
IntelRealSense/librealsense | c94410a420b74e5fb6a414bd12215c05ddd82b69 | wrappers/python/examples/box_dimensioner_multicam/calculate_rmsd_kabsch.py | python | kabsch_rotate | (P, Q) | return P | Rotate matrix P unto matrix Q using Kabsch algorithm.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
P : array
(N,D) matrix, where N is points and D is dimension,
rotated | Rotate matrix P unto matrix Q using Kabsch algorithm. | [
"Rotate",
"matrix",
"P",
"unto",
"matrix",
"Q",
"using",
"Kabsch",
"algorithm",
"."
] | def kabsch_rotate(P, Q):
"""
Rotate matrix P unto matrix Q using Kabsch algorithm.
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
P : array
(N,D) matrix, where N is points and D is dimension,
rotated
"""
U = kabsch(P, Q)
# Rotate P
P = np.dot(P, U)
return P | [
"def",
"kabsch_rotate",
"(",
"P",
",",
"Q",
")",
":",
"U",
"=",
"kabsch",
"(",
"P",
",",
"Q",
")",
"# Rotate P",
"P",
"=",
"np",
".",
"dot",
"(",
"P",
",",
"U",
")",
"return",
"P"
] | https://github.com/IntelRealSense/librealsense/blob/c94410a420b74e5fb6a414bd12215c05ddd82b69/wrappers/python/examples/box_dimensioner_multicam/calculate_rmsd_kabsch.py#L52-L74 | |
trilinos/Trilinos | 6168be6dd51e35e1cd681e9c4b24433e709df140 | packages/kokkos-kernels/scripts/analysis/batched/pd.py | python | flop_lu | (n) | return 2.0/3*(n-1)**3 + (n-1)**2 + 1.0/3*(n-1) + n**2/2.0 + n/2.0 | # of + and * for LU of nxn matrix. | # of + and * for LU of nxn matrix. | [
"#",
"of",
"+",
"and",
"*",
"for",
"LU",
"of",
"nxn",
"matrix",
"."
] | def flop_lu(n):
"# of + and * for LU of nxn matrix."
return 2.0/3*(n-1)**3 + (n-1)**2 + 1.0/3*(n-1) + n**2/2.0 + n/2.0 | [
"def",
"flop_lu",
"(",
"n",
")",
":",
"return",
"2.0",
"/",
"3",
"*",
"(",
"n",
"-",
"1",
")",
"**",
"3",
"+",
"(",
"n",
"-",
"1",
")",
"**",
"2",
"+",
"1.0",
"/",
"3",
"*",
"(",
"n",
"-",
"1",
")",
"+",
"n",
"**",
"2",
"/",
"2.0",
"+",
"n",
"/",
"2.0"
] | https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/kokkos-kernels/scripts/analysis/batched/pd.py#L88-L90 | |
psi4/psi4 | be533f7f426b6ccc263904e55122899b16663395 | psi4/driver/qcdb/cfour.py | python | harvest_zmat | (zmat) | return mol | Parses the contents of the Cfour ZMAT file into array and
coordinate information. The coordinate info is converted into a
rather dinky Molecule (no fragment, but does read charge, mult,
unit). Return qcdb.Molecule. Written for findif zmat* where
geometry always Cartesian and Bohr. | Parses the contents of the Cfour ZMAT file into array and
coordinate information. The coordinate info is converted into a
rather dinky Molecule (no fragment, but does read charge, mult,
unit). Return qcdb.Molecule. Written for findif zmat* where
geometry always Cartesian and Bohr. | [
"Parses",
"the",
"contents",
"of",
"the",
"Cfour",
"ZMAT",
"file",
"into",
"array",
"and",
"coordinate",
"information",
".",
"The",
"coordinate",
"info",
"is",
"converted",
"into",
"a",
"rather",
"dinky",
"Molecule",
"(",
"no",
"fragment",
"but",
"does",
"read",
"charge",
"mult",
"unit",
")",
".",
"Return",
"qcdb",
".",
"Molecule",
".",
"Written",
"for",
"findif",
"zmat",
"*",
"where",
"geometry",
"always",
"Cartesian",
"and",
"Bohr",
"."
] | def harvest_zmat(zmat):
"""Parses the contents of the Cfour ZMAT file into array and
coordinate information. The coordinate info is converted into a
rather dinky Molecule (no fragment, but does read charge, mult,
unit). Return qcdb.Molecule. Written for findif zmat* where
geometry always Cartesian and Bohr.
"""
zmat = zmat.splitlines()[1:] # skip comment line
Nat = 0
readCoord = True
isBohr = ''
charge = 0
mult = 1
molxyz = ''
cgeom = []
for line in zmat:
if line.strip() == '':
readCoord = False
elif readCoord:
lline = line.split()
molxyz += line + '\n'
Nat += 1
else:
if line.find('CHARGE') > -1:
idx = line.find('CHARGE')
charge = line[idx + 7:]
idxc = charge.find(',')
if idxc > -1:
charge = charge[:idxc]
charge = int(charge)
if line.find('MULTIPLICITY') > -1:
idx = line.find('MULTIPLICITY')
mult = line[idx + 13:]
idxc = mult.find(',')
if idxc > -1:
mult = mult[:idxc]
mult = int(mult)
if line.find('UNITS=BOHR') > -1:
isBohr = ' bohr'
molxyz = '%d%s\n%d %d\n' % (Nat, isBohr, charge, mult) + molxyz
mol = Molecule.from_string(molxyz, dtype='xyz+', fix_com=True, fix_orientation=True)
return mol | [
"def",
"harvest_zmat",
"(",
"zmat",
")",
":",
"zmat",
"=",
"zmat",
".",
"splitlines",
"(",
")",
"[",
"1",
":",
"]",
"# skip comment line",
"Nat",
"=",
"0",
"readCoord",
"=",
"True",
"isBohr",
"=",
"''",
"charge",
"=",
"0",
"mult",
"=",
"1",
"molxyz",
"=",
"''",
"cgeom",
"=",
"[",
"]",
"for",
"line",
"in",
"zmat",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"''",
":",
"readCoord",
"=",
"False",
"elif",
"readCoord",
":",
"lline",
"=",
"line",
".",
"split",
"(",
")",
"molxyz",
"+=",
"line",
"+",
"'\\n'",
"Nat",
"+=",
"1",
"else",
":",
"if",
"line",
".",
"find",
"(",
"'CHARGE'",
")",
">",
"-",
"1",
":",
"idx",
"=",
"line",
".",
"find",
"(",
"'CHARGE'",
")",
"charge",
"=",
"line",
"[",
"idx",
"+",
"7",
":",
"]",
"idxc",
"=",
"charge",
".",
"find",
"(",
"','",
")",
"if",
"idxc",
">",
"-",
"1",
":",
"charge",
"=",
"charge",
"[",
":",
"idxc",
"]",
"charge",
"=",
"int",
"(",
"charge",
")",
"if",
"line",
".",
"find",
"(",
"'MULTIPLICITY'",
")",
">",
"-",
"1",
":",
"idx",
"=",
"line",
".",
"find",
"(",
"'MULTIPLICITY'",
")",
"mult",
"=",
"line",
"[",
"idx",
"+",
"13",
":",
"]",
"idxc",
"=",
"mult",
".",
"find",
"(",
"','",
")",
"if",
"idxc",
">",
"-",
"1",
":",
"mult",
"=",
"mult",
"[",
":",
"idxc",
"]",
"mult",
"=",
"int",
"(",
"mult",
")",
"if",
"line",
".",
"find",
"(",
"'UNITS=BOHR'",
")",
">",
"-",
"1",
":",
"isBohr",
"=",
"' bohr'",
"molxyz",
"=",
"'%d%s\\n%d %d\\n'",
"%",
"(",
"Nat",
",",
"isBohr",
",",
"charge",
",",
"mult",
")",
"+",
"molxyz",
"mol",
"=",
"Molecule",
".",
"from_string",
"(",
"molxyz",
",",
"dtype",
"=",
"'xyz+'",
",",
"fix_com",
"=",
"True",
",",
"fix_orientation",
"=",
"True",
")",
"return",
"mol"
] | https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/cfour.py#L731-L775 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/markdown/extensions/__init__.py | python | Extension.setConfig | (self, key, value) | Set a config setting for `key` with the given `value`. | Set a config setting for `key` with the given `value`. | [
"Set",
"a",
"config",
"setting",
"for",
"key",
"with",
"the",
"given",
"value",
"."
] | def setConfig(self, key, value):
""" Set a config setting for `key` with the given `value`. """
self.config[key][0] = value | [
"def",
"setConfig",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"config",
"[",
"key",
"]",
"[",
"0",
"]",
"=",
"value"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/markdown/extensions/__init__.py#L66-L68 | ||
llvm/llvm-project | ffa6262cb4e2a335d26416fad39a581b4f98c5f4 | openmp/runtime/tools/summarizeStats.py | python | readCounters | (f) | return readData(f) | This can be just the same! | This can be just the same! | [
"This",
"can",
"be",
"just",
"the",
"same!"
] | def readCounters(f):
"""This can be just the same!"""
return readData(f) | [
"def",
"readCounters",
"(",
"f",
")",
":",
"return",
"readData",
"(",
"f",
")"
] | https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/openmp/runtime/tools/summarizeStats.py#L133-L135 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/grid.py | python | GridCellWorker.SetParameters | (*args, **kwargs) | return _grid.GridCellWorker_SetParameters(*args, **kwargs) | SetParameters(self, String params) | SetParameters(self, String params) | [
"SetParameters",
"(",
"self",
"String",
"params",
")"
] | def SetParameters(*args, **kwargs):
"""SetParameters(self, String params)"""
return _grid.GridCellWorker_SetParameters(*args, **kwargs) | [
"def",
"SetParameters",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_grid",
".",
"GridCellWorker_SetParameters",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/grid.py#L95-L97 | |
perilouswithadollarsign/cstrike15_src | f82112a2388b841d72cb62ca48ab1846dfcc11c8 | thirdparty/protobuf-2.5.0/python/google/protobuf/text_format.py | python | _Tokenizer.ConsumeByteString | (self) | return "".join(list) | Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed. | Consumes a byte array value. | [
"Consumes",
"a",
"byte",
"array",
"value",
"."
] | def ConsumeByteString(self):
"""Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed.
"""
list = [self._ConsumeSingleByteString()]
while len(self.token) > 0 and self.token[0] in ('\'', '"'):
list.append(self._ConsumeSingleByteString())
return "".join(list) | [
"def",
"ConsumeByteString",
"(",
"self",
")",
":",
"list",
"=",
"[",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
"]",
"while",
"len",
"(",
"self",
".",
"token",
")",
">",
"0",
"and",
"self",
".",
"token",
"[",
"0",
"]",
"in",
"(",
"'\\''",
",",
"'\"'",
")",
":",
"list",
".",
"append",
"(",
"self",
".",
"_ConsumeSingleByteString",
"(",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"list",
")"
] | https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/text_format.py#L506-L518 | |
wallix/redemption | fb4ceefb39e11e1ae250bce17e878e1dc7d195d2 | tools/sesman/sesmanworker/parsers.py | python | resolve_scenario_account | (enginei, field, param, force_device=True, default=None) | return acc_infos.get(field.lower()) | Get password or login field from scenario account
:param enginei: engine interface
must implement:
- get_target_login_info
- get_username
- get_account_infos_by_type
:param field: str
requested field of scenario account, must be "password" or "login"
:param param: str
string representing scenario account:
string format is account_name@domain_name[@device_name]
each part can contain placeholder <attribute>
:param force_device: bool
force device_name part in param to match current device
True by default
:param default: bool
default value to be returned in case resolution fails;
if set to None, param will be returned
True by default
:return: requested field (password or login) of scenario account
if param is not a scenario account, returns its value
:rtype: str | Get password or login field from scenario account | [
"Get",
"password",
"or",
"login",
"field",
"from",
"scenario",
"account"
] | def resolve_scenario_account(enginei, field, param, force_device=True, default=None):
"""
Get password or login field from scenario account
:param enginei: engine interface
must implement:
- get_target_login_info
- get_username
- get_account_infos_by_type
:param field: str
requested field of scenario account, must be "password" or "login"
:param param: str
string representing scenario account:
string format is account_name@domain_name[@device_name]
each part can contain placeholder <attribute>
:param force_device: bool
force device_name part in param to match current device
True by default
:param default: bool
default value to be returned in case resolution fails;
if set to None, param will be returned
True by default
:return: requested field (password or login) of scenario account
if param is not a scenario account, returns its value
:rtype: str
"""
if default is None:
default = param
session_infos = enginei.get_target_login_info().get_target_dict()
session_infos["user"] = enginei.get_username()
acc_tuple = parse_account(param, session_infos, force_device)
if acc_tuple is None:
return default
acc_infos = enginei.get_account_infos_by_type(
*acc_tuple,
account_type="scenario"
)
if acc_infos is None:
Logger().debug(
"Error: Unable to retrieve account info from '%s'" %
param
)
return default
return acc_infos.get(field.lower()) | [
"def",
"resolve_scenario_account",
"(",
"enginei",
",",
"field",
",",
"param",
",",
"force_device",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"param",
"session_infos",
"=",
"enginei",
".",
"get_target_login_info",
"(",
")",
".",
"get_target_dict",
"(",
")",
"session_infos",
"[",
"\"user\"",
"]",
"=",
"enginei",
".",
"get_username",
"(",
")",
"acc_tuple",
"=",
"parse_account",
"(",
"param",
",",
"session_infos",
",",
"force_device",
")",
"if",
"acc_tuple",
"is",
"None",
":",
"return",
"default",
"acc_infos",
"=",
"enginei",
".",
"get_account_infos_by_type",
"(",
"*",
"acc_tuple",
",",
"account_type",
"=",
"\"scenario\"",
")",
"if",
"acc_infos",
"is",
"None",
":",
"Logger",
"(",
")",
".",
"debug",
"(",
"\"Error: Unable to retrieve account info from '%s'\"",
"%",
"param",
")",
"return",
"default",
"return",
"acc_infos",
".",
"get",
"(",
"field",
".",
"lower",
"(",
")",
")"
] | https://github.com/wallix/redemption/blob/fb4ceefb39e11e1ae250bce17e878e1dc7d195d2/tools/sesman/sesmanworker/parsers.py#L68-L112 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/tlslite/tlslite/utils/cipherfactory.py | python | createAES | (key, IV, implList=None) | Create a new AES object.
@type key: str
@param key: A 16, 24, or 32 byte string.
@type IV: str
@param IV: A 16 byte string
@rtype: L{tlslite.utils.AES}
@return: An AES object. | Create a new AES object. | [
"Create",
"a",
"new",
"AES",
"object",
"."
] | def createAES(key, IV, implList=None):
"""Create a new AES object.
@type key: str
@param key: A 16, 24, or 32 byte string.
@type IV: str
@param IV: A 16 byte string
@rtype: L{tlslite.utils.AES}
@return: An AES object.
"""
if implList == None:
implList = ["cryptlib", "openssl", "pycrypto", "python"]
for impl in implList:
if impl == "cryptlib" and cryptomath.cryptlibpyLoaded:
return Cryptlib_AES.new(key, 2, IV)
elif impl == "openssl" and cryptomath.m2cryptoLoaded:
return OpenSSL_AES.new(key, 2, IV)
elif impl == "pycrypto" and cryptomath.pycryptoLoaded:
return PyCrypto_AES.new(key, 2, IV)
elif impl == "python":
return Python_AES.new(key, 2, IV)
raise NotImplementedError() | [
"def",
"createAES",
"(",
"key",
",",
"IV",
",",
"implList",
"=",
"None",
")",
":",
"if",
"implList",
"==",
"None",
":",
"implList",
"=",
"[",
"\"cryptlib\"",
",",
"\"openssl\"",
",",
"\"pycrypto\"",
",",
"\"python\"",
"]",
"for",
"impl",
"in",
"implList",
":",
"if",
"impl",
"==",
"\"cryptlib\"",
"and",
"cryptomath",
".",
"cryptlibpyLoaded",
":",
"return",
"Cryptlib_AES",
".",
"new",
"(",
"key",
",",
"2",
",",
"IV",
")",
"elif",
"impl",
"==",
"\"openssl\"",
"and",
"cryptomath",
".",
"m2cryptoLoaded",
":",
"return",
"OpenSSL_AES",
".",
"new",
"(",
"key",
",",
"2",
",",
"IV",
")",
"elif",
"impl",
"==",
"\"pycrypto\"",
"and",
"cryptomath",
".",
"pycryptoLoaded",
":",
"return",
"PyCrypto_AES",
".",
"new",
"(",
"key",
",",
"2",
",",
"IV",
")",
"elif",
"impl",
"==",
"\"python\"",
":",
"return",
"Python_AES",
".",
"new",
"(",
"key",
",",
"2",
",",
"IV",
")",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/tlslite/tlslite/utils/cipherfactory.py#L34-L58 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/peacock/ExodusViewer/plugins/ContourPlugin.py | python | ContourPlugin._callbackContourLevels | (self) | Called when contour levels are changed. | Called when contour levels are changed. | [
"Called",
"when",
"contour",
"levels",
"are",
"changed",
"."
] | def _callbackContourLevels(self):
"""
Called when contour levels are changed.
"""
self.store(self.ContourLevels)
self.updateOptions()
self.windowRequiresUpdate.emit() | [
"def",
"_callbackContourLevels",
"(",
"self",
")",
":",
"self",
".",
"store",
"(",
"self",
".",
"ContourLevels",
")",
"self",
".",
"updateOptions",
"(",
")",
"self",
".",
"windowRequiresUpdate",
".",
"emit",
"(",
")"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/ExodusViewer/plugins/ContourPlugin.py#L174-L180 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_cocoa/xrc.py | python | XmlResourceHandler.GetParamValue | (*args, **kwargs) | return _xrc.XmlResourceHandler_GetParamValue(*args, **kwargs) | GetParamValue(self, String param) -> String | GetParamValue(self, String param) -> String | [
"GetParamValue",
"(",
"self",
"String",
"param",
")",
"-",
">",
"String"
] | def GetParamValue(*args, **kwargs):
"""GetParamValue(self, String param) -> String"""
return _xrc.XmlResourceHandler_GetParamValue(*args, **kwargs) | [
"def",
"GetParamValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_xrc",
".",
"XmlResourceHandler_GetParamValue",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/xrc.py#L643-L645 | |
llvm-mirror/lldb | d01083a850f577b85501a0902b52fd0930de72c7 | third_party/Python/module/pexpect-4.6/pexpect/exceptions.py | python | ExceptionPexpect.get_trace | (self) | return ''.join(tblist) | This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. | This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. | [
"This",
"returns",
"an",
"abbreviated",
"stack",
"trace",
"with",
"lines",
"that",
"only",
"concern",
"the",
"caller",
".",
"In",
"other",
"words",
"the",
"stack",
"trace",
"inside",
"the",
"Pexpect",
"module",
"is",
"not",
"included",
"."
] | def get_trace(self):
'''This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. '''
tblist = traceback.extract_tb(sys.exc_info()[2])
tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
and ('pexpect/expect' not in item[0])]
tblist = traceback.format_list(tblist)
return ''.join(tblist) | [
"def",
"get_trace",
"(",
"self",
")",
":",
"tblist",
"=",
"traceback",
".",
"extract_tb",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
")",
"tblist",
"=",
"[",
"item",
"for",
"item",
"in",
"tblist",
"if",
"(",
"'pexpect/__init__'",
"not",
"in",
"item",
"[",
"0",
"]",
")",
"and",
"(",
"'pexpect/expect'",
"not",
"in",
"item",
"[",
"0",
"]",
")",
"]",
"tblist",
"=",
"traceback",
".",
"format_list",
"(",
"tblist",
")",
"return",
"''",
".",
"join",
"(",
"tblist",
")"
] | https://github.com/llvm-mirror/lldb/blob/d01083a850f577b85501a0902b52fd0930de72c7/third_party/Python/module/pexpect-4.6/pexpect/exceptions.py#L17-L26 | |
rsummers11/CADLab | 976ed959a0b5208bb4173127a7ef732ac73a9b6f | lesion_detector_3DCE/rcnn/symbol/proposal.py | python | ProposalOperator._filter_boxes | (boxes, min_size) | return keep | Remove all boxes with any side smaller than min_size | Remove all boxes with any side smaller than min_size | [
"Remove",
"all",
"boxes",
"with",
"any",
"side",
"smaller",
"than",
"min_size"
] | def _filter_boxes(boxes, min_size):
""" Remove all boxes with any side smaller than min_size """
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
keep = np.where((ws >= min_size) & (hs >= min_size))[0]
return keep | [
"def",
"_filter_boxes",
"(",
"boxes",
",",
"min_size",
")",
":",
"ws",
"=",
"boxes",
"[",
":",
",",
"2",
"]",
"-",
"boxes",
"[",
":",
",",
"0",
"]",
"+",
"1",
"hs",
"=",
"boxes",
"[",
":",
",",
"3",
"]",
"-",
"boxes",
"[",
":",
",",
"1",
"]",
"+",
"1",
"keep",
"=",
"np",
".",
"where",
"(",
"(",
"ws",
">=",
"min_size",
")",
"&",
"(",
"hs",
">=",
"min_size",
")",
")",
"[",
"0",
"]",
"return",
"keep"
] | https://github.com/rsummers11/CADLab/blob/976ed959a0b5208bb4173127a7ef732ac73a9b6f/lesion_detector_3DCE/rcnn/symbol/proposal.py#L168-L173 | |
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/richtext.py | python | RichTextCtrl.BeginItalic | (*args, **kwargs) | return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs) | BeginItalic(self) -> bool
Begin using italic | BeginItalic(self) -> bool | [
"BeginItalic",
"(",
"self",
")",
"-",
">",
"bool"
] | def BeginItalic(*args, **kwargs):
"""
BeginItalic(self) -> bool
Begin using italic
"""
return _richtext.RichTextCtrl_BeginItalic(*args, **kwargs) | [
"def",
"BeginItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_richtext",
".",
"RichTextCtrl_BeginItalic",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L3355-L3361 | |
pmq20/node-packer | 12c46c6e44fbc14d9ee645ebd17d5296b324f7e0 | lts/deps/v8/third_party/jinja2/environment.py | python | Environment.join_path | (self, template, parent) | return template | Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here. | Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name. | [
"Join",
"a",
"template",
"with",
"the",
"parent",
".",
"By",
"default",
"all",
"the",
"lookups",
"are",
"relative",
"to",
"the",
"loader",
"root",
"so",
"this",
"method",
"returns",
"the",
"template",
"parameter",
"unchanged",
"but",
"if",
"the",
"paths",
"should",
"be",
"relative",
"to",
"the",
"parent",
"template",
"this",
"function",
"can",
"be",
"used",
"to",
"calculate",
"the",
"real",
"template",
"name",
"."
] | def join_path(self, template, parent):
"""Join a template with the parent. By default all the lookups are
relative to the loader root so this method returns the `template`
parameter unchanged, but if the paths should be relative to the
parent template, this function can be used to calculate the real
template name.
Subclasses may override this method and implement template path
joining here.
"""
return template | [
"def",
"join_path",
"(",
"self",
",",
"template",
",",
"parent",
")",
":",
"return",
"template"
] | https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/v8/third_party/jinja2/environment.py#L782-L792 | |
eclipse/sumo | 7132a9b8b6eea734bdec38479026b4d8c4336d03 | tools/contributed/sumopy/plugins/mapmatching/wxgui.py | python | WxGui.on_plot_connectionresults | (self, event=None) | Plot connection results of route analysis in Matplotlib plotting envitonment. | Plot connection results of route analysis in Matplotlib plotting envitonment. | [
"Plot",
"connection",
"results",
"of",
"route",
"analysis",
"in",
"Matplotlib",
"plotting",
"envitonment",
"."
] | def on_plot_connectionresults(self, event=None):
"""
Plot connection results of route analysis in Matplotlib plotting envitonment.
"""
if is_mpl:
resultplotter = results_mpl.ConnectionresultPlotter(self._results,
logger=self._mainframe.get_logger()
)
dlg = results_mpl.ResultDialog(self._mainframe, resultplotter)
dlg.CenterOnScreen()
# this does not return until the dialog is closed.
val = dlg.ShowModal()
# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL
# print ' status =',dlg.get_status()
if dlg.get_status() != 'success': # val == wx.ID_CANCEL:
# print ">>>>>>>>>Unsuccessful\n"
dlg.Destroy()
if dlg.get_status() == 'success':
# print ">>>>>>>>>successful\n"
# apply current widget values to scenario instance
dlg.apply()
dlg.Destroy() | [
"def",
"on_plot_connectionresults",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"is_mpl",
":",
"resultplotter",
"=",
"results_mpl",
".",
"ConnectionresultPlotter",
"(",
"self",
".",
"_results",
",",
"logger",
"=",
"self",
".",
"_mainframe",
".",
"get_logger",
"(",
")",
")",
"dlg",
"=",
"results_mpl",
".",
"ResultDialog",
"(",
"self",
".",
"_mainframe",
",",
"resultplotter",
")",
"dlg",
".",
"CenterOnScreen",
"(",
")",
"# this does not return until the dialog is closed.",
"val",
"=",
"dlg",
".",
"ShowModal",
"(",
")",
"# print ' val,val == wx.ID_OK',val,wx.ID_OK,wx.ID_CANCEL,val == wx.ID_CANCEL",
"# print ' status =',dlg.get_status()",
"if",
"dlg",
".",
"get_status",
"(",
")",
"!=",
"'success'",
":",
"# val == wx.ID_CANCEL:",
"# print \">>>>>>>>>Unsuccessful\\n\"",
"dlg",
".",
"Destroy",
"(",
")",
"if",
"dlg",
".",
"get_status",
"(",
")",
"==",
"'success'",
":",
"# print \">>>>>>>>>successful\\n\"",
"# apply current widget values to scenario instance",
"dlg",
".",
"apply",
"(",
")",
"dlg",
".",
"Destroy",
"(",
")"
] | https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/plugins/mapmatching/wxgui.py#L818-L842 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/metric/metrics.py | python | Accuracy.name | (self) | return self._name | Return name of metric instance. | Return name of metric instance. | [
"Return",
"name",
"of",
"metric",
"instance",
"."
] | def name(self):
"""
Return name of metric instance.
"""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/metric/metrics.py#L322-L326 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py | python | RFC2217Serial.fromURL | (self, url) | return (host, port) | extract host and port from an URL string | extract host and port from an URL string | [
"extract",
"host",
"and",
"port",
"from",
"an",
"URL",
"string"
] | def fromURL(self, url):
"""extract host and port from an URL string"""
if url.lower().startswith("rfc2217://"): url = url[10:]
try:
# is there a "path" (our options)?
if '/' in url:
# cut away options
url, options = url.split('/', 1)
# process options now, directly altering self
for option in options.split('/'):
if '=' in option:
option, value = option.split('=', 1)
else:
value = None
if option == 'logging':
logging.basicConfig() # XXX is that good to call it here?
self.logger = logging.getLogger('pySerial.rfc2217')
self.logger.setLevel(LOGGER_LEVELS[value])
self.logger.debug('enabled logging')
elif option == 'ign_set_control':
self._ignore_set_control_answer = True
elif option == 'poll_modem':
self._poll_modem_state = True
elif option == 'timeout':
self._network_timeout = float(value)
else:
raise ValueError('unknown option: %r' % (option,))
# get host and port
host, port = url.split(':', 1) # may raise ValueError because of unpacking
port = int(port) # and this if it's not a number
if not 0 <= port < 65536: raise ValueError("port not in range 0...65535")
except ValueError, e:
raise SerialException('expected a string in the form "[rfc2217://]<host>:<port>[/option[/option...]]": %s' % e)
return (host, port) | [
"def",
"fromURL",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"rfc2217://\"",
")",
":",
"url",
"=",
"url",
"[",
"10",
":",
"]",
"try",
":",
"# is there a \"path\" (our options)?",
"if",
"'/'",
"in",
"url",
":",
"# cut away options",
"url",
",",
"options",
"=",
"url",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"# process options now, directly altering self",
"for",
"option",
"in",
"options",
".",
"split",
"(",
"'/'",
")",
":",
"if",
"'='",
"in",
"option",
":",
"option",
",",
"value",
"=",
"option",
".",
"split",
"(",
"'='",
",",
"1",
")",
"else",
":",
"value",
"=",
"None",
"if",
"option",
"==",
"'logging'",
":",
"logging",
".",
"basicConfig",
"(",
")",
"# XXX is that good to call it here?",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'pySerial.rfc2217'",
")",
"self",
".",
"logger",
".",
"setLevel",
"(",
"LOGGER_LEVELS",
"[",
"value",
"]",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'enabled logging'",
")",
"elif",
"option",
"==",
"'ign_set_control'",
":",
"self",
".",
"_ignore_set_control_answer",
"=",
"True",
"elif",
"option",
"==",
"'poll_modem'",
":",
"self",
".",
"_poll_modem_state",
"=",
"True",
"elif",
"option",
"==",
"'timeout'",
":",
"self",
".",
"_network_timeout",
"=",
"float",
"(",
"value",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown option: %r'",
"%",
"(",
"option",
",",
")",
")",
"# get host and port",
"host",
",",
"port",
"=",
"url",
".",
"split",
"(",
"':'",
",",
"1",
")",
"# may raise ValueError because of unpacking",
"port",
"=",
"int",
"(",
"port",
")",
"# and this if it's not a number",
"if",
"not",
"0",
"<=",
"port",
"<",
"65536",
":",
"raise",
"ValueError",
"(",
"\"port not in range 0...65535\"",
")",
"except",
"ValueError",
",",
"e",
":",
"raise",
"SerialException",
"(",
"'expected a string in the form \"[rfc2217://]<host>:<port>[/option[/option...]]\": %s'",
"%",
"e",
")",
"return",
"(",
"host",
",",
"port",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyserial/serial/rfc2217.py#L526-L559 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py | python | VersionControl.get_src_requirement | (cls, repo_dir, project_name) | return req | Return the requirement string to use to redownload the files
currently at the given repository directory.
Args:
project_name: the (unescaped) project name.
The return value has a form similar to the following:
{repository_url}@{revision}#egg={project_name} | [] | def get_src_requirement(cls, repo_dir, project_name):
# type: (str, str) -> str
"""
Return the requirement string to use to redownload the files
currently at the given repository directory.
Args:
project_name: the (unescaped) project name.
The return value has a form similar to the following:
{repository_url}@{revision}#egg={project_name}
"""
repo_url = cls.get_remote_url(repo_dir)
if cls.should_add_vcs_url_prefix(repo_url):
repo_url = f'{cls.name}+{repo_url}'
revision = cls.get_requirement_revision(repo_dir)
subdir = cls.get_subdirectory(repo_dir)
req = make_vcs_requirement_url(repo_url, revision, project_name,
subdir=subdir)
return req | [
"def",
"get_src_requirement",
"(",
"cls",
",",
"repo_dir",
",",
"project_name",
")",
":",
"# type: (str, str) -> str",
"repo_url",
"=",
"cls",
".",
"get_remote_url",
"(",
"repo_dir",
")",
"if",
"cls",
".",
"should_add_vcs_url_prefix",
"(",
"repo_url",
")",
":",
"repo_url",
"=",
"f'{cls.name}+{repo_url}'",
"revision",
"=",
"cls",
".",
"get_requirement_revision",
"(",
"repo_dir",
")",
"subdir",
"=",
"cls",
".",
"get_subdirectory",
"(",
"repo_dir",
")",
"req",
"=",
"make_vcs_requirement_url",
"(",
"repo_url",
",",
"revision",
",",
"project_name",
",",
"subdir",
"=",
"subdir",
")",
"return",
"req"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py#L629-L675 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/generic.py | python | _recast_datetimelike_result | (result: DataFrame) | return result | If we have date/time like in the original, then coerce dates
as we are stacking can easily have object dtypes here.
Parameters
----------
result : DataFrame
Returns
-------
DataFrame
Notes
-----
- Assumes Groupby._selected_obj has ndim==2 and at least one
datetimelike column | If we have date/time like in the original, then coerce dates
as we are stacking can easily have object dtypes here. | [
"If",
"we",
"have",
"date",
"/",
"time",
"like",
"in",
"the",
"original",
"then",
"coerce",
"dates",
"as",
"we",
"are",
"stacking",
"can",
"easily",
"have",
"object",
"dtypes",
"here",
"."
] | def _recast_datetimelike_result(result: DataFrame) -> DataFrame:
"""
If we have date/time like in the original, then coerce dates
as we are stacking can easily have object dtypes here.
Parameters
----------
result : DataFrame
Returns
-------
DataFrame
Notes
-----
- Assumes Groupby._selected_obj has ndim==2 and at least one
datetimelike column
"""
result = result.copy()
obj_cols = [
idx
for idx in range(len(result.columns))
if is_object_dtype(result.dtypes.iloc[idx])
]
# See GH#26285
for n in obj_cols:
converted = maybe_convert_objects(
result.iloc[:, n].values, convert_numeric=False
)
result.iloc[:, n] = converted
return result | [
"def",
"_recast_datetimelike_result",
"(",
"result",
":",
"DataFrame",
")",
"->",
"DataFrame",
":",
"result",
"=",
"result",
".",
"copy",
"(",
")",
"obj_cols",
"=",
"[",
"idx",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"result",
".",
"columns",
")",
")",
"if",
"is_object_dtype",
"(",
"result",
".",
"dtypes",
".",
"iloc",
"[",
"idx",
"]",
")",
"]",
"# See GH#26285",
"for",
"n",
"in",
"obj_cols",
":",
"converted",
"=",
"maybe_convert_objects",
"(",
"result",
".",
"iloc",
"[",
":",
",",
"n",
"]",
".",
"values",
",",
"convert_numeric",
"=",
"False",
")",
"result",
".",
"iloc",
"[",
":",
",",
"n",
"]",
"=",
"converted",
"return",
"result"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/groupby/generic.py#L2057-L2090 | |
Slicer/SlicerGitSVNArchive | 65e92bb16c2b32ea47a1a66bee71f238891ee1ca | Base/Python/tpycl/tpycl.py | python | tpycl.tcl_putenv | (self, key, value) | Set environment variable | Set environment variable | [
"Set",
"environment",
"variable"
] | def tcl_putenv(self, key, value):
""" Set environment variable
"""
import re
self.tcl.eval("global env; set env(%s) \"%s\""%(key, re.escape(value))) | [
"def",
"tcl_putenv",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"import",
"re",
"self",
".",
"tcl",
".",
"eval",
"(",
"\"global env; set env(%s) \\\"%s\\\"\"",
"%",
"(",
"key",
",",
"re",
".",
"escape",
"(",
"value",
")",
")",
")"
] | https://github.com/Slicer/SlicerGitSVNArchive/blob/65e92bb16c2b32ea47a1a66bee71f238891ee1ca/Base/Python/tpycl/tpycl.py#L206-L210 | ||
BlzFans/wke | b0fa21158312e40c5fbd84682d643022b6c34a93 | cygwin/lib/python2.6/pkgutil.py | python | get_data | (package, resource) | return loader.get_data(resource_name) | Get a resource from a package.
This is a wrapper round the PEP 302 loader get_data API. The package
argument should be the name of a package, in standard module format
(foo.bar). The resource argument should be in the form of a relative
filename, using '/' as the path separator. The parent directory name '..'
is not allowed, and nor is a rooted name (starting with a '/').
The function returns a binary string, which is the contents of the
specified resource.
For packages located in the filesystem, which have already been imported,
this is the rough equivalent of
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
If the package cannot be located or loaded, or it uses a PEP 302 loader
which does not support get_data(), then None is returned. | Get a resource from a package. | [
"Get",
"a",
"resource",
"from",
"a",
"package",
"."
] | def get_data(package, resource):
"""Get a resource from a package.
This is a wrapper round the PEP 302 loader get_data API. The package
argument should be the name of a package, in standard module format
(foo.bar). The resource argument should be in the form of a relative
filename, using '/' as the path separator. The parent directory name '..'
is not allowed, and nor is a rooted name (starting with a '/').
The function returns a binary string, which is the contents of the
specified resource.
For packages located in the filesystem, which have already been imported,
this is the rough equivalent of
d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()
If the package cannot be located or loaded, or it uses a PEP 302 loader
which does not support get_data(), then None is returned.
"""
loader = get_loader(package)
if loader is None or not hasattr(loader, 'get_data'):
return None
mod = sys.modules.get(package) or loader.load_module(package)
if mod is None or not hasattr(mod, '__file__'):
return None
# Modify the resource name to be compatible with the loader.get_data
# signature - an os.path format "filename" starting with the dirname of
# the package's __file__
parts = resource.split('/')
parts.insert(0, os.path.dirname(mod.__file__))
resource_name = os.path.join(*parts)
return loader.get_data(resource_name) | [
"def",
"get_data",
"(",
"package",
",",
"resource",
")",
":",
"loader",
"=",
"get_loader",
"(",
"package",
")",
"if",
"loader",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"loader",
",",
"'get_data'",
")",
":",
"return",
"None",
"mod",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"package",
")",
"or",
"loader",
".",
"load_module",
"(",
"package",
")",
"if",
"mod",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"mod",
",",
"'__file__'",
")",
":",
"return",
"None",
"# Modify the resource name to be compatible with the loader.get_data",
"# signature - an os.path format \"filename\" starting with the dirname of",
"# the package's __file__",
"parts",
"=",
"resource",
".",
"split",
"(",
"'/'",
")",
"parts",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"mod",
".",
"__file__",
")",
")",
"resource_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"parts",
")",
"return",
"loader",
".",
"get_data",
"(",
"resource_name",
")"
] | https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pkgutil.py#L548-L583 | |
ChromiumWebApps/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | third_party/jinja2/filters.py | python | make_attrgetter | (environment, attribute) | return attrgetter | Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers. | Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers. | [
"Returns",
"a",
"callable",
"that",
"looks",
"up",
"the",
"given",
"attribute",
"from",
"a",
"passed",
"object",
"with",
"the",
"rules",
"of",
"the",
"environment",
".",
"Dots",
"are",
"allowed",
"to",
"access",
"attributes",
"of",
"attributes",
".",
"Integer",
"parts",
"in",
"paths",
"are",
"looked",
"up",
"as",
"integers",
"."
] | def make_attrgetter(environment, attribute):
"""Returns a callable that looks up the given attribute from a
passed object with the rules of the environment. Dots are allowed
to access attributes of attributes. Integer parts in paths are
looked up as integers.
"""
if not isinstance(attribute, string_types) \
or ('.' not in attribute and not attribute.isdigit()):
return lambda x: environment.getitem(x, attribute)
attribute = attribute.split('.')
def attrgetter(item):
for part in attribute:
if part.isdigit():
part = int(part)
item = environment.getitem(item, part)
return item
return attrgetter | [
"def",
"make_attrgetter",
"(",
"environment",
",",
"attribute",
")",
":",
"if",
"not",
"isinstance",
"(",
"attribute",
",",
"string_types",
")",
"or",
"(",
"'.'",
"not",
"in",
"attribute",
"and",
"not",
"attribute",
".",
"isdigit",
"(",
")",
")",
":",
"return",
"lambda",
"x",
":",
"environment",
".",
"getitem",
"(",
"x",
",",
"attribute",
")",
"attribute",
"=",
"attribute",
".",
"split",
"(",
"'.'",
")",
"def",
"attrgetter",
"(",
"item",
")",
":",
"for",
"part",
"in",
"attribute",
":",
"if",
"part",
".",
"isdigit",
"(",
")",
":",
"part",
"=",
"int",
"(",
"part",
")",
"item",
"=",
"environment",
".",
"getitem",
"(",
"item",
",",
"part",
")",
"return",
"item",
"return",
"attrgetter"
] | https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/jinja2/filters.py#L54-L70 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py | python | Context.set_tmp_ecdh | (self, curve) | Select a curve to use for ECDHE key exchange.
:param curve: A curve object to use as returned by either
:meth:`OpenSSL.crypto.get_elliptic_curve` or
:meth:`OpenSSL.crypto.get_elliptic_curves`.
:return: None | Select a curve to use for ECDHE key exchange. | [
"Select",
"a",
"curve",
"to",
"use",
"for",
"ECDHE",
"key",
"exchange",
"."
] | def set_tmp_ecdh(self, curve):
"""
Select a curve to use for ECDHE key exchange.
:param curve: A curve object to use as returned by either
:meth:`OpenSSL.crypto.get_elliptic_curve` or
:meth:`OpenSSL.crypto.get_elliptic_curves`.
:return: None
"""
_lib.SSL_CTX_set_tmp_ecdh(self._context, curve._to_EC_KEY()) | [
"def",
"set_tmp_ecdh",
"(",
"self",
",",
"curve",
")",
":",
"_lib",
".",
"SSL_CTX_set_tmp_ecdh",
"(",
"self",
".",
"_context",
",",
"curve",
".",
"_to_EC_KEY",
"(",
")",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/OpenSSL/SSL.py#L1174-L1184 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py | python | vander | (x, n=None) | return _vander | Masked values in the input array result in rows of zeros. | Masked values in the input array result in rows of zeros. | [
"Masked",
"values",
"in",
"the",
"input",
"array",
"result",
"in",
"rows",
"of",
"zeros",
"."
] | def vander(x, n=None):
"""
Masked values in the input array result in rows of zeros.
"""
_vander = np.vander(x, n)
m = getmask(x)
if m is not nomask:
_vander[m] = 0
return _vander | [
"def",
"vander",
"(",
"x",
",",
"n",
"=",
"None",
")",
":",
"_vander",
"=",
"np",
".",
"vander",
"(",
"x",
",",
"n",
")",
"m",
"=",
"getmask",
"(",
"x",
")",
"if",
"m",
"is",
"not",
"nomask",
":",
"_vander",
"[",
"m",
"]",
"=",
"0",
"return",
"_vander"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/ma/extras.py#L1882-L1891 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/code.py | python | InteractiveConsole.resetbuffer | (self) | Reset the input buffer. | Reset the input buffer. | [
"Reset",
"the",
"input",
"buffer",
"."
] | def resetbuffer(self):
"""Reset the input buffer."""
self.buffer = [] | [
"def",
"resetbuffer",
"(",
"self",
")",
":",
"self",
".",
"buffer",
"=",
"[",
"]"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/code.py#L184-L186 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/osx_carbon/_gdi.py | python | DC.GetImpl | (*args, **kwargs) | return _gdi_.DC_GetImpl(*args, **kwargs) | GetImpl(self) -> DCImpl | GetImpl(self) -> DCImpl | [
"GetImpl",
"(",
"self",
")",
"-",
">",
"DCImpl"
] | def GetImpl(*args, **kwargs):
"""GetImpl(self) -> DCImpl"""
return _gdi_.DC_GetImpl(*args, **kwargs) | [
"def",
"GetImpl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_gdi_",
".",
"DC_GetImpl",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3312-L3314 | |
wlanjie/AndroidFFmpeg | 7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf | tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/managers.py | python | Server.number_of_objects | (self, c) | return len(self.id_to_obj) - 1 | Number of shared objects | Number of shared objects | [
"Number",
"of",
"shared",
"objects"
] | def number_of_objects(self, c):
'''
Number of shared objects
'''
return len(self.id_to_obj) - 1 | [
"def",
"number_of_objects",
"(",
"self",
",",
"c",
")",
":",
"return",
"len",
"(",
"self",
".",
"id_to_obj",
")",
"-",
"1"
] | https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/multiprocessing/managers.py#L335-L339 | |
sdhash/sdhash | b9eff63e4e5867e910f41fd69032bbb1c94a2a5e | sdhash-ui/jinja2/optimizer.py | python | Optimizer.visit_If | (self, node) | return result | Eliminate dead code. | Eliminate dead code. | [
"Eliminate",
"dead",
"code",
"."
] | def visit_If(self, node):
"""Eliminate dead code."""
# do not optimize ifs that have a block inside so that it doesn't
# break super().
if node.find(nodes.Block) is not None:
return self.generic_visit(node)
try:
val = self.visit(node.test).as_const()
except nodes.Impossible:
return self.generic_visit(node)
if val:
body = node.body
else:
body = node.else_
result = []
for node in body:
result.extend(self.visit_list(node))
return result | [
"def",
"visit_If",
"(",
"self",
",",
"node",
")",
":",
"# do not optimize ifs that have a block inside so that it doesn't",
"# break super().",
"if",
"node",
".",
"find",
"(",
"nodes",
".",
"Block",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"try",
":",
"val",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"test",
")",
".",
"as_const",
"(",
")",
"except",
"nodes",
".",
"Impossible",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"if",
"val",
":",
"body",
"=",
"node",
".",
"body",
"else",
":",
"body",
"=",
"node",
".",
"else_",
"result",
"=",
"[",
"]",
"for",
"node",
"in",
"body",
":",
"result",
".",
"extend",
"(",
"self",
".",
"visit_list",
"(",
"node",
")",
")",
"return",
"result"
] | https://github.com/sdhash/sdhash/blob/b9eff63e4e5867e910f41fd69032bbb1c94a2a5e/sdhash-ui/jinja2/optimizer.py#L35-L52 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/multiindex.py | python | MultiIndex.append | (self, other) | return MultiIndex._concat(to_concat) | Append a collection of MultiIndex objects together
Parameters
----------
other : MultiIndex or list/tuple of MultiIndex objects
Returns
-------
appended : Index
Examples
--------
>>> import cudf
>>> idx1 = cudf.MultiIndex(
... levels=[[1, 2], ['blue', 'red']],
... codes=[[0, 0, 1, 1], [1, 0, 1, 0]]
... )
>>> idx2 = cudf.MultiIndex(
... levels=[[3, 4], ['blue', 'red']],
... codes=[[0, 0, 1, 1], [1, 0, 1, 0]]
... )
>>> idx1
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue')],
)
>>> idx2
MultiIndex([(3, 'red'),
(3, 'blue'),
(4, 'red'),
(4, 'blue')],
)
>>> idx1.append(idx2)
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue'),
(3, 'red'),
(3, 'blue'),
(4, 'red'),
(4, 'blue')],
) | Append a collection of MultiIndex objects together | [
"Append",
"a",
"collection",
"of",
"MultiIndex",
"objects",
"together"
] | def append(self, other):
"""
Append a collection of MultiIndex objects together
Parameters
----------
other : MultiIndex or list/tuple of MultiIndex objects
Returns
-------
appended : Index
Examples
--------
>>> import cudf
>>> idx1 = cudf.MultiIndex(
... levels=[[1, 2], ['blue', 'red']],
... codes=[[0, 0, 1, 1], [1, 0, 1, 0]]
... )
>>> idx2 = cudf.MultiIndex(
... levels=[[3, 4], ['blue', 'red']],
... codes=[[0, 0, 1, 1], [1, 0, 1, 0]]
... )
>>> idx1
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue')],
)
>>> idx2
MultiIndex([(3, 'red'),
(3, 'blue'),
(4, 'red'),
(4, 'blue')],
)
>>> idx1.append(idx2)
MultiIndex([(1, 'red'),
(1, 'blue'),
(2, 'red'),
(2, 'blue'),
(3, 'red'),
(3, 'blue'),
(4, 'red'),
(4, 'blue')],
)
"""
if isinstance(other, (list, tuple)):
to_concat = [self]
to_concat.extend(other)
else:
to_concat = [self, other]
for obj in to_concat:
if not isinstance(obj, MultiIndex):
raise TypeError(
f"all objects should be of type "
f"MultiIndex for MultiIndex.append, "
f"found object of type: {type(obj)}"
)
return MultiIndex._concat(to_concat) | [
"def",
"append",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"to_concat",
"=",
"[",
"self",
"]",
"to_concat",
".",
"extend",
"(",
"other",
")",
"else",
":",
"to_concat",
"=",
"[",
"self",
",",
"other",
"]",
"for",
"obj",
"in",
"to_concat",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"MultiIndex",
")",
":",
"raise",
"TypeError",
"(",
"f\"all objects should be of type \"",
"f\"MultiIndex for MultiIndex.append, \"",
"f\"found object of type: {type(obj)}\"",
")",
"return",
"MultiIndex",
".",
"_concat",
"(",
"to_concat",
")"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/multiindex.py#L1429-L1489 | |
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/tools/python3/src/Lib/email/__init__.py | python | message_from_file | (fp, *args, **kws) | return Parser(*args, **kws).parse(fp) | Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. | Read a file and parse its contents into a Message object model. | [
"Read",
"a",
"file",
"and",
"parse",
"its",
"contents",
"into",
"a",
"Message",
"object",
"model",
"."
] | def message_from_file(fp, *args, **kws):
"""Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from email.parser import Parser
return Parser(*args, **kws).parse(fp) | [
"def",
"message_from_file",
"(",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"email",
".",
"parser",
"import",
"Parser",
"return",
"Parser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
".",
"parse",
"(",
"fp",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/email/__init__.py#L48-L54 | |
facebookresearch/mvfst-rl | 778bc4259ae7277e67c2ead593a493845c93db83 | scripts/plotting/plot_sweep.py | python | get_label | (key) | Return a single string representing the given key (which has same format as in `get_kdims()`). | Return a single string representing the given key (which has same format as in `get_kdims()`). | [
"Return",
"a",
"single",
"string",
"representing",
"the",
"given",
"key",
"(",
"which",
"has",
"same",
"format",
"as",
"in",
"get_kdims",
"()",
")",
"."
] | def get_label(key):
"""
Return a single string representing the given key (which has same format as in `get_kdims()`).
"""
if key is None:
return "exp"
elif isinstance(key, str):
return key
else:
return "|".join(key) | [
"def",
"get_label",
"(",
"key",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"\"exp\"",
"elif",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"return",
"key",
"else",
":",
"return",
"\"|\"",
".",
"join",
"(",
"key",
")"
] | https://github.com/facebookresearch/mvfst-rl/blob/778bc4259ae7277e67c2ead593a493845c93db83/scripts/plotting/plot_sweep.py#L268-L277 | ||
idaholab/moose | 9eeebc65e098b4c30f8205fb41591fd5b61eb6ff | python/chigger/base/ColorMap.py | python | ColorMap.names | (self) | return names | Return all the possible colormap names. | Return all the possible colormap names. | [
"Return",
"all",
"the",
"possible",
"colormap",
"names",
"."
] | def names(self):
"""
Return all the possible colormap names.
"""
names = ['default']
if USE_MATPLOTLIB:
names += dir(cm)
names += self._data.keys()
return names | [
"def",
"names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"'default'",
"]",
"if",
"USE_MATPLOTLIB",
":",
"names",
"+=",
"dir",
"(",
"cm",
")",
"names",
"+=",
"self",
".",
"_data",
".",
"keys",
"(",
")",
"return",
"names"
] | https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/chigger/base/ColorMap.py#L71-L79 | |
windystrife/UnrealEngine_NVIDIAGameWorks | b50e6338a7c5b26374d66306ebc7807541ff815e | Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_pyio.py | python | RawIOBase.write | (self, b) | Write the given buffer to the IO stream.
Returns the number of bytes written, which may be less than len(b). | Write the given buffer to the IO stream. | [
"Write",
"the",
"given",
"buffer",
"to",
"the",
"IO",
"stream",
"."
] | def write(self, b):
"""Write the given buffer to the IO stream.
Returns the number of bytes written, which may be less than len(b).
"""
self._unsupported("write") | [
"def",
"write",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_unsupported",
"(",
"\"write\"",
")"
] | https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/_pyio.py#L580-L585 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/filedialog.py | python | askopenfilename | (**options) | return Open(**options).show() | Ask for a filename to open | Ask for a filename to open | [
"Ask",
"for",
"a",
"filename",
"to",
"open"
] | def askopenfilename(**options):
"Ask for a filename to open"
return Open(**options).show() | [
"def",
"askopenfilename",
"(",
"*",
"*",
"options",
")",
":",
"return",
"Open",
"(",
"*",
"*",
"options",
")",
".",
"show",
"(",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/filedialog.py#L372-L375 | |
gnuradio/gnuradio | 09c3c4fa4bfb1a02caac74cb5334dfe065391e3b | gr-utils/modtool/core/makeyaml.py | python | ModToolMakeYAML._make_grc_yaml_from_block_data | (self, params, iosig, blockname) | Take the return values from the parser and call the YAML
generator. Also, check the makefile if the .yml file is in there.
If necessary, add. | Take the return values from the parser and call the YAML
generator. Also, check the makefile if the .yml file is in there.
If necessary, add. | [
"Take",
"the",
"return",
"values",
"from",
"the",
"parser",
"and",
"call",
"the",
"YAML",
"generator",
".",
"Also",
"check",
"the",
"makefile",
"if",
"the",
".",
"yml",
"file",
"is",
"in",
"there",
".",
"If",
"necessary",
"add",
"."
] | def _make_grc_yaml_from_block_data(self, params, iosig, blockname):
""" Take the return values from the parser and call the YAML
generator. Also, check the makefile if the .yml file is in there.
If necessary, add. """
fname_yml = f'{self.info["modname"]}_{blockname}.block.yml'
path_to_yml = os.path.join('grc', fname_yml)
# Some adaptions for the GRC
for inout in ('in', 'out'):
if iosig[inout]['max_ports'] == '-1':
iosig[inout]['max_ports'] = f'$num_{inout}puts'
params.append({'key': f'num_{inout}puts',
'type': 'int',
'name': f'Num {inout}puts',
'default': '2',
'in_constructor': False})
file_exists = False
if os.path.isfile(path_to_yml):
if not self.info['yes']:
if not ask_yes_no('Overwrite existing GRC file?', False):
return
else:
file_exists = True
logger.warning("Warning: Overwriting existing GRC file.")
grc_generator = GRCYAMLGenerator(
modname=self.info['modname'],
blockname=blockname,
params=params,
iosig=iosig
)
grc_generator.save(path_to_yml)
if file_exists:
self.scm.mark_files_updated((path_to_yml,))
else:
self.scm.add_files((path_to_yml,))
if not self.skip_subdirs['grc']:
ed = CMakeFileEditor(self._file['cmgrc'])
if re.search(fname_yml, ed.cfile) is None and not ed.check_for_glob('*.yml'):
logger.info("Adding GRC bindings to grc/CMakeLists.txt...")
ed.append_value('install', fname_yml,
to_ignore_end='DESTINATION[^()]+')
ed.write()
self.scm.mark_files_updated(self._file['cmgrc']) | [
"def",
"_make_grc_yaml_from_block_data",
"(",
"self",
",",
"params",
",",
"iosig",
",",
"blockname",
")",
":",
"fname_yml",
"=",
"f'{self.info[\"modname\"]}_{blockname}.block.yml'",
"path_to_yml",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'grc'",
",",
"fname_yml",
")",
"# Some adaptions for the GRC",
"for",
"inout",
"in",
"(",
"'in'",
",",
"'out'",
")",
":",
"if",
"iosig",
"[",
"inout",
"]",
"[",
"'max_ports'",
"]",
"==",
"'-1'",
":",
"iosig",
"[",
"inout",
"]",
"[",
"'max_ports'",
"]",
"=",
"f'$num_{inout}puts'",
"params",
".",
"append",
"(",
"{",
"'key'",
":",
"f'num_{inout}puts'",
",",
"'type'",
":",
"'int'",
",",
"'name'",
":",
"f'Num {inout}puts'",
",",
"'default'",
":",
"'2'",
",",
"'in_constructor'",
":",
"False",
"}",
")",
"file_exists",
"=",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path_to_yml",
")",
":",
"if",
"not",
"self",
".",
"info",
"[",
"'yes'",
"]",
":",
"if",
"not",
"ask_yes_no",
"(",
"'Overwrite existing GRC file?'",
",",
"False",
")",
":",
"return",
"else",
":",
"file_exists",
"=",
"True",
"logger",
".",
"warning",
"(",
"\"Warning: Overwriting existing GRC file.\"",
")",
"grc_generator",
"=",
"GRCYAMLGenerator",
"(",
"modname",
"=",
"self",
".",
"info",
"[",
"'modname'",
"]",
",",
"blockname",
"=",
"blockname",
",",
"params",
"=",
"params",
",",
"iosig",
"=",
"iosig",
")",
"grc_generator",
".",
"save",
"(",
"path_to_yml",
")",
"if",
"file_exists",
":",
"self",
".",
"scm",
".",
"mark_files_updated",
"(",
"(",
"path_to_yml",
",",
")",
")",
"else",
":",
"self",
".",
"scm",
".",
"add_files",
"(",
"(",
"path_to_yml",
",",
")",
")",
"if",
"not",
"self",
".",
"skip_subdirs",
"[",
"'grc'",
"]",
":",
"ed",
"=",
"CMakeFileEditor",
"(",
"self",
".",
"_file",
"[",
"'cmgrc'",
"]",
")",
"if",
"re",
".",
"search",
"(",
"fname_yml",
",",
"ed",
".",
"cfile",
")",
"is",
"None",
"and",
"not",
"ed",
".",
"check_for_glob",
"(",
"'*.yml'",
")",
":",
"logger",
".",
"info",
"(",
"\"Adding GRC bindings to grc/CMakeLists.txt...\"",
")",
"ed",
".",
"append_value",
"(",
"'install'",
",",
"fname_yml",
",",
"to_ignore_end",
"=",
"'DESTINATION[^()]+'",
")",
"ed",
".",
"write",
"(",
")",
"self",
".",
"scm",
".",
"mark_files_updated",
"(",
"self",
".",
"_file",
"[",
"'cmgrc'",
"]",
")"
] | https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/core/makeyaml.py#L124-L165 | ||
google/syzygy | 8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5 | third_party/numpy/files/numpy/distutils/command/install.py | python | install.setuptools_run | (self) | The setuptools version of the .run() method.
We must pull in the entire code so we can override the level used in the
_getframe() call since we wrap this call by one more level. | The setuptools version of the .run() method. | [
"The",
"setuptools",
"version",
"of",
"the",
".",
"run",
"()",
"method",
"."
] | def setuptools_run(self):
""" The setuptools version of the .run() method.
We must pull in the entire code so we can override the level used in the
_getframe() call since we wrap this call by one more level.
"""
# Explicit request for old-style install? Just do it
if self.old_and_unmanageable or self.single_version_externally_managed:
return old_install_mod._install.run(self)
# Attempt to detect whether we were called from setup() or by another
# command. If we were called by setup(), our caller will be the
# 'run_command' method in 'distutils.dist', and *its* caller will be
# the 'run_commands' method. If we were called any other way, our
# immediate caller *might* be 'run_command', but it won't have been
# called by 'run_commands'. This is slightly kludgy, but seems to
# work.
#
caller = sys._getframe(3)
caller_module = caller.f_globals.get('__name__','')
caller_name = caller.f_code.co_name
if caller_module != 'distutils.dist' or caller_name!='run_commands':
# We weren't called from the command line or setup(), so we
# should run in backward-compatibility mode to support bdist_*
# commands.
old_install_mod._install.run(self)
else:
self.do_egg_install() | [
"def",
"setuptools_run",
"(",
"self",
")",
":",
"# Explicit request for old-style install? Just do it",
"if",
"self",
".",
"old_and_unmanageable",
"or",
"self",
".",
"single_version_externally_managed",
":",
"return",
"old_install_mod",
".",
"_install",
".",
"run",
"(",
"self",
")",
"# Attempt to detect whether we were called from setup() or by another",
"# command. If we were called by setup(), our caller will be the",
"# 'run_command' method in 'distutils.dist', and *its* caller will be",
"# the 'run_commands' method. If we were called any other way, our",
"# immediate caller *might* be 'run_command', but it won't have been",
"# called by 'run_commands'. This is slightly kludgy, but seems to",
"# work.",
"#",
"caller",
"=",
"sys",
".",
"_getframe",
"(",
"3",
")",
"caller_module",
"=",
"caller",
".",
"f_globals",
".",
"get",
"(",
"'__name__'",
",",
"''",
")",
"caller_name",
"=",
"caller",
".",
"f_code",
".",
"co_name",
"if",
"caller_module",
"!=",
"'distutils.dist'",
"or",
"caller_name",
"!=",
"'run_commands'",
":",
"# We weren't called from the command line or setup(), so we",
"# should run in backward-compatibility mode to support bdist_*",
"# commands.",
"old_install_mod",
".",
"_install",
".",
"run",
"(",
"self",
")",
"else",
":",
"self",
".",
"do_egg_install",
"(",
")"
] | https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/distutils/command/install.py#L23-L51 | ||
eomahony/Numberjack | 53fa9e994a36f881ffd320d8d04158097190aad8 | Numberjack/Decomp.py | python | MyConstraint.decompose | (self) | return (variable, constraint_list) | Decompose must return either a list containing a list of expressions | Decompose must return either a list containing a list of expressions | [
"Decompose",
"must",
"return",
"either",
"a",
"list",
"containing",
"a",
"list",
"of",
"expressions"
] | def decompose(self):
'''
Decompose must return either a list containing a list of expressions
'''
constraint_list = []
variable = Variable(0, 1)
return (variable, constraint_list) | [
"def",
"decompose",
"(",
"self",
")",
":",
"constraint_list",
"=",
"[",
"]",
"variable",
"=",
"Variable",
"(",
"0",
",",
"1",
")",
"return",
"(",
"variable",
",",
"constraint_list",
")"
] | https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/Decomp.py#L20-L28 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py | python | PathFinder._path_hooks | (cls, path) | Search sys.path_hooks for a finder for 'path'. | Search sys.path_hooks for a finder for 'path'. | [
"Search",
"sys",
".",
"path_hooks",
"for",
"a",
"finder",
"for",
"path",
"."
] | def _path_hooks(cls, path):
"""Search sys.path_hooks for a finder for 'path'."""
if sys.path_hooks is not None and not sys.path_hooks:
_warnings.warn('sys.path_hooks is empty', ImportWarning)
for hook in sys.path_hooks:
try:
return hook(path)
except ImportError:
continue
else:
return None | [
"def",
"_path_hooks",
"(",
"cls",
",",
"path",
")",
":",
"if",
"sys",
".",
"path_hooks",
"is",
"not",
"None",
"and",
"not",
"sys",
".",
"path_hooks",
":",
"_warnings",
".",
"warn",
"(",
"'sys.path_hooks is empty'",
",",
"ImportWarning",
")",
"for",
"hook",
"in",
"sys",
".",
"path_hooks",
":",
"try",
":",
"return",
"hook",
"(",
"path",
")",
"except",
"ImportError",
":",
"continue",
"else",
":",
"return",
"None"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/importlib/_bootstrap_external.py#L1191-L1201 | ||
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py | python | diag | (v, k=0) | Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal.
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.
Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]]) | Extract a diagonal or construct a diagonal array. | [
"Extract",
"a",
"diagonal",
"or",
"construct",
"a",
"diagonal",
"array",
"."
] | def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``numpy.diagonal`` if you use this
function to extract a diagonal and wish to write to the resulting array;
whether it returns a copy or a view depends on what version of numpy you
are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal.
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also
--------
diagonal : Return specified diagonals.
diagflat : Create a 2-D array with the flattened input as a diagonal.
trace : Sum along diagonals.
triu : Upper triangle of an array.
tril : Lower triangle of an array.
Examples
--------
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
"""
v = asanyarray(v)
s = v.shape
if len(s) == 1:
n = s[0]+abs(k)
res = zeros((n, n), v.dtype)
if k >= 0:
i = k
else:
i = (-k) * n
res[:n-k].flat[i::n+1] = v
return res
elif len(s) == 2:
return diagonal(v, k)
else:
raise ValueError("Input must be 1- or 2-d.") | [
"def",
"diag",
"(",
"v",
",",
"k",
"=",
"0",
")",
":",
"v",
"=",
"asanyarray",
"(",
"v",
")",
"s",
"=",
"v",
".",
"shape",
"if",
"len",
"(",
"s",
")",
"==",
"1",
":",
"n",
"=",
"s",
"[",
"0",
"]",
"+",
"abs",
"(",
"k",
")",
"res",
"=",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
",",
"v",
".",
"dtype",
")",
"if",
"k",
">=",
"0",
":",
"i",
"=",
"k",
"else",
":",
"i",
"=",
"(",
"-",
"k",
")",
"*",
"n",
"res",
"[",
":",
"n",
"-",
"k",
"]",
".",
"flat",
"[",
"i",
":",
":",
"n",
"+",
"1",
"]",
"=",
"v",
"return",
"res",
"elif",
"len",
"(",
"s",
")",
"==",
"2",
":",
"return",
"diagonal",
"(",
"v",
",",
"k",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Input must be 1- or 2-d.\"",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numpy/lib/twodim_base.py#L217-L285 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/tensor/manipulation.py | python | gather | (x, index, axis=None, name=None) | return out | Output is obtained by gathering entries of ``axis``
of ``x`` indexed by ``index`` and concatenate them together.
.. code-block:: text
Given:
x = [[1, 2],
[3, 4],
[5, 6]]
index = [1, 2]
axis=[0]
Then:
out = [[3, 4],
[5, 6]]
Args:
x (Tensor): The source input tensor with rank>=1. Supported data type is
int32, int64, float32, float64 and uint8 (only for CPU),
float16 (only for GPU).
index (Tensor): The index input tensor with rank=1. Data type is int32 or int64.
axis (Tensor|int, optional): The axis of input to be gathered, it's can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the ``axis`` is 0.
name (str, optional): The default value is None. Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name` .
Returns:
output (Tensor): The output is a tensor with the same rank as ``x``.
Examples:
.. code-block:: python
import paddle
input = paddle.to_tensor([[1,2],[3,4],[5,6]])
index = paddle.to_tensor([0,1])
output = paddle.gather(input, index, axis=0)
# expected output: [[1,2],[3,4]] | Output is obtained by gathering entries of ``axis``
of ``x`` indexed by ``index`` and concatenate them together. | [
"Output",
"is",
"obtained",
"by",
"gathering",
"entries",
"of",
"axis",
"of",
"x",
"indexed",
"by",
"index",
"and",
"concatenate",
"them",
"together",
"."
] | def gather(x, index, axis=None, name=None):
"""
Output is obtained by gathering entries of ``axis``
of ``x`` indexed by ``index`` and concatenate them together.
.. code-block:: text
Given:
x = [[1, 2],
[3, 4],
[5, 6]]
index = [1, 2]
axis=[0]
Then:
out = [[3, 4],
[5, 6]]
Args:
x (Tensor): The source input tensor with rank>=1. Supported data type is
int32, int64, float32, float64 and uint8 (only for CPU),
float16 (only for GPU).
index (Tensor): The index input tensor with rank=1. Data type is int32 or int64.
axis (Tensor|int, optional): The axis of input to be gathered, it's can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the ``axis`` is 0.
name (str, optional): The default value is None. Normally there is no need for user to set this property.
For more information, please refer to :ref:`api_guide_Name` .
Returns:
output (Tensor): The output is a tensor with the same rank as ``x``.
Examples:
.. code-block:: python
import paddle
input = paddle.to_tensor([[1,2],[3,4],[5,6]])
index = paddle.to_tensor([0,1])
output = paddle.gather(input, index, axis=0)
# expected output: [[1,2],[3,4]]
"""
if axis is None:
axis = 0
if in_dygraph_mode():
axis = axis.item() if isinstance(axis, paddle.Tensor) else axis
return _C_ops.gather(x, index, None, "axis", axis, "overwrite", False)
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'],
'gather')
check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather')
if isinstance(axis, Variable):
check_variable_and_dtype(axis, 'axis', ['int32', 'int64'], 'gather')
helper = LayerHelper('gather', **locals())
dtype = helper.input_dtype('x')
out = helper.create_variable_for_type_inference(dtype)
if not isinstance(axis, Variable):
helper.append_op(
type="gather",
inputs={"X": x,
"Index": index},
attrs={'axis': axis,
'overwrite': False},
outputs={"Out": out})
else:
helper.append_op(
type="gather",
inputs={"X": x,
"Index": index,
"Axis": axis},
attrs={"overwrite": False},
outputs={"Out": out})
return out | [
"def",
"gather",
"(",
"x",
",",
"index",
",",
"axis",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"0",
"if",
"in_dygraph_mode",
"(",
")",
":",
"axis",
"=",
"axis",
".",
"item",
"(",
")",
"if",
"isinstance",
"(",
"axis",
",",
"paddle",
".",
"Tensor",
")",
"else",
"axis",
"return",
"_C_ops",
".",
"gather",
"(",
"x",
",",
"index",
",",
"None",
",",
"\"axis\"",
",",
"axis",
",",
"\"overwrite\"",
",",
"False",
")",
"check_variable_and_dtype",
"(",
"x",
",",
"'x'",
",",
"[",
"'float16'",
",",
"'float32'",
",",
"'float64'",
",",
"'int32'",
",",
"'int64'",
",",
"'uint8'",
"]",
",",
"'gather'",
")",
"check_variable_and_dtype",
"(",
"index",
",",
"'index'",
",",
"[",
"'int32'",
",",
"'int64'",
"]",
",",
"'gather'",
")",
"if",
"isinstance",
"(",
"axis",
",",
"Variable",
")",
":",
"check_variable_and_dtype",
"(",
"axis",
",",
"'axis'",
",",
"[",
"'int32'",
",",
"'int64'",
"]",
",",
"'gather'",
")",
"helper",
"=",
"LayerHelper",
"(",
"'gather'",
",",
"*",
"*",
"locals",
"(",
")",
")",
"dtype",
"=",
"helper",
".",
"input_dtype",
"(",
"'x'",
")",
"out",
"=",
"helper",
".",
"create_variable_for_type_inference",
"(",
"dtype",
")",
"if",
"not",
"isinstance",
"(",
"axis",
",",
"Variable",
")",
":",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"gather\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"x",
",",
"\"Index\"",
":",
"index",
"}",
",",
"attrs",
"=",
"{",
"'axis'",
":",
"axis",
",",
"'overwrite'",
":",
"False",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"out",
"}",
")",
"else",
":",
"helper",
".",
"append_op",
"(",
"type",
"=",
"\"gather\"",
",",
"inputs",
"=",
"{",
"\"X\"",
":",
"x",
",",
"\"Index\"",
":",
"index",
",",
"\"Axis\"",
":",
"axis",
"}",
",",
"attrs",
"=",
"{",
"\"overwrite\"",
":",
"False",
"}",
",",
"outputs",
"=",
"{",
"\"Out\"",
":",
"out",
"}",
")",
"return",
"out"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/tensor/manipulation.py#L1350-L1430 | |
hanpfei/chromium-net | 392cc1fa3a8f92f42e4071ab6e674d8e0482f83f | tools/perf/metrics/memory.py | python | MemoryMetric.Stop | (self, page, tab) | Prepare the results for this page.
The results are the differences between the current histogram values
and the values when Start() was called. | Prepare the results for this page. | [
"Prepare",
"the",
"results",
"for",
"this",
"page",
"."
] | def Stop(self, page, tab):
"""Prepare the results for this page.
The results are the differences between the current histogram values
and the values when Start() was called.
"""
if not self._browser.supports_memory_metrics:
return
assert self._started, 'Must call Start() first'
for h in _HISTOGRAMS:
# Histogram data may not be available
if h['name'] not in self._histogram_start:
continue
histogram_data = histogram_util.GetHistogram(
h['type'], h['name'], tab)
self._histogram_delta[h['name']] = histogram_util.SubtractHistogram(
histogram_data, self._histogram_start[h['name']]) | [
"def",
"Stop",
"(",
"self",
",",
"page",
",",
"tab",
")",
":",
"if",
"not",
"self",
".",
"_browser",
".",
"supports_memory_metrics",
":",
"return",
"assert",
"self",
".",
"_started",
",",
"'Must call Start() first'",
"for",
"h",
"in",
"_HISTOGRAMS",
":",
"# Histogram data may not be available",
"if",
"h",
"[",
"'name'",
"]",
"not",
"in",
"self",
".",
"_histogram_start",
":",
"continue",
"histogram_data",
"=",
"histogram_util",
".",
"GetHistogram",
"(",
"h",
"[",
"'type'",
"]",
",",
"h",
"[",
"'name'",
"]",
",",
"tab",
")",
"self",
".",
"_histogram_delta",
"[",
"h",
"[",
"'name'",
"]",
"]",
"=",
"histogram_util",
".",
"SubtractHistogram",
"(",
"histogram_data",
",",
"self",
".",
"_histogram_start",
"[",
"h",
"[",
"'name'",
"]",
"]",
")"
] | https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/perf/metrics/memory.py#L106-L123 | ||
intel/linux-sgx | 2ee53db4e8fd25437a817612d3bcb94b66a28373 | sdk/debugger_interface/linux/gdb-sgx-plugin/printers.py | python | StdDequePrinter._calculate_block_size | (self, element_type) | return 4096 / size if size < 256 else 16 | Calculates the number of elements in a full block. | Calculates the number of elements in a full block. | [
"Calculates",
"the",
"number",
"of",
"elements",
"in",
"a",
"full",
"block",
"."
] | def _calculate_block_size(self, element_type):
"""Calculates the number of elements in a full block."""
size = element_type.sizeof
# Copied from struct __deque_block_size implementation of libcxx.
return 4096 / size if size < 256 else 16 | [
"def",
"_calculate_block_size",
"(",
"self",
",",
"element_type",
")",
":",
"size",
"=",
"element_type",
".",
"sizeof",
"# Copied from struct __deque_block_size implementation of libcxx.",
"return",
"4096",
"/",
"size",
"if",
"size",
"<",
"256",
"else",
"16"
] | https://github.com/intel/linux-sgx/blob/2ee53db4e8fd25437a817612d3bcb94b66a28373/sdk/debugger_interface/linux/gdb-sgx-plugin/printers.py#L509-L513 | |
MegaGlest/megaglest-source | e3af470288a3c9cc179f63b5a1eb414a669e3772 | mk/windoze/symbolstore.py | python | Dumper.Process | (self, file_or_dir) | Process a file or all the (valid) files in a directory; processing is performed
asynchronously, and Finish must be called to wait for it complete and cleanup. | Process a file or all the (valid) files in a directory; processing is performed
asynchronously, and Finish must be called to wait for it complete and cleanup. | [
"Process",
"a",
"file",
"or",
"all",
"the",
"(",
"valid",
")",
"files",
"in",
"a",
"directory",
";",
"processing",
"is",
"performed",
"asynchronously",
"and",
"Finish",
"must",
"be",
"called",
"to",
"wait",
"for",
"it",
"complete",
"and",
"cleanup",
"."
] | def Process(self, file_or_dir):
"""Process a file or all the (valid) files in a directory; processing is performed
asynchronously, and Finish must be called to wait for it complete and cleanup."""
if os.path.isdir(file_or_dir) and not self.ShouldSkipDir(file_or_dir):
self.ProcessDir(file_or_dir)
elif os.path.isfile(file_or_dir):
self.ProcessFiles((file_or_dir,)) | [
"def",
"Process",
"(",
"self",
",",
"file_or_dir",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"file_or_dir",
")",
"and",
"not",
"self",
".",
"ShouldSkipDir",
"(",
"file_or_dir",
")",
":",
"self",
".",
"ProcessDir",
"(",
"file_or_dir",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"file_or_dir",
")",
":",
"self",
".",
"ProcessFiles",
"(",
"(",
"file_or_dir",
",",
")",
")"
] | https://github.com/MegaGlest/megaglest-source/blob/e3af470288a3c9cc179f63b5a1eb414a669e3772/mk/windoze/symbolstore.py#L504-L510 | ||
catboost/catboost | 167f64f237114a4d10b2b4ee42adb4569137debe | contrib/python/setuptools/py2/pkg_resources/__init__.py | python | EggMetadata.__init__ | (self, importer) | Create a metadata provider from a zipimporter | Create a metadata provider from a zipimporter | [
"Create",
"a",
"metadata",
"provider",
"from",
"a",
"zipimporter"
] | def __init__(self, importer):
"""Create a metadata provider from a zipimporter"""
self.zip_pre = importer.archive + os.sep
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix() | [
"def",
"__init__",
"(",
"self",
",",
"importer",
")",
":",
"self",
".",
"zip_pre",
"=",
"importer",
".",
"archive",
"+",
"os",
".",
"sep",
"self",
".",
"loader",
"=",
"importer",
"if",
"importer",
".",
"prefix",
":",
"self",
".",
"module_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"importer",
".",
"archive",
",",
"importer",
".",
"prefix",
")",
"else",
":",
"self",
".",
"module_path",
"=",
"importer",
".",
"archive",
"self",
".",
"_setup_prefix",
"(",
")"
] | https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py2/pkg_resources/__init__.py#L1942-L1951 | ||
PaddlePaddle/Paddle | 1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c | python/paddle/fluid/dataset.py | python | DatasetBase.set_download_cmd | (self, download_cmd) | Set customized download cmd: download_cmd
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset()
dataset.set_download_cmd("./read_from_afs")
Args:
download_cmd(str): customized download command | Set customized download cmd: download_cmd | [
"Set",
"customized",
"download",
"cmd",
":",
"download_cmd"
] | def set_download_cmd(self, download_cmd):
"""
Set customized download cmd: download_cmd
Examples:
.. code-block:: python
import paddle.fluid as fluid
dataset = fluid.DatasetFactory().create_dataset()
dataset.set_download_cmd("./read_from_afs")
Args:
download_cmd(str): customized download command
"""
self.dataset.set_download_cmd(download_cmd) | [
"def",
"set_download_cmd",
"(",
"self",
",",
"download_cmd",
")",
":",
"self",
".",
"dataset",
".",
"set_download_cmd",
"(",
"download_cmd",
")"
] | https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dataset.py#L297-L311 | ||
ricardoquesada/Spidermonkey | 4a75ea2543408bd1b2c515aa95901523eeef7858 | addon-sdk/source/python-lib/simplejson/__init__.py | python | loads | (s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw) | return cls(encoding=encoding, **kw).decode(s) | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg. | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object. | [
"Deserialize",
"s",
"(",
"a",
"str",
"or",
"unicode",
"instance",
"containing",
"a",
"JSON",
"document",
")",
"to",
"a",
"Python",
"object",
"."
] | def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, **kw):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(encoding=encoding, **kw).decode(s) | [
"def",
"loads",
"(",
"s",
",",
"encoding",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"object_hook",
"=",
"None",
",",
"parse_float",
"=",
"None",
",",
"parse_int",
"=",
"None",
",",
"parse_constant",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"(",
"cls",
"is",
"None",
"and",
"encoding",
"is",
"None",
"and",
"object_hook",
"is",
"None",
"and",
"parse_int",
"is",
"None",
"and",
"parse_float",
"is",
"None",
"and",
"parse_constant",
"is",
"None",
"and",
"not",
"kw",
")",
":",
"return",
"_default_decoder",
".",
"decode",
"(",
"s",
")",
"if",
"cls",
"is",
"None",
":",
"cls",
"=",
"JSONDecoder",
"if",
"object_hook",
"is",
"not",
"None",
":",
"kw",
"[",
"'object_hook'",
"]",
"=",
"object_hook",
"if",
"parse_float",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_float'",
"]",
"=",
"parse_float",
"if",
"parse_int",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_int'",
"]",
"=",
"parse_int",
"if",
"parse_constant",
"is",
"not",
"None",
":",
"kw",
"[",
"'parse_constant'",
"]",
"=",
"parse_constant",
"return",
"cls",
"(",
"encoding",
"=",
"encoding",
",",
"*",
"*",
"kw",
")",
".",
"decode",
"(",
"s",
")"
] | https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/addon-sdk/source/python-lib/simplejson/__init__.py#L276-L324 | |
aws/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | dev/Tools/Python/3.7.10/windows/Lib/_collections_abc.py | python | MutableSequence.extend | (self, values) | S.extend(iterable) -- extend sequence by appending elements from the iterable | S.extend(iterable) -- extend sequence by appending elements from the iterable | [
"S",
".",
"extend",
"(",
"iterable",
")",
"--",
"extend",
"sequence",
"by",
"appending",
"elements",
"from",
"the",
"iterable"
] | def extend(self, values):
'S.extend(iterable) -- extend sequence by appending elements from the iterable'
for v in values:
self.append(v) | [
"def",
"extend",
"(",
"self",
",",
"values",
")",
":",
"for",
"v",
"in",
"values",
":",
"self",
".",
"append",
"(",
"v",
")"
] | https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_collections_abc.py#L987-L990 | ||
hpi-xnor/BMXNet-v2 | af2b1859eafc5c721b1397cef02f946aaf2ce20d | example/image-classification/symbols/resnet.py | python | residual_unit | (data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False) | Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator | Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator | [
"Return",
"ResNet",
"Unit",
"symbol",
"for",
"building",
"ResNet",
"Parameters",
"----------",
"data",
":",
"str",
"Input",
"data",
"num_filter",
":",
"int",
"Number",
"of",
"output",
"channels",
"bnf",
":",
"int",
"Bottle",
"neck",
"channels",
"factor",
"with",
"regard",
"to",
"num_filter",
"stride",
":",
"tuple",
"Stride",
"used",
"in",
"convolution",
"dim_match",
":",
"Boolean",
"True",
"means",
"channel",
"number",
"between",
"input",
"and",
"output",
"is",
"the",
"same",
"otherwise",
"means",
"differ",
"name",
":",
"str",
"Base",
"name",
"of",
"the",
"operators",
"workspace",
":",
"int",
"Workspace",
"used",
"in",
"convolution",
"operator"
] | def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, bn_mom=0.9, workspace=256, memonger=False):
"""Return ResNet Unit symbol for building ResNet
Parameters
----------
data : str
Input data
num_filter : int
Number of output channels
bnf : int
Bottle neck channels factor with regard to num_filter
stride : tuple
Stride used in convolution
dim_match : Boolean
True means channel number between input and output is the same, otherwise means differ
name : str
Base name of the operators
workspace : int
Workspace used in convolution operator
"""
if bottle_neck:
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=int(num_filter*0.25), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=int(num_filter*0.25), kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
bn3 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
act3 = mx.sym.Activation(data=bn3, act_type='relu', name=name + '_relu3')
conv3 = mx.sym.Convolution(data=act3, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv3 + shortcut
else:
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn1')
act1 = mx.sym.Activation(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(3,3), stride=stride, pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1')
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
act2 = mx.sym.Activation(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = mx.sym.Convolution(data=act2, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
if dim_match:
shortcut = data
else:
shortcut = mx.sym.Convolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv2 + shortcut | [
"def",
"residual_unit",
"(",
"data",
",",
"num_filter",
",",
"stride",
",",
"dim_match",
",",
"name",
",",
"bottle_neck",
"=",
"True",
",",
"bn_mom",
"=",
"0.9",
",",
"workspace",
"=",
"256",
",",
"memonger",
"=",
"False",
")",
":",
"if",
"bottle_neck",
":",
"# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper",
"bn1",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"data",
",",
"fix_gamma",
"=",
"False",
",",
"eps",
"=",
"2e-5",
",",
"momentum",
"=",
"bn_mom",
",",
"name",
"=",
"name",
"+",
"'_bn1'",
")",
"act1",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"bn1",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"name",
"+",
"'_relu1'",
")",
"conv1",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act1",
",",
"num_filter",
"=",
"int",
"(",
"num_filter",
"*",
"0.25",
")",
",",
"kernel",
"=",
"(",
"1",
",",
"1",
")",
",",
"stride",
"=",
"(",
"1",
",",
"1",
")",
",",
"pad",
"=",
"(",
"0",
",",
"0",
")",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_conv1'",
")",
"bn2",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"conv1",
",",
"fix_gamma",
"=",
"False",
",",
"eps",
"=",
"2e-5",
",",
"momentum",
"=",
"bn_mom",
",",
"name",
"=",
"name",
"+",
"'_bn2'",
")",
"act2",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"bn2",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"name",
"+",
"'_relu2'",
")",
"conv2",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act2",
",",
"num_filter",
"=",
"int",
"(",
"num_filter",
"*",
"0.25",
")",
",",
"kernel",
"=",
"(",
"3",
",",
"3",
")",
",",
"stride",
"=",
"stride",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_conv2'",
")",
"bn3",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"conv2",
",",
"fix_gamma",
"=",
"False",
",",
"eps",
"=",
"2e-5",
",",
"momentum",
"=",
"bn_mom",
",",
"name",
"=",
"name",
"+",
"'_bn3'",
")",
"act3",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"bn3",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"name",
"+",
"'_relu3'",
")",
"conv3",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act3",
",",
"num_filter",
"=",
"num_filter",
",",
"kernel",
"=",
"(",
"1",
",",
"1",
")",
",",
"stride",
"=",
"(",
"1",
",",
"1",
")",
",",
"pad",
"=",
"(",
"0",
",",
"0",
")",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_conv3'",
")",
"if",
"dim_match",
":",
"shortcut",
"=",
"data",
"else",
":",
"shortcut",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act1",
",",
"num_filter",
"=",
"num_filter",
",",
"kernel",
"=",
"(",
"1",
",",
"1",
")",
",",
"stride",
"=",
"stride",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_sc'",
")",
"if",
"memonger",
":",
"shortcut",
".",
"_set_attr",
"(",
"mirror_stage",
"=",
"'True'",
")",
"return",
"conv3",
"+",
"shortcut",
"else",
":",
"bn1",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"data",
",",
"fix_gamma",
"=",
"False",
",",
"momentum",
"=",
"bn_mom",
",",
"eps",
"=",
"2e-5",
",",
"name",
"=",
"name",
"+",
"'_bn1'",
")",
"act1",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"bn1",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"name",
"+",
"'_relu1'",
")",
"conv1",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act1",
",",
"num_filter",
"=",
"num_filter",
",",
"kernel",
"=",
"(",
"3",
",",
"3",
")",
",",
"stride",
"=",
"stride",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_conv1'",
")",
"bn2",
"=",
"mx",
".",
"sym",
".",
"BatchNorm",
"(",
"data",
"=",
"conv1",
",",
"fix_gamma",
"=",
"False",
",",
"momentum",
"=",
"bn_mom",
",",
"eps",
"=",
"2e-5",
",",
"name",
"=",
"name",
"+",
"'_bn2'",
")",
"act2",
"=",
"mx",
".",
"sym",
".",
"Activation",
"(",
"data",
"=",
"bn2",
",",
"act_type",
"=",
"'relu'",
",",
"name",
"=",
"name",
"+",
"'_relu2'",
")",
"conv2",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act2",
",",
"num_filter",
"=",
"num_filter",
",",
"kernel",
"=",
"(",
"3",
",",
"3",
")",
",",
"stride",
"=",
"(",
"1",
",",
"1",
")",
",",
"pad",
"=",
"(",
"1",
",",
"1",
")",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_conv2'",
")",
"if",
"dim_match",
":",
"shortcut",
"=",
"data",
"else",
":",
"shortcut",
"=",
"mx",
".",
"sym",
".",
"Convolution",
"(",
"data",
"=",
"act1",
",",
"num_filter",
"=",
"num_filter",
",",
"kernel",
"=",
"(",
"1",
",",
"1",
")",
",",
"stride",
"=",
"stride",
",",
"no_bias",
"=",
"True",
",",
"workspace",
"=",
"workspace",
",",
"name",
"=",
"name",
"+",
"'_sc'",
")",
"if",
"memonger",
":",
"shortcut",
".",
"_set_attr",
"(",
"mirror_stage",
"=",
"'True'",
")",
"return",
"conv2",
"+",
"shortcut"
] | https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/image-classification/symbols/resnet.py#L29-L86 | ||
wxWidgets/wxPython-Classic | 19571e1ae65f1ac445f5491474121998c97a1bf0 | src/msw/_windows.py | python | PyPreviewFrame.SetControlBar | (*args, **kwargs) | return _windows_.PyPreviewFrame_SetControlBar(*args, **kwargs) | SetControlBar(self, PreviewControlBar bar) | SetControlBar(self, PreviewControlBar bar) | [
"SetControlBar",
"(",
"self",
"PreviewControlBar",
"bar",
")"
] | def SetControlBar(*args, **kwargs):
"""SetControlBar(self, PreviewControlBar bar)"""
return _windows_.PyPreviewFrame_SetControlBar(*args, **kwargs) | [
"def",
"SetControlBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_windows_",
".",
"PyPreviewFrame_SetControlBar",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L5752-L5754 | |
rapidsai/cudf | d5b2448fc69f17509304d594f029d0df56984962 | python/cudf/cudf/core/udf/utils.py | python | _mask_get | (mask, pos) | return (mask[pos // MASK_BITSIZE] >> (pos % MASK_BITSIZE)) & 1 | Return the validity of mask[pos] as a word. | Return the validity of mask[pos] as a word. | [
"Return",
"the",
"validity",
"of",
"mask",
"[",
"pos",
"]",
"as",
"a",
"word",
"."
] | def _mask_get(mask, pos):
"""Return the validity of mask[pos] as a word."""
return (mask[pos // MASK_BITSIZE] >> (pos % MASK_BITSIZE)) & 1 | [
"def",
"_mask_get",
"(",
"mask",
",",
"pos",
")",
":",
"return",
"(",
"mask",
"[",
"pos",
"//",
"MASK_BITSIZE",
"]",
">>",
"(",
"pos",
"%",
"MASK_BITSIZE",
")",
")",
"&",
"1"
] | https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/udf/utils.py#L146-L148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.