nwo
stringlengths 5
58
| sha
stringlengths 40
40
| path
stringlengths 5
172
| language
stringclasses 1
value | identifier
stringlengths 1
100
| parameters
stringlengths 2
3.5k
| argument_list
stringclasses 1
value | return_statement
stringlengths 0
21.5k
| docstring
stringlengths 2
17k
| docstring_summary
stringlengths 0
6.58k
| docstring_tokens
sequence | function
stringlengths 35
55.6k
| function_tokens
sequence | url
stringlengths 89
269
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | tools/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.Pchify | (self, path, lang) | return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) | Convert a prefix header path to its output directory form. | Convert a prefix header path to its output directory form. | [
"Convert",
"a",
"prefix",
"header",
"path",
"to",
"its",
"output",
"directory",
"form",
"."
] | def Pchify(self, path, lang):
"""Convert a prefix header path to its output directory form."""
path = self.Absolutify(path)
if '$(' in path:
path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' %
(self.toolset, lang))
return path
return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path) | [
"def",
"Pchify",
"(",
"self",
",",
"path",
",",
"lang",
")",
":",
"path",
"=",
"self",
".",
"Absolutify",
"(",
"path",
")",
"if",
"'$('",
"in",
"path",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"'$(obj)/'",
",",
"'$(obj).%s/$(TARGET)/pch-%s'",
"%",
"(",
"self",
".",
"toolset",
",",
"lang",
")",
")",
"return",
"path",
"return",
"'$(obj).%s/$(TARGET)/pch-%s/%s'",
"%",
"(",
"self",
".",
"toolset",
",",
"lang",
",",
"path",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/tools/gyp/pylib/gyp/generator/make.py#L1896-L1903 |
|
xixiaoyao/CS224n-winter-together | f1fbcd4db284a804cb9dfc24b65481ba66e7d32c | Assignments/assignment2/Bryce/word2vec.py | python | negSamplingLossAndGradient | (
centerWordVec,
outsideWordIdx,
outsideVectors,
dataset,
K=10
) | return loss, gradCenterVec, gradOutsideVecs | Negative sampling loss function for word2vec models
Implement the negative sampling loss and gradients for a centerWordVec
and a outsideWordIdx word vector as a building block for word2vec
models. K is the number of negative samples to take.
Note: The same word may be negatively sampled multiple times. For
example if an outside word is sampled twice, you shall have to
double count the gradient with respect to this word. Thrice if
it was sampled three times, and so forth.
Arguments/Return Specifications: same as naiveSoftmaxLossAndGradient | Negative sampling loss function for word2vec models | [
"Negative",
"sampling",
"loss",
"function",
"for",
"word2vec",
"models"
] | def negSamplingLossAndGradient(
centerWordVec,
outsideWordIdx,
outsideVectors,
dataset,
K=10
):
""" Negative sampling loss function for word2vec models
Implement the negative sampling loss and gradients for a centerWordVec
and a outsideWordIdx word vector as a building block for word2vec
models. K is the number of negative samples to take.
Note: The same word may be negatively sampled multiple times. For
example if an outside word is sampled twice, you shall have to
double count the gradient with respect to this word. Thrice if
it was sampled three times, and so forth.
Arguments/Return Specifications: same as naiveSoftmaxLossAndGradient
"""
# Negative sampling of words is done for you. Do not modify this if you
# wish to match the autograder and receive points!
negSampleWordIndices = getNegativeSamples(outsideWordIdx, dataset, K)
# indices = [outsideWordIdx] + negSampleWordIndices
### YOUR CODE HERE
### Please use your implementation of sigmoid in here.
uv_oc = sigmoid((outsideVectors[outsideWordIdx, :] * centerWordVec).sum()) # (1, 1)
uv_kc = sigmoid(- centerWordVec @ outsideVectors[negSampleWordIndices, :].T) # (1, k)
loss = - np.log(uv_oc) - np.sum(np.log(uv_kc))
gradCenterVec = (1 - uv_kc) @ outsideVectors[negSampleWordIndices, :] - (1 - uv_oc) * outsideVectors[outsideWordIdx]
gradOutsideVecs = np.zeros_like(outsideVectors)
gradOutsideVecs[outsideWordIdx] = (uv_oc - 1) * centerWordVec # 更新 outside word 的梯度
# 由于负采样可能会把一些单词重复采出,所以梯度需要累加而下面这种方式只保留了最后一次的梯度,所以必须以循环的方式计算
# gradOutsideVecs[negSampleWordIndices] = (1 - uv_kc).reshape(-1, 1) @ centerWordVec.reshape(1, -1)
gradOutside = (1 - uv_kc).reshape(-1, 1) @ centerWordVec.reshape(1, -1)
# 更新负采样中单词向量的梯度
for i, idx in enumerate(negSampleWordIndices):
gradOutsideVecs[idx] += gradOutside[i]
### END YOUR CODE
return loss, gradCenterVec, gradOutsideVecs | [
"def",
"negSamplingLossAndGradient",
"(",
"centerWordVec",
",",
"outsideWordIdx",
",",
"outsideVectors",
",",
"dataset",
",",
"K",
"=",
"10",
")",
":",
"# Negative sampling of words is done for you. Do not modify this if you",
"# wish to match the autograder and receive points!",
"negSampleWordIndices",
"=",
"getNegativeSamples",
"(",
"outsideWordIdx",
",",
"dataset",
",",
"K",
")",
"# indices = [outsideWordIdx] + negSampleWordIndices",
"### YOUR CODE HERE",
"### Please use your implementation of sigmoid in here.",
"uv_oc",
"=",
"sigmoid",
"(",
"(",
"outsideVectors",
"[",
"outsideWordIdx",
",",
":",
"]",
"*",
"centerWordVec",
")",
".",
"sum",
"(",
")",
")",
"# (1, 1)",
"uv_kc",
"=",
"sigmoid",
"(",
"-",
"centerWordVec",
"@",
"outsideVectors",
"[",
"negSampleWordIndices",
",",
":",
"]",
".",
"T",
")",
"# (1, k)",
"loss",
"=",
"-",
"np",
".",
"log",
"(",
"uv_oc",
")",
"-",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"uv_kc",
")",
")",
"gradCenterVec",
"=",
"(",
"1",
"-",
"uv_kc",
")",
"@",
"outsideVectors",
"[",
"negSampleWordIndices",
",",
":",
"]",
"-",
"(",
"1",
"-",
"uv_oc",
")",
"*",
"outsideVectors",
"[",
"outsideWordIdx",
"]",
"gradOutsideVecs",
"=",
"np",
".",
"zeros_like",
"(",
"outsideVectors",
")",
"gradOutsideVecs",
"[",
"outsideWordIdx",
"]",
"=",
"(",
"uv_oc",
"-",
"1",
")",
"*",
"centerWordVec",
"# 更新 outside word 的梯度",
"# 由于负采样可能会把一些单词重复采出,所以梯度需要累加而下面这种方式只保留了最后一次的梯度,所以必须以循环的方式计算",
"# gradOutsideVecs[negSampleWordIndices] = (1 - uv_kc).reshape(-1, 1) @ centerWordVec.reshape(1, -1)",
"gradOutside",
"=",
"(",
"1",
"-",
"uv_kc",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"@",
"centerWordVec",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
"# 更新负采样中单词向量的梯度",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"negSampleWordIndices",
")",
":",
"gradOutsideVecs",
"[",
"idx",
"]",
"+=",
"gradOutside",
"[",
"i",
"]",
"### END YOUR CODE",
"return",
"loss",
",",
"gradCenterVec",
",",
"gradOutsideVecs"
] | https://github.com/xixiaoyao/CS224n-winter-together/blob/f1fbcd4db284a804cb9dfc24b65481ba66e7d32c/Assignments/assignment2/Bryce/word2vec.py#L88-L132 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/account/models/account_move.py | python | AccountMove._get_invoice_in_payment_state | (self) | return 'paid' | Hook to give the state when the invoice becomes fully paid. This is necessary because the users working
with only invoicing don't want to see the 'in_payment' state. Then, this method will be overridden in the
accountant module to enable the 'in_payment' state. | Hook to give the state when the invoice becomes fully paid. This is necessary because the users working
with only invoicing don't want to see the 'in_payment' state. Then, this method will be overridden in the
accountant module to enable the 'in_payment' state. | [
"Hook",
"to",
"give",
"the",
"state",
"when",
"the",
"invoice",
"becomes",
"fully",
"paid",
".",
"This",
"is",
"necessary",
"because",
"the",
"users",
"working",
"with",
"only",
"invoicing",
"don",
"t",
"want",
"to",
"see",
"the",
"in_payment",
"state",
".",
"Then",
"this",
"method",
"will",
"be",
"overridden",
"in",
"the",
"accountant",
"module",
"to",
"enable",
"the",
"in_payment",
"state",
"."
] | def _get_invoice_in_payment_state(self):
''' Hook to give the state when the invoice becomes fully paid. This is necessary because the users working
with only invoicing don't want to see the 'in_payment' state. Then, this method will be overridden in the
accountant module to enable the 'in_payment' state. '''
return 'paid' | [
"def",
"_get_invoice_in_payment_state",
"(",
"self",
")",
":",
"return",
"'paid'"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/account/models/account_move.py#L1356-L1360 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py | python | HexDump.hexa_qword | (data, separator = ' ') | return separator.join( [ '%.16x' % struct.unpack('<Q', data[i:i+8])[0]\
for i in compat.xrange(0, len(data), 8) ] ) | Convert binary data to a string of hexadecimal QWORDs.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each QWORD.
@rtype: str
@return: Hexadecimal representation. | Convert binary data to a string of hexadecimal QWORDs. | [
"Convert",
"binary",
"data",
"to",
"a",
"string",
"of",
"hexadecimal",
"QWORDs",
"."
] | def hexa_qword(data, separator = ' '):
"""
Convert binary data to a string of hexadecimal QWORDs.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each QWORD.
@rtype: str
@return: Hexadecimal representation.
"""
if len(data) & 7 != 0:
data += '\0' * (8 - (len(data) & 7))
return separator.join( [ '%.16x' % struct.unpack('<Q', data[i:i+8])[0]\
for i in compat.xrange(0, len(data), 8) ] ) | [
"def",
"hexa_qword",
"(",
"data",
",",
"separator",
"=",
"' '",
")",
":",
"if",
"len",
"(",
"data",
")",
"&",
"7",
"!=",
"0",
":",
"data",
"+=",
"'\\0'",
"*",
"(",
"8",
"-",
"(",
"len",
"(",
"data",
")",
"&",
"7",
")",
")",
"return",
"separator",
".",
"join",
"(",
"[",
"'%.16x'",
"%",
"struct",
".",
"unpack",
"(",
"'<Q'",
",",
"data",
"[",
"i",
":",
"i",
"+",
"8",
"]",
")",
"[",
"0",
"]",
"for",
"i",
"in",
"compat",
".",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"8",
")",
"]",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py#L592-L609 |
|
npm/cli | 892b66eba9f21dbfbc250572d437141e39a6de24 | node_modules/node-gyp/gyp/pylib/gyp/generator/make.py | python | Linkable | (filename) | return filename.endswith(".o") | Return true if the file is linkable (should be on the link line). | Return true if the file is linkable (should be on the link line). | [
"Return",
"true",
"if",
"the",
"file",
"is",
"linkable",
"(",
"should",
"be",
"on",
"the",
"link",
"line",
")",
"."
] | def Linkable(filename):
"""Return true if the file is linkable (should be on the link line)."""
return filename.endswith(".o") | [
"def",
"Linkable",
"(",
"filename",
")",
":",
"return",
"filename",
".",
"endswith",
"(",
"\".o\"",
")"
] | https://github.com/npm/cli/blob/892b66eba9f21dbfbc250572d437141e39a6de24/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L605-L607 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/faraday/plugins/repo/nmap/plugin.py | python | NmapPlugin.processCommandString | (self, username, current_path, command_string) | Adds the -oX parameter to get xml output to the command string that the
user has set. | Adds the -oX parameter to get xml output to the command string that the
user has set. | [
"Adds",
"the",
"-",
"oX",
"parameter",
"to",
"get",
"xml",
"output",
"to",
"the",
"command",
"string",
"that",
"the",
"user",
"has",
"set",
"."
] | def processCommandString(self, username, current_path, command_string):
"""
Adds the -oX parameter to get xml output to the command string that the
user has set.
"""
self._output_file_path = os.path.join(self.data_path,"nmap_output-%s.xml" % random.uniform(1,10))
arg_match = self.xml_arg_re.match(command_string)
if arg_match is None:
return re.sub(r"(^.*?nmap)",
r"\1 -oX %s" % self._output_file_path,
command_string)
else:
return re.sub(arg_match.group(1),
r"-oX %s" % self._output_file_path,
command_string) | [
"def",
"processCommandString",
"(",
"self",
",",
"username",
",",
"current_path",
",",
"command_string",
")",
":",
"self",
".",
"_output_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_path",
",",
"\"nmap_output-%s.xml\"",
"%",
"random",
".",
"uniform",
"(",
"1",
",",
"10",
")",
")",
"arg_match",
"=",
"self",
".",
"xml_arg_re",
".",
"match",
"(",
"command_string",
")",
"if",
"arg_match",
"is",
"None",
":",
"return",
"re",
".",
"sub",
"(",
"r\"(^.*?nmap)\"",
",",
"r\"\\1 -oX %s\"",
"%",
"self",
".",
"_output_file_path",
",",
"command_string",
")",
"else",
":",
"return",
"re",
".",
"sub",
"(",
"arg_match",
".",
"group",
"(",
"1",
")",
",",
"r\"-oX %s\"",
"%",
"self",
".",
"_output_file_path",
",",
"command_string",
")"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/faraday/plugins/repo/nmap/plugin.py#L564-L581 |
||
DFIRKuiper/Kuiper | c5b4cb3d535287c360b239b7596e82731954fc77 | kuiper/app/parsers/vol_Parser/volatility/framework/plugins/isfinfo.py | python | IsfInfo._get_banner | (self, clazz: Type[symbol_cache.SymbolBannerCache], data: Any) | return banner_symbol | Gets a banner from an ISF file | Gets a banner from an ISF file | [
"Gets",
"a",
"banner",
"from",
"an",
"ISF",
"file"
] | def _get_banner(self, clazz: Type[symbol_cache.SymbolBannerCache], data: Any) -> str:
"""Gets a banner from an ISF file"""
banner_symbol = data.get('symbols', {}).get(clazz.symbol_name, {}).get('constant_data',
renderers.NotAvailableValue())
if not isinstance(banner_symbol, interfaces.renderers.BaseAbsentValue):
banner_symbol = str(base64.b64decode(banner_symbol), encoding = 'latin-1')
return banner_symbol | [
"def",
"_get_banner",
"(",
"self",
",",
"clazz",
":",
"Type",
"[",
"symbol_cache",
".",
"SymbolBannerCache",
"]",
",",
"data",
":",
"Any",
")",
"->",
"str",
":",
"banner_symbol",
"=",
"data",
".",
"get",
"(",
"'symbols'",
",",
"{",
"}",
")",
".",
"get",
"(",
"clazz",
".",
"symbol_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"'constant_data'",
",",
"renderers",
".",
"NotAvailableValue",
"(",
")",
")",
"if",
"not",
"isinstance",
"(",
"banner_symbol",
",",
"interfaces",
".",
"renderers",
".",
"BaseAbsentValue",
")",
":",
"banner_symbol",
"=",
"str",
"(",
"base64",
".",
"b64decode",
"(",
"banner_symbol",
")",
",",
"encoding",
"=",
"'latin-1'",
")",
"return",
"banner_symbol"
] | https://github.com/DFIRKuiper/Kuiper/blob/c5b4cb3d535287c360b239b7596e82731954fc77/kuiper/app/parsers/vol_Parser/volatility/framework/plugins/isfinfo.py#L65-L71 |
|
buu700/napster.fm | 3df1e3d4b31890020db0160922996f137b7efea7 | js/closure-library/closure/bin/calcdeps.py | python | GetInputsFromOptions | (options) | return FilterByExcludes(options, inputs) | Generates the inputs from flag options.
Args:
options: The flags to calcdeps.
Returns:
A list of inputs (strings). | Generates the inputs from flag options. | [
"Generates",
"the",
"inputs",
"from",
"flag",
"options",
"."
] | def GetInputsFromOptions(options):
"""Generates the inputs from flag options.
Args:
options: The flags to calcdeps.
Returns:
A list of inputs (strings).
"""
inputs = options.inputs
if not inputs: # Parse stdin
logging.info('No inputs specified. Reading from stdin...')
inputs = filter(None, [line.strip('\n') for line in sys.stdin.readlines()])
logging.info('Scanning files...')
inputs = ExpandDirectories(inputs)
return FilterByExcludes(options, inputs) | [
"def",
"GetInputsFromOptions",
"(",
"options",
")",
":",
"inputs",
"=",
"options",
".",
"inputs",
"if",
"not",
"inputs",
":",
"# Parse stdin",
"logging",
".",
"info",
"(",
"'No inputs specified. Reading from stdin...'",
")",
"inputs",
"=",
"filter",
"(",
"None",
",",
"[",
"line",
".",
"strip",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"sys",
".",
"stdin",
".",
"readlines",
"(",
")",
"]",
")",
"logging",
".",
"info",
"(",
"'Scanning files...'",
")",
"inputs",
"=",
"ExpandDirectories",
"(",
"inputs",
")",
"return",
"FilterByExcludes",
"(",
"options",
",",
"inputs",
")"
] | https://github.com/buu700/napster.fm/blob/3df1e3d4b31890020db0160922996f137b7efea7/js/closure-library/closure/bin/calcdeps.py#L431-L447 |
|
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/v8/tools/grokdump.py | python | InspectionShell.do_do_map | (self, address) | Print a descriptor array in a readable format. | Print a descriptor array in a readable format. | [
"Print",
"a",
"descriptor",
"array",
"in",
"a",
"readable",
"format",
"."
] | def do_do_map(self, address):
"""
Print a descriptor array in a readable format.
"""
start = int(address, 16)
if ((start & 1) == 1): start = start - 1
Map(self.heap, None, start).Print(Printer()) | [
"def",
"do_do_map",
"(",
"self",
",",
"address",
")",
":",
"start",
"=",
"int",
"(",
"address",
",",
"16",
")",
"if",
"(",
"(",
"start",
"&",
"1",
")",
"==",
"1",
")",
":",
"start",
"=",
"start",
"-",
"1",
"Map",
"(",
"self",
".",
"heap",
",",
"None",
",",
"start",
")",
".",
"Print",
"(",
"Printer",
"(",
")",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/v8/tools/grokdump.py#L2988-L2994 |
||
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | _FormatAsEnvironmentBlock | (envvar_dict) | return block | Format as an 'environment block' directly suitable for CreateProcess.
Briefly this is a list of key=value\0, terminated by an additional \0. See
CreateProcess documentation for more details. | Format as an 'environment block' directly suitable for CreateProcess.
Briefly this is a list of key=value\0, terminated by an additional \0. See
CreateProcess documentation for more details. | [
"Format",
"as",
"an",
"environment",
"block",
"directly",
"suitable",
"for",
"CreateProcess",
".",
"Briefly",
"this",
"is",
"a",
"list",
"of",
"key",
"=",
"value",
"\\",
"0",
"terminated",
"by",
"an",
"additional",
"\\",
"0",
".",
"See",
"CreateProcess",
"documentation",
"for",
"more",
"details",
"."
] | def _FormatAsEnvironmentBlock(envvar_dict):
"""Format as an 'environment block' directly suitable for CreateProcess.
Briefly this is a list of key=value\0, terminated by an additional \0. See
CreateProcess documentation for more details."""
block = ''
nul = '\0'
for key, value in envvar_dict.iteritems():
block += key + '=' + value + nul
block += nul
return block | [
"def",
"_FormatAsEnvironmentBlock",
"(",
"envvar_dict",
")",
":",
"block",
"=",
"''",
"nul",
"=",
"'\\0'",
"for",
"key",
",",
"value",
"in",
"envvar_dict",
".",
"iteritems",
"(",
")",
":",
"block",
"+=",
"key",
"+",
"'='",
"+",
"value",
"+",
"nul",
"block",
"+=",
"nul",
"return",
"block"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/msvs_emulation.py#L988-L997 |
|
yodaos-project/ShadowNode | b03929d5500fd0823fdc3bc37c9b82ba88cc3f6d | tools/travis_script.py | python | check_change | (path) | return commit_diff.find(path) != -1 | Check if current pull request depends on path,
return `False` if not depends, else if depends. | Check if current pull request depends on path,
return `False` if not depends, else if depends. | [
"Check",
"if",
"current",
"pull",
"request",
"depends",
"on",
"path",
"return",
"False",
"if",
"not",
"depends",
"else",
"if",
"depends",
"."
] | def check_change(path):
'''Check if current pull request depends on path,
return `False` if not depends, else if depends.'''
if os.getenv('TRAVIS_PULL_REQUEST') == 'false':
return True
travis_branch = os.getenv('TRAVIS_BRANCH')
commit_diff = ex.run_cmd_output('git',
[
'diff',
'--name-only',
'HEAD..origin/' + travis_branch],
True)
return commit_diff.find(path) != -1 | [
"def",
"check_change",
"(",
"path",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"'TRAVIS_PULL_REQUEST'",
")",
"==",
"'false'",
":",
"return",
"True",
"travis_branch",
"=",
"os",
".",
"getenv",
"(",
"'TRAVIS_BRANCH'",
")",
"commit_diff",
"=",
"ex",
".",
"run_cmd_output",
"(",
"'git'",
",",
"[",
"'diff'",
",",
"'--name-only'",
",",
"'HEAD..origin/'",
"+",
"travis_branch",
"]",
",",
"True",
")",
"return",
"commit_diff",
".",
"find",
"(",
"path",
")",
"!=",
"-",
"1"
] | https://github.com/yodaos-project/ShadowNode/blob/b03929d5500fd0823fdc3bc37c9b82ba88cc3f6d/tools/travis_script.py#L11-L23 |
|
Unmanic/unmanic | 655b18b5fd80c814e45ec38929d1046da93114c3 | unmanic/webserver/api_v2/base_api_handler.py | python | BaseApiHandler.get | (self, path) | Route all GET requests to the 'action_route()' method
:param path:
:return: | Route all GET requests to the 'action_route()' method | [
"Route",
"all",
"GET",
"requests",
"to",
"the",
"action_route",
"()",
"method"
] | async def get(self, path):
"""
Route all GET requests to the 'action_route()' method
:param path:
:return:
"""
await IOLoop.current().run_in_executor(None, self.action_route) | [
"async",
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"await",
"IOLoop",
".",
"current",
"(",
")",
".",
"run_in_executor",
"(",
"None",
",",
"self",
".",
"action_route",
")"
] | https://github.com/Unmanic/unmanic/blob/655b18b5fd80c814e45ec38929d1046da93114c3/unmanic/webserver/api_v2/base_api_handler.py#L275-L282 |
||
jeff1evesque/machine-learning | 4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff | brain/database/entity.py | python | Entity.remove_entity | (self, uid, collection) | This method is responsible deleting an entity, with respect to a
defined uid, and collection.
@sql_statement, is a sql format string, and not a python string.
Therefore, '%s' is used for argument substitution. | [] | def remove_entity(self, uid, collection):
'''
This method is responsible deleting an entity, with respect to a
defined uid, and collection.
@sql_statement, is a sql format string, and not a python string.
Therefore, '%s' is used for argument substitution.
'''
# delete entity
self.sql.connect(self.db_ml)
sql_statement = 'Delete '\
'FROM tbl_dataset_entity '\
'WHERE (uid_created=%s AND collection=%s)'
args = (uid, collection)
response = self.sql.execute('delete', sql_statement, args)
# retrieve any error(s)
response_error = self.sql.get_errors()
# return result
if response_error:
return {'error': response_error, 'result': None}
else:
return {'error': None, 'result': int(response['id'])} | [
"def",
"remove_entity",
"(",
"self",
",",
"uid",
",",
"collection",
")",
":",
"# delete entity",
"self",
".",
"sql",
".",
"connect",
"(",
"self",
".",
"db_ml",
")",
"sql_statement",
"=",
"'Delete '",
"'FROM tbl_dataset_entity '",
"'WHERE (uid_created=%s AND collection=%s)'",
"args",
"=",
"(",
"uid",
",",
"collection",
")",
"response",
"=",
"self",
".",
"sql",
".",
"execute",
"(",
"'delete'",
",",
"sql_statement",
",",
"args",
")",
"# retrieve any error(s)",
"response_error",
"=",
"self",
".",
"sql",
".",
"get_errors",
"(",
")",
"# return result",
"if",
"response_error",
":",
"return",
"{",
"'error'",
":",
"response_error",
",",
"'result'",
":",
"None",
"}",
"else",
":",
"return",
"{",
"'error'",
":",
"None",
",",
"'result'",
":",
"int",
"(",
"response",
"[",
"'id'",
"]",
")",
"}"
] | https://github.com/jeff1evesque/machine-learning/blob/4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff/brain/database/entity.py#L181-L207 |
|||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/distutils/dep_util.py | python | newer | (source, target) | return os.stat(source).st_mtime > os.stat(target).st_mtime | Tells if the target is newer than the source.
Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't.
Return false if both exist and 'target' is the same age or younger
than 'source'. Raise DistutilsFileError if 'source' does not exist.
Note that this test is not very accurate: files created in the same second
will have the same "age". | Tells if the target is newer than the source. | [
"Tells",
"if",
"the",
"target",
"is",
"newer",
"than",
"the",
"source",
"."
] | def newer(source, target):
"""Tells if the target is newer than the source.
Return true if 'source' exists and is more recently modified than
'target', or if 'source' exists and 'target' doesn't.
Return false if both exist and 'target' is the same age or younger
than 'source'. Raise DistutilsFileError if 'source' does not exist.
Note that this test is not very accurate: files created in the same second
will have the same "age".
"""
if not os.path.exists(source):
raise DistutilsFileError("file '%s' does not exist" %
os.path.abspath(source))
if not os.path.exists(target):
return True
return os.stat(source).st_mtime > os.stat(target).st_mtime | [
"def",
"newer",
"(",
"source",
",",
"target",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"source",
")",
":",
"raise",
"DistutilsFileError",
"(",
"\"file '%s' does not exist\"",
"%",
"os",
".",
"path",
".",
"abspath",
"(",
"source",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target",
")",
":",
"return",
"True",
"return",
"os",
".",
"stat",
"(",
"source",
")",
".",
"st_mtime",
">",
"os",
".",
"stat",
"(",
"target",
")",
".",
"st_mtime"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/distutils/dep_util.py#L12-L30 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/logging/handlers.py | python | SMTPHandler.emit | (self, record) | Emit a record.
Format the record and send it to the specified addressees. | Emit a record. | [
"Emit",
"a",
"record",
"."
] | def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
from email.utils import formatdate
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
",".join(self.toaddrs),
self.getSubject(record),
formatdate(), msg)
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"try",
":",
"import",
"smtplib",
"from",
"email",
".",
"utils",
"import",
"formatdate",
"port",
"=",
"self",
".",
"mailport",
"if",
"not",
"port",
":",
"port",
"=",
"smtplib",
".",
"SMTP_PORT",
"smtp",
"=",
"smtplib",
".",
"SMTP",
"(",
"self",
".",
"mailhost",
",",
"port",
")",
"msg",
"=",
"self",
".",
"format",
"(",
"record",
")",
"msg",
"=",
"\"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\nDate: %s\\r\\n\\r\\n%s\"",
"%",
"(",
"self",
".",
"fromaddr",
",",
"\",\"",
".",
"join",
"(",
"self",
".",
"toaddrs",
")",
",",
"self",
".",
"getSubject",
"(",
"record",
")",
",",
"formatdate",
"(",
")",
",",
"msg",
")",
"if",
"self",
".",
"username",
":",
"if",
"self",
".",
"secure",
"is",
"not",
"None",
":",
"smtp",
".",
"ehlo",
"(",
")",
"smtp",
".",
"starttls",
"(",
"*",
"self",
".",
"secure",
")",
"smtp",
".",
"ehlo",
"(",
")",
"smtp",
".",
"login",
"(",
"self",
".",
"username",
",",
"self",
".",
"password",
")",
"smtp",
".",
"sendmail",
"(",
"self",
".",
"fromaddr",
",",
"self",
".",
"toaddrs",
",",
"msg",
")",
"smtp",
".",
"quit",
"(",
")",
"except",
"(",
"KeyboardInterrupt",
",",
"SystemExit",
")",
":",
"raise",
"except",
":",
"self",
".",
"handleError",
"(",
"record",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/logging/handlers.py#L865-L895 |
||
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py | python | UninstallPathSet._permitted | (self, path) | return is_local(path) | Return True if the given path is one we are permitted to
remove/modify, False otherwise. | Return True if the given path is one we are permitted to
remove/modify, False otherwise. | [
"Return",
"True",
"if",
"the",
"given",
"path",
"is",
"one",
"we",
"are",
"permitted",
"to",
"remove",
"/",
"modify",
"False",
"otherwise",
"."
] | def _permitted(self, path):
# type: (str) -> bool
"""
Return True if the given path is one we are permitted to
remove/modify, False otherwise.
"""
return is_local(path) | [
"def",
"_permitted",
"(",
"self",
",",
"path",
")",
":",
"# type: (str) -> bool",
"return",
"is_local",
"(",
"path",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/req/req_uninstall.py#L325-L332 |
|
jasonsanjose/brackets-sass | 88b351f2ebc3aaa514494eac368d197f63438caf | node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.WriteSubMake | (self, output_filename, makefile_path, targets, build_dir) | Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project | Write a "sub-project" Makefile. | [
"Write",
"a",
"sub",
"-",
"project",
"Makefile",
"."
] | def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
"""Write a "sub-project" Makefile.
This is a small, wrapper Makefile that calls the top-level Makefile to build
the targets from a single gyp file (i.e. a sub-project).
Arguments:
output_filename: sub-project Makefile name to write
makefile_path: path to the top-level Makefile
targets: list of "all" targets for this sub-project
build_dir: build output directory, relative to the sub-project
"""
gyp.common.EnsureDirExists(output_filename)
self.fp = open(output_filename, 'w')
self.fp.write(header)
# For consistency with other builders, put sub-project build output in the
# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).
self.WriteLn('export builddir_name ?= %s' %
os.path.join(os.path.dirname(output_filename), build_dir))
self.WriteLn('.PHONY: all')
self.WriteLn('all:')
if makefile_path:
makefile_path = ' -C ' + makefile_path
self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets)))
self.fp.close() | [
"def",
"WriteSubMake",
"(",
"self",
",",
"output_filename",
",",
"makefile_path",
",",
"targets",
",",
"build_dir",
")",
":",
"gyp",
".",
"common",
".",
"EnsureDirExists",
"(",
"output_filename",
")",
"self",
".",
"fp",
"=",
"open",
"(",
"output_filename",
",",
"'w'",
")",
"self",
".",
"fp",
".",
"write",
"(",
"header",
")",
"# For consistency with other builders, put sub-project build output in the",
"# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).",
"self",
".",
"WriteLn",
"(",
"'export builddir_name ?= %s'",
"%",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"output_filename",
")",
",",
"build_dir",
")",
")",
"self",
".",
"WriteLn",
"(",
"'.PHONY: all'",
")",
"self",
".",
"WriteLn",
"(",
"'all:'",
")",
"if",
"makefile_path",
":",
"makefile_path",
"=",
"' -C '",
"+",
"makefile_path",
"self",
".",
"WriteLn",
"(",
"'\\t$(MAKE)%s %s'",
"%",
"(",
"makefile_path",
",",
"' '",
".",
"join",
"(",
"targets",
")",
")",
")",
"self",
".",
"fp",
".",
"close",
"(",
")"
] | https://github.com/jasonsanjose/brackets-sass/blob/88b351f2ebc3aaa514494eac368d197f63438caf/node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/make.py#L805-L829 |
||
webrtc/apprtc | db975e22ea07a0c11a4179d4beb2feb31cf344f4 | src/third_party/oauth2client/client.py | python | OAuth2WebServerFlow.__init__ | (self, client_id, client_secret, scope,
redirect_uri=None,
user_agent=None,
auth_uri=GOOGLE_AUTH_URI,
token_uri=GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI,
**kwargs) | Constructor for OAuth2WebServerFlow.
The kwargs argument is used to set extra query parameters on the
auth_uri. For example, the access_type and approval_prompt
query parameters can be set via kwargs.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or iterable of strings, scope(s) of the credentials being
requested.
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls. | Constructor for OAuth2WebServerFlow. | [
"Constructor",
"for",
"OAuth2WebServerFlow",
"."
] | def __init__(self, client_id, client_secret, scope,
redirect_uri=None,
user_agent=None,
auth_uri=GOOGLE_AUTH_URI,
token_uri=GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI,
**kwargs):
"""Constructor for OAuth2WebServerFlow.
The kwargs argument is used to set extra query parameters on the
auth_uri. For example, the access_type and approval_prompt
query parameters can be set via kwargs.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or iterable of strings, scope(s) of the credentials being
requested.
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
revoke_uri: string, URI for revoke endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
self.scope = util.scopes_to_string(scope)
self.redirect_uri = redirect_uri
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.revoke_uri = revoke_uri
self.params = {
'access_type': 'offline',
'response_type': 'code',
}
self.params.update(kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"scope",
",",
"redirect_uri",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"auth_uri",
"=",
"GOOGLE_AUTH_URI",
",",
"token_uri",
"=",
"GOOGLE_TOKEN_URI",
",",
"revoke_uri",
"=",
"GOOGLE_REVOKE_URI",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client_id",
"=",
"client_id",
"self",
".",
"client_secret",
"=",
"client_secret",
"self",
".",
"scope",
"=",
"util",
".",
"scopes_to_string",
"(",
"scope",
")",
"self",
".",
"redirect_uri",
"=",
"redirect_uri",
"self",
".",
"user_agent",
"=",
"user_agent",
"self",
".",
"auth_uri",
"=",
"auth_uri",
"self",
".",
"token_uri",
"=",
"token_uri",
"self",
".",
"revoke_uri",
"=",
"revoke_uri",
"self",
".",
"params",
"=",
"{",
"'access_type'",
":",
"'offline'",
",",
"'response_type'",
":",
"'code'",
",",
"}",
"self",
".",
"params",
".",
"update",
"(",
"kwargs",
")"
] | https://github.com/webrtc/apprtc/blob/db975e22ea07a0c11a4179d4beb2feb31cf344f4/src/third_party/oauth2client/client.py#L1161-L1204 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/v8/third_party/jinja2/compiler.py | python | FrameIdentifierVisitor.visit_Assign | (self, node) | Visit assignments in the correct order. | Visit assignments in the correct order. | [
"Visit",
"assignments",
"in",
"the",
"correct",
"order",
"."
] | def visit_Assign(self, node):
"""Visit assignments in the correct order."""
self.visit(node.node)
self.visit(node.target) | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"node",
")",
"self",
".",
"visit",
"(",
"node",
".",
"target",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/v8/third_party/jinja2/compiler.py#L334-L337 |
||
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | addons/account/wizard/setup_wizards.py | python | SetupBarBankConfigWizard.validate | (self) | Called by the validation button of this wizard. Serves as an
extension hook in account_bank_statement_import. | Called by the validation button of this wizard. Serves as an
extension hook in account_bank_statement_import. | [
"Called",
"by",
"the",
"validation",
"button",
"of",
"this",
"wizard",
".",
"Serves",
"as",
"an",
"extension",
"hook",
"in",
"account_bank_statement_import",
"."
] | def validate(self):
""" Called by the validation button of this wizard. Serves as an
extension hook in account_bank_statement_import.
"""
self.linked_journal_id.mark_bank_setup_as_done_action() | [
"def",
"validate",
"(",
"self",
")",
":",
"self",
".",
"linked_journal_id",
".",
"mark_bank_setup_as_done_action",
"(",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/account/wizard/setup_wizards.py#L140-L144 |
||
stdlib-js/stdlib | e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df | lib/node_modules/@stdlib/math/base/special/min/benchmark/python/benchmark.py | python | print_results | (elapsed) | Print benchmark results.
# Arguments
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(0.131009101868)
``` | Print benchmark results. | [
"Print",
"benchmark",
"results",
"."
] | def print_results(elapsed):
"""Print benchmark results.
# Arguments
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(0.131009101868)
```
"""
rate = ITERATIONS / elapsed
print(" ---")
print(" iterations: " + str(ITERATIONS))
print(" elapsed: " + str(elapsed))
print(" rate: " + str(rate))
print(" ...") | [
"def",
"print_results",
"(",
"elapsed",
")",
":",
"rate",
"=",
"ITERATIONS",
"/",
"elapsed",
"print",
"(",
"\" ---\"",
")",
"print",
"(",
"\" iterations: \"",
"+",
"str",
"(",
"ITERATIONS",
")",
")",
"print",
"(",
"\" elapsed: \"",
"+",
"str",
"(",
"elapsed",
")",
")",
"print",
"(",
"\" rate: \"",
"+",
"str",
"(",
"rate",
")",
")",
"print",
"(",
"\" ...\"",
")"
] | https://github.com/stdlib-js/stdlib/blob/e3c14dd9a7985ed1cd1cc80e83b6659aeabeb7df/lib/node_modules/@stdlib/math/base/special/min/benchmark/python/benchmark.py#L51-L70 |
||
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | teamvision_web/teamvision/teamvision/ci/views/ci_task_parameter_view.py | python | save | (request) | return HttpResponse(result) | save parameter value for exiting parameter group | save parameter value for exiting parameter group | [
"save",
"parameter",
"value",
"for",
"exiting",
"parameter",
"group"
] | def save(request):
'''save parameter value for exiting parameter group'''
result=True
try:
print(request.POST)
CITaskParameterService.save_task_parameter(request)
except Exception as ex:
result=str(ex)
SimpleLogger.exception(ex)
return HttpResponse(result) | [
"def",
"save",
"(",
"request",
")",
":",
"result",
"=",
"True",
"try",
":",
"print",
"(",
"request",
".",
"POST",
")",
"CITaskParameterService",
".",
"save_task_parameter",
"(",
"request",
")",
"except",
"Exception",
"as",
"ex",
":",
"result",
"=",
"str",
"(",
"ex",
")",
"SimpleLogger",
".",
"exception",
"(",
"ex",
")",
"return",
"HttpResponse",
"(",
"result",
")"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/teamvision_web/teamvision/teamvision/ci/views/ci_task_parameter_view.py#L45-L54 |
|
DFIRKuiper/Kuiper | c5b4cb3d535287c360b239b7596e82731954fc77 | kuiper/app/parsers/vol_Parser/volatility/framework/symbols/intermed.py | python | Version1Format.symbols | (self) | return list(self._json_object.get('symbols', {})) | Returns an iterator of the symbol names. | Returns an iterator of the symbol names. | [
"Returns",
"an",
"iterator",
"of",
"the",
"symbol",
"names",
"."
] | def symbols(self) -> Iterable[str]:
"""Returns an iterator of the symbol names."""
return list(self._json_object.get('symbols', {})) | [
"def",
"symbols",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"return",
"list",
"(",
"self",
".",
"_json_object",
".",
"get",
"(",
"'symbols'",
",",
"{",
"}",
")",
")"
] | https://github.com/DFIRKuiper/Kuiper/blob/c5b4cb3d535287c360b239b7596e82731954fc77/kuiper/app/parsers/vol_Parser/volatility/framework/symbols/intermed.py#L347-L349 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py | python | VisualStudioVersion.ProjectExtension | (self) | return self.uses_vcxproj and '.vcxproj' or '.vcproj' | Returns the file extension for the project. | Returns the file extension for the project. | [
"Returns",
"the",
"file",
"extension",
"for",
"the",
"project",
"."
] | def ProjectExtension(self):
"""Returns the file extension for the project."""
return self.uses_vcxproj and '.vcxproj' or '.vcproj' | [
"def",
"ProjectExtension",
"(",
"self",
")",
":",
"return",
"self",
".",
"uses_vcxproj",
"and",
"'.vcxproj'",
"or",
"'.vcproj'"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L56-L58 |
|
mapillary/OpenSfM | 9766a11e11544fc71fe689f33b34d0610cca2944 | opensfm/dataset.py | python | UndistortedDataSet.load_undistorted_image | (self, image: str) | return self.io_handler.imread(self._undistorted_image_file(image)) | Load undistorted image pixels as a numpy array. | Load undistorted image pixels as a numpy array. | [
"Load",
"undistorted",
"image",
"pixels",
"as",
"a",
"numpy",
"array",
"."
] | def load_undistorted_image(self, image: str) -> np.ndarray:
"""Load undistorted image pixels as a numpy array."""
return self.io_handler.imread(self._undistorted_image_file(image)) | [
"def",
"load_undistorted_image",
"(",
"self",
",",
"image",
":",
"str",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"io_handler",
".",
"imread",
"(",
"self",
".",
"_undistorted_image_file",
"(",
"image",
")",
")"
] | https://github.com/mapillary/OpenSfM/blob/9766a11e11544fc71fe689f33b34d0610cca2944/opensfm/dataset.py#L719-L721 |
|
liftoff/GateOne | 6ae1d01f7fe21e2703bdf982df7353e7bb81a500 | gateone/core/server.py | python | timeout_sessions | () | Loops over the SESSIONS dict killing any sessions that haven't been used
for the length of time specified in *TIMEOUT* (global). The value of
*TIMEOUT* can be set in 10server.conf or specified on the command line via
the *session_timeout* value.
Applications and plugins can register functions to be called when a session
times out by attaching them to the user's session inside the `SESSIONS`
dict under 'timeout_callbacks'. The best place to do this is inside of the
application's `authenticate()` function or by attaching them to the
`go:authenticate` event. Examples::
# Imagine this is inside an application's authenticate() method:
sess = SESSIONS[self.ws.session]
# Pretend timeout_session() is a function we wrote to kill stuff
if timeout_session not in sess["timeout_session"]:
sess["timeout_session"].append(timeout_session)
.. note::
This function is meant to be called via Tornado's
:meth:`~tornado.ioloop.PeriodicCallback`. | Loops over the SESSIONS dict killing any sessions that haven't been used
for the length of time specified in *TIMEOUT* (global). The value of
*TIMEOUT* can be set in 10server.conf or specified on the command line via
the *session_timeout* value. | [
"Loops",
"over",
"the",
"SESSIONS",
"dict",
"killing",
"any",
"sessions",
"that",
"haven",
"t",
"been",
"used",
"for",
"the",
"length",
"of",
"time",
"specified",
"in",
"*",
"TIMEOUT",
"*",
"(",
"global",
")",
".",
"The",
"value",
"of",
"*",
"TIMEOUT",
"*",
"can",
"be",
"set",
"in",
"10server",
".",
"conf",
"or",
"specified",
"on",
"the",
"command",
"line",
"via",
"the",
"*",
"session_timeout",
"*",
"value",
"."
] | def timeout_sessions():
"""
Loops over the SESSIONS dict killing any sessions that haven't been used
for the length of time specified in *TIMEOUT* (global). The value of
*TIMEOUT* can be set in 10server.conf or specified on the command line via
the *session_timeout* value.
Applications and plugins can register functions to be called when a session
times out by attaching them to the user's session inside the `SESSIONS`
dict under 'timeout_callbacks'. The best place to do this is inside of the
application's `authenticate()` function or by attaching them to the
`go:authenticate` event. Examples::
# Imagine this is inside an application's authenticate() method:
sess = SESSIONS[self.ws.session]
# Pretend timeout_session() is a function we wrote to kill stuff
if timeout_session not in sess["timeout_session"]:
sess["timeout_session"].append(timeout_session)
.. note::
This function is meant to be called via Tornado's
:meth:`~tornado.ioloop.PeriodicCallback`.
"""
disabled = timedelta(0) # If the user sets session_timeout to "0"
# Commented because it is a bit noisy. Uncomment to debug this mechanism.
#if TIMEOUT != disabled:
#logging.debug("timeout_sessions() TIMEOUT: %s" % TIMEOUT)
#else :
#logging.debug("timeout_sessions() TIMEOUT: disabled")
try:
if not SESSIONS: # Last client has timed out
logger.info(_("All user sessions have terminated."))
global SESSION_WATCHER
if SESSION_WATCHER:
SESSION_WATCHER.stop() # Stop ourselves
SESSION_WATCHER = None # So authenticate() will know to start it
for session in list(SESSIONS.keys()):
if "last_seen" not in SESSIONS[session]:
# Session is in the process of being created. We'll check it
# the next time timeout_sessions() is called.
continue
if SESSIONS[session]["last_seen"] == 'connected':
# Connected sessions do not need to be checked for timeouts
continue
if TIMEOUT == disabled or \
datetime.now() > SESSIONS[session]["last_seen"] + TIMEOUT:
# Kill the session
logger.info(_("{session} timeout.".format(session=session)))
if "timeout_callbacks" in SESSIONS[session]:
if SESSIONS[session]["timeout_callbacks"]:
for callback in SESSIONS[session]["timeout_callbacks"]:
callback(session)
del SESSIONS[session]
except Exception as e:
logger.error(_(
"Exception encountered in timeout_sessions(): {exception}".format(
exception=e)
))
import traceback
traceback.print_exc(file=sys.stdout) | [
"def",
"timeout_sessions",
"(",
")",
":",
"disabled",
"=",
"timedelta",
"(",
"0",
")",
"# If the user sets session_timeout to \"0\"",
"# Commented because it is a bit noisy. Uncomment to debug this mechanism.",
"#if TIMEOUT != disabled:",
"#logging.debug(\"timeout_sessions() TIMEOUT: %s\" % TIMEOUT)",
"#else :",
"#logging.debug(\"timeout_sessions() TIMEOUT: disabled\")",
"try",
":",
"if",
"not",
"SESSIONS",
":",
"# Last client has timed out",
"logger",
".",
"info",
"(",
"_",
"(",
"\"All user sessions have terminated.\"",
")",
")",
"global",
"SESSION_WATCHER",
"if",
"SESSION_WATCHER",
":",
"SESSION_WATCHER",
".",
"stop",
"(",
")",
"# Stop ourselves",
"SESSION_WATCHER",
"=",
"None",
"# So authenticate() will know to start it",
"for",
"session",
"in",
"list",
"(",
"SESSIONS",
".",
"keys",
"(",
")",
")",
":",
"if",
"\"last_seen\"",
"not",
"in",
"SESSIONS",
"[",
"session",
"]",
":",
"# Session is in the process of being created. We'll check it",
"# the next time timeout_sessions() is called.",
"continue",
"if",
"SESSIONS",
"[",
"session",
"]",
"[",
"\"last_seen\"",
"]",
"==",
"'connected'",
":",
"# Connected sessions do not need to be checked for timeouts",
"continue",
"if",
"TIMEOUT",
"==",
"disabled",
"or",
"datetime",
".",
"now",
"(",
")",
">",
"SESSIONS",
"[",
"session",
"]",
"[",
"\"last_seen\"",
"]",
"+",
"TIMEOUT",
":",
"# Kill the session",
"logger",
".",
"info",
"(",
"_",
"(",
"\"{session} timeout.\"",
".",
"format",
"(",
"session",
"=",
"session",
")",
")",
")",
"if",
"\"timeout_callbacks\"",
"in",
"SESSIONS",
"[",
"session",
"]",
":",
"if",
"SESSIONS",
"[",
"session",
"]",
"[",
"\"timeout_callbacks\"",
"]",
":",
"for",
"callback",
"in",
"SESSIONS",
"[",
"session",
"]",
"[",
"\"timeout_callbacks\"",
"]",
":",
"callback",
"(",
"session",
")",
"del",
"SESSIONS",
"[",
"session",
"]",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"_",
"(",
"\"Exception encountered in timeout_sessions(): {exception}\"",
".",
"format",
"(",
"exception",
"=",
"e",
")",
")",
")",
"import",
"traceback",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"sys",
".",
"stdout",
")"
] | https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/gateone/core/server.py#L645-L705 |
||
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | tools/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings._Setting | (self, path, config,
default=None, prefix='', append=None, map=None) | return self._GetAndMunge(
self.msvs_settings[config], path, default, prefix, append, map) | _GetAndMunge for msvs_settings. | _GetAndMunge for msvs_settings. | [
"_GetAndMunge",
"for",
"msvs_settings",
"."
] | def _Setting(self, path, config,
default=None, prefix='', append=None, map=None):
"""_GetAndMunge for msvs_settings."""
return self._GetAndMunge(
self.msvs_settings[config], path, default, prefix, append, map) | [
"def",
"_Setting",
"(",
"self",
",",
"path",
",",
"config",
",",
"default",
"=",
"None",
",",
"prefix",
"=",
"''",
",",
"append",
"=",
"None",
",",
"map",
"=",
"None",
")",
":",
"return",
"self",
".",
"_GetAndMunge",
"(",
"self",
".",
"msvs_settings",
"[",
"config",
"]",
",",
"path",
",",
"default",
",",
"prefix",
",",
"append",
",",
"map",
")"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/msvs_emulation.py#L320-L324 |
|
lionleaf/dwitter | 455133bcd62cddcbac04176a3d1145351016c2c1 | dwitter/models.py | python | Dweet.calculate_hotness | (self, is_new) | Hotness is inspired by the Hackernews ranking algorithm
Read more here:
https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d | Hotness is inspired by the Hackernews ranking algorithm
Read more here:
https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d | [
"Hotness",
"is",
"inspired",
"by",
"the",
"Hackernews",
"ranking",
"algorithm",
"Read",
"more",
"here",
":",
"https",
":",
"//",
"medium",
".",
"com",
"/",
"hacking",
"-",
"and",
"-",
"gonzo",
"/",
"how",
"-",
"hacker",
"-",
"news",
"-",
"ranking",
"-",
"algorithm",
"-",
"works",
"-",
"1d9b0cf2c08d"
] | def calculate_hotness(self, is_new):
"""
Hotness is inspired by the Hackernews ranking algorithm
Read more here:
https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
"""
def epoch_seconds(date):
epoch = datetime(2015, 5, 5) # arbitrary start date before Dwitter existed
naive = date.replace(tzinfo=None)
td = naive - epoch
return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
likes = 1
if not is_new:
likes = max(self.likes.count(), 1)
order = log(likes, 2)
# 86400 seconds = 24 hours.
# So for every log(2) likes on a dweet, its effective
# "posted time" moves 24 forward
# In other words, it takes log2(likes) * 24hrs before
# a dweet with a single like beat yours
self.hotness = round(order + epoch_seconds(self.posted)/86400, 7) | [
"def",
"calculate_hotness",
"(",
"self",
",",
"is_new",
")",
":",
"def",
"epoch_seconds",
"(",
"date",
")",
":",
"epoch",
"=",
"datetime",
"(",
"2015",
",",
"5",
",",
"5",
")",
"# arbitrary start date before Dwitter existed",
"naive",
"=",
"date",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"td",
"=",
"naive",
"-",
"epoch",
"return",
"td",
".",
"days",
"*",
"86400",
"+",
"td",
".",
"seconds",
"+",
"(",
"float",
"(",
"td",
".",
"microseconds",
")",
"/",
"1000000",
")",
"likes",
"=",
"1",
"if",
"not",
"is_new",
":",
"likes",
"=",
"max",
"(",
"self",
".",
"likes",
".",
"count",
"(",
")",
",",
"1",
")",
"order",
"=",
"log",
"(",
"likes",
",",
"2",
")",
"# 86400 seconds = 24 hours.",
"# So for every log(2) likes on a dweet, its effective",
"# \"posted time\" moves 24 forward",
"# In other words, it takes log2(likes) * 24hrs before",
"# a dweet with a single like beat yours",
"self",
".",
"hotness",
"=",
"round",
"(",
"order",
"+",
"epoch_seconds",
"(",
"self",
".",
"posted",
")",
"/",
"86400",
",",
"7",
")"
] | https://github.com/lionleaf/dwitter/blob/455133bcd62cddcbac04176a3d1145351016c2c1/dwitter/models.py#L81-L103 |
||
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py | python | XCObject.Print | (self, file=sys.stdout) | Prints a reprentation of this object to file, adhering to Xcode output
formatting. | Prints a reprentation of this object to file, adhering to Xcode output
formatting. | [
"Prints",
"a",
"reprentation",
"of",
"this",
"object",
"to",
"file",
"adhering",
"to",
"Xcode",
"output",
"formatting",
"."
] | def Print(self, file=sys.stdout):
"""Prints a reprentation of this object to file, adhering to Xcode output
formatting.
"""
self.VerifyHasRequiredProperties()
if self._should_print_single_line:
# When printing an object in a single line, Xcode doesn't put any space
# between the beginning of a dictionary (or presumably a list) and the
# first contained item, so you wind up with snippets like
# ...CDEF = {isa = PBXFileReference; fileRef = 0123...
# If it were me, I would have put a space in there after the opening
# curly, but I guess this is just another one of those inconsistencies
# between how Xcode prints PBXFileReference and PBXBuildFile objects as
# compared to other objects. Mimic Xcode's behavior here by using an
# empty string for sep.
sep = ''
end_tabs = 0
else:
sep = '\n'
end_tabs = 2
# Start the object. For example, '\t\tPBXProject = {\n'.
self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep)
# "isa" isn't in the _properties dictionary, it's an intrinsic property
# of the class which the object belongs to. Xcode always outputs "isa"
# as the first element of an object dictionary.
self._XCKVPrint(file, 3, 'isa', self.__class__.__name__)
# The remaining elements of an object dictionary are sorted alphabetically.
for property, value in sorted(self._properties.iteritems()):
self._XCKVPrint(file, 3, property, value)
# End the object.
self._XCPrint(file, end_tabs, '};\n') | [
"def",
"Print",
"(",
"self",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"self",
".",
"VerifyHasRequiredProperties",
"(",
")",
"if",
"self",
".",
"_should_print_single_line",
":",
"# When printing an object in a single line, Xcode doesn't put any space",
"# between the beginning of a dictionary (or presumably a list) and the",
"# first contained item, so you wind up with snippets like",
"# ...CDEF = {isa = PBXFileReference; fileRef = 0123...",
"# If it were me, I would have put a space in there after the opening",
"# curly, but I guess this is just another one of those inconsistencies",
"# between how Xcode prints PBXFileReference and PBXBuildFile objects as",
"# compared to other objects. Mimic Xcode's behavior here by using an",
"# empty string for sep.",
"sep",
"=",
"''",
"end_tabs",
"=",
"0",
"else",
":",
"sep",
"=",
"'\\n'",
"end_tabs",
"=",
"2",
"# Start the object. For example, '\\t\\tPBXProject = {\\n'.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"2",
",",
"self",
".",
"_XCPrintableValue",
"(",
"2",
",",
"self",
")",
"+",
"' = {'",
"+",
"sep",
")",
"# \"isa\" isn't in the _properties dictionary, it's an intrinsic property",
"# of the class which the object belongs to. Xcode always outputs \"isa\"",
"# as the first element of an object dictionary.",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"'isa'",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"# The remaining elements of an object dictionary are sorted alphabetically.",
"for",
"property",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"_properties",
".",
"iteritems",
"(",
")",
")",
":",
"self",
".",
"_XCKVPrint",
"(",
"file",
",",
"3",
",",
"property",
",",
"value",
")",
"# End the object.",
"self",
".",
"_XCPrint",
"(",
"file",
",",
"end_tabs",
",",
"'};\\n'",
")"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L701-L737 |
||
babybuddy/babybuddy | acde3156c6de781f90a85d021eaf086b28a7a008 | dashboard/templatetags/cards.py | python | card_tummytime_day | (context, child, date=None) | return {
'type': 'tummytime',
'stats': stats,
'instances': instances,
'last': instances.first(),
'empty': empty,
'hide_empty': _hide_empty(context)
} | Filters Tummy Time instances and generates statistics for a specific date.
:param child: an instance of the Child model.
:param date: a Date object for the day to filter.
:returns: a dictionary of all Tummy Time instances and stats for date. | Filters Tummy Time instances and generates statistics for a specific date.
:param child: an instance of the Child model.
:param date: a Date object for the day to filter.
:returns: a dictionary of all Tummy Time instances and stats for date. | [
"Filters",
"Tummy",
"Time",
"instances",
"and",
"generates",
"statistics",
"for",
"a",
"specific",
"date",
".",
":",
"param",
"child",
":",
"an",
"instance",
"of",
"the",
"Child",
"model",
".",
":",
"param",
"date",
":",
"a",
"Date",
"object",
"for",
"the",
"day",
"to",
"filter",
".",
":",
"returns",
":",
"a",
"dictionary",
"of",
"all",
"Tummy",
"Time",
"instances",
"and",
"stats",
"for",
"date",
"."
] | def card_tummytime_day(context, child, date=None):
"""
Filters Tummy Time instances and generates statistics for a specific date.
:param child: an instance of the Child model.
:param date: a Date object for the day to filter.
:returns: a dictionary of all Tummy Time instances and stats for date.
"""
if not date:
date = timezone.localtime().date()
instances = models.TummyTime.objects.filter(
child=child, end__year=date.year, end__month=date.month,
end__day=date.day).order_by('-end')
empty = len(instances) == 0
stats = {
'total': timezone.timedelta(seconds=0),
'count': instances.count()
}
for instance in instances:
stats['total'] += timezone.timedelta(seconds=instance.duration.seconds)
return {
'type': 'tummytime',
'stats': stats,
'instances': instances,
'last': instances.first(),
'empty': empty,
'hide_empty': _hide_empty(context)
} | [
"def",
"card_tummytime_day",
"(",
"context",
",",
"child",
",",
"date",
"=",
"None",
")",
":",
"if",
"not",
"date",
":",
"date",
"=",
"timezone",
".",
"localtime",
"(",
")",
".",
"date",
"(",
")",
"instances",
"=",
"models",
".",
"TummyTime",
".",
"objects",
".",
"filter",
"(",
"child",
"=",
"child",
",",
"end__year",
"=",
"date",
".",
"year",
",",
"end__month",
"=",
"date",
".",
"month",
",",
"end__day",
"=",
"date",
".",
"day",
")",
".",
"order_by",
"(",
"'-end'",
")",
"empty",
"=",
"len",
"(",
"instances",
")",
"==",
"0",
"stats",
"=",
"{",
"'total'",
":",
"timezone",
".",
"timedelta",
"(",
"seconds",
"=",
"0",
")",
",",
"'count'",
":",
"instances",
".",
"count",
"(",
")",
"}",
"for",
"instance",
"in",
"instances",
":",
"stats",
"[",
"'total'",
"]",
"+=",
"timezone",
".",
"timedelta",
"(",
"seconds",
"=",
"instance",
".",
"duration",
".",
"seconds",
")",
"return",
"{",
"'type'",
":",
"'tummytime'",
",",
"'stats'",
":",
"stats",
",",
"'instances'",
":",
"instances",
",",
"'last'",
":",
"instances",
".",
"first",
"(",
")",
",",
"'empty'",
":",
"empty",
",",
"'hide_empty'",
":",
"_hide_empty",
"(",
"context",
")",
"}"
] | https://github.com/babybuddy/babybuddy/blob/acde3156c6de781f90a85d021eaf086b28a7a008/dashboard/templatetags/cards.py#L618-L646 |
|
erlerobot/robot_blockly | c2b334502a7dea035a6aadf5ad65ab0e733f7f03 | frontend/closure-library/closure/bin/build/jscompiler.py | python | _GetJsCompilerArgs | (compiler_jar_path, java_version, source_paths,
jvm_flags, compiler_flags) | return args | Assembles arguments for call to JsCompiler. | Assembles arguments for call to JsCompiler. | [
"Assembles",
"arguments",
"for",
"call",
"to",
"JsCompiler",
"."
] | def _GetJsCompilerArgs(compiler_jar_path, java_version, source_paths,
jvm_flags, compiler_flags):
"""Assembles arguments for call to JsCompiler."""
if java_version < (1, 7):
raise JsCompilerError('Closure Compiler requires Java 1.7 or higher. '
'Please visit http://www.java.com/getjava')
args = ['java']
# Add JVM flags we believe will produce the best performance. See
# https://groups.google.com/forum/#!topic/closure-library-discuss/7w_O9-vzlj4
# Attempt 32-bit mode if available (Java 7 on Mac OS X does not support 32-bit
# mode, for example).
if _JavaSupports32BitMode():
args += ['-d32']
# Prefer the "client" VM.
args += ['-client']
# Add JVM flags, if any
if jvm_flags:
args += jvm_flags
# Add the application JAR.
args += ['-jar', compiler_jar_path]
for path in source_paths:
args += ['--js', path]
# Add compiler flags, if any.
if compiler_flags:
args += compiler_flags
return args | [
"def",
"_GetJsCompilerArgs",
"(",
"compiler_jar_path",
",",
"java_version",
",",
"source_paths",
",",
"jvm_flags",
",",
"compiler_flags",
")",
":",
"if",
"java_version",
"<",
"(",
"1",
",",
"7",
")",
":",
"raise",
"JsCompilerError",
"(",
"'Closure Compiler requires Java 1.7 or higher. '",
"'Please visit http://www.java.com/getjava'",
")",
"args",
"=",
"[",
"'java'",
"]",
"# Add JVM flags we believe will produce the best performance. See",
"# https://groups.google.com/forum/#!topic/closure-library-discuss/7w_O9-vzlj4",
"# Attempt 32-bit mode if available (Java 7 on Mac OS X does not support 32-bit",
"# mode, for example).",
"if",
"_JavaSupports32BitMode",
"(",
")",
":",
"args",
"+=",
"[",
"'-d32'",
"]",
"# Prefer the \"client\" VM.",
"args",
"+=",
"[",
"'-client'",
"]",
"# Add JVM flags, if any",
"if",
"jvm_flags",
":",
"args",
"+=",
"jvm_flags",
"# Add the application JAR.",
"args",
"+=",
"[",
"'-jar'",
",",
"compiler_jar_path",
"]",
"for",
"path",
"in",
"source_paths",
":",
"args",
"+=",
"[",
"'--js'",
",",
"path",
"]",
"# Add compiler flags, if any.",
"if",
"compiler_flags",
":",
"args",
"+=",
"compiler_flags",
"return",
"args"
] | https://github.com/erlerobot/robot_blockly/blob/c2b334502a7dea035a6aadf5ad65ab0e733f7f03/frontend/closure-library/closure/bin/build/jscompiler.py#L72-L107 |
|
almonk/Bind | 03e9e98fb8b30a58cb4fc2829f06289fa9958897 | public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | python | _Same | (tool, name, setting_type) | Defines a setting that has the same name in MSVS and MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting. | Defines a setting that has the same name in MSVS and MSBuild. | [
"Defines",
"a",
"setting",
"that",
"has",
"the",
"same",
"name",
"in",
"MSVS",
"and",
"MSBuild",
"."
] | def _Same(tool, name, setting_type):
"""Defines a setting that has the same name in MSVS and MSBuild.
Args:
tool: a dictionary that gives the names of the tool for MSVS and MSBuild.
name: the name of the setting.
setting_type: the type of this setting.
"""
_Renamed(tool, name, name, setting_type) | [
"def",
"_Same",
"(",
"tool",
",",
"name",
",",
"setting_type",
")",
":",
"_Renamed",
"(",
"tool",
",",
"name",
",",
"name",
",",
"setting_type",
")"
] | https://github.com/almonk/Bind/blob/03e9e98fb8b30a58cb4fc2829f06289fa9958897/public/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L233-L241 |
||
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py | python | Process.search | (self, pattern, minAddr = None, maxAddr = None) | Search for the given pattern within the process memory.
@type pattern: str, compat.unicode or L{Pattern}
@param pattern: Pattern to search for.
It may be a byte string, a Unicode string, or an instance of
L{Pattern}.
The following L{Pattern} subclasses are provided by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
You can also write your own subclass of L{Pattern} for customized
searches.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory. | Search for the given pattern within the process memory. | [
"Search",
"for",
"the",
"given",
"pattern",
"within",
"the",
"process",
"memory",
"."
] | def search(self, pattern, minAddr = None, maxAddr = None):
"""
Search for the given pattern within the process memory.
@type pattern: str, compat.unicode or L{Pattern}
@param pattern: Pattern to search for.
It may be a byte string, a Unicode string, or an instance of
L{Pattern}.
The following L{Pattern} subclasses are provided by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
You can also write your own subclass of L{Pattern} for customized
searches.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
if isinstance(pattern, str):
return self.search_bytes(pattern, minAddr, maxAddr)
if isinstance(pattern, compat.unicode):
return self.search_bytes(pattern.encode("utf-16le"),
minAddr, maxAddr)
if isinstance(pattern, Pattern):
return Search.search_process(self, pattern, minAddr, maxAddr)
raise TypeError("Unknown pattern type: %r" % type(pattern)) | [
"def",
"search",
"(",
"self",
",",
"pattern",
",",
"minAddr",
"=",
"None",
",",
"maxAddr",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"str",
")",
":",
"return",
"self",
".",
"search_bytes",
"(",
"pattern",
",",
"minAddr",
",",
"maxAddr",
")",
"if",
"isinstance",
"(",
"pattern",
",",
"compat",
".",
"unicode",
")",
":",
"return",
"self",
".",
"search_bytes",
"(",
"pattern",
".",
"encode",
"(",
"\"utf-16le\"",
")",
",",
"minAddr",
",",
"maxAddr",
")",
"if",
"isinstance",
"(",
"pattern",
",",
"Pattern",
")",
":",
"return",
"Search",
".",
"search_process",
"(",
"self",
",",
"pattern",
",",
"minAddr",
",",
"maxAddr",
")",
"raise",
"TypeError",
"(",
"\"Unknown pattern type: %r\"",
"%",
"type",
"(",
"pattern",
")",
")"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py#L1355-L1395 |
||
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/pyasm/prod/service/api_xmlrpc.py | python | BaseApiXMLRPC._get_sobject_dict | (self, sobject, columns=None, use_id=False) | if not sobject:
return {}
search_type = sobject.get_search_type()
column_info = SearchType.get_column_info(search_type)
if not columns:
search = Search(search_type)
columns = search.get_columns()
result = {}
language = self.get_language()
for column in columns:
if column == 'metadata':
value = sobject.get_metadata_dict()
else:
value = sobject.get_value(column)
if language == 'c#':
if value == '':
value = None
info = column_info.get(column)
data_type = info.get("data_type")
# This type is specific to sql server and is not a data
# element that in TACTIC (at the moment)
if data_type == 'sqlserver_timestamp':
continue
elif isinstance(value, datetime.datetime):
try:
value = str(value)
except Exception as e:
print("WARNING: Value [%s] can't be processed" % value)
continue
elif isinstance(value, long) and value > MAXINT:
elif isinstance(value, six.integer_types) and value > MAXINT:
value = str(value)
elif isinstance(value, basestring):
try:
value = value.encode("UTF8")
except Exception as e:
print("WARNING: Value [%s] can't be processed" % value)
continue
result[column] = value
result['__search_key__'] = SearchKey.build_by_sobject(sobject, use_id=use_id)
return result | if not sobject:
return {} | [
"if",
"not",
"sobject",
":",
"return",
"{}"
] | def _get_sobject_dict(self, sobject, columns=None, use_id=False):
if not sobject:
return {}
sobjects = self._get_sobjects_dict([sobject], columns=columns, use_id=use_id)
if not sobjects:
return {}
else:
return sobjects[0]
#########################
"""
if not sobject:
return {}
search_type = sobject.get_search_type()
column_info = SearchType.get_column_info(search_type)
if not columns:
search = Search(search_type)
columns = search.get_columns()
result = {}
language = self.get_language()
for column in columns:
if column == 'metadata':
value = sobject.get_metadata_dict()
else:
value = sobject.get_value(column)
if language == 'c#':
if value == '':
value = None
info = column_info.get(column)
data_type = info.get("data_type")
# This type is specific to sql server and is not a data
# element that in TACTIC (at the moment)
if data_type == 'sqlserver_timestamp':
continue
elif isinstance(value, datetime.datetime):
try:
value = str(value)
except Exception as e:
print("WARNING: Value [%s] can't be processed" % value)
continue
elif isinstance(value, long) and value > MAXINT:
elif isinstance(value, six.integer_types) and value > MAXINT:
value = str(value)
elif isinstance(value, basestring):
try:
value = value.encode("UTF8")
except Exception as e:
print("WARNING: Value [%s] can't be processed" % value)
continue
result[column] = value
result['__search_key__'] = SearchKey.build_by_sobject(sobject, use_id=use_id)
return result
""" | [
"def",
"_get_sobject_dict",
"(",
"self",
",",
"sobject",
",",
"columns",
"=",
"None",
",",
"use_id",
"=",
"False",
")",
":",
"if",
"not",
"sobject",
":",
"return",
"{",
"}",
"sobjects",
"=",
"self",
".",
"_get_sobjects_dict",
"(",
"[",
"sobject",
"]",
",",
"columns",
"=",
"columns",
",",
"use_id",
"=",
"use_id",
")",
"if",
"not",
"sobjects",
":",
"return",
"{",
"}",
"else",
":",
"return",
"sobjects",
"[",
"0",
"]",
"#########################"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/prod/service/api_xmlrpc.py#L970-L1030 |
||
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | hardware/opentrons_hardware/drivers/can_bus/can_messenger.py | python | CanMessenger.start | (self) | Start the reader task. | Start the reader task. | [
"Start",
"the",
"reader",
"task",
"."
] | def start(self) -> None:
"""Start the reader task."""
if self._task:
log.warning("task already running.")
return
self._task = asyncio.get_event_loop().create_task(self._read_task()) | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_task",
":",
"log",
".",
"warning",
"(",
"\"task already running.\"",
")",
"return",
"self",
".",
"_task",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
".",
"create_task",
"(",
"self",
".",
"_read_task",
"(",
")",
")"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/hardware/opentrons_hardware/drivers/can_bus/can_messenger.py#L72-L77 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_pkgutil_old.py | python | find_loader | (fullname) | return None | Find a PEP 302 "loader" object for fullname
If fullname contains dots, path must be the containing package's __path__.
Returns None if the module cannot be found or imported. This function uses
iter_importers(), and is thus subject to the same limitations regarding
platform-specific special import locations such as the Windows registry. | Find a PEP 302 "loader" object for fullname | [
"Find",
"a",
"PEP",
"302",
"loader",
"object",
"for",
"fullname"
] | def find_loader(fullname):
"""Find a PEP 302 "loader" object for fullname
If fullname contains dots, path must be the containing package's __path__.
Returns None if the module cannot be found or imported. This function uses
iter_importers(), and is thus subject to the same limitations regarding
platform-specific special import locations such as the Windows registry.
"""
for importer in iter_importers(fullname):
loader = importer.find_module(fullname)
if loader is not None:
return loader
return None | [
"def",
"find_loader",
"(",
"fullname",
")",
":",
"for",
"importer",
"in",
"iter_importers",
"(",
"fullname",
")",
":",
"loader",
"=",
"importer",
".",
"find_module",
"(",
"fullname",
")",
"if",
"loader",
"is",
"not",
"None",
":",
"return",
"loader",
"return",
"None"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_pkgutil_old.py#L466-L479 |
|
algorithmiaio/sample-apps | a5c90698c09c61febcd03d922d47dc437a1f4cdc | recipes/scene_detection/scene_detection.py | python | scene_detection | () | Extract scenes from videos and return timestamps. | Extract scenes from videos and return timestamps. | [
"Extract",
"scenes",
"from",
"videos",
"and",
"return",
"timestamps",
"."
] | def scene_detection():
"""Extract scenes from videos and return timestamps.""" | [
"def",
"scene_detection",
"(",
")",
":"
] | https://github.com/algorithmiaio/sample-apps/blob/a5c90698c09c61febcd03d922d47dc437a1f4cdc/recipes/scene_detection/scene_detection.py#L10-L11 |
||
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/Sqlmap/thirdparty/gprof2dot/gprof2dot.py | python | Profile.find_cycles | (self) | Find cycles using Tarjan's strongly connected components algorithm. | Find cycles using Tarjan's strongly connected components algorithm. | [
"Find",
"cycles",
"using",
"Tarjan",
"s",
"strongly",
"connected",
"components",
"algorithm",
"."
] | def find_cycles(self):
"""Find cycles using Tarjan's strongly connected components algorithm."""
# Apply the Tarjan's algorithm successively until all functions are visited
visited = set()
for function in self.functions.itervalues():
if function not in visited:
self._tarjan(function, 0, [], {}, {}, visited)
cycles = []
for function in self.functions.itervalues():
if function.cycle is not None and function.cycle not in cycles:
cycles.append(function.cycle)
self.cycles = cycles
if 0:
for cycle in cycles:
sys.stderr.write("Cycle:\n")
for member in cycle.functions:
sys.stderr.write("\tFunction %s\n" % member.name) | [
"def",
"find_cycles",
"(",
"self",
")",
":",
"# Apply the Tarjan's algorithm successively until all functions are visited",
"visited",
"=",
"set",
"(",
")",
"for",
"function",
"in",
"self",
".",
"functions",
".",
"itervalues",
"(",
")",
":",
"if",
"function",
"not",
"in",
"visited",
":",
"self",
".",
"_tarjan",
"(",
"function",
",",
"0",
",",
"[",
"]",
",",
"{",
"}",
",",
"{",
"}",
",",
"visited",
")",
"cycles",
"=",
"[",
"]",
"for",
"function",
"in",
"self",
".",
"functions",
".",
"itervalues",
"(",
")",
":",
"if",
"function",
".",
"cycle",
"is",
"not",
"None",
"and",
"function",
".",
"cycle",
"not",
"in",
"cycles",
":",
"cycles",
".",
"append",
"(",
"function",
".",
"cycle",
")",
"self",
".",
"cycles",
"=",
"cycles",
"if",
"0",
":",
"for",
"cycle",
"in",
"cycles",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Cycle:\\n\"",
")",
"for",
"member",
"in",
"cycle",
".",
"functions",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\tFunction %s\\n\"",
"%",
"member",
".",
"name",
")"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/gprof2dot/gprof2dot.py#L246-L263 |
||
UWFlow/rmc | 00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9 | migrations/delete_non_existing_course_user_courses.py | python | delete_non_existing_course_user_courses | () | NOTE: Do not run this yet, as it seems from dry run that there are
some usercourses that we would be deleting that are legit courses
that we should try getting into our Course collection.
Delete UserCourse models that reference Course objects we dont' have
(e.g. wkrpt100) | NOTE: Do not run this yet, as it seems from dry run that there are
some usercourses that we would be deleting that are legit courses
that we should try getting into our Course collection. | [
"NOTE",
":",
"Do",
"not",
"run",
"this",
"yet",
"as",
"it",
"seems",
"from",
"dry",
"run",
"that",
"there",
"are",
"some",
"usercourses",
"that",
"we",
"would",
"be",
"deleting",
"that",
"are",
"legit",
"courses",
"that",
"we",
"should",
"try",
"getting",
"into",
"our",
"Course",
"collection",
"."
] | def delete_non_existing_course_user_courses():
"""
NOTE: Do not run this yet, as it seems from dry run that there are
some usercourses that we would be deleting that are legit courses
that we should try getting into our Course collection.
Delete UserCourse models that reference Course objects we dont' have
(e.g. wkrpt100)"""
for uc in m.UserCourse.objects:
if not m.Course.objects.with_id(uc.course_id):
print 'deleting: %s, %s, %s' % (
uc.user_id, uc.course_id, uc.term_id)
uc.delete() | [
"def",
"delete_non_existing_course_user_courses",
"(",
")",
":",
"for",
"uc",
"in",
"m",
".",
"UserCourse",
".",
"objects",
":",
"if",
"not",
"m",
".",
"Course",
".",
"objects",
".",
"with_id",
"(",
"uc",
".",
"course_id",
")",
":",
"print",
"'deleting: %s, %s, %s'",
"%",
"(",
"uc",
".",
"user_id",
",",
"uc",
".",
"course_id",
",",
"uc",
".",
"term_id",
")",
"uc",
".",
"delete",
"(",
")"
] | https://github.com/UWFlow/rmc/blob/00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9/migrations/delete_non_existing_course_user_courses.py#L7-L20 |
||
frenck/home-assistant-config | 91fb77e527bc470b557b6156fd1d60515e0b0be9 | custom_components/samsungtv_smart/config_flow.py | python | _async_get_domains_service | (hass: HomeAssistant, service_name: str) | return [
domain
for domain, service in hass.services.async_services().items()
if service_name in service
] | Fetch list of domain that provide a specific service. | Fetch list of domain that provide a specific service. | [
"Fetch",
"list",
"of",
"domain",
"that",
"provide",
"a",
"specific",
"service",
"."
] | def _async_get_domains_service(hass: HomeAssistant, service_name: str):
"""Fetch list of domain that provide a specific service."""
return [
domain
for domain, service in hass.services.async_services().items()
if service_name in service
] | [
"def",
"_async_get_domains_service",
"(",
"hass",
":",
"HomeAssistant",
",",
"service_name",
":",
"str",
")",
":",
"return",
"[",
"domain",
"for",
"domain",
",",
"service",
"in",
"hass",
".",
"services",
".",
"async_services",
"(",
")",
".",
"items",
"(",
")",
"if",
"service_name",
"in",
"service",
"]"
] | https://github.com/frenck/home-assistant-config/blob/91fb77e527bc470b557b6156fd1d60515e0b0be9/custom_components/samsungtv_smart/config_flow.py#L543-L549 |
|
rhiokim/haroopress | 616f07a52268b200598c4952df79ffa2cd076877 | node_modules/stringex/node_modules/js-yaml/support/pyyaml-src/__init__.py | python | dump | (data, stream=None, Dumper=Dumper, **kwds) | return dump_all([data], stream, Dumper=Dumper, **kwds) | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead. | Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead. | [
"Serialize",
"a",
"Python",
"object",
"into",
"a",
"YAML",
"stream",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
] | def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=Dumper, **kwds) | [
"def",
"dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"Dumper",
"=",
"Dumper",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"dump_all",
"(",
"[",
"data",
"]",
",",
"stream",
",",
"Dumper",
"=",
"Dumper",
",",
"*",
"*",
"kwds",
")"
] | https://github.com/rhiokim/haroopress/blob/616f07a52268b200598c4952df79ffa2cd076877/node_modules/stringex/node_modules/js-yaml/support/pyyaml-src/__init__.py#L195-L200 |
|
chanzuckerberg/cellxgene | ceb0cc6f27821ad056209b6908db6620f0ec3da6 | server/data_common/data_adaptor.py | python | DataAdaptor.get_X_array | (self, obs_mask=None, var_mask=None) | return the X array, possibly filtered by obs_mask or var_mask.
the return type is either ndarray or scipy.sparse.spmatrix. | return the X array, possibly filtered by obs_mask or var_mask.
the return type is either ndarray or scipy.sparse.spmatrix. | [
"return",
"the",
"X",
"array",
"possibly",
"filtered",
"by",
"obs_mask",
"or",
"var_mask",
".",
"the",
"return",
"type",
"is",
"either",
"ndarray",
"or",
"scipy",
".",
"sparse",
".",
"spmatrix",
"."
] | def get_X_array(self, obs_mask=None, var_mask=None):
"""return the X array, possibly filtered by obs_mask or var_mask.
the return type is either ndarray or scipy.sparse.spmatrix."""
pass | [
"def",
"get_X_array",
"(",
"self",
",",
"obs_mask",
"=",
"None",
",",
"var_mask",
"=",
"None",
")",
":",
"pass"
] | https://github.com/chanzuckerberg/cellxgene/blob/ceb0cc6f27821ad056209b6908db6620f0ec3da6/server/data_common/data_adaptor.py#L70-L73 |
||
JoneXiong/YouMd | 15c57a76ecc5a09e84558dfd1508adbbeeafd5a7 | model.py | python | Models.archive | (self, archive_type, archive_url, display, url, count=1) | return Dict2Object(model) | archve model
args:
archive_type: the type of this archive, entry or raw
archive_url: the url of this archive
display: the title displayed
url: current url of the archived item
count: the number of archived items
reference:
template/archive.html, template/modules/archive.html | archve model | [
"archve",
"model"
] | def archive(self, archive_type, archive_url, display, url, count=1):
"""
archve model
args:
archive_type: the type of this archive, entry or raw
archive_url: the url of this archive
display: the title displayed
url: current url of the archived item
count: the number of archived items
reference:
template/archive.html, template/modules/archive.html
"""
title = display + ' 共' + str(count) + '篇'
#title = 'Archive ' + str(count) + ' ' + self.plurals(archive_type, count) + ' of ' + display
model = {
'type':archive_type,
'url':archive_url,
'display':display,
'title':title,
'urls':[url],
'count':count
}
return Dict2Object(model) | [
"def",
"archive",
"(",
"self",
",",
"archive_type",
",",
"archive_url",
",",
"display",
",",
"url",
",",
"count",
"=",
"1",
")",
":",
"title",
"=",
"display",
"+",
"' 共' +",
"s",
"r(c",
"o",
"unt) ",
"+",
"'",
"'",
"#title = 'Archive ' + str(count) + ' ' + self.plurals(archive_type, count) + ' of ' + display",
"model",
"=",
"{",
"'type'",
":",
"archive_type",
",",
"'url'",
":",
"archive_url",
",",
"'display'",
":",
"display",
",",
"'title'",
":",
"title",
",",
"'urls'",
":",
"[",
"url",
"]",
",",
"'count'",
":",
"count",
"}",
"return",
"Dict2Object",
"(",
"model",
")"
] | https://github.com/JoneXiong/YouMd/blob/15c57a76ecc5a09e84558dfd1508adbbeeafd5a7/model.py#L125-L149 |
|
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Packages/pymdownx/st3/pymdownx/emoji.py | python | EmojiPattern._get_category | (self, emoji) | return emoji.get('category') | Get the category. | Get the category. | [
"Get",
"the",
"category",
"."
] | def _get_category(self, emoji):
"""Get the category."""
return emoji.get('category') | [
"def",
"_get_category",
"(",
"self",
",",
"emoji",
")",
":",
"return",
"emoji",
".",
"get",
"(",
"'category'",
")"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/pymdownx/st3/pymdownx/emoji.py#L300-L303 |
|
wotermelon/toJump | 3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f | lib/mac/systrace/catapult/third_party/pyserial/serial/serialutil.py | python | SerialBase.applySettingsDict | (self, d) | apply stored settings from a dictionary returned from
getSettingsDict. it's allowed to delete keys from the dictionary. these
values will simply left unchanged. | apply stored settings from a dictionary returned from
getSettingsDict. it's allowed to delete keys from the dictionary. these
values will simply left unchanged. | [
"apply",
"stored",
"settings",
"from",
"a",
"dictionary",
"returned",
"from",
"getSettingsDict",
".",
"it",
"s",
"allowed",
"to",
"delete",
"keys",
"from",
"the",
"dictionary",
".",
"these",
"values",
"will",
"simply",
"left",
"unchanged",
"."
] | def applySettingsDict(self, d):
"""apply stored settings from a dictionary returned from
getSettingsDict. it's allowed to delete keys from the dictionary. these
values will simply left unchanged."""
for key in self._SETTINGS:
if d[key] != getattr(self, '_'+key): # check against internal "_" value
setattr(self, key, d[key]) | [
"def",
"applySettingsDict",
"(",
"self",
",",
"d",
")",
":",
"for",
"key",
"in",
"self",
".",
"_SETTINGS",
":",
"if",
"d",
"[",
"key",
"]",
"!=",
"getattr",
"(",
"self",
",",
"'_'",
"+",
"key",
")",
":",
"# check against internal \"_\" value",
"setattr",
"(",
"self",
",",
"key",
",",
"d",
"[",
"key",
"]",
")"
] | https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/third_party/pyserial/serial/serialutil.py#L496-L502 |
||
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/v8/third_party/jinja2/ext.py | python | Extension.bind | (self, environment) | return rv | Create a copy of this extension bound to another environment. | Create a copy of this extension bound to another environment. | [
"Create",
"a",
"copy",
"of",
"this",
"extension",
"bound",
"to",
"another",
"environment",
"."
] | def bind(self, environment):
"""Create a copy of this extension bound to another environment."""
rv = object.__new__(self.__class__)
rv.__dict__.update(self.__dict__)
rv.environment = environment
return rv | [
"def",
"bind",
"(",
"self",
",",
"environment",
")",
":",
"rv",
"=",
"object",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"rv",
".",
"__dict__",
".",
"update",
"(",
"self",
".",
"__dict__",
")",
"rv",
".",
"environment",
"=",
"environment",
"return",
"rv"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/v8/third_party/jinja2/ext.py#L73-L78 |
|
xl7dev/BurpSuite | d1d4bd4981a87f2f4c0c9744ad7c476336c813da | Extender/burp-protobuf-decoder/Lib/google/protobuf/internal/encoder.py | python | _TagSize | (field_number) | return _VarintSize(wire_format.PackTag(field_number, 0)) | Returns the number of bytes required to serialize a tag with this field
number. | Returns the number of bytes required to serialize a tag with this field
number. | [
"Returns",
"the",
"number",
"of",
"bytes",
"required",
"to",
"serialize",
"a",
"tag",
"with",
"this",
"field",
"number",
"."
] | def _TagSize(field_number):
"""Returns the number of bytes required to serialize a tag with this field
number."""
# Just pass in type 0, since the type won't affect the tag+type size.
return _VarintSize(wire_format.PackTag(field_number, 0)) | [
"def",
"_TagSize",
"(",
"field_number",
")",
":",
"# Just pass in type 0, since the type won't affect the tag+type size.",
"return",
"_VarintSize",
"(",
"wire_format",
".",
"PackTag",
"(",
"field_number",
",",
"0",
")",
")"
] | https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/burp-protobuf-decoder/Lib/google/protobuf/internal/encoder.py#L108-L112 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pgen2/driver.py | python | Driver.parse_stream_raw | (self, stream, debug=False) | return self.parse_tokens(tokens, debug) | Parse a stream and return the syntax tree. | Parse a stream and return the syntax tree. | [
"Parse",
"a",
"stream",
"and",
"return",
"the",
"syntax",
"tree",
"."
] | def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug) | [
"def",
"parse_stream_raw",
"(",
"self",
",",
"stream",
",",
"debug",
"=",
"False",
")",
":",
"tokens",
"=",
"tokenize",
".",
"generate_tokens",
"(",
"stream",
".",
"readline",
")",
"return",
"self",
".",
"parse_tokens",
"(",
"tokens",
",",
"debug",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/pgen2/driver.py#L86-L89 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/urllib.py | python | splithost | (url) | return None, url | splithost('//host[:port]/path') --> 'host[:port]', '/path'. | splithost('//host[:port]/path') --> 'host[:port]', '/path'. | [
"splithost",
"(",
"//",
"host",
"[",
":",
"port",
"]",
"/",
"path",
")",
"--",
">",
"host",
"[",
":",
"port",
"]",
"/",
"path",
"."
] | def splithost(url):
"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
global _hostprog
if _hostprog is None:
import re
_hostprog = re.compile('^//([^/?]*)(.*)$')
match = _hostprog.match(url)
if match:
host_port = match.group(1)
path = match.group(2)
if path and not path.startswith('/'):
path = '/' + path
return host_port, path
return None, url | [
"def",
"splithost",
"(",
"url",
")",
":",
"global",
"_hostprog",
"if",
"_hostprog",
"is",
"None",
":",
"import",
"re",
"_hostprog",
"=",
"re",
".",
"compile",
"(",
"'^//([^/?]*)(.*)$'",
")",
"match",
"=",
"_hostprog",
".",
"match",
"(",
"url",
")",
"if",
"match",
":",
"host_port",
"=",
"match",
".",
"group",
"(",
"1",
")",
"path",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"path",
"and",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"path",
"=",
"'/'",
"+",
"path",
"return",
"host_port",
",",
"path",
"return",
"None",
",",
"url"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/urllib.py#L1059-L1073 |
|
prometheus-ar/vot.ar | 72d8fa1ea08fe417b64340b98dff68df8364afdf | msa/core/ipc/server/armve_controller.py | python | ARMVEController.guardar_tag | (self, tipo_tag, data, marcar_ro, aes_key=False) | return guardado | Guarda un tag.
Argumentos:
tipo_tag -- el tipo de tag a guardar.
data -- el contenido del tag a guardar.
marcar_ro -- quema el tag. | Guarda un tag. | [
"Guarda",
"un",
"tag",
"."
] | def guardar_tag(self, tipo_tag, data, marcar_ro, aes_key=False):
"""Guarda un tag.
Argumentos:
tipo_tag -- el tipo de tag a guardar.
data -- el contenido del tag a guardar.
marcar_ro -- quema el tag.
"""
guardado = False
try:
# si el estado del papel tiene todas las condiciones requeridas
# para guardar el tag.
if self.parent.printer.is_paper_ready():
# traigo los tags
tags = self.parent.rfid.get_tags()
# si tengo un solo tag y puedo guardar.
if (tags is not None and tags[0] is not None and
tags[0]["number"] == 1):
serial_number = tags[0]["serial_number"][0]
# si es un voto y tengo la key de encriptacion lo encripto
if tipo_tag == TAG_VOTO and aes_key:
data = encriptar_voto(aes_key, serial_number, data)
# guardamos el tag y obtenemos el estado de grabación.
guardado = self.write(serial_number, tipo_tag, data,
marcar_ro)
except Exception as e:
logger.exception(e)
return guardado | [
"def",
"guardar_tag",
"(",
"self",
",",
"tipo_tag",
",",
"data",
",",
"marcar_ro",
",",
"aes_key",
"=",
"False",
")",
":",
"guardado",
"=",
"False",
"try",
":",
"# si el estado del papel tiene todas las condiciones requeridas",
"# para guardar el tag.",
"if",
"self",
".",
"parent",
".",
"printer",
".",
"is_paper_ready",
"(",
")",
":",
"# traigo los tags",
"tags",
"=",
"self",
".",
"parent",
".",
"rfid",
".",
"get_tags",
"(",
")",
"# si tengo un solo tag y puedo guardar.",
"if",
"(",
"tags",
"is",
"not",
"None",
"and",
"tags",
"[",
"0",
"]",
"is",
"not",
"None",
"and",
"tags",
"[",
"0",
"]",
"[",
"\"number\"",
"]",
"==",
"1",
")",
":",
"serial_number",
"=",
"tags",
"[",
"0",
"]",
"[",
"\"serial_number\"",
"]",
"[",
"0",
"]",
"# si es un voto y tengo la key de encriptacion lo encripto",
"if",
"tipo_tag",
"==",
"TAG_VOTO",
"and",
"aes_key",
":",
"data",
"=",
"encriptar_voto",
"(",
"aes_key",
",",
"serial_number",
",",
"data",
")",
"# guardamos el tag y obtenemos el estado de grabación.",
"guardado",
"=",
"self",
".",
"write",
"(",
"serial_number",
",",
"tipo_tag",
",",
"data",
",",
"marcar_ro",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"return",
"guardado"
] | https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/ipc/server/armve_controller.py#L492-L521 |
|
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/xcode_emulation.py | python | MacPrefixHeader.GetInclude | (self, lang, arch=None) | Gets the cflags to include the prefix header for language |lang|. | Gets the cflags to include the prefix header for language |lang|. | [
"Gets",
"the",
"cflags",
"to",
"include",
"the",
"prefix",
"header",
"for",
"language",
"|lang|",
"."
] | def GetInclude(self, lang, arch=None):
"""Gets the cflags to include the prefix header for language |lang|."""
if self.compile_headers and lang in self.compiled_headers:
return '-include %s' % self._CompiledHeader(lang, arch)
elif self.header:
return '-include %s' % self.header
else:
return '' | [
"def",
"GetInclude",
"(",
"self",
",",
"lang",
",",
"arch",
"=",
"None",
")",
":",
"if",
"self",
".",
"compile_headers",
"and",
"lang",
"in",
"self",
".",
"compiled_headers",
":",
"return",
"'-include %s'",
"%",
"self",
".",
"_CompiledHeader",
"(",
"lang",
",",
"arch",
")",
"elif",
"self",
".",
"header",
":",
"return",
"'-include %s'",
"%",
"self",
".",
"header",
"else",
":",
"return",
"''"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/xcode_emulation.py#L1332-L1339 |
||
Jumpscale/go-raml | f151e1e143c47282b294fe70c5e56f113988ed10 | codegen/python/fixtures/method/client/complex_body/query_params_requests/animals_service.py | python | AnimalsService.animals_get | (
self,
name,
nodef,
depth=1,
inspect=false,
headers=None,
query_params=None,
content_type="application/json") | test query params
It is method for GET /animals | test query params
It is method for GET /animals | [
"test",
"query",
"params",
"It",
"is",
"method",
"for",
"GET",
"/",
"animals"
] | def animals_get(
self,
name,
nodef,
depth=1,
inspect=false,
headers=None,
query_params=None,
content_type="application/json"):
"""
test query params
It is method for GET /animals
"""
if query_params is None:
query_params = {}
query_params['depth'] = depth
query_params['inspect'] = inspect
query_params['name'] = name
query_params['nodef'] = nodef
uri = self.client.base_url + "/animals"
resp = self.client.get(uri, None, headers, query_params, content_type)
try:
if resp.status_code == 201:
resps = []
for elem in resp.json():
resps.append(animal(elem))
return resps, resp
message = 'unknown status code={}'.format(resp.status_code)
raise UnhandledAPIError(response=resp, code=resp.status_code,
message=message)
except ValueError as msg:
raise UnmarshallError(resp, msg)
except UnhandledAPIError as uae:
raise uae
except Exception as e:
raise UnmarshallError(resp, e.message) | [
"def",
"animals_get",
"(",
"self",
",",
"name",
",",
"nodef",
",",
"depth",
"=",
"1",
",",
"inspect",
"=",
"false",
",",
"headers",
"=",
"None",
",",
"query_params",
"=",
"None",
",",
"content_type",
"=",
"\"application/json\"",
")",
":",
"if",
"query_params",
"is",
"None",
":",
"query_params",
"=",
"{",
"}",
"query_params",
"[",
"'depth'",
"]",
"=",
"depth",
"query_params",
"[",
"'inspect'",
"]",
"=",
"inspect",
"query_params",
"[",
"'name'",
"]",
"=",
"name",
"query_params",
"[",
"'nodef'",
"]",
"=",
"nodef",
"uri",
"=",
"self",
".",
"client",
".",
"base_url",
"+",
"\"/animals\"",
"resp",
"=",
"self",
".",
"client",
".",
"get",
"(",
"uri",
",",
"None",
",",
"headers",
",",
"query_params",
",",
"content_type",
")",
"try",
":",
"if",
"resp",
".",
"status_code",
"==",
"201",
":",
"resps",
"=",
"[",
"]",
"for",
"elem",
"in",
"resp",
".",
"json",
"(",
")",
":",
"resps",
".",
"append",
"(",
"animal",
"(",
"elem",
")",
")",
"return",
"resps",
",",
"resp",
"message",
"=",
"'unknown status code={}'",
".",
"format",
"(",
"resp",
".",
"status_code",
")",
"raise",
"UnhandledAPIError",
"(",
"response",
"=",
"resp",
",",
"code",
"=",
"resp",
".",
"status_code",
",",
"message",
"=",
"message",
")",
"except",
"ValueError",
"as",
"msg",
":",
"raise",
"UnmarshallError",
"(",
"resp",
",",
"msg",
")",
"except",
"UnhandledAPIError",
"as",
"uae",
":",
"raise",
"uae",
"except",
"Exception",
"as",
"e",
":",
"raise",
"UnmarshallError",
"(",
"resp",
",",
"e",
".",
"message",
")"
] | https://github.com/Jumpscale/go-raml/blob/f151e1e143c47282b294fe70c5e56f113988ed10/codegen/python/fixtures/method/client/complex_body/query_params_requests/animals_service.py#L11-L49 |
||
silklabs/silk | 08c273949086350aeddd8e23e92f0f79243f446f | node_modules/node-gyp/gyp/pylib/gyp/generator/make.py | python | MakefileWriter.Objectify | (self, path) | return path | Convert a path to its output directory form. | Convert a path to its output directory form. | [
"Convert",
"a",
"path",
"to",
"its",
"output",
"directory",
"form",
"."
] | def Objectify(self, path):
"""Convert a path to its output directory form."""
if '$(' in path:
path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset)
if not '$(obj)' in path:
path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path)
return path | [
"def",
"Objectify",
"(",
"self",
",",
"path",
")",
":",
"if",
"'$('",
"in",
"path",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"'$(obj)/'",
",",
"'$(obj).%s/$(TARGET)/'",
"%",
"self",
".",
"toolset",
")",
"if",
"not",
"'$(obj)'",
"in",
"path",
":",
"path",
"=",
"'$(obj).%s/$(TARGET)/%s'",
"%",
"(",
"self",
".",
"toolset",
",",
"path",
")",
"return",
"path"
] | https://github.com/silklabs/silk/blob/08c273949086350aeddd8e23e92f0f79243f446f/node_modules/node-gyp/gyp/pylib/gyp/generator/make.py#L1876-L1882 |
|
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | tools/gyp/pylib/gyp/mac_tool.py | python | MacTool._CommandifyName | (self, name_string) | return name_string.title().replace('-', '') | Transforms a tool name like copy-info-plist to CopyInfoPlist | Transforms a tool name like copy-info-plist to CopyInfoPlist | [
"Transforms",
"a",
"tool",
"name",
"like",
"copy",
"-",
"info",
"-",
"plist",
"to",
"CopyInfoPlist"
] | def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace('-', '') | [
"def",
"_CommandifyName",
"(",
"self",
",",
"name_string",
")",
":",
"return",
"name_string",
".",
"title",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/tools/gyp/pylib/gyp/mac_tool.py#L44-L46 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py | python | Script.call_signatures | (self) | return [classes.CallSignature(self._evaluator, d.name,
call_signature_details.bracket_leaf.start_pos,
call_signature_details.call_index,
call_signature_details.keyword_name_str)
for d in definitions if hasattr(d, 'py__call__')] | Return the function object of the call you're currently in.
E.g. if the cursor is here::
abs(# <-- cursor is here
This would return the ``abs`` function. On the other hand::
abs()# <-- cursor is here
This would return an empty list..
:rtype: list of :class:`classes.CallSignature` | Return the function object of the call you're currently in. | [
"Return",
"the",
"function",
"object",
"of",
"the",
"call",
"you",
"re",
"currently",
"in",
"."
] | def call_signatures(self):
"""
Return the function object of the call you're currently in.
E.g. if the cursor is here::
abs(# <-- cursor is here
This would return the ``abs`` function. On the other hand::
abs()# <-- cursor is here
This would return an empty list..
:rtype: list of :class:`classes.CallSignature`
"""
call_signature_details = \
helpers.get_call_signature_details(self._module_node, self._pos)
if call_signature_details is None:
return []
context = self._evaluator.create_context(
self._get_module(),
call_signature_details.bracket_leaf
)
definitions = helpers.cache_call_signatures(
self._evaluator,
context,
call_signature_details.bracket_leaf,
self._code_lines,
self._pos
)
debug.speed('func_call followed')
return [classes.CallSignature(self._evaluator, d.name,
call_signature_details.bracket_leaf.start_pos,
call_signature_details.call_index,
call_signature_details.keyword_name_str)
for d in definitions if hasattr(d, 'py__call__')] | [
"def",
"call_signatures",
"(",
"self",
")",
":",
"call_signature_details",
"=",
"helpers",
".",
"get_call_signature_details",
"(",
"self",
".",
"_module_node",
",",
"self",
".",
"_pos",
")",
"if",
"call_signature_details",
"is",
"None",
":",
"return",
"[",
"]",
"context",
"=",
"self",
".",
"_evaluator",
".",
"create_context",
"(",
"self",
".",
"_get_module",
"(",
")",
",",
"call_signature_details",
".",
"bracket_leaf",
")",
"definitions",
"=",
"helpers",
".",
"cache_call_signatures",
"(",
"self",
".",
"_evaluator",
",",
"context",
",",
"call_signature_details",
".",
"bracket_leaf",
",",
"self",
".",
"_code_lines",
",",
"self",
".",
"_pos",
")",
"debug",
".",
"speed",
"(",
"'func_call followed'",
")",
"return",
"[",
"classes",
".",
"CallSignature",
"(",
"self",
".",
"_evaluator",
",",
"d",
".",
"name",
",",
"call_signature_details",
".",
"bracket_leaf",
".",
"start_pos",
",",
"call_signature_details",
".",
"call_index",
",",
"call_signature_details",
".",
"keyword_name_str",
")",
"for",
"d",
"in",
"definitions",
"if",
"hasattr",
"(",
"d",
",",
"'py__call__'",
")",
"]"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/api/__init__.py#L262-L300 |
|
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | tools/gyp/pylib/gyp/generator/make.py | python | Compilable | (filename) | return False | Return true if the file is compilable (should be in OBJS). | Return true if the file is compilable (should be in OBJS). | [
"Return",
"true",
"if",
"the",
"file",
"is",
"compilable",
"(",
"should",
"be",
"in",
"OBJS",
")",
"."
] | def Compilable(filename):
"""Return true if the file is compilable (should be in OBJS)."""
for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS):
if res:
return True
return False | [
"def",
"Compilable",
"(",
"filename",
")",
":",
"for",
"res",
"in",
"(",
"filename",
".",
"endswith",
"(",
"e",
")",
"for",
"e",
"in",
"COMPILABLE_EXTENSIONS",
")",
":",
"if",
"res",
":",
"return",
"True",
"return",
"False"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/tools/gyp/pylib/gyp/generator/make.py#L564-L569 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | bt5/erp5_crm/DocumentTemplateItem/portal_components/document.erp5.Ticket.py | python | Ticket.isAccountable | (self) | return 1 | Tickets are accountable. | Tickets are accountable. | [
"Tickets",
"are",
"accountable",
"."
] | def isAccountable(self):
"""Tickets are accountable.
"""
return 1 | [
"def",
"isAccountable",
"(",
"self",
")",
":",
"return",
"1"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_crm/DocumentTemplateItem/portal_components/document.erp5.Ticket.py#L78-L81 |
|
defunctzombie/libuv.js | 04a76a470dfdcad14ea8f19b6f215f205a9214f8 | tools/gyp/pylib/gyp/xcode_emulation.py | python | GetSpecPostbuildCommands | (spec, quiet=False) | return postbuilds | Returns the list of postbuilds explicitly defined on |spec|, in a form
executable by a shell. | Returns the list of postbuilds explicitly defined on |spec|, in a form
executable by a shell. | [
"Returns",
"the",
"list",
"of",
"postbuilds",
"explicitly",
"defined",
"on",
"|spec|",
"in",
"a",
"form",
"executable",
"by",
"a",
"shell",
"."
] | def GetSpecPostbuildCommands(spec, quiet=False):
"""Returns the list of postbuilds explicitly defined on |spec|, in a form
executable by a shell."""
postbuilds = []
for postbuild in spec.get('postbuilds', []):
if not quiet:
postbuilds.append('echo POSTBUILD\\(%s\\) %s' % (
spec['target_name'], postbuild['postbuild_name']))
postbuilds.append(gyp.common.EncodePOSIXShellList(postbuild['action']))
return postbuilds | [
"def",
"GetSpecPostbuildCommands",
"(",
"spec",
",",
"quiet",
"=",
"False",
")",
":",
"postbuilds",
"=",
"[",
"]",
"for",
"postbuild",
"in",
"spec",
".",
"get",
"(",
"'postbuilds'",
",",
"[",
"]",
")",
":",
"if",
"not",
"quiet",
":",
"postbuilds",
".",
"append",
"(",
"'echo POSTBUILD\\\\(%s\\\\) %s'",
"%",
"(",
"spec",
"[",
"'target_name'",
"]",
",",
"postbuild",
"[",
"'postbuild_name'",
"]",
")",
")",
"postbuilds",
".",
"append",
"(",
"gyp",
".",
"common",
".",
"EncodePOSIXShellList",
"(",
"postbuild",
"[",
"'action'",
"]",
")",
")",
"return",
"postbuilds"
] | https://github.com/defunctzombie/libuv.js/blob/04a76a470dfdcad14ea8f19b6f215f205a9214f8/tools/gyp/pylib/gyp/xcode_emulation.py#L1271-L1280 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/pkg_resources/__init__.py | python | EntryPoint.parse | (cls, src, dist=None) | return cls(res['name'], res['module'], attrs, extras, dist) | Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional | Parse a single entry point from string `src` | [
"Parse",
"a",
"single",
"entry",
"point",
"from",
"string",
"src"
] | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1, extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
m = cls.pattern.match(src)
if not m:
msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
raise ValueError(msg, src)
res = m.groupdict()
extras = cls._parse_extras(res['extras'])
attrs = res['attr'].split('.') if res['attr'] else ()
return cls(res['name'], res['module'], attrs, extras, dist) | [
"def",
"parse",
"(",
"cls",
",",
"src",
",",
"dist",
"=",
"None",
")",
":",
"m",
"=",
"cls",
".",
"pattern",
".",
"match",
"(",
"src",
")",
"if",
"not",
"m",
":",
"msg",
"=",
"\"EntryPoint must be in 'name=module:attrs [extras]' format\"",
"raise",
"ValueError",
"(",
"msg",
",",
"src",
")",
"res",
"=",
"m",
".",
"groupdict",
"(",
")",
"extras",
"=",
"cls",
".",
"_parse_extras",
"(",
"res",
"[",
"'extras'",
"]",
")",
"attrs",
"=",
"res",
"[",
"'attr'",
"]",
".",
"split",
"(",
"'.'",
")",
"if",
"res",
"[",
"'attr'",
"]",
"else",
"(",
")",
"return",
"cls",
"(",
"res",
"[",
"'name'",
"]",
",",
"res",
"[",
"'module'",
"]",
",",
"attrs",
",",
"extras",
",",
"dist",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/pkg_resources/__init__.py#L2469-L2486 |
|
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/v8/tools/release/common_includes.py | python | VCInterface.Tag | (self, tag, remote, message) | Sets a tag for the current commit.
Assumptions: The commit already landed and the commit message is unique. | Sets a tag for the current commit. | [
"Sets",
"a",
"tag",
"for",
"the",
"current",
"commit",
"."
] | def Tag(self, tag, remote, message):
"""Sets a tag for the current commit.
Assumptions: The commit already landed and the commit message is unique.
"""
raise NotImplementedError() | [
"def",
"Tag",
"(",
"self",
",",
"tag",
",",
"remote",
",",
"message",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/v8/tools/release/common_includes.py#L321-L326 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/spidershim/spidermonkey/python/mach/mach/logging.py | python | LoggingManager.disable_unstructured | (self) | Disable logging of unstructured messages. | Disable logging of unstructured messages. | [
"Disable",
"logging",
"of",
"unstructured",
"messages",
"."
] | def disable_unstructured(self):
"""Disable logging of unstructured messages."""
if self.terminal_handler:
self.terminal_handler.removeFilter(self.structured_filter)
self.root_logger.removeHandler(self.terminal_handler) | [
"def",
"disable_unstructured",
"(",
"self",
")",
":",
"if",
"self",
".",
"terminal_handler",
":",
"self",
".",
"terminal_handler",
".",
"removeFilter",
"(",
"self",
".",
"structured_filter",
")",
"self",
".",
"root_logger",
".",
"removeHandler",
"(",
"self",
".",
"terminal_handler",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/spidershim/spidermonkey/python/mach/mach/logging.py#L251-L255 |
||
IonicChina/ioniclub | 208d5298939672ef44076bb8a7e8e6df5278e286 | node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeOutputBasename | (self, spec) | return ''.join(self.ComputeOutputParts(spec)) | Return the 'output basename' of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'libfoobar.so' | Return the 'output basename' of a gyp spec. | [
"Return",
"the",
"output",
"basename",
"of",
"a",
"gyp",
"spec",
"."
] | def ComputeOutputBasename(self, spec):
"""Return the 'output basename' of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'libfoobar.so'
"""
return ''.join(self.ComputeOutputParts(spec)) | [
"def",
"ComputeOutputBasename",
"(",
"self",
",",
"spec",
")",
":",
"return",
"''",
".",
"join",
"(",
"self",
".",
"ComputeOutputParts",
"(",
"spec",
")",
")"
] | https://github.com/IonicChina/ioniclub/blob/208d5298939672ef44076bb8a7e8e6df5278e286/node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/pylib/gyp/generator/android.py#L660-L666 |
|
hotosm/tasking-manager | 1a7b02c6ccd431029a96d709d4d786c83cb37f5e | backend/api/tasks/actions.py | python | TasksActionsValidationStopAPI.post | (self, project_id) | Unlock tasks that are locked for validation resetting them to their last status
---
tags:
- tasks
produces:
- application/json
parameters:
- in: header
name: Authorization
description: Base64 encoded session token
required: true
type: string
default: Token sessionTokenHere==
- in: header
name: Accept-Language
description: Language user is requesting
type: string
required: true
default: en
- name: project_id
in: path
description: Project ID the task is associated with
required: true
type: integer
default: 1
- in: body
name: body
required: true
description: JSON object for unlocking a task
schema:
properties:
resetTasks:
type: array
items:
schema:
$ref: "#/definitions/ResetTask"
responses:
200:
description: Task unlocked
400:
description: Client Error
401:
description: Unauthorized - Invalid credentials
403:
description: Forbidden
404:
description: Task not found
500:
description: Internal Server Error | Unlock tasks that are locked for validation resetting them to their last status
---
tags:
- tasks
produces:
- application/json
parameters:
- in: header
name: Authorization
description: Base64 encoded session token
required: true
type: string
default: Token sessionTokenHere==
- in: header
name: Accept-Language
description: Language user is requesting
type: string
required: true
default: en
- name: project_id
in: path
description: Project ID the task is associated with
required: true
type: integer
default: 1
- in: body
name: body
required: true
description: JSON object for unlocking a task
schema:
properties:
resetTasks:
type: array
items:
schema:
$ref: "#/definitions/ResetTask"
responses:
200:
description: Task unlocked
400:
description: Client Error
401:
description: Unauthorized - Invalid credentials
403:
description: Forbidden
404:
description: Task not found
500:
description: Internal Server Error | [
"Unlock",
"tasks",
"that",
"are",
"locked",
"for",
"validation",
"resetting",
"them",
"to",
"their",
"last",
"status",
"---",
"tags",
":",
"-",
"tasks",
"produces",
":",
"-",
"application",
"/",
"json",
"parameters",
":",
"-",
"in",
":",
"header",
"name",
":",
"Authorization",
"description",
":",
"Base64",
"encoded",
"session",
"token",
"required",
":",
"true",
"type",
":",
"string",
"default",
":",
"Token",
"sessionTokenHere",
"==",
"-",
"in",
":",
"header",
"name",
":",
"Accept",
"-",
"Language",
"description",
":",
"Language",
"user",
"is",
"requesting",
"type",
":",
"string",
"required",
":",
"true",
"default",
":",
"en",
"-",
"name",
":",
"project_id",
"in",
":",
"path",
"description",
":",
"Project",
"ID",
"the",
"task",
"is",
"associated",
"with",
"required",
":",
"true",
"type",
":",
"integer",
"default",
":",
"1",
"-",
"in",
":",
"body",
"name",
":",
"body",
"required",
":",
"true",
"description",
":",
"JSON",
"object",
"for",
"unlocking",
"a",
"task",
"schema",
":",
"properties",
":",
"resetTasks",
":",
"type",
":",
"array",
"items",
":",
"schema",
":",
"$ref",
":",
"#",
"/",
"definitions",
"/",
"ResetTask",
"responses",
":",
"200",
":",
"description",
":",
"Task",
"unlocked",
"400",
":",
"description",
":",
"Client",
"Error",
"401",
":",
"description",
":",
"Unauthorized",
"-",
"Invalid",
"credentials",
"403",
":",
"description",
":",
"Forbidden",
"404",
":",
"description",
":",
"Task",
"not",
"found",
"500",
":",
"description",
":",
"Internal",
"Server",
"Error"
] | def post(self, project_id):
"""
Unlock tasks that are locked for validation resetting them to their last status
---
tags:
- tasks
produces:
- application/json
parameters:
- in: header
name: Authorization
description: Base64 encoded session token
required: true
type: string
default: Token sessionTokenHere==
- in: header
name: Accept-Language
description: Language user is requesting
type: string
required: true
default: en
- name: project_id
in: path
description: Project ID the task is associated with
required: true
type: integer
default: 1
- in: body
name: body
required: true
description: JSON object for unlocking a task
schema:
properties:
resetTasks:
type: array
items:
schema:
$ref: "#/definitions/ResetTask"
responses:
200:
description: Task unlocked
400:
description: Client Error
401:
description: Unauthorized - Invalid credentials
403:
description: Forbidden
404:
description: Task not found
500:
description: Internal Server Error
"""
try:
validated_dto = StopValidationDTO(request.get_json())
validated_dto.project_id = project_id
validated_dto.user_id = token_auth.current_user()
validated_dto.preferred_locale = request.environ.get("HTTP_ACCEPT_LANGUAGE")
validated_dto.validate()
except DataError as e:
current_app.logger.error(f"Error validating request: {str(e)}")
return {"Error": "Task unlock failed"}, 400
try:
tasks = ValidatorService.stop_validating_tasks(validated_dto)
return tasks.to_primitive(), 200
except ValidatorServiceError:
return {"Error": "Task unlock failed"}, 403
except NotFound:
return {"Error": "Task unlock failed"}, 404
except Exception as e:
error_msg = f"Stop Validating API - unhandled error: {str(e)}"
current_app.logger.critical(error_msg)
return {"Error": "Task unlock failed"}, 500 | [
"def",
"post",
"(",
"self",
",",
"project_id",
")",
":",
"try",
":",
"validated_dto",
"=",
"StopValidationDTO",
"(",
"request",
".",
"get_json",
"(",
")",
")",
"validated_dto",
".",
"project_id",
"=",
"project_id",
"validated_dto",
".",
"user_id",
"=",
"token_auth",
".",
"current_user",
"(",
")",
"validated_dto",
".",
"preferred_locale",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"\"HTTP_ACCEPT_LANGUAGE\"",
")",
"validated_dto",
".",
"validate",
"(",
")",
"except",
"DataError",
"as",
"e",
":",
"current_app",
".",
"logger",
".",
"error",
"(",
"f\"Error validating request: {str(e)}\"",
")",
"return",
"{",
"\"Error\"",
":",
"\"Task unlock failed\"",
"}",
",",
"400",
"try",
":",
"tasks",
"=",
"ValidatorService",
".",
"stop_validating_tasks",
"(",
"validated_dto",
")",
"return",
"tasks",
".",
"to_primitive",
"(",
")",
",",
"200",
"except",
"ValidatorServiceError",
":",
"return",
"{",
"\"Error\"",
":",
"\"Task unlock failed\"",
"}",
",",
"403",
"except",
"NotFound",
":",
"return",
"{",
"\"Error\"",
":",
"\"Task unlock failed\"",
"}",
",",
"404",
"except",
"Exception",
"as",
"e",
":",
"error_msg",
"=",
"f\"Stop Validating API - unhandled error: {str(e)}\"",
"current_app",
".",
"logger",
".",
"critical",
"(",
"error_msg",
")",
"return",
"{",
"\"Error\"",
":",
"\"Task unlock failed\"",
"}",
",",
"500"
] | https://github.com/hotosm/tasking-manager/blob/1a7b02c6ccd431029a96d709d4d786c83cb37f5e/backend/api/tasks/actions.py#L423-L495 |
||
rurseekatze/node-tileserver | 8e1173778c7d5ecd66e95b55eb96e4197dc62e3d | mapcss_parser/parse.py | python | p_supports_condition_disj | (p) | sup_condition : sup_disjunction | sup_condition : sup_disjunction | [
"sup_condition",
":",
"sup_disjunction"
] | def p_supports_condition_disj(p):
'sup_condition : sup_disjunction'
p[0] = ast.SupportsCondition(p[1]) | [
"def",
"p_supports_condition_disj",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"SupportsCondition",
"(",
"p",
"[",
"1",
"]",
")"
] | https://github.com/rurseekatze/node-tileserver/blob/8e1173778c7d5ecd66e95b55eb96e4197dc62e3d/mapcss_parser/parse.py#L246-L248 |
||
prometheus-ar/vot.ar | 72d8fa1ea08fe417b64340b98dff68df8364afdf | msa/modulos/asistida/__init__.py | python | Modulo.__init__ | (self, *args, **kwargs) | Constructor. inicializa lo mismo que Sufragio más el locutor. | Constructor. inicializa lo mismo que Sufragio más el locutor. | [
"Constructor",
".",
"inicializa",
"lo",
"mismo",
"que",
"Sufragio",
"más",
"el",
"locutor",
"."
] | def __init__(self, *args, **kwargs):
"""Constructor. inicializa lo mismo que Sufragio más el locutor."""
ModuloSufragio.__init__(self, *args, **kwargs)
self.config_files = [COMMON_SETTINGS, MODULO_SUFRAGIO, self.nombre]
self._load_config()
self._start_audio()
self.inicializar_locutor() | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ModuloSufragio",
".",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"config_files",
"=",
"[",
"COMMON_SETTINGS",
",",
"MODULO_SUFRAGIO",
",",
"self",
".",
"nombre",
"]",
"self",
".",
"_load_config",
"(",
")",
"self",
".",
"_start_audio",
"(",
")",
"self",
".",
"inicializar_locutor",
"(",
")"
] | https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/modulos/asistida/__init__.py#L23-L29 |
||
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/tactic/ui/checkin/scm_dir_list_wdg.py | python | ScmFileSelectorWdg.get_display | (self) | return top | client_env_var = Config.get_value("perforce", "client_env_var")
if not client_env_var:
client_env_var = "P4Client"
port_env_var = Config.get_value("perforce", "port_env_var")
if not port_env_var:
port_env_var = "P4Port"
user_env_var = Config.get_value("perforce", "user_env_var")
if not user_env_var:
user_env_var = "P4User"
password_env_var = Config.get_value("perforce", "password_env_var")
if not password_env_var:
password_env_var = "P4Passwd" | client_env_var = Config.get_value("perforce", "client_env_var")
if not client_env_var:
client_env_var = "P4Client"
port_env_var = Config.get_value("perforce", "port_env_var")
if not port_env_var:
port_env_var = "P4Port"
user_env_var = Config.get_value("perforce", "user_env_var")
if not user_env_var:
user_env_var = "P4User"
password_env_var = Config.get_value("perforce", "password_env_var")
if not password_env_var:
password_env_var = "P4Passwd" | [
"client_env_var",
"=",
"Config",
".",
"get_value",
"(",
"perforce",
"client_env_var",
")",
"if",
"not",
"client_env_var",
":",
"client_env_var",
"=",
"P4Client",
"port_env_var",
"=",
"Config",
".",
"get_value",
"(",
"perforce",
"port_env_var",
")",
"if",
"not",
"port_env_var",
":",
"port_env_var",
"=",
"P4Port",
"user_env_var",
"=",
"Config",
".",
"get_value",
"(",
"perforce",
"user_env_var",
")",
"if",
"not",
"user_env_var",
":",
"user_env_var",
"=",
"P4User",
"password_env_var",
"=",
"Config",
".",
"get_value",
"(",
"perforce",
"password_env_var",
")",
"if",
"not",
"password_env_var",
":",
"password_env_var",
"=",
"P4Passwd"
] | def get_display(self):
self.search_key = self.kwargs.get("search_key")
self.process = self.kwargs.get("process")
self.sobject = Search.get_by_search_key(self.search_key)
self.pipeline_code = self.kwargs.get("pipeline_code")
top = DivWdg()
top.add_class("spt_file_selector")
top.add_style("position: relative")
hidden = HiddenWdg("mode")
#hidden = TextWdg("mode")
hidden.add_class("spt_mode")
top.add(hidden)
top.add_style("padding: 5px")
top.add_style("min-width: 500px")
top.add_style("min-height: 400px")
top.add_color("background", "background")
top.add_color("color", "color")
#top.add_border()
logo_wdg = DivWdg()
logo = HtmlElement.img(src="/context/icons/logo/perforce_logo.gif")
logo_wdg.add(logo)
top.add(logo_wdg)
logo_wdg.add_style("opacity: 0.2")
logo_wdg.add_style("position: absolute")
logo_wdg.add_style("bottom: 0px")
logo_wdg.add_style("right: 5px")
# get some info from the config file
"""
client_env_var = Config.get_value("perforce", "client_env_var")
if not client_env_var:
client_env_var = "P4Client"
port_env_var = Config.get_value("perforce", "port_env_var")
if not port_env_var:
port_env_var = "P4Port"
user_env_var = Config.get_value("perforce", "user_env_var")
if not user_env_var:
user_env_var = "P4User"
password_env_var = Config.get_value("perforce", "password_env_var")
if not password_env_var:
password_env_var = "P4Passwd"
"""
# {GET(sthpw/login)}_user
host = ""
client = ""
user = ""
password = ""
port = ""
project = self.sobject.get_project()
depot = project.get_value("location", no_exception=True)
if not depot:
depot = ""
top.add_behavior( {
'type': 'load',
#'client_env_var': client_env_var,
#'port_env_var': port_env_var,
#'user_env_var': user_env_var,
#'password_env_var': password_env_var,
'client': client,
'user': user,
'password': password,
'host': host,
'port': port,
'depot': depot,
'cbjs_action': get_onload_js()
} )
list_wdg = DivWdg()
top.add(list_wdg)
list_wdg.add_style("height: 32px")
from tactic.ui.widget import SingleButtonWdg, ButtonNewWdg, ButtonRowWdg
button_row = ButtonRowWdg()
list_wdg.add(button_row)
button_row.add_style("float: left")
button = ButtonNewWdg(title="Refresh", icon=IconWdg.REFRESH, long=False)
button_row.add(button)
button.add_style("float: left")
button.add_behavior( {
'type': 'click_up',
'cbjs_action': '''
spt.app_busy.show("Reading file system ...")
var top = bvr.src_el.getParent(".spt_checkin_top");
spt.panel.refresh(top);
spt.app_busy.hide();
'''
} )
button = ButtonNewWdg(title="Check-out", icon=IconWdg.CHECK_OUT, long=False)
button_row.add(button)
self.sandbox_dir = self.kwargs.get("sandbox_dir")
# what are we trying to do here???
#self.root_sandbox_dir = Environment.get_sandbox_dir()
#project = self.sobject.get_project()
#self.root_sandbox_dir = "%s/%s" % (self.root_sandbox_dir, project.get_code())
#repo_dir = self.sandbox_dir.replace("%s/" % self.root_sandbox_dir, "")
#repo_dir = "%s/%s" % (project.get_code(), repo_dir)
# checkout command requires either starting with //<depot>/ or just
# the relative path to the root. The following removes
# the root of the sandbox folder assuming that this is mapped
# to the base of the depot
self.root_sandbox_dir = Environment.get_sandbox_dir()
repo_dir = self.sandbox_dir
repo_dir = self.sandbox_dir.replace("%s/" % self.root_sandbox_dir, "")
#button.add_style("padding-right: 14px")
button.add_style("float: left")
button.add_behavior( {
'type': 'click_up',
'repo_dir': repo_dir,
'cbjs_action': '''
var top = bvr.src_el.getParent(".spt_checkin_top");
spt.app_busy.show("Reading file system ...")
var data = spt.scm.checkout(bvr.repo_dir)
spt.panel.refresh(top);
spt.app_busy.hide();
'''
} )
button = ButtonNewWdg(title="Perforce Actions", icon=IconWdg.PERFORCE, show_arrow=True)
#button.set_show_arrow_menu(True)
button_row.add(button)
menu = Menu(width=220)
menu_item = MenuItem(type='title', label='Perforce')
menu.add(menu_item)
menu_item = MenuItem(type='action', label='Show Workspaces')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'cbjs_action': '''
var activator = spt.smenu.get_activator(bvr);
var class_name = 'tactic.ui.checkin.WorkspaceWdg';
var top = activator.getParent(".spt_checkin_top");
var content = top.getElement(".spt_checkin_content");
var el = top.getElement(".spt_mode");
el.value = "workspace";
var kwargs = {};
spt.panel.load(content, class_name, kwargs);
'''
} )
menu_item = MenuItem(type='action', label='Show Changelists')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'cbjs_action': '''
var activator = spt.smenu.get_activator(bvr);
var class_name = 'tactic.ui.checkin.ChangelistWdg';
var top = activator.getParent(".spt_checkin_top");
var content = top.getElement(".spt_checkin_content");
var el = top.getElement(".spt_mode");
el.value = "changelist";
var kwargs = {};
spt.panel.load(content, class_name, kwargs);
'''
} )
menu_item = MenuItem(type='action', label='Show Branches')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'cbjs_action': '''
var activator = spt.smenu.get_activator(bvr);
var class_name = 'tactic.ui.checkin.branch_wdg.BranchWdg';
var top = activator.getParent(".spt_checkin_top");
var content = top.getElement(".spt_checkin_content");
var el = top.getElement(".spt_mode");
el.value = "branch";
var kwargs = {};
spt.panel.load(content, class_name, kwargs);
'''
} )
menu_item = MenuItem(type='title', label='Actions')
menu.add(menu_item)
menu_item = MenuItem(type='action', label='Add New Changelist')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'load',
'cbjs_action': '''
var activator = spt.smenu.get_activator(bvr);
spt.scm.run("add_changelist", ["New Changelist"]);
var class_name = 'tactic.ui.checkin.ChangelistWdg';
var top = activator.getParent(".spt_checkin_top");
var content = top.getElement(".spt_checkin_content");
spt.panel.load(content, class_name);
'''
} )
menu_item = MenuItem(type='separator')
menu.add(menu_item)
menu_item = MenuItem(type='action', label='Sign Out of Perforce')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'load',
'cbjs_action': '''
if (!confirm("Are you sure you wish to sign out of Perforce?")) {
return;
}
spt.scm.signout_user();
var activator = spt.smenu.get_activator(bvr);
var top = activator.getParent(".spt_checkin_top");
spt.panel.refresh(top);
'''
} )
#SmartMenu.add_smart_menu_set( button.get_arrow_wdg(), { 'BUTTON_MENU': menu } )
#SmartMenu.assign_as_local_activator( button.get_arrow_wdg(), "BUTTON_MENU", True )
SmartMenu.add_smart_menu_set( button.get_button_wdg(), { 'BUTTON_MENU': menu } )
SmartMenu.assign_as_local_activator( button.get_button_wdg(), "BUTTON_MENU", True )
# Perforce script editor. (nice because it should run as the user
# in the appopriate environment
"""
button = ButtonNewWdg(title="P4 Script Editor", icon=IconWdg.CREATE, show_arrow=True)
#button_row.add(button)
button.add_style("padding-right: 14px")
button.add_style("float: left")
"""
button = ButtonNewWdg(title="Changelists Counter", icon=IconWdg.CHECK_OUT_SM, show_arrow=True)
#button_row.add(button)
#button.add_style("padding-right: 14px")
button.add_style("float: left")
button.add_behavior( {
'type': 'click_up',
'cbjs_action': '''
// find any changelists that were missed
var changelists = spt.scm.run("get_changelists", []);
for (var i = 0; i < changelists.length; i++) {
var changelist = changelists[i];
var info = spt.scm.run("get_changelist_info",[changelist.change]);
console.log(info);
}
'''
} )
# Hiding this for now
button = ButtonNewWdg(title="Create", icon=IconWdg.NEW, show_arrow=True)
#button_row.add(button)
button.add_style("padding-right: 14px")
button.add_style("float: left")
menu = Menu(width=220)
menu_item = MenuItem(type='title', label='New ...')
menu.add(menu_item)
menu_item = MenuItem(type='action', label='Text File')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'sandbox_dir': self.sandbox_dir,
'cbjs_action': '''
var path = bvr.sandbox_dir + "/" + "new_text_file.txt";
var env = spt.Environment.get();
var url = env.get_server_url() + "/context/VERSION_API";
var applet = spt.Applet.get();
applet.download_file(url, path);
var activator = spt.smenu.get_activator(bvr);
var top = activator.getParent(".spt_checkin_top");
spt.panel.refresh(top);
'''
} )
#create_sobj = SObject.create("sthpw/virtual")
#create_sobj.set_value("title", "Maya Project")
#create_sobj.set_value("script_path", "create/maya_project")
script_path = 'create/maya_project'
menu_item = MenuItem(type='action', label='Maya Project')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'sandbox_dir': self.sandbox_dir,
'process': self.process,
'script_path': script_path,
'cbjs_action': '''
var script = spt.CustomProject.get_script_by_path(bvr.script_path);
var options = {};
options.script = script;
// add some data to options
options.sandbox_dir = bvr.sandbox_dir;
options.process = bvr.process;
spt.CustomProject.exec_custom_script({}, options);
var activator = spt.smenu.get_activator(bvr);
var top = activator.getParent(".spt_checkin_top");
spt.panel.refresh(top);
'''
} )
template_path = '/context/template/maya_project.zip'
menu_item = MenuItem(type='action', label='Zipped Template')
menu.add(menu_item)
menu_item.add_behavior( {
'type': 'click_up',
'sandbox_dir': self.sandbox_dir,
'template_path': template_path,
'cbjs_action': '''
var path = bvr.sandbox_dir + "/" + "_template.zip";
var env = spt.Environment.get();
var url = env.get_server_url() + bvr.template_path;
var applet = spt.Applet.get();
applet.download_file(url, path);
applet.unzip_file(path, bvr.sandbox_dir);
applet.rmtree(path);
var activator = spt.smenu.get_activator(bvr);
var top = activator.getParent(".spt_checkin_top");
spt.panel.refresh(top);
'''
} )
SmartMenu.add_smart_menu_set( button, { 'BUTTON_MENU': menu } )
SmartMenu.assign_as_local_activator( button, "BUTTON_MENU", True )
# Browse button for browsing files and dirs directly
"""
browse_div = DivWdg()
list_wdg.add(browse_div)
browse_div.add_style("float: left")
button = ActionButtonWdg(title="Browse", tip="Select Files or Folder to Check-In")
browse_div.add(button)
behavior = {
'type': 'click_up',
'base_dir': self.sandbox_dir,
'cbjs_action': '''
var current_dir = bvr.base_dir;
var is_sandbox = false;
spt.checkin.browse_folder(current_dir, is_sandbox);
'''
}
button.add_behavior( behavior )
"""
from tactic.ui.widget import SandboxButtonWdg, CheckoutButtonWdg, ExploreButtonWdg, GearMenuButtonWdg
button_row = ButtonRowWdg()
list_wdg.add(button_row)
button_row.add_style("float: right")
#button = SandboxButtonWdg(base_dir=self.sandbox_dir, process=self.process)
#button_row.add(button)
#button = CheckoutButtonWdg(base_dir=self.sandbox_dir, sobject=self.sobject, proces=self.process)
#button_row.add(button)
button = ExploreButtonWdg(base_dir=self.sandbox_dir)
button_row.add(button)
button = GearMenuButtonWdg(base_dir=self.sandbox_dir, process=self.process, pipeline_code=self.pipeline_code)
button_row.add(button)
list_wdg.add("<br clear='all'/>")
top.add("<hr/>")
content_div = DivWdg()
top.add(content_div)
content_div.add_class("spt_checkin_content")
content = self.get_content_wdg()
content_div.add(content)
return top | [
"def",
"get_display",
"(",
"self",
")",
":",
"self",
".",
"search_key",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"search_key\"",
")",
"self",
".",
"process",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"process\"",
")",
"self",
".",
"sobject",
"=",
"Search",
".",
"get_by_search_key",
"(",
"self",
".",
"search_key",
")",
"self",
".",
"pipeline_code",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"pipeline_code\"",
")",
"top",
"=",
"DivWdg",
"(",
")",
"top",
".",
"add_class",
"(",
"\"spt_file_selector\"",
")",
"top",
".",
"add_style",
"(",
"\"position: relative\"",
")",
"hidden",
"=",
"HiddenWdg",
"(",
"\"mode\"",
")",
"#hidden = TextWdg(\"mode\")",
"hidden",
".",
"add_class",
"(",
"\"spt_mode\"",
")",
"top",
".",
"add",
"(",
"hidden",
")",
"top",
".",
"add_style",
"(",
"\"padding: 5px\"",
")",
"top",
".",
"add_style",
"(",
"\"min-width: 500px\"",
")",
"top",
".",
"add_style",
"(",
"\"min-height: 400px\"",
")",
"top",
".",
"add_color",
"(",
"\"background\"",
",",
"\"background\"",
")",
"top",
".",
"add_color",
"(",
"\"color\"",
",",
"\"color\"",
")",
"#top.add_border()",
"logo_wdg",
"=",
"DivWdg",
"(",
")",
"logo",
"=",
"HtmlElement",
".",
"img",
"(",
"src",
"=",
"\"/context/icons/logo/perforce_logo.gif\"",
")",
"logo_wdg",
".",
"add",
"(",
"logo",
")",
"top",
".",
"add",
"(",
"logo_wdg",
")",
"logo_wdg",
".",
"add_style",
"(",
"\"opacity: 0.2\"",
")",
"logo_wdg",
".",
"add_style",
"(",
"\"position: absolute\"",
")",
"logo_wdg",
".",
"add_style",
"(",
"\"bottom: 0px\"",
")",
"logo_wdg",
".",
"add_style",
"(",
"\"right: 5px\"",
")",
"# get some info from the config file",
"# {GET(sthpw/login)}_user",
"host",
"=",
"\"\"",
"client",
"=",
"\"\"",
"user",
"=",
"\"\"",
"password",
"=",
"\"\"",
"port",
"=",
"\"\"",
"project",
"=",
"self",
".",
"sobject",
".",
"get_project",
"(",
")",
"depot",
"=",
"project",
".",
"get_value",
"(",
"\"location\"",
",",
"no_exception",
"=",
"True",
")",
"if",
"not",
"depot",
":",
"depot",
"=",
"\"\"",
"top",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'load'",
",",
"#'client_env_var': client_env_var,",
"#'port_env_var': port_env_var,",
"#'user_env_var': user_env_var,",
"#'password_env_var': password_env_var,",
"'client'",
":",
"client",
",",
"'user'",
":",
"user",
",",
"'password'",
":",
"password",
",",
"'host'",
":",
"host",
",",
"'port'",
":",
"port",
",",
"'depot'",
":",
"depot",
",",
"'cbjs_action'",
":",
"get_onload_js",
"(",
")",
"}",
")",
"list_wdg",
"=",
"DivWdg",
"(",
")",
"top",
".",
"add",
"(",
"list_wdg",
")",
"list_wdg",
".",
"add_style",
"(",
"\"height: 32px\"",
")",
"from",
"tactic",
".",
"ui",
".",
"widget",
"import",
"SingleButtonWdg",
",",
"ButtonNewWdg",
",",
"ButtonRowWdg",
"button_row",
"=",
"ButtonRowWdg",
"(",
")",
"list_wdg",
".",
"add",
"(",
"button_row",
")",
"button_row",
".",
"add_style",
"(",
"\"float: left\"",
")",
"button",
"=",
"ButtonNewWdg",
"(",
"title",
"=",
"\"Refresh\"",
",",
"icon",
"=",
"IconWdg",
".",
"REFRESH",
",",
"long",
"=",
"False",
")",
"button_row",
".",
"add",
"(",
"button",
")",
"button",
".",
"add_style",
"(",
"\"float: left\"",
")",
"button",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'cbjs_action'",
":",
"'''\n spt.app_busy.show(\"Reading file system ...\")\n var top = bvr.src_el.getParent(\".spt_checkin_top\");\n spt.panel.refresh(top);\n spt.app_busy.hide();\n '''",
"}",
")",
"button",
"=",
"ButtonNewWdg",
"(",
"title",
"=",
"\"Check-out\"",
",",
"icon",
"=",
"IconWdg",
".",
"CHECK_OUT",
",",
"long",
"=",
"False",
")",
"button_row",
".",
"add",
"(",
"button",
")",
"self",
".",
"sandbox_dir",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"sandbox_dir\"",
")",
"# what are we trying to do here???",
"#self.root_sandbox_dir = Environment.get_sandbox_dir()",
"#project = self.sobject.get_project()",
"#self.root_sandbox_dir = \"%s/%s\" % (self.root_sandbox_dir, project.get_code())",
"#repo_dir = self.sandbox_dir.replace(\"%s/\" % self.root_sandbox_dir, \"\")",
"#repo_dir = \"%s/%s\" % (project.get_code(), repo_dir)",
"# checkout command requires either starting with //<depot>/ or just",
"# the relative path to the root. The following removes",
"# the root of the sandbox folder assuming that this is mapped",
"# to the base of the depot",
"self",
".",
"root_sandbox_dir",
"=",
"Environment",
".",
"get_sandbox_dir",
"(",
")",
"repo_dir",
"=",
"self",
".",
"sandbox_dir",
"repo_dir",
"=",
"self",
".",
"sandbox_dir",
".",
"replace",
"(",
"\"%s/\"",
"%",
"self",
".",
"root_sandbox_dir",
",",
"\"\"",
")",
"#button.add_style(\"padding-right: 14px\")",
"button",
".",
"add_style",
"(",
"\"float: left\"",
")",
"button",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'repo_dir'",
":",
"repo_dir",
",",
"'cbjs_action'",
":",
"'''\n var top = bvr.src_el.getParent(\".spt_checkin_top\");\n spt.app_busy.show(\"Reading file system ...\")\n\n var data = spt.scm.checkout(bvr.repo_dir)\n spt.panel.refresh(top);\n\n spt.app_busy.hide();\n '''",
"}",
")",
"button",
"=",
"ButtonNewWdg",
"(",
"title",
"=",
"\"Perforce Actions\"",
",",
"icon",
"=",
"IconWdg",
".",
"PERFORCE",
",",
"show_arrow",
"=",
"True",
")",
"#button.set_show_arrow_menu(True)",
"button_row",
".",
"add",
"(",
"button",
")",
"menu",
"=",
"Menu",
"(",
"width",
"=",
"220",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'title'",
",",
"label",
"=",
"'Perforce'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Show Workspaces'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'cbjs_action'",
":",
"'''\n var activator = spt.smenu.get_activator(bvr);\n\n var class_name = 'tactic.ui.checkin.WorkspaceWdg';\n var top = activator.getParent(\".spt_checkin_top\");\n var content = top.getElement(\".spt_checkin_content\");\n\n var el = top.getElement(\".spt_mode\");\n el.value = \"workspace\";\n\n var kwargs = {};\n spt.panel.load(content, class_name, kwargs);\n '''",
"}",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Show Changelists'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'cbjs_action'",
":",
"'''\n var activator = spt.smenu.get_activator(bvr);\n\n var class_name = 'tactic.ui.checkin.ChangelistWdg';\n var top = activator.getParent(\".spt_checkin_top\");\n var content = top.getElement(\".spt_checkin_content\");\n\n var el = top.getElement(\".spt_mode\");\n el.value = \"changelist\";\n\n var kwargs = {};\n spt.panel.load(content, class_name, kwargs);\n '''",
"}",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Show Branches'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'cbjs_action'",
":",
"'''\n var activator = spt.smenu.get_activator(bvr);\n\n var class_name = 'tactic.ui.checkin.branch_wdg.BranchWdg';\n var top = activator.getParent(\".spt_checkin_top\");\n var content = top.getElement(\".spt_checkin_content\");\n\n var el = top.getElement(\".spt_mode\");\n el.value = \"branch\";\n\n var kwargs = {};\n spt.panel.load(content, class_name, kwargs);\n '''",
"}",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'title'",
",",
"label",
"=",
"'Actions'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Add New Changelist'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'load'",
",",
"'cbjs_action'",
":",
"'''\n var activator = spt.smenu.get_activator(bvr);\n spt.scm.run(\"add_changelist\", [\"New Changelist\"]);\n\n var class_name = 'tactic.ui.checkin.ChangelistWdg';\n var top = activator.getParent(\".spt_checkin_top\");\n var content = top.getElement(\".spt_checkin_content\");\n spt.panel.load(content, class_name);\n\n '''",
"}",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'separator'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Sign Out of Perforce'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'load'",
",",
"'cbjs_action'",
":",
"'''\n\n if (!confirm(\"Are you sure you wish to sign out of Perforce?\")) {\n return;\n }\n spt.scm.signout_user();\n\n var activator = spt.smenu.get_activator(bvr);\n var top = activator.getParent(\".spt_checkin_top\");\n spt.panel.refresh(top);\n\n\n '''",
"}",
")",
"#SmartMenu.add_smart_menu_set( button.get_arrow_wdg(), { 'BUTTON_MENU': menu } )",
"#SmartMenu.assign_as_local_activator( button.get_arrow_wdg(), \"BUTTON_MENU\", True )",
"SmartMenu",
".",
"add_smart_menu_set",
"(",
"button",
".",
"get_button_wdg",
"(",
")",
",",
"{",
"'BUTTON_MENU'",
":",
"menu",
"}",
")",
"SmartMenu",
".",
"assign_as_local_activator",
"(",
"button",
".",
"get_button_wdg",
"(",
")",
",",
"\"BUTTON_MENU\"",
",",
"True",
")",
"# Perforce script editor. (nice because it should run as the user",
"# in the appopriate environment",
"\"\"\"\n button = ButtonNewWdg(title=\"P4 Script Editor\", icon=IconWdg.CREATE, show_arrow=True)\n #button_row.add(button)\n button.add_style(\"padding-right: 14px\")\n button.add_style(\"float: left\")\n \"\"\"",
"button",
"=",
"ButtonNewWdg",
"(",
"title",
"=",
"\"Changelists Counter\"",
",",
"icon",
"=",
"IconWdg",
".",
"CHECK_OUT_SM",
",",
"show_arrow",
"=",
"True",
")",
"#button_row.add(button)",
"#button.add_style(\"padding-right: 14px\")",
"button",
".",
"add_style",
"(",
"\"float: left\"",
")",
"button",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'cbjs_action'",
":",
"'''\n // find any changelists that were missed\n var changelists = spt.scm.run(\"get_changelists\", []);\n for (var i = 0; i < changelists.length; i++) {\n var changelist = changelists[i];\n var info = spt.scm.run(\"get_changelist_info\",[changelist.change]);\n console.log(info);\n }\n '''",
"}",
")",
"# Hiding this for now",
"button",
"=",
"ButtonNewWdg",
"(",
"title",
"=",
"\"Create\"",
",",
"icon",
"=",
"IconWdg",
".",
"NEW",
",",
"show_arrow",
"=",
"True",
")",
"#button_row.add(button)",
"button",
".",
"add_style",
"(",
"\"padding-right: 14px\"",
")",
"button",
".",
"add_style",
"(",
"\"float: left\"",
")",
"menu",
"=",
"Menu",
"(",
"width",
"=",
"220",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'title'",
",",
"label",
"=",
"'New ...'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Text File'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'sandbox_dir'",
":",
"self",
".",
"sandbox_dir",
",",
"'cbjs_action'",
":",
"'''\n var path = bvr.sandbox_dir + \"/\" + \"new_text_file.txt\";\n var env = spt.Environment.get();\n var url = env.get_server_url() + \"/context/VERSION_API\";\n var applet = spt.Applet.get();\n applet.download_file(url, path);\n\n var activator = spt.smenu.get_activator(bvr);\n var top = activator.getParent(\".spt_checkin_top\");\n spt.panel.refresh(top);\n\n '''",
"}",
")",
"#create_sobj = SObject.create(\"sthpw/virtual\")",
"#create_sobj.set_value(\"title\", \"Maya Project\")",
"#create_sobj.set_value(\"script_path\", \"create/maya_project\")",
"script_path",
"=",
"'create/maya_project'",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Maya Project'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'sandbox_dir'",
":",
"self",
".",
"sandbox_dir",
",",
"'process'",
":",
"self",
".",
"process",
",",
"'script_path'",
":",
"script_path",
",",
"'cbjs_action'",
":",
"'''\n var script = spt.CustomProject.get_script_by_path(bvr.script_path);\n var options = {};\n options.script = script;\n\n // add some data to options\n options.sandbox_dir = bvr.sandbox_dir;\n options.process = bvr.process;\n spt.CustomProject.exec_custom_script({}, options);\n\n var activator = spt.smenu.get_activator(bvr);\n var top = activator.getParent(\".spt_checkin_top\");\n spt.panel.refresh(top);\n '''",
"}",
")",
"template_path",
"=",
"'/context/template/maya_project.zip'",
"menu_item",
"=",
"MenuItem",
"(",
"type",
"=",
"'action'",
",",
"label",
"=",
"'Zipped Template'",
")",
"menu",
".",
"add",
"(",
"menu_item",
")",
"menu_item",
".",
"add_behavior",
"(",
"{",
"'type'",
":",
"'click_up'",
",",
"'sandbox_dir'",
":",
"self",
".",
"sandbox_dir",
",",
"'template_path'",
":",
"template_path",
",",
"'cbjs_action'",
":",
"'''\n var path = bvr.sandbox_dir + \"/\" + \"_template.zip\";\n var env = spt.Environment.get();\n var url = env.get_server_url() + bvr.template_path;\n var applet = spt.Applet.get();\n applet.download_file(url, path);\n applet.unzip_file(path, bvr.sandbox_dir);\n applet.rmtree(path);\n\n var activator = spt.smenu.get_activator(bvr);\n var top = activator.getParent(\".spt_checkin_top\");\n spt.panel.refresh(top);\n\n '''",
"}",
")",
"SmartMenu",
".",
"add_smart_menu_set",
"(",
"button",
",",
"{",
"'BUTTON_MENU'",
":",
"menu",
"}",
")",
"SmartMenu",
".",
"assign_as_local_activator",
"(",
"button",
",",
"\"BUTTON_MENU\"",
",",
"True",
")",
"# Browse button for browsing files and dirs directly",
"\"\"\"\n browse_div = DivWdg()\n list_wdg.add(browse_div)\n browse_div.add_style(\"float: left\")\n\n button = ActionButtonWdg(title=\"Browse\", tip=\"Select Files or Folder to Check-In\")\n browse_div.add(button)\n\n behavior = {\n 'type': 'click_up',\n 'base_dir': self.sandbox_dir,\n 'cbjs_action': '''\n var current_dir = bvr.base_dir;\n var is_sandbox = false;\n spt.checkin.browse_folder(current_dir, is_sandbox);\n '''\n }\n button.add_behavior( behavior )\n \"\"\"",
"from",
"tactic",
".",
"ui",
".",
"widget",
"import",
"SandboxButtonWdg",
",",
"CheckoutButtonWdg",
",",
"ExploreButtonWdg",
",",
"GearMenuButtonWdg",
"button_row",
"=",
"ButtonRowWdg",
"(",
")",
"list_wdg",
".",
"add",
"(",
"button_row",
")",
"button_row",
".",
"add_style",
"(",
"\"float: right\"",
")",
"#button = SandboxButtonWdg(base_dir=self.sandbox_dir, process=self.process)",
"#button_row.add(button)",
"#button = CheckoutButtonWdg(base_dir=self.sandbox_dir, sobject=self.sobject, proces=self.process)",
"#button_row.add(button)",
"button",
"=",
"ExploreButtonWdg",
"(",
"base_dir",
"=",
"self",
".",
"sandbox_dir",
")",
"button_row",
".",
"add",
"(",
"button",
")",
"button",
"=",
"GearMenuButtonWdg",
"(",
"base_dir",
"=",
"self",
".",
"sandbox_dir",
",",
"process",
"=",
"self",
".",
"process",
",",
"pipeline_code",
"=",
"self",
".",
"pipeline_code",
")",
"button_row",
".",
"add",
"(",
"button",
")",
"list_wdg",
".",
"add",
"(",
"\"<br clear='all'/>\"",
")",
"top",
".",
"add",
"(",
"\"<hr/>\"",
")",
"content_div",
"=",
"DivWdg",
"(",
")",
"top",
".",
"add",
"(",
"content_div",
")",
"content_div",
".",
"add_class",
"(",
"\"spt_checkin_content\"",
")",
"content",
"=",
"self",
".",
"get_content_wdg",
"(",
")",
"content_div",
".",
"add",
"(",
"content",
")",
"return",
"top"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/tactic/ui/checkin/scm_dir_list_wdg.py#L270-L726 |
|
harvard-lil/perma | c54ff21b3eee931f5094a7654fdddc9ad90fc29c | perma_web/perma/views/common.py | python | about | (request) | return render(request, 'about.html', {
'partners': partners,
'partners_first_col': partners_first_col,
'partners_last_col': partners_last_col
}) | The about page | The about page | [
"The",
"about",
"page"
] | def about(request):
"""
The about page
"""
partners = sorted(Registrar.objects.filter(show_partner_status=True), key=lambda r: r.partner_display_name or r.name)
halfway_point = int(len(partners)/2)
# sending two sets of arrays so that we can separate them
# into two columns alphabetically, the right way
partners_first_col = partners[:halfway_point] if len(partners) > 0 else []
partners_last_col = partners[halfway_point:] if len(partners) > 0 else []
return render(request, 'about.html', {
'partners': partners,
'partners_first_col': partners_first_col,
'partners_last_col': partners_last_col
}) | [
"def",
"about",
"(",
"request",
")",
":",
"partners",
"=",
"sorted",
"(",
"Registrar",
".",
"objects",
".",
"filter",
"(",
"show_partner_status",
"=",
"True",
")",
",",
"key",
"=",
"lambda",
"r",
":",
"r",
".",
"partner_display_name",
"or",
"r",
".",
"name",
")",
"halfway_point",
"=",
"int",
"(",
"len",
"(",
"partners",
")",
"/",
"2",
")",
"# sending two sets of arrays so that we can separate them",
"# into two columns alphabetically, the right way",
"partners_first_col",
"=",
"partners",
"[",
":",
"halfway_point",
"]",
"if",
"len",
"(",
"partners",
")",
">",
"0",
"else",
"[",
"]",
"partners_last_col",
"=",
"partners",
"[",
"halfway_point",
":",
"]",
"if",
"len",
"(",
"partners",
")",
">",
"0",
"else",
"[",
"]",
"return",
"render",
"(",
"request",
",",
"'about.html'",
",",
"{",
"'partners'",
":",
"partners",
",",
"'partners_first_col'",
":",
"partners_first_col",
",",
"'partners_last_col'",
":",
"partners_last_col",
"}",
")"
] | https://github.com/harvard-lil/perma/blob/c54ff21b3eee931f5094a7654fdddc9ad90fc29c/perma_web/perma/views/common.py#L75-L93 |
|
downthemall/downthemall-legacy | 84160d789062691de0ffd82bdc4ebc123b540203 | make.py | python | devrdf | (fp, **kw) | return io | Preprocesses install.rdf for default mode | Preprocesses install.rdf for default mode | [
"Preprocesses",
"install",
".",
"rdf",
"for",
"default",
"mode"
] | def devrdf(fp, **kw):
""" Preprocesses install.rdf for default mode """
kw = kw
rdf = XML(fp.read())
node = rdf.getElementsByTagNameNS(NS_EM, 'name')[0].childNodes[0]
node.data += " *unofficial developer build*"
io = BytesIO()
with Reset(io):
io.write(rdf.toxml(encoding="utf-8"))
io.truncate()
rdf.unlink()
return io | [
"def",
"devrdf",
"(",
"fp",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"=",
"kw",
"rdf",
"=",
"XML",
"(",
"fp",
".",
"read",
"(",
")",
")",
"node",
"=",
"rdf",
".",
"getElementsByTagNameNS",
"(",
"NS_EM",
",",
"'name'",
")",
"[",
"0",
"]",
".",
"childNodes",
"[",
"0",
"]",
"node",
".",
"data",
"+=",
"\" *unofficial developer build*\"",
"io",
"=",
"BytesIO",
"(",
")",
"with",
"Reset",
"(",
"io",
")",
":",
"io",
".",
"write",
"(",
"rdf",
".",
"toxml",
"(",
"encoding",
"=",
"\"utf-8\"",
")",
")",
"io",
".",
"truncate",
"(",
")",
"rdf",
".",
"unlink",
"(",
")",
"return",
"io"
] | https://github.com/downthemall/downthemall-legacy/blob/84160d789062691de0ffd82bdc4ebc123b540203/make.py#L437-L449 |
|
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/spidershim/spidermonkey/python/mozbuild/mozpack/files.py | python | BaseFile.is_older | (first, second) | return int(os.path.getmtime(first) * 1000) \
<= int(os.path.getmtime(second) * 1000) | Compares the modification time of two files, and returns whether the
``first`` file is older than the ``second`` file. | Compares the modification time of two files, and returns whether the
``first`` file is older than the ``second`` file. | [
"Compares",
"the",
"modification",
"time",
"of",
"two",
"files",
"and",
"returns",
"whether",
"the",
"first",
"file",
"is",
"older",
"than",
"the",
"second",
"file",
"."
] | def is_older(first, second):
'''
Compares the modification time of two files, and returns whether the
``first`` file is older than the ``second`` file.
'''
# os.path.getmtime returns a result in seconds with precision up to
# the microsecond. But microsecond is too precise because
# shutil.copystat only copies milliseconds, and seconds is not
# enough precision.
return int(os.path.getmtime(first) * 1000) \
<= int(os.path.getmtime(second) * 1000) | [
"def",
"is_older",
"(",
"first",
",",
"second",
")",
":",
"# os.path.getmtime returns a result in seconds with precision up to",
"# the microsecond. But microsecond is too precise because",
"# shutil.copystat only copies milliseconds, and seconds is not",
"# enough precision.",
"return",
"int",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"first",
")",
"*",
"1000",
")",
"<=",
"int",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"second",
")",
"*",
"1000",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/spidershim/spidermonkey/python/mozbuild/mozpack/files.py#L113-L123 |
|
breuleux/terminus | 9d041329e695bbf42ec4eaf4f0d055789e353483 | bin/pexpect.py | python | spawn.write | (self, s) | This is similar to send() except that there is no return value. | This is similar to send() except that there is no return value. | [
"This",
"is",
"similar",
"to",
"send",
"()",
"except",
"that",
"there",
"is",
"no",
"return",
"value",
"."
] | def write(self, s): # File-like object.
"""This is similar to send() except that there is no return value.
"""
self.send (s) | [
"def",
"write",
"(",
"self",
",",
"s",
")",
":",
"# File-like object.",
"self",
".",
"send",
"(",
"s",
")"
] | https://github.com/breuleux/terminus/blob/9d041329e695bbf42ec4eaf4f0d055789e353483/bin/pexpect.py#L926-L931 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py | python | BufferWatch.match | (self, address) | return self.__start <= address < self.__end | Determine if the given memory address lies within the watched buffer.
@rtype: bool
@return: C{True} if the given memory address lies within the watched
buffer, C{False} otherwise. | Determine if the given memory address lies within the watched buffer. | [
"Determine",
"if",
"the",
"given",
"memory",
"address",
"lies",
"within",
"the",
"watched",
"buffer",
"."
] | def match(self, address):
"""
Determine if the given memory address lies within the watched buffer.
@rtype: bool
@return: C{True} if the given memory address lies within the watched
buffer, C{False} otherwise.
"""
return self.__start <= address < self.__end | [
"def",
"match",
"(",
"self",
",",
"address",
")",
":",
"return",
"self",
".",
"__start",
"<=",
"address",
"<",
"self",
".",
"__end"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py#L1806-L1814 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/cookielib.py | python | DefaultCookiePolicy.set_allowed_domains | (self, allowed_domains) | Set the sequence of allowed domains, or None. | Set the sequence of allowed domains, or None. | [
"Set",
"the",
"sequence",
"of",
"allowed",
"domains",
"or",
"None",
"."
] | def set_allowed_domains(self, allowed_domains):
"""Set the sequence of allowed domains, or None."""
if allowed_domains is not None:
allowed_domains = tuple(allowed_domains)
self._allowed_domains = allowed_domains | [
"def",
"set_allowed_domains",
"(",
"self",
",",
"allowed_domains",
")",
":",
"if",
"allowed_domains",
"is",
"not",
"None",
":",
"allowed_domains",
"=",
"tuple",
"(",
"allowed_domains",
")",
"self",
".",
"_allowed_domains",
"=",
"allowed_domains"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/cookielib.py#L897-L901 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/lib2to3/refactor.py | python | RefactoringTool.refactor_dir | (self, dir_name, write=False, doctests_only=False) | Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped. | Descends down a directory and refactor every Python file found. | [
"Descends",
"down",
"a",
"directory",
"and",
"refactor",
"every",
"Python",
"file",
"found",
"."
] | def refactor_dir(self, dir_name, write=False, doctests_only=False):
"""Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped.
"""
py_ext = os.extsep + "py"
for dirpath, dirnames, filenames in os.walk(dir_name):
self.log_debug("Descending into %s", dirpath)
dirnames.sort()
filenames.sort()
for name in filenames:
if (not name.startswith(".") and
os.path.splitext(name)[1] == py_ext):
fullname = os.path.join(dirpath, name)
self.refactor_file(fullname, write, doctests_only)
# Modify dirnames in-place to remove subdirs with leading dots
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")] | [
"def",
"refactor_dir",
"(",
"self",
",",
"dir_name",
",",
"write",
"=",
"False",
",",
"doctests_only",
"=",
"False",
")",
":",
"py_ext",
"=",
"os",
".",
"extsep",
"+",
"\"py\"",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"dir_name",
")",
":",
"self",
".",
"log_debug",
"(",
"\"Descending into %s\"",
",",
"dirpath",
")",
"dirnames",
".",
"sort",
"(",
")",
"filenames",
".",
"sort",
"(",
")",
"for",
"name",
"in",
"filenames",
":",
"if",
"(",
"not",
"name",
".",
"startswith",
"(",
"\".\"",
")",
"and",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
"==",
"py_ext",
")",
":",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"name",
")",
"self",
".",
"refactor_file",
"(",
"fullname",
",",
"write",
",",
"doctests_only",
")",
"# Modify dirnames in-place to remove subdirs with leading dots",
"dirnames",
"[",
":",
"]",
"=",
"[",
"dn",
"for",
"dn",
"in",
"dirnames",
"if",
"not",
"dn",
".",
"startswith",
"(",
"\".\"",
")",
"]"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/lib2to3/refactor.py#L298-L316 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/pipes.py | python | Template.open_r | (self, file) | return os.popen(cmd, 'r') | t.open_r(file) and t.open_w(file) implement
t.open(file, 'r') and t.open(file, 'w') respectively. | t.open_r(file) and t.open_w(file) implement
t.open(file, 'r') and t.open(file, 'w') respectively. | [
"t",
".",
"open_r",
"(",
"file",
")",
"and",
"t",
".",
"open_w",
"(",
"file",
")",
"implement",
"t",
".",
"open",
"(",
"file",
"r",
")",
"and",
"t",
".",
"open",
"(",
"file",
"w",
")",
"respectively",
"."
] | def open_r(self, file):
"""t.open_r(file) and t.open_w(file) implement
t.open(file, 'r') and t.open(file, 'w') respectively."""
if not self.steps:
return open(file, 'r')
if self.steps[-1][1] == SINK:
raise ValueError, \
'Template.open_r: pipeline ends width SINK'
cmd = self.makepipeline(file, '')
return os.popen(cmd, 'r') | [
"def",
"open_r",
"(",
"self",
",",
"file",
")",
":",
"if",
"not",
"self",
".",
"steps",
":",
"return",
"open",
"(",
"file",
",",
"'r'",
")",
"if",
"self",
".",
"steps",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"==",
"SINK",
":",
"raise",
"ValueError",
",",
"'Template.open_r: pipeline ends width SINK'",
"cmd",
"=",
"self",
".",
"makepipeline",
"(",
"file",
",",
"''",
")",
"return",
"os",
".",
"popen",
"(",
"cmd",
",",
"'r'",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/pipes.py#L164-L173 |
|
nodejs/node-convergence-archive | e11fe0c2777561827cdb7207d46b0917ef3c42a7 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | Target.UsesToc | (self, flavor) | return self.type in ('shared_library', 'loadable_module') | Return true if the target should produce a restat rule based on a TOC
file. | Return true if the target should produce a restat rule based on a TOC
file. | [
"Return",
"true",
"if",
"the",
"target",
"should",
"produce",
"a",
"restat",
"rule",
"based",
"on",
"a",
"TOC",
"file",
"."
] | def UsesToc(self, flavor):
"""Return true if the target should produce a restat rule based on a TOC
file."""
# For bundles, the .TOC should be produced for the binary, not for
# FinalOutput(). But the naive approach would put the TOC file into the
# bundle, so don't do this for bundles for now.
if flavor == 'win' or self.bundle:
return False
return self.type in ('shared_library', 'loadable_module') | [
"def",
"UsesToc",
"(",
"self",
",",
"flavor",
")",
":",
"# For bundles, the .TOC should be produced for the binary, not for",
"# FinalOutput(). But the naive approach would put the TOC file into the",
"# bundle, so don't do this for bundles for now.",
"if",
"flavor",
"==",
"'win'",
"or",
"self",
".",
"bundle",
":",
"return",
"False",
"return",
"self",
".",
"type",
"in",
"(",
"'shared_library'",
",",
"'loadable_module'",
")"
] | https://github.com/nodejs/node-convergence-archive/blob/e11fe0c2777561827cdb7207d46b0917ef3c42a7/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L161-L169 |
|
CERT-Polska/drakvuf-sandbox | 765f58cc14ac822a70e605da1c935bc50bd02923 | drakrun/drakrun/vba_graph.py | python | vba_extract_properties | (vba_content_lines) | return vba_prop_dict | Find and extract the use of VBA Properties, in order to obfuscate macros
Args:
vba_content_lines (string[]): VBA code lines without comments, metadata or spaces
Returns:
dict[property_name]=property_code: Dictionary of VBA Properties found | Find and extract the use of VBA Properties, in order to obfuscate macros | [
"Find",
"and",
"extract",
"the",
"use",
"of",
"VBA",
"Properties",
"in",
"order",
"to",
"obfuscate",
"macros"
] | def vba_extract_properties(vba_content_lines):
"""Find and extract the use of VBA Properties, in order to obfuscate macros
Args:
vba_content_lines (string[]): VBA code lines without comments, metadata or spaces
Returns:
dict[property_name]=property_code: Dictionary of VBA Properties found
"""
vba_prop_dict = {}
inside_property = False
prop_name = ""
for vba_line in vba_content_lines:
# Look for property start keywords.
prop_start_pos = max(
vba_line.find("Property Let "), vba_line.find("Property Get ")
)
# Look for property end keywords.
is_prop_end = vba_line.startswith("End Property")
# Check if we've reached the end of a property.
if is_prop_end:
inside_property = False
continue
# Check if we've hit a new property.
elif prop_start_pos > -1:
inside_property = True
# Extract property name from declaration.
if "Property Let " in vba_line or "Property Get " in vba_line:
prop_name = (
vba_line[
(prop_start_pos + len("Property Let ")) : vba_line.find("(")
]
+ " (Property)"
)
else:
logging.error("Error parsing property name")
sys.exit(1)
# Check if we are inside a property code.
elif inside_property:
if prop_name in vba_prop_dict:
# Append code to to an existing property.
vba_prop_dict[prop_name] += LINE_SEP + vba_line
else:
# Create a new property name inside the dict
# & add the first line of code.
vba_prop_dict[prop_name] = vba_line
# We are in a global section code line.
else:
pass
return vba_prop_dict | [
"def",
"vba_extract_properties",
"(",
"vba_content_lines",
")",
":",
"vba_prop_dict",
"=",
"{",
"}",
"inside_property",
"=",
"False",
"prop_name",
"=",
"\"\"",
"for",
"vba_line",
"in",
"vba_content_lines",
":",
"# Look for property start keywords.",
"prop_start_pos",
"=",
"max",
"(",
"vba_line",
".",
"find",
"(",
"\"Property Let \"",
")",
",",
"vba_line",
".",
"find",
"(",
"\"Property Get \"",
")",
")",
"# Look for property end keywords.",
"is_prop_end",
"=",
"vba_line",
".",
"startswith",
"(",
"\"End Property\"",
")",
"# Check if we've reached the end of a property.",
"if",
"is_prop_end",
":",
"inside_property",
"=",
"False",
"continue",
"# Check if we've hit a new property.",
"elif",
"prop_start_pos",
">",
"-",
"1",
":",
"inside_property",
"=",
"True",
"# Extract property name from declaration.",
"if",
"\"Property Let \"",
"in",
"vba_line",
"or",
"\"Property Get \"",
"in",
"vba_line",
":",
"prop_name",
"=",
"(",
"vba_line",
"[",
"(",
"prop_start_pos",
"+",
"len",
"(",
"\"Property Let \"",
")",
")",
":",
"vba_line",
".",
"find",
"(",
"\"(\"",
")",
"]",
"+",
"\" (Property)\"",
")",
"else",
":",
"logging",
".",
"error",
"(",
"\"Error parsing property name\"",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Check if we are inside a property code.",
"elif",
"inside_property",
":",
"if",
"prop_name",
"in",
"vba_prop_dict",
":",
"# Append code to to an existing property.",
"vba_prop_dict",
"[",
"prop_name",
"]",
"+=",
"LINE_SEP",
"+",
"vba_line",
"else",
":",
"# Create a new property name inside the dict",
"# & add the first line of code.",
"vba_prop_dict",
"[",
"prop_name",
"]",
"=",
"vba_line",
"# We are in a global section code line.",
"else",
":",
"pass",
"return",
"vba_prop_dict"
] | https://github.com/CERT-Polska/drakvuf-sandbox/blob/765f58cc14ac822a70e605da1c935bc50bd02923/drakrun/drakrun/vba_graph.py#L222-L280 |
|
iSECPartners/Introspy-Analyzer | ceb2b2429a974a32690ac2d454e0a91f7e817e36 | introspy/DBParser.py | python | DBParser.get_all_files | (self) | return filesList | Returns the list of all files accessed within the traced calls. | Returns the list of all files accessed within the traced calls. | [
"Returns",
"the",
"list",
"of",
"all",
"files",
"accessed",
"within",
"the",
"traced",
"calls",
"."
] | def get_all_files(self):
"""Returns the list of all files accessed within the traced calls."""
filesList = []
for call in self.tracedCalls:
if 'url' in call.argsAndReturnValue['arguments']:
filesList.append(call.argsAndReturnValue['arguments']['url']['absoluteString'])
if 'path' in call.argsAndReturnValue['arguments']:
filesList.append(call.argsAndReturnValue['arguments']['path'])
# Sort and remove duplicates
filesList = dict(map(None,filesList,[])).keys()
filesList.sort()
return filesList | [
"def",
"get_all_files",
"(",
"self",
")",
":",
"filesList",
"=",
"[",
"]",
"for",
"call",
"in",
"self",
".",
"tracedCalls",
":",
"if",
"'url'",
"in",
"call",
".",
"argsAndReturnValue",
"[",
"'arguments'",
"]",
":",
"filesList",
".",
"append",
"(",
"call",
".",
"argsAndReturnValue",
"[",
"'arguments'",
"]",
"[",
"'url'",
"]",
"[",
"'absoluteString'",
"]",
")",
"if",
"'path'",
"in",
"call",
".",
"argsAndReturnValue",
"[",
"'arguments'",
"]",
":",
"filesList",
".",
"append",
"(",
"call",
".",
"argsAndReturnValue",
"[",
"'arguments'",
"]",
"[",
"'path'",
"]",
")",
"# Sort and remove duplicates",
"filesList",
"=",
"dict",
"(",
"map",
"(",
"None",
",",
"filesList",
",",
"[",
"]",
")",
")",
".",
"keys",
"(",
")",
"filesList",
".",
"sort",
"(",
")",
"return",
"filesList"
] | https://github.com/iSECPartners/Introspy-Analyzer/blob/ceb2b2429a974a32690ac2d454e0a91f7e817e36/introspy/DBParser.py#L126-L137 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py | python | Thread.get_teb | (self) | return self.get_process().read_structure( self.get_teb_address(),
win32.TEB ) | Returns a copy of the TEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{TEB}
@return: TEB structure.
@raise WindowsError: An exception is raised on error. | Returns a copy of the TEB.
To dereference pointers in it call L{Process.read_structure}. | [
"Returns",
"a",
"copy",
"of",
"the",
"TEB",
".",
"To",
"dereference",
"pointers",
"in",
"it",
"call",
"L",
"{",
"Process",
".",
"read_structure",
"}",
"."
] | def get_teb(self):
"""
Returns a copy of the TEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{TEB}
@return: TEB structure.
@raise WindowsError: An exception is raised on error.
"""
return self.get_process().read_structure( self.get_teb_address(),
win32.TEB ) | [
"def",
"get_teb",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_process",
"(",
")",
".",
"read_structure",
"(",
"self",
".",
"get_teb_address",
"(",
")",
",",
"win32",
".",
"TEB",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py#L915-L925 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Formulator/help/Form.py | python | Form.get_field_ids | () | As 'get_fields()', but instead returns a list of ids of all the fields.
Permission -- 'View' | As 'get_fields()', but instead returns a list of ids of all the fields. | [
"As",
"get_fields",
"()",
"but",
"instead",
"returns",
"a",
"list",
"of",
"ids",
"of",
"all",
"the",
"fields",
"."
] | def get_field_ids():
"""
As 'get_fields()', but instead returns a list of ids of all the fields.
Permission -- 'View'
""" | [
"def",
"get_field_ids",
"(",
")",
":"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Formulator/help/Form.py#L88-L93 |
||
npm/cli | 892b66eba9f21dbfbc250572d437141e39a6de24 | node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetRuleShellFlags | (self, rule) | return MsvsSettings.RuleShellFlags(cygwin, quote_cmd) | Return RuleShellFlags about how the given rule should be run. This
includes whether it should run under cygwin (msvs_cygwin_shell), and
whether the commands should be quoted (msvs_quote_cmd). | Return RuleShellFlags about how the given rule should be run. This
includes whether it should run under cygwin (msvs_cygwin_shell), and
whether the commands should be quoted (msvs_quote_cmd). | [
"Return",
"RuleShellFlags",
"about",
"how",
"the",
"given",
"rule",
"should",
"be",
"run",
".",
"This",
"includes",
"whether",
"it",
"should",
"run",
"under",
"cygwin",
"(",
"msvs_cygwin_shell",
")",
"and",
"whether",
"the",
"commands",
"should",
"be",
"quoted",
"(",
"msvs_quote_cmd",
")",
"."
] | def GetRuleShellFlags(self, rule):
"""Return RuleShellFlags about how the given rule should be run. This
includes whether it should run under cygwin (msvs_cygwin_shell), and
whether the commands should be quoted (msvs_quote_cmd)."""
# If the variable is unset, or set to 1 we use cygwin
cygwin = int(rule.get("msvs_cygwin_shell",
self.spec.get("msvs_cygwin_shell", 1))) != 0
# Default to quoting. There's only a few special instances where the
# target command uses non-standard command line parsing and handle quotes
# and quote escaping differently.
quote_cmd = int(rule.get("msvs_quote_cmd", 1))
assert quote_cmd != 0 or cygwin != 1, \
"msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0"
return MsvsSettings.RuleShellFlags(cygwin, quote_cmd) | [
"def",
"GetRuleShellFlags",
"(",
"self",
",",
"rule",
")",
":",
"# If the variable is unset, or set to 1 we use cygwin",
"cygwin",
"=",
"int",
"(",
"rule",
".",
"get",
"(",
"\"msvs_cygwin_shell\"",
",",
"self",
".",
"spec",
".",
"get",
"(",
"\"msvs_cygwin_shell\"",
",",
"1",
")",
")",
")",
"!=",
"0",
"# Default to quoting. There's only a few special instances where the",
"# target command uses non-standard command line parsing and handle quotes",
"# and quote escaping differently.",
"quote_cmd",
"=",
"int",
"(",
"rule",
".",
"get",
"(",
"\"msvs_quote_cmd\"",
",",
"1",
")",
")",
"assert",
"quote_cmd",
"!=",
"0",
"or",
"cygwin",
"!=",
"1",
",",
"\"msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0\"",
"return",
"MsvsSettings",
".",
"RuleShellFlags",
"(",
"cygwin",
",",
"quote_cmd",
")"
] | https://github.com/npm/cli/blob/892b66eba9f21dbfbc250572d437141e39a6de24/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L946-L959 |
|
aaPanel/aaPanel | d2a66661dbd66948cce5a074214257550aec91ee | class/safe_warning/sw_mysql_port.py | python | check_run | () | return False,'MySQL port: {}, can be accessed by any server, which may cause MySQL to be cracked by brute force, posing security risks'.format(port_tmp[0]) | @name 开始检测
@author hwliang<2020-08-03>
@return tuple (status<bool>,msg<string>)
@example
status, msg = check_run()
if status:
print('OK')
else:
print('Warning: {}'.format(msg)) | @name 开始检测
@author hwliang<2020-08-03>
@return tuple (status<bool>,msg<string>) | [
"@name",
"开始检测",
"@author",
"hwliang<2020",
"-",
"08",
"-",
"03",
">",
"@return",
"tuple",
"(",
"status<bool",
">",
"msg<string",
">",
")"
] | def check_run():
'''
@name 开始检测
@author hwliang<2020-08-03>
@return tuple (status<bool>,msg<string>)
@example
status, msg = check_run()
if status:
print('OK')
else:
print('Warning: {}'.format(msg))
'''
mycnf_file = '/etc/my.cnf'
if not os.path.exists(mycnf_file):
return True,'MySQL is not installed'
mycnf = public.readFile(mycnf_file)
port_tmp = re.findall(r"port\s*=\s*(\d+)",mycnf)
if not port_tmp:
return True,'MySQL is not installed'
if not public.ExecShell("lsof -i :{}".format(port_tmp[0]))[0]:
return True,'MySQL is not installed'
result = public.check_port_stat(int(port_tmp[0]),public.GetLocalIp())
if result == 0:
return True,'Risk-free'
fail2ban_file = '/www/server/panel/plugin/fail2ban/config.json'
if os.path.exists(fail2ban_file):
try:
fail2ban_config = json.loads(public.readFile(fail2ban_file))
if 'mysql' in fail2ban_config.keys():
if fail2ban_config['mysql']['act'] == 'true':
return True,'Fail2ban is enabled'
except: pass
return False,'MySQL port: {}, can be accessed by any server, which may cause MySQL to be cracked by brute force, posing security risks'.format(port_tmp[0]) | [
"def",
"check_run",
"(",
")",
":",
"mycnf_file",
"=",
"'/etc/my.cnf'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"mycnf_file",
")",
":",
"return",
"True",
",",
"'MySQL is not installed'",
"mycnf",
"=",
"public",
".",
"readFile",
"(",
"mycnf_file",
")",
"port_tmp",
"=",
"re",
".",
"findall",
"(",
"r\"port\\s*=\\s*(\\d+)\"",
",",
"mycnf",
")",
"if",
"not",
"port_tmp",
":",
"return",
"True",
",",
"'MySQL is not installed'",
"if",
"not",
"public",
".",
"ExecShell",
"(",
"\"lsof -i :{}\"",
".",
"format",
"(",
"port_tmp",
"[",
"0",
"]",
")",
")",
"[",
"0",
"]",
":",
"return",
"True",
",",
"'MySQL is not installed'",
"result",
"=",
"public",
".",
"check_port_stat",
"(",
"int",
"(",
"port_tmp",
"[",
"0",
"]",
")",
",",
"public",
".",
"GetLocalIp",
"(",
")",
")",
"if",
"result",
"==",
"0",
":",
"return",
"True",
",",
"'Risk-free'",
"fail2ban_file",
"=",
"'/www/server/panel/plugin/fail2ban/config.json'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fail2ban_file",
")",
":",
"try",
":",
"fail2ban_config",
"=",
"json",
".",
"loads",
"(",
"public",
".",
"readFile",
"(",
"fail2ban_file",
")",
")",
"if",
"'mysql'",
"in",
"fail2ban_config",
".",
"keys",
"(",
")",
":",
"if",
"fail2ban_config",
"[",
"'mysql'",
"]",
"[",
"'act'",
"]",
"==",
"'true'",
":",
"return",
"True",
",",
"'Fail2ban is enabled'",
"except",
":",
"pass",
"return",
"False",
",",
"'MySQL port: {}, can be accessed by any server, which may cause MySQL to be cracked by brute force, posing security risks'",
".",
"format",
"(",
"port_tmp",
"[",
"0",
"]",
")"
] | https://github.com/aaPanel/aaPanel/blob/d2a66661dbd66948cce5a074214257550aec91ee/class/safe_warning/sw_mysql_port.py#L30-L66 |
|
crits/crits | 6b357daa5c3060cf622d3a3b0c7b41a9ca69c049 | crits/core/handlers.py | python | parse_search_term | (term, force_full=False) | return search | Parse a search term to break it into search operators that we can use to
enhance the search results.
:param term: Search term
:type term: str
:returns: search string or dictionary for regex search | Parse a search term to break it into search operators that we can use to
enhance the search results. | [
"Parse",
"a",
"search",
"term",
"to",
"break",
"it",
"into",
"search",
"operators",
"that",
"we",
"can",
"use",
"to",
"enhance",
"the",
"search",
"results",
"."
] | def parse_search_term(term, force_full=False):
"""
Parse a search term to break it into search operators that we can use to
enhance the search results.
:param term: Search term
:type term: str
:returns: search string or dictionary for regex search
"""
# decode the term so we aren't dealing with weird encoded characters
if force_full == False:
term = urllib.unquote(term)
search = {}
# setup lexer, parse our term, and define operators
try:
sh = shlex.shlex(term.strip())
sh.wordchars += '!@#$%^&*()-_=+[]{}|\:;<,>.?/~`'
sh.commenters = ''
parsed = list(iter(sh.get_token, ''))
except Exception as e:
search['query'] = {'error': str(e)}
return search
operators = ['regex', 'full', 'type', 'field']
# for each parsed term, check to see if we have an operator and a value
regex_term = ""
if len(parsed) > 0:
for p in parsed:
s = p.split(':')
if len(s) >= 2:
so = s[0]
st = ':'.join(s[1:])
if so in operators:
# can make this more flexible for regex?
if so == 'regex':
search['query'] = generate_regex(st)
elif so == 'full':
regex_term += "%s " % (st,)
force_full = True
elif so == 'type':
search['type'] = st.title()
elif so == 'field':
search['field'] = remove_quotes(st.lower())
else:
regex_term += "%s:%s " % (so, st)
else:
regex_term += "%s " % p
if regex_term:
if force_full:
search['query'] = remove_quotes(regex_term.strip())
else:
search['query'] = generate_regex(regex_term.strip())
return search | [
"def",
"parse_search_term",
"(",
"term",
",",
"force_full",
"=",
"False",
")",
":",
"# decode the term so we aren't dealing with weird encoded characters",
"if",
"force_full",
"==",
"False",
":",
"term",
"=",
"urllib",
".",
"unquote",
"(",
"term",
")",
"search",
"=",
"{",
"}",
"# setup lexer, parse our term, and define operators",
"try",
":",
"sh",
"=",
"shlex",
".",
"shlex",
"(",
"term",
".",
"strip",
"(",
")",
")",
"sh",
".",
"wordchars",
"+=",
"'!@#$%^&*()-_=+[]{}|\\:;<,>.?/~`'",
"sh",
".",
"commenters",
"=",
"''",
"parsed",
"=",
"list",
"(",
"iter",
"(",
"sh",
".",
"get_token",
",",
"''",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"search",
"[",
"'query'",
"]",
"=",
"{",
"'error'",
":",
"str",
"(",
"e",
")",
"}",
"return",
"search",
"operators",
"=",
"[",
"'regex'",
",",
"'full'",
",",
"'type'",
",",
"'field'",
"]",
"# for each parsed term, check to see if we have an operator and a value",
"regex_term",
"=",
"\"\"",
"if",
"len",
"(",
"parsed",
")",
">",
"0",
":",
"for",
"p",
"in",
"parsed",
":",
"s",
"=",
"p",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"s",
")",
">=",
"2",
":",
"so",
"=",
"s",
"[",
"0",
"]",
"st",
"=",
"':'",
".",
"join",
"(",
"s",
"[",
"1",
":",
"]",
")",
"if",
"so",
"in",
"operators",
":",
"# can make this more flexible for regex?",
"if",
"so",
"==",
"'regex'",
":",
"search",
"[",
"'query'",
"]",
"=",
"generate_regex",
"(",
"st",
")",
"elif",
"so",
"==",
"'full'",
":",
"regex_term",
"+=",
"\"%s \"",
"%",
"(",
"st",
",",
")",
"force_full",
"=",
"True",
"elif",
"so",
"==",
"'type'",
":",
"search",
"[",
"'type'",
"]",
"=",
"st",
".",
"title",
"(",
")",
"elif",
"so",
"==",
"'field'",
":",
"search",
"[",
"'field'",
"]",
"=",
"remove_quotes",
"(",
"st",
".",
"lower",
"(",
")",
")",
"else",
":",
"regex_term",
"+=",
"\"%s:%s \"",
"%",
"(",
"so",
",",
"st",
")",
"else",
":",
"regex_term",
"+=",
"\"%s \"",
"%",
"p",
"if",
"regex_term",
":",
"if",
"force_full",
":",
"search",
"[",
"'query'",
"]",
"=",
"remove_quotes",
"(",
"regex_term",
".",
"strip",
"(",
")",
")",
"else",
":",
"search",
"[",
"'query'",
"]",
"=",
"generate_regex",
"(",
"regex_term",
".",
"strip",
"(",
")",
")",
"return",
"search"
] | https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/core/handlers.py#L1594-L1650 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/ERP5/bootstrap/erp5_core/DocumentTemplateItem/portal_components/document.erp5.ImmobilisableItem.py | python | ImmobilisableItem.isNotCurrentlyImmobilised | (self, **kw) | return not self.isCurrentlyImmobilised(**kw) | Returns true if the item is not immobilised at this time | Returns true if the item is not immobilised at this time | [
"Returns",
"true",
"if",
"the",
"item",
"is",
"not",
"immobilised",
"at",
"this",
"time"
] | def isNotCurrentlyImmobilised(self, **kw):
""" Returns true if the item is not immobilised at this time """
return not self.isCurrentlyImmobilised(**kw) | [
"def",
"isNotCurrentlyImmobilised",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"return",
"not",
"self",
".",
"isCurrentlyImmobilised",
"(",
"*",
"*",
"kw",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/DocumentTemplateItem/portal_components/document.erp5.ImmobilisableItem.py#L630-L632 |
|
korolr/dotfiles | 8e46933503ecb8d8651739ffeb1d2d4f0f5c6524 | .config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py | python | _get_scheme | (view) | return obj, user_css, default_css | Get the scheme object and user CSS. | Get the scheme object and user CSS. | [
"Get",
"the",
"scheme",
"object",
"and",
"user",
"CSS",
"."
] | def _get_scheme(view):
"""Get the scheme object and user CSS."""
scheme = view.settings().get('color_scheme')
settings = sublime.load_settings("Preferences.sublime-settings")
obj = None
user_css = ''
default_css = ''
if scheme is not None:
if scheme in _scheme_cache:
obj, user_css, default_css, t = _scheme_cache[scheme]
# Check if cache expired or user changed pygments setting.
if (
_is_cache_expired(t) or
obj.use_pygments != (not settings.get(HL_SETTING, True)) or
obj.default_style != settings.get(STYLE_SETTING, True)
):
obj = None
user_css = ''
default_css = ''
if obj is None:
try:
obj = SchemeTemplate(scheme)
_prune_cache()
user_css = _get_user_css()
default_css = _get_default_css()
_scheme_cache[scheme] = (obj, user_css, default_css, time.time())
except Exception:
_log('Failed to convert/retrieve scheme to CSS!')
_debug(traceback.format_exc(), ERROR)
return obj, user_css, default_css | [
"def",
"_get_scheme",
"(",
"view",
")",
":",
"scheme",
"=",
"view",
".",
"settings",
"(",
")",
".",
"get",
"(",
"'color_scheme'",
")",
"settings",
"=",
"sublime",
".",
"load_settings",
"(",
"\"Preferences.sublime-settings\"",
")",
"obj",
"=",
"None",
"user_css",
"=",
"''",
"default_css",
"=",
"''",
"if",
"scheme",
"is",
"not",
"None",
":",
"if",
"scheme",
"in",
"_scheme_cache",
":",
"obj",
",",
"user_css",
",",
"default_css",
",",
"t",
"=",
"_scheme_cache",
"[",
"scheme",
"]",
"# Check if cache expired or user changed pygments setting.",
"if",
"(",
"_is_cache_expired",
"(",
"t",
")",
"or",
"obj",
".",
"use_pygments",
"!=",
"(",
"not",
"settings",
".",
"get",
"(",
"HL_SETTING",
",",
"True",
")",
")",
"or",
"obj",
".",
"default_style",
"!=",
"settings",
".",
"get",
"(",
"STYLE_SETTING",
",",
"True",
")",
")",
":",
"obj",
"=",
"None",
"user_css",
"=",
"''",
"default_css",
"=",
"''",
"if",
"obj",
"is",
"None",
":",
"try",
":",
"obj",
"=",
"SchemeTemplate",
"(",
"scheme",
")",
"_prune_cache",
"(",
")",
"user_css",
"=",
"_get_user_css",
"(",
")",
"default_css",
"=",
"_get_default_css",
"(",
")",
"_scheme_cache",
"[",
"scheme",
"]",
"=",
"(",
"obj",
",",
"user_css",
",",
"default_css",
",",
"time",
".",
"time",
"(",
")",
")",
"except",
"Exception",
":",
"_log",
"(",
"'Failed to convert/retrieve scheme to CSS!'",
")",
"_debug",
"(",
"traceback",
".",
"format_exc",
"(",
")",
",",
"ERROR",
")",
"return",
"obj",
",",
"user_css",
",",
"default_css"
] | https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py#L158-L188 |
|
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/jscshim/webkit/Tools/Scripts/webkitpy/style/optparser.py | python | ArgumentPrinter.to_flag_string | (self, options) | return flag_string.strip() | Return a flag string of the given CommandOptionValues instance.
This method orders the flag values alphabetically by the flag key.
Args:
options: A CommandOptionValues instance. | Return a flag string of the given CommandOptionValues instance. | [
"Return",
"a",
"flag",
"string",
"of",
"the",
"given",
"CommandOptionValues",
"instance",
"."
] | def to_flag_string(self, options):
"""Return a flag string of the given CommandOptionValues instance.
This method orders the flag values alphabetically by the flag key.
Args:
options: A CommandOptionValues instance.
"""
flags = {}
flags['min-confidence'] = options.min_confidence
flags['output'] = options.output_format
# Only include the filter flag if user-provided rules are present.
filter_rules = options.filter_rules
if filter_rules:
flags['filter'] = ",".join(filter_rules)
if options.git_commit:
flags['git-commit'] = options.git_commit
if options.diff_files:
flags['diff_files'] = options.diff_files
flag_string = ''
# Alphabetizing lets us unit test this method.
for key in sorted(flags.keys()):
flag_string += self._flag_pair_to_string(key, flags[key]) + ' '
return flag_string.strip() | [
"def",
"to_flag_string",
"(",
"self",
",",
"options",
")",
":",
"flags",
"=",
"{",
"}",
"flags",
"[",
"'min-confidence'",
"]",
"=",
"options",
".",
"min_confidence",
"flags",
"[",
"'output'",
"]",
"=",
"options",
".",
"output_format",
"# Only include the filter flag if user-provided rules are present.",
"filter_rules",
"=",
"options",
".",
"filter_rules",
"if",
"filter_rules",
":",
"flags",
"[",
"'filter'",
"]",
"=",
"\",\"",
".",
"join",
"(",
"filter_rules",
")",
"if",
"options",
".",
"git_commit",
":",
"flags",
"[",
"'git-commit'",
"]",
"=",
"options",
".",
"git_commit",
"if",
"options",
".",
"diff_files",
":",
"flags",
"[",
"'diff_files'",
"]",
"=",
"options",
".",
"diff_files",
"flag_string",
"=",
"''",
"# Alphabetizing lets us unit test this method.",
"for",
"key",
"in",
"sorted",
"(",
"flags",
".",
"keys",
"(",
")",
")",
":",
"flag_string",
"+=",
"self",
".",
"_flag_pair_to_string",
"(",
"key",
",",
"flags",
"[",
"key",
"]",
")",
"+",
"' '",
"return",
"flag_string",
".",
"strip",
"(",
")"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/jscshim/webkit/Tools/Scripts/webkitpy/style/optparser.py#L209-L235 |
|
jam-py/jam-py | 0821492cdff8665928e0f093a4435aa64285a45c | jam/third_party/werkzeug/websocket.py | python | WebSocket._parse_messages | (self) | return msgs | Parses for messages in the buffer *buf*. It is assumed that
the buffer contains the start character for a message, but that it
may contain only part of the rest of the message.
Returns an array of messages, and the buffer remainder that
didn't contain any full messages. | Parses for messages in the buffer *buf*. It is assumed that
the buffer contains the start character for a message, but that it
may contain only part of the rest of the message.
Returns an array of messages, and the buffer remainder that
didn't contain any full messages. | [
"Parses",
"for",
"messages",
"in",
"the",
"buffer",
"*",
"buf",
"*",
".",
"It",
"is",
"assumed",
"that",
"the",
"buffer",
"contains",
"the",
"start",
"character",
"for",
"a",
"message",
"but",
"that",
"it",
"may",
"contain",
"only",
"part",
"of",
"the",
"rest",
"of",
"the",
"message",
".",
"Returns",
"an",
"array",
"of",
"messages",
"and",
"the",
"buffer",
"remainder",
"that",
"didn",
"t",
"contain",
"any",
"full",
"messages",
"."
] | def _parse_messages(self):
""" Parses for messages in the buffer *buf*. It is assumed that
the buffer contains the start character for a message, but that it
may contain only part of the rest of the message.
Returns an array of messages, and the buffer remainder that
didn't contain any full messages."""
msgs = []
end_idx = 0
buf = self._buf
while buf:
if self.version in (7, 8, 13):
frame = decode_hybi(buf, base64=False)
if frame['payload'] == None:
break
else:
if frame['opcode'] == 0x8: # connection close
self.closed = True
break
else:
msgs.append(frame['payload']);
if frame['left']:
buf = buf[-frame['left']:]
else:
buf = b''
else:
frame_type = ord(buf[0])
if frame_type == 0:
# Normal message.
end_idx = buf.find("\xFF")
if end_idx == -1: #pragma NO COVER
break
msgs.append(buf[1:end_idx].decode('utf-8', 'replace'))
buf = buf[end_idx+1:]
elif frame_type == 255:
# Closing handshake.
assert ord(buf[1]) == 0, "Unexpected closing handshake: %r" % buf
self.closed = True
break
else:
raise ValueError("Don't understand how to parse this type of message: %r" % buf)
self._buf = buf
return msgs | [
"def",
"_parse_messages",
"(",
"self",
")",
":",
"msgs",
"=",
"[",
"]",
"end_idx",
"=",
"0",
"buf",
"=",
"self",
".",
"_buf",
"while",
"buf",
":",
"if",
"self",
".",
"version",
"in",
"(",
"7",
",",
"8",
",",
"13",
")",
":",
"frame",
"=",
"decode_hybi",
"(",
"buf",
",",
"base64",
"=",
"False",
")",
"if",
"frame",
"[",
"'payload'",
"]",
"==",
"None",
":",
"break",
"else",
":",
"if",
"frame",
"[",
"'opcode'",
"]",
"==",
"0x8",
":",
"# connection close",
"self",
".",
"closed",
"=",
"True",
"break",
"else",
":",
"msgs",
".",
"append",
"(",
"frame",
"[",
"'payload'",
"]",
")",
"if",
"frame",
"[",
"'left'",
"]",
":",
"buf",
"=",
"buf",
"[",
"-",
"frame",
"[",
"'left'",
"]",
":",
"]",
"else",
":",
"buf",
"=",
"b''",
"else",
":",
"frame_type",
"=",
"ord",
"(",
"buf",
"[",
"0",
"]",
")",
"if",
"frame_type",
"==",
"0",
":",
"# Normal message.",
"end_idx",
"=",
"buf",
".",
"find",
"(",
"\"\\xFF\"",
")",
"if",
"end_idx",
"==",
"-",
"1",
":",
"#pragma NO COVER",
"break",
"msgs",
".",
"append",
"(",
"buf",
"[",
"1",
":",
"end_idx",
"]",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")",
"buf",
"=",
"buf",
"[",
"end_idx",
"+",
"1",
":",
"]",
"elif",
"frame_type",
"==",
"255",
":",
"# Closing handshake.",
"assert",
"ord",
"(",
"buf",
"[",
"1",
"]",
")",
"==",
"0",
",",
"\"Unexpected closing handshake: %r\"",
"%",
"buf",
"self",
".",
"closed",
"=",
"True",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"\"Don't understand how to parse this type of message: %r\"",
"%",
"buf",
")",
"self",
".",
"_buf",
"=",
"buf",
"return",
"msgs"
] | https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/websocket.py#L234-L277 |
|
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.BuildCygwinBashCommandLine | (self, args, path_to_base) | return cmd | Build a command line that runs args via cygwin bash. We assume that all
incoming paths are in Windows normpath'd form, so they need to be
converted to posix style for the part of the command line that's passed to
bash. We also have to do some Visual Studio macro emulation here because
various rules use magic VS names for things. Also note that rules that
contain ninja variables cannot be fixed here (for example ${source}), so
the outer generator needs to make sure that the paths that are written out
are in posix style, if the command line will be used here. | Build a command line that runs args via cygwin bash. We assume that all
incoming paths are in Windows normpath'd form, so they need to be
converted to posix style for the part of the command line that's passed to
bash. We also have to do some Visual Studio macro emulation here because
various rules use magic VS names for things. Also note that rules that
contain ninja variables cannot be fixed here (for example ${source}), so
the outer generator needs to make sure that the paths that are written out
are in posix style, if the command line will be used here. | [
"Build",
"a",
"command",
"line",
"that",
"runs",
"args",
"via",
"cygwin",
"bash",
".",
"We",
"assume",
"that",
"all",
"incoming",
"paths",
"are",
"in",
"Windows",
"normpath",
"d",
"form",
"so",
"they",
"need",
"to",
"be",
"converted",
"to",
"posix",
"style",
"for",
"the",
"part",
"of",
"the",
"command",
"line",
"that",
"s",
"passed",
"to",
"bash",
".",
"We",
"also",
"have",
"to",
"do",
"some",
"Visual",
"Studio",
"macro",
"emulation",
"here",
"because",
"various",
"rules",
"use",
"magic",
"VS",
"names",
"for",
"things",
".",
"Also",
"note",
"that",
"rules",
"that",
"contain",
"ninja",
"variables",
"cannot",
"be",
"fixed",
"here",
"(",
"for",
"example",
"$",
"{",
"source",
"}",
")",
"so",
"the",
"outer",
"generator",
"needs",
"to",
"make",
"sure",
"that",
"the",
"paths",
"that",
"are",
"written",
"out",
"are",
"in",
"posix",
"style",
"if",
"the",
"command",
"line",
"will",
"be",
"used",
"here",
"."
] | def BuildCygwinBashCommandLine(self, args, path_to_base):
"""Build a command line that runs args via cygwin bash. We assume that all
incoming paths are in Windows normpath'd form, so they need to be
converted to posix style for the part of the command line that's passed to
bash. We also have to do some Visual Studio macro emulation here because
various rules use magic VS names for things. Also note that rules that
contain ninja variables cannot be fixed here (for example ${source}), so
the outer generator needs to make sure that the paths that are written out
are in posix style, if the command line will be used here."""
cygwin_dir = os.path.normpath(
os.path.join(path_to_base, self.msvs_cygwin_dirs[0]))
cd = ('cd %s' % path_to_base).replace('\\', '/')
args = [a.replace('\\', '/').replace('"', '\\"') for a in args]
args = ["'%s'" % a.replace("'", "'\\''") for a in args]
bash_cmd = ' '.join(args)
cmd = (
'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir +
'bash -c "%s ; %s"' % (cd, bash_cmd))
return cmd | [
"def",
"BuildCygwinBashCommandLine",
"(",
"self",
",",
"args",
",",
"path_to_base",
")",
":",
"cygwin_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path_to_base",
",",
"self",
".",
"msvs_cygwin_dirs",
"[",
"0",
"]",
")",
")",
"cd",
"=",
"(",
"'cd %s'",
"%",
"path_to_base",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"args",
"=",
"[",
"a",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
"for",
"a",
"in",
"args",
"]",
"args",
"=",
"[",
"\"'%s'\"",
"%",
"a",
".",
"replace",
"(",
"\"'\"",
",",
"\"'\\\\''\"",
")",
"for",
"a",
"in",
"args",
"]",
"bash_cmd",
"=",
"' '",
".",
"join",
"(",
"args",
")",
"cmd",
"=",
"(",
"'call \"%s\\\\setup_env.bat\" && set CYGWIN=nontsec && '",
"%",
"cygwin_dir",
"+",
"'bash -c \"%s ; %s\"'",
"%",
"(",
"cd",
",",
"bash_cmd",
")",
")",
"return",
"cmd"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L802-L820 |
|
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | tools/gyp/pylib/gyp/generator/msvs.py | python | _GenerateNativeRulesForMSVS | (p, rules, output_dir, spec, options) | Generate a native rules file.
Arguments:
p: the target project
rules: the set of rules to include
output_dir: the directory in which the project/gyp resides
spec: the project dict
options: global generator options | Generate a native rules file. | [
"Generate",
"a",
"native",
"rules",
"file",
"."
] | def _GenerateNativeRulesForMSVS(p, rules, output_dir, spec, options):
"""Generate a native rules file.
Arguments:
p: the target project
rules: the set of rules to include
output_dir: the directory in which the project/gyp resides
spec: the project dict
options: global generator options
"""
rules_filename = '%s%s.rules' % (spec['target_name'],
options.suffix)
rules_file = MSVSToolFile.Writer(os.path.join(output_dir, rules_filename),
spec['target_name'])
# Add each rule.
for r in rules:
rule_name = r['rule_name']
rule_ext = r['extension']
inputs = _FixPaths(r.get('inputs', []))
outputs = _FixPaths(r.get('outputs', []))
# Skip a rule with no action and no inputs.
if 'action' not in r and not r.get('rule_sources', []):
continue
cmd = _BuildCommandLineForRule(spec, r, has_input_path=True,
do_setup_env=True)
rules_file.AddCustomBuildRule(name=rule_name,
description=r.get('message', rule_name),
extensions=[rule_ext],
additional_dependencies=inputs,
outputs=outputs,
cmd=cmd)
# Write out rules file.
rules_file.WriteIfChanged()
# Add rules file to project.
p.AddToolFile(rules_filename) | [
"def",
"_GenerateNativeRulesForMSVS",
"(",
"p",
",",
"rules",
",",
"output_dir",
",",
"spec",
",",
"options",
")",
":",
"rules_filename",
"=",
"'%s%s.rules'",
"%",
"(",
"spec",
"[",
"'target_name'",
"]",
",",
"options",
".",
"suffix",
")",
"rules_file",
"=",
"MSVSToolFile",
".",
"Writer",
"(",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"rules_filename",
")",
",",
"spec",
"[",
"'target_name'",
"]",
")",
"# Add each rule.",
"for",
"r",
"in",
"rules",
":",
"rule_name",
"=",
"r",
"[",
"'rule_name'",
"]",
"rule_ext",
"=",
"r",
"[",
"'extension'",
"]",
"inputs",
"=",
"_FixPaths",
"(",
"r",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
")",
"outputs",
"=",
"_FixPaths",
"(",
"r",
".",
"get",
"(",
"'outputs'",
",",
"[",
"]",
")",
")",
"# Skip a rule with no action and no inputs.",
"if",
"'action'",
"not",
"in",
"r",
"and",
"not",
"r",
".",
"get",
"(",
"'rule_sources'",
",",
"[",
"]",
")",
":",
"continue",
"cmd",
"=",
"_BuildCommandLineForRule",
"(",
"spec",
",",
"r",
",",
"has_input_path",
"=",
"True",
",",
"do_setup_env",
"=",
"True",
")",
"rules_file",
".",
"AddCustomBuildRule",
"(",
"name",
"=",
"rule_name",
",",
"description",
"=",
"r",
".",
"get",
"(",
"'message'",
",",
"rule_name",
")",
",",
"extensions",
"=",
"[",
"rule_ext",
"]",
",",
"additional_dependencies",
"=",
"inputs",
",",
"outputs",
"=",
"outputs",
",",
"cmd",
"=",
"cmd",
")",
"# Write out rules file.",
"rules_file",
".",
"WriteIfChanged",
"(",
")",
"# Add rules file to project.",
"p",
".",
"AddToolFile",
"(",
"rules_filename",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/tools/gyp/pylib/gyp/generator/msvs.py#L539-L574 |
||
alex-cory/fasthacks | 72b099f11df2e5640d61e55c80706c3b234eacbe | notes/JavaScript/nodejs/nodeJS_Lynda/command_line_tools/node_modules/connect-mongo/node_modules/mongodb/upload.py | python | SubversionVCS._EscapeFilename | (self, filename) | return filename | Escapes filename for SVN commands. | Escapes filename for SVN commands. | [
"Escapes",
"filename",
"for",
"SVN",
"commands",
"."
] | def _EscapeFilename(self, filename):
"""Escapes filename for SVN commands."""
if "@" in filename and not filename.endswith("@"):
filename = "%s@" % filename
return filename | [
"def",
"_EscapeFilename",
"(",
"self",
",",
"filename",
")",
":",
"if",
"\"@\"",
"in",
"filename",
"and",
"not",
"filename",
".",
"endswith",
"(",
"\"@\"",
")",
":",
"filename",
"=",
"\"%s@\"",
"%",
"filename",
"return",
"filename"
] | https://github.com/alex-cory/fasthacks/blob/72b099f11df2e5640d61e55c80706c3b234eacbe/notes/JavaScript/nodejs/nodeJS_Lynda/command_line_tools/node_modules/connect-mongo/node_modules/mongodb/upload.py#L985-L989 |
|
jam-py/jam-py | 0821492cdff8665928e0f093a4435aa64285a45c | jam/third_party/werkzeug/_internal.py | python | _cookie_parse_impl | (b) | Lowlevel cookie parsing facility that operates on bytes. | Lowlevel cookie parsing facility that operates on bytes. | [
"Lowlevel",
"cookie",
"parsing",
"facility",
"that",
"operates",
"on",
"bytes",
"."
] | def _cookie_parse_impl(b):
"""Lowlevel cookie parsing facility that operates on bytes."""
i = 0
n = len(b)
while i < n:
match = _cookie_re.search(b + b";", i)
if not match:
break
key = match.group("key").strip()
value = match.group("val") or b""
i = match.end(0)
yield _cookie_unquote(key), _cookie_unquote(value) | [
"def",
"_cookie_parse_impl",
"(",
"b",
")",
":",
"i",
"=",
"0",
"n",
"=",
"len",
"(",
"b",
")",
"while",
"i",
"<",
"n",
":",
"match",
"=",
"_cookie_re",
".",
"search",
"(",
"b",
"+",
"b\";\"",
",",
"i",
")",
"if",
"not",
"match",
":",
"break",
"key",
"=",
"match",
".",
"group",
"(",
"\"key\"",
")",
".",
"strip",
"(",
")",
"value",
"=",
"match",
".",
"group",
"(",
"\"val\"",
")",
"or",
"b\"\"",
"i",
"=",
"match",
".",
"end",
"(",
"0",
")",
"yield",
"_cookie_unquote",
"(",
"key",
")",
",",
"_cookie_unquote",
"(",
"value",
")"
] | https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/werkzeug/_internal.py#L315-L329 |
||
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | odoo/addons/base/models/res_lang.py | python | Lang.get_installed | (self) | return sorted([(lang.code, lang.name) for lang in langs], key=itemgetter(1)) | Return the installed languages as a list of (code, name) sorted by name. | Return the installed languages as a list of (code, name) sorted by name. | [
"Return",
"the",
"installed",
"languages",
"as",
"a",
"list",
"of",
"(",
"code",
"name",
")",
"sorted",
"by",
"name",
"."
] | def get_installed(self):
""" Return the installed languages as a list of (code, name) sorted by name. """
langs = self.with_context(active_test=True).search([])
return sorted([(lang.code, lang.name) for lang in langs], key=itemgetter(1)) | [
"def",
"get_installed",
"(",
"self",
")",
":",
"langs",
"=",
"self",
".",
"with_context",
"(",
"active_test",
"=",
"True",
")",
".",
"search",
"(",
"[",
"]",
")",
"return",
"sorted",
"(",
"[",
"(",
"lang",
".",
"code",
",",
"lang",
".",
"name",
")",
"for",
"lang",
"in",
"langs",
"]",
",",
"key",
"=",
"itemgetter",
"(",
"1",
")",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/addons/base/models/res_lang.py#L254-L257 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | agora_site/agora_core/models/voting_systems/plurality.py | python | Plurality.create_tally | (election, question_num) | return PluralityTally(election, question_num) | Create object that helps to compute the tally | Create object that helps to compute the tally | [
"Create",
"object",
"that",
"helps",
"to",
"compute",
"the",
"tally"
] | def create_tally(election, question_num):
'''
Create object that helps to compute the tally
'''
return PluralityTally(election, question_num) | [
"def",
"create_tally",
"(",
"election",
",",
"question_num",
")",
":",
"return",
"PluralityTally",
"(",
"election",
",",
"question_num",
")"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/agora_core/models/voting_systems/plurality.py#L27-L31 |
|
PublicMapping/districtbuilder-classic | 6e4b9d644043082eb0499f5aa77e777fff73a67c | django/publicmapping/redistricting/config.py | python | SpatialUtils.configure_geoserver | (self) | return True | Configure all the components in Geoserver. This method configures the
geoserver workspace, datastore, feature types, and styles. All
configuration steps get processed through the REST config.
@returns: A flag indicating if geoserver was configured correctly. | Configure all the components in Geoserver. This method configures the
geoserver workspace, datastore, feature types, and styles. All
configuration steps get processed through the REST config. | [
"Configure",
"all",
"the",
"components",
"in",
"Geoserver",
".",
"This",
"method",
"configures",
"the",
"geoserver",
"workspace",
"datastore",
"feature",
"types",
"and",
"styles",
".",
"All",
"configuration",
"steps",
"get",
"processed",
"through",
"the",
"REST",
"config",
"."
] | def configure_geoserver(self):
"""
Configure all the components in Geoserver. This method configures the
geoserver workspace, datastore, feature types, and styles. All
configuration steps get processed through the REST config.
@returns: A flag indicating if geoserver was configured correctly.
"""
# Set the Geoserver proxy base url
# This is necessary for geoserver to know where to look for its internal
# resources like its copy of openlayers and other things
settings = requests.get(
'%s/rest/settings.json' % self.origin,
headers=self.headers['default']).json()
settings['global']['proxyBaseUrl'] = self.origin
resp = requests.put(
'%s/rest/settings' % self.origin,
json=settings,
headers=self.headers['default'])
resp.raise_for_status()
# Create our namespace
namespace_url = '%s/rest/namespaces' % self.origin
namespace_obj = {'namespace': {'prefix': self.ns, 'uri': self.nshref}}
if self._check_spatial_resource(namespace_url, self.ns, namespace_obj):
logger.debug('Created namespace "%s"' % self.ns)
else:
logger.warn('Could not create Namespace')
return False
# Create our DataStore
if self.store is None:
logger.warning(
'Geoserver cannot be fully configured without a stored config.'
)
return False
data_store_url = '%s/rest/workspaces/%s/datastores' % (self.origin,
self.ns)
data_store_name = 'PostGIS'
data_store_obj = {
'dataStore': {
'name': data_store_name,
'workspace': {
'name': self.ns,
'link': self.nshref
},
'connectionParameters': {
'host': os.getenv('DATABASE_HOST', self.host),
'port': os.getenv('DATABASE_PORT'),
'database': os.getenv('DATABASE_DATABASE'),
'user': os.getenv('DATABASE_USER'),
'passwd': os.getenv('DATABASE_PASSWORD'),
'dbtype': 'postgis',
'schema': 'public'
}
}
}
if self._check_spatial_resource(data_store_url, data_store_name,
data_store_obj):
logger.debug('Created datastore "%s"' % data_store_name)
else:
logger.warn('Could not create Datastore')
return False
# Create the feature types and their styles
subject_attrs = [
{'name': 'name', 'binding': 'java.lang.String'},
{'name': 'geom', 'binding': 'com.vividsolutions.jts.geom.MultiPolygon'},
{'name': 'geolevel_id', 'binding': 'java.lang.Integer'},
{'name': 'number', 'binding': 'java.lang.Double'},
{'name': 'percentage', 'binding': 'java.lang.Double'},
]
if self.create_featuretype(
'identify_geounit',
attributes=[
{'name': 'id', 'binding': 'java.lang.Integer'},
{'name': 'name', 'binding': 'java.lang.String'},
{'name': 'geolevel_id', 'binding': 'java.lang.Integer'},
{'name': 'geom', 'binding': 'com.vividsolutions.jts.geom.MultiPolygon'},
{'name': 'number', 'binding': 'java.lang.Double'},
{'name': 'percentage', 'binding': 'java.lang.Double'},
{'name': 'subject_id', 'binding': 'java.lang.Integer'}
]
):
logger.debug('Created feature type "identify_geounit"')
else:
logger.warn('Could not create "identify_geounit" feature type')
for geolevel in Geolevel.objects.all():
if geolevel.legislativelevel_set.all().count() == 0:
# Skip 'abstract' geolevels if regions are configured
continue
if self.create_featuretype(
'simple_%s' % geolevel.name,
attributes=[
{'name': 'name', 'binding': 'java.lang.String'},
{'name': 'geolevel_id', 'binding': 'java.lang.Integer'},
{'name': 'geom', 'binding': 'com.vividsolutions.jts.geom.MultiPolygon'}
]
):
logger.debug(
'Created "simple_%s" feature type' % geolevel.name)
else:
logger.warn('Could not create "simple_%s" simple feature type'
% geolevel.name)
simple_district_attrs = [
{'name': 'district_id', 'binding': 'java.lang.Integer'},
{'name': 'plan_id', 'binding': 'java.lang.Integer'},
{'name': 'legislative_body_id', 'binding': 'java.lang.Integer'},
{'name': 'geom', 'binding': 'com.vividsolutions.jts.geom.MultiPolygon'}
]
if self.create_featuretype('simple_district_%s' % geolevel.name,
attributes=simple_district_attrs):
logger.debug('Created "simple_district_%s" feature type' %
geolevel.name)
else:
logger.warn(
'Could not create "simple_district_%s" simple district feature type'
% geolevel.name)
all_subjects = Subject.objects.all().order_by('sort_key')
if all_subjects.count() > 0:
subject = all_subjects[0]
# Create NONE demographic layer, based on first subject
featuretype_name = get_featuretype_name(geolevel.name)
if self.create_featuretype(
featuretype_name,
alias=get_featuretype_name(geolevel.name,
subject.name),
attributes=subject_attrs):
logger.debug(
'Created "%s" feature type' % featuretype_name)
else:
logger.warn('Could not create "%s" feature type' %
featuretype_name)
if self.create_style(featuretype_name):
logger.debug('Created "%s" style' % featuretype_name)
else:
logger.warn(
'Could not create style for "%s"' % featuretype_name)
try:
sld_content = SpatialUtils.generate_style(
geolevel,
geolevel.geounit_set.all(),
1,
layername='none')
self.write_style(geolevel.name + '_none', sld_content)
except Exception:
logger.error(traceback.format_exc())
# Have to return here, since there's no guarantee sld_content is defined
return False
if self.set_style(featuretype_name, sld_content):
logger.debug('Set "%s" style' % featuretype_name)
else:
logger.warn('Could not set "%s" style' % featuretype_name)
if self.assign_style(featuretype_name, featuretype_name):
logger.debug('Assigned style for "%s"' % featuretype_name)
else:
logger.warn(
'Could not assign style for "%s"' % featuretype_name)
# Create boundary layer, based on geographic boundaries
featuretype_name = '%s_boundaries' % geolevel.name
if self.create_featuretype(
featuretype_name,
alias=get_featuretype_name(geolevel.name,
subject.name),
attributes=subject_attrs):
logger.debug(
'Created "%s" feature type' % featuretype_name)
else:
logger.warn('Could not create "%s" feature type' %
featuretype_name)
if self.create_style(featuretype_name):
logger.debug('Created "%s" style' % featuretype_name)
else:
logger.warn(
'Could not create "%s" style' % featuretype_name)
try:
sld_content = SpatialUtils.generate_style(
geolevel,
geolevel.geounit_set.all(),
1,
layername='boundary')
self.write_style(geolevel.name + '_boundaries',
sld_content)
except Exception:
logger.error(traceback.format_exc())
if self.set_style(featuretype_name, sld_content):
logger.debug('Set "%s" style' % featuretype_name)
else:
logger.warn('Could not set "%s" style' % featuretype_name)
if self.assign_style(featuretype_name, featuretype_name):
logger.debug('Assigned style for "%s"' % featuretype_name)
else:
logger.warn(
'Could not assign style for "%s"' % featuretype_name)
for subject in all_subjects:
featuretype_name = get_featuretype_name(
geolevel.name, subject.name)
if self.create_featuretype(
featuretype_name, attributes=subject_attrs):
logger.debug(
'Created "%s" feature type' % featuretype_name)
else:
logger.warn('Could not create "%s" subject feature type' %
featuretype_name)
if self.create_style(featuretype_name):
logger.debug('Created "%s" style' % featuretype_name)
else:
logger.warn(
'Could not create "%s" style' % featuretype_name)
try:
sld_content = SpatialUtils.generate_style(
geolevel,
geolevel.geounit_set.all(),
5,
subject=subject)
self.write_style(geolevel.name + '_' + subject.name,
sld_content)
except Exception:
logger.error(traceback.format_exc())
if self.set_style(featuretype_name, sld_content):
logger.debug('Set "%s" style' % featuretype_name)
else:
logger.warn('Could not set "%s" style' % featuretype_name)
if self.assign_style(featuretype_name, featuretype_name):
logger.debug('Assigned "%s" style' % featuretype_name)
else:
logger.warn(
'Could not assign "%s" style' % featuretype_name)
# map all the legislative body / geolevels combos
ngeolevels_map = []
for lbody in LegislativeBody.objects.all():
geolevels = lbody.get_geolevels()
# list by # of geolevels, and the first geolevel
ngeolevels_map.append((
len(geolevels),
lbody,
geolevels[0],
))
# sort descending by the # of geolevels
ngeolevels_map.sort(key=lambda x: -x[0])
# get the first geolevel from the legislative body with the most geolevels
geolevel = ngeolevels_map[0][2]
# create simple_district as an alias to the largest geolevel (e.g. counties)
if self.create_featuretype(
'simple_district',
alias='simple_district_%s' % geolevel.name,
attributes=simple_district_attrs):
logger.debug('Created "simple_district" feature type')
else:
logger.warn('Could not create "simple_district" feature type')
if self.assign_style('simple_district', 'polygon'):
logger.debug('Assigned style "polygon" to feature type')
else:
logger.warn('Could not assign "polygon" style to simple_district')
try:
# add the district intervals
intervals = self.store.filter_nodes(
'//ScoreFunction[@calculator="redistricting.calculators.Interval"]'
)
for interval in intervals:
subject_name = interval.xpath('SubjectArgument')[0].get('ref')
lbody_name = interval.xpath('LegislativeBody')[0].get('ref')
interval_avg = float(
interval.xpath('Argument[@name="target"]')[0].get('value'))
interval_bnd1 = float(
interval.xpath('Argument[@name="bound1"]')[0].get('value'))
interval_bnd2 = float(
interval.xpath('Argument[@name="bound2"]')[0].get('value'))
intervals = [(interval_avg + interval_avg * interval_bnd2,
None, _('Far Over Target'), {
'fill': '#ebb95e',
'fill-opacity': '0.3'
}), (interval_avg + interval_avg * interval_bnd1,
interval_avg + interval_avg * interval_bnd2,
_('Over Target'), {
'fill': '#ead3a7',
'fill-opacity': '0.3'
}),
(interval_avg - interval_avg * interval_bnd1,
interval_avg + interval_avg * interval_bnd1,
_('Meets Target'), {
'fill': '#eeeeee',
'fill-opacity': '0.1'
}), (interval_avg - interval_avg * interval_bnd2,
interval_avg - interval_avg * interval_bnd1,
_('Under Target'), {
'fill': '#a2d5d0',
'fill-opacity': '0.3'
}),
(None,
interval_avg - interval_avg * interval_bnd2,
_('Far Under Target'), {
'fill': '#0aac98',
'fill-opacity': '0.3'
})]
doc = sld.StyledLayerDescriptor()
fts = doc.create_namedlayer(
subject_name).create_userstyle().create_featuretypestyle()
for interval in intervals:
imin, imax, ititle, ifill = interval
rule = fts.create_rule(ititle, sld.PolygonSymbolizer)
if imin is None:
rule.create_filter('number', '<', str(
int(round(imax))))
elif imax is None:
rule.create_filter('number', '>=', str(
int(round(imin))))
else:
f1 = sld.Filter(rule)
f1.PropertyIsGreaterThanOrEqualTo = sld.PropertyCriterion(
f1, 'PropertyIsGreaterThanOrEqualTo')
f1.PropertyIsGreaterThanOrEqualTo.PropertyName = 'number'
f1.PropertyIsGreaterThanOrEqualTo.Literal = str(
int(round(imin)))
f2 = sld.Filter(rule)
f2.PropertyIsLessThan = sld.PropertyCriterion(
f2, 'PropertyIsLessThan')
f2.PropertyIsLessThan.PropertyName = 'number'
f2.PropertyIsLessThan.Literal = str(int(round(imax)))
rule.Filter = f1 + f2
ps = rule.PolygonSymbolizer
ps.Fill.CssParameters[0].Value = ifill['fill']
ps.Fill.create_cssparameter('fill-opacity',
ifill['fill-opacity'])
ps.Stroke.CssParameters[0].Value = '#fdb913'
ps.Stroke.CssParameters[1].Value = '2'
ps.Stroke.create_cssparameter('stroke-opacity', '1')
self.write_style(
lbody_name + '_' + subject_name,
doc.as_sld(pretty_print=True))
except Exception:
logger.warn(traceback.format_exc())
logger.warn('LegislativeBody intervals are not configured.')
logger.info("Geoserver configuration complete.")
# finished configure_geoserver
return True | [
"def",
"configure_geoserver",
"(",
"self",
")",
":",
"# Set the Geoserver proxy base url",
"# This is necessary for geoserver to know where to look for its internal",
"# resources like its copy of openlayers and other things",
"settings",
"=",
"requests",
".",
"get",
"(",
"'%s/rest/settings.json'",
"%",
"self",
".",
"origin",
",",
"headers",
"=",
"self",
".",
"headers",
"[",
"'default'",
"]",
")",
".",
"json",
"(",
")",
"settings",
"[",
"'global'",
"]",
"[",
"'proxyBaseUrl'",
"]",
"=",
"self",
".",
"origin",
"resp",
"=",
"requests",
".",
"put",
"(",
"'%s/rest/settings'",
"%",
"self",
".",
"origin",
",",
"json",
"=",
"settings",
",",
"headers",
"=",
"self",
".",
"headers",
"[",
"'default'",
"]",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"# Create our namespace",
"namespace_url",
"=",
"'%s/rest/namespaces'",
"%",
"self",
".",
"origin",
"namespace_obj",
"=",
"{",
"'namespace'",
":",
"{",
"'prefix'",
":",
"self",
".",
"ns",
",",
"'uri'",
":",
"self",
".",
"nshref",
"}",
"}",
"if",
"self",
".",
"_check_spatial_resource",
"(",
"namespace_url",
",",
"self",
".",
"ns",
",",
"namespace_obj",
")",
":",
"logger",
".",
"debug",
"(",
"'Created namespace \"%s\"'",
"%",
"self",
".",
"ns",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create Namespace'",
")",
"return",
"False",
"# Create our DataStore",
"if",
"self",
".",
"store",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"'Geoserver cannot be fully configured without a stored config.'",
")",
"return",
"False",
"data_store_url",
"=",
"'%s/rest/workspaces/%s/datastores'",
"%",
"(",
"self",
".",
"origin",
",",
"self",
".",
"ns",
")",
"data_store_name",
"=",
"'PostGIS'",
"data_store_obj",
"=",
"{",
"'dataStore'",
":",
"{",
"'name'",
":",
"data_store_name",
",",
"'workspace'",
":",
"{",
"'name'",
":",
"self",
".",
"ns",
",",
"'link'",
":",
"self",
".",
"nshref",
"}",
",",
"'connectionParameters'",
":",
"{",
"'host'",
":",
"os",
".",
"getenv",
"(",
"'DATABASE_HOST'",
",",
"self",
".",
"host",
")",
",",
"'port'",
":",
"os",
".",
"getenv",
"(",
"'DATABASE_PORT'",
")",
",",
"'database'",
":",
"os",
".",
"getenv",
"(",
"'DATABASE_DATABASE'",
")",
",",
"'user'",
":",
"os",
".",
"getenv",
"(",
"'DATABASE_USER'",
")",
",",
"'passwd'",
":",
"os",
".",
"getenv",
"(",
"'DATABASE_PASSWORD'",
")",
",",
"'dbtype'",
":",
"'postgis'",
",",
"'schema'",
":",
"'public'",
"}",
"}",
"}",
"if",
"self",
".",
"_check_spatial_resource",
"(",
"data_store_url",
",",
"data_store_name",
",",
"data_store_obj",
")",
":",
"logger",
".",
"debug",
"(",
"'Created datastore \"%s\"'",
"%",
"data_store_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create Datastore'",
")",
"return",
"False",
"# Create the feature types and their styles",
"subject_attrs",
"=",
"[",
"{",
"'name'",
":",
"'name'",
",",
"'binding'",
":",
"'java.lang.String'",
"}",
",",
"{",
"'name'",
":",
"'geom'",
",",
"'binding'",
":",
"'com.vividsolutions.jts.geom.MultiPolygon'",
"}",
",",
"{",
"'name'",
":",
"'geolevel_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'number'",
",",
"'binding'",
":",
"'java.lang.Double'",
"}",
",",
"{",
"'name'",
":",
"'percentage'",
",",
"'binding'",
":",
"'java.lang.Double'",
"}",
",",
"]",
"if",
"self",
".",
"create_featuretype",
"(",
"'identify_geounit'",
",",
"attributes",
"=",
"[",
"{",
"'name'",
":",
"'id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'name'",
",",
"'binding'",
":",
"'java.lang.String'",
"}",
",",
"{",
"'name'",
":",
"'geolevel_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'geom'",
",",
"'binding'",
":",
"'com.vividsolutions.jts.geom.MultiPolygon'",
"}",
",",
"{",
"'name'",
":",
"'number'",
",",
"'binding'",
":",
"'java.lang.Double'",
"}",
",",
"{",
"'name'",
":",
"'percentage'",
",",
"'binding'",
":",
"'java.lang.Double'",
"}",
",",
"{",
"'name'",
":",
"'subject_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"'Created feature type \"identify_geounit\"'",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"identify_geounit\" feature type'",
")",
"for",
"geolevel",
"in",
"Geolevel",
".",
"objects",
".",
"all",
"(",
")",
":",
"if",
"geolevel",
".",
"legislativelevel_set",
".",
"all",
"(",
")",
".",
"count",
"(",
")",
"==",
"0",
":",
"# Skip 'abstract' geolevels if regions are configured",
"continue",
"if",
"self",
".",
"create_featuretype",
"(",
"'simple_%s'",
"%",
"geolevel",
".",
"name",
",",
"attributes",
"=",
"[",
"{",
"'name'",
":",
"'name'",
",",
"'binding'",
":",
"'java.lang.String'",
"}",
",",
"{",
"'name'",
":",
"'geolevel_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'geom'",
",",
"'binding'",
":",
"'com.vividsolutions.jts.geom.MultiPolygon'",
"}",
"]",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"simple_%s\" feature type'",
"%",
"geolevel",
".",
"name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"simple_%s\" simple feature type'",
"%",
"geolevel",
".",
"name",
")",
"simple_district_attrs",
"=",
"[",
"{",
"'name'",
":",
"'district_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'plan_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'legislative_body_id'",
",",
"'binding'",
":",
"'java.lang.Integer'",
"}",
",",
"{",
"'name'",
":",
"'geom'",
",",
"'binding'",
":",
"'com.vividsolutions.jts.geom.MultiPolygon'",
"}",
"]",
"if",
"self",
".",
"create_featuretype",
"(",
"'simple_district_%s'",
"%",
"geolevel",
".",
"name",
",",
"attributes",
"=",
"simple_district_attrs",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"simple_district_%s\" feature type'",
"%",
"geolevel",
".",
"name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"simple_district_%s\" simple district feature type'",
"%",
"geolevel",
".",
"name",
")",
"all_subjects",
"=",
"Subject",
".",
"objects",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"'sort_key'",
")",
"if",
"all_subjects",
".",
"count",
"(",
")",
">",
"0",
":",
"subject",
"=",
"all_subjects",
"[",
"0",
"]",
"# Create NONE demographic layer, based on first subject",
"featuretype_name",
"=",
"get_featuretype_name",
"(",
"geolevel",
".",
"name",
")",
"if",
"self",
".",
"create_featuretype",
"(",
"featuretype_name",
",",
"alias",
"=",
"get_featuretype_name",
"(",
"geolevel",
".",
"name",
",",
"subject",
".",
"name",
")",
",",
"attributes",
"=",
"subject_attrs",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" feature type'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"%s\" feature type'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"create_style",
"(",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create style for \"%s\"'",
"%",
"featuretype_name",
")",
"try",
":",
"sld_content",
"=",
"SpatialUtils",
".",
"generate_style",
"(",
"geolevel",
",",
"geolevel",
".",
"geounit_set",
".",
"all",
"(",
")",
",",
"1",
",",
"layername",
"=",
"'none'",
")",
"self",
".",
"write_style",
"(",
"geolevel",
".",
"name",
"+",
"'_none'",
",",
"sld_content",
")",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"# Have to return here, since there's no guarantee sld_content is defined",
"return",
"False",
"if",
"self",
".",
"set_style",
"(",
"featuretype_name",
",",
"sld_content",
")",
":",
"logger",
".",
"debug",
"(",
"'Set \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not set \"%s\" style'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"assign_style",
"(",
"featuretype_name",
",",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Assigned style for \"%s\"'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not assign style for \"%s\"'",
"%",
"featuretype_name",
")",
"# Create boundary layer, based on geographic boundaries",
"featuretype_name",
"=",
"'%s_boundaries'",
"%",
"geolevel",
".",
"name",
"if",
"self",
".",
"create_featuretype",
"(",
"featuretype_name",
",",
"alias",
"=",
"get_featuretype_name",
"(",
"geolevel",
".",
"name",
",",
"subject",
".",
"name",
")",
",",
"attributes",
"=",
"subject_attrs",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" feature type'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"%s\" feature type'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"create_style",
"(",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"%s\" style'",
"%",
"featuretype_name",
")",
"try",
":",
"sld_content",
"=",
"SpatialUtils",
".",
"generate_style",
"(",
"geolevel",
",",
"geolevel",
".",
"geounit_set",
".",
"all",
"(",
")",
",",
"1",
",",
"layername",
"=",
"'boundary'",
")",
"self",
".",
"write_style",
"(",
"geolevel",
".",
"name",
"+",
"'_boundaries'",
",",
"sld_content",
")",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"if",
"self",
".",
"set_style",
"(",
"featuretype_name",
",",
"sld_content",
")",
":",
"logger",
".",
"debug",
"(",
"'Set \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not set \"%s\" style'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"assign_style",
"(",
"featuretype_name",
",",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Assigned style for \"%s\"'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not assign style for \"%s\"'",
"%",
"featuretype_name",
")",
"for",
"subject",
"in",
"all_subjects",
":",
"featuretype_name",
"=",
"get_featuretype_name",
"(",
"geolevel",
".",
"name",
",",
"subject",
".",
"name",
")",
"if",
"self",
".",
"create_featuretype",
"(",
"featuretype_name",
",",
"attributes",
"=",
"subject_attrs",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" feature type'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"%s\" subject feature type'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"create_style",
"(",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"%s\" style'",
"%",
"featuretype_name",
")",
"try",
":",
"sld_content",
"=",
"SpatialUtils",
".",
"generate_style",
"(",
"geolevel",
",",
"geolevel",
".",
"geounit_set",
".",
"all",
"(",
")",
",",
"5",
",",
"subject",
"=",
"subject",
")",
"self",
".",
"write_style",
"(",
"geolevel",
".",
"name",
"+",
"'_'",
"+",
"subject",
".",
"name",
",",
"sld_content",
")",
"except",
"Exception",
":",
"logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"if",
"self",
".",
"set_style",
"(",
"featuretype_name",
",",
"sld_content",
")",
":",
"logger",
".",
"debug",
"(",
"'Set \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not set \"%s\" style'",
"%",
"featuretype_name",
")",
"if",
"self",
".",
"assign_style",
"(",
"featuretype_name",
",",
"featuretype_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Assigned \"%s\" style'",
"%",
"featuretype_name",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not assign \"%s\" style'",
"%",
"featuretype_name",
")",
"# map all the legislative body / geolevels combos",
"ngeolevels_map",
"=",
"[",
"]",
"for",
"lbody",
"in",
"LegislativeBody",
".",
"objects",
".",
"all",
"(",
")",
":",
"geolevels",
"=",
"lbody",
".",
"get_geolevels",
"(",
")",
"# list by # of geolevels, and the first geolevel",
"ngeolevels_map",
".",
"append",
"(",
"(",
"len",
"(",
"geolevels",
")",
",",
"lbody",
",",
"geolevels",
"[",
"0",
"]",
",",
")",
")",
"# sort descending by the # of geolevels",
"ngeolevels_map",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"-",
"x",
"[",
"0",
"]",
")",
"# get the first geolevel from the legislative body with the most geolevels",
"geolevel",
"=",
"ngeolevels_map",
"[",
"0",
"]",
"[",
"2",
"]",
"# create simple_district as an alias to the largest geolevel (e.g. counties)",
"if",
"self",
".",
"create_featuretype",
"(",
"'simple_district'",
",",
"alias",
"=",
"'simple_district_%s'",
"%",
"geolevel",
".",
"name",
",",
"attributes",
"=",
"simple_district_attrs",
")",
":",
"logger",
".",
"debug",
"(",
"'Created \"simple_district\" feature type'",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not create \"simple_district\" feature type'",
")",
"if",
"self",
".",
"assign_style",
"(",
"'simple_district'",
",",
"'polygon'",
")",
":",
"logger",
".",
"debug",
"(",
"'Assigned style \"polygon\" to feature type'",
")",
"else",
":",
"logger",
".",
"warn",
"(",
"'Could not assign \"polygon\" style to simple_district'",
")",
"try",
":",
"# add the district intervals",
"intervals",
"=",
"self",
".",
"store",
".",
"filter_nodes",
"(",
"'//ScoreFunction[@calculator=\"redistricting.calculators.Interval\"]'",
")",
"for",
"interval",
"in",
"intervals",
":",
"subject_name",
"=",
"interval",
".",
"xpath",
"(",
"'SubjectArgument'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'ref'",
")",
"lbody_name",
"=",
"interval",
".",
"xpath",
"(",
"'LegislativeBody'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'ref'",
")",
"interval_avg",
"=",
"float",
"(",
"interval",
".",
"xpath",
"(",
"'Argument[@name=\"target\"]'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'value'",
")",
")",
"interval_bnd1",
"=",
"float",
"(",
"interval",
".",
"xpath",
"(",
"'Argument[@name=\"bound1\"]'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'value'",
")",
")",
"interval_bnd2",
"=",
"float",
"(",
"interval",
".",
"xpath",
"(",
"'Argument[@name=\"bound2\"]'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'value'",
")",
")",
"intervals",
"=",
"[",
"(",
"interval_avg",
"+",
"interval_avg",
"*",
"interval_bnd2",
",",
"None",
",",
"_",
"(",
"'Far Over Target'",
")",
",",
"{",
"'fill'",
":",
"'#ebb95e'",
",",
"'fill-opacity'",
":",
"'0.3'",
"}",
")",
",",
"(",
"interval_avg",
"+",
"interval_avg",
"*",
"interval_bnd1",
",",
"interval_avg",
"+",
"interval_avg",
"*",
"interval_bnd2",
",",
"_",
"(",
"'Over Target'",
")",
",",
"{",
"'fill'",
":",
"'#ead3a7'",
",",
"'fill-opacity'",
":",
"'0.3'",
"}",
")",
",",
"(",
"interval_avg",
"-",
"interval_avg",
"*",
"interval_bnd1",
",",
"interval_avg",
"+",
"interval_avg",
"*",
"interval_bnd1",
",",
"_",
"(",
"'Meets Target'",
")",
",",
"{",
"'fill'",
":",
"'#eeeeee'",
",",
"'fill-opacity'",
":",
"'0.1'",
"}",
")",
",",
"(",
"interval_avg",
"-",
"interval_avg",
"*",
"interval_bnd2",
",",
"interval_avg",
"-",
"interval_avg",
"*",
"interval_bnd1",
",",
"_",
"(",
"'Under Target'",
")",
",",
"{",
"'fill'",
":",
"'#a2d5d0'",
",",
"'fill-opacity'",
":",
"'0.3'",
"}",
")",
",",
"(",
"None",
",",
"interval_avg",
"-",
"interval_avg",
"*",
"interval_bnd2",
",",
"_",
"(",
"'Far Under Target'",
")",
",",
"{",
"'fill'",
":",
"'#0aac98'",
",",
"'fill-opacity'",
":",
"'0.3'",
"}",
")",
"]",
"doc",
"=",
"sld",
".",
"StyledLayerDescriptor",
"(",
")",
"fts",
"=",
"doc",
".",
"create_namedlayer",
"(",
"subject_name",
")",
".",
"create_userstyle",
"(",
")",
".",
"create_featuretypestyle",
"(",
")",
"for",
"interval",
"in",
"intervals",
":",
"imin",
",",
"imax",
",",
"ititle",
",",
"ifill",
"=",
"interval",
"rule",
"=",
"fts",
".",
"create_rule",
"(",
"ititle",
",",
"sld",
".",
"PolygonSymbolizer",
")",
"if",
"imin",
"is",
"None",
":",
"rule",
".",
"create_filter",
"(",
"'number'",
",",
"'<'",
",",
"str",
"(",
"int",
"(",
"round",
"(",
"imax",
")",
")",
")",
")",
"elif",
"imax",
"is",
"None",
":",
"rule",
".",
"create_filter",
"(",
"'number'",
",",
"'>='",
",",
"str",
"(",
"int",
"(",
"round",
"(",
"imin",
")",
")",
")",
")",
"else",
":",
"f1",
"=",
"sld",
".",
"Filter",
"(",
"rule",
")",
"f1",
".",
"PropertyIsGreaterThanOrEqualTo",
"=",
"sld",
".",
"PropertyCriterion",
"(",
"f1",
",",
"'PropertyIsGreaterThanOrEqualTo'",
")",
"f1",
".",
"PropertyIsGreaterThanOrEqualTo",
".",
"PropertyName",
"=",
"'number'",
"f1",
".",
"PropertyIsGreaterThanOrEqualTo",
".",
"Literal",
"=",
"str",
"(",
"int",
"(",
"round",
"(",
"imin",
")",
")",
")",
"f2",
"=",
"sld",
".",
"Filter",
"(",
"rule",
")",
"f2",
".",
"PropertyIsLessThan",
"=",
"sld",
".",
"PropertyCriterion",
"(",
"f2",
",",
"'PropertyIsLessThan'",
")",
"f2",
".",
"PropertyIsLessThan",
".",
"PropertyName",
"=",
"'number'",
"f2",
".",
"PropertyIsLessThan",
".",
"Literal",
"=",
"str",
"(",
"int",
"(",
"round",
"(",
"imax",
")",
")",
")",
"rule",
".",
"Filter",
"=",
"f1",
"+",
"f2",
"ps",
"=",
"rule",
".",
"PolygonSymbolizer",
"ps",
".",
"Fill",
".",
"CssParameters",
"[",
"0",
"]",
".",
"Value",
"=",
"ifill",
"[",
"'fill'",
"]",
"ps",
".",
"Fill",
".",
"create_cssparameter",
"(",
"'fill-opacity'",
",",
"ifill",
"[",
"'fill-opacity'",
"]",
")",
"ps",
".",
"Stroke",
".",
"CssParameters",
"[",
"0",
"]",
".",
"Value",
"=",
"'#fdb913'",
"ps",
".",
"Stroke",
".",
"CssParameters",
"[",
"1",
"]",
".",
"Value",
"=",
"'2'",
"ps",
".",
"Stroke",
".",
"create_cssparameter",
"(",
"'stroke-opacity'",
",",
"'1'",
")",
"self",
".",
"write_style",
"(",
"lbody_name",
"+",
"'_'",
"+",
"subject_name",
",",
"doc",
".",
"as_sld",
"(",
"pretty_print",
"=",
"True",
")",
")",
"except",
"Exception",
":",
"logger",
".",
"warn",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"logger",
".",
"warn",
"(",
"'LegislativeBody intervals are not configured.'",
")",
"logger",
".",
"info",
"(",
"\"Geoserver configuration complete.\"",
")",
"# finished configure_geoserver",
"return",
"True"
] | https://github.com/PublicMapping/districtbuilder-classic/blob/6e4b9d644043082eb0499f5aa77e777fff73a67c/django/publicmapping/redistricting/config.py#L1132-L1511 |
|
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.GypPathToUniqueOutput | (self, path, qualified=True) | return os.path.normpath(os.path.join(obj, self.base_dir, path_dir,
path_basename)) | Translate a gyp path to a ninja path for writing output.
If qualified is True, qualify the resulting filename with the name
of the target. This is necessary when e.g. compiling the same
path twice for two separate output targets.
See the above discourse on path conversions. | Translate a gyp path to a ninja path for writing output. | [
"Translate",
"a",
"gyp",
"path",
"to",
"a",
"ninja",
"path",
"for",
"writing",
"output",
"."
] | def GypPathToUniqueOutput(self, path, qualified=True):
"""Translate a gyp path to a ninja path for writing output.
If qualified is True, qualify the resulting filename with the name
of the target. This is necessary when e.g. compiling the same
path twice for two separate output targets.
See the above discourse on path conversions."""
path = self.ExpandSpecial(path)
assert not path.startswith('$'), path
# Translate the path following this scheme:
# Input: foo/bar.gyp, target targ, references baz/out.o
# Output: obj/foo/baz/targ.out.o (if qualified)
# obj/foo/baz/out.o (otherwise)
# (and obj.host instead of obj for cross-compiles)
#
# Why this scheme and not some other one?
# 1) for a given input, you can compute all derived outputs by matching
# its path, even if the input is brought via a gyp file with '..'.
# 2) simple files like libraries and stamps have a simple filename.
obj = 'obj'
if self.toolset != 'target':
obj += '.' + self.toolset
path_dir, path_basename = os.path.split(path)
assert not os.path.isabs(path_dir), (
"'%s' can not be absolute path (see crbug.com/462153)." % path_dir)
if qualified:
path_basename = self.name + '.' + path_basename
return os.path.normpath(os.path.join(obj, self.base_dir, path_dir,
path_basename)) | [
"def",
"GypPathToUniqueOutput",
"(",
"self",
",",
"path",
",",
"qualified",
"=",
"True",
")",
":",
"path",
"=",
"self",
".",
"ExpandSpecial",
"(",
"path",
")",
"assert",
"not",
"path",
".",
"startswith",
"(",
"'$'",
")",
",",
"path",
"# Translate the path following this scheme:",
"# Input: foo/bar.gyp, target targ, references baz/out.o",
"# Output: obj/foo/baz/targ.out.o (if qualified)",
"# obj/foo/baz/out.o (otherwise)",
"# (and obj.host instead of obj for cross-compiles)",
"#",
"# Why this scheme and not some other one?",
"# 1) for a given input, you can compute all derived outputs by matching",
"# its path, even if the input is brought via a gyp file with '..'.",
"# 2) simple files like libraries and stamps have a simple filename.",
"obj",
"=",
"'obj'",
"if",
"self",
".",
"toolset",
"!=",
"'target'",
":",
"obj",
"+=",
"'.'",
"+",
"self",
".",
"toolset",
"path_dir",
",",
"path_basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"assert",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path_dir",
")",
",",
"(",
"\"'%s' can not be absolute path (see crbug.com/462153).\"",
"%",
"path_dir",
")",
"if",
"qualified",
":",
"path_basename",
"=",
"self",
".",
"name",
"+",
"'.'",
"+",
"path_basename",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"obj",
",",
"self",
".",
"base_dir",
",",
"path_dir",
",",
"path_basename",
")",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L308-L342 |
|
diracdeltas/sniffly | 5535a1191ecc1a879377263c70b92a6f41892f5f | util/scrape.py | python | display | (uri, response) | Prints the uri and HSTS header. | Prints the uri and HSTS header. | [
"Prints",
"the",
"uri",
"and",
"HSTS",
"header",
"."
] | def display(uri, response):
"""Prints the uri and HSTS header."""
print {uri: list(response.headers.getRawHeaders(
'Strict-Transport-Security', []))} | [
"def",
"display",
"(",
"uri",
",",
"response",
")",
":",
"print",
"{",
"uri",
":",
"list",
"(",
"response",
".",
"headers",
".",
"getRawHeaders",
"(",
"'Strict-Transport-Security'",
",",
"[",
"]",
")",
")",
"}"
] | https://github.com/diracdeltas/sniffly/blob/5535a1191ecc1a879377263c70b92a6f41892f5f/util/scrape.py#L67-L70 |
||
E2OpenPlugins/e2openplugin-OpenWebif | b238b3770b90f49ba076987f66a4f042eb4b318e | plugin/controllers/utilities.py | python | lenient_force_utf_8 | (value) | return lenient_decode(value).encode('utf_8') | Args:
value: input value
Returns:
(basestring) utf-8 encoded value
>>> isinstance(lenient_force_utf_8(''), basestring)
True
>>> lenient_force_utf_8(u"Hallo")
'Hallo'
>>> lenient_force_utf_8("HällöÜ")
'H\\xc3\\xa4ll\\xc3\\xb6\\xc3\\x9c' | [] | def lenient_force_utf_8(value):
"""
Args:
value: input value
Returns:
(basestring) utf-8 encoded value
>>> isinstance(lenient_force_utf_8(''), basestring)
True
>>> lenient_force_utf_8(u"Hallo")
'Hallo'
>>> lenient_force_utf_8("HällöÜ")
'H\\xc3\\xa4ll\\xc3\\xb6\\xc3\\x9c'
"""
if isinstance(value, six.text_type):
return value
return lenient_decode(value).encode('utf_8') | [
"def",
"lenient_force_utf_8",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
":",
"return",
"value",
"return",
"lenient_decode",
"(",
"value",
")",
".",
"encode",
"(",
"'utf_8'",
")"
] | https://github.com/E2OpenPlugins/e2openplugin-OpenWebif/blob/b238b3770b90f49ba076987f66a4f042eb4b318e/plugin/controllers/utilities.py#L99-L116 |
||
tum-pbs/PhiFlow | 31d9944f4f26e56358dd73fa797dde567b6334b0 | phi/math/backend/_backend.py | python | Backend.list_devices | (self, device_type: str or None = None) | Fetches information about all available compute devices this backend can use.
Implementations:
* NumPy: [`os.cpu_count`](https://docs.python.org/3/library/os.html#os.cpu_count)
* PyTorch: [`torch.cuda.get_device_properties`](https://pytorch.org/docs/stable/cuda.html#torch.cuda.get_device_properties)
* TensorFlow: `tensorflow.python.client.device_lib.list_local_devices`
* Jax: [`jax.devices`](https://jax.readthedocs.io/en/latest/jax.html#jax.devices)
Args:
device_type: (optional) Return only devices of this type, e.g. `'GPU'` or `'CPU'`. See `ComputeDevice.device_type`.
Returns:
`list` of all currently available devices. | Fetches information about all available compute devices this backend can use. | [
"Fetches",
"information",
"about",
"all",
"available",
"compute",
"devices",
"this",
"backend",
"can",
"use",
"."
] | def list_devices(self, device_type: str or None = None) -> List[ComputeDevice]:
"""
Fetches information about all available compute devices this backend can use.
Implementations:
* NumPy: [`os.cpu_count`](https://docs.python.org/3/library/os.html#os.cpu_count)
* PyTorch: [`torch.cuda.get_device_properties`](https://pytorch.org/docs/stable/cuda.html#torch.cuda.get_device_properties)
* TensorFlow: `tensorflow.python.client.device_lib.list_local_devices`
* Jax: [`jax.devices`](https://jax.readthedocs.io/en/latest/jax.html#jax.devices)
Args:
device_type: (optional) Return only devices of this type, e.g. `'GPU'` or `'CPU'`. See `ComputeDevice.device_type`.
Returns:
`list` of all currently available devices.
"""
raise NotImplementedError() | [
"def",
"list_devices",
"(",
"self",
",",
"device_type",
":",
"str",
"or",
"None",
"=",
"None",
")",
"->",
"List",
"[",
"ComputeDevice",
"]",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/tum-pbs/PhiFlow/blob/31d9944f4f26e56358dd73fa797dde567b6334b0/phi/math/backend/_backend.py#L149-L166 |
||
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | tools/gyp/pylib/gyp/win_tool.py | python | WinTool._UseSeparateMspdbsrv | (self, env, args) | Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one. | Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one. | [
"Allows",
"to",
"use",
"a",
"unique",
"instance",
"of",
"mspdbsrv",
".",
"exe",
"per",
"linker",
"instead",
"of",
"a",
"shared",
"one",
"."
] | def _UseSeparateMspdbsrv(self, env, args):
"""Allows to use a unique instance of mspdbsrv.exe per linker instead of a
shared one."""
if len(args) < 1:
raise Exception("Not enough arguments")
if args[0] != 'link.exe':
return
# Use the output filename passed to the linker to generate an endpoint name
# for mspdbsrv.exe.
endpoint_name = None
for arg in args:
m = _LINK_EXE_OUT_ARG.match(arg)
if m:
endpoint_name = re.sub(r'\W+', '',
'%s_%d' % (m.group('out'), os.getpid()))
break
if endpoint_name is None:
return
# Adds the appropriate environment variable. This will be read by link.exe
# to know which instance of mspdbsrv.exe it should connect to (if it's
# not set then the default endpoint is used).
env['_MSPDBSRV_ENDPOINT_'] = endpoint_name | [
"def",
"_UseSeparateMspdbsrv",
"(",
"self",
",",
"env",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"\"Not enough arguments\"",
")",
"if",
"args",
"[",
"0",
"]",
"!=",
"'link.exe'",
":",
"return",
"# Use the output filename passed to the linker to generate an endpoint name",
"# for mspdbsrv.exe.",
"endpoint_name",
"=",
"None",
"for",
"arg",
"in",
"args",
":",
"m",
"=",
"_LINK_EXE_OUT_ARG",
".",
"match",
"(",
"arg",
")",
"if",
"m",
":",
"endpoint_name",
"=",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"''",
",",
"'%s_%d'",
"%",
"(",
"m",
".",
"group",
"(",
"'out'",
")",
",",
"os",
".",
"getpid",
"(",
")",
")",
")",
"break",
"if",
"endpoint_name",
"is",
"None",
":",
"return",
"# Adds the appropriate environment variable. This will be read by link.exe",
"# to know which instance of mspdbsrv.exe it should connect to (if it's",
"# not set then the default endpoint is used).",
"env",
"[",
"'_MSPDBSRV_ENDPOINT_'",
"]",
"=",
"endpoint_name"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/win_tool.py#L37-L62 |
||
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/v8/gypfiles/landmine_utils.py | python | gyp_generator_flags | () | return dict(arg.split('=', 1)
for arg in shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', ''))) | Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary. | Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary. | [
"Parses",
"and",
"returns",
"GYP_GENERATOR_FLAGS",
"env",
"var",
"as",
"a",
"dictionary",
"."
] | def gyp_generator_flags():
"""Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary."""
return dict(arg.split('=', 1)
for arg in shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', ''))) | [
"def",
"gyp_generator_flags",
"(",
")",
":",
"return",
"dict",
"(",
"arg",
".",
"split",
"(",
"'='",
",",
"1",
")",
"for",
"arg",
"in",
"shlex",
".",
"split",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'GYP_GENERATOR_FLAGS'",
",",
"''",
")",
")",
")"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/v8/gypfiles/landmine_utils.py#L52-L55 |
|
jasonsanjose/brackets-sass | 88b351f2ebc3aaa514494eac368d197f63438caf | node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/buildbot/buildbot_run.py | python | CallSubProcess | (*args, **kwargs) | Wrapper around subprocess.call which treats errors as build exceptions. | Wrapper around subprocess.call which treats errors as build exceptions. | [
"Wrapper",
"around",
"subprocess",
".",
"call",
"which",
"treats",
"errors",
"as",
"build",
"exceptions",
"."
] | def CallSubProcess(*args, **kwargs):
"""Wrapper around subprocess.call which treats errors as build exceptions."""
retcode = subprocess.call(*args, **kwargs)
if retcode != 0:
print '@@@STEP_EXCEPTION@@@'
sys.exit(1) | [
"def",
"CallSubProcess",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retcode",
"=",
"subprocess",
".",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"retcode",
"!=",
"0",
":",
"print",
"'@@@STEP_EXCEPTION@@@'",
"sys",
".",
"exit",
"(",
"1",
")"
] | https://github.com/jasonsanjose/brackets-sass/blob/88b351f2ebc3aaa514494eac368d197f63438caf/node/2.0.3/node_modules/node-sass/node_modules/pangyp/gyp/buildbot/buildbot_run.py#L31-L36 |