nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
DasIch/brownie
8e29a9ceb50622e50b7209690d31203ad42ca164
brownie/terminal/__init__.py
python
TerminalWriter.options
(self, text_colour=None, background_colour=None, bold=None, faint=None, standout=None, underline=None, blink=None, indentation=False, escape=None)
A contextmanager which allows you to set certain options for the following writes. :param text_colour: The desired text colour. :param background_colour: The desired background colour. :param bold: If present the text is displayed bold. :param faint: If present the text is displayed faint. :param standout: If present the text stands out. :param underline: If present the text is underlined. :param blink: If present the text blinks. :param indentation: Adds a level of indentation if ``True``. :param escape: Overrides the escaping behaviour for this block. .. note:: The underlying terminal may support only certain options, especially the attributes (`bold`, `faint`, `standout` and `blink`) are not necessarily available. The following colours are available, the exact colour varies between terminals and their configuration. .. ansi-block:: :string_escape: Colors ====== \x1b[30mblack\x1b[0m \x1b[33myellow\x1b[0m \x1b[36mteal\x1b[0m \x1b[31mred\x1b[0m \x1b[34mblue\x1b[0m \x1b[37mwhite\x1b[0m \x1b[32mgreen\x1b[0m \x1b[35mpurple\x1b[0m
A contextmanager which allows you to set certain options for the following writes.
[ "A", "contextmanager", "which", "allows", "you", "to", "set", "certain", "options", "for", "the", "following", "writes", "." ]
def options(self, text_colour=None, background_colour=None, bold=None, faint=None, standout=None, underline=None, blink=None, indentation=False, escape=None): """ A contextmanager which allows you to set certain options for the following writes. :param text_colour: The desired text colour. :param background_colour: The desired background colour. :param bold: If present the text is displayed bold. :param faint: If present the text is displayed faint. :param standout: If present the text stands out. :param underline: If present the text is underlined. :param blink: If present the text blinks. :param indentation: Adds a level of indentation if ``True``. :param escape: Overrides the escaping behaviour for this block. .. note:: The underlying terminal may support only certain options, especially the attributes (`bold`, `faint`, `standout` and `blink`) are not necessarily available. The following colours are available, the exact colour varies between terminals and their configuration. .. ansi-block:: :string_escape: Colors ====== \x1b[30mblack\x1b[0m \x1b[33myellow\x1b[0m \x1b[36mteal\x1b[0m \x1b[31mred\x1b[0m \x1b[34mblue\x1b[0m \x1b[37mwhite\x1b[0m \x1b[32mgreen\x1b[0m \x1b[35mpurple\x1b[0m """ attributes = [ name for name, using in [ ('bold', bold), ('faint', faint), ('standout', standout), ('underline', underline), ('blink', blink) ] if using ] if not self.ignore_options: if text_colour: self.stream.write(TEXT_COLOURS[text_colour]) if background_colour: self.stream.write(BACKGROUND_COLOURS[background_colour]) for attribute in attributes: if attribute: self.stream.write(ATTRIBUTES[attribute]) if indentation: self.indent() if escape is not None: previous_setting = self.autoescape self.autoescape = escape try: yield self finally: if not self.ignore_options: if text_colour: self.stream.write(TEXT_COLOURS['reset']) if background_colour: self.stream.write(BACKGROUND_COLOURS['reset']) if any(attributes): self.stream.write(ATTRIBUTES['reset']) if indentation: self.dedent() if escape is not None: self.autoescape = previous_setting
[ "def", "options", "(", "self", ",", "text_colour", "=", "None", ",", "background_colour", "=", "None", ",", "bold", "=", "None", ",", "faint", "=", "None", ",", "standout", "=", "None", ",", "underline", "=", "None", ",", "blink", "=", "None", ",", "...
https://github.com/DasIch/brownie/blob/8e29a9ceb50622e50b7209690d31203ad42ca164/brownie/terminal/__init__.py#L236-L320
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/jinja2/filters.py
python
do_lower
(s)
return soft_unicode(s).lower()
Convert a value to lowercase.
Convert a value to lowercase.
[ "Convert", "a", "value", "to", "lowercase", "." ]
def do_lower(s): """Convert a value to lowercase.""" return soft_unicode(s).lower()
[ "def", "do_lower", "(", "s", ")", ":", "return", "soft_unicode", "(", "s", ")", ".", "lower", "(", ")" ]
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/jinja2/filters.py#L106-L108
pydata/xarray
9226c7ac87b3eb246f7a7e49f8f0f23d68951624
xarray/core/formatting.py
python
pretty_print
(x, numchars: int)
return s + " " * max(numchars - len(s), 0)
Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary
Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary
[ "Given", "an", "object", "x", "call", "str", "(", "x", ")", "and", "format", "the", "returned", "string", "so", "that", "it", "is", "numchars", "long", "padding", "with", "trailing", "spaces", "or", "truncating", "with", "ellipses", "as", "necessary" ]
def pretty_print(x, numchars: int): """Given an object `x`, call `str(x)` and format the returned string so that it is numchars long, padding with trailing spaces or truncating with ellipses as necessary """ s = maybe_truncate(x, numchars) return s + " " * max(numchars - len(s), 0)
[ "def", "pretty_print", "(", "x", ",", "numchars", ":", "int", ")", ":", "s", "=", "maybe_truncate", "(", "x", ",", "numchars", ")", "return", "s", "+", "\" \"", "*", "max", "(", "numchars", "-", "len", "(", "s", ")", ",", "0", ")" ]
https://github.com/pydata/xarray/blob/9226c7ac87b3eb246f7a7e49f8f0f23d68951624/xarray/core/formatting.py#L20-L26
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_internal/vcs/git.py
python
Git.is_commit_id_equal
(cls, dest: str, name: Optional[str])
return cls.get_revision(dest) == name
Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name.
Return whether the current commit hash equals the given name.
[ "Return", "whether", "the", "current", "commit", "hash", "equals", "the", "given", "name", "." ]
def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool: """ Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name. """ if not name: # Then avoid an unnecessary subprocess call. return False return cls.get_revision(dest) == name
[ "def", "is_commit_id_equal", "(", "cls", ",", "dest", ":", "str", ",", "name", ":", "Optional", "[", "str", "]", ")", "->", "bool", ":", "if", "not", "name", ":", "# Then avoid an unnecessary subprocess call.", "return", "False", "return", "cls", ".", "get_r...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_internal/vcs/git.py#L242-L254
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/owscatterplot.py
python
OWScatterPlot._add_controls
(self)
[]
def _add_controls(self): self._add_controls_axis() self._add_controls_sampling() super()._add_controls() self.gui.add_widget(self.gui.JitterNumericValues, self._effects_box) self.gui.add_widgets( [self.gui.ShowGridLines, self.gui.ToolTipShowsAll, self.gui.RegressionLine], self._plot_box) gui.checkBox( self._plot_box, self, value="graph.orthonormal_regression", label="Treat variables as independent", callback=self.graph.update_regression_line, tooltip= "If checked, fit line to group (minimize distance from points);\n" "otherwise fit y as a function of x (minimize vertical distances)", disabledBy=self.cb_reg_line)
[ "def", "_add_controls", "(", "self", ")", ":", "self", ".", "_add_controls_axis", "(", ")", "self", ".", "_add_controls_sampling", "(", ")", "super", "(", ")", ".", "_add_controls", "(", ")", "self", ".", "gui", ".", "add_widget", "(", "self", ".", "gui"...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owscatterplot.py#L373-L391
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/matrices/common.py
python
MatrixProperties.is_upper
(self)
return all(self[i, j].is_zero for i in range(1, self.rows) for j in range(min(i, self.cols)))
Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg
Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square.
[ "Check", "if", "matrix", "is", "an", "upper", "triangular", "matrix", ".", "True", "can", "be", "returned", "even", "if", "the", "matrix", "is", "not", "square", "." ]
def is_upper(self): """Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg """ return all(self[i, j].is_zero for i in range(1, self.rows) for j in range(min(i, self.cols)))
[ "def", "is_upper", "(", "self", ")", ":", "return", "all", "(", "self", "[", "i", ",", "j", "]", ".", "is_zero", "for", "i", "in", "range", "(", "1", ",", "self", ".", "rows", ")", "for", "j", "in", "range", "(", "min", "(", "i", ",", "self",...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/matrices/common.py#L1896-L1939
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/leo_babel/babel_lib.py
python
otpUnquote
(otp)
return otp
Remove all otp-quoting from a string @param otp: Otp-quoted outline path @param return: Unquoted outline path
Remove all otp-quoting from a string
[ "Remove", "all", "otp", "-", "quoting", "from", "a", "string" ]
def otpUnquote(otp): """ Remove all otp-quoting from a string @param otp: Otp-quoted outline path @param return: Unquoted outline path """ if otp: for un, qu in quoteList: otp = otp.replace(qu, un) return otp
[ "def", "otpUnquote", "(", "otp", ")", ":", "if", "otp", ":", "for", "un", ",", "qu", "in", "quoteList", ":", "otp", "=", "otp", ".", "replace", "(", "qu", ",", "un", ")", "return", "otp" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/leo_babel/babel_lib.py#L102-L114
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/linux/cffi/api.py
python
FFI.from_buffer
(self, python_buffer)
return self._backend.from_buffer(self.BCharA, python_buffer)
Return a <cdata 'char[]'> that points to the data of the given Python object, which must support the buffer interface. Note that this is not meant to be used on the built-in types str, unicode, or bytearray (you can build 'char[]' arrays explicitly) but only on objects containing large quantities of raw data in some other format, like 'array.array' or numpy arrays.
Return a <cdata 'char[]'> that points to the data of the given Python object, which must support the buffer interface. Note that this is not meant to be used on the built-in types str, unicode, or bytearray (you can build 'char[]' arrays explicitly) but only on objects containing large quantities of raw data in some other format, like 'array.array' or numpy arrays.
[ "Return", "a", "<cdata", "char", "[]", ">", "that", "points", "to", "the", "data", "of", "the", "given", "Python", "object", "which", "must", "support", "the", "buffer", "interface", ".", "Note", "that", "this", "is", "not", "meant", "to", "be", "used", ...
def from_buffer(self, python_buffer): """Return a <cdata 'char[]'> that points to the data of the given Python object, which must support the buffer interface. Note that this is not meant to be used on the built-in types str, unicode, or bytearray (you can build 'char[]' arrays explicitly) but only on objects containing large quantities of raw data in some other format, like 'array.array' or numpy arrays. """ return self._backend.from_buffer(self.BCharA, python_buffer)
[ "def", "from_buffer", "(", "self", ",", "python_buffer", ")", ":", "return", "self", ".", "_backend", ".", "from_buffer", "(", "self", ".", "BCharA", ",", "python_buffer", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/linux/cffi/api.py#L306-L314
opendevops-cn/codo-cmdb
334fba324512841d84535f31a094717eb5a40acf
libs/server/push_system_user.py
python
PushSystemUser.create_system_user
(self)
Ansible API创建系统用户 :return:
Ansible API创建系统用户 :return:
[ "Ansible", "API创建系统用户", ":", "return", ":" ]
def create_system_user(self): """ Ansible API创建系统用户 :return: """ system_user_list = self.get_system_user() connect_server_list = self.get_asset_info() # print(connect_server_list) # connect_server_list = [('172.16.0.93', 22, 'yanghongfei'), ('172.16.0.219', 22, 'root'), # ('2.2.2.2', 22, 'root')] for host in connect_server_list: ip = host[0] user = host[2] for data in system_user_list: system_user = data.get('system_user') if system_user in self.exc_list: self.msg = '{}内置用户不能创建,请跳过此类用户:{}'.format(system_user, self.exc_list) return self.msg bash_shell = data.get('bash_shell') module_args = '{sudo} grep -c {system_user} /etc/passwd >> /dev/null || {sudo} useradd {system_user} -s {bash_shell}; echo ok'.format( sudo=self.sudo, system_user=system_user, bash_shell=bash_shell ) result = self.run("shell", module_args, ip, user) print(result) if result['dark']: self.err_msg = {"status": False, "ip": ip, "msg": result['dark'][ip]['msg']} self.err_list.append(self.err_msg) if self.err_list: self.write_error_log()
[ "def", "create_system_user", "(", "self", ")", ":", "system_user_list", "=", "self", ".", "get_system_user", "(", ")", "connect_server_list", "=", "self", ".", "get_asset_info", "(", ")", "# print(connect_server_list)", "# connect_server_list = [('172.16.0.93', 22, 'yanghon...
https://github.com/opendevops-cn/codo-cmdb/blob/334fba324512841d84535f31a094717eb5a40acf/libs/server/push_system_user.py#L91-L124
luanfonceca/speakerfight
c9350d84664ac3bad83dd661a2c5d55d1b8cbf5b
deck/templatetags/deck_tags.py
python
is_user_in_jury
(event, user)
return event.jury.users.filter(pk=user.pk).exists()
[]
def is_user_in_jury(event, user): if isinstance(user, AnonymousUser): return False return event.jury.users.filter(pk=user.pk).exists()
[ "def", "is_user_in_jury", "(", "event", ",", "user", ")", ":", "if", "isinstance", "(", "user", ",", "AnonymousUser", ")", ":", "return", "False", "return", "event", ".", "jury", ".", "users", ".", "filter", "(", "pk", "=", "user", ".", "pk", ")", "....
https://github.com/luanfonceca/speakerfight/blob/c9350d84664ac3bad83dd661a2c5d55d1b8cbf5b/deck/templatetags/deck_tags.py#L49-L52
googledatalab/pydatalab
1c86e26a0d24e3bc8097895ddeab4d0607be4c40
datalab/storage/_item.py
python
Item.key
(self)
return self._key
Returns the key of the item.
Returns the key of the item.
[ "Returns", "the", "key", "of", "the", "item", "." ]
def key(self): """Returns the key of the item.""" return self._key
[ "def", "key", "(", "self", ")", ":", "return", "self", ".", "_key" ]
https://github.com/googledatalab/pydatalab/blob/1c86e26a0d24e3bc8097895ddeab4d0607be4c40/datalab/storage/_item.py#L96-L98
bwbaugh/causeofwhy
4791d29d539da68f20c338a0f7a2a3878c754b54
causeofwhy/indexer.py
python
Index.union
(self, terms)
return pages
Returns set of Page.IDs that contain any term in the term list.
Returns set of Page.IDs that contain any term in the term list.
[ "Returns", "set", "of", "Page", ".", "IDs", "that", "contain", "any", "term", "in", "the", "term", "list", "." ]
def union(self, terms): """Returns set of Page.IDs that contain any term in the term list.""" terms = list(terms) try: # Check that each term is a number (token-ID). _ = [x + 1 for x in terms] except TypeError: # They're not numbers, so we need to convert them to token-IDs. terms = [self.dict.token2id.get(term, None) for term in terms] terms = [x for x in terms if x] pages = set() if pymongo: pages.update(self.toki[terms]) else: for term in terms: if term in self.toki: ID = self.toki[term] pages.update(ID) return pages
[ "def", "union", "(", "self", ",", "terms", ")", ":", "terms", "=", "list", "(", "terms", ")", "try", ":", "# Check that each term is a number (token-ID).", "_", "=", "[", "x", "+", "1", "for", "x", "in", "terms", "]", "except", "TypeError", ":", "# They'...
https://github.com/bwbaugh/causeofwhy/blob/4791d29d539da68f20c338a0f7a2a3878c754b54/causeofwhy/indexer.py#L212-L230
eliben/code-for-blog
06d6887eccd84ca5703b792a85ab6c1ebfc5393e
2009/py_rd_parser_example/rd_parser_infix_expr.py
python
CalcParser.calc
(self, line)
return val
Parse a new line of input and return its result. Variables defined in previous calls to calc can be used in following ones. ParseError can be raised in case of errors.
Parse a new line of input and return its result.
[ "Parse", "a", "new", "line", "of", "input", "and", "return", "its", "result", "." ]
def calc(self, line): """ Parse a new line of input and return its result. Variables defined in previous calls to calc can be used in following ones. ParseError can be raised in case of errors. """ self.lexer.input(line) self._get_next_token() val = self._stmt() if self.cur_token.type != None: self._error('Unexpected token %s (at #%s)' % ( self.cur_token.val, self.cur_token.pos)) return val
[ "def", "calc", "(", "self", ",", "line", ")", ":", "self", ".", "lexer", ".", "input", "(", "line", ")", "self", ".", "_get_next_token", "(", ")", "val", "=", "self", ".", "_stmt", "(", ")", "if", "self", ".", "cur_token", ".", "type", "!=", "Non...
https://github.com/eliben/code-for-blog/blob/06d6887eccd84ca5703b792a85ab6c1ebfc5393e/2009/py_rd_parser_example/rd_parser_infix_expr.py#L66-L83
lozuwa/impy
ddfaedf764c1cb2ced7f644a3a065715758874a5
impy/AugmentationConfigurationFile.py
python
AugmentationConfigurationFile.isGeometricConfFile
(self, keys = None)
Check if file is a bounding box configuration file. Args: keys: A list of strings. Returns: A boolean that is true if the conf file is geomtric.
Check if file is a bounding box configuration file. Args: keys: A list of strings. Returns: A boolean that is true if the conf file is geomtric.
[ "Check", "if", "file", "is", "a", "bounding", "box", "configuration", "file", ".", "Args", ":", "keys", ":", "A", "list", "of", "strings", ".", "Returns", ":", "A", "boolean", "that", "is", "true", "if", "the", "conf", "file", "is", "geomtric", "." ]
def isGeometricConfFile(self, keys = None): """ Check if file is a bounding box configuration file. Args: keys: A list of strings. Returns: A boolean that is true if the conf file is geomtric. """ # Assertions if (keys == None): raise ValueError("ERROR: Keys parameter cannot be empty.") if (type(keys) != list): raise ValueError("ERROR: keys should be a list.") if (len(keys) != 1): raise ValueError("ERROR: keys should be of len > 1.") # Check for type of configuration if (keys[0] == self.confAugGeometric): return True else: return False
[ "def", "isGeometricConfFile", "(", "self", ",", "keys", "=", "None", ")", ":", "# Assertions", "if", "(", "keys", "==", "None", ")", ":", "raise", "ValueError", "(", "\"ERROR: Keys parameter cannot be empty.\"", ")", "if", "(", "type", "(", "keys", ")", "!="...
https://github.com/lozuwa/impy/blob/ddfaedf764c1cb2ced7f644a3a065715758874a5/impy/AugmentationConfigurationFile.py#L273-L292
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/program_enrollments/rest_api/v1/utils.py
python
verify_course_exists_and_in_program
(view_func)
return wrapped_function
Raises: An api error if the course run specified by the `course_id` kwarg in the wrapped function is not part of the curriculum of the program specified by the `program_uuid` kwarg This decorator guarantees existance of the program and course, so wrapping alongside `verify_{program,course}_exists` is redundant. Expects to be used within a subclass of ProgramCourseSpecificViewMixin.
Raises: An api error if the course run specified by the `course_id` kwarg in the wrapped function is not part of the curriculum of the program specified by the `program_uuid` kwarg
[ "Raises", ":", "An", "api", "error", "if", "the", "course", "run", "specified", "by", "the", "course_id", "kwarg", "in", "the", "wrapped", "function", "is", "not", "part", "of", "the", "curriculum", "of", "the", "program", "specified", "by", "the", "progra...
def verify_course_exists_and_in_program(view_func): """ Raises: An api error if the course run specified by the `course_id` kwarg in the wrapped function is not part of the curriculum of the program specified by the `program_uuid` kwarg This decorator guarantees existance of the program and course, so wrapping alongside `verify_{program,course}_exists` is redundant. Expects to be used within a subclass of ProgramCourseSpecificViewMixin. """ @wraps(view_func) @verify_program_exists @verify_course_exists() def wrapped_function(self, *args, **kwargs): """ Wraps view function """ if not is_course_run_in_program(self.course_key, self.program): raise self.api_error( status_code=status.HTTP_404_NOT_FOUND, developer_message="the program's curriculum does not contain the given course", error_code='course_not_in_program' ) return view_func(self, *args, **kwargs) return wrapped_function
[ "def", "verify_course_exists_and_in_program", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ")", "@", "verify_program_exists", "@", "verify_course_exists", "(", ")", "def", "wrapped_function", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs",...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/program_enrollments/rest_api/v1/utils.py#L145-L171
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/contrib/rpsystem.py
python
ContribRPObject.search
( self, searchdata, global_search=False, use_nicks=True, typeclass=None, location=None, attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None, multimatch_string=None, use_dbref=None, )
return _AT_SEARCH_RESULT( results, self, query=searchdata, nofound_string=nofound_string, multimatch_string=multimatch_string, )
Returns an Object matching a search string/condition, taking sdescs into account. Perform a standard object search in the database, handling multiple results and lack thereof gracefully. By default, only objects in the current `location` of `self` or its inventory are searched for. Args: searchdata (str or obj): Primary search criterion. Will be matched against `object.key` (with `object.aliases` second) unless the keyword attribute_name specifies otherwise. **Special strings:** - `#<num>`: search by unique dbref. This is always a global search. - `me,self`: self-reference to this object - `<num>-<string>` - can be used to differentiate between multiple same-named matches global_search (bool): Search all objects globally. This is overruled by `location` keyword. use_nicks (bool): Use nickname-replace (nicktype "object") on `searchdata`. typeclass (str or Typeclass, or list of either): Limit search only to `Objects` with this typeclass. May be a list of typeclasses for a broader search. location (Object or list): Specify a location or multiple locations to search. Note that this is used to query the *contents* of a location and will not match for the location itself - if you want that, don't set this or use `candidates` to specify exactly which objects should be searched. attribute_name (str): Define which property to search. If set, no key+alias search will be performed. This can be used to search database fields (db_ will be automatically appended), and if that fails, it will try to return objects having Attributes with this name and value equal to searchdata. A special use is to search for "key" here if you want to do a key-search without including aliases. quiet (bool): don't display default error messages - this tells the search method that the user wants to handle all errors themselves. It also changes the return value type, see below. exact (bool): if unset (default) - prefers to match to beginning of string rather than not matching at all. If set, requires exact matching of entire string. candidates (list of objects): this is an optional custom list of objects to search (filter) between. It is ignored if `global_search` is given. If not set, this list will automatically be defined to include the location, the contents of location and the caller's contents (inventory). nofound_string (str): optional custom string for not-found error message. multimatch_string (str): optional custom string for multimatch error header. use_dbref (bool or None): If None, only turn off use_dbref if we are of a lower permission than Builder. Otherwise, honor the True/False value. Returns: match (Object, None or list): will return an Object/None if `quiet=False`, otherwise it will return a list of 0, 1 or more matches. Notes: To find Accounts, use eg. `evennia.account_search`. If `quiet=False`, error messages will be handled by `settings.SEARCH_AT_RESULT` and echoed automatically (on error, return will be `None`). If `quiet=True`, the error messaging is assumed to be handled by the caller.
Returns an Object matching a search string/condition, taking sdescs into account.
[ "Returns", "an", "Object", "matching", "a", "search", "string", "/", "condition", "taking", "sdescs", "into", "account", "." ]
def search( self, searchdata, global_search=False, use_nicks=True, typeclass=None, location=None, attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None, multimatch_string=None, use_dbref=None, ): """ Returns an Object matching a search string/condition, taking sdescs into account. Perform a standard object search in the database, handling multiple results and lack thereof gracefully. By default, only objects in the current `location` of `self` or its inventory are searched for. Args: searchdata (str or obj): Primary search criterion. Will be matched against `object.key` (with `object.aliases` second) unless the keyword attribute_name specifies otherwise. **Special strings:** - `#<num>`: search by unique dbref. This is always a global search. - `me,self`: self-reference to this object - `<num>-<string>` - can be used to differentiate between multiple same-named matches global_search (bool): Search all objects globally. This is overruled by `location` keyword. use_nicks (bool): Use nickname-replace (nicktype "object") on `searchdata`. typeclass (str or Typeclass, or list of either): Limit search only to `Objects` with this typeclass. May be a list of typeclasses for a broader search. location (Object or list): Specify a location or multiple locations to search. Note that this is used to query the *contents* of a location and will not match for the location itself - if you want that, don't set this or use `candidates` to specify exactly which objects should be searched. attribute_name (str): Define which property to search. If set, no key+alias search will be performed. This can be used to search database fields (db_ will be automatically appended), and if that fails, it will try to return objects having Attributes with this name and value equal to searchdata. A special use is to search for "key" here if you want to do a key-search without including aliases. quiet (bool): don't display default error messages - this tells the search method that the user wants to handle all errors themselves. It also changes the return value type, see below. exact (bool): if unset (default) - prefers to match to beginning of string rather than not matching at all. If set, requires exact matching of entire string. candidates (list of objects): this is an optional custom list of objects to search (filter) between. It is ignored if `global_search` is given. If not set, this list will automatically be defined to include the location, the contents of location and the caller's contents (inventory). nofound_string (str): optional custom string for not-found error message. multimatch_string (str): optional custom string for multimatch error header. use_dbref (bool or None): If None, only turn off use_dbref if we are of a lower permission than Builder. Otherwise, honor the True/False value. Returns: match (Object, None or list): will return an Object/None if `quiet=False`, otherwise it will return a list of 0, 1 or more matches. Notes: To find Accounts, use eg. `evennia.account_search`. If `quiet=False`, error messages will be handled by `settings.SEARCH_AT_RESULT` and echoed automatically (on error, return will be `None`). If `quiet=True`, the error messaging is assumed to be handled by the caller. """ is_string = isinstance(searchdata, str) if is_string: # searchdata is a string; wrap some common self-references if searchdata.lower() in ("here",): return [self.location] if quiet else self.location if searchdata.lower() in ("me", "self"): return [self] if quiet else self if use_nicks: # do nick-replacement on search searchdata = self.nicks.nickreplace( searchdata, categories=("object", "account"), include_account=True ) if global_search or ( is_string and searchdata.startswith("#") and len(searchdata) > 1 and searchdata[1:].isdigit() ): # only allow exact matching if searching the entire database # or unique #dbrefs exact = True elif candidates is None: # no custom candidates given - get them automatically if location: # location(s) were given candidates = [] for obj in make_iter(location): candidates.extend(obj.contents) else: # local search. Candidates are taken from # self.contents, self.location and # self.location.contents location = self.location candidates = self.contents if location: candidates = candidates + [location] + location.contents else: # normally we don't need this since we are # included in location.contents candidates.append(self) # the sdesc-related substitution is_builder = self.locks.check_lockstring(self, "perm(Builder)") use_dbref = is_builder if use_dbref is None else use_dbref def search_obj(string): "helper wrapper for searching" return ObjectDB.objects.object_search( string, attribute_name=attribute_name, typeclass=typeclass, candidates=candidates, exact=exact, use_dbref=use_dbref, ) if candidates: candidates = parse_sdescs_and_recogs( self, candidates, _PREFIX + searchdata, search_mode=True ) results = [] for candidate in candidates: # we search by candidate keys here; this allows full error # management and use of all kwargs - we will use searchdata # in eventual error reporting later (not their keys). Doing # it like this e.g. allows for use of the typeclass kwarg # limiter. results.extend([obj for obj in search_obj(candidate.key) if obj not in results]) if not results and is_builder: # builders get a chance to search only by key+alias results = search_obj(searchdata) else: # global searches / #drefs end up here. Global searches are # only done in code, so is controlled, #dbrefs are turned off # for non-Builders. results = search_obj(searchdata) if quiet: return results return _AT_SEARCH_RESULT( results, self, query=searchdata, nofound_string=nofound_string, multimatch_string=multimatch_string, )
[ "def", "search", "(", "self", ",", "searchdata", ",", "global_search", "=", "False", ",", "use_nicks", "=", "True", ",", "typeclass", "=", "None", ",", "location", "=", "None", ",", "attribute_name", "=", "None", ",", "quiet", "=", "False", ",", "exact",...
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/contrib/rpsystem.py#L1245-L1415
stoq/stoq
c26991644d1affcf96bc2e0a0434796cabdf8448
stoq/lib/status.py
python
ResourceStatusManager.refresh_and_notify
(self, force=False)
return self._refresh_and_notify(force=force)
Refresh the status and notify for changes
Refresh the status and notify for changes
[ "Refresh", "the", "status", "and", "notify", "for", "changes" ]
def refresh_and_notify(self, force=False): """Refresh the status and notify for changes""" # Do not run checks if we are running tests. It breaks the whole suite if os.environ.get('STOQ_TESTSUIT_RUNNING', '0') == '1': return False return self._refresh_and_notify(force=force)
[ "def", "refresh_and_notify", "(", "self", ",", "force", "=", "False", ")", ":", "# Do not run checks if we are running tests. It breaks the whole suite", "if", "os", ".", "environ", ".", "get", "(", "'STOQ_TESTSUIT_RUNNING'", ",", "'0'", ")", "==", "'1'", ":", "retu...
https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoq/lib/status.py#L189-L194
joxeankoret/nightmare
11b22bb7c346611de90f479ee781c9228af453ea
runtime/diff_match_patch.py
python
diff_match_patch.diff_commonOverlap
(self, text1, text2)
Determine if the suffix of one string is the prefix of another. Args: text1 First string. text2 Second string. Returns: The number of characters common to the end of the first string and the start of the second string.
Determine if the suffix of one string is the prefix of another.
[ "Determine", "if", "the", "suffix", "of", "one", "string", "is", "the", "prefix", "of", "another", "." ]
def diff_commonOverlap(self, text1, text2): """Determine if the suffix of one string is the prefix of another. Args: text1 First string. text2 Second string. Returns: The number of characters common to the end of the first string and the start of the second string. """ # Cache the text lengths to prevent multiple calls. text1_length = len(text1) text2_length = len(text2) # Eliminate the null case. if text1_length == 0 or text2_length == 0: return 0 # Truncate the longer string. if text1_length > text2_length: text1 = text1[-text2_length:] elif text1_length < text2_length: text2 = text2[:text1_length] text_length = min(text1_length, text2_length) # Quick check for the worst case. if text1 == text2: return text_length # Start by looking for a single character match # and increase length until no match is found. # Performance analysis: http://neil.fraser.name/news/2010/11/04/ best = 0 length = 1 while True: pattern = text1[-length:] found = text2.find(pattern) if found == -1: return best length += found if found == 0 or text1[-length:] == text2[:length]: best = length length += 1
[ "def", "diff_commonOverlap", "(", "self", ",", "text1", ",", "text2", ")", ":", "# Cache the text lengths to prevent multiple calls.", "text1_length", "=", "len", "(", "text1", ")", "text2_length", "=", "len", "(", "text2", ")", "# Eliminate the null case.", "if", "...
https://github.com/joxeankoret/nightmare/blob/11b22bb7c346611de90f479ee781c9228af453ea/runtime/diff_match_patch.py#L511-L551
Screetsec/BruteSploit
124029d7a4cf35d7017a0f2fa37c8f8e5f32a359
tools/dirsearch/thirdparty/requests/packages/urllib3/fields.py
python
RequestField._render_part
(self, name, value)
return format_header_param(name, value)
Overridable helper function to format a single header parameter. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.
Overridable helper function to format a single header parameter.
[ "Overridable", "helper", "function", "to", "format", "a", "single", "header", "parameter", "." ]
def _render_part(self, name, value): """ Overridable helper function to format a single header parameter. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ return format_header_param(name, value)
[ "def", "_render_part", "(", "self", ",", "name", ",", "value", ")", ":", "return", "format_header_param", "(", "name", ",", "value", ")" ]
https://github.com/Screetsec/BruteSploit/blob/124029d7a4cf35d7017a0f2fa37c8f8e5f32a359/tools/dirsearch/thirdparty/requests/packages/urllib3/fields.py#L104-L113
python-gitlab/python-gitlab
4a000b6c41f0a7ef6121c62a4c598edc20973799
gitlab/v4/objects/jobs.py
python
ProjectJob.retry
(self, **kwargs: Any)
return result
Retry the job. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobRetryError: If the job could not be retried
Retry the job.
[ "Retry", "the", "job", "." ]
def retry(self, **kwargs: Any) -> Dict[str, Any]: """Retry the job. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobRetryError: If the job could not be retried """ path = f"{self.manager.path}/{self.get_id()}/retry" result = self.manager.gitlab.http_post(path) if TYPE_CHECKING: assert isinstance(result, dict) return result
[ "def", "retry", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "path", "=", "f\"{self.manager.path}/{self.get_id()}/retry\"", "result", "=", "self", ".", "manager", ".", "gitlab", ".", "http_post", ...
https://github.com/python-gitlab/python-gitlab/blob/4a000b6c41f0a7ef6121c62a4c598edc20973799/gitlab/v4/objects/jobs.py#L38-L52
Dan-in-CA/SIP
7d08d807d7730bff2b5eaaa57e743665c8b143a6
web/db.py
python
DB.transaction
(self)
return Transaction(self.ctx)
Start a transaction.
Start a transaction.
[ "Start", "a", "transaction", "." ]
def transaction(self): """Start a transaction.""" return Transaction(self.ctx)
[ "def", "transaction", "(", "self", ")", ":", "return", "Transaction", "(", "self", ".", "ctx", ")" ]
https://github.com/Dan-in-CA/SIP/blob/7d08d807d7730bff2b5eaaa57e743665c8b143a6/web/db.py#L1191-L1193
Symbo1/wsltools
0b6e536fc85c707a1c81f0296c4e91ca835396a1
wsltools/utils/faker/providers/__init__.py
python
BaseProvider.random_digit
(self)
return self.generator.random.randint(0, 9)
Returns a random digit/number between 0 and 9.
Returns a random digit/number between 0 and 9.
[ "Returns", "a", "random", "digit", "/", "number", "between", "0", "and", "9", "." ]
def random_digit(self): """ Returns a random digit/number between 0 and 9. """ return self.generator.random.randint(0, 9)
[ "def", "random_digit", "(", "self", ")", ":", "return", "self", ".", "generator", ".", "random", ".", "randint", "(", "0", ",", "9", ")" ]
https://github.com/Symbo1/wsltools/blob/0b6e536fc85c707a1c81f0296c4e91ca835396a1/wsltools/utils/faker/providers/__init__.py#L109-L114
intel/IntelSEAPI
7997a782fd3fa5621e275bd31060f9795564e6ca
runtool/sea_runtool.py
python
bisect_right
(array, value, key=lambda item: item)
return lo
[]
def bisect_right(array, value, key=lambda item: item): #upper_bound, dichotomy, binary search lo = 0 hi = len(array) while lo < hi: mid = (lo + hi) // 2 if value < key(array[mid]): hi = mid else: lo = mid + 1 return lo
[ "def", "bisect_right", "(", "array", ",", "value", ",", "key", "=", "lambda", "item", ":", "item", ")", ":", "#upper_bound, dichotomy, binary search", "lo", "=", "0", "hi", "=", "len", "(", "array", ")", "while", "lo", "<", "hi", ":", "mid", "=", "(", ...
https://github.com/intel/IntelSEAPI/blob/7997a782fd3fa5621e275bd31060f9795564e6ca/runtool/sea_runtool.py#L2378-L2387
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1alpha1_queuing_configuration.py
python
V1alpha1QueuingConfiguration.queues
(self)
return self._queues
Gets the queues of this V1alpha1QueuingConfiguration. # noqa: E501 `queues` is the number of queues for this priority level. The queues exist independently at each apiserver. The value must be positive. Setting it to 1 effectively precludes shufflesharding and thus makes the distinguisher method of associated flow schemas irrelevant. This field has a default value of 64. # noqa: E501 :return: The queues of this V1alpha1QueuingConfiguration. # noqa: E501 :rtype: int
Gets the queues of this V1alpha1QueuingConfiguration. # noqa: E501
[ "Gets", "the", "queues", "of", "this", "V1alpha1QueuingConfiguration", ".", "#", "noqa", ":", "E501" ]
def queues(self): """Gets the queues of this V1alpha1QueuingConfiguration. # noqa: E501 `queues` is the number of queues for this priority level. The queues exist independently at each apiserver. The value must be positive. Setting it to 1 effectively precludes shufflesharding and thus makes the distinguisher method of associated flow schemas irrelevant. This field has a default value of 64. # noqa: E501 :return: The queues of this V1alpha1QueuingConfiguration. # noqa: E501 :rtype: int """ return self._queues
[ "def", "queues", "(", "self", ")", ":", "return", "self", ".", "_queues" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1alpha1_queuing_configuration.py#L112-L120
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/databases/db.py
python
ClientPathHistory.AddHashEntry
(self, timestamp, hash_entry)
[]
def AddHashEntry(self, timestamp, hash_entry): precondition.AssertType(timestamp, rdfvalue.RDFDatetime) precondition.AssertType(hash_entry, rdf_crypto.Hash) self.hash_entries[timestamp] = hash_entry
[ "def", "AddHashEntry", "(", "self", ",", "timestamp", ",", "hash_entry", ")", ":", "precondition", ".", "AssertType", "(", "timestamp", ",", "rdfvalue", ".", "RDFDatetime", ")", "precondition", ".", "AssertType", "(", "hash_entry", ",", "rdf_crypto", ".", "Has...
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/databases/db.py#L551-L554
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/mechanize/_response.py
python
upgrade_response
(response)
return response
Return a copy of response that supports Browser response interface. Browser response interface is that of "seekable responses" (response_seek_wrapper), plus the requirement that responses must be useable after .close() (closeable_response). Accepts responses from both mechanize and urllib2 handlers. Copes with both ordinary response instances and HTTPError instances (which can't be simply wrapped due to the requirement of preserving the exception base class).
Return a copy of response that supports Browser response interface.
[ "Return", "a", "copy", "of", "response", "that", "supports", "Browser", "response", "interface", "." ]
def upgrade_response(response): """Return a copy of response that supports Browser response interface. Browser response interface is that of "seekable responses" (response_seek_wrapper), plus the requirement that responses must be useable after .close() (closeable_response). Accepts responses from both mechanize and urllib2 handlers. Copes with both ordinary response instances and HTTPError instances (which can't be simply wrapped due to the requirement of preserving the exception base class). """ wrapper_class = get_seek_wrapper_class(response) if hasattr(response, "closeable_response"): if not hasattr(response, "seek"): response = wrapper_class(response) assert hasattr(response, "get_data") return copy.copy(response) # a urllib2 handler constructed the response, i.e. the response is an # urllib.addinfourl or a urllib2.HTTPError, instead of a # _Util.closeable_response as returned by e.g. mechanize.HTTPHandler try: code = response.code except AttributeError: code = None try: msg = response.msg except AttributeError: msg = None # may have already-.read() data from .seek() cache data = None get_data = getattr(response, "get_data", None) if get_data: data = get_data() response = closeable_response( response.fp, response.info(), response.geturl(), code, msg) response = wrapper_class(response) if data: response.set_data(data) return response
[ "def", "upgrade_response", "(", "response", ")", ":", "wrapper_class", "=", "get_seek_wrapper_class", "(", "response", ")", "if", "hasattr", "(", "response", ",", "\"closeable_response\"", ")", ":", "if", "not", "hasattr", "(", "response", ",", "\"seek\"", ")", ...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/mechanize/_response.py#L482-L525
deluge-torrent/deluge
2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc
deluge/core/rpcserver.py
python
DelugeRPCProtocol.connectionMade
(self)
This method is called when a new client connects.
This method is called when a new client connects.
[ "This", "method", "is", "called", "when", "a", "new", "client", "connects", "." ]
def connectionMade(self): # NOQA: N802 """ This method is called when a new client connects. """ peer = self.transport.getPeer() log.info('Deluge Client connection made from: %s:%s', peer.host, peer.port) # Set the initial auth level of this session to AUTH_LEVEL_NONE self.factory.authorized_sessions[self.transport.sessionno] = self.AuthLevel( AUTH_LEVEL_NONE, '' )
[ "def", "connectionMade", "(", "self", ")", ":", "# NOQA: N802", "peer", "=", "self", ".", "transport", ".", "getPeer", "(", ")", "log", ".", "info", "(", "'Deluge Client connection made from: %s:%s'", ",", "peer", ".", "host", ",", "peer", ".", "port", ")", ...
https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/core/rpcserver.py#L161-L170
nucleic/enaml
65c2a2a2d765e88f2e1103046680571894bb41ed
enaml/qt/qt_calendar.py
python
QtCalendar.create_widget
(self)
Create the calender widget.
Create the calender widget.
[ "Create", "the", "calender", "widget", "." ]
def create_widget(self): """ Create the calender widget. """ self.widget = QCalendarWidget(self.parent_widget())
[ "def", "create_widget", "(", "self", ")", ":", "self", ".", "widget", "=", "QCalendarWidget", "(", "self", ".", "parent_widget", "(", ")", ")" ]
https://github.com/nucleic/enaml/blob/65c2a2a2d765e88f2e1103046680571894bb41ed/enaml/qt/qt_calendar.py#L27-L31
mozilla/http-observatory
169ae7ce44002ce21d7e8c162525f992a198586f
httpobs/scanner/analyzer/headers.py
python
x_xss_protection
(reqs: dict, expectation='x-xss-protection-1-mode-block')
return output
:param reqs: dictionary containing all the request and response objects :param expectation: test expectation x-xss-protection-enabled-mode-block: X-XSS-Protection set to "1; block" [default] x-xss-protection-enabled: X-XSS-Protection set to "1" x-xss-protection-not-needed-due-to-csp: no X-XSS-Protection header, but CSP blocks inline nonsense x-xss-protection-disabled: X-XSS-Protection set to "0" (disabled) x-xss-protection-not-implemented: X-XSS-Protection header missing x-xss-protection-header-invalid :return: dictionary with: data: the raw X-XSS-Protection header expectation: test expectation pass: whether the site's configuration met its expectation result: short string describing the result of the test
:param reqs: dictionary containing all the request and response objects :param expectation: test expectation x-xss-protection-enabled-mode-block: X-XSS-Protection set to "1; block" [default] x-xss-protection-enabled: X-XSS-Protection set to "1" x-xss-protection-not-needed-due-to-csp: no X-XSS-Protection header, but CSP blocks inline nonsense x-xss-protection-disabled: X-XSS-Protection set to "0" (disabled) x-xss-protection-not-implemented: X-XSS-Protection header missing x-xss-protection-header-invalid :return: dictionary with: data: the raw X-XSS-Protection header expectation: test expectation pass: whether the site's configuration met its expectation result: short string describing the result of the test
[ ":", "param", "reqs", ":", "dictionary", "containing", "all", "the", "request", "and", "response", "objects", ":", "param", "expectation", ":", "test", "expectation", "x", "-", "xss", "-", "protection", "-", "enabled", "-", "mode", "-", "block", ":", "X", ...
def x_xss_protection(reqs: dict, expectation='x-xss-protection-1-mode-block') -> dict: """ :param reqs: dictionary containing all the request and response objects :param expectation: test expectation x-xss-protection-enabled-mode-block: X-XSS-Protection set to "1; block" [default] x-xss-protection-enabled: X-XSS-Protection set to "1" x-xss-protection-not-needed-due-to-csp: no X-XSS-Protection header, but CSP blocks inline nonsense x-xss-protection-disabled: X-XSS-Protection set to "0" (disabled) x-xss-protection-not-implemented: X-XSS-Protection header missing x-xss-protection-header-invalid :return: dictionary with: data: the raw X-XSS-Protection header expectation: test expectation pass: whether the site's configuration met its expectation result: short string describing the result of the test """ VALID_DIRECTIVES = ('0', '1', 'mode', 'report') VALID_MODES = ('block',) output = { 'data': None, 'expectation': expectation, 'pass': False, 'result': None, } enabled = False # XXSSP enabled or not valid = True # XXSSP header valid or not response = reqs['responses']['auto'] header = response.headers.get('X-XSS-Protection', '').strip() xxssp = {} if header: output['data'] = header[0:256] # code defensively # Parse out the X-XSS-Protection header try: if header[0] not in ('0', '1'): raise ValueError if header[0] == '1': enabled = True # {'1': None, 'mode': 'block', 'report': 'https://www.example.com/__reporturi__'} for directive in header.lower().split(';'): k, v = [d.strip() for d in directive.split('=')] if '=' in directive else (directive.strip(), None) # An invalid directive, like foo=bar if k not in VALID_DIRECTIVES: raise ValueError # An invalid mode, like mode=allow if k == 'mode' and v not in VALID_MODES: raise ValueError # A repeated directive, such as 1; mode=block; mode=block if k in xxssp: raise ValueError xxssp[k] = v except: output['result'] = 'x-xss-protection-header-invalid' valid = False if valid and enabled and xxssp.get('mode') == 'block': output['result'] = 'x-xss-protection-enabled-mode-block' output['pass'] = True elif valid and enabled: output['result'] = 'x-xss-protection-enabled' output['pass'] = True elif valid and not enabled: output['result'] = 'x-xss-protection-disabled' else: output['result'] = 'x-xss-protection-not-implemented' # Allow sites to skip out of having X-XSS-Protection if they implement a strong CSP policy # Note that having an invalid XXSSP setting will still trigger, even with a good CSP policy if valid and output['pass'] is False: if content_security_policy(reqs)['pass']: output['pass'] = True output['result'] = 'x-xss-protection-not-needed-due-to-csp' return output
[ "def", "x_xss_protection", "(", "reqs", ":", "dict", ",", "expectation", "=", "'x-xss-protection-1-mode-block'", ")", "->", "dict", ":", "VALID_DIRECTIVES", "=", "(", "'0'", ",", "'1'", ",", "'mode'", ",", "'report'", ")", "VALID_MODES", "=", "(", "'block'", ...
https://github.com/mozilla/http-observatory/blob/169ae7ce44002ce21d7e8c162525f992a198586f/httpobs/scanner/analyzer/headers.py#L770-L853
markokr/rarfile
55fe778b5207ebba48b8158d2c25d9d536ec89de
rarfile.py
python
UnicodeFilename.enc_byte
(self)
Copy encoded byte.
Copy encoded byte.
[ "Copy", "encoded", "byte", "." ]
def enc_byte(self): """Copy encoded byte.""" try: c = self.encdata[self.encpos] self.encpos += 1 return c except IndexError: self.failed = 1 return 0
[ "def", "enc_byte", "(", "self", ")", ":", "try", ":", "c", "=", "self", ".", "encdata", "[", "self", ".", "encpos", "]", "self", ".", "encpos", "+=", "1", "return", "c", "except", "IndexError", ":", "self", ".", "failed", "=", "1", "return", "0" ]
https://github.com/markokr/rarfile/blob/55fe778b5207ebba48b8158d2c25d9d536ec89de/rarfile.py#L2114-L2122
pika/pika
12dcdf15d0932c388790e0fa990810bfd21b1a32
examples/asynchronous_publisher_example.py
python
ExamplePublisher.on_connection_open
(self, _unused_connection)
This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :param pika.SelectConnection _unused_connection: The connection
This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused.
[ "This", "method", "is", "called", "by", "pika", "once", "the", "connection", "to", "RabbitMQ", "has", "been", "established", ".", "It", "passes", "the", "handle", "to", "the", "connection", "object", "in", "case", "we", "need", "it", "but", "in", "this", ...
def on_connection_open(self, _unused_connection): """This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it, but in this case, we'll just mark it unused. :param pika.SelectConnection _unused_connection: The connection """ LOGGER.info('Connection opened') self.open_channel()
[ "def", "on_connection_open", "(", "self", ",", "_unused_connection", ")", ":", "LOGGER", ".", "info", "(", "'Connection opened'", ")", "self", ".", "open_channel", "(", ")" ]
https://github.com/pika/pika/blob/12dcdf15d0932c388790e0fa990810bfd21b1a32/examples/asynchronous_publisher_example.py#L67-L76
philip-huang/PIXOR
2f64e84f72d915f8b5b80d4615bc9a0c881b5dab
srcs/postprocess.py
python
compute_iou
(box, boxes)
return np.array(iou, dtype=np.float32)
Calculates IoU of the given box with the array of the given boxes. box: a polygon boxes: a vector of polygons Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work.
Calculates IoU of the given box with the array of the given boxes. box: a polygon boxes: a vector of polygons Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work.
[ "Calculates", "IoU", "of", "the", "given", "box", "with", "the", "array", "of", "the", "given", "boxes", ".", "box", ":", "a", "polygon", "boxes", ":", "a", "vector", "of", "polygons", "Note", ":", "the", "areas", "are", "passed", "in", "rather", "than...
def compute_iou(box, boxes): """Calculates IoU of the given box with the array of the given boxes. box: a polygon boxes: a vector of polygons Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas iou = [box.intersection(b).area / box.union(b).area for b in boxes] return np.array(iou, dtype=np.float32)
[ "def", "compute_iou", "(", "box", ",", "boxes", ")", ":", "# Calculate intersection areas", "iou", "=", "[", "box", ".", "intersection", "(", "b", ")", ".", "area", "/", "box", ".", "union", "(", "b", ")", ".", "area", "for", "b", "in", "boxes", "]",...
https://github.com/philip-huang/PIXOR/blob/2f64e84f72d915f8b5b80d4615bc9a0c881b5dab/srcs/postprocess.py#L43-L53
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/multiprocessing/sharedctypes.py
python
Array
(typecode_or_type, size_or_initializer, **kwds)
return synchronized(obj, lock)
Return a synchronization wrapper for a RawArray
Return a synchronization wrapper for a RawArray
[ "Return", "a", "synchronization", "wrapper", "for", "a", "RawArray" ]
def Array(typecode_or_type, size_or_initializer, **kwds): ''' Return a synchronization wrapper for a RawArray ''' lock = kwds.pop('lock', None) if kwds: raise ValueError('unrecognized keyword argument(s): %s' % kwds.keys()) obj = RawArray(typecode_or_type, size_or_initializer) if lock is False: return obj if lock in (True, None): lock = RLock() if not hasattr(lock, 'acquire'): raise AttributeError("'%r' has no method 'acquire'" % lock) return synchronized(obj, lock)
[ "def", "Array", "(", "typecode_or_type", ",", "size_or_initializer", ",", "*", "*", "kwds", ")", ":", "lock", "=", "kwds", ".", "pop", "(", "'lock'", ",", "None", ")", "if", "kwds", ":", "raise", "ValueError", "(", "'unrecognized keyword argument(s): %s'", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/multiprocessing/sharedctypes.py#L108-L122
pyudev/pyudev
d5630bf15692b652db55d626f66274169f3448d5
src/pyudev/device/_device.py
python
Properties.asint
(self, prop)
return int(self[prop])
Get the given property from this device as integer. ``prop`` is a unicode or byte string containing the name of the property. Return the property value as integer. Raise a :exc:`~exceptions.KeyError`, if the given property is not defined for this device, or a :exc:`~exceptions.ValueError`, if the property value cannot be converted to an integer.
Get the given property from this device as integer.
[ "Get", "the", "given", "property", "from", "this", "device", "as", "integer", "." ]
def asint(self, prop): """ Get the given property from this device as integer. ``prop`` is a unicode or byte string containing the name of the property. Return the property value as integer. Raise a :exc:`~exceptions.KeyError`, if the given property is not defined for this device, or a :exc:`~exceptions.ValueError`, if the property value cannot be converted to an integer. """ return int(self[prop])
[ "def", "asint", "(", "self", ",", "prop", ")", ":", "return", "int", "(", "self", "[", "prop", "]", ")" ]
https://github.com/pyudev/pyudev/blob/d5630bf15692b652db55d626f66274169f3448d5/src/pyudev/device/_device.py#L1118-L1130
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py
python
_IPAddressBase._report_invalid_netmask
(cls, netmask_str)
[]
def _report_invalid_netmask(cls, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg)
[ "def", "_report_invalid_netmask", "(", "cls", ",", "netmask_str", ")", ":", "msg", "=", "'%r is not a valid netmask'", "%", "netmask_str", "raise", "NetmaskValueError", "(", "msg", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/ipaddress.py#L594-L596
libertysoft3/saidit
271c7d03adb369f82921d811360b00812e42da24
r2/r2/lib/loid.py
python
LoId._create
(cls, request, context)
return loid
Create and return a new logged out id and timestamp. This also triggers an loid_event in the event pipeline. :param request: current :py:module:`pylons` request object :param context: current :py:module:`pylons` context object :rtype: :py:class:`LoId` :returns: new ``LoId``
Create and return a new logged out id and timestamp.
[ "Create", "and", "return", "a", "new", "logged", "out", "id", "and", "timestamp", "." ]
def _create(cls, request, context): """Create and return a new logged out id and timestamp. This also triggers an loid_event in the event pipeline. :param request: current :py:module:`pylons` request object :param context: current :py:module:`pylons` context object :rtype: :py:class:`LoId` :returns: new ``LoId`` """ loid = cls( request=request, context=context, new=True, loid=randstr(LOID_LENGTH, LOID_CHARSPACE), ) loid._trigger_event("create_loid") return loid
[ "def", "_create", "(", "cls", ",", "request", ",", "context", ")", ":", "loid", "=", "cls", "(", "request", "=", "request", ",", "context", "=", "context", ",", "new", "=", "True", ",", "loid", "=", "randstr", "(", "LOID_LENGTH", ",", "LOID_CHARSPACE",...
https://github.com/libertysoft3/saidit/blob/271c7d03adb369f82921d811360b00812e42da24/r2/r2/lib/loid.py#L95-L112
HeinleinSupport/check_mk_extensions
aa7d7389b812ed00f91dad61d66fb676284897d8
entropy_avail/lib/check_mk/base/plugins/agent_based/entropy_avail.py
python
parse_entropy_avail
(string_table)
return section
[]
def parse_entropy_avail(string_table): section = {} for line in string_table: try: section[line[0]] = int(line[1]) except ValueError: pass return section
[ "def", "parse_entropy_avail", "(", "string_table", ")", ":", "section", "=", "{", "}", "for", "line", "in", "string_table", ":", "try", ":", "section", "[", "line", "[", "0", "]", "]", "=", "int", "(", "line", "[", "1", "]", ")", "except", "ValueErro...
https://github.com/HeinleinSupport/check_mk_extensions/blob/aa7d7389b812ed00f91dad61d66fb676284897d8/entropy_avail/lib/check_mk/base/plugins/agent_based/entropy_avail.py#L33-L40
rogertrullo/pytorch_convlstm
ed5572e9728fff665f31765d65578d5d283d3d05
conv_lstm.py
python
CLSTM.forward
(self, input, hidden_state)
return next_hidden, current_input
args: hidden_state:list of tuples, one for every layer, each tuple should be hidden_layer_i,c_layer_i input is the tensor of shape seq_len,Batch,Chans,H,W
args: hidden_state:list of tuples, one for every layer, each tuple should be hidden_layer_i,c_layer_i input is the tensor of shape seq_len,Batch,Chans,H,W
[ "args", ":", "hidden_state", ":", "list", "of", "tuples", "one", "for", "every", "layer", "each", "tuple", "should", "be", "hidden_layer_i", "c_layer_i", "input", "is", "the", "tensor", "of", "shape", "seq_len", "Batch", "Chans", "H", "W" ]
def forward(self, input, hidden_state): """ args: hidden_state:list of tuples, one for every layer, each tuple should be hidden_layer_i,c_layer_i input is the tensor of shape seq_len,Batch,Chans,H,W """ current_input = input.transpose(0, 1)#now is seq_len,B,C,H,W #current_input=input next_hidden=[]#hidden states(h and c) seq_len=current_input.size(0) for idlayer in xrange(self.num_layers):#loop for every layer hidden_c=hidden_state[idlayer]#hidden and c are images with several channels all_output = [] output_inner = [] for t in xrange(seq_len):#loop for every step hidden_c=self.cell_list[idlayer](current_input[t,...],hidden_c)#cell_list is a list with different conv_lstms 1 for every layer output_inner.append(hidden_c[0]) next_hidden.append(hidden_c) current_input = torch.cat(output_inner, 0).view(current_input.size(0), *output_inner[0].size())#seq_len,B,chans,H,W return next_hidden, current_input
[ "def", "forward", "(", "self", ",", "input", ",", "hidden_state", ")", ":", "current_input", "=", "input", ".", "transpose", "(", "0", ",", "1", ")", "#now is seq_len,B,C,H,W", "#current_input=input", "next_hidden", "=", "[", "]", "#hidden states(h and c)", "seq...
https://github.com/rogertrullo/pytorch_convlstm/blob/ed5572e9728fff665f31765d65578d5d283d3d05/conv_lstm.py#L79-L107
nlloyd/SubliminalCollaborator
5c619e17ddbe8acb9eea8996ec038169ddcd50a1
libs/twisted/python/versions.py
python
_inf.__cmp__
(self, other)
return 1
@param other: Another object. @type other: any @return: 0 if other is inf, 1 otherwise. @rtype: C{int}
@param other: Another object. @type other: any
[ "@param", "other", ":", "Another", "object", ".", "@type", "other", ":", "any" ]
def __cmp__(self, other): """ @param other: Another object. @type other: any @return: 0 if other is inf, 1 otherwise. @rtype: C{int} """ if other is _inf: return 0 return 1
[ "def", "__cmp__", "(", "self", ",", "other", ")", ":", "if", "other", "is", "_inf", ":", "return", "0", "return", "1" ]
https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/python/versions.py#L18-L28
shiyanlou/louplus-python
4c61697259e286e3d9116c3299f170d019ba3767
taobei/challenge-04/tbmall/handlers/shop.py
python
update_shop
(id)
return json_response(shop=ShopSchema().dump(shop))
更新店铺
更新店铺
[ "更新店铺" ]
def update_shop(id): """更新店铺 """ data = request.get_json() count = Shop.query.filter(Shop.id == id).update(data) if count == 0: return json_response(ResponseCode.NOT_FOUND) shop = Shop.query.get(id) session.commit() return json_response(shop=ShopSchema().dump(shop))
[ "def", "update_shop", "(", "id", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "count", "=", "Shop", ".", "query", ".", "filter", "(", "Shop", ".", "id", "==", "id", ")", ".", "update", "(", "data", ")", "if", "count", "==", "0", ...
https://github.com/shiyanlou/louplus-python/blob/4c61697259e286e3d9116c3299f170d019ba3767/taobei/challenge-04/tbmall/handlers/shop.py#L48-L60
zopefoundation/Zope
ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb
src/Products/PageTemplates/engine.py
python
RepeatDictWrapper.__call__
(self, key, iterable)
return ri, length
We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.
We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.
[ "We", "coerce", "the", "iterable", "to", "a", "tuple", "and", "return", "an", "iterator", "after", "registering", "it", "in", "the", "repeat", "dictionary", "." ]
def __call__(self, key, iterable): """We coerce the iterable to a tuple and return an iterator after registering it in the repeat dictionary.""" iterable = list(iterable) if iterable is not None else () length = len(iterable) # Insert as repeat item ri = self[key] = RepeatItem(None, iterable, _PseudoContext) return ri, length
[ "def", "__call__", "(", "self", ",", "key", ",", "iterable", ")", ":", "iterable", "=", "list", "(", "iterable", ")", "if", "iterable", "is", "not", "None", "else", "(", ")", "length", "=", "len", "(", "iterable", ")", "# Insert as repeat item", "ri", ...
https://github.com/zopefoundation/Zope/blob/ea04dd670d1a48d4d5c879d3db38fc2e9b4330bb/src/Products/PageTemplates/engine.py#L71-L81
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/common/numberTools.py
python
unitNormalizeProportion
(values: Sequence[int])
return unit
Normalize values within the unit interval, where max is determined by the sum of the series. >>> common.unitNormalizeProportion([0, 3, 4]) [0.0, 0.42857142857142855, 0.5714285714285714] >>> common.unitNormalizeProportion([1, 1, 1]) [0.3333333..., 0.333333..., 0.333333...] On 32-bit computers this number is inexact. On 64-bit it works fine. # >>> common.unitNormalizeProportion([0.2, 0.6, 0.2]) # [0.20000000000000001, 0.59999999999999998, 0.20000000000000001] Negative values should be shifted to positive region first: >>> common.unitNormalizeProportion([0, -2, -8]) Traceback (most recent call last): ValueError: value members must be positive
Normalize values within the unit interval, where max is determined by the sum of the series.
[ "Normalize", "values", "within", "the", "unit", "interval", "where", "max", "is", "determined", "by", "the", "sum", "of", "the", "series", "." ]
def unitNormalizeProportion(values: Sequence[int]) -> List[float]: ''' Normalize values within the unit interval, where max is determined by the sum of the series. >>> common.unitNormalizeProportion([0, 3, 4]) [0.0, 0.42857142857142855, 0.5714285714285714] >>> common.unitNormalizeProportion([1, 1, 1]) [0.3333333..., 0.333333..., 0.333333...] On 32-bit computers this number is inexact. On 64-bit it works fine. # >>> common.unitNormalizeProportion([0.2, 0.6, 0.2]) # [0.20000000000000001, 0.59999999999999998, 0.20000000000000001] Negative values should be shifted to positive region first: >>> common.unitNormalizeProportion([0, -2, -8]) Traceback (most recent call last): ValueError: value members must be positive ''' summation = 0 for x in values: if x < 0: raise ValueError('value members must be positive') summation += x unit = [] # weights on the unit interval; sum == 1 for x in values: unit.append((x / summation)) return unit
[ "def", "unitNormalizeProportion", "(", "values", ":", "Sequence", "[", "int", "]", ")", "->", "List", "[", "float", "]", ":", "summation", "=", "0", "for", "x", "in", "values", ":", "if", "x", "<", "0", ":", "raise", "ValueError", "(", "'value members ...
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/common/numberTools.py#L666-L697
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/api/mail.py
python
_EmailMessageBase.initialize
(self, **kw)
Keyword initialization. Used to set all fields of the email message using keyword arguments. Args: kw: List of keyword properties as defined by PROPERTIES.
Keyword initialization.
[ "Keyword", "initialization", "." ]
def initialize(self, **kw): """Keyword initialization. Used to set all fields of the email message using keyword arguments. Args: kw: List of keyword properties as defined by PROPERTIES. """ for name, value in kw.iteritems(): setattr(self, name, value)
[ "def", "initialize", "(", "self", ",", "*", "*", "kw", ")", ":", "for", "name", ",", "value", "in", "kw", ".", "iteritems", "(", ")", ":", "setattr", "(", "self", ",", "name", ",", "value", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/api/mail.py#L774-L783
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/gevent/_sslgte279.py
python
SSLSocket._real_connect
(self, addr, connect_ex)
[]
def _real_connect(self, addr, connect_ex): if self.server_side: raise ValueError("can't connect in server-side mode") # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._connected: raise ValueError("attempt to connect already-connected SSLSocket!") self._sslobj = self.context._wrap_socket(self._sock, False, self.server_hostname, ssl_sock=self) try: if connect_ex: rc = socket.connect_ex(self, addr) else: rc = None socket.connect(self, addr) if not rc: self._connected = True if self.do_handshake_on_connect: self.do_handshake() return rc except socket_error: self._sslobj = None raise
[ "def", "_real_connect", "(", "self", ",", "addr", ",", "connect_ex", ")", ":", "if", "self", ".", "server_side", ":", "raise", "ValueError", "(", "\"can't connect in server-side mode\"", ")", "# Here we assume that the socket is client-side, and not", "# connected at the ti...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/gevent/_sslgte279.py#L582-L603
apache/tvm
6eb4ed813ebcdcd9558f0906a1870db8302ff1e0
python/tvm/auto_scheduler/measure_record.py
python
save_records
(filename, inputs, results)
Append measure records to file. Parameters ---------- filename : str File name to write log to. inputs: List[MeasureInputs] The MeasureInputs to be written. results: List[MeasureResults] The MeasureResults to be written.
Append measure records to file.
[ "Append", "measure", "records", "to", "file", "." ]
def save_records(filename, inputs, results): """ Append measure records to file. Parameters ---------- filename : str File name to write log to. inputs: List[MeasureInputs] The MeasureInputs to be written. results: List[MeasureResults] The MeasureResults to be written. """ dirname = os.path.dirname(os.path.abspath(filename)) if not os.path.exists(dirname): os.makedirs(dirname) _ffi_api.SaveRecords(filename, inputs, results)
[ "def", "save_records", "(", "filename", ",", "inputs", ",", "results", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(...
https://github.com/apache/tvm/blob/6eb4ed813ebcdcd9558f0906a1870db8302ff1e0/python/tvm/auto_scheduler/measure_record.py#L197-L213
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.85/Libs/x86smt/solver_cvc3.py
python
Solver.forallExpr
(self, Bvars, exp)
return self.CVC.vc_forallExpr(self.vc, arr, len(Bvars), exp) | self.get_error()
FORALL (Bvars): exp Bvars is a list of Expr
FORALL (Bvars): exp Bvars is a list of Expr
[ "FORALL", "(", "Bvars", ")", ":", "exp", "Bvars", "is", "a", "list", "of", "Expr" ]
def forallExpr(self, Bvars, exp): """ FORALL (Bvars): exp Bvars is a list of Expr """ arr = (c_ulong * len(Bvars))() c=0 for x in Bvars: arr[c] = x c+=1 return self.CVC.vc_forallExpr(self.vc, arr, len(Bvars), exp) | self.get_error()
[ "def", "forallExpr", "(", "self", ",", "Bvars", ",", "exp", ")", ":", "arr", "=", "(", "c_ulong", "*", "len", "(", "Bvars", ")", ")", "(", ")", "c", "=", "0", "for", "x", "in", "Bvars", ":", "arr", "[", "c", "]", "=", "x", "c", "+=", "1", ...
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.85/Libs/x86smt/solver_cvc3.py#L587-L598
seomoz/shovel
fc29232b2b8be33972f8fb498a91a67e334f057f
shovel/tasks.py
python
Shovel.__getitem__
(self, key)
return current[split[-1]]
Find a task with the provided name
Find a task with the provided name
[ "Find", "a", "task", "with", "the", "provided", "name" ]
def __getitem__(self, key): '''Find a task with the provided name''' current = self.map split = key.split('.') for module in split[:-1]: if module not in current: raise KeyError('Module not found') current = current[module].map if split[-1] not in current: raise KeyError('Task not found') return current[split[-1]]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "current", "=", "self", ".", "map", "split", "=", "key", ".", "split", "(", "'.'", ")", "for", "module", "in", "split", "[", ":", "-", "1", "]", ":", "if", "module", "not", "in", "current",...
https://github.com/seomoz/shovel/blob/fc29232b2b8be33972f8fb498a91a67e334f057f/shovel/tasks.py#L101-L111
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/nlp/data/dialogue_state_tracking/sgd/schema.py
python
ServiceSchema.__init__
(self, schema_json: dict, service_id: Optional[int] = None)
Constructor for ServiceSchema. Args: schema_json: schema json dict service_id: service ID
Constructor for ServiceSchema. Args: schema_json: schema json dict service_id: service ID
[ "Constructor", "for", "ServiceSchema", ".", "Args", ":", "schema_json", ":", "schema", "json", "dict", "service_id", ":", "service", "ID" ]
def __init__(self, schema_json: dict, service_id: Optional[int] = None): """ Constructor for ServiceSchema. Args: schema_json: schema json dict service_id: service ID """ self._service_name = schema_json["service_name"] self._description = schema_json["description"] self._schema_json = schema_json self._service_id = service_id # Construct the vocabulary for intents, slots, categorical slots, # non-categorical slots and categorical slot values. self._intents = ["NONE"] + sorted(i["name"] for i in schema_json["intents"]) self._intent_descriptions = {i["name"]: i["description"] for i in schema_json["intents"]} self._intent_descriptions["NONE"] = "none" self._slots = sorted(s["name"] for s in schema_json["slots"]) self._slots_descriptions = {s["name"]: s["description"] for s in schema_json["slots"]} self._categorical_slots = sorted( s["name"] for s in schema_json["slots"] if s["is_categorical"] and s["name"] in self.state_slots ) self._non_categorical_slots = sorted( s["name"] for s in schema_json["slots"] if not s["is_categorical"] and s["name"] in self.state_slots ) slot_schemas = {s["name"]: s for s in schema_json["slots"]} categorical_slot_values = {} categorical_slot_value_ids = {} categorical_slot_ids = {} non_categorical_slot_ids = {} for slot_id, slot in enumerate(self._categorical_slots): slot_schema = slot_schemas[slot] values = sorted(slot_schema["possible_values"]) categorical_slot_values[slot] = values value_ids = {value: idx for idx, value in enumerate(values)} categorical_slot_value_ids[slot] = value_ids categorical_slot_ids[slot] = slot_id for slot_id, slot in enumerate(self._non_categorical_slots): non_categorical_slot_ids[slot] = slot_id self._categorical_slot_values = categorical_slot_values self._categorical_slot_value_ids = categorical_slot_value_ids self._categorical_slot_ids = categorical_slot_ids self._non_categorical_slot_ids = non_categorical_slot_ids
[ "def", "__init__", "(", "self", ",", "schema_json", ":", "dict", ",", "service_id", ":", "Optional", "[", "int", "]", "=", "None", ")", ":", "self", ".", "_service_name", "=", "schema_json", "[", "\"service_name\"", "]", "self", ".", "_description", "=", ...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/nlp/data/dialogue_state_tracking/sgd/schema.py#L33-L78
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/tools/scripttool.py
python
_get_playback_tractor
(length, range_frame_res_str=None, in_frame=-1, out_frame=-1)
return tractor
[]
def _get_playback_tractor(length, range_frame_res_str=None, in_frame=-1, out_frame=-1): # Create tractor and tracks tractor = mlt.Tractor() multitrack = tractor.multitrack() track0 = mlt.Playlist() multitrack.connect(track0, 0) bg_path = respaths.FLUXITY_EMPTY_BG_RES_PATH profile = mltprofiles.get_profile(_current_profile_name) if range_frame_res_str == None: # producer displaying 'not rendered' bg image bg_clip = mlt.Producer(profile, str(bg_path)) track0.insert(bg_clip, 0, 0, length - 1) else: # producer displaying frame sequence indx = 0 if in_frame > 0: bg_clip1 = mlt.Producer(profile, str(bg_path)) track0.insert(bg_clip1, indx, 0, in_frame - 1) indx += 1 range_producer = mlt.Producer(profile, range_frame_res_str) track0.insert(range_producer, indx, 0, out_frame - in_frame) indx += 1 if out_frame < length - 1: bg_clip2 = mlt.Producer(profile, str(bg_path)) track0.insert(bg_clip2, indx, out_frame + 1, length - 1) return tractor
[ "def", "_get_playback_tractor", "(", "length", ",", "range_frame_res_str", "=", "None", ",", "in_frame", "=", "-", "1", ",", "out_frame", "=", "-", "1", ")", ":", "# Create tractor and tracks", "tractor", "=", "mlt", ".", "Tractor", "(", ")", "multitrack", "...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/tools/scripttool.py#L267-L295
inpanel/inpanel
be53d86a72e30dd5476780ed5ba334315a23004b
lib/tornado/web.py
python
RequestHandler.require_setting
(self, name, feature="this feature")
Raises an exception if the given app setting is not defined.
Raises an exception if the given app setting is not defined.
[ "Raises", "an", "exception", "if", "the", "given", "app", "setting", "is", "not", "defined", "." ]
def require_setting(self, name, feature="this feature"): """Raises an exception if the given app setting is not defined.""" if not self.application.settings.get(name): raise Exception("You must define the '%s' setting in your " "application to use %s" % (name, feature))
[ "def", "require_setting", "(", "self", ",", "name", ",", "feature", "=", "\"this feature\"", ")", ":", "if", "not", "self", ".", "application", ".", "settings", ".", "get", "(", "name", ")", ":", "raise", "Exception", "(", "\"You must define the '%s' setting i...
https://github.com/inpanel/inpanel/blob/be53d86a72e30dd5476780ed5ba334315a23004b/lib/tornado/web.py#L973-L977
declare-lab/conv-emotion
0c9dcb9cc5234a7ca8cf6af81aabe28ef3814d0e
TL-ERC/bert_model/layer/encoder.py
python
BaseRNNEncoder.__init__
(self)
Base RNN Encoder Class
Base RNN Encoder Class
[ "Base", "RNN", "Encoder", "Class" ]
def __init__(self): """Base RNN Encoder Class""" super(BaseRNNEncoder, self).__init__()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "BaseRNNEncoder", ",", "self", ")", ".", "__init__", "(", ")" ]
https://github.com/declare-lab/conv-emotion/blob/0c9dcb9cc5234a7ca8cf6af81aabe28ef3814d0e/TL-ERC/bert_model/layer/encoder.py#L12-L14
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/urllib3/packages/six.py
python
ensure_text
(s, encoding="utf-8", errors="strict")
Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
Coerce *s* to six.text_type.
[ "Coerce", "*", "s", "*", "to", "six", ".", "text_type", "." ]
def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s))
[ "def", "ensure_text", "(", "s", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "\"strict\"", ")", ":", "if", "isinstance", "(", "s", ",", "binary_type", ")", ":", "return", "s", ".", "decode", "(", "encoding", ",", "errors", ")", "elif", "isins...
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/urllib3/packages/six.py#L1015-L1031
magicalraccoon/tootstream
6dd84fc3767ef25df645a599cb632ad3745744df
src/tootstream/toot.py
python
block
(mastodon, rest)
Blocks a user by username or id. ex: block 23 block @user block @user@instance.example.com
Blocks a user by username or id.
[ "Blocks", "a", "user", "by", "username", "or", "id", "." ]
def block(mastodon, rest): """Blocks a user by username or id. ex: block 23 block @user block @user@instance.example.com""" userid = get_userid(mastodon, rest) if isinstance(userid, list): cprint(" multiple matches found:", fg('red')) printUsersShort(userid) elif userid == -1: cprint(" username not found", fg('red')) else: try: relations = mastodon.account_block(userid) if relations['blocking']: cprint(" user " + str(userid) + " is now blocked", fg('blue')) except: cprint(" Error, unable to block.", fg('red'))
[ "def", "block", "(", "mastodon", ",", "rest", ")", ":", "userid", "=", "get_userid", "(", "mastodon", ",", "rest", ")", "if", "isinstance", "(", "userid", ",", "list", ")", ":", "cprint", "(", "\" multiple matches found:\"", ",", "fg", "(", "'red'", ")"...
https://github.com/magicalraccoon/tootstream/blob/6dd84fc3767ef25df645a599cb632ad3745744df/src/tootstream/toot.py#L1598-L1616
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/rex.py
python
RexExecutor.append_system_paths
(self)
Append system paths to $PATH.
Append system paths to $PATH.
[ "Append", "system", "paths", "to", "$PATH", "." ]
def append_system_paths(self): """Append system paths to $PATH.""" from rez.shells import Shell, create_shell sh = self.interpreter if isinstance(self.interpreter, Shell) \ else create_shell() paths = sh.get_syspaths() paths_str = os.pathsep.join(paths) self.env.PATH.append(paths_str)
[ "def", "append_system_paths", "(", "self", ")", ":", "from", "rez", ".", "shells", "import", "Shell", ",", "create_shell", "sh", "=", "self", ".", "interpreter", "if", "isinstance", "(", "self", ".", "interpreter", ",", "Shell", ")", "else", "create_shell", ...
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/rex.py#L1295-L1303
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/console/Console.py
python
ConsoleWidget.write
(self, strn, html=False, scrollToBottom='auto')
Write a string into the console. If scrollToBottom is 'auto', then the console is automatically scrolled to fit the new text only if it was already at the bottom.
Write a string into the console.
[ "Write", "a", "string", "into", "the", "console", "." ]
def write(self, strn, html=False, scrollToBottom='auto'): """Write a string into the console. If scrollToBottom is 'auto', then the console is automatically scrolled to fit the new text only if it was already at the bottom. """ isGuiThread = QtCore.QThread.currentThread() == QtCore.QCoreApplication.instance().thread() if not isGuiThread: self.stdout.write(strn) return sb = self.output.verticalScrollBar() scroll = sb.value() if scrollToBottom == 'auto': atBottom = scroll == sb.maximum() scrollToBottom = atBottom self.output.moveCursor(QtGui.QTextCursor.End) if html: self.output.textCursor().insertHtml(strn) else: if self.inCmd: self.inCmd = False self.output.textCursor().insertHtml("</div><br><div style='font-weight: normal; background-color: #FFF; color: black'>") self.output.insertPlainText(strn) if scrollToBottom: sb.setValue(sb.maximum()) else: sb.setValue(scroll)
[ "def", "write", "(", "self", ",", "strn", ",", "html", "=", "False", ",", "scrollToBottom", "=", "'auto'", ")", ":", "isGuiThread", "=", "QtCore", ".", "QThread", ".", "currentThread", "(", ")", "==", "QtCore", ".", "QCoreApplication", ".", "instance", "...
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0/pyqtgraph/console/Console.py#L209-L238
initstring/cloud_enum
ca59fa9fba30146736ee7ed5cc8bee195c010cd2
enum_tools/aws_checks.py
python
run_all
(names, args)
Function is called by main program
Function is called by main program
[ "Function", "is", "called", "by", "main", "program" ]
def run_all(names, args): """ Function is called by main program """ print(BANNER) # Use user-supplied AWS region if provided #if not regions: # regions = AWS_REGIONS check_s3_buckets(names, args.threads) check_awsapps(names, args.threads, args.nameserver)
[ "def", "run_all", "(", "names", ",", "args", ")", ":", "print", "(", "BANNER", ")", "# Use user-supplied AWS region if provided", "#if not regions:", "# regions = AWS_REGIONS", "check_s3_buckets", "(", "names", ",", "args", ".", "threads", ")", "check_awsapps", "("...
https://github.com/initstring/cloud_enum/blob/ca59fa9fba30146736ee7ed5cc8bee195c010cd2/enum_tools/aws_checks.py#L121-L131
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/dimse_primitives.py
python
N_DELETE.RequestedSOPClassUID
(self)
return self._RequestedSOPClassUID
Return the *Requested SOP Class UID* as :class:`~pydicom.uid.UID`. Parameters ---------- pydicom.uid.UID, bytes or str The value to use for the *Requested SOP Class UID* parameter.
Return the *Requested SOP Class UID* as :class:`~pydicom.uid.UID`.
[ "Return", "the", "*", "Requested", "SOP", "Class", "UID", "*", "as", ":", "class", ":", "~pydicom", ".", "uid", ".", "UID", "." ]
def RequestedSOPClassUID(self) -> Optional[UID]: """Return the *Requested SOP Class UID* as :class:`~pydicom.uid.UID`. Parameters ---------- pydicom.uid.UID, bytes or str The value to use for the *Requested SOP Class UID* parameter. """ return self._RequestedSOPClassUID
[ "def", "RequestedSOPClassUID", "(", "self", ")", "->", "Optional", "[", "UID", "]", ":", "return", "self", ".", "_RequestedSOPClassUID" ]
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/dimse_primitives.py#L2103-L2111
miha-skalic/youtube8mchallenge
65f20e9760ecb582e746e2a16cef6898a0ab6270
model_utils.py
python
SampleRandomFrames
(model_input, num_frames, num_samples)
Samples a random set of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tensor of size batch_size x num_samples x feature_size
Samples a random set of frames of size num_samples.
[ "Samples", "a", "random", "set", "of", "frames", "of", "size", "num_samples", "." ]
def SampleRandomFrames(model_input, num_frames, num_samples): """Samples a random set of frames of size num_samples. Args: model_input: A tensor of size batch_size x max_frames x feature_size num_frames: A tensor of size batch_size x 1 num_samples: A scalar Returns: `model_input`: A tensor of size batch_size x num_samples x feature_size """ batch_size = tf.shape(model_input)[0] frame_index = tf.cast( tf.multiply( tf.random_uniform([batch_size, num_samples]), tf.tile(tf.cast(num_frames, tf.float32), [1, num_samples])), tf.int32) batch_index = tf.tile( tf.expand_dims(tf.range(batch_size), 1), [1, num_samples]) index = tf.stack([batch_index, frame_index], 2) if FLAGS.sample_all: sampled_frames = tf.gather_nd(model_input, index) return represent_all(model_input, sampled_frames, num_frames) else: return tf.gather_nd(model_input, index)
[ "def", "SampleRandomFrames", "(", "model_input", ",", "num_frames", ",", "num_samples", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "model_input", ")", "[", "0", "]", "frame_index", "=", "tf", ".", "cast", "(", "tf", ".", "multiply", "(", "tf",...
https://github.com/miha-skalic/youtube8mchallenge/blob/65f20e9760ecb582e746e2a16cef6898a0ab6270/model_utils.py#L72-L95
alanhamlett/pip-update-requirements
ce875601ef278c8ce00ad586434a978731525561
pur/packages/pip/_vendor/html5lib/treeadapters/genshi.py
python
to_genshi
(walker)
Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes
Convert a tree to a genshi tree
[ "Convert", "a", "tree", "to", "a", "genshi", "tree" ]
def to_genshi(walker): """Convert a tree to a genshi tree :arg walker: the treewalker to use to walk the tree to convert it :returns: generator of genshi nodes """ text = [] for token in walker: type = token["type"] if type in ("Characters", "SpaceCharacters"): text.append(token["data"]) elif text: yield TEXT, "".join(text), (None, -1, -1) text = [] if type in ("StartTag", "EmptyTag"): if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) for attr, value in token["data"].items()]) yield (START, (QName(name), attrs), (None, -1, -1)) if type == "EmptyTag": type = "EndTag" if type == "EndTag": if token["namespace"]: name = "{%s}%s" % (token["namespace"], token["name"]) else: name = token["name"] yield END, QName(name), (None, -1, -1) elif type == "Comment": yield COMMENT, token["data"], (None, -1, -1) elif type == "Doctype": yield DOCTYPE, (token["name"], token["publicId"], token["systemId"]), (None, -1, -1) else: pass # FIXME: What to do? if text: yield TEXT, "".join(text), (None, -1, -1)
[ "def", "to_genshi", "(", "walker", ")", ":", "text", "=", "[", "]", "for", "token", "in", "walker", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"Characters\"", ",", "\"SpaceCharacters\"", ")", ":", "text", ".", "append",...
https://github.com/alanhamlett/pip-update-requirements/blob/ce875601ef278c8ce00ad586434a978731525561/pur/packages/pip/_vendor/html5lib/treeadapters/genshi.py#L7-L54
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/difflib.py
python
Differ._qformat
(self, aline, bline, atags, btags)
r""" Format "?" output and deal with tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n', ... ' ^ ^ ^ ', ' ^ ^ ^ ') >>> for line in results: print(repr(line)) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \tabcdefGhijkl\n' '? \t ^ ^ ^\n'
r""" Format "?" output and deal with tabs.
[ "r", "Format", "?", "output", "and", "deal", "with", "tabs", "." ]
def _qformat(self, aline, bline, atags, btags): r""" Format "?" output and deal with tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n', ... ' ^ ^ ^ ', ' ^ ^ ^ ') >>> for line in results: print(repr(line)) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \tabcdefGhijkl\n' '? \t ^ ^ ^\n' """ atags = _keep_original_ws(aline, atags).rstrip() btags = _keep_original_ws(bline, btags).rstrip() yield "- " + aline if atags: yield f"? {atags}\n" yield "+ " + bline if btags: yield f"? {btags}\n"
[ "def", "_qformat", "(", "self", ",", "aline", ",", "bline", ",", "atags", ",", "btags", ")", ":", "atags", "=", "_keep_original_ws", "(", "aline", ",", "atags", ")", ".", "rstrip", "(", ")", "btags", "=", "_keep_original_ws", "(", "bline", ",", "btags"...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/difflib.py#L1029-L1054
jeffgortmaker/pyblp
33ad24d8a800b8178aafa47304a822077a607558
pyblp/results/problem_results.py
python
ProblemResults._compute_importance_weights
( self, agents: RecArray, delta: Array, draws: int, ar_constant: float, seed: Optional[int])
return weights, errors
Compute the importance sampling weights associated with a set of agents.
Compute the importance sampling weights associated with a set of agents.
[ "Compute", "the", "importance", "sampling", "weights", "associated", "with", "a", "set", "of", "agents", "." ]
def _compute_importance_weights( self, agents: RecArray, delta: Array, draws: int, ar_constant: float, seed: Optional[int]) -> ( Tuple[Array, List[Error]]): """Compute the importance sampling weights associated with a set of agents.""" errors: List[Error] = [] market_indices = get_indices(agents.market_ids) def market_factory(s: Hashable) -> Tuple[ResultsMarket]: """Build a market use to compute probabilities.""" market_s = ResultsMarket( self.problem, s, self._parameters, self.sigma, self.pi, self.rho, delta=delta, agents_override=agents[market_indices[s]] ) return market_s, # compute weights market-by-market state = np.random.RandomState(seed) weights = np.zeros_like(agents.weights) generator = generate_items( self.problem.unique_market_ids, market_factory, ResultsMarket.safely_compute_probabilities ) for t, (probabilities_t, errors_t) in generator: errors.extend(errors_t) with np.errstate(all='ignore'): inside_share_t = self.problem.products.shares[self.problem._product_market_indices[t]].sum() inside_probabilities = probabilities_t.sum(axis=0) probability_cutoffs_t = state.uniform(size=inside_probabilities.size) accept_indices_t = np.where(probability_cutoffs_t < inside_probabilities / ar_constant)[0] try: sampled_indices_t = state.choice(accept_indices_t, size=draws, replace=False) except ValueError: raise RuntimeError( f"The number of accepted draws in market '{t}' was {accept_indices_t.size}, which is less then " f"{draws}. Either decrease the number of desired draws in each market or increase the size of " f"sampling_agent_data and/or sampling_integration." ) weights_t = np.zeros_like(inside_probabilities) weights_t[sampled_indices_t] = inside_share_t / inside_probabilities[sampled_indices_t] / draws weights[market_indices[t]] = weights_t[:, None] return weights, errors
[ "def", "_compute_importance_weights", "(", "self", ",", "agents", ":", "RecArray", ",", "delta", ":", "Array", ",", "draws", ":", "int", ",", "ar_constant", ":", "float", ",", "seed", ":", "Optional", "[", "int", "]", ")", "->", "(", "Tuple", "[", "Arr...
https://github.com/jeffgortmaker/pyblp/blob/33ad24d8a800b8178aafa47304a822077a607558/pyblp/results/problem_results.py#L1475-L1515
SUSE/DeepSea
9c7fad93915ba1250c40d50c855011e9fe41ed21
srv/salt/_modules/keyring.py
python
secret
(filename)
return gen_secret()
Read the filename and return the key value. If it does not exist, generate one. Note that if used on a file that contains multiple keys, this will always return the first key.
Read the filename and return the key value. If it does not exist, generate one.
[ "Read", "the", "filename", "and", "return", "the", "key", "value", ".", "If", "it", "does", "not", "exist", "generate", "one", "." ]
def secret(filename): """ Read the filename and return the key value. If it does not exist, generate one. Note that if used on a file that contains multiple keys, this will always return the first key. """ if os.path.exists(filename): with open(filename, 'r') as keyring: for line in keyring: if 'key' in line and ' = ' in line: key = line.split(' = ')[1].strip() return key return gen_secret()
[ "def", "secret", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "keyring", ":", "for", "line", "in", "keyring", ":", "if", "'key'", "in", "line",...
https://github.com/SUSE/DeepSea/blob/9c7fad93915ba1250c40d50c855011e9fe41ed21/srv/salt/_modules/keyring.py#L15-L30
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/websocket/_core.py
python
WebSocket.__iter__
(self)
Allow iteration over websocket, implying sequential `recv` executions.
Allow iteration over websocket, implying sequential `recv` executions.
[ "Allow", "iteration", "over", "websocket", "implying", "sequential", "recv", "executions", "." ]
def __iter__(self): """ Allow iteration over websocket, implying sequential `recv` executions. """ while True: yield self.recv()
[ "def", "__iter__", "(", "self", ")", ":", "while", "True", ":", "yield", "self", ".", "recv", "(", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/websocket/_core.py#L102-L107
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/analysis/psa.py
python
PSAnalysis.save_paths
(self, filename=None)
return filename
Save fitted :attr:`PSAnalysis.paths` to numpy compressed npz files. The data are saved with :func:`numpy.savez_compressed` in the directory specified by :attr:`PSAnalysis.targetdir`. Parameters ---------- filename : str specifies filename [``None``] Returns ------- filename : str See Also -------- load
Save fitted :attr:`PSAnalysis.paths` to numpy compressed npz files.
[ "Save", "fitted", ":", "attr", ":", "PSAnalysis", ".", "paths", "to", "numpy", "compressed", "npz", "files", "." ]
def save_paths(self, filename=None): """Save fitted :attr:`PSAnalysis.paths` to numpy compressed npz files. The data are saved with :func:`numpy.savez_compressed` in the directory specified by :attr:`PSAnalysis.targetdir`. Parameters ---------- filename : str specifies filename [``None``] Returns ------- filename : str See Also -------- load """ filename = filename or 'path_psa' head = os.path.join(self.targetdir, self.datadirs['paths']) outfile = os.path.join(head, filename) if self.paths is None: raise NoDataError("Paths have not been calculated yet") path_names = [] for i, path in enumerate(self.paths): current_outfile = "{0}{1:03n}.npy".format(outfile, i+1) np.save(current_outfile, self.paths[i]) path_names.append(current_outfile) logger.info("Wrote path to file %r", current_outfile) self.path_names = path_names with open(self._paths_pkl, 'wb') as output: pickle.dump(self.path_names, output) return filename
[ "def", "save_paths", "(", "self", ",", "filename", "=", "None", ")", ":", "filename", "=", "filename", "or", "'path_psa'", "head", "=", "os", ".", "path", ".", "join", "(", "self", ".", "targetdir", ",", "self", ".", "datadirs", "[", "'paths'", "]", ...
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/analysis/psa.py#L1579-L1613
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/marian/convert_marian_to_pytorch.py
python
lmap
(f, x)
return list(map(f, x))
[]
def lmap(f, x) -> List: return list(map(f, x))
[ "def", "lmap", "(", "f", ",", "x", ")", "->", "List", ":", "return", "list", "(", "map", "(", "f", ",", "x", ")", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/marian/convert_marian_to_pytorch.py#L314-L315
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/pint/context.py
python
ContextChain.graph
(self)
return self._graph
The graph relating
The graph relating
[ "The", "graph", "relating" ]
def graph(self): """The graph relating """ if self._graph is None: self._graph = defaultdict(set) for fr_, to_ in self: self._graph[fr_].add(to_) return self._graph
[ "def", "graph", "(", "self", ")", ":", "if", "self", ".", "_graph", "is", "None", ":", "self", ".", "_graph", "=", "defaultdict", "(", "set", ")", "for", "fr_", ",", "to_", "in", "self", ":", "self", ".", "_graph", "[", "fr_", "]", ".", "add", ...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/pint/context.py#L231-L238
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
chainer_/chainercv2/models/xdensenet_cifar.py
python
xdensenet40_2_k24_bc_svhn
(classes=10, **kwargs)
return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True, model_name="xdensenet40_2_k24_bc_svhn", **kwargs)
X-DenseNet-BC-40-2 (k=24) model for SVHN from 'Deep Expander Networks: Efficient Deep Networks from Graph Theory,' https://arxiv.org/abs/1711.08757. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters.
X-DenseNet-BC-40-2 (k=24) model for SVHN from 'Deep Expander Networks: Efficient Deep Networks from Graph Theory,' https://arxiv.org/abs/1711.08757.
[ "X", "-", "DenseNet", "-", "BC", "-", "40", "-", "2", "(", "k", "=", "24", ")", "model", "for", "SVHN", "from", "Deep", "Expander", "Networks", ":", "Efficient", "Deep", "Networks", "from", "Graph", "Theory", "https", ":", "//", "arxiv", ".", "org", ...
def xdensenet40_2_k24_bc_svhn(classes=10, **kwargs): """ X-DenseNet-BC-40-2 (k=24) model for SVHN from 'Deep Expander Networks: Efficient Deep Networks from Graph Theory,' https://arxiv.org/abs/1711.08757. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_xdensenet_cifar(classes=classes, blocks=40, growth_rate=24, bottleneck=True, model_name="xdensenet40_2_k24_bc_svhn", **kwargs)
[ "def", "xdensenet40_2_k24_bc_svhn", "(", "classes", "=", "10", ",", "*", "*", "kwargs", ")", ":", "return", "get_xdensenet_cifar", "(", "classes", "=", "classes", ",", "blocks", "=", "40", ",", "growth_rate", "=", "24", ",", "bottleneck", "=", "True", ",",...
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/xdensenet_cifar.py#L255-L270
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/adapters/cache.py
python
_CachedRelation.__deepcopy__
(self, memo)
[]
def __deepcopy__(self, memo): new = self.__class__(self.inner.incorporate()) new.__dict__.update(self.__dict__) new.referenced_by = deepcopy(self.referenced_by, memo)
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "new", "=", "self", ".", "__class__", "(", "self", ".", "inner", ".", "incorporate", "(", ")", ")", "new", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "new", ".", "re...
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/adapters/cache.py#L69-L72
mcneel/rhinoscriptsyntax
c49bd0bf24c2513bdcb84d1bf307144489600fd9
Scripts/rhinoscript/application.py
python
Ortho
(enable=None)
return rc
Enables or disables Rhino's ortho modeling aid. Parameters: enable (bool, optional): The new enabled status (True or False). If omitted the current state is returned. Returns: bool: if enable is not specified, then the current ortho status bool: if enable is specified, then the previous ortho status Example: import rhinoscriptsyntax as rs if not rs.Ortho(): rs.Ortho(True) See Also: Osnap Planar Snap
Enables or disables Rhino's ortho modeling aid. Parameters: enable (bool, optional): The new enabled status (True or False). If omitted the current state is returned. Returns: bool: if enable is not specified, then the current ortho status bool: if enable is specified, then the previous ortho status Example: import rhinoscriptsyntax as rs if not rs.Ortho(): rs.Ortho(True) See Also: Osnap Planar Snap
[ "Enables", "or", "disables", "Rhino", "s", "ortho", "modeling", "aid", ".", "Parameters", ":", "enable", "(", "bool", "optional", ")", ":", "The", "new", "enabled", "status", "(", "True", "or", "False", ")", ".", "If", "omitted", "the", "current", "state...
def Ortho(enable=None): """Enables or disables Rhino's ortho modeling aid. Parameters: enable (bool, optional): The new enabled status (True or False). If omitted the current state is returned. Returns: bool: if enable is not specified, then the current ortho status bool: if enable is specified, then the previous ortho status Example: import rhinoscriptsyntax as rs if not rs.Ortho(): rs.Ortho(True) See Also: Osnap Planar Snap """ rc = modelaid.Ortho if enable!=None: modelaid.Ortho = enable return rc
[ "def", "Ortho", "(", "enable", "=", "None", ")", ":", "rc", "=", "modelaid", ".", "Ortho", "if", "enable", "!=", "None", ":", "modelaid", ".", "Ortho", "=", "enable", "return", "rc" ]
https://github.com/mcneel/rhinoscriptsyntax/blob/c49bd0bf24c2513bdcb84d1bf307144489600fd9/Scripts/rhinoscript/application.py#L833-L850
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/splom/_diagonal.py
python
Diagonal.visible
(self)
return self["visible"]
Determines whether or not subplots on the diagonal are displayed. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool
Determines whether or not subplots on the diagonal are displayed. The 'visible' property must be specified as a bool (either True, or False)
[ "Determines", "whether", "or", "not", "subplots", "on", "the", "diagonal", "are", "displayed", ".", "The", "visible", "property", "must", "be", "specified", "as", "a", "bool", "(", "either", "True", "or", "False", ")" ]
def visible(self): """ Determines whether or not subplots on the diagonal are displayed. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"]
[ "def", "visible", "(", "self", ")", ":", "return", "self", "[", "\"visible\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/splom/_diagonal.py#L16-L28
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarInfo.fromtarfile
(cls, tarfile)
return obj._proc_member(tarfile)
Return the next TarInfo object from TarFile object tarfile.
Return the next TarInfo object from TarFile object tarfile.
[ "Return", "the", "next", "TarInfo", "object", "from", "TarFile", "object", "tarfile", "." ]
def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf, tarfile.encoding, tarfile.errors) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE return obj._proc_member(tarfile)
[ "def", "fromtarfile", "(", "cls", ",", "tarfile", ")", ":", "buf", "=", "tarfile", ".", "fileobj", ".", "read", "(", "BLOCKSIZE", ")", "obj", "=", "cls", ".", "frombuf", "(", "buf", ",", "tarfile", ".", "encoding", ",", "tarfile", ".", "errors", ")",...
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/distlib/_backport/tarfile.py#L1283-L1290
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/scripts/depfixer.py
python
Elf.fix_deps
(self, prefix: bytes)
[]
def fix_deps(self, prefix: bytes) -> None: sec = self.find_section(b'.dynstr') deps = [] for i in self.dynamic: if i.d_tag == DT_NEEDED: deps.append(i) for i in deps: offset = sec.sh_offset + i.val self.bf.seek(offset) name = self.read_str() if name.startswith(prefix): basename = name.split(b'/')[-1] padding = b'\0' * (len(name) - len(basename)) newname = basename + padding assert len(newname) == len(name) self.bf.seek(offset) self.bf.write(newname)
[ "def", "fix_deps", "(", "self", ",", "prefix", ":", "bytes", ")", "->", "None", ":", "sec", "=", "self", ".", "find_section", "(", "b'.dynstr'", ")", "deps", "=", "[", "]", "for", "i", "in", "self", ".", "dynamic", ":", "if", "i", ".", "d_tag", "...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/scripts/depfixer.py#L298-L314
LGE-ARC-AdvancedAI/auptimizer
50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617
docs/archive/aup.py
python
BasicConfig.load
(self, filename)
return self
Load config parameters from JSON/pickle file :param filename: file name ends with [.json|.pkl] :type filename: string :return: configuration parsed from file :rtype: aup.BasicConfig
Load config parameters from JSON/pickle file
[ "Load", "config", "parameters", "from", "JSON", "/", "pickle", "file" ]
def load(self, filename): """Load config parameters from JSON/pickle file :param filename: file name ends with [.json|.pkl] :type filename: string :return: configuration parsed from file :rtype: aup.BasicConfig """ name = "_load_" + BasicConfig._get_format(filename) func = getattr(self, name) data = func(filename) if type(data) is not dict: raise TypeError("Config must be dict") self.update(data) logger.debug("Load config from %s: %s" % (filename, data.__str__())) return self
[ "def", "load", "(", "self", ",", "filename", ")", ":", "name", "=", "\"_load_\"", "+", "BasicConfig", ".", "_get_format", "(", "filename", ")", "func", "=", "getattr", "(", "self", ",", "name", ")", "data", "=", "func", "(", "filename", ")", "if", "t...
https://github.com/LGE-ARC-AdvancedAI/auptimizer/blob/50f6e3b4e0cb9146ca90fd74b9b24ca97ae22617/docs/archive/aup.py#L63-L78
onnx/onnx-coreml
141fc33d7217674ea8bda36494fa8089a543a3f3
onnx_coreml/_operators.py
python
_convert_sub
(builder, node, graph, err)
[]
def _convert_sub(builder, node, graph, err): # type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None _convert_broadcast_op(builder, node, graph, err, "ADD")
[ "def", "_convert_sub", "(", "builder", ",", "node", ",", "graph", ",", "err", ")", ":", "# type: (NeuralNetworkBuilder, Node, Graph, ErrorHandling) -> None", "_convert_broadcast_op", "(", "builder", ",", "node", ",", "graph", ",", "err", ",", "\"ADD\"", ")" ]
https://github.com/onnx/onnx-coreml/blob/141fc33d7217674ea8bda36494fa8089a543a3f3/onnx_coreml/_operators.py#L278-L279
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/solvers/functional/default_functionals.py
python
IndicatorGroupL1UnitBall.__init__
(self, vfspace, exponent=None)
Initialize a new instance. Parameters ---------- vfspace : `ProductSpace` Space of vector fields on which the operator acts. It has to be a product space of identical spaces, i.e. a power space. exponent : non-zero float, optional Exponent of the norm in each point. Values between 0 and 1 are currently not supported due to numerical instability. Infinity gives the supremum norm. Default: ``vfspace.exponent``, usually 2. Examples -------- >>> space = odl.rn(2) >>> pspace = odl.ProductSpace(space, 2) >>> op = IndicatorGroupL1UnitBall(pspace) >>> op([[0.1, 0.5], [0.2, 0.3]]) 0 >>> op([[3, 3], [4, 4]]) inf Set exponent of inner (p) norm: >>> op2 = IndicatorGroupL1UnitBall(pspace, exponent=1)
Initialize a new instance.
[ "Initialize", "a", "new", "instance", "." ]
def __init__(self, vfspace, exponent=None): """Initialize a new instance. Parameters ---------- vfspace : `ProductSpace` Space of vector fields on which the operator acts. It has to be a product space of identical spaces, i.e. a power space. exponent : non-zero float, optional Exponent of the norm in each point. Values between 0 and 1 are currently not supported due to numerical instability. Infinity gives the supremum norm. Default: ``vfspace.exponent``, usually 2. Examples -------- >>> space = odl.rn(2) >>> pspace = odl.ProductSpace(space, 2) >>> op = IndicatorGroupL1UnitBall(pspace) >>> op([[0.1, 0.5], [0.2, 0.3]]) 0 >>> op([[3, 3], [4, 4]]) inf Set exponent of inner (p) norm: >>> op2 = IndicatorGroupL1UnitBall(pspace, exponent=1) """ if not isinstance(vfspace, ProductSpace): raise TypeError('`space` must be a `ProductSpace`') if not vfspace.is_power_space: raise TypeError('`space.is_power_space` must be `True`') super(IndicatorGroupL1UnitBall, self).__init__( space=vfspace, linear=False, grad_lipschitz=np.nan) self.pointwise_norm = PointwiseNorm(vfspace, exponent)
[ "def", "__init__", "(", "self", ",", "vfspace", ",", "exponent", "=", "None", ")", ":", "if", "not", "isinstance", "(", "vfspace", ",", "ProductSpace", ")", ":", "raise", "TypeError", "(", "'`space` must be a `ProductSpace`'", ")", "if", "not", "vfspace", "....
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/solvers/functional/default_functionals.py#L347-L383
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/functions/hyperbolic.py
python
Function_arccsch._eval_numpy_
(self, x)
return arcsinh(1.0 / x)
EXAMPLES:: sage: import numpy sage: a = numpy.linspace(0,1,3) sage: acsch(a) doctest:...: RuntimeWarning: divide by zero encountered in ...divide array([ inf, 1.44363548, 0.88137359])
EXAMPLES::
[ "EXAMPLES", "::" ]
def _eval_numpy_(self, x): """ EXAMPLES:: sage: import numpy sage: a = numpy.linspace(0,1,3) sage: acsch(a) doctest:...: RuntimeWarning: divide by zero encountered in ...divide array([ inf, 1.44363548, 0.88137359]) """ return arcsinh(1.0 / x)
[ "def", "_eval_numpy_", "(", "self", ",", "x", ")", ":", "return", "arcsinh", "(", "1.0", "/", "x", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/functions/hyperbolic.py#L706-L716
nipy/nipy
d16d268938dcd5c15748ca051532c21f57cf8a22
nipy/algorithms/slicetiming/timefuncs.py
python
st_42031
(n_slices, TR)
return st_02413(n_slices, TR)[::-1]
Descend alternate every second slice, starting at last slice Collect slice (`n_slices` - 1) first, slice (`nslices` - 3) second down to bottom (lowest numbered slice). Then return to collect slice (`n_slices` -2), slice (`n_slices` - 4) etc. For example, for 5 slices and a TR of 1: >>> {name}(5, 1.) array([ 0.4, 0.8, 0.2, 0.6, 0. ]) {pstr}
Descend alternate every second slice, starting at last slice
[ "Descend", "alternate", "every", "second", "slice", "starting", "at", "last", "slice" ]
def st_42031(n_slices, TR): """Descend alternate every second slice, starting at last slice Collect slice (`n_slices` - 1) first, slice (`nslices` - 3) second down to bottom (lowest numbered slice). Then return to collect slice (`n_slices` -2), slice (`n_slices` - 4) etc. For example, for 5 slices and a TR of 1: >>> {name}(5, 1.) array([ 0.4, 0.8, 0.2, 0.6, 0. ]) {pstr} """ return st_02413(n_slices, TR)[::-1]
[ "def", "st_42031", "(", "n_slices", ",", "TR", ")", ":", "return", "st_02413", "(", "n_slices", ",", "TR", ")", "[", ":", ":", "-", "1", "]" ]
https://github.com/nipy/nipy/blob/d16d268938dcd5c15748ca051532c21f57cf8a22/nipy/algorithms/slicetiming/timefuncs.py#L174-L188
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/storage/memory_mixins/paged_memory/pages/ultra_page.py
python
UltraPage.store
(self, addr, data: Union[int,SimMemoryObject], size: int=None, endness=None, memory=None, page_addr=None, # pylint: disable=arguments-differ cooperate=False, **kwargs)
[]
def store(self, addr, data: Union[int,SimMemoryObject], size: int=None, endness=None, memory=None, page_addr=None, # pylint: disable=arguments-differ cooperate=False, **kwargs): super().store(addr, data, size=size, endness=endness, memory=memory, cooperate=cooperate, page_addr=page_addr, **kwargs) if not cooperate: data = self._force_store_cooperation(addr, data, size, endness, page_addr=page_addr, memory=memory, **kwargs) if size >= memory.page_size - addr: size = memory.page_size - addr if type(data) is not int: if data.object.op == 'BVV' and not data.object.annotations: # trim the unnecessary leading bytes if there are any full_bits = len(data.object) start = (page_addr + addr - data.base) & ((1 << memory.state.arch.bits) - 1) if start >= data.base + data.length: raise SimMemoryError("Not enough bytes to store.") start_bits = full_bits - start * memory.state.arch.byte_width - 1 # trim the overflowing bytes if there are any end_bits = start_bits + 1 - size * memory.state.arch.byte_width if start_bits != full_bits - 1 or end_bits != 0: if endness == 'Iend_LE': start_bits, end_bits = len(data.object) - end_bits - 1, len(data.object) - start_bits - 1 obj = data.object[start_bits: end_bits] data = obj.args[0] if type(data) is int or (data.object.op == 'BVV' and not data.object.annotations): # mark range as not symbolic self.symbolic_bitmap[addr:addr+size] = b'\0'*size # store arange = range(addr, addr+size) if type(data) is int: ival = data else: # data.object.op == 'BVV' ival = data.object.args[0] if endness == 'Iend_BE': arange = reversed(arange) assert memory.state.arch.byte_width == 8 # TODO: Make UltraPage support architectures with greater byte_widths (but are still multiples of 8) for subaddr in arange: self.concrete_data[subaddr] = ival & 0xff ival >>= 8 else: # mark range as symbolic self.symbolic_bitmap[addr:addr+size] = b'\1'*size # set ending object try: endpiece = next(self.symbolic_data.irange(maximum=addr+size, reverse=True)) except StopIteration: pass else: if endpiece != addr + size: self.symbolic_data[addr + size] = self.symbolic_data[endpiece] # clear range for midpiece in self.symbolic_data.irange(maximum=addr+size-1, minimum=addr, reverse=True): del self.symbolic_data[midpiece] # set. self.symbolic_data[addr] = data
[ "def", "store", "(", "self", ",", "addr", ",", "data", ":", "Union", "[", "int", ",", "SimMemoryObject", "]", ",", "size", ":", "int", "=", "None", ",", "endness", "=", "None", ",", "memory", "=", "None", ",", "page_addr", "=", "None", ",", "# pyli...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/storage/memory_mixins/paged_memory/pages/ultra_page.py#L106-L170
zalando/expan
49a1ba3d9fdd786e08146f904a631f67484fd2d3
expan/core/statistics.py
python
pooled_std
(std1, n1, std2, n2)
return np.sqrt(((n1 - 1) * std1 ** 2 + (n2 - 1) * std2 ** 2) / (n1 + n2 - 2))
Returns the pooled estimate of standard deviation. For further information visit: http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/BS704_Confidence_Intervals/BS704_Confidence_Intervals5.html :param std1: standard deviation of first sample :type std1: float :param n1: size of first sample :type n1: int :param std2: standard deviation of second sample :type std2: float :param n2: size of second sample :type n2: int :return: pooled standard deviation :type: float
Returns the pooled estimate of standard deviation.
[ "Returns", "the", "pooled", "estimate", "of", "standard", "deviation", "." ]
def pooled_std(std1, n1, std2, n2): """ Returns the pooled estimate of standard deviation. For further information visit: http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/BS704_Confidence_Intervals/BS704_Confidence_Intervals5.html :param std1: standard deviation of first sample :type std1: float :param n1: size of first sample :type n1: int :param std2: standard deviation of second sample :type std2: float :param n2: size of second sample :type n2: int :return: pooled standard deviation :type: float """ if (std1 ** 2) > 2.0*(std2 ** 2) or \ (std1 ** 2) < 0.5*(std2 ** 2): warnings.warn('Sample variances differ too much to assume that population variances are equal.') logger.warning('Sample variances differ too much to assume that population variances are equal.') return np.sqrt(((n1 - 1) * std1 ** 2 + (n2 - 1) * std2 ** 2) / (n1 + n2 - 2))
[ "def", "pooled_std", "(", "std1", ",", "n1", ",", "std2", ",", "n2", ")", ":", "if", "(", "std1", "**", "2", ")", ">", "2.0", "*", "(", "std2", "**", "2", ")", "or", "(", "std1", "**", "2", ")", "<", "0.5", "*", "(", "std2", "**", "2", ")...
https://github.com/zalando/expan/blob/49a1ba3d9fdd786e08146f904a631f67484fd2d3/expan/core/statistics.py#L284-L308
nwcell/psycopg2-windows
5698844286001962f3eeeab58164301898ef48e9
psycopg2/_range.py
python
Range.upper_inf
(self)
return self._upper is None
`!True` if the range doesn't have an upper bound.
`!True` if the range doesn't have an upper bound.
[ "!True", "if", "the", "range", "doesn", "t", "have", "an", "upper", "bound", "." ]
def upper_inf(self): """`!True` if the range doesn't have an upper bound.""" if self._bounds is None: return False return self._upper is None
[ "def", "upper_inf", "(", "self", ")", ":", "if", "self", ".", "_bounds", "is", "None", ":", "return", "False", "return", "self", ".", "_upper", "is", "None" ]
https://github.com/nwcell/psycopg2-windows/blob/5698844286001962f3eeeab58164301898ef48e9/psycopg2/_range.py#L85-L88
man-group/mdf
4b2c78084467791ad883c0b4c53832ad70fc96ef
mdf/lab/__init__.py
python
DataFrameWithShiftSet.__init__
(self, df, shift_set_name, shift_set)
[]
def __init__(self, df, shift_set_name, shift_set): pd.DataFrame.__init__(self, df) self.__shift_set_name = shift_set_name self.__shift_set = dict(shift_set)
[ "def", "__init__", "(", "self", ",", "df", ",", "shift_set_name", ",", "shift_set", ")", ":", "pd", ".", "DataFrame", ".", "__init__", "(", "self", ",", "df", ")", "self", ".", "__shift_set_name", "=", "shift_set_name", "self", ".", "__shift_set", "=", "...
https://github.com/man-group/mdf/blob/4b2c78084467791ad883c0b4c53832ad70fc96ef/mdf/lab/__init__.py#L84-L87
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.makedir
(self, tarinfo, targetpath)
Make a directory called targetpath.
Make a directory called targetpath.
[ "Make", "a", "directory", "called", "targetpath", "." ]
def makedir(self, tarinfo, targetpath): """Make a directory called targetpath. """ try: # Use a safe mode for the directory, the real mode is set # later in _extract_member(). os.mkdir(targetpath, 0o700) except EnvironmentError as e: if e.errno != errno.EEXIST: raise
[ "def", "makedir", "(", "self", ",", "tarinfo", ",", "targetpath", ")", ":", "try", ":", "# Use a safe mode for the directory, the real mode is set", "# later in _extract_member().", "os", ".", "mkdir", "(", "targetpath", ",", "0o700", ")", "except", "EnvironmentError", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2285-L2294
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/fixtures/views.py
python
UploadFixtureAPIResponse.__init__
(self, status, message)
[]
def __init__(self, status, message): assert status in self.response_codes, \ 'status must be in {!r}: {}'.format(list(self.response_codes), status) self.status = status self.message = message
[ "def", "__init__", "(", "self", ",", "status", ",", "message", ")", ":", "assert", "status", "in", "self", ".", "response_codes", ",", "'status must be in {!r}: {}'", ".", "format", "(", "list", "(", "self", ".", "response_codes", ")", ",", "status", ")", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/fixtures/views.py#L396-L400
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/web.py
python
RequestHandler.write
(self, chunk)
Writes the given chunk to the output buffer. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call set_header *after* calling write()). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
Writes the given chunk to the output buffer.
[ "Writes", "the", "given", "chunk", "to", "the", "output", "buffer", "." ]
def write(self, chunk): """Writes the given chunk to the output buffer. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call set_header *after* calling write()). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx """ if self._finished: raise RuntimeError("Cannot write() after finish(). May be caused " "by using async operations without the " "@asynchronous decorator.") if isinstance(chunk, dict): chunk = escape.json_encode(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") chunk = utf8(chunk) self._write_buffer.append(chunk)
[ "def", "write", "(", "self", ",", "chunk", ")", ":", "if", "self", ".", "_finished", ":", "raise", "RuntimeError", "(", "\"Cannot write() after finish(). May be caused \"", "\"by using async operations without the \"", "\"@asynchronous decorator.\"", ")", "if", "isinstance...
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/web.py#L497-L520
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
cms/djangoapps/contentstore/views/item.py
python
xblock_view_handler
(request, usage_key_string, view_name)
The restful handler for requests for rendered xblock views. Returns a json object containing two keys: html: The rendered html of the view resources: A list of tuples where the first element is the resource hash, and the second is the resource description
The restful handler for requests for rendered xblock views.
[ "The", "restful", "handler", "for", "requests", "for", "rendered", "xblock", "views", "." ]
def xblock_view_handler(request, usage_key_string, view_name): """ The restful handler for requests for rendered xblock views. Returns a json object containing two keys: html: The rendered html of the view resources: A list of tuples where the first element is the resource hash, and the second is the resource description """ usage_key = usage_key_with_run(usage_key_string) if not has_studio_read_access(request.user, usage_key.course_key): raise PermissionDenied() accept_header = request.META.get('HTTP_ACCEPT', 'application/json') if 'application/json' in accept_header: store = modulestore() xblock = store.get_item(usage_key) container_views = ['container_preview', 'reorderable_container_child_preview', 'container_child_preview'] # wrap the generated fragment in the xmodule_editor div so that the javascript # can bind to it correctly xblock.runtime.wrappers.append(partial( wrap_xblock, 'StudioRuntime', usage_id_serializer=str, request_token=request_token(request), )) xblock.runtime.wrappers_asides.append(partial( wrap_xblock_aside, 'StudioRuntime', usage_id_serializer=str, request_token=request_token(request), extra_classes=['wrapper-comp-plugins'] )) if view_name in (STUDIO_VIEW, VISIBILITY_VIEW): if view_name == STUDIO_VIEW and xblock.xmodule_runtime is None: xblock.xmodule_runtime = StudioEditModuleRuntime(request.user) try: fragment = xblock.render(view_name) # catch exceptions indiscriminately, since after this point they escape the # dungeon and surface as uneditable, unsaveable, and undeletable # component-goblins. except Exception as exc: # pylint: disable=broad-except log.debug("Unable to render %s for %r", view_name, xblock, exc_info=True) fragment = Fragment(render_to_string('html_error.html', {'message': str(exc)})) elif view_name in PREVIEW_VIEWS + container_views: is_pages_view = view_name == STUDENT_VIEW # Only the "Pages" view uses student view in Studio can_edit = has_studio_write_access(request.user, usage_key.course_key) # Determine the items to be shown as reorderable. Note that the view # 'reorderable_container_child_preview' is only rendered for xblocks that # are being shown in a reorderable container, so the xblock is automatically # added to the list. reorderable_items = set() if view_name == 'reorderable_container_child_preview': reorderable_items.add(xblock.location) paging = None try: if request.GET.get('enable_paging', 'false') == 'true': paging = { 'page_number': int(request.GET.get('page_number', 0)), 'page_size': int(request.GET.get('page_size', 0)), } except ValueError: return HttpResponse( content="Couldn't parse paging parameters: enable_paging: " "{}, page_number: {}, page_size: {}".format( request.GET.get('enable_paging', 'false'), request.GET.get('page_number', 0), request.GET.get('page_size', 0) ), status=400, content_type="text/plain", ) force_render = request.GET.get('force_render', None) # Set up the context to be passed to each XBlock's render method. context = request.GET.dict() context.update({ # This setting disables the recursive wrapping of xblocks 'is_pages_view': is_pages_view or view_name == AUTHOR_VIEW, 'is_unit_page': is_unit(xblock), 'can_edit': can_edit, 'root_xblock': xblock if (view_name == 'container_preview') else None, 'reorderable_items': reorderable_items, 'paging': paging, 'force_render': force_render, 'item_url': '/container/{usage_key}', }) fragment = get_preview_fragment(request, xblock, context) # Note that the container view recursively adds headers into the preview fragment, # so only the "Pages" view requires that this extra wrapper be included. if is_pages_view: fragment.content = render_to_string('component.html', { 'xblock_context': context, 'xblock': xblock, 'locator': usage_key, 'preview': fragment.content, 'label': xblock.display_name or xblock.scope_ids.block_type, }) else: raise Http404 hashed_resources = OrderedDict() for resource in fragment.resources: hashed_resources[hash_resource(resource)] = resource._asdict() fragment_content = fragment.content if isinstance(fragment_content, bytes): fragment_content = fragment.content.decode('utf-8') return JsonResponse({ 'html': fragment_content, 'resources': list(hashed_resources.items()) }) else: return HttpResponse(status=406)
[ "def", "xblock_view_handler", "(", "request", ",", "usage_key_string", ",", "view_name", ")", ":", "usage_key", "=", "usage_key_with_run", "(", "usage_key_string", ")", "if", "not", "has_studio_read_access", "(", "request", ".", "user", ",", "usage_key", ".", "cou...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/cms/djangoapps/contentstore/views/item.py#L329-L454
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/vpc/vpc.py
python
VPC.detach_classic_instance
(self, instance_id, dry_run=False)
return self.connection.detach_classic_link_vpc( vpc_id=self.id, instance_id=instance_id, dry_run=dry_run )
Unlinks a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. :type intance_id: str :param instance_is: The ID of the VPC to which the instance is linked. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful
Unlinks a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped.
[ "Unlinks", "a", "linked", "EC2", "-", "Classic", "instance", "from", "a", "VPC", ".", "After", "the", "instance", "has", "been", "unlinked", "the", "VPC", "security", "groups", "are", "no", "longer", "associated", "with", "it", ".", "An", "instance", "is",...
def detach_classic_instance(self, instance_id, dry_run=False): """ Unlinks a linked EC2-Classic instance from a VPC. After the instance has been unlinked, the VPC security groups are no longer associated with it. An instance is automatically unlinked from a VPC when it's stopped. :type intance_id: str :param instance_is: The ID of the VPC to which the instance is linked. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: bool :return: True if successful """ return self.connection.detach_classic_link_vpc( vpc_id=self.id, instance_id=instance_id, dry_run=dry_run )
[ "def", "detach_classic_instance", "(", "self", ",", "instance_id", ",", "dry_run", "=", "False", ")", ":", "return", "self", ".", "connection", ".", "detach_classic_link_vpc", "(", "vpc_id", "=", "self", ".", "id", ",", "instance_id", "=", "instance_id", ",", ...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/vpc/vpc.py#L184-L204
openstack/python-neutronclient
517bef2c5454dde2eba5cc2194ee857be6be7164
neutronclient/v2_0/client.py
python
Client.get_lbaas_agent_hosting_pool
(self, pool, **_params)
return self.get((self.pool_path + self.LOADBALANCER_AGENT) % pool, params=_params)
Fetches a loadbalancer agent hosting a pool.
Fetches a loadbalancer agent hosting a pool.
[ "Fetches", "a", "loadbalancer", "agent", "hosting", "a", "pool", "." ]
def get_lbaas_agent_hosting_pool(self, pool, **_params): """Fetches a loadbalancer agent hosting a pool.""" return self.get((self.pool_path + self.LOADBALANCER_AGENT) % pool, params=_params)
[ "def", "get_lbaas_agent_hosting_pool", "(", "self", ",", "pool", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "(", "self", ".", "pool_path", "+", "self", ".", "LOADBALANCER_AGENT", ")", "%", "pool", ",", "params", "=", "_params"...
https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/v2_0/client.py#L1796-L1799
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/SQLAlchemy-1.3.17/examples/performance/large_resultsets.py
python
test_orm_full_objects_list
(n)
Load fully tracked ORM objects into one big list().
Load fully tracked ORM objects into one big list().
[ "Load", "fully", "tracked", "ORM", "objects", "into", "one", "big", "list", "()", "." ]
def test_orm_full_objects_list(n): """Load fully tracked ORM objects into one big list().""" sess = Session(engine) list(sess.query(Customer).limit(n))
[ "def", "test_orm_full_objects_list", "(", "n", ")", ":", "sess", "=", "Session", "(", "engine", ")", "list", "(", "sess", ".", "query", "(", "Customer", ")", ".", "limit", "(", "n", ")", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/examples/performance/large_resultsets.py#L63-L67
ConsenSys/mythril
d00152f8e4d925c7749d63b533152a937e1dd516
mythril/analysis/module/modules/arbitrary_write.py
python
ArbitraryStorage.reset_module
(self)
Resets the module by clearing everything :return:
Resets the module by clearing everything :return:
[ "Resets", "the", "module", "by", "clearing", "everything", ":", "return", ":" ]
def reset_module(self): """ Resets the module by clearing everything :return: """ super().reset_module()
[ "def", "reset_module", "(", "self", ")", ":", "super", "(", ")", ".", "reset_module", "(", ")" ]
https://github.com/ConsenSys/mythril/blob/d00152f8e4d925c7749d63b533152a937e1dd516/mythril/analysis/module/modules/arbitrary_write.py#L30-L35
Kozea/pygal
8267b03535ff55789a30bf66b798302adad88623
pygal/util.py
python
round_to_int
(number, precision)
return rounded
Round a number to a precision
Round a number to a precision
[ "Round", "a", "number", "to", "a", "precision" ]
def round_to_int(number, precision): """Round a number to a precision""" precision = int(precision) rounded = (int(number) + precision / 2) // precision * precision return rounded
[ "def", "round_to_int", "(", "number", ",", "precision", ")", ":", "precision", "=", "int", "(", "precision", ")", "rounded", "=", "(", "int", "(", "number", ")", "+", "precision", "/", "2", ")", "//", "precision", "*", "precision", "return", "rounded" ]
https://github.com/Kozea/pygal/blob/8267b03535ff55789a30bf66b798302adad88623/pygal/util.py#L61-L65
materialsproject/fireworks
83a907c19baf2a5c9fdcf63996f9797c3c85b785
fireworks/features/multi_launcher.py
python
rapidfire_process
( fworker, nlaunches, sleep, loglvl, port, node_list, sub_nproc, timeout, running_ids_dict, local_redirect )
Initializes shared data with multiprocessing parameters and starts a rapidfire. Args: fworker (FWorker): object nlaunches (int): 0 means 'until completion', -1 or "infinite" means to loop forever sleep (int): secs to sleep between rapidfire loop iterations loglvl (str): level at which to output logs to stdout port (int): Listening port number of the shared object manage password (str): security password to access the server node_list ([str]): computer node list sub_nproc (int): number of processors of the sub job timeout (int): # of seconds after which to stop the rapidfire process local_redirect (bool): redirect standard input and output to local file
Initializes shared data with multiprocessing parameters and starts a rapidfire.
[ "Initializes", "shared", "data", "with", "multiprocessing", "parameters", "and", "starts", "a", "rapidfire", "." ]
def rapidfire_process( fworker, nlaunches, sleep, loglvl, port, node_list, sub_nproc, timeout, running_ids_dict, local_redirect ): """ Initializes shared data with multiprocessing parameters and starts a rapidfire. Args: fworker (FWorker): object nlaunches (int): 0 means 'until completion', -1 or "infinite" means to loop forever sleep (int): secs to sleep between rapidfire loop iterations loglvl (str): level at which to output logs to stdout port (int): Listening port number of the shared object manage password (str): security password to access the server node_list ([str]): computer node list sub_nproc (int): number of processors of the sub job timeout (int): # of seconds after which to stop the rapidfire process local_redirect (bool): redirect standard input and output to local file """ ds = DataServer(address=("127.0.0.1", port), authkey=DS_PASSWORD) ds.connect() launchpad = ds.LaunchPad() FWData().DATASERVER = ds FWData().MULTIPROCESSING = True FWData().NODE_LIST = node_list FWData().SUB_NPROCS = sub_nproc FWData().Running_IDs = running_ids_dict sleep_time = sleep if sleep else RAPIDFIRE_SLEEP_SECS l_dir = launchpad.get_logdir() if launchpad else None l_logger = get_fw_logger("rocket.launcher", l_dir=l_dir, stream_level=loglvl) rapidfire( launchpad, fworker=fworker, m_dir=None, nlaunches=nlaunches, max_loops=-1, sleep_time=sleep, strm_lvl=loglvl, timeout=timeout, local_redirect=local_redirect, ) while nlaunches == 0: time.sleep(1.5) # wait for LaunchPad to be initialized launch_ids = FWData().Running_IDs.values() live_ids = list(set(launch_ids) - {None}) if len(live_ids) > 0: # Some other sub jobs are still running log_multi(l_logger, f"Sleeping for {sleep_time} secs before resubmit sub job") time.sleep(sleep_time) log_multi(l_logger, "Resubmit sub job") rapidfire( launchpad, fworker=fworker, m_dir=None, nlaunches=nlaunches, max_loops=-1, sleep_time=sleep, strm_lvl=loglvl, timeout=timeout, local_redirect=local_redirect, ) else: break log_multi(l_logger, "Sub job finished")
[ "def", "rapidfire_process", "(", "fworker", ",", "nlaunches", ",", "sleep", ",", "loglvl", ",", "port", ",", "node_list", ",", "sub_nproc", ",", "timeout", ",", "running_ids_dict", ",", "local_redirect", ")", ":", "ds", "=", "DataServer", "(", "address", "="...
https://github.com/materialsproject/fireworks/blob/83a907c19baf2a5c9fdcf63996f9797c3c85b785/fireworks/features/multi_launcher.py#L57-L119
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/AzureStorageFileShare/Integrations/AzureStorageFileShare/AzureStorageFileShare.py
python
Client.create_directory_request
(self, share_name: str, directory_name: str, directory_path: str = None)
return response
Create a new directory under the specified share or parent directory. Args: share_name (str): Share name. directory_name (str): New directory name. directory_path (str): The path to the directory. Returns: Response: API response from Azure.
Create a new directory under the specified share or parent directory. Args: share_name (str): Share name. directory_name (str): New directory name. directory_path (str): The path to the directory.
[ "Create", "a", "new", "directory", "under", "the", "specified", "share", "or", "parent", "directory", ".", "Args", ":", "share_name", "(", "str", ")", ":", "Share", "name", ".", "directory_name", "(", "str", ")", ":", "New", "directory", "name", ".", "di...
def create_directory_request(self, share_name: str, directory_name: str, directory_path: str = None) -> Response: """ Create a new directory under the specified share or parent directory. Args: share_name (str): Share name. directory_name (str): New directory name. directory_path (str): The path to the directory. Returns: Response: API response from Azure. """ params = assign_params(restype="directory") headers = {'x-ms-file-permission': 'inherit ', 'x-ms-file-attributes': 'None', 'x-ms-file-creation-time': 'now', 'x-ms-file-last-write-time': 'now'} url_suffix = f'{share_name}/{directory_path}/{directory_name}' if directory_path else f'{share_name}/{directory_name}' response = self.ms_client.http_request(method='PUT', url_suffix=url_suffix, params=params, headers=headers, return_empty_response=True) return response
[ "def", "create_directory_request", "(", "self", ",", "share_name", ":", "str", ",", "directory_name", ":", "str", ",", "directory_path", ":", "str", "=", "None", ")", "->", "Response", ":", "params", "=", "assign_params", "(", "restype", "=", "\"directory\"", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/AzureStorageFileShare/Integrations/AzureStorageFileShare/AzureStorageFileShare.py#L103-L127
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/bulkload/bulkloader_config.py
python
create_transformer_classes
(transformer_spec, config_globals, reserve_keys)
return importer_class, exporter_class
Create an importer and exporter class from a transformer spec. Args: transformer_spec: A bulkloader_parser.TransformerEntry. config_globals: Dict to use to reference globals for code in the config. reserve_keys: Method ReserveKeys(keys) which will advance the id sequence in the datastore beyond each key.id(). Can be None. Raises: InvalidConfig: when the config is invalid. Returns: Tuple, (importer class, exporter class), each which is in turn a wrapper for the GenericImporter/GenericExporter class using a DictConvertor object configured as per the transformer_spec.
Create an importer and exporter class from a transformer spec.
[ "Create", "an", "importer", "and", "exporter", "class", "from", "a", "transformer", "spec", "." ]
def create_transformer_classes(transformer_spec, config_globals, reserve_keys): """Create an importer and exporter class from a transformer spec. Args: transformer_spec: A bulkloader_parser.TransformerEntry. config_globals: Dict to use to reference globals for code in the config. reserve_keys: Method ReserveKeys(keys) which will advance the id sequence in the datastore beyond each key.id(). Can be None. Raises: InvalidConfig: when the config is invalid. Returns: Tuple, (importer class, exporter class), each which is in turn a wrapper for the GenericImporter/GenericExporter class using a DictConvertor object configured as per the transformer_spec. """ if transformer_spec.connector in CONNECTOR_FACTORIES: connector_factory = CONNECTOR_FACTORIES[transformer_spec.connector] elif config_globals and '.' in transformer_spec.connector: try: connector_factory = eval(transformer_spec.connector, config_globals) except (NameError, AttributeError): raise bulkloader_errors.InvalidConfiguration( 'Invalid connector specified for name=%s. Could not evaluate %s.' % (transformer_spec.name, transformer_spec.connector)) else: raise bulkloader_errors.InvalidConfiguration( 'Invalid connector specified for name=%s. Must be either a built in ' 'connector ("%s") or a factory method in a module imported via ' 'python_preamble.' % (transformer_spec.name, '", "'.join(CONNECTOR_FACTORIES))) options = {} if transformer_spec.connector_options: options = transformer_spec.connector_options.ToDict() try: connector_object = connector_factory(options, transformer_spec.name) except TypeError: raise bulkloader_errors.InvalidConfiguration( 'Invalid connector specified for name=%s. Could not initialize %s.' % (transformer_spec.name, transformer_spec.connector)) dict_to_model_object = DictConvertor(transformer_spec) class ImporterClass(GenericImporter): """Class to pass to the bulkloader, wraps the specificed configuration.""" def __init__(self): super(self.__class__, self).__init__( connector_object.generate_import_record, dict_to_model_object.dict_to_entity, transformer_spec.name, reserve_keys) importer_class = ImporterClass class ExporterClass(GenericExporter): """Class to pass to the bulkloader, wraps the specificed configuration.""" def __init__(self): super(self.__class__, self).__init__( connector_object, dict_to_model_object.entity_to_dict, transformer_spec.kind, transformer_spec.sort_key_from_entity) exporter_class = ExporterClass return importer_class, exporter_class
[ "def", "create_transformer_classes", "(", "transformer_spec", ",", "config_globals", ",", "reserve_keys", ")", ":", "if", "transformer_spec", ".", "connector", "in", "CONNECTOR_FACTORIES", ":", "connector_factory", "=", "CONNECTOR_FACTORIES", "[", "transformer_spec", ".",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/bulkload/bulkloader_config.py#L518-L593
msikma/pokesprite
b9cecdbf8ad1610ed0a0a71a1429f38fc818276c
scripts/gen_docs.py
python
determine_form
(slug, form_name, form_data)
return (form_slug_file, form_slug_display, form_alias)
Return two Pokémon form strings: one for display, and one referencing a file
Return two Pokémon form strings: one for display, and one referencing a file
[ "Return", "two", "Pokémon", "form", "strings", ":", "one", "for", "display", "and", "one", "referencing", "a", "file" ]
def determine_form(slug, form_name, form_data): '''Return two Pokémon form strings: one for display, and one referencing a file''' # The regular form is indicated by a '$', and can be an alias of another one. form_value = '' if form_name == '$' else form_name form_alias = form_data.get('is_alias_of', None) form_alias = '' if form_alias == '$' else form_alias form_file = form_alias if form_alias is not None else form_value form_display = form_value # Save two slugs: the first one is literally just the Pokémon name plus its form, # and the other uses the 'is_alias_of' slug and is used for selecting the right file. form_slug_display = '-'.join(filter(len, [slug, form_display])) form_slug_file = '-'.join(filter(len, [slug, form_file])) return (form_slug_file, form_slug_display, form_alias)
[ "def", "determine_form", "(", "slug", ",", "form_name", ",", "form_data", ")", ":", "# The regular form is indicated by a '$', and can be an alias of another one.", "form_value", "=", "''", "if", "form_name", "==", "'$'", "else", "form_name", "form_alias", "=", "form_data...
https://github.com/msikma/pokesprite/blob/b9cecdbf8ad1610ed0a0a71a1429f38fc818276c/scripts/gen_docs.py#L371-L386
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/mailbox.py
python
_mboxMMDFMessage.remove_flag
(self, flag)
Unset the given string flag(s) without changing others.
Unset the given string flag(s) without changing others.
[ "Unset", "the", "given", "string", "flag", "(", "s", ")", "without", "changing", "others", "." ]
def remove_flag(self, flag): """Unset the given string flag(s) without changing others.""" if 'Status' in self or 'X-Status' in self: self.set_flags(''.join(set(self.get_flags()) - set(flag)))
[ "def", "remove_flag", "(", "self", ",", "flag", ")", ":", "if", "'Status'", "in", "self", "or", "'X-Status'", "in", "self", ":", "self", ".", "set_flags", "(", "''", ".", "join", "(", "set", "(", "self", ".", "get_flags", "(", ")", ")", "-", "set",...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/mailbox.py#L1638-L1641
Gandi/gandi.cli
5de0605126247e986f8288b467a52710a78e1794
gandi/cli/commands/oper.py
python
list
(gandi, limit, step)
return result
List operations.
List operations.
[ "List", "operations", "." ]
def list(gandi, limit, step): """List operations.""" output_keys = ['id', 'type', 'step'] options = { 'step': step, 'items_per_page': limit, 'sort_by': 'date_created DESC' } result = gandi.oper.list(options) for num, oper in enumerate(reversed(result)): if num: gandi.separator_line() output_generic(gandi, oper, output_keys) return result
[ "def", "list", "(", "gandi", ",", "limit", ",", "step", ")", ":", "output_keys", "=", "[", "'id'", ",", "'type'", ",", "'step'", "]", "options", "=", "{", "'step'", ":", "step", ",", "'items_per_page'", ":", "limit", ",", "'sort_by'", ":", "'date_creat...
https://github.com/Gandi/gandi.cli/blob/5de0605126247e986f8288b467a52710a78e1794/gandi/cli/commands/oper.py#L23-L39
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/lib/base.py
python
OpenShiftCLI._create
(self, fname)
return self.openshift_cmd(['create', '-f', fname])
call oc create on a filename
call oc create on a filename
[ "call", "oc", "create", "on", "a", "filename" ]
def _create(self, fname): '''call oc create on a filename''' return self.openshift_cmd(['create', '-f', fname])
[ "def", "_create", "(", "self", ",", "fname", ")", ":", "return", "self", ".", "openshift_cmd", "(", "[", "'create'", ",", "'-f'", ",", "fname", "]", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/lib/base.py#L112-L114
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/ex-submodules/casexml/apps/case/xform.py
python
process_cases_with_casedb
(xforms, case_db)
return case_processing_result
[]
def process_cases_with_casedb(xforms, case_db): case_processing_result = _get_or_update_cases(xforms, case_db) cases = case_processing_result.cases xform = xforms[0] _update_sync_logs(xform, cases) try: cases_received.send(sender=None, xform=xform, cases=cases) except Exception as e: # don't let the exceptions in signals prevent standard case processing notify_exception( None, 'something went wrong sending the cases_received signal ' 'for form %s: %s' % (xform.form_id, e) ) for case in cases: case_db.post_process_case(case, xform) case_db.mark_changed(case) case_processing_result.set_cases(cases) return case_processing_result
[ "def", "process_cases_with_casedb", "(", "xforms", ",", "case_db", ")", ":", "case_processing_result", "=", "_get_or_update_cases", "(", "xforms", ",", "case_db", ")", "cases", "=", "case_processing_result", ".", "cases", "xform", "=", "xforms", "[", "0", "]", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/ex-submodules/casexml/apps/case/xform.py#L36-L58
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
python
HTTPResponse._decode
(self, data, decode_content, flush_decoder)
return data
Decode the data passed in and potentially flush the decoder.
Decode the data passed in and potentially flush the decoder.
[ "Decode", "the", "data", "passed", "in", "and", "potentially", "flush", "the", "decoder", "." ]
def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ try: if decode_content and self._decoder: data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e) if flush_decoder and decode_content and self._decoder: buf = self._decoder.decompress(binary_type()) data += buf + self._decoder.flush() return data
[ "def", "_decode", "(", "self", ",", "data", ",", "decode_content", ",", "flush_decoder", ")", ":", "try", ":", "if", "decode_content", "and", "self", ".", "_decoder", ":", "data", "=", "self", ".", "_decoder", ".", "decompress", "(", "data", ")", "except...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py#L186-L203
bslatkin/effectivepython
4ae6f3141291ea137eb29a245bf889dbc8091713
example_code/item_73.py
python
heap_overdue_benchmark
(count)
return print_results(count, tests)
[]
def heap_overdue_benchmark(count): def prepare(): to_add = list(range(count)) random.shuffle(to_add) return [], to_add def run(queue, to_add): for i in to_add: heappush(queue, i) while queue: heappop(queue) tests = timeit.repeat( setup='queue, to_add = prepare()', stmt=f'run(queue, to_add)', globals=locals(), repeat=100, number=1) return print_results(count, tests)
[ "def", "heap_overdue_benchmark", "(", "count", ")", ":", "def", "prepare", "(", ")", ":", "to_add", "=", "list", "(", "range", "(", "count", ")", ")", "random", ".", "shuffle", "(", "to_add", ")", "return", "[", "]", ",", "to_add", "def", "run", "(",...
https://github.com/bslatkin/effectivepython/blob/4ae6f3141291ea137eb29a245bf889dbc8091713/example_code/item_73.py#L291-L310