nwo
stringlengths
5
58
sha
stringlengths
40
40
path
stringlengths
5
172
language
stringclasses
1 value
identifier
stringlengths
1
100
parameters
stringlengths
2
3.5k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
21.5k
docstring
stringlengths
2
17k
docstring_summary
stringlengths
0
6.58k
docstring_tokens
sequence
function
stringlengths
35
55.6k
function_tokens
sequence
url
stringlengths
89
269
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteMakeRule
(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None)
Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels
Write a Makefile rule, with some extra tricks.
[ "Write", "a", "Makefile", "rule", "with", "some", "extra", "tricks", "." ]
def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = map(QuoteSpaces, outputs) inputs = map(QuoteSpaces, inputs) if comment: self.WriteLn('# ' + comment) if phony: self.WriteLn('.PHONY: ' + ' '.join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = ' FORCE_DO_CMD' if force else '' if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn('%s: | %s%s' % (' '.join(outputs), ' '.join(inputs), force_append)) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn('%s: %s%s' % (outputs[0], ' '.join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. cmddigest = hashlib.sha1(command if command else self.target).hexdigest() intermediate = "%s.intermediate" % (cmddigest) self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:'); self.WriteLn('%s: %s' % ('.INTERMEDIATE', intermediate)) self.WriteLn('%s: %s%s' % (intermediate, ' '.join(inputs), force_append)) actions.insert(0, '$(call do_cmd,touch)') if actions: for action in actions: self.WriteLn('\t%s' % action) self.WriteLn()
[ "def", "WriteMakeRule", "(", "self", ",", "outputs", ",", "inputs", ",", "actions", "=", "None", ",", "comment", "=", "None", ",", "order_only", "=", "False", ",", "force", "=", "False", ",", "phony", "=", "False", ",", "command", "=", "None", ")", ":", "outputs", "=", "map", "(", "QuoteSpaces", ",", "outputs", ")", "inputs", "=", "map", "(", "QuoteSpaces", ",", "inputs", ")", "if", "comment", ":", "self", ".", "WriteLn", "(", "'# '", "+", "comment", ")", "if", "phony", ":", "self", ".", "WriteLn", "(", "'.PHONY: '", "+", "' '", ".", "join", "(", "outputs", ")", ")", "if", "actions", ":", "self", ".", "WriteLn", "(", "\"%s: TOOLSET := $(TOOLSET)\"", "%", "outputs", "[", "0", "]", ")", "force_append", "=", "' FORCE_DO_CMD'", "if", "force", "else", "''", "if", "order_only", ":", "# Order only rule: Just write a simple rule.", "# TODO(evanm): just make order_only a list of deps instead of this hack.", "self", ".", "WriteLn", "(", "'%s: | %s%s'", "%", "(", "' '", ".", "join", "(", "outputs", ")", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "elif", "len", "(", "outputs", ")", "==", "1", ":", "# Regular rule, one output: Just write a simple rule.", "self", ".", "WriteLn", "(", "'%s: %s%s'", "%", "(", "outputs", "[", "0", "]", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "else", ":", "# Regular rule, more than one output: Multiple outputs are tricky in", "# make. We will write three rules:", "# - All outputs depend on an intermediate file.", "# - Make .INTERMEDIATE depend on the intermediate.", "# - The intermediate file depends on the inputs and executes the", "# actual command.", "# - The intermediate recipe will 'touch' the intermediate file.", "# - The multi-output rule will have an do-nothing recipe.", "# Hash the target name to avoid generating overlong filenames.", "cmddigest", "=", "hashlib", ".", "sha1", "(", "command", "if", "command", "else", "self", ".", "target", ")", ".", "hexdigest", "(", ")", "intermediate", "=", "\"%s.intermediate\"", "%", "(", "cmddigest", ")", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "' '", ".", "join", "(", "outputs", ")", ",", "intermediate", ")", ")", "self", ".", "WriteLn", "(", "'\\t%s'", "%", "'@:'", ")", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "'.INTERMEDIATE'", ",", "intermediate", ")", ")", "self", ".", "WriteLn", "(", "'%s: %s%s'", "%", "(", "intermediate", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "actions", ".", "insert", "(", "0", ",", "'$(call do_cmd,touch)'", ")", "if", "actions", ":", "for", "action", "in", "actions", ":", "self", ".", "WriteLn", "(", "'\\t%s'", "%", "action", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/generator/make.py#L1710-L1768
SteeltoeOSS/Samples
a27be0f2fd2af0e263f32aceb131df21fb54c82b
Connectors/src/Redis/scaffold/cloudfoundry.py
python
setup
(context)
:type context: behave.runner.Context
:type context: behave.runner.Context
[ ":", "type", "context", ":", "behave", ".", "runner", ".", "Context" ]
def setup(context): """ :type context: behave.runner.Context """ cf = cloudfoundry.CloudFoundry(context) # remove previous app app = 'redis-connector' cf.delete_app(app) # create service service = 'p-redis' plan = 'shared-vm' instance = 'myRedisService' cf.create_service(service, plan, instance)
[ "def", "setup", "(", "context", ")", ":", "cf", "=", "cloudfoundry", ".", "CloudFoundry", "(", "context", ")", "# remove previous app", "app", "=", "'redis-connector'", "cf", ".", "delete_app", "(", "app", ")", "# create service", "service", "=", "'p-redis'", "plan", "=", "'shared-vm'", "instance", "=", "'myRedisService'", "cf", ".", "create_service", "(", "service", ",", "plan", ",", "instance", ")" ]
https://github.com/SteeltoeOSS/Samples/blob/a27be0f2fd2af0e263f32aceb131df21fb54c82b/Connectors/src/Redis/scaffold/cloudfoundry.py#L4-L16
hotosm/tasking-manager
1a7b02c6ccd431029a96d709d4d786c83cb37f5e
backend/api/notifications/resources.py
python
NotificationsAllAPI.get
(self)
Get all messages for logged in user --- tags: - notifications produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: query name: messageType type: string description: Optional message-type filter; leave blank to retrieve all - in: query name: from description: Optional from username filter type: string - in: query name: project description: Optional project filter type: string - in: query name: taskId description: Optional task filter type: integer - in: query name: status description: Optional status filter (read or unread) type: string - in: query name: sortBy description: field to sort by, defaults to 'date'. Other useful options are 'read', 'project_id' and 'message_type' type: string - in: query name: sortDirection description: sorting direction ('asc' or 'desc'), defaults to 'desc' type: string - in: query name: page description: Page of results type: integer - in: query name: pageSize description: Size of page, defaults to 10 type: integer responses: 200: description: Messages found 404: description: User has no messages 500: description: Internal Server Error
Get all messages for logged in user --- tags: - notifications produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: query name: messageType type: string description: Optional message-type filter; leave blank to retrieve all - in: query name: from description: Optional from username filter type: string - in: query name: project description: Optional project filter type: string - in: query name: taskId description: Optional task filter type: integer - in: query name: status description: Optional status filter (read or unread) type: string - in: query name: sortBy description: field to sort by, defaults to 'date'. Other useful options are 'read', 'project_id' and 'message_type' type: string - in: query name: sortDirection description: sorting direction ('asc' or 'desc'), defaults to 'desc' type: string - in: query name: page description: Page of results type: integer - in: query name: pageSize description: Size of page, defaults to 10 type: integer responses: 200: description: Messages found 404: description: User has no messages 500: description: Internal Server Error
[ "Get", "all", "messages", "for", "logged", "in", "user", "---", "tags", ":", "-", "notifications", "produces", ":", "-", "application", "/", "json", "parameters", ":", "-", "in", ":", "header", "name", ":", "Authorization", "description", ":", "Base64", "encoded", "session", "token", "required", ":", "true", "type", ":", "string", "default", ":", "Token", "sessionTokenHere", "==", "-", "in", ":", "query", "name", ":", "messageType", "type", ":", "string", "description", ":", "Optional", "message", "-", "type", "filter", ";", "leave", "blank", "to", "retrieve", "all", "-", "in", ":", "query", "name", ":", "from", "description", ":", "Optional", "from", "username", "filter", "type", ":", "string", "-", "in", ":", "query", "name", ":", "project", "description", ":", "Optional", "project", "filter", "type", ":", "string", "-", "in", ":", "query", "name", ":", "taskId", "description", ":", "Optional", "task", "filter", "type", ":", "integer", "-", "in", ":", "query", "name", ":", "status", "description", ":", "Optional", "status", "filter", "(", "read", "or", "unread", ")", "type", ":", "string", "-", "in", ":", "query", "name", ":", "sortBy", "description", ":", "field", "to", "sort", "by", "defaults", "to", "date", ".", "Other", "useful", "options", "are", "read", "project_id", "and", "message_type", "type", ":", "string", "-", "in", ":", "query", "name", ":", "sortDirection", "description", ":", "sorting", "direction", "(", "asc", "or", "desc", ")", "defaults", "to", "desc", "type", ":", "string", "-", "in", ":", "query", "name", ":", "page", "description", ":", "Page", "of", "results", "type", ":", "integer", "-", "in", ":", "query", "name", ":", "pageSize", "description", ":", "Size", "of", "page", "defaults", "to", "10", "type", ":", "integer", "responses", ":", "200", ":", "description", ":", "Messages", "found", "404", ":", "description", ":", "User", "has", "no", "messages", "500", ":", "description", ":", "Internal", "Server", "Error" ]
def get(self): """ Get all messages for logged in user --- tags: - notifications produces: - application/json parameters: - in: header name: Authorization description: Base64 encoded session token required: true type: string default: Token sessionTokenHere== - in: query name: messageType type: string description: Optional message-type filter; leave blank to retrieve all - in: query name: from description: Optional from username filter type: string - in: query name: project description: Optional project filter type: string - in: query name: taskId description: Optional task filter type: integer - in: query name: status description: Optional status filter (read or unread) type: string - in: query name: sortBy description: field to sort by, defaults to 'date'. Other useful options are 'read', 'project_id' and 'message_type' type: string - in: query name: sortDirection description: sorting direction ('asc' or 'desc'), defaults to 'desc' type: string - in: query name: page description: Page of results type: integer - in: query name: pageSize description: Size of page, defaults to 10 type: integer responses: 200: description: Messages found 404: description: User has no messages 500: description: Internal Server Error """ try: preferred_locale = request.environ.get("HTTP_ACCEPT_LANGUAGE") page = request.args.get("page", 1, int) page_size = request.args.get("pageSize", 10, int) sort_by = request.args.get("sortBy", "date") sort_direction = request.args.get("sortDirection", "desc") message_type = request.args.get("messageType", None) from_username = request.args.get("from") project = request.args.get("project", None, int) task_id = request.args.get("taskId", None, int) status = request.args.get("status", None, str) user_messages = MessageService.get_all_messages( token_auth.current_user(), preferred_locale, page, page_size, sort_by, sort_direction, message_type, from_username, project, task_id, status, ) return user_messages.to_primitive(), 200 except Exception as e: error_msg = f"Messages GET all - unhandled error: {str(e)}" current_app.logger.critical(error_msg) return {"Error": "Unable to fetch messages"}, 500
[ "def", "get", "(", "self", ")", ":", "try", ":", "preferred_locale", "=", "request", ".", "environ", ".", "get", "(", "\"HTTP_ACCEPT_LANGUAGE\"", ")", "page", "=", "request", ".", "args", ".", "get", "(", "\"page\"", ",", "1", ",", "int", ")", "page_size", "=", "request", ".", "args", ".", "get", "(", "\"pageSize\"", ",", "10", ",", "int", ")", "sort_by", "=", "request", ".", "args", ".", "get", "(", "\"sortBy\"", ",", "\"date\"", ")", "sort_direction", "=", "request", ".", "args", ".", "get", "(", "\"sortDirection\"", ",", "\"desc\"", ")", "message_type", "=", "request", ".", "args", ".", "get", "(", "\"messageType\"", ",", "None", ")", "from_username", "=", "request", ".", "args", ".", "get", "(", "\"from\"", ")", "project", "=", "request", ".", "args", ".", "get", "(", "\"project\"", ",", "None", ",", "int", ")", "task_id", "=", "request", ".", "args", ".", "get", "(", "\"taskId\"", ",", "None", ",", "int", ")", "status", "=", "request", ".", "args", ".", "get", "(", "\"status\"", ",", "None", ",", "str", ")", "user_messages", "=", "MessageService", ".", "get_all_messages", "(", "token_auth", ".", "current_user", "(", ")", ",", "preferred_locale", ",", "page", ",", "page_size", ",", "sort_by", ",", "sort_direction", ",", "message_type", ",", "from_username", ",", "project", ",", "task_id", ",", "status", ",", ")", "return", "user_messages", ".", "to_primitive", "(", ")", ",", "200", "except", "Exception", "as", "e", ":", "error_msg", "=", "f\"Messages GET all - unhandled error: {str(e)}\"", "current_app", ".", "logger", ".", "critical", "(", "error_msg", ")", "return", "{", "\"Error\"", ":", "\"Unable to fetch messages\"", "}", ",", "500" ]
https://github.com/hotosm/tasking-manager/blob/1a7b02c6ccd431029a96d709d4d786c83cb37f5e/backend/api/notifications/resources.py#L108-L196
agoravoting/agora-ciudadana
a7701035ea77d7a91baa9b5c2d0c05d91d1b4262
agora_site/agora_core/models/voting_systems/wright_stv.py
python
WrightSTV.validate_question
(question)
Validates the value of a given question in an election
Validates the value of a given question in an election
[ "Validates", "the", "value", "of", "a", "given", "question", "in", "an", "election" ]
def validate_question(question): ''' Validates the value of a given question in an election ''' error = django_forms.ValidationError(_('Invalid questions format')) if 'num_seats' not in question or\ not isinstance(question['num_seats'], int) or\ question['num_seats'] < 1: return error if question['a'] != 'ballot/question' or\ not isinstance(question['min'], int) or question['min'] < 0 or\ question['min'] > 1 or\ not isinstance(question['max'], int) or question['max'] < 1 or\ not isinstance(question['randomize_answer_order'], bool): raise error # check there are at least 2 possible answers if not isinstance(question['answers'], list) or\ len(question['answers']) < 2 or\ len(question['answers']) < question['num_seats'] or\ len(question['answers']) > 100: raise error # check each answer answer_values = [] for answer in question['answers']: if not isinstance(answer, dict): raise error # check it contains the valid elements if not list_contains_all(['a', 'value', 'url', 'details'], answer.keys()): raise error for el in ['a', 'value', 'url', 'details']: if not (isinstance(answer[el], unicode) or\ isinstance(answer[el], str)) or\ len(answer[el]) > 500: raise error if answer['a'] != 'ballot/answer' or\ not ( isinstance(answer['value'], unicode) or\ isinstance(answer['value'], str) ) or len(answer['value']) < 1: raise error if answer['value'] in answer_values: raise error answer_values.append(answer['value'])
[ "def", "validate_question", "(", "question", ")", ":", "error", "=", "django_forms", ".", "ValidationError", "(", "_", "(", "'Invalid questions format'", ")", ")", "if", "'num_seats'", "not", "in", "question", "or", "not", "isinstance", "(", "question", "[", "'num_seats'", "]", ",", "int", ")", "or", "question", "[", "'num_seats'", "]", "<", "1", ":", "return", "error", "if", "question", "[", "'a'", "]", "!=", "'ballot/question'", "or", "not", "isinstance", "(", "question", "[", "'min'", "]", ",", "int", ")", "or", "question", "[", "'min'", "]", "<", "0", "or", "question", "[", "'min'", "]", ">", "1", "or", "not", "isinstance", "(", "question", "[", "'max'", "]", ",", "int", ")", "or", "question", "[", "'max'", "]", "<", "1", "or", "not", "isinstance", "(", "question", "[", "'randomize_answer_order'", "]", ",", "bool", ")", ":", "raise", "error", "# check there are at least 2 possible answers", "if", "not", "isinstance", "(", "question", "[", "'answers'", "]", ",", "list", ")", "or", "len", "(", "question", "[", "'answers'", "]", ")", "<", "2", "or", "len", "(", "question", "[", "'answers'", "]", ")", "<", "question", "[", "'num_seats'", "]", "or", "len", "(", "question", "[", "'answers'", "]", ")", ">", "100", ":", "raise", "error", "# check each answer", "answer_values", "=", "[", "]", "for", "answer", "in", "question", "[", "'answers'", "]", ":", "if", "not", "isinstance", "(", "answer", ",", "dict", ")", ":", "raise", "error", "# check it contains the valid elements", "if", "not", "list_contains_all", "(", "[", "'a'", ",", "'value'", ",", "'url'", ",", "'details'", "]", ",", "answer", ".", "keys", "(", ")", ")", ":", "raise", "error", "for", "el", "in", "[", "'a'", ",", "'value'", ",", "'url'", ",", "'details'", "]", ":", "if", "not", "(", "isinstance", "(", "answer", "[", "el", "]", ",", "unicode", ")", "or", "isinstance", "(", "answer", "[", "el", "]", ",", "str", ")", ")", "or", "len", "(", "answer", "[", "el", "]", ")", ">", "500", ":", "raise", "error", "if", "answer", "[", "'a'", "]", "!=", "'ballot/answer'", "or", "not", "(", "isinstance", "(", "answer", "[", "'value'", "]", ",", "unicode", ")", "or", "isinstance", "(", "answer", "[", "'value'", "]", ",", "str", ")", ")", "or", "len", "(", "answer", "[", "'value'", "]", ")", "<", "1", ":", "raise", "error", "if", "answer", "[", "'value'", "]", "in", "answer_values", ":", "raise", "error", "answer_values", ".", "append", "(", "answer", "[", "'value'", "]", ")" ]
https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/agora_core/models/voting_systems/wright_stv.py#L49-L100
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5Type/Base.py
python
Base.isDeleted
(self)
return False
Test if the context is in 'deleted' state
Test if the context is in 'deleted' state
[ "Test", "if", "the", "context", "is", "in", "deleted", "state" ]
def isDeleted(self): """Test if the context is in 'deleted' state""" for wf in self.getPortalObject().portal_workflow.getWorkflowValueListFor(self): state = wf._getWorkflowStateOf(self) if state is not None and state.getReference() == 'deleted': return True return False
[ "def", "isDeleted", "(", "self", ")", ":", "for", "wf", "in", "self", ".", "getPortalObject", "(", ")", ".", "portal_workflow", ".", "getWorkflowValueListFor", "(", "self", ")", ":", "state", "=", "wf", ".", "_getWorkflowStateOf", "(", "self", ")", "if", "state", "is", "not", "None", "and", "state", ".", "getReference", "(", ")", "==", "'deleted'", ":", "return", "True", "return", "False" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Type/Base.py#L2811-L2817
wotermelon/toJump
3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f
lib/mac/systrace/catapult/devil/devil/android/fastboot_utils.py
python
FastbootUtils.Reboot
( self, bootloader=False, wait_for_reboot=True, timeout=None, retries=None)
Reboots out of fastboot mode. It reboots the phone either back into fastboot, or to a regular boot. It then blocks until the device is ready. Args: bootloader: If set to True, reboots back into bootloader.
Reboots out of fastboot mode.
[ "Reboots", "out", "of", "fastboot", "mode", "." ]
def Reboot( self, bootloader=False, wait_for_reboot=True, timeout=None, retries=None): """Reboots out of fastboot mode. It reboots the phone either back into fastboot, or to a regular boot. It then blocks until the device is ready. Args: bootloader: If set to True, reboots back into bootloader. """ if bootloader: self.fastboot.RebootBootloader() self.WaitForFastbootMode() else: self.fastboot.Reboot() if wait_for_reboot: self._device.WaitUntilFullyBooted(timeout=_FASTBOOT_REBOOT_TIMEOUT)
[ "def", "Reboot", "(", "self", ",", "bootloader", "=", "False", ",", "wait_for_reboot", "=", "True", ",", "timeout", "=", "None", ",", "retries", "=", "None", ")", ":", "if", "bootloader", ":", "self", ".", "fastboot", ".", "RebootBootloader", "(", ")", "self", ".", "WaitForFastbootMode", "(", ")", "else", ":", "self", ".", "fastboot", ".", "Reboot", "(", ")", "if", "wait_for_reboot", ":", "self", ".", "_device", ".", "WaitUntilFullyBooted", "(", "timeout", "=", "_FASTBOOT_REBOOT_TIMEOUT", ")" ]
https://github.com/wotermelon/toJump/blob/3dcec5cb5d91387d415b805d015ab8d2e6ffcf5f/lib/mac/systrace/catapult/devil/devil/android/fastboot_utils.py#L128-L144
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py
python
get_mixed_type_key
(obj)
return NotImplemented
Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key.
Return a key suitable for sorting between networks and addresses.
[ "Return", "a", "key", "suitable", "for", "sorting", "between", "networks", "and", "addresses", "." ]
def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented
[ "def", "get_mixed_type_key", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "_BaseNetwork", ")", ":", "return", "obj", ".", "_get_networks_key", "(", ")", "elif", "isinstance", "(", "obj", ",", "_BaseAddress", ")", ":", "return", "obj", ".", "_get_address_key", "(", ")", "return", "NotImplemented" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py#L480-L502
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/mass_mailing_sms/models/mailing_list.py
python
MailingList._get_contact_statistics_fields
(self)
return values
See super method docstring for more info. Adds: - contact_count_sms: all valid sms - contact_count_blacklisted: override the dict entry to add SMS blacklist condition
See super method docstring for more info. Adds: - contact_count_sms: all valid sms - contact_count_blacklisted: override the dict entry to add SMS blacklist condition
[ "See", "super", "method", "docstring", "for", "more", "info", ".", "Adds", ":", "-", "contact_count_sms", ":", "all", "valid", "sms", "-", "contact_count_blacklisted", ":", "override", "the", "dict", "entry", "to", "add", "SMS", "blacklist", "condition" ]
def _get_contact_statistics_fields(self): """ See super method docstring for more info. Adds: - contact_count_sms: all valid sms - contact_count_blacklisted: override the dict entry to add SMS blacklist condition """ values = super(MailingList, self)._get_contact_statistics_fields() values.update({ 'contact_count_sms': ''' SUM(CASE WHEN (c.phone_sanitized IS NOT NULL AND COALESCE(r.opt_out,FALSE) = FALSE AND bl_sms.id IS NULL) THEN 1 ELSE 0 END) AS contact_count_sms''', 'contact_count_blacklisted': f''' SUM(CASE WHEN (bl.id IS NOT NULL OR bl_sms.id IS NOT NULL) THEN 1 ELSE 0 END) AS contact_count_blacklisted''' }) return values
[ "def", "_get_contact_statistics_fields", "(", "self", ")", ":", "values", "=", "super", "(", "MailingList", ",", "self", ")", ".", "_get_contact_statistics_fields", "(", ")", "values", ".", "update", "(", "{", "'contact_count_sms'", ":", "'''\n SUM(CASE WHEN\n (c.phone_sanitized IS NOT NULL\n AND COALESCE(r.opt_out,FALSE) = FALSE\n AND bl_sms.id IS NULL)\n THEN 1 ELSE 0 END) AS contact_count_sms'''", ",", "'contact_count_blacklisted'", ":", "f'''\n SUM(CASE WHEN (bl.id IS NOT NULL OR bl_sms.id IS NOT NULL)\n THEN 1 ELSE 0 END) AS contact_count_blacklisted'''", "}", ")", "return", "values" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/mass_mailing_sms/models/mailing_list.py#L30-L48
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_invoicing/DocumentTemplateItem/portal_components/document.erp5.InvoiceSimulationRule.py
python
InvoiceSimulationRule._getMovementGenerator
(self, context)
return InvoicingRuleMovementGenerator(applied_rule=context, rule=self)
Return the movement generator to use in the expand process
Return the movement generator to use in the expand process
[ "Return", "the", "movement", "generator", "to", "use", "in", "the", "expand", "process" ]
def _getMovementGenerator(self, context): """ Return the movement generator to use in the expand process """ return InvoicingRuleMovementGenerator(applied_rule=context, rule=self)
[ "def", "_getMovementGenerator", "(", "self", ",", "context", ")", ":", "return", "InvoicingRuleMovementGenerator", "(", "applied_rule", "=", "context", ",", "rule", "=", "self", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_invoicing/DocumentTemplateItem/portal_components/document.erp5.InvoiceSimulationRule.py#L81-L85
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/urllib2.py
python
build_opener
(*handlers)
return opener
Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable, HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used.
Create an opener object from a list of handlers.
[ "Create", "an", "opener", "object", "from", "a", "list", "of", "handlers", "." ]
def build_opener(*handlers): """Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable, HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. """ import types def isclass(obj): return isinstance(obj, (types.ClassType, type)) opener = OpenerDirector() default_classes = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] if hasattr(httplib, 'HTTPS'): default_classes.append(HTTPSHandler) skip = set() for klass in default_classes: for check in handlers: if isclass(check): if issubclass(check, klass): skip.add(klass) elif isinstance(check, klass): skip.add(klass) for klass in skip: default_classes.remove(klass) for klass in default_classes: opener.add_handler(klass()) for h in handlers: if isclass(h): h = h() opener.add_handler(h) return opener
[ "def", "build_opener", "(", "*", "handlers", ")", ":", "import", "types", "def", "isclass", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "(", "types", ".", "ClassType", ",", "type", ")", ")", "opener", "=", "OpenerDirector", "(", ")", "default_classes", "=", "[", "ProxyHandler", ",", "UnknownHandler", ",", "HTTPHandler", ",", "HTTPDefaultErrorHandler", ",", "HTTPRedirectHandler", ",", "FTPHandler", ",", "FileHandler", ",", "HTTPErrorProcessor", "]", "if", "hasattr", "(", "httplib", ",", "'HTTPS'", ")", ":", "default_classes", ".", "append", "(", "HTTPSHandler", ")", "skip", "=", "set", "(", ")", "for", "klass", "in", "default_classes", ":", "for", "check", "in", "handlers", ":", "if", "isclass", "(", "check", ")", ":", "if", "issubclass", "(", "check", ",", "klass", ")", ":", "skip", ".", "add", "(", "klass", ")", "elif", "isinstance", "(", "check", ",", "klass", ")", ":", "skip", ".", "add", "(", "klass", ")", "for", "klass", "in", "skip", ":", "default_classes", ".", "remove", "(", "klass", ")", "for", "klass", "in", "default_classes", ":", "opener", ".", "add_handler", "(", "klass", "(", ")", ")", "for", "h", "in", "handlers", ":", "if", "isclass", "(", "h", ")", ":", "h", "=", "h", "(", ")", "opener", ".", "add_handler", "(", "h", ")", "return", "opener" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/urllib2.py#L444-L481
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/Sqlmap/thirdparty/bottle/bottle.py
python
Bottle.wsgi
(self, environ, start_response)
The bottle WSGI-interface.
The bottle WSGI-interface.
[ "The", "bottle", "WSGI", "-", "interface", "." ]
def wsgi(self, environ, start_response): """ The bottle WSGI-interface. """ try: out = self._cast(self._handle(environ)) # rfc2616 section 4.3 if response._status_code in (100, 101, 204, 304)\ or environ['REQUEST_METHOD'] == 'HEAD': if hasattr(out, 'close'): out.close() out = [] start_response(response._status_line, response.headerlist) return out except (KeyboardInterrupt, SystemExit, MemoryError): raise except Exception: if not self.catchall: raise err = '<h1>Critical error while processing request: %s</h1>' \ % html_escape(environ.get('PATH_INFO', '/')) if DEBUG: err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \ '<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \ % (html_escape(repr(_e())), html_escape(format_exc())) environ['wsgi.errors'].write(err) headers = [('Content-Type', 'text/html; charset=UTF-8')] start_response('500 INTERNAL SERVER ERROR', headers) return [tob(err)]
[ "def", "wsgi", "(", "self", ",", "environ", ",", "start_response", ")", ":", "try", ":", "out", "=", "self", ".", "_cast", "(", "self", ".", "_handle", "(", "environ", ")", ")", "# rfc2616 section 4.3", "if", "response", ".", "_status_code", "in", "(", "100", ",", "101", ",", "204", ",", "304", ")", "or", "environ", "[", "'REQUEST_METHOD'", "]", "==", "'HEAD'", ":", "if", "hasattr", "(", "out", ",", "'close'", ")", ":", "out", ".", "close", "(", ")", "out", "=", "[", "]", "start_response", "(", "response", ".", "_status_line", ",", "response", ".", "headerlist", ")", "return", "out", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ",", "MemoryError", ")", ":", "raise", "except", "Exception", ":", "if", "not", "self", ".", "catchall", ":", "raise", "err", "=", "'<h1>Critical error while processing request: %s</h1>'", "%", "html_escape", "(", "environ", ".", "get", "(", "'PATH_INFO'", ",", "'/'", ")", ")", "if", "DEBUG", ":", "err", "+=", "'<h2>Error:</h2>\\n<pre>\\n%s\\n</pre>\\n'", "'<h2>Traceback:</h2>\\n<pre>\\n%s\\n</pre>\\n'", "%", "(", "html_escape", "(", "repr", "(", "_e", "(", ")", ")", ")", ",", "html_escape", "(", "format_exc", "(", ")", ")", ")", "environ", "[", "'wsgi.errors'", "]", ".", "write", "(", "err", ")", "headers", "=", "[", "(", "'Content-Type'", ",", "'text/html; charset=UTF-8'", ")", "]", "start_response", "(", "'500 INTERNAL SERVER ERROR'", ",", "headers", ")", "return", "[", "tob", "(", "err", ")", "]" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/Sqlmap/thirdparty/bottle/bottle.py#L850-L874
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py
python
_BreakpointContainer._notify_exit_process
(self, event)
return True
Notify the termination of a process. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise.
Notify the termination of a process.
[ "Notify", "the", "termination", "of", "a", "process", "." ]
def _notify_exit_process(self, event): """ Notify the termination of a process. @type event: L{ExitProcessEvent} @param event: Exit process event. @rtype: bool @return: C{True} to call the user-defined handler, C{False} otherwise. """ self.__cleanup_process(event) self.__cleanup_thread(event) return True
[ "def", "_notify_exit_process", "(", "self", ",", "event", ")", ":", "self", ".", "__cleanup_process", "(", "event", ")", "self", ".", "__cleanup_thread", "(", "event", ")", "return", "True" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py#L3689-L3701
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
python
WinTool._UseSeparateMspdbsrv
(self, env, args)
Allows to use a unique instance of mspdbsrv.exe per linker instead of a shared one.
Allows to use a unique instance of mspdbsrv.exe per linker instead of a shared one.
[ "Allows", "to", "use", "a", "unique", "instance", "of", "mspdbsrv", ".", "exe", "per", "linker", "instead", "of", "a", "shared", "one", "." ]
def _UseSeparateMspdbsrv(self, env, args): """Allows to use a unique instance of mspdbsrv.exe per linker instead of a shared one.""" if len(args) < 1: raise Exception("Not enough arguments") if args[0] != 'link.exe': return # Use the output filename passed to the linker to generate an endpoint name # for mspdbsrv.exe. endpoint_name = None for arg in args: m = _LINK_EXE_OUT_ARG.match(arg) if m: endpoint_name = re.sub(r'\W+', '', '%s_%d' % (m.group('out'), os.getpid())) break if endpoint_name is None: return # Adds the appropriate environment variable. This will be read by link.exe # to know which instance of mspdbsrv.exe it should connect to (if it's # not set then the default endpoint is used). env['_MSPDBSRV_ENDPOINT_'] = endpoint_name
[ "def", "_UseSeparateMspdbsrv", "(", "self", ",", "env", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<", "1", ":", "raise", "Exception", "(", "\"Not enough arguments\"", ")", "if", "args", "[", "0", "]", "!=", "'link.exe'", ":", "return", "# Use the output filename passed to the linker to generate an endpoint name", "# for mspdbsrv.exe.", "endpoint_name", "=", "None", "for", "arg", "in", "args", ":", "m", "=", "_LINK_EXE_OUT_ARG", ".", "match", "(", "arg", ")", "if", "m", ":", "endpoint_name", "=", "re", ".", "sub", "(", "r'\\W+'", ",", "''", ",", "'%s_%d'", "%", "(", "m", ".", "group", "(", "'out'", ")", ",", "os", ".", "getpid", "(", ")", ")", ")", "break", "if", "endpoint_name", "is", "None", ":", "return", "# Adds the appropriate environment variable. This will be read by link.exe", "# to know which instance of mspdbsrv.exe it should connect to (if it's", "# not set then the default endpoint is used).", "env", "[", "'_MSPDBSRV_ENDPOINT_'", "]", "=", "endpoint_name" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py#L37-L62
dirtbags/pcapdb
3917cf50cd83ec4d7409d7cd99321e8bdaa57e2e
core/apps/capture_node_api/lib/search/node.py
python
OrNode.prune
(self)
Prune the tree of any atoms and AND clauses that must logically result in an empty set. Raises a ParseError if the entire parse tree ends up being empty.
Prune the tree of any atoms and AND clauses that must logically result in an empty set. Raises a ParseError if the entire parse tree ends up being empty.
[ "Prune", "the", "tree", "of", "any", "atoms", "and", "AND", "clauses", "that", "must", "logically", "result", "in", "an", "empty", "set", ".", "Raises", "a", "ParseError", "if", "the", "entire", "parse", "tree", "ends", "up", "being", "empty", "." ]
def prune(self): """Prune the tree of any atoms and AND clauses that must logically result in an empty set. Raises a ParseError if the entire parse tree ends up being empty.""" for and_clause in self: and_clause.prune() if len(self) == 0: raise ParseError("Optimized search tree is empty.", self)
[ "def", "prune", "(", "self", ")", ":", "for", "and_clause", "in", "self", ":", "and_clause", ".", "prune", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "raise", "ParseError", "(", "\"Optimized search tree is empty.\"", ",", "self", ")" ]
https://github.com/dirtbags/pcapdb/blob/3917cf50cd83ec4d7409d7cd99321e8bdaa57e2e/core/apps/capture_node_api/lib/search/node.py#L524-L532
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/v8/third_party/jinja2/idtracking.py
python
FrameSymbolVisitor.visit_AssignBlock
(self, node, **kwargs)
Stop visiting at block assigns.
Stop visiting at block assigns.
[ "Stop", "visiting", "at", "block", "assigns", "." ]
def visit_AssignBlock(self, node, **kwargs): """Stop visiting at block assigns.""" self.visit(node.target, **kwargs)
[ "def", "visit_AssignBlock", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "self", ".", "visit", "(", "node", ".", "target", ",", "*", "*", "kwargs", ")" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/third_party/jinja2/idtracking.py#L275-L277
domogik/domogik
fefd584d354875bcb15f351cbc455abffaa6501f
src/domogik/tools/pep8.py
python
_main
()
Parse options and run checks on Python source.
Parse options and run checks on Python source.
[ "Parse", "options", "and", "run", "checks", "on", "Python", "source", "." ]
def _main(): """ Parse options and run checks on Python source. """ options, args = process_options() if options.doctest: import doctest return doctest.testmod() start_time = time.time() for path in args: if os.path.isdir(path): input_dir(path) else: input_file(path) elapsed = time.time() - start_time if options.statistics: print_statistics() if options.benchmark: print_benchmark(elapsed)
[ "def", "_main", "(", ")", ":", "options", ",", "args", "=", "process_options", "(", ")", "if", "options", ".", "doctest", ":", "import", "doctest", "return", "doctest", ".", "testmod", "(", ")", "start_time", "=", "time", ".", "time", "(", ")", "for", "path", "in", "args", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "input_dir", "(", "path", ")", "else", ":", "input_file", "(", "path", ")", "elapsed", "=", "time", ".", "time", "(", ")", "-", "start_time", "if", "options", ".", "statistics", ":", "print_statistics", "(", ")", "if", "options", ".", "benchmark", ":", "print_benchmark", "(", "elapsed", ")" ]
https://github.com/domogik/domogik/blob/fefd584d354875bcb15f351cbc455abffaa6501f/src/domogik/tools/pep8.py#L834-L852
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pkg_resources/_vendor/pyparsing.py
python
_makeTags
(tagStr, xml)
return openTag, closeTag
Internal helper to construct opening and closing tag expressions, given a tag name
Internal helper to construct opening and closing tag expressions, given a tag name
[ "Internal", "helper", "to", "construct", "opening", "and", "closing", "tag", "expressions", "given", "a", "tag", "name" ]
def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) else: resname = tagStr.name tagAttrName = Word(alphas,alphanums+"_-:") if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") else: printablesLessRAbrack = "".join(c for c in printables if c not in ">") tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) openTag = Suppress("<") + tagStr("tag") + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Optional( Suppress("=") + tagAttrValue ) ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine(_L("</") + tagStr + ">") openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname) closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % resname) openTag.tag = resname closeTag.tag = resname return openTag, closeTag
[ "def", "_makeTags", "(", "tagStr", ",", "xml", ")", ":", "if", "isinstance", "(", "tagStr", ",", "basestring", ")", ":", "resname", "=", "tagStr", "tagStr", "=", "Keyword", "(", "tagStr", ",", "caseless", "=", "not", "xml", ")", "else", ":", "resname", "=", "tagStr", ".", "name", "tagAttrName", "=", "Word", "(", "alphas", ",", "alphanums", "+", "\"_-:\"", ")", "if", "(", "xml", ")", ":", "tagAttrValue", "=", "dblQuotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", "+", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "else", ":", "printablesLessRAbrack", "=", "\"\"", ".", "join", "(", "c", "for", "c", "in", "printables", "if", "c", "not", "in", "\">\"", ")", "tagAttrValue", "=", "quotedString", ".", "copy", "(", ")", ".", "setParseAction", "(", "removeQuotes", ")", "|", "Word", "(", "printablesLessRAbrack", ")", "openTag", "=", "Suppress", "(", "\"<\"", ")", "+", "tagStr", "(", "\"tag\"", ")", "+", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "tagAttrName", ".", "setParseAction", "(", "downcaseTokens", ")", "+", "Optional", "(", "Suppress", "(", "\"=\"", ")", "+", "tagAttrValue", ")", ")", ")", ")", "+", "Optional", "(", "\"/\"", ",", "default", "=", "[", "False", "]", ")", ".", "setResultsName", "(", "\"empty\"", ")", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "t", "[", "0", "]", "==", "'/'", ")", "+", "Suppress", "(", "\">\"", ")", "closeTag", "=", "Combine", "(", "_L", "(", "\"</\"", ")", "+", "tagStr", "+", "\">\"", ")", "openTag", "=", "openTag", ".", "setResultsName", "(", "\"start\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"<%s>\"", "%", "resname", ")", "closeTag", "=", "closeTag", ".", "setResultsName", "(", "\"end\"", "+", "\"\"", ".", "join", "(", "resname", ".", "replace", "(", "\":\"", ",", "\" \"", ")", ".", "title", "(", ")", ".", "split", "(", ")", ")", ")", ".", "setName", "(", "\"</%s>\"", "%", "resname", ")", "openTag", ".", "tag", "=", "resname", "closeTag", ".", "tag", "=", "resname", "return", "openTag", ",", "closeTag" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pkg_resources/_vendor/pyparsing.py#L4875-L4902
nodejs/node
ac3c33c1646bf46104c15ae035982c06364da9b8
tools/inspector_protocol/jinja2/runtime.py
python
Context.__getitem__
(self, key)
return item
Lookup a variable or raise `KeyError` if the variable is undefined.
Lookup a variable or raise `KeyError` if the variable is undefined.
[ "Lookup", "a", "variable", "or", "raise", "KeyError", "if", "the", "variable", "is", "undefined", "." ]
def __getitem__(self, key): """Lookup a variable or raise `KeyError` if the variable is undefined. """ item = self.resolve_or_missing(key) if item is missing: raise KeyError(key) return item
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "item", "=", "self", ".", "resolve_or_missing", "(", "key", ")", "if", "item", "is", "missing", ":", "raise", "KeyError", "(", "key", ")", "return", "item" ]
https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/inspector_protocol/jinja2/runtime.py#L299-L306
xtk/X
04c1aa856664a8517d23aefd94c470d47130aead
lib/selenium/selenium/selenium.py
python
selenium.get_mouse_speed
(self)
return self.get_number("getMouseSpeed", [])
Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10).
[ "Returns", "the", "number", "of", "pixels", "between", "mousemove", "events", "during", "dragAndDrop", "commands", "(", "default", "=", "10", ")", "." ]
def get_mouse_speed(self): """ Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10). """ return self.get_number("getMouseSpeed", [])
[ "def", "get_mouse_speed", "(", "self", ")", ":", "return", "self", ".", "get_number", "(", "\"getMouseSpeed\"", ",", "[", "]", ")" ]
https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/selenium.py#L1467-L1472
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/sane_lists.py
python
SaneListExtension.extendMarkdown
(self, md, md_globals)
Override existing Processors.
Override existing Processors.
[ "Override", "existing", "Processors", "." ]
def extendMarkdown(self, md, md_globals): """ Override existing Processors. """ md.parser.blockprocessors['olist'] = SaneOListProcessor(md.parser) md.parser.blockprocessors['ulist'] = SaneUListProcessor(md.parser)
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "parser", ".", "blockprocessors", "[", "'olist'", "]", "=", "SaneOListProcessor", "(", "md", ".", "parser", ")", "md", ".", "parser", ".", "blockprocessors", "[", "'ulist'", "]", "=", "SaneUListProcessor", "(", "md", ".", "parser", ")" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/python-markdown/st3/markdown/extensions/sane_lists.py#L48-L51
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/packages/rfc3986/exceptions.py
python
InvalidComponentsError.__init__
(self, uri, *component_names)
Initialize the error with the invalid component name(s).
Initialize the error with the invalid component name(s).
[ "Initialize", "the", "error", "with", "the", "invalid", "component", "name", "(", "s", ")", "." ]
def __init__(self, uri, *component_names): """Initialize the error with the invalid component name(s).""" verb = 'was' if len(component_names) > 1: verb = 'were' self.uri = uri self.components = sorted(component_names) components = ', '.join(self.components) super(InvalidComponentsError, self).__init__( "{} {} found to be invalid".format(components, verb), uri, self.components, )
[ "def", "__init__", "(", "self", ",", "uri", ",", "*", "component_names", ")", ":", "verb", "=", "'was'", "if", "len", "(", "component_names", ")", ">", "1", ":", "verb", "=", "'were'", "self", ".", "uri", "=", "uri", "self", ".", "components", "=", "sorted", "(", "component_names", ")", "components", "=", "', '", ".", "join", "(", "self", ".", "components", ")", "super", "(", "InvalidComponentsError", ",", "self", ")", ".", "__init__", "(", "\"{} {} found to be invalid\"", ".", "format", "(", "components", ",", "verb", ")", ",", "uri", ",", "self", ".", "components", ",", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/packages/rfc3986/exceptions.py#L101-L114
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/pygments/all/pygments/formatters/img.py
python
ImageFormatter._get_char_x
(self, charno)
return charno * self.fontw + self.image_pad + self.line_number_width
Get the X coordinate of a character position.
Get the X coordinate of a character position.
[ "Get", "the", "X", "coordinate", "of", "a", "character", "position", "." ]
def _get_char_x(self, charno): """ Get the X coordinate of a character position. """ return charno * self.fontw + self.image_pad + self.line_number_width
[ "def", "_get_char_x", "(", "self", ",", "charno", ")", ":", "return", "charno", "*", "self", ".", "fontw", "+", "self", ".", "image_pad", "+", "self", ".", "line_number_width" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/pygments/all/pygments/formatters/img.py#L368-L372
rapidpro/rapidpro
8b6e58221fff967145f0b3411d85bcc15a0d3e72
temba/archives/models.py
python
Archive.iter_records
(self, *, where: dict = None)
Creates an iterator for the records in this archive, streaming and decompressing on the fly
Creates an iterator for the records in this archive, streaming and decompressing on the fly
[ "Creates", "an", "iterator", "for", "the", "records", "in", "this", "archive", "streaming", "and", "decompressing", "on", "the", "fly" ]
def iter_records(self, *, where: dict = None): """ Creates an iterator for the records in this archive, streaming and decompressing on the fly """ s3_client = s3.client() if where: bucket, key = self.get_storage_location() response = s3_client.select_object_content( Bucket=bucket, Key=key, ExpressionType="SQL", Expression=s3.compile_select(where=where), InputSerialization={"CompressionType": "GZIP", "JSON": {"Type": "LINES"}}, OutputSerialization={"JSON": {"RecordDelimiter": "\n"}}, ) def generator(): for record in EventStreamReader(response["Payload"]): yield record return generator() else: bucket, key = self.get_storage_location() s3_obj = s3_client.get_object(Bucket=bucket, Key=key) return jsonlgz_iterate(s3_obj["Body"])
[ "def", "iter_records", "(", "self", ",", "*", ",", "where", ":", "dict", "=", "None", ")", ":", "s3_client", "=", "s3", ".", "client", "(", ")", "if", "where", ":", "bucket", ",", "key", "=", "self", ".", "get_storage_location", "(", ")", "response", "=", "s3_client", ".", "select_object_content", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "ExpressionType", "=", "\"SQL\"", ",", "Expression", "=", "s3", ".", "compile_select", "(", "where", "=", "where", ")", ",", "InputSerialization", "=", "{", "\"CompressionType\"", ":", "\"GZIP\"", ",", "\"JSON\"", ":", "{", "\"Type\"", ":", "\"LINES\"", "}", "}", ",", "OutputSerialization", "=", "{", "\"JSON\"", ":", "{", "\"RecordDelimiter\"", ":", "\"\\n\"", "}", "}", ",", ")", "def", "generator", "(", ")", ":", "for", "record", "in", "EventStreamReader", "(", "response", "[", "\"Payload\"", "]", ")", ":", "yield", "record", "return", "generator", "(", ")", "else", ":", "bucket", ",", "key", "=", "self", ".", "get_storage_location", "(", ")", "s3_obj", "=", "s3_client", ".", "get_object", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ")", "return", "jsonlgz_iterate", "(", "s3_obj", "[", "\"Body\"", "]", ")" ]
https://github.com/rapidpro/rapidpro/blob/8b6e58221fff967145f0b3411d85bcc15a0d3e72/temba/archives/models.py#L181-L208
JoneXiong/YouMd
15c57a76ecc5a09e84558dfd1508adbbeeafd5a7
mole/request.py
python
Request.COOKIES
(self)
return cookies
Cookies parsed into a dictionary. Secure cookies are NOT decoded automatically. See :meth:`get_cookie` for details.
Cookies parsed into a dictionary. Secure cookies are NOT decoded automatically. See :meth:`get_cookie` for details.
[ "Cookies", "parsed", "into", "a", "dictionary", ".", "Secure", "cookies", "are", "NOT", "decoded", "automatically", ".", "See", ":", "meth", ":", "get_cookie", "for", "details", "." ]
def COOKIES(self): """ Cookies parsed into a dictionary. Secure cookies are NOT decoded automatically. See :meth:`get_cookie` for details. """ raw_dict = SimpleCookie(self.headers.get('Cookie','')) cookies = {} for cookie in raw_dict.itervalues(): cookies[cookie.key] = cookie.value return cookies
[ "def", "COOKIES", "(", "self", ")", ":", "raw_dict", "=", "SimpleCookie", "(", "self", ".", "headers", ".", "get", "(", "'Cookie'", ",", "''", ")", ")", "cookies", "=", "{", "}", "for", "cookie", "in", "raw_dict", ".", "itervalues", "(", ")", ":", "cookies", "[", "cookie", ".", "key", "]", "=", "cookie", ".", "value", "return", "cookies" ]
https://github.com/JoneXiong/YouMd/blob/15c57a76ecc5a09e84558dfd1508adbbeeafd5a7/mole/request.py#L302-L310
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
tools/gyp/pylib/gyp/MSVSSettings.py
python
_GetMSBuildToolSettings
(msbuild_settings, tool)
return msbuild_settings.setdefault(tool.msbuild_name, {})
Returns an MSBuild tool dictionary. Creates it if needed.
Returns an MSBuild tool dictionary. Creates it if needed.
[ "Returns", "an", "MSBuild", "tool", "dictionary", ".", "Creates", "it", "if", "needed", "." ]
def _GetMSBuildToolSettings(msbuild_settings, tool): """Returns an MSBuild tool dictionary. Creates it if needed.""" return msbuild_settings.setdefault(tool.msbuild_name, {})
[ "def", "_GetMSBuildToolSettings", "(", "msbuild_settings", ",", "tool", ")", ":", "return", "msbuild_settings", ".", "setdefault", "(", "tool", ".", "msbuild_name", ",", "{", "}", ")" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/tools/gyp/pylib/gyp/MSVSSettings.py#L62-L64
XRPLF/xrpl-dev-portal
4a75fe3579fa7938acf4fc3fe48fc01c8eb5a38c
content/_code-samples/key-derivation/RFC1751.py
python
_extract
(key, start, length)
return reduce(lambda x,y: x*2+ord(y)-48, k, 0)
Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.
Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.
[ "Extract", "a", "bitstring", "(", "2", ".", "x", ")", "/", "bytestring", "(", "2", ".", "x", ")", "from", "a", "string", "of", "binary", "digits", "and", "return", "its", "numeric", "value", "." ]
def _extract(key, start, length): """Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.""" k=key[start:start+length] return reduce(lambda x,y: x*2+ord(y)-48, k, 0)
[ "def", "_extract", "(", "key", ",", "start", ",", "length", ")", ":", "k", "=", "key", "[", "start", ":", "start", "+", "length", "]", "return", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "*", "2", "+", "ord", "(", "y", ")", "-", "48", ",", "k", ",", "0", ")" ]
https://github.com/XRPLF/xrpl-dev-portal/blob/4a75fe3579fa7938acf4fc3fe48fc01c8eb5a38c/content/_code-samples/key-derivation/RFC1751.py#L56-L60
defunctzombie/libuv.js
04a76a470dfdcad14ea8f19b6f215f205a9214f8
tools/gyp/pylib/gyp/input.py
python
DependencyGraphNode._AddImportedDependencies
(self, targets, dependencies=None)
return dependencies
Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point.
Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings.
[ "Given", "a", "list", "of", "direct", "dependencies", "adds", "indirect", "dependencies", "that", "other", "dependencies", "have", "declared", "to", "export", "their", "settings", "." ]
def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies
[ "def", "_AddImportedDependencies", "(", "self", ",", "targets", ",", "dependencies", "=", "None", ")", ":", "if", "dependencies", "==", "None", ":", "dependencies", "=", "[", "]", "index", "=", "0", "while", "index", "<", "len", "(", "dependencies", ")", ":", "dependency", "=", "dependencies", "[", "index", "]", "dependency_dict", "=", "targets", "[", "dependency", "]", "# Add any dependencies whose settings should be imported to the list", "# if not already present. Newly-added items will be checked for", "# their own imports when the list iteration reaches them.", "# Rather than simply appending new items, insert them after the", "# dependency that exported them. This is done to more closely match", "# the depth-first method used by DeepDependencies.", "add_index", "=", "1", "for", "imported_dependency", "in", "dependency_dict", ".", "get", "(", "'export_dependent_settings'", ",", "[", "]", ")", ":", "if", "imported_dependency", "not", "in", "dependencies", ":", "dependencies", ".", "insert", "(", "index", "+", "add_index", ",", "imported_dependency", ")", "add_index", "=", "add_index", "+", "1", "index", "=", "index", "+", "1", "return", "dependencies" ]
https://github.com/defunctzombie/libuv.js/blob/04a76a470dfdcad14ea8f19b6f215f205a9214f8/tools/gyp/pylib/gyp/input.py#L1542-L1581
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/mailbox.py
python
MH.iterkeys
(self)
return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit()))
Return an iterator over keys.
Return an iterator over keys.
[ "Return", "an", "iterator", "over", "keys", "." ]
def iterkeys(self): """Return an iterator over keys.""" return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit()))
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "sorted", "(", "int", "(", "entry", ")", "for", "entry", "in", "os", ".", "listdir", "(", "self", ".", "_path", ")", "if", "entry", ".", "isdigit", "(", ")", ")", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mailbox.py#L1005-L1008
nodejs/node-chakracore
770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetBundlePlistPath
(self)
Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.
Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.
[ "Returns", "the", "qualified", "path", "to", "the", "bundle", "s", "plist", "file", ".", "E", ".", "g", ".", "Chromium", ".", "app", "/", "Contents", "/", "Info", ".", "plist", ".", "Only", "valid", "for", "bundles", "." ]
def GetBundlePlistPath(self): """Returns the qualified path to the bundle's plist file. E.g. Chromium.app/Contents/Info.plist. Only valid for bundles.""" assert self._IsBundle() if self.spec['type'] in ('executable', 'loadable_module') or \ self.IsIosFramework(): return os.path.join(self.GetBundleContentsFolderPath(), 'Info.plist') else: return os.path.join(self.GetBundleContentsFolderPath(), 'Resources', 'Info.plist')
[ "def", "GetBundlePlistPath", "(", "self", ")", ":", "assert", "self", ".", "_IsBundle", "(", ")", "if", "self", ".", "spec", "[", "'type'", "]", "in", "(", "'executable'", ",", "'loadable_module'", ")", "or", "self", ".", "IsIosFramework", "(", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleContentsFolderPath", "(", ")", ",", "'Info.plist'", ")", "else", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "GetBundleContentsFolderPath", "(", ")", ",", "'Resources'", ",", "'Info.plist'", ")" ]
https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/tools/gyp/pylib/gyp/xcode_emulation.py#L365-L374
dataarts/tailbone
5ed162bbfdb369a31f4f50bd089239c9c105457a
tailbone/restful/counter.py
python
TailboneGeneralCounterShardConfig.all_keys
(cls, name)
return [ndb.Key(TailboneGeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
Returns all possible keys for the counter name given the config. Args: name: The name of the counter. Returns: The full list of ndb.Key values corresponding to all the possible counter shards that could exist.
Returns all possible keys for the counter name given the config.
[ "Returns", "all", "possible", "keys", "for", "the", "counter", "name", "given", "the", "config", "." ]
def all_keys(cls, name): """Returns all possible keys for the counter name given the config. Args: name: The name of the counter. Returns: The full list of ndb.Key values corresponding to all the possible counter shards that could exist. """ config = cls.get_or_insert(name) shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)] return [ndb.Key(TailboneGeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
[ "def", "all_keys", "(", "cls", ",", "name", ")", ":", "config", "=", "cls", ".", "get_or_insert", "(", "name", ")", "shard_key_strings", "=", "[", "SHARD_KEY_TEMPLATE", ".", "format", "(", "name", ",", "index", ")", "for", "index", "in", "range", "(", "config", ".", "num_shards", ")", "]", "return", "[", "ndb", ".", "Key", "(", "TailboneGeneralCounterShard", ",", "shard_key_string", ")", "for", "shard_key_string", "in", "shard_key_strings", "]" ]
https://github.com/dataarts/tailbone/blob/5ed162bbfdb369a31f4f50bd089239c9c105457a/tailbone/restful/counter.py#L15-L29
carlosperate/ardublockly
04fa48273b5651386d0ef1ce6dd446795ffc2594
ardublocklyserver/local-packages/serial/rfc2217.py
python
Serial.cd
(self)
return bool(self.get_modem_state() & MODEMSTATE_MASK_CD)
Read terminal status line: Carrier Detect.
Read terminal status line: Carrier Detect.
[ "Read", "terminal", "status", "line", ":", "Carrier", "Detect", "." ]
def cd(self): """Read terminal status line: Carrier Detect.""" if not self.is_open: raise portNotOpenError return bool(self.get_modem_state() & MODEMSTATE_MASK_CD)
[ "def", "cd", "(", "self", ")", ":", "if", "not", "self", ".", "is_open", ":", "raise", "portNotOpenError", "return", "bool", "(", "self", ".", "get_modem_state", "(", ")", "&", "MODEMSTATE_MASK_CD", ")" ]
https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/local-packages/serial/rfc2217.py#L711-L715
NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application
b9b1f9e9aa84e379c573063fc5622ef50d38898d
tracker/code/euclidean/euchelper.py
python
densify_line
(line, hypotenuse)
return dense_line
Densify a line ("line") Arguments: line {[type]} -- [description] hypotenuse {[type]} -- [description] Returns: [type] -- [description]
Densify a line ("line")
[ "Densify", "a", "line", "(", "line", ")" ]
def densify_line(line, hypotenuse): """ Densify a line ("line") Arguments: line {[type]} -- [description] hypotenuse {[type]} -- [description] Returns: [type] -- [description] """ x1_temp = line[0][0] y1_temp = line[0][1] x2_temp = line[1][0] y2_temp = line[1][1] # Flag to keep track if reorder was needed flipped = False # Reorder so that x1 is smaller than x2 if x2_temp > x1_temp: var_x1 = x1_temp var_y1 = y1_temp var_x2 = x2_temp var_y2 = y2_temp else: flipped = True var_x1 = x2_temp var_y1 = y2_temp var_x2 = x1_temp var_y2 = y1_temp # Get total distance to evaluate number of needed points dist_euc = math.sqrt(pow((var_x2-var_x1), 2) + pow((var_y2-var_y1), 2)) # Get the angle of the line angle_radians = get_angle(var_x1, var_y1, var_x2, var_y2) # print(angle_radians) # Calculate number of needed internal points, allowing any remainder internal_points = int(int(dist_euc)/hypotenuse) # Calculate the needed x values x_out = [var_x1] for a_pt in range(internal_points): adj = hypotenuse*math.cos(angle_radians) next_x = x_out[a_pt] + adj x_out.append(next_x) xp_pt = [var_x1, var_x2] fp_pt = [var_y1, var_y2] y_out = numpy.interp(x_out, xp_pt, fp_pt) dense_line = [[var_x1, var_y1]] for a_pt in range(0, len(x_out)): dense_line.append([x_out[a_pt], y_out[a_pt]]) dense_line.append([var_x2, var_y2]) if flipped: dense_line.reverse() return dense_line
[ "def", "densify_line", "(", "line", ",", "hypotenuse", ")", ":", "x1_temp", "=", "line", "[", "0", "]", "[", "0", "]", "y1_temp", "=", "line", "[", "0", "]", "[", "1", "]", "x2_temp", "=", "line", "[", "1", "]", "[", "0", "]", "y2_temp", "=", "line", "[", "1", "]", "[", "1", "]", "# Flag to keep track if reorder was needed", "flipped", "=", "False", "# Reorder so that x1 is smaller than x2", "if", "x2_temp", ">", "x1_temp", ":", "var_x1", "=", "x1_temp", "var_y1", "=", "y1_temp", "var_x2", "=", "x2_temp", "var_y2", "=", "y2_temp", "else", ":", "flipped", "=", "True", "var_x1", "=", "x2_temp", "var_y1", "=", "y2_temp", "var_x2", "=", "x1_temp", "var_y2", "=", "y1_temp", "# Get total distance to evaluate number of needed points", "dist_euc", "=", "math", ".", "sqrt", "(", "pow", "(", "(", "var_x2", "-", "var_x1", ")", ",", "2", ")", "+", "pow", "(", "(", "var_y2", "-", "var_y1", ")", ",", "2", ")", ")", "# Get the angle of the line", "angle_radians", "=", "get_angle", "(", "var_x1", ",", "var_y1", ",", "var_x2", ",", "var_y2", ")", "# print(angle_radians)", "# Calculate number of needed internal points, allowing any remainder", "internal_points", "=", "int", "(", "int", "(", "dist_euc", ")", "/", "hypotenuse", ")", "# Calculate the needed x values", "x_out", "=", "[", "var_x1", "]", "for", "a_pt", "in", "range", "(", "internal_points", ")", ":", "adj", "=", "hypotenuse", "*", "math", ".", "cos", "(", "angle_radians", ")", "next_x", "=", "x_out", "[", "a_pt", "]", "+", "adj", "x_out", ".", "append", "(", "next_x", ")", "xp_pt", "=", "[", "var_x1", ",", "var_x2", "]", "fp_pt", "=", "[", "var_y1", ",", "var_y2", "]", "y_out", "=", "numpy", ".", "interp", "(", "x_out", ",", "xp_pt", ",", "fp_pt", ")", "dense_line", "=", "[", "[", "var_x1", ",", "var_y1", "]", "]", "for", "a_pt", "in", "range", "(", "0", ",", "len", "(", "x_out", ")", ")", ":", "dense_line", ".", "append", "(", "[", "x_out", "[", "a_pt", "]", ",", "y_out", "[", "a_pt", "]", "]", ")", "dense_line", ".", "append", "(", "[", "var_x2", ",", "var_y2", "]", ")", "if", "flipped", ":", "dense_line", ".", "reverse", "(", ")", "return", "dense_line" ]
https://github.com/NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application/blob/b9b1f9e9aa84e379c573063fc5622ef50d38898d/tracker/code/euclidean/euchelper.py#L50-L113
nodejs/node-chakracore
770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCObject._XCKVPrint
(self, file, tabs, key, value)
Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline.
Prints a key and value, members of an XCObject's _properties dictionary, to file.
[ "Prints", "a", "key", "and", "value", "members", "of", "an", "XCObject", "s", "_properties", "dictionary", "to", "file", "." ]
def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline. """ if self._should_print_single_line: printable = '' after_kv = ' ' else: printable = '\t' * tabs after_kv = '\n' # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy # objects without comments. Sometimes it prints them with comments, but # the majority of the time, it doesn't. To avoid unnecessary changes to # the project file after Xcode opens it, don't write comments for # remoteGlobalIDString. This is a sucky hack and it would certainly be # cleaner to extend the schema to indicate whether or not a comment should # be printed, but since this is the only case where the problem occurs and # Xcode itself can't seem to make up its mind, the hack will suffice. # # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. if key == 'remoteGlobalIDString' and isinstance(self, PBXContainerItemProxy): value_to_print = value.id else: value_to_print = value # PBXBuildFile's settings property is represented in the output as a dict, # but a hack here has it represented as a string. Arrange to strip off the # quotes so that it shows up in the output as expected. if key == 'settings' and isinstance(self, PBXBuildFile): strip_value_quotes = True else: strip_value_quotes = False # In another one-off, let's set flatten_list on buildSettings properties # of XCBuildConfiguration objects, because that's how Xcode treats them. if key == 'buildSettings' and isinstance(self, XCBuildConfiguration): flatten_list = True else: flatten_list = False try: printable_key = self._XCPrintableValue(tabs, key, flatten_list) printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list) if strip_value_quotes and len(printable_value) > 1 and \ printable_value[0] == '"' and printable_value[-1] == '"': printable_value = printable_value[1:-1] printable += printable_key + ' = ' + printable_value + ';' + after_kv except TypeError, e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise self._XCPrint(file, 0, printable)
[ "def", "_XCKVPrint", "(", "self", ",", "file", ",", "tabs", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_should_print_single_line", ":", "printable", "=", "''", "after_kv", "=", "' '", "else", ":", "printable", "=", "'\\t'", "*", "tabs", "after_kv", "=", "'\\n'", "# Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy", "# objects without comments. Sometimes it prints them with comments, but", "# the majority of the time, it doesn't. To avoid unnecessary changes to", "# the project file after Xcode opens it, don't write comments for", "# remoteGlobalIDString. This is a sucky hack and it would certainly be", "# cleaner to extend the schema to indicate whether or not a comment should", "# be printed, but since this is the only case where the problem occurs and", "# Xcode itself can't seem to make up its mind, the hack will suffice.", "#", "# Also see PBXContainerItemProxy._schema['remoteGlobalIDString'].", "if", "key", "==", "'remoteGlobalIDString'", "and", "isinstance", "(", "self", ",", "PBXContainerItemProxy", ")", ":", "value_to_print", "=", "value", ".", "id", "else", ":", "value_to_print", "=", "value", "# PBXBuildFile's settings property is represented in the output as a dict,", "# but a hack here has it represented as a string. Arrange to strip off the", "# quotes so that it shows up in the output as expected.", "if", "key", "==", "'settings'", "and", "isinstance", "(", "self", ",", "PBXBuildFile", ")", ":", "strip_value_quotes", "=", "True", "else", ":", "strip_value_quotes", "=", "False", "# In another one-off, let's set flatten_list on buildSettings properties", "# of XCBuildConfiguration objects, because that's how Xcode treats them.", "if", "key", "==", "'buildSettings'", "and", "isinstance", "(", "self", ",", "XCBuildConfiguration", ")", ":", "flatten_list", "=", "True", "else", ":", "flatten_list", "=", "False", "try", ":", "printable_key", "=", "self", ".", "_XCPrintableValue", "(", "tabs", ",", "key", ",", "flatten_list", ")", "printable_value", "=", "self", ".", "_XCPrintableValue", "(", "tabs", ",", "value_to_print", ",", "flatten_list", ")", "if", "strip_value_quotes", "and", "len", "(", "printable_value", ")", ">", "1", "and", "printable_value", "[", "0", "]", "==", "'\"'", "and", "printable_value", "[", "-", "1", "]", "==", "'\"'", ":", "printable_value", "=", "printable_value", "[", "1", ":", "-", "1", "]", "printable", "+=", "printable_key", "+", "' = '", "+", "printable_value", "+", "';'", "+", "after_kv", "except", "TypeError", ",", "e", ":", "gyp", ".", "common", ".", "ExceptionAppend", "(", "e", ",", "'while printing key \"%s\"'", "%", "key", ")", "raise", "self", ".", "_XCPrint", "(", "file", ",", "0", ",", "printable", ")" ]
https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L639-L699
jam-py/jam-py
0821492cdff8665928e0f093a4435aa64285a45c
jam/third_party/sqlalchemy/sql/selectable.py
python
subquery
(alias, *args, **kwargs)
return Select(*args, **kwargs).subquery(alias)
r"""Return an :class:`.Subquery` object derived from a :class:`.Select`. :param name: the alias name for the subquery :param \*args, \**kwargs: all other arguments are passed through to the :func:`.select` function.
r"""Return an :class:`.Subquery` object derived from a :class:`.Select`.
[ "r", "Return", "an", ":", "class", ":", ".", "Subquery", "object", "derived", "from", "a", ":", "class", ":", ".", "Select", "." ]
def subquery(alias, *args, **kwargs): r"""Return an :class:`.Subquery` object derived from a :class:`.Select`. :param name: the alias name for the subquery :param \*args, \**kwargs: all other arguments are passed through to the :func:`.select` function. """ return Select(*args, **kwargs).subquery(alias)
[ "def", "subquery", "(", "alias", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Select", "(", "*", "args", ",", "*", "*", "kwargs", ")", ".", "subquery", "(", "alias", ")" ]
https://github.com/jam-py/jam-py/blob/0821492cdff8665928e0f093a4435aa64285a45c/jam/third_party/sqlalchemy/sql/selectable.py#L69-L79
jeff1evesque/machine-learning
4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff
brain/cache/query.py
python
Query.__init__
(self, db_num=0, host=None, port=None)
This constructor defines necessary redis attributes, used to define a connection between the client, and redis server. @db, the redis database number to store jobs into (there are 0-15). Note: we implement the 'StrictRedis' class, which adheres to the strict redis syntax, not the backwards compatibile subclass, 'Redis'. Note: this class explicitly inherits the 'new-style' class.
[]
def __init__(self, db_num=0, host=None, port=None): ''' This constructor defines necessary redis attributes, used to define a connection between the client, and redis server. @db, the redis database number to store jobs into (there are 0-15). Note: we implement the 'StrictRedis' class, which adheres to the strict redis syntax, not the backwards compatibile subclass, 'Redis'. Note: this class explicitly inherits the 'new-style' class. ''' # redis settings my_redis = Settings() # define host, and port, if provided if host: my_redis.set_host(host) if port: my_redis.set_port(port) # get redis parameters self.host = my_redis.get_host() self.port = my_redis.get_port() self.db_num = db_num
[ "def", "__init__", "(", "self", ",", "db_num", "=", "0", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "# redis settings", "my_redis", "=", "Settings", "(", ")", "# define host, and port, if provided", "if", "host", ":", "my_redis", ".", "set_host", "(", "host", ")", "if", "port", ":", "my_redis", ".", "set_port", "(", "port", ")", "# get redis parameters", "self", ".", "host", "=", "my_redis", ".", "get_host", "(", ")", "self", ".", "port", "=", "my_redis", ".", "get_port", "(", ")", "self", ".", "db_num", "=", "db_num" ]
https://github.com/jeff1evesque/machine-learning/blob/4c54e36f8ebf6a0b481c8aca71a6b3b4010dd4ff/brain/cache/query.py#L39-L66
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.GetMapFileName
(self, config, expand_special)
return map_file
Gets the explicitly overriden map file name for a target or returns None if it's not set.
Gets the explicitly overriden map file name for a target or returns None if it's not set.
[ "Gets", "the", "explicitly", "overriden", "map", "file", "name", "for", "a", "target", "or", "returns", "None", "if", "it", "s", "not", "set", "." ]
def GetMapFileName(self, config, expand_special): """Gets the explicitly overriden map file name for a target or returns None if it's not set.""" config = self._TargetConfig(config) map_file = self._Setting(('VCLinkerTool', 'MapFileName'), config) if map_file: map_file = expand_special(self.ConvertVSMacros(map_file, config=config)) return map_file
[ "def", "GetMapFileName", "(", "self", ",", "config", ",", "expand_special", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "map_file", "=", "self", ".", "_Setting", "(", "(", "'VCLinkerTool'", ",", "'MapFileName'", ")", ",", "config", ")", "if", "map_file", ":", "map_file", "=", "expand_special", "(", "self", ".", "ConvertVSMacros", "(", "map_file", ",", "config", "=", "config", ")", ")", "return", "map_file" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/msvs_emulation.py#L381-L388
ireaderlab/zkdash
a9e27e9cc63dcfbb483a1fdfa00c98fd0b079739
lib/zyqconf/types.py
python
ListNode.__iter__
(self)
迭代器协议实现
迭代器协议实现
[ "迭代器协议实现" ]
def __iter__(self): """迭代器协议实现 """ keys = qconf_py.get_batch_keys(self.parent_path) for key in keys: path = self.join_path(self.parent_path, key) yield self.get_conf(path)
[ "def", "__iter__", "(", "self", ")", ":", "keys", "=", "qconf_py", ".", "get_batch_keys", "(", "self", ".", "parent_path", ")", "for", "key", "in", "keys", ":", "path", "=", "self", ".", "join_path", "(", "self", ".", "parent_path", ",", "key", ")", "yield", "self", ".", "get_conf", "(", "path", ")" ]
https://github.com/ireaderlab/zkdash/blob/a9e27e9cc63dcfbb483a1fdfa00c98fd0b079739/lib/zyqconf/types.py#L126-L132
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
bt5/erp5_rss_reader/ExtensionTemplateItem/ERP5RSSFeed.py
python
getObjectStringList
(xml_string, element_to_find='object')
return [etree.tostring(node) for node in rss_doc.xpath('//%s' % element_to_find)]
this function splits an ERP5 XML string into object string list, each object string is converted into utf-8 encoding and html entities are translated into corresponding unicode code
this function splits an ERP5 XML string into object string list, each object string is converted into utf-8 encoding and html entities are translated into corresponding unicode code
[ "this", "function", "splits", "an", "ERP5", "XML", "string", "into", "object", "string", "list", "each", "object", "string", "is", "converted", "into", "utf", "-", "8", "encoding", "and", "html", "entities", "are", "translated", "into", "corresponding", "unicode", "code" ]
def getObjectStringList(xml_string, element_to_find='object'): """ this function splits an ERP5 XML string into object string list, each object string is converted into utf-8 encoding and html entities are translated into corresponding unicode code """ rss_doc = etree.fromstring(xml_string) return [etree.tostring(node) for node in rss_doc.xpath('//%s' % element_to_find)]
[ "def", "getObjectStringList", "(", "xml_string", ",", "element_to_find", "=", "'object'", ")", ":", "rss_doc", "=", "etree", ".", "fromstring", "(", "xml_string", ")", "return", "[", "etree", ".", "tostring", "(", "node", ")", "for", "node", "in", "rss_doc", ".", "xpath", "(", "'//%s'", "%", "element_to_find", ")", "]" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_rss_reader/ExtensionTemplateItem/ERP5RSSFeed.py#L35-L43
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/v8/third_party/jinja2/parser.py
python
Parser.parse_statements
(self, end_tokens, drop_needle=False)
return result
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed.
Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed.
[ "Parse", "multiple", "statements", "into", "a", "list", "until", "one", "of", "the", "end", "tokens", "is", "reached", ".", "This", "is", "used", "to", "parse", "the", "body", "of", "statements", "as", "it", "also", "parses", "template", "data", "if", "appropriate", ".", "The", "parser", "checks", "first", "if", "the", "current", "token", "is", "a", "colon", "and", "skips", "it", "if", "there", "is", "one", ".", "Then", "it", "checks", "for", "the", "block", "end", "and", "parses", "until", "if", "one", "of", "the", "end_tokens", "is", "reached", ".", "Per", "default", "the", "active", "token", "in", "the", "stream", "at", "the", "end", "of", "the", "call", "is", "the", "matched", "end", "token", ".", "If", "this", "is", "not", "wanted", "drop_needle", "can", "be", "set", "to", "True", "and", "the", "end", "token", "is", "removed", "." ]
def parse_statements(self, end_tokens, drop_needle=False): """Parse multiple statements into a list until one of the end tokens is reached. This is used to parse the body of statements as it also parses template data if appropriate. The parser checks first if the current token is a colon and skips it if there is one. Then it checks for the block end and parses until if one of the `end_tokens` is reached. Per default the active token in the stream at the end of the call is the matched end token. If this is not wanted `drop_needle` can be set to `True` and the end token is removed. """ # the first token may be a colon for python compatibility self.stream.skip_if('colon') # in the future it would be possible to add whole code sections # by adding some sort of end of statement token and parsing those here. self.stream.expect('block_end') result = self.subparse(end_tokens) # we reached the end of the template too early, the subparser # does not check for this, so we do that now if self.stream.current.type == 'eof': self.fail_eof(end_tokens) if drop_needle: next(self.stream) return result
[ "def", "parse_statements", "(", "self", ",", "end_tokens", ",", "drop_needle", "=", "False", ")", ":", "# the first token may be a colon for python compatibility", "self", ".", "stream", ".", "skip_if", "(", "'colon'", ")", "# in the future it would be possible to add whole code sections", "# by adding some sort of end of statement token and parsing those here.", "self", ".", "stream", ".", "expect", "(", "'block_end'", ")", "result", "=", "self", ".", "subparse", "(", "end_tokens", ")", "# we reached the end of the template too early, the subparser", "# does not check for this, so we do that now", "if", "self", ".", "stream", ".", "current", ".", "type", "==", "'eof'", ":", "self", ".", "fail_eof", "(", "end_tokens", ")", "if", "drop_needle", ":", "next", "(", "self", ".", "stream", ")", "return", "result" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/v8/third_party/jinja2/parser.py#L149-L174
kwhinnery/node-workshop
594bfc6bebf38d34a36b797e48f6f6d4600da5e4
challenge4/start/node_modules/mongoose/node_modules/mongodb/upload.py
python
VersionControlSystem.GetBaseFile
(self, filename)
Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file.
Get the content of the upstream version of a file.
[ "Get", "the", "content", "of", "the", "upstream", "version", "of", "a", "file", "." ]
def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__)
[ "def", "GetBaseFile", "(", "self", ",", "filename", ")", ":", "raise", "NotImplementedError", "(", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__", ")" ]
https://github.com/kwhinnery/node-workshop/blob/594bfc6bebf38d34a36b797e48f6f6d4600da5e4/challenge4/start/node_modules/mongoose/node_modules/mongodb/upload.py#L821-L835
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/setuptools/dist.py
python
Distribution.include_feature
(self, name)
Request inclusion of feature named 'name
Request inclusion of feature named 'name
[ "Request", "inclusion", "of", "feature", "named", "name" ]
def include_feature(self, name): """Request inclusion of feature named 'name'""" if self.feature_is_included(name) == 0: descr = self.features[name].description raise DistutilsOptionError( descr + " is required, but was excluded or is not available" ) self.features[name].include_in(self) self._set_feature(name, 1)
[ "def", "include_feature", "(", "self", ",", "name", ")", ":", "if", "self", ".", "feature_is_included", "(", "name", ")", "==", "0", ":", "descr", "=", "self", ".", "features", "[", "name", "]", ".", "description", "raise", "DistutilsOptionError", "(", "descr", "+", "\" is required, but was excluded or is not available\"", ")", "self", ".", "features", "[", "name", "]", ".", "include_in", "(", "self", ")", "self", ".", "_set_feature", "(", "name", ",", "1", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/setuptools/dist.py#L869-L878
mceSystems/node-jsc
90634f3064fab8e89a85b3942f0cc5054acc86fa
tools/gyp/pylib/gyp/common.py
python
EncodePOSIXShellList
(list)
return ' '.join(encoded_arguments)
Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator.
Encodes |list| suitably for consumption by POSIX shells.
[ "Encodes", "|list|", "suitably", "for", "consumption", "by", "POSIX", "shells", "." ]
def EncodePOSIXShellList(list): """Encodes |list| suitably for consumption by POSIX shells. Returns EncodePOSIXShellArgument for each item in list, and joins them together using the space character as an argument separator. """ encoded_arguments = [] for argument in list: encoded_arguments.append(EncodePOSIXShellArgument(argument)) return ' '.join(encoded_arguments)
[ "def", "EncodePOSIXShellList", "(", "list", ")", ":", "encoded_arguments", "=", "[", "]", "for", "argument", "in", "list", ":", "encoded_arguments", ".", "append", "(", "EncodePOSIXShellArgument", "(", "argument", ")", ")", "return", "' '", ".", "join", "(", "encoded_arguments", ")" ]
https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/tools/gyp/pylib/gyp/common.py#L283-L293
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/xml/dom/expatbuilder.py
python
Namespaces.install
(self, parser)
Insert the namespace-handlers onto the parser.
Insert the namespace-handlers onto the parser.
[ "Insert", "the", "namespace", "-", "handlers", "onto", "the", "parser", "." ]
def install(self, parser): """Insert the namespace-handlers onto the parser.""" ExpatBuilder.install(self, parser) if self._options.namespace_declarations: parser.StartNamespaceDeclHandler = ( self.start_namespace_decl_handler)
[ "def", "install", "(", "self", ",", "parser", ")", ":", "ExpatBuilder", ".", "install", "(", "self", ",", "parser", ")", "if", "self", ".", "_options", ".", "namespace_declarations", ":", "parser", ".", "StartNamespaceDeclHandler", "=", "(", "self", ".", "start_namespace_decl_handler", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/xml/dom/expatbuilder.py#L732-L737
pyistanbul/dbpatterns
6936cfa3555bae9ef65296c7f31a6637c0ef5d54
web/dbpatterns/documents/parsers/django_orm.py
python
DjangoORMParser.m2m_to_entity
(self, model, field, position_top, position_left)
return { "name": model.lower() + "_" + field.get("name"), "position": { "top": position_top, "left": position_left }, "attributes": [ { "name": "id", "type": TYPES_INTEGER, }, { "name": model.lower() + "_id", "type": TYPES_INTEGER, "is_foreign_key": True, "foreign_key_entity": model.lower(), "foreign_key_attribute": "id" }, { "name": field.get("relationship").lower() + "_id", "type": TYPES_INTEGER, "is_foreign_key": True, "foreign_key_entity": field.get("relationship").lower(), "foreign_key_attribute": "id" } ] }
Returns an entity that consist of provided m2m field.
Returns an entity that consist of provided m2m field.
[ "Returns", "an", "entity", "that", "consist", "of", "provided", "m2m", "field", "." ]
def m2m_to_entity(self, model, field, position_top, position_left): """ Returns an entity that consist of provided m2m field. """ return { "name": model.lower() + "_" + field.get("name"), "position": { "top": position_top, "left": position_left }, "attributes": [ { "name": "id", "type": TYPES_INTEGER, }, { "name": model.lower() + "_id", "type": TYPES_INTEGER, "is_foreign_key": True, "foreign_key_entity": model.lower(), "foreign_key_attribute": "id" }, { "name": field.get("relationship").lower() + "_id", "type": TYPES_INTEGER, "is_foreign_key": True, "foreign_key_entity": field.get("relationship").lower(), "foreign_key_attribute": "id" } ] }
[ "def", "m2m_to_entity", "(", "self", ",", "model", ",", "field", ",", "position_top", ",", "position_left", ")", ":", "return", "{", "\"name\"", ":", "model", ".", "lower", "(", ")", "+", "\"_\"", "+", "field", ".", "get", "(", "\"name\"", ")", ",", "\"position\"", ":", "{", "\"top\"", ":", "position_top", ",", "\"left\"", ":", "position_left", "}", ",", "\"attributes\"", ":", "[", "{", "\"name\"", ":", "\"id\"", ",", "\"type\"", ":", "TYPES_INTEGER", ",", "}", ",", "{", "\"name\"", ":", "model", ".", "lower", "(", ")", "+", "\"_id\"", ",", "\"type\"", ":", "TYPES_INTEGER", ",", "\"is_foreign_key\"", ":", "True", ",", "\"foreign_key_entity\"", ":", "model", ".", "lower", "(", ")", ",", "\"foreign_key_attribute\"", ":", "\"id\"", "}", ",", "{", "\"name\"", ":", "field", ".", "get", "(", "\"relationship\"", ")", ".", "lower", "(", ")", "+", "\"_id\"", ",", "\"type\"", ":", "TYPES_INTEGER", ",", "\"is_foreign_key\"", ":", "True", ",", "\"foreign_key_entity\"", ":", "field", ".", "get", "(", "\"relationship\"", ")", ".", "lower", "(", ")", ",", "\"foreign_key_attribute\"", ":", "\"id\"", "}", "]", "}" ]
https://github.com/pyistanbul/dbpatterns/blob/6936cfa3555bae9ef65296c7f31a6637c0ef5d54/web/dbpatterns/documents/parsers/django_orm.py#L153-L183
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/v8/third_party/jinja2/bccache.py
python
BytecodeCache.set_bucket
(self, bucket)
Put the bucket into the cache.
Put the bucket into the cache.
[ "Put", "the", "bucket", "into", "the", "cache", "." ]
def set_bucket(self, bucket): """Put the bucket into the cache.""" self.dump_bytecode(bucket)
[ "def", "set_bucket", "(", "self", ",", "bucket", ")", ":", "self", ".", "dump_bytecode", "(", "bucket", ")" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/v8/third_party/jinja2/bccache.py#L190-L192
domogik/domogik
fefd584d354875bcb15f351cbc455abffaa6501f
src/domogik/admin/static/libraries/blockly/i18n/dedup_json.py
python
main
()
Parses arguments and iterates over files. Raises: IOError: An I/O error occurred with an input or output file. InputError: Input JSON could not be parsed.
Parses arguments and iterates over files.
[ "Parses", "arguments", "and", "iterates", "over", "files", "." ]
def main(): """Parses arguments and iterates over files. Raises: IOError: An I/O error occurred with an input or output file. InputError: Input JSON could not be parsed. """ # Set up argument parser. parser = argparse.ArgumentParser( description='Removes duplicate key-value pairs from JSON files.') parser.add_argument('--suffix', default='', help='optional suffix for output files; ' 'if empty, files will be changed in place') parser.add_argument('files', nargs='+', help='input files') args = parser.parse_args() # Iterate over files. for filename in args.files: # Read in json using Python libraries. This eliminates duplicates. print('Processing ' + filename + '...') try: with codecs.open(filename, 'r', 'utf-8') as infile: j = json.load(infile) except ValueError, e: print('Error reading ' + filename) raise InputError(file, str(e)) # Built up output strings as an array to make output of delimiters easier. output = [] for key in j: if key != '@metadata': output.append('\t"' + key + '": "' + j[key].replace('\n', '\\n') + '"') # Output results. with codecs.open(filename + args.suffix, 'w', 'utf-8') as outfile: outfile.write('{\n') outfile.write(',\n'.join(output)) outfile.write('\n}\n')
[ "def", "main", "(", ")", ":", "# Set up argument parser.", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Removes duplicate key-value pairs from JSON files.'", ")", "parser", ".", "add_argument", "(", "'--suffix'", ",", "default", "=", "''", ",", "help", "=", "'optional suffix for output files; '", "'if empty, files will be changed in place'", ")", "parser", ".", "add_argument", "(", "'files'", ",", "nargs", "=", "'+'", ",", "help", "=", "'input files'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "# Iterate over files.", "for", "filename", "in", "args", ".", "files", ":", "# Read in json using Python libraries. This eliminates duplicates.", "print", "(", "'Processing '", "+", "filename", "+", "'...'", ")", "try", ":", "with", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf-8'", ")", "as", "infile", ":", "j", "=", "json", ".", "load", "(", "infile", ")", "except", "ValueError", ",", "e", ":", "print", "(", "'Error reading '", "+", "filename", ")", "raise", "InputError", "(", "file", ",", "str", "(", "e", ")", ")", "# Built up output strings as an array to make output of delimiters easier.", "output", "=", "[", "]", "for", "key", "in", "j", ":", "if", "key", "!=", "'@metadata'", ":", "output", ".", "append", "(", "'\\t\"'", "+", "key", "+", "'\": \"'", "+", "j", "[", "key", "]", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", "+", "'\"'", ")", "# Output results.", "with", "codecs", ".", "open", "(", "filename", "+", "args", ".", "suffix", ",", "'w'", ",", "'utf-8'", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "'{\\n'", ")", "outfile", ".", "write", "(", "',\\n'", ".", "join", "(", "output", ")", ")", "outfile", ".", "write", "(", "'\\n}\\n'", ")" ]
https://github.com/domogik/domogik/blob/fefd584d354875bcb15f351cbc455abffaa6501f/src/domogik/admin/static/libraries/blockly/i18n/dedup_json.py#L30-L69
ansible/awx
15c7a3f85b5e948f011c67111c4433a38c4544e9
awx/main/signals.py
python
sync_superuser_status_to_rbac
(instance, **kwargs)
When the is_superuser flag is changed on a user, reflect that in the membership of the System Admnistrator role
When the is_superuser flag is changed on a user, reflect that in the membership of the System Admnistrator role
[ "When", "the", "is_superuser", "flag", "is", "changed", "on", "a", "user", "reflect", "that", "in", "the", "membership", "of", "the", "System", "Admnistrator", "role" ]
def sync_superuser_status_to_rbac(instance, **kwargs): 'When the is_superuser flag is changed on a user, reflect that in the membership of the System Admnistrator role' update_fields = kwargs.get('update_fields', None) if update_fields and 'is_superuser' not in update_fields: return if instance.is_superuser: Role.singleton(ROLE_SINGLETON_SYSTEM_ADMINISTRATOR).members.add(instance) else: Role.singleton(ROLE_SINGLETON_SYSTEM_ADMINISTRATOR).members.remove(instance)
[ "def", "sync_superuser_status_to_rbac", "(", "instance", ",", "*", "*", "kwargs", ")", ":", "update_fields", "=", "kwargs", ".", "get", "(", "'update_fields'", ",", "None", ")", "if", "update_fields", "and", "'is_superuser'", "not", "in", "update_fields", ":", "return", "if", "instance", ".", "is_superuser", ":", "Role", ".", "singleton", "(", "ROLE_SINGLETON_SYSTEM_ADMINISTRATOR", ")", ".", "members", ".", "add", "(", "instance", ")", "else", ":", "Role", ".", "singleton", "(", "ROLE_SINGLETON_SYSTEM_ADMINISTRATOR", ")", ".", "members", ".", "remove", "(", "instance", ")" ]
https://github.com/ansible/awx/blob/15c7a3f85b5e948f011c67111c4433a38c4544e9/awx/main/signals.py#L127-L135
svaarala/duktape
5c5cbcd0d2a7abc1d6b99037de1cb4cf4684cbf3
tools/dukutil.py
python
GenerateC.emitHeader
(self, autogen_by)
Emit file header comments.
Emit file header comments.
[ "Emit", "file", "header", "comments", "." ]
def emitHeader(self, autogen_by): "Emit file header comments." # Note: a timestamp would be nice but it breaks incremental building self.emitLine('/*') self.emitLine(' * Automatically generated by %s, do not edit!' % autogen_by) self.emitLine(' */') self.emitLine('')
[ "def", "emitHeader", "(", "self", ",", "autogen_by", ")", ":", "# Note: a timestamp would be nice but it breaks incremental building", "self", ".", "emitLine", "(", "'/*'", ")", "self", ".", "emitLine", "(", "' * Automatically generated by %s, do not edit!'", "%", "autogen_by", ")", "self", ".", "emitLine", "(", "' */'", ")", "self", ".", "emitLine", "(", "''", ")" ]
https://github.com/svaarala/duktape/blob/5c5cbcd0d2a7abc1d6b99037de1cb4cf4684cbf3/tools/dukutil.py#L118-L125
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/closured/lib/python2.7/lib2to3/btm_utils.py
python
MinNode.get_linear_subpattern
(self)
Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity, i.e. (a|b c) -> (a|b) if b more characteristic than c Returns: The most 'characteristic'(as defined by get_characteristic_subpattern) path for the compiled pattern tree.
Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity,
[ "Drives", "the", "leaf_to_root", "method", ".", "The", "reason", "that", "leaf_to_root", "must", "be", "run", "multiple", "times", "is", "because", "we", "need", "to", "reject", "group", "matches", ";", "for", "example", "the", "alternative", "form", "(", "a", "|", "b", "c", ")", "creates", "a", "group", "[", "b", "c", "]", "that", "needs", "to", "be", "matched", ".", "Since", "matching", "multiple", "linear", "patterns", "overcomes", "the", "automaton", "s", "capabilities", "leaf_to_root", "merges", "each", "group", "into", "a", "single", "choice", "based", "on", "characteristic", "ity" ]
def get_linear_subpattern(self): """Drives the leaf_to_root method. The reason that leaf_to_root must be run multiple times is because we need to reject 'group' matches; for example the alternative form (a | b c) creates a group [b c] that needs to be matched. Since matching multiple linear patterns overcomes the automaton's capabilities, leaf_to_root merges each group into a single choice based on 'characteristic'ity, i.e. (a|b c) -> (a|b) if b more characteristic than c Returns: The most 'characteristic'(as defined by get_characteristic_subpattern) path for the compiled pattern tree. """ for l in self.leaves(): subp = l.leaf_to_root() if subp: return subp
[ "def", "get_linear_subpattern", "(", "self", ")", ":", "for", "l", "in", "self", ".", "leaves", "(", ")", ":", "subp", "=", "l", ".", "leaf_to_root", "(", ")", "if", "subp", ":", "return", "subp" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/lib2to3/btm_utils.py#L75-L94
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/stats/handlers.py
python
update_results
(collection, m, r, stat_query, field, campaign_stats)
return campaign_stats
Update campaign results. :param collection: The collection to get campaign results for. :type collection: str :param m: The map. :type m: :class:`bson.Code` :param r: The reduce. :type r: :clas:`bson.Code` :param stat_query: The query to use in the mapreduce. :type stat_query: dict :param field: The field to update. :type field: str :param campaign_stats: The campaign stats. :type campaign_stats: dict :returns: dict
Update campaign results.
[ "Update", "campaign", "results", "." ]
def update_results(collection, m, r, stat_query, field, campaign_stats): """ Update campaign results. :param collection: The collection to get campaign results for. :type collection: str :param m: The map. :type m: :class:`bson.Code` :param r: The reduce. :type r: :clas:`bson.Code` :param stat_query: The query to use in the mapreduce. :type stat_query: dict :param field: The field to update. :type field: str :param campaign_stats: The campaign stats. :type campaign_stats: dict :returns: dict """ if collection.find().count() > 0: results = collection.inline_map_reduce(m,r, query=stat_query) for result in results: if result["_id"] != None: if result["_id"] not in campaign_stats: campaign_stats[result["_id"]] = zero_campaign() campaign_stats[result["_id"]][field] = result["value"]["count"] return campaign_stats
[ "def", "update_results", "(", "collection", ",", "m", ",", "r", ",", "stat_query", ",", "field", ",", "campaign_stats", ")", ":", "if", "collection", ".", "find", "(", ")", ".", "count", "(", ")", ">", "0", ":", "results", "=", "collection", ".", "inline_map_reduce", "(", "m", ",", "r", ",", "query", "=", "stat_query", ")", "for", "result", "in", "results", ":", "if", "result", "[", "\"_id\"", "]", "!=", "None", ":", "if", "result", "[", "\"_id\"", "]", "not", "in", "campaign_stats", ":", "campaign_stats", "[", "result", "[", "\"_id\"", "]", "]", "=", "zero_campaign", "(", ")", "campaign_stats", "[", "result", "[", "\"_id\"", "]", "]", "[", "field", "]", "=", "result", "[", "\"value\"", "]", "[", "\"count\"", "]", "return", "campaign_stats" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/stats/handlers.py#L97-L123
leffss/devops
0feba3160cc272734da74f727b6a8e37e656eb4a
util/ansible_api.py
python
AnsibleAPI.__init__
(self, check=False, remote_user='root', private_key_file=None, forks=cpu_count() * 2, extra_vars=None, dynamic_inventory=None, callback=None)
可以选择性的针对业务场景在初始化中加入用户定义的参数
可以选择性的针对业务场景在初始化中加入用户定义的参数
[ "可以选择性的针对业务场景在初始化中加入用户定义的参数" ]
def __init__(self, check=False, remote_user='root', private_key_file=None, forks=cpu_count() * 2, extra_vars=None, dynamic_inventory=None, callback=None): """ 可以选择性的针对业务场景在初始化中加入用户定义的参数 """ # 运行前检查,即命令行的-C self.check = check # key登陆文件 self.private_key_file = private_key_file # 并发连接数 self.forks = forks # 远端登陆用户 self.remote_user = remote_user # 数据解析器 self.loader = DataLoader() # 必须有此参数,假如通过了公钥信任,可以为空dict self.passwords = {} # 回调结果 self.results_callback = callback # 组和主机相关,处理动态资产 self.dynamic_inventory = dynamic_inventory # 变量管理器 self.variable_manager = VariableManager(loader=self.loader, inventory=self.dynamic_inventory) self.variable_manager._extra_vars = extra_vars if extra_vars is not None else {} # 自定义选项的初始化 self.__init_options()
[ "def", "__init__", "(", "self", ",", "check", "=", "False", ",", "remote_user", "=", "'root'", ",", "private_key_file", "=", "None", ",", "forks", "=", "cpu_count", "(", ")", "*", "2", ",", "extra_vars", "=", "None", ",", "dynamic_inventory", "=", "None", ",", "callback", "=", "None", ")", ":", "# 运行前检查,即命令行的-C", "self", ".", "check", "=", "check", "# key登陆文件", "self", ".", "private_key_file", "=", "private_key_file", "# 并发连接数", "self", ".", "forks", "=", "forks", "# 远端登陆用户", "self", ".", "remote_user", "=", "remote_user", "# 数据解析器", "self", ".", "loader", "=", "DataLoader", "(", ")", "# 必须有此参数,假如通过了公钥信任,可以为空dict", "self", ".", "passwords", "=", "{", "}", "# 回调结果", "self", ".", "results_callback", "=", "callback", "# 组和主机相关,处理动态资产", "self", ".", "dynamic_inventory", "=", "dynamic_inventory", "# 变量管理器", "self", ".", "variable_manager", "=", "VariableManager", "(", "loader", "=", "self", ".", "loader", ",", "inventory", "=", "self", ".", "dynamic_inventory", ")", "self", ".", "variable_manager", ".", "_extra_vars", "=", "extra_vars", "if", "extra_vars", "is", "not", "None", "else", "{", "}", "# 自定义选项的初始化", "self", ".", "__init_options", "(", ")" ]
https://github.com/leffss/devops/blob/0feba3160cc272734da74f727b6a8e37e656eb4a/util/ansible_api.py#L77-L102
JoneXiong/DjangoX
c2a723e209ef13595f571923faac7eb29e4c8150
xadmin/wizard/views.py
python
StepsHelper.prev
(self)
return self._wizard.get_prev_step()
Returns the previous step.
Returns the previous step.
[ "Returns", "the", "previous", "step", "." ]
def prev(self): "Returns the previous step." return self._wizard.get_prev_step()
[ "def", "prev", "(", "self", ")", ":", "return", "self", ".", "_wizard", ".", "get_prev_step", "(", ")" ]
https://github.com/JoneXiong/DjangoX/blob/c2a723e209ef13595f571923faac7eb29e4c8150/xadmin/wizard/views.py#L79-L81
JoneXiong/PyRedisAdmin
130107d51ae4b84fbfdd89d7e748cedb721614dd
redis/connection.py
python
BlockingConnectionPool.release
(self, connection)
Releases the connection back to the pool.
Releases the connection back to the pool.
[ "Releases", "the", "connection", "back", "to", "the", "pool", "." ]
def release(self, connection): "Releases the connection back to the pool." # Make sure we haven't changed process. self._checkpid() if connection.pid != self.pid: return # Put the connection back into the pool. try: self.pool.put_nowait(connection) except Full: # perhaps the pool has been reset() after a fork? regardless, # we don't want this connection pass
[ "def", "release", "(", "self", ",", "connection", ")", ":", "# Make sure we haven't changed process.", "self", ".", "_checkpid", "(", ")", "if", "connection", ".", "pid", "!=", "self", ".", "pid", ":", "return", "# Put the connection back into the pool.", "try", ":", "self", ".", "pool", ".", "put_nowait", "(", "connection", ")", "except", "Full", ":", "# perhaps the pool has been reset() after a fork? regardless,", "# we don't want this connection", "pass" ]
https://github.com/JoneXiong/PyRedisAdmin/blob/130107d51ae4b84fbfdd89d7e748cedb721614dd/redis/connection.py#L999-L1012
GeoNode/geonode
326d70153ad79e1ed831d46a0e3b239d422757a8
geonode/api/api.py
python
GeoserverStyleResource.populate_object
(self, style)
return style
Populate results with necessary fields :param style: Style objects :type style: Style :return:
Populate results with necessary fields
[ "Populate", "results", "with", "necessary", "fields" ]
def populate_object(self, style): """Populate results with necessary fields :param style: Style objects :type style: Style :return: """ style.type = 'sld' return style
[ "def", "populate_object", "(", "self", ",", "style", ")", ":", "style", ".", "type", "=", "'sld'", "return", "style" ]
https://github.com/GeoNode/geonode/blob/326d70153ad79e1ed831d46a0e3b239d422757a8/geonode/api/api.py#L681-L689
Southpaw-TACTIC/TACTIC
ba9b87aef0ee3b3ea51446f25b285ebbca06f62c
3rd_party/python3/site-packages/cherrypy/lib/profiler.py
python
Profiler.statfiles
(self)
return [f for f in os.listdir(self.path) if f.startswith('cp_') and f.endswith('.prof')]
:rtype: list of available profiles.
:rtype: list of available profiles.
[ ":", "rtype", ":", "list", "of", "available", "profiles", "." ]
def statfiles(self): """:rtype: list of available profiles. """ return [f for f in os.listdir(self.path) if f.startswith('cp_') and f.endswith('.prof')]
[ "def", "statfiles", "(", "self", ")", ":", "return", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "self", ".", "path", ")", "if", "f", ".", "startswith", "(", "'cp_'", ")", "and", "f", ".", "endswith", "(", "'.prof'", ")", "]" ]
https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/3rd_party/python3/site-packages/cherrypy/lib/profiler.py#L89-L93
co-meeting/crowy
69843d22af0f738424f51336cf418c57cb0d3cc4
src/conf/__init__.py
python
Server.verify_request
(self, request, consumer, token)
return parameters
Verifies an api call and checks all the parameters.
Verifies an api call and checks all the parameters.
[ "Verifies", "an", "api", "call", "and", "checks", "all", "the", "parameters", "." ]
def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" version = self._get_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters
[ "def", "verify_request", "(", "self", ",", "request", ",", "consumer", ",", "token", ")", ":", "version", "=", "self", ".", "_get_version", "(", "request", ")", "self", ".", "_check_signature", "(", "request", ",", "consumer", ",", "token", ")", "parameters", "=", "request", ".", "get_nonoauth_parameters", "(", ")", "return", "parameters" ]
https://github.com/co-meeting/crowy/blob/69843d22af0f738424f51336cf418c57cb0d3cc4/src/conf/__init__.py#L609-L615
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5/bootstrap/erp5_core/InterfaceTemplateItem/portal_components/interface.erp5.IUploadable.py
python
IUploadable.getSourceFormatTitleList
()
Returns the list of titles of acceptable formats for upload as a list of strings which can be translated and displayed to the user.
Returns the list of titles of acceptable formats for upload as a list of strings which can be translated and displayed to the user.
[ "Returns", "the", "list", "of", "titles", "of", "acceptable", "formats", "for", "upload", "as", "a", "list", "of", "strings", "which", "can", "be", "translated", "and", "displayed", "to", "the", "user", "." ]
def getSourceFormatTitleList(): """ Returns the list of titles of acceptable formats for upload as a list of strings which can be translated and displayed to the user. """
[ "def", "getSourceFormatTitleList", "(", ")", ":" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5/bootstrap/erp5_core/InterfaceTemplateItem/portal_components/interface.erp5.IUploadable.py#L83-L88
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/reloop-closured/lib/python2.7/pickletools.py
python
dis
(pickle, out=None, memo=None, indentlevel=4)
Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined.
Produce a symbolic disassembly of a pickle.
[ "Produce", "a", "symbolic", "disassembly", "of", "a", "pickle", "." ]
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpicker memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
[ "def", "dis", "(", "pickle", ",", "out", "=", "None", ",", "memo", "=", "None", ",", "indentlevel", "=", "4", ")", ":", "# Most of the hair here is for sanity checks, but most of it is needed", "# anyway to detect when a protocol 0 POP takes a MARK off the stack", "# (which in turn is needed to indent MARK blocks correctly).", "stack", "=", "[", "]", "# crude emulation of unpickler stack", "if", "memo", "is", "None", ":", "memo", "=", "{", "}", "# crude emulation of unpicker memo", "maxproto", "=", "-", "1", "# max protocol number seen", "markstack", "=", "[", "]", "# bytecode positions of MARK opcodes", "indentchunk", "=", "' '", "*", "indentlevel", "errormsg", "=", "None", "for", "opcode", ",", "arg", ",", "pos", "in", "genops", "(", "pickle", ")", ":", "if", "pos", "is", "not", "None", ":", "print", ">>", "out", ",", "\"%5d:\"", "%", "pos", ",", "line", "=", "\"%-4s %s%s\"", "%", "(", "repr", "(", "opcode", ".", "code", ")", "[", "1", ":", "-", "1", "]", ",", "indentchunk", "*", "len", "(", "markstack", ")", ",", "opcode", ".", "name", ")", "maxproto", "=", "max", "(", "maxproto", ",", "opcode", ".", "proto", ")", "before", "=", "opcode", ".", "stack_before", "# don't mutate", "after", "=", "opcode", ".", "stack_after", "# don't mutate", "numtopop", "=", "len", "(", "before", ")", "# See whether a MARK should be popped.", "markmsg", "=", "None", "if", "markobject", "in", "before", "or", "(", "opcode", ".", "name", "==", "\"POP\"", "and", "stack", "and", "stack", "[", "-", "1", "]", "is", "markobject", ")", ":", "assert", "markobject", "not", "in", "after", "if", "__debug__", ":", "if", "markobject", "in", "before", ":", "assert", "before", "[", "-", "1", "]", "is", "stackslice", "if", "markstack", ":", "markpos", "=", "markstack", ".", "pop", "(", ")", "if", "markpos", "is", "None", ":", "markmsg", "=", "\"(MARK at unknown opcode offset)\"", "else", ":", "markmsg", "=", "\"(MARK at %d)\"", "%", "markpos", "# Pop everything at and after the topmost markobject.", "while", "stack", "[", "-", "1", "]", "is", "not", "markobject", ":", "stack", ".", "pop", "(", ")", "stack", ".", "pop", "(", ")", "# Stop later code from popping too much.", "try", ":", "numtopop", "=", "before", ".", "index", "(", "markobject", ")", "except", "ValueError", ":", "assert", "opcode", ".", "name", "==", "\"POP\"", "numtopop", "=", "0", "else", ":", "errormsg", "=", "markmsg", "=", "\"no MARK exists on stack\"", "# Check for correct memo usage.", "if", "opcode", ".", "name", "in", "(", "\"PUT\"", ",", "\"BINPUT\"", ",", "\"LONG_BINPUT\"", ")", ":", "assert", "arg", "is", "not", "None", "if", "arg", "in", "memo", ":", "errormsg", "=", "\"memo key %r already defined\"", "%", "arg", "elif", "not", "stack", ":", "errormsg", "=", "\"stack is empty -- can't store into memo\"", "elif", "stack", "[", "-", "1", "]", "is", "markobject", ":", "errormsg", "=", "\"can't store markobject in the memo\"", "else", ":", "memo", "[", "arg", "]", "=", "stack", "[", "-", "1", "]", "elif", "opcode", ".", "name", "in", "(", "\"GET\"", ",", "\"BINGET\"", ",", "\"LONG_BINGET\"", ")", ":", "if", "arg", "in", "memo", ":", "assert", "len", "(", "after", ")", "==", "1", "after", "=", "[", "memo", "[", "arg", "]", "]", "# for better stack emulation", "else", ":", "errormsg", "=", "\"memo key %r has never been stored into\"", "%", "arg", "if", "arg", "is", "not", "None", "or", "markmsg", ":", "# make a mild effort to align arguments", "line", "+=", "' '", "*", "(", "10", "-", "len", "(", "opcode", ".", "name", ")", ")", "if", "arg", "is", "not", "None", ":", "line", "+=", "' '", "+", "repr", "(", "arg", ")", "if", "markmsg", ":", "line", "+=", "' '", "+", "markmsg", "print", ">>", "out", ",", "line", "if", "errormsg", ":", "# Note that we delayed complaining until the offending opcode", "# was printed.", "raise", "ValueError", "(", "errormsg", ")", "# Emulate the stack effects.", "if", "len", "(", "stack", ")", "<", "numtopop", ":", "raise", "ValueError", "(", "\"tries to pop %d items from stack with \"", "\"only %d items\"", "%", "(", "numtopop", ",", "len", "(", "stack", ")", ")", ")", "if", "numtopop", ":", "del", "stack", "[", "-", "numtopop", ":", "]", "if", "markobject", "in", "after", ":", "assert", "markobject", "not", "in", "before", "markstack", ".", "append", "(", "pos", ")", "stack", ".", "extend", "(", "after", ")", "print", ">>", "out", ",", "\"highest protocol among opcodes =\"", ",", "maxproto", "if", "stack", ":", "raise", "ValueError", "(", "\"stack not empty after STOP: %r\"", "%", "stack", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/pickletools.py#L1891-L2025
ayojs/ayo
45a1c8cf6384f5bcc81d834343c3ed9d78b97df3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py
python
OrderedDict.keys
(self)
return list(self)
od.keys() -> list of keys in od
od.keys() -> list of keys in od
[ "od", ".", "keys", "()", "-", ">", "list", "of", "keys", "in", "od" ]
def keys(self): 'od.keys() -> list of keys in od' return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L143-L145
ibuler/jumpserver
0aa43c7cabc012cf02f39826fdce80f4b7b7654b
jperm/ansible_api.py
python
MyPlaybook.raw_results
(self)
return self.results
get the raw results after playbook run.
get the raw results after playbook run.
[ "get", "the", "raw", "results", "after", "playbook", "run", "." ]
def raw_results(self): """ get the raw results after playbook run. """ return self.results
[ "def", "raw_results", "(", "self", ")", ":", "return", "self", ".", "results" ]
https://github.com/ibuler/jumpserver/blob/0aa43c7cabc012cf02f39826fdce80f4b7b7654b/jperm/ansible_api.py#L465-L469
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_internal/operations/check.py
python
check_install_conflicts
(to_install)
return ( package_set, check_package_set( package_set, should_ignore=lambda name: name not in whitelist ) )
For checking if the dependency graph would be consistent after \ installing given requirements
For checking if the dependency graph would be consistent after \ installing given requirements
[ "For", "checking", "if", "the", "dependency", "graph", "would", "be", "consistent", "after", "\\", "installing", "given", "requirements" ]
def check_install_conflicts(to_install): # type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult] """For checking if the dependency graph would be consistent after \ installing given requirements """ # Start from the current state package_set, _ = create_package_set_from_installed() # Install packages would_be_installed = _simulate_installation_of(to_install, package_set) # Only warn about directly-dependent packages; create a whitelist of them whitelist = _create_whitelist(would_be_installed, package_set) return ( package_set, check_package_set( package_set, should_ignore=lambda name: name not in whitelist ) )
[ "def", "check_install_conflicts", "(", "to_install", ")", ":", "# type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult]", "# Start from the current state", "package_set", ",", "_", "=", "create_package_set_from_installed", "(", ")", "# Install packages", "would_be_installed", "=", "_simulate_installation_of", "(", "to_install", ",", "package_set", ")", "# Only warn about directly-dependent packages; create a whitelist of them", "whitelist", "=", "_create_whitelist", "(", "would_be_installed", ",", "package_set", ")", "return", "(", "package_set", ",", "check_package_set", "(", "package_set", ",", "should_ignore", "=", "lambda", "name", ":", "name", "not", "in", "whitelist", ")", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/operations/check.py#L104-L122
KhronosGroup/OpenCL-Docs
2f8b8140b71cfbc9698678f74fb35b6ab6d46f66
scripts/generator.py
python
regSortOrderKey
(feature)
return feature.sortorder
Sort key for regSortFeatures - key is the sortorder attribute.
Sort key for regSortFeatures - key is the sortorder attribute.
[ "Sort", "key", "for", "regSortFeatures", "-", "key", "is", "the", "sortorder", "attribute", "." ]
def regSortOrderKey(feature): """Sort key for regSortFeatures - key is the sortorder attribute.""" # print("regSortOrderKey {} -> {}".format(feature.name, feature.sortorder)) return feature.sortorder
[ "def", "regSortOrderKey", "(", "feature", ")", ":", "# print(\"regSortOrderKey {} -> {}\".format(feature.name, feature.sortorder))", "return", "feature", ".", "sortorder" ]
https://github.com/KhronosGroup/OpenCL-Docs/blob/2f8b8140b71cfbc9698678f74fb35b6ab6d46f66/scripts/generator.py#L68-L72
aws-samples/lambda-refarch-fileprocessing
38896310187d090e25adf08b57c5a252979de487
src/sentiment/sentiment.py
python
check_s3_object_size
(bucket, key_name)
return(size)
Take in a bucket and key and return the number of bytes Parameters ---------- bucket: string, required Bucket name where object is stored key_name: string, required Key name of object Returns ------- size: integer Size of key_name in bucket
Take in a bucket and key and return the number of bytes
[ "Take", "in", "a", "bucket", "and", "key", "and", "return", "the", "number", "of", "bytes" ]
def check_s3_object_size(bucket, key_name): """Take in a bucket and key and return the number of bytes Parameters ---------- bucket: string, required Bucket name where object is stored key_name: string, required Key name of object Returns ------- size: integer Size of key_name in bucket """ tracer.put_metadata('object', f's3://{bucket}/{key_name}') try: size = s3_resource.Object(bucket, key_name).content_length tracer.put_metadata('object_size', size) except Exception as e: logger.error(f'Error: {str(e)}') size = 'NaN' tracer.put_metadata('object_size', size) return(size)
[ "def", "check_s3_object_size", "(", "bucket", ",", "key_name", ")", ":", "tracer", ".", "put_metadata", "(", "'object'", ",", "f's3://{bucket}/{key_name}'", ")", "try", ":", "size", "=", "s3_resource", ".", "Object", "(", "bucket", ",", "key_name", ")", ".", "content_length", "tracer", ".", "put_metadata", "(", "'object_size'", ",", "size", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "f'Error: {str(e)}'", ")", "size", "=", "'NaN'", "tracer", ".", "put_metadata", "(", "'object_size'", ",", "size", ")", "return", "(", "size", ")" ]
https://github.com/aws-samples/lambda-refarch-fileprocessing/blob/38896310187d090e25adf08b57c5a252979de487/src/sentiment/sentiment.py#L37-L64
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_AppendFiltersForMSBuild
(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, platforms, filter_group, source_group)
Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appeneded.
Creates the list of filters and sources to be added in the filter file.
[ "Creates", "the", "list", "of", "filters", "and", "sources", "to", "be", "added", "in", "the", "filter", "file", "." ]
def _AppendFiltersForMSBuild(parent_filter_name, sources, rule_dependencies, extension_to_rule_name, platforms, filter_group, source_group): """Creates the list of filters and sources to be added in the filter file. Args: parent_filter_name: The name of the filter under which the sources are found. sources: The hierarchy of filters and sources to process. extension_to_rule_name: A dictionary mapping file extensions to rules. filter_group: The list to which filter entries will be appended. source_group: The list to which source entries will be appeneded. """ for source in sources: if isinstance(source, MSVSProject.Filter): # We have a sub-filter. Create the name of that sub-filter. if not parent_filter_name: filter_name = source.name else: filter_name = '%s\\%s' % (parent_filter_name, source.name) # Add the filter to the group. filter_group.append( ['Filter', {'Include': filter_name}, ['UniqueIdentifier', MSVSNew.MakeGuid(source.name)]]) # Recurse and add its dependents. _AppendFiltersForMSBuild(filter_name, source.contents, rule_dependencies, extension_to_rule_name, platforms, filter_group, source_group) else: # It's a source. Create a source entry. _, element = _MapFileToMsBuildSourceType(source, rule_dependencies, extension_to_rule_name, platforms) source_entry = [element, {'Include': source}] # Specify the filter it is part of, if any. if parent_filter_name: source_entry.append(['Filter', parent_filter_name]) source_group.append(source_entry)
[ "def", "_AppendFiltersForMSBuild", "(", "parent_filter_name", ",", "sources", ",", "rule_dependencies", ",", "extension_to_rule_name", ",", "platforms", ",", "filter_group", ",", "source_group", ")", ":", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "source", ",", "MSVSProject", ".", "Filter", ")", ":", "# We have a sub-filter. Create the name of that sub-filter.", "if", "not", "parent_filter_name", ":", "filter_name", "=", "source", ".", "name", "else", ":", "filter_name", "=", "'%s\\\\%s'", "%", "(", "parent_filter_name", ",", "source", ".", "name", ")", "# Add the filter to the group.", "filter_group", ".", "append", "(", "[", "'Filter'", ",", "{", "'Include'", ":", "filter_name", "}", ",", "[", "'UniqueIdentifier'", ",", "MSVSNew", ".", "MakeGuid", "(", "source", ".", "name", ")", "]", "]", ")", "# Recurse and add its dependents.", "_AppendFiltersForMSBuild", "(", "filter_name", ",", "source", ".", "contents", ",", "rule_dependencies", ",", "extension_to_rule_name", ",", "platforms", ",", "filter_group", ",", "source_group", ")", "else", ":", "# It's a source. Create a source entry.", "_", ",", "element", "=", "_MapFileToMsBuildSourceType", "(", "source", ",", "rule_dependencies", ",", "extension_to_rule_name", ",", "platforms", ")", "source_entry", "=", "[", "element", ",", "{", "'Include'", ":", "source", "}", "]", "# Specify the filter it is part of, if any.", "if", "parent_filter_name", ":", "source_entry", ".", "append", "(", "[", "'Filter'", ",", "parent_filter_name", "]", ")", "source_group", ".", "append", "(", "source_entry", ")" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L2080-L2117
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/closured/lib/python2.7/mailbox.py
python
MaildirMessage.get_date
(self)
return self._date
Return delivery date of message, in seconds since the epoch.
Return delivery date of message, in seconds since the epoch.
[ "Return", "delivery", "date", "of", "message", "in", "seconds", "since", "the", "epoch", "." ]
def get_date(self): """Return delivery date of message, in seconds since the epoch.""" return self._date
[ "def", "get_date", "(", "self", ")", ":", "return", "self", ".", "_date" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/mailbox.py#L1462-L1464
dataflownb/dfkernel
825f45a636cc915b491e339e269cfbea7433f460
dfkernel/kernelspec.py
python
make_ipkernel_cmd
(mod='dfkernel_launcher', executable=None, extra_arguments=None, **kw)
return arguments
Build Popen command list for launching an IPython kernel. Parameters ---------- mod : str, optional (default 'dfkernel') A string of an IPython module whose __main__ starts an IPython kernel executable : str, optional (default sys.executable) The Python executable to use for the kernel process. extra_arguments : list, optional A list of extra arguments to pass when executing the launch code. Returns ------- A Popen command list
Build Popen command list for launching an IPython kernel.
[ "Build", "Popen", "command", "list", "for", "launching", "an", "IPython", "kernel", "." ]
def make_ipkernel_cmd(mod='dfkernel_launcher', executable=None, extra_arguments=None, **kw): """Build Popen command list for launching an IPython kernel. Parameters ---------- mod : str, optional (default 'dfkernel') A string of an IPython module whose __main__ starts an IPython kernel executable : str, optional (default sys.executable) The Python executable to use for the kernel process. extra_arguments : list, optional A list of extra arguments to pass when executing the launch code. Returns ------- A Popen command list """ if executable is None: executable = sys.executable extra_arguments = extra_arguments or [] arguments = [executable, '-m', mod, '-f', '{connection_file}'] arguments.extend(extra_arguments) return arguments
[ "def", "make_ipkernel_cmd", "(", "mod", "=", "'dfkernel_launcher'", ",", "executable", "=", "None", ",", "extra_arguments", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "executable", "is", "None", ":", "executable", "=", "sys", ".", "executable", "extra_arguments", "=", "extra_arguments", "or", "[", "]", "arguments", "=", "[", "executable", ",", "'-m'", ",", "mod", ",", "'-f'", ",", "'{connection_file}'", "]", "arguments", ".", "extend", "(", "extra_arguments", ")", "return", "arguments" ]
https://github.com/dataflownb/dfkernel/blob/825f45a636cc915b491e339e269cfbea7433f460/dfkernel/kernelspec.py#L25-L50
catmaid/CATMAID
9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf
django/applications/catmaid/control/ontology.py
python
remove_all_links_from_ontology
(request:HttpRequest, project_id=None)
return JsonResponse({'deleted_links': removed_links})
Removes all class-class links for a given project.
Removes all class-class links for a given project.
[ "Removes", "all", "class", "-", "class", "links", "for", "a", "given", "project", "." ]
def remove_all_links_from_ontology(request:HttpRequest, project_id=None) -> JsonResponse: """ Removes all class-class links for a given project. """ cc_q = ClassClass.objects.filter(user=request.user, project_id = project_id) removed_links = [] for cc in cc_q: removed_links.append(cc.id) cc_q.delete() return JsonResponse({'deleted_links': removed_links})
[ "def", "remove_all_links_from_ontology", "(", "request", ":", "HttpRequest", ",", "project_id", "=", "None", ")", "->", "JsonResponse", ":", "cc_q", "=", "ClassClass", ".", "objects", ".", "filter", "(", "user", "=", "request", ".", "user", ",", "project_id", "=", "project_id", ")", "removed_links", "=", "[", "]", "for", "cc", "in", "cc_q", ":", "removed_links", ".", "append", "(", "cc", ".", "id", ")", "cc_q", ".", "delete", "(", ")", "return", "JsonResponse", "(", "{", "'deleted_links'", ":", "removed_links", "}", ")" ]
https://github.com/catmaid/CATMAID/blob/9f3312f2eacfc6fab48e4c6f1bd24672cc9c9ecf/django/applications/catmaid/control/ontology.py#L630-L641
onlytiancai/codesnip
9852cb181ca2fe44dada08adecacf78ca7fe5d70
python/littledb/littledb.py
python
Db.load
(self)
加载库
加载库
[ "加载库" ]
def load(self): '加载库' if not os.path.exists(self.db_path): raise Exception('%s is not exist' % self.db_path)
[ "def", "load", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "db_path", ")", ":", "raise", "Exception", "(", "'%s is not exist'", "%", "self", ".", "db_path", ")" ]
https://github.com/onlytiancai/codesnip/blob/9852cb181ca2fe44dada08adecacf78ca7fe5d70/python/littledb/littledb.py#L28-L31
mtianyan/xadmin_ueditor_django2.2
fc4461cb72c3ed92b63d35de685afbd76a67c38b
xadmin_2.0.1/views/list.py
python
ListAdminView.get_ordering_field_columns
(self)
return ordering_fields
Returns a OrderedDict of ordering field column numbers and asc/desc
Returns a OrderedDict of ordering field column numbers and asc/desc
[ "Returns", "a", "OrderedDict", "of", "ordering", "field", "column", "numbers", "and", "asc", "/", "desc" ]
def get_ordering_field_columns(self): """ Returns a OrderedDict of ordering field column numbers and asc/desc """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = OrderedDict() if ORDER_VAR not in self.params or not self.params[ORDER_VAR]: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: order_type = 'asc' for attr in self.list_display: if self.get_ordering_field(attr) == field: ordering_fields[field] = order_type break else: for p in self.params[ORDER_VAR].split('.'): none, pfx, field_name = p.rpartition('-') ordering_fields[field_name] = 'desc' if pfx == '-' else 'asc' return ordering_fields
[ "def", "get_ordering_field_columns", "(", "self", ")", ":", "# We must cope with more than one column having the same underlying sort", "# field, so we base things on column numbers.", "ordering", "=", "self", ".", "_get_default_ordering", "(", ")", "ordering_fields", "=", "OrderedDict", "(", ")", "if", "ORDER_VAR", "not", "in", "self", ".", "params", "or", "not", "self", ".", "params", "[", "ORDER_VAR", "]", ":", "# for ordering specified on ModelAdmin or model Meta, we don't know", "# the right column numbers absolutely, because there might be more", "# than one column associated with that ordering, so we guess.", "for", "field", "in", "ordering", ":", "if", "field", ".", "startswith", "(", "'-'", ")", ":", "field", "=", "field", "[", "1", ":", "]", "order_type", "=", "'desc'", "else", ":", "order_type", "=", "'asc'", "for", "attr", "in", "self", ".", "list_display", ":", "if", "self", ".", "get_ordering_field", "(", "attr", ")", "==", "field", ":", "ordering_fields", "[", "field", "]", "=", "order_type", "break", "else", ":", "for", "p", "in", "self", ".", "params", "[", "ORDER_VAR", "]", ".", "split", "(", "'.'", ")", ":", "none", ",", "pfx", ",", "field_name", "=", "p", ".", "rpartition", "(", "'-'", ")", "ordering_fields", "[", "field_name", "]", "=", "'desc'", "if", "pfx", "==", "'-'", "else", "'asc'", "return", "ordering_fields" ]
https://github.com/mtianyan/xadmin_ueditor_django2.2/blob/fc4461cb72c3ed92b63d35de685afbd76a67c38b/xadmin_2.0.1/views/list.py#L309-L336
basnijholt/home-assistant-config
ae69265f1b9bb904e884e985b99d5d2cbaa77f82
custom_components/kef_custom/select.py
python
MediaSelect.async_update
(self, **kwargs)
Update the select entity with the latest DSP settings.
Update the select entity with the latest DSP settings.
[ "Update", "the", "select", "entity", "with", "the", "latest", "DSP", "settings", "." ]
async def async_update(self, **kwargs): """Update the select entity with the latest DSP settings.""" self._attr_current_option = option_to_str(self._speaker.dsp[self._dsp_attr]) self.async_write_ha_state()
[ "async", "def", "async_update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_attr_current_option", "=", "option_to_str", "(", "self", ".", "_speaker", ".", "dsp", "[", "self", ".", "_dsp_attr", "]", ")", "self", ".", "async_write_ha_state", "(", ")" ]
https://github.com/basnijholt/home-assistant-config/blob/ae69265f1b9bb904e884e985b99d5d2cbaa77f82/custom_components/kef_custom/select.py#L124-L127
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py
python
Process.__init__
(self, dwProcessId, hProcess = None, fileName = None)
@type dwProcessId: int @param dwProcessId: Global process ID. @type hProcess: L{ProcessHandle} @param hProcess: Handle to the process. @type fileName: str @param fileName: (Optional) Filename of the main module.
@type dwProcessId: int @param dwProcessId: Global process ID.
[ "@type", "dwProcessId", ":", "int", "@param", "dwProcessId", ":", "Global", "process", "ID", "." ]
def __init__(self, dwProcessId, hProcess = None, fileName = None): """ @type dwProcessId: int @param dwProcessId: Global process ID. @type hProcess: L{ProcessHandle} @param hProcess: Handle to the process. @type fileName: str @param fileName: (Optional) Filename of the main module. """ _ThreadContainer.__init__(self) _ModuleContainer.__init__(self) self.dwProcessId = dwProcessId self.hProcess = hProcess self.fileName = fileName
[ "def", "__init__", "(", "self", ",", "dwProcessId", ",", "hProcess", "=", "None", ",", "fileName", "=", "None", ")", ":", "_ThreadContainer", ".", "__init__", "(", "self", ")", "_ModuleContainer", ".", "__init__", "(", "self", ")", "self", ".", "dwProcessId", "=", "dwProcessId", "self", ".", "hProcess", "=", "hProcess", "self", ".", "fileName", "=", "fileName" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py#L153-L169
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/connectionpool.py
python
HTTPConnectionPool._raise_timeout
(self, err, url, timeout_value)
Is the error actually a timeout? Will raise a ReadTimeout or pass
Is the error actually a timeout? Will raise a ReadTimeout or pass
[ "Is", "the", "error", "actually", "a", "timeout?", "Will", "raise", "a", "ReadTimeout", "or", "pass" ]
def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, 'errno') and err.errno in _blocking_errnos: raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python < 2.7.4 raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
[ "def", "_raise_timeout", "(", "self", ",", "err", ",", "url", ",", "timeout_value", ")", ":", "if", "isinstance", "(", "err", ",", "SocketTimeout", ")", ":", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")", "# See the above comment about EAGAIN in Python 3. In Python 2 we have", "# to specifically catch it and throw the timeout error", "if", "hasattr", "(", "err", ",", "'errno'", ")", "and", "err", ".", "errno", "in", "_blocking_errnos", ":", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")", "# Catch possible read timeouts thrown as SSL errors. If not the", "# case, rethrow the original. We need to do this because of:", "# http://bugs.python.org/issue10272", "if", "'timed out'", "in", "str", "(", "err", ")", "or", "'did not complete (read)'", "in", "str", "(", "err", ")", ":", "# Python < 2.7.4", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "timeout_value", ")" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/urllib3/connectionpool.py#L303-L318
alex-cory/fasthacks
72b099f11df2e5640d61e55c80706c3b234eacbe
notes/JavaScript/nodejs/nodeJS_Lynda/chap09/01/start/node_modules/connect-mongo/node_modules/mongodb/upload.py
python
CheckReviewer
(reviewer)
Validate a reviewer -- either a nickname or an email addres. Args: reviewer: A nickname or an email address. Calls ErrorExit() if it is an invalid email address.
Validate a reviewer -- either a nickname or an email addres.
[ "Validate", "a", "reviewer", "--", "either", "a", "nickname", "or", "an", "email", "addres", "." ]
def CheckReviewer(reviewer): """Validate a reviewer -- either a nickname or an email addres. Args: reviewer: A nickname or an email address. Calls ErrorExit() if it is an invalid email address. """ if "@" not in reviewer: return # Assume nickname parts = reviewer.split("@") if len(parts) > 2: ErrorExit("Invalid email address: %r" % reviewer) assert len(parts) == 2 if "." not in parts[1]: ErrorExit("Invalid email address: %r" % reviewer)
[ "def", "CheckReviewer", "(", "reviewer", ")", ":", "if", "\"@\"", "not", "in", "reviewer", ":", "return", "# Assume nickname", "parts", "=", "reviewer", ".", "split", "(", "\"@\"", ")", "if", "len", "(", "parts", ")", ">", "2", ":", "ErrorExit", "(", "\"Invalid email address: %r\"", "%", "reviewer", ")", "assert", "len", "(", "parts", ")", "==", "2", "if", "\".\"", "not", "in", "parts", "[", "1", "]", ":", "ErrorExit", "(", "\"Invalid email address: %r\"", "%", "reviewer", ")" ]
https://github.com/alex-cory/fasthacks/blob/72b099f11df2e5640d61e55c80706c3b234eacbe/notes/JavaScript/nodejs/nodeJS_Lynda/chap09/01/start/node_modules/connect-mongo/node_modules/mongodb/upload.py#L2022-L2037
virtual-world-framework/vwf
49d3f906f61c7d8f5f472d28a51400994ddb56cd
support/build/Pygments-1.4/pygments/formatters/html.py
python
escape_html
(text, table=_escape_html_table)
return text.translate(table)
Escape &, <, > as well as single and double quotes for HTML.
Escape &, <, > as well as single and double quotes for HTML.
[ "Escape", "&", "<", ">", "as", "well", "as", "single", "and", "double", "quotes", "for", "HTML", "." ]
def escape_html(text, table=_escape_html_table): """Escape &, <, > as well as single and double quotes for HTML.""" return text.translate(table)
[ "def", "escape_html", "(", "text", ",", "table", "=", "_escape_html_table", ")", ":", "return", "text", ".", "translate", "(", "table", ")" ]
https://github.com/virtual-world-framework/vwf/blob/49d3f906f61c7d8f5f472d28a51400994ddb56cd/support/build/Pygments-1.4/pygments/formatters/html.py#L32-L34
openlayers/ol2
ab7a809ebad7055d9ada4170aed582d7be4a7b77
tools/BeautifulSoup.py
python
Tag.findAll
(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
return self._findAll(name, attrs, text, limit, generator, **kwargs)
Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.
Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have.
[ "Extracts", "a", "list", "of", "Tag", "objects", "that", "match", "the", "given", "criteria", ".", "You", "can", "specify", "the", "name", "of", "the", "Tag", "and", "any", "attributes", "you", "want", "the", "Tag", "to", "have", "." ]
def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.recursiveChildGenerator if not recursive: generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs)
[ "def", "findAll", "(", "self", ",", "name", "=", "None", ",", "attrs", "=", "{", "}", ",", "recursive", "=", "True", ",", "text", "=", "None", ",", "limit", "=", "None", ",", "*", "*", "kwargs", ")", ":", "generator", "=", "self", ".", "recursiveChildGenerator", "if", "not", "recursive", ":", "generator", "=", "self", ".", "childGenerator", "return", "self", ".", "_findAll", "(", "name", ",", "attrs", ",", "text", ",", "limit", ",", "generator", ",", "*", "*", "kwargs", ")" ]
https://github.com/openlayers/ol2/blob/ab7a809ebad7055d9ada4170aed582d7be4a7b77/tools/BeautifulSoup.py#L634-L648
Opentrons/opentrons
466e0567065d8773a81c25cd1b5c7998e00adf2c
robot-server/robot_server/protocols/protocol_store.py
python
ProtocolStore.upsert
(self, resource: ProtocolResource)
Upsert a protocol resource into the store.
Upsert a protocol resource into the store.
[ "Upsert", "a", "protocol", "resource", "into", "the", "store", "." ]
def upsert(self, resource: ProtocolResource) -> None: """Upsert a protocol resource into the store.""" self._protocols_by_id[resource.protocol_id] = resource
[ "def", "upsert", "(", "self", ",", "resource", ":", "ProtocolResource", ")", "->", "None", ":", "self", ".", "_protocols_by_id", "[", "resource", ".", "protocol_id", "]", "=", "resource" ]
https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/robot-server/robot_server/protocols/protocol_store.py#L36-L38
chagel/CNPROG
07fea9955202f0b23221081ca171192a6c7350f2
django_authopenid/forms.py
python
OpenidAuthForm.clean_next
(self)
validate next url
validate next url
[ "validate", "next", "url" ]
def clean_next(self): """ validate next url """ if 'next' in self.cleaned_data and \ self.cleaned_data['next'] != "": self.cleaned_data['next'] = clean_next(self.cleaned_data['next']) return self.cleaned_data['next']
[ "def", "clean_next", "(", "self", ")", ":", "if", "'next'", "in", "self", ".", "cleaned_data", "and", "self", ".", "cleaned_data", "[", "'next'", "]", "!=", "\"\"", ":", "self", ".", "cleaned_data", "[", "'next'", "]", "=", "clean_next", "(", "self", ".", "cleaned_data", "[", "'next'", "]", ")", "return", "self", ".", "cleaned_data", "[", "'next'", "]" ]
https://github.com/chagel/CNPROG/blob/07fea9955202f0b23221081ca171192a6c7350f2/django_authopenid/forms.py#L133-L138
redapple0204/my-boring-python
1ab378e9d4f39ad920ff542ef3b2db68f0575a98
pythonenv3.8/lib/python3.8/site-packages/setuptools/command/upload.py
python
upload._prompt_for_password
(self)
Prompt for a password on the tty. Suppress Exceptions.
Prompt for a password on the tty. Suppress Exceptions.
[ "Prompt", "for", "a", "password", "on", "the", "tty", ".", "Suppress", "Exceptions", "." ]
def _prompt_for_password(self): """ Prompt for a password on the tty. Suppress Exceptions. """ try: return getpass.getpass() except (Exception, KeyboardInterrupt): pass
[ "def", "_prompt_for_password", "(", "self", ")", ":", "try", ":", "return", "getpass", ".", "getpass", "(", ")", "except", "(", "Exception", ",", "KeyboardInterrupt", ")", ":", "pass" ]
https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/setuptools/command/upload.py#L189-L196
nodejs/quic
5baab3f3a05548d3b51bea98868412b08766e34d
tools/gyp/pylib/gyp/xcodeproj_file.py
python
PBXProject.RootGroupForPath
(self, path)
return (self.SourceGroup(), True)
Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False).
Returns a PBXGroup child of this object to which path should be added.
[ "Returns", "a", "PBXGroup", "child", "of", "this", "object", "to", "which", "path", "should", "be", "added", "." ]
def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree != None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True)
[ "def", "RootGroupForPath", "(", "self", ",", "path", ")", ":", "# TODO(mark): make this a class variable and bind to self on call?", "# Also, this list is nowhere near exhaustive.", "# INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by", "# gyp.generator.xcode. There should probably be some way for that module", "# to push the names in, rather than having to hard-code them here.", "source_tree_groups", "=", "{", "'DERIVED_FILE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'INTERMEDIATE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'PROJECT_DERIVED_FILE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "'SHARED_INTERMEDIATE_DIR'", ":", "(", "self", ".", "IntermediatesGroup", ",", "True", ")", ",", "}", "(", "source_tree", ",", "path", ")", "=", "SourceTreeAndPathFromPath", "(", "path", ")", "if", "source_tree", "!=", "None", "and", "source_tree", "in", "source_tree_groups", ":", "(", "group_func", ",", "hierarchical", ")", "=", "source_tree_groups", "[", "source_tree", "]", "group", "=", "group_func", "(", ")", "return", "(", "group", ",", "hierarchical", ")", "# TODO(mark): make additional choices based on file extension.", "return", "(", "self", ".", "SourceGroup", "(", ")", ",", "True", ")" ]
https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/tools/gyp/pylib/gyp/xcodeproj_file.py#L2646-L2681
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py
python
HardwareBreakpoint.__set_bp
(self, aThread)
Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object.
Sets this breakpoint in the debug registers.
[ "Sets", "this", "breakpoint", "in", "the", "debug", "registers", "." ]
def __set_bp(self, aThread): """ Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__slot is None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) self.__slot = DebugRegister.find_slot(ctx) if self.__slot is None: msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread.get_tid() raise RuntimeError(msg) DebugRegister.set_bp(ctx, self.__slot, self.get_address(), self.__trigger, self.__watch) aThread.set_context(ctx) finally: aThread.resume()
[ "def", "__set_bp", "(", "self", ",", "aThread", ")", ":", "if", "self", ".", "__slot", "is", "None", ":", "aThread", ".", "suspend", "(", ")", "try", ":", "ctx", "=", "aThread", ".", "get_context", "(", "win32", ".", "CONTEXT_DEBUG_REGISTERS", ")", "self", ".", "__slot", "=", "DebugRegister", ".", "find_slot", "(", "ctx", ")", "if", "self", ".", "__slot", "is", "None", ":", "msg", "=", "\"No available hardware breakpoint slots for thread ID %d\"", "msg", "=", "msg", "%", "aThread", ".", "get_tid", "(", ")", "raise", "RuntimeError", "(", "msg", ")", "DebugRegister", ".", "set_bp", "(", "ctx", ",", "self", ".", "__slot", ",", "self", ".", "get_address", "(", ")", ",", "self", ".", "__trigger", ",", "self", ".", "__watch", ")", "aThread", ".", "set_context", "(", "ctx", ")", "finally", ":", "aThread", ".", "resume", "(", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py#L912-L932
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/l10n_ar/models/account_journal.py
python
AccountJournal._onchange_set_short_name
(self)
Will define the AFIP POS Address field domain taking into account the company configured in the journal The short code of the journal only admit 5 characters, so depending on the size of the pos_number (also max 5) we add or not a prefix to identify sales journal.
Will define the AFIP POS Address field domain taking into account the company configured in the journal The short code of the journal only admit 5 characters, so depending on the size of the pos_number (also max 5) we add or not a prefix to identify sales journal.
[ "Will", "define", "the", "AFIP", "POS", "Address", "field", "domain", "taking", "into", "account", "the", "company", "configured", "in", "the", "journal", "The", "short", "code", "of", "the", "journal", "only", "admit", "5", "characters", "so", "depending", "on", "the", "size", "of", "the", "pos_number", "(", "also", "max", "5", ")", "we", "add", "or", "not", "a", "prefix", "to", "identify", "sales", "journal", "." ]
def _onchange_set_short_name(self): """ Will define the AFIP POS Address field domain taking into account the company configured in the journal The short code of the journal only admit 5 characters, so depending on the size of the pos_number (also max 5) we add or not a prefix to identify sales journal. """ if self.type == 'sale' and self.l10n_ar_afip_pos_number: self.code = "%05i" % self.l10n_ar_afip_pos_number
[ "def", "_onchange_set_short_name", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'sale'", "and", "self", ".", "l10n_ar_afip_pos_number", ":", "self", ".", "code", "=", "\"%05i\"", "%", "self", ".", "l10n_ar_afip_pos_number" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/l10n_ar/models/account_journal.py#L133-L139
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/decimal.py
python
Decimal.__float__
(self)
return float(str(self))
Float representation.
Float representation.
[ "Float", "representation", "." ]
def __float__(self): """Float representation.""" return float(str(self))
[ "def", "__float__", "(", "self", ")", ":", "return", "float", "(", "str", "(", "self", ")", ")" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/decimal.py#L1582-L1584
odoo/odoo
8de8c196a137f4ebbf67d7c7c83fee36f873f5c8
addons/stock/models/stock_move.py
python
StockMove._compute_forecast_information
(self)
Compute forecasted information of the related product by warehouse.
Compute forecasted information of the related product by warehouse.
[ "Compute", "forecasted", "information", "of", "the", "related", "product", "by", "warehouse", "." ]
def _compute_forecast_information(self): """ Compute forecasted information of the related product by warehouse.""" self.forecast_availability = False self.forecast_expected_date = False # Prefetch product info to avoid fetching all product fields self.product_id.read(['type', 'uom_id'], load=False) not_product_moves = self.filtered(lambda move: move.product_id.type != 'product') for move in not_product_moves: move.forecast_availability = move.product_qty product_moves = (self - not_product_moves) outgoing_unreserved_moves_per_warehouse = defaultdict(set) now = fields.Datetime.now() def key_virtual_available(move, incoming=False): warehouse_id = move.location_dest_id.warehouse_id.id if incoming else move.location_id.warehouse_id.id return warehouse_id, max(move.date, now) # Prefetch efficiently virtual_available for _consuming_picking_types draft move. prefetch_virtual_available = defaultdict(set) virtual_available_dict = {} for move in product_moves: if move.picking_type_id.code in self._consuming_picking_types() and move.state == 'draft': prefetch_virtual_available[key_virtual_available(move)].add(move.product_id.id) elif move.picking_type_id.code == 'incoming': prefetch_virtual_available[key_virtual_available(move, incoming=True)].add(move.product_id.id) for key_context, product_ids in prefetch_virtual_available.items(): read_res = self.env['product.product'].browse(product_ids).with_context(warehouse=key_context[0], to_date=key_context[1]).read(['virtual_available']) virtual_available_dict[key_context] = {res['id']: res['virtual_available'] for res in read_res} for move in product_moves: if move.picking_type_id.code in self._consuming_picking_types(): if move.state == 'assigned': move.forecast_availability = move.product_uom._compute_quantity( move.reserved_availability, move.product_id.uom_id, rounding_method='HALF-UP') elif move.state == 'draft': # for move _consuming_picking_types and in draft -> the forecast_availability > 0 if in stock move.forecast_availability = virtual_available_dict[key_virtual_available(move)][move.product_id.id] - move.product_qty elif move.state in ('waiting', 'confirmed', 'partially_available'): outgoing_unreserved_moves_per_warehouse[move.location_id.warehouse_id].add(move.id) elif move.picking_type_id.code == 'incoming': forecast_availability = virtual_available_dict[key_virtual_available(move, incoming=True)][move.product_id.id] if move.state == 'draft': forecast_availability += move.product_qty move.forecast_availability = forecast_availability for warehouse, moves_ids in outgoing_unreserved_moves_per_warehouse.items(): if not warehouse: # No prediction possible if no warehouse. continue moves = self.browse(moves_ids) forecast_info = moves._get_forecast_availability_outgoing(warehouse) for move in moves: move.forecast_availability, move.forecast_expected_date = forecast_info[move]
[ "def", "_compute_forecast_information", "(", "self", ")", ":", "self", ".", "forecast_availability", "=", "False", "self", ".", "forecast_expected_date", "=", "False", "# Prefetch product info to avoid fetching all product fields", "self", ".", "product_id", ".", "read", "(", "[", "'type'", ",", "'uom_id'", "]", ",", "load", "=", "False", ")", "not_product_moves", "=", "self", ".", "filtered", "(", "lambda", "move", ":", "move", ".", "product_id", ".", "type", "!=", "'product'", ")", "for", "move", "in", "not_product_moves", ":", "move", ".", "forecast_availability", "=", "move", ".", "product_qty", "product_moves", "=", "(", "self", "-", "not_product_moves", ")", "outgoing_unreserved_moves_per_warehouse", "=", "defaultdict", "(", "set", ")", "now", "=", "fields", ".", "Datetime", ".", "now", "(", ")", "def", "key_virtual_available", "(", "move", ",", "incoming", "=", "False", ")", ":", "warehouse_id", "=", "move", ".", "location_dest_id", ".", "warehouse_id", ".", "id", "if", "incoming", "else", "move", ".", "location_id", ".", "warehouse_id", ".", "id", "return", "warehouse_id", ",", "max", "(", "move", ".", "date", ",", "now", ")", "# Prefetch efficiently virtual_available for _consuming_picking_types draft move.", "prefetch_virtual_available", "=", "defaultdict", "(", "set", ")", "virtual_available_dict", "=", "{", "}", "for", "move", "in", "product_moves", ":", "if", "move", ".", "picking_type_id", ".", "code", "in", "self", ".", "_consuming_picking_types", "(", ")", "and", "move", ".", "state", "==", "'draft'", ":", "prefetch_virtual_available", "[", "key_virtual_available", "(", "move", ")", "]", ".", "add", "(", "move", ".", "product_id", ".", "id", ")", "elif", "move", ".", "picking_type_id", ".", "code", "==", "'incoming'", ":", "prefetch_virtual_available", "[", "key_virtual_available", "(", "move", ",", "incoming", "=", "True", ")", "]", ".", "add", "(", "move", ".", "product_id", ".", "id", ")", "for", "key_context", ",", "product_ids", "in", "prefetch_virtual_available", ".", "items", "(", ")", ":", "read_res", "=", "self", ".", "env", "[", "'product.product'", "]", ".", "browse", "(", "product_ids", ")", ".", "with_context", "(", "warehouse", "=", "key_context", "[", "0", "]", ",", "to_date", "=", "key_context", "[", "1", "]", ")", ".", "read", "(", "[", "'virtual_available'", "]", ")", "virtual_available_dict", "[", "key_context", "]", "=", "{", "res", "[", "'id'", "]", ":", "res", "[", "'virtual_available'", "]", "for", "res", "in", "read_res", "}", "for", "move", "in", "product_moves", ":", "if", "move", ".", "picking_type_id", ".", "code", "in", "self", ".", "_consuming_picking_types", "(", ")", ":", "if", "move", ".", "state", "==", "'assigned'", ":", "move", ".", "forecast_availability", "=", "move", ".", "product_uom", ".", "_compute_quantity", "(", "move", ".", "reserved_availability", ",", "move", ".", "product_id", ".", "uom_id", ",", "rounding_method", "=", "'HALF-UP'", ")", "elif", "move", ".", "state", "==", "'draft'", ":", "# for move _consuming_picking_types and in draft -> the forecast_availability > 0 if in stock", "move", ".", "forecast_availability", "=", "virtual_available_dict", "[", "key_virtual_available", "(", "move", ")", "]", "[", "move", ".", "product_id", ".", "id", "]", "-", "move", ".", "product_qty", "elif", "move", ".", "state", "in", "(", "'waiting'", ",", "'confirmed'", ",", "'partially_available'", ")", ":", "outgoing_unreserved_moves_per_warehouse", "[", "move", ".", "location_id", ".", "warehouse_id", "]", ".", "add", "(", "move", ".", "id", ")", "elif", "move", ".", "picking_type_id", ".", "code", "==", "'incoming'", ":", "forecast_availability", "=", "virtual_available_dict", "[", "key_virtual_available", "(", "move", ",", "incoming", "=", "True", ")", "]", "[", "move", ".", "product_id", ".", "id", "]", "if", "move", ".", "state", "==", "'draft'", ":", "forecast_availability", "+=", "move", ".", "product_qty", "move", ".", "forecast_availability", "=", "forecast_availability", "for", "warehouse", ",", "moves_ids", "in", "outgoing_unreserved_moves_per_warehouse", ".", "items", "(", ")", ":", "if", "not", "warehouse", ":", "# No prediction possible if no warehouse.", "continue", "moves", "=", "self", ".", "browse", "(", "moves_ids", ")", "forecast_info", "=", "moves", ".", "_get_forecast_availability_outgoing", "(", "warehouse", ")", "for", "move", "in", "moves", ":", "move", ".", "forecast_availability", ",", "move", ".", "forecast_expected_date", "=", "forecast_info", "[", "move", "]" ]
https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/addons/stock/models/stock_move.py#L407-L462
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5Type/Core/PropertyExistenceConstraint.py
python
PropertyExistenceConstraint._checkConsistency
(self, obj, fixit=False)
return error_list
Check the object's consistency
Check the object's consistency
[ "Check", "the", "object", "s", "consistency" ]
def _checkConsistency(self, obj, fixit=False): """ Check the object's consistency """ error_list = [] # For each attribute name, we check if defined for property_id in self.getConstraintPropertyList(): error_message_id = self._checkPropertyConsistency(obj, property_id) if error_message_id is not None: error_list.append(self._generateError( obj, self._getMessage(error_message_id), dict(property_id=property_id))) return error_list
[ "def", "_checkConsistency", "(", "self", ",", "obj", ",", "fixit", "=", "False", ")", ":", "error_list", "=", "[", "]", "# For each attribute name, we check if defined", "for", "property_id", "in", "self", ".", "getConstraintPropertyList", "(", ")", ":", "error_message_id", "=", "self", ".", "_checkPropertyConsistency", "(", "obj", ",", "property_id", ")", "if", "error_message_id", "is", "not", "None", ":", "error_list", ".", "append", "(", "self", ".", "_generateError", "(", "obj", ",", "self", ".", "_getMessage", "(", "error_message_id", ")", ",", "dict", "(", "property_id", "=", "property_id", ")", ")", ")", "return", "error_list" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Type/Core/PropertyExistenceConstraint.py#L72-L85
ElasticHQ/elasticsearch-HQ
8197e21d09b1312492dcb6998a2349d73b06efc6
elastichq/vendor/elasticsearch_dsl/v2/elasticsearch_dsl/search.py
python
Search.sort
(self, *keys)
return s
Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field': {'any': 'dict'}} so for example:: s = Search().sort( 'category', '-title', {"price" : {"order" : "asc", "mode" : "avg"}} ) will sort by ``category``, ``title`` (in descending order) and ``price`` in ascending order using the ``avg`` mode. The API returns a copy of the Search object and can thus be chained.
Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are::
[ "Add", "sorting", "information", "to", "the", "search", "request", ".", "If", "called", "without", "arguments", "it", "will", "remove", "all", "sort", "requirements", ".", "Otherwise", "it", "will", "replace", "them", ".", "Acceptable", "arguments", "are", "::" ]
def sort(self, *keys): """ Add sorting information to the search request. If called without arguments it will remove all sort requirements. Otherwise it will replace them. Acceptable arguments are:: 'some.field' '-some.other.field' {'different.field': {'any': 'dict'}} so for example:: s = Search().sort( 'category', '-title', {"price" : {"order" : "asc", "mode" : "avg"}} ) will sort by ``category``, ``title`` (in descending order) and ``price`` in ascending order using the ``avg`` mode. The API returns a copy of the Search object and can thus be chained. """ s = self._clone() s._sort = [] for k in keys: if isinstance(k, string_types) and k.startswith('-'): k = {k[1:]: {"order": "desc"}} s._sort.append(k) return s
[ "def", "sort", "(", "self", ",", "*", "keys", ")", ":", "s", "=", "self", ".", "_clone", "(", ")", "s", ".", "_sort", "=", "[", "]", "for", "k", "in", "keys", ":", "if", "isinstance", "(", "k", ",", "string_types", ")", "and", "k", ".", "startswith", "(", "'-'", ")", ":", "k", "=", "{", "k", "[", "1", ":", "]", ":", "{", "\"order\"", ":", "\"desc\"", "}", "}", "s", ".", "_sort", ".", "append", "(", "k", ")", "return", "s" ]
https://github.com/ElasticHQ/elasticsearch-HQ/blob/8197e21d09b1312492dcb6998a2349d73b06efc6/elastichq/vendor/elasticsearch_dsl/v2/elasticsearch_dsl/search.py#L462-L491
korolr/dotfiles
8e46933503ecb8d8651739ffeb1d2d4f0f5c6524
.config/sublime-text-3/Packages/python-jinja2/all/jinja2/utils.py
python
consume
(iterable)
Consumes an iterable without doing anything with it.
Consumes an iterable without doing anything with it.
[ "Consumes", "an", "iterable", "without", "doing", "anything", "with", "it", "." ]
def consume(iterable): """Consumes an iterable without doing anything with it.""" for event in iterable: pass
[ "def", "consume", "(", "iterable", ")", ":", "for", "event", "in", "iterable", ":", "pass" ]
https://github.com/korolr/dotfiles/blob/8e46933503ecb8d8651739ffeb1d2d4f0f5c6524/.config/sublime-text-3/Packages/python-jinja2/all/jinja2/utils.py#L102-L105
Nexedi/erp5
44df1959c0e21576cf5e9803d602d95efb4b695b
product/ERP5Type/ERP5Type.py
python
ERP5TypeInformation.PrincipiaSearchSource
(self)
return ' '.join(filter(None, search_source_list))
Return keywords for "Find" tab in ZMI
Return keywords for "Find" tab in ZMI
[ "Return", "keywords", "for", "Find", "tab", "in", "ZMI" ]
def PrincipiaSearchSource(self): """Return keywords for "Find" tab in ZMI""" search_source_list = [self.getId(), self.getTypeFactoryMethodId(), self.getTypeAddPermission(), self.getTypeInitScriptId()] search_source_list += self.getTypePropertySheetList() search_source_list += self.getTypeBaseCategoryList() search_source_list += self.getTypeWorkflowList() return ' '.join(filter(None, search_source_list))
[ "def", "PrincipiaSearchSource", "(", "self", ")", ":", "search_source_list", "=", "[", "self", ".", "getId", "(", ")", ",", "self", ".", "getTypeFactoryMethodId", "(", ")", ",", "self", ".", "getTypeAddPermission", "(", ")", ",", "self", ".", "getTypeInitScriptId", "(", ")", "]", "search_source_list", "+=", "self", ".", "getTypePropertySheetList", "(", ")", "search_source_list", "+=", "self", ".", "getTypeBaseCategoryList", "(", ")", "search_source_list", "+=", "self", ".", "getTypeWorkflowList", "(", ")", "return", "' '", ".", "join", "(", "filter", "(", "None", ",", "search_source_list", ")", ")" ]
https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/ERP5Type/ERP5Type.py#L678-L687
TeamvisionCorp/TeamVision
aa2a57469e430ff50cce21174d8f280efa0a83a7
distribute/0.0.5/build_shell/teamvision/teamvision/project/views/project_settings_view.py
python
get_create_dialog
(request)
return HttpResponse(page_worker.get_settings_create_dialog(request,None))
index page
index page
[ "index", "page" ]
def get_create_dialog(request): ''' index page''' page_worker=ProjectSettingsPageWorker(request) return HttpResponse(page_worker.get_settings_create_dialog(request,None))
[ "def", "get_create_dialog", "(", "request", ")", ":", "page_worker", "=", "ProjectSettingsPageWorker", "(", "request", ")", "return", "HttpResponse", "(", "page_worker", ".", "get_settings_create_dialog", "(", "request", ",", "None", ")", ")" ]
https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.5/build_shell/teamvision/teamvision/project/views/project_settings_view.py#L40-L43
aosabook/500lines
fba689d101eb5600f5c8f4d7fd79912498e950e2
_build/preprocessor.py
python
parse_aosafigures
(text)
return figures_list
parse_aosafigures(text) -> [(fullmatch, width, location, caption, id)]
parse_aosafigures(text) -> [(fullmatch, width, location, caption, id)]
[ "parse_aosafigures", "(", "text", ")", "-", ">", "[", "(", "fullmatch", "width", "location", "caption", "id", ")", "]" ]
def parse_aosafigures(text): '''parse_aosafigures(text) -> [(fullmatch, width, location, caption, id)]''' # \aosafigure[233pt]{warp-images/2.png}{Event driven}{fig.warp.f2} regex = re.compile("(\\\\aosafigure\[?([^\]]+)?\]?\{(.*)\}\{(.*)\}\{(.*)\})",re.MULTILINE) figures_list = regex.findall(text) return figures_list
[ "def", "parse_aosafigures", "(", "text", ")", ":", "# \\aosafigure[233pt]{warp-images/2.png}{Event driven}{fig.warp.f2}", "regex", "=", "re", ".", "compile", "(", "\"(\\\\\\\\aosafigure\\[?([^\\]]+)?\\]?\\{(.*)\\}\\{(.*)\\}\\{(.*)\\})\"", ",", "re", ".", "MULTILINE", ")", "figures_list", "=", "regex", ".", "findall", "(", "text", ")", "return", "figures_list" ]
https://github.com/aosabook/500lines/blob/fba689d101eb5600f5c8f4d7fd79912498e950e2/_build/preprocessor.py#L21-L26
jxcore/jxcore
b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410
tools/gyp/pylib/gyp/msvs_emulation.py
python
PrecompiledHeader.GetFlagsModifications
(self, input, output, implicit, command, cflags_c, cflags_cc, expand_special)
return [], output, implicit
Get the modified cflags and implicit dependencies that should be used for the pch compilation step.
Get the modified cflags and implicit dependencies that should be used for the pch compilation step.
[ "Get", "the", "modified", "cflags", "and", "implicit", "dependencies", "that", "should", "be", "used", "for", "the", "pch", "compilation", "step", "." ]
def GetFlagsModifications(self, input, output, implicit, command, cflags_c, cflags_cc, expand_special): """Get the modified cflags and implicit dependencies that should be used for the pch compilation step.""" if input == self.pch_source: pch_output = ['/Yc' + self._PchHeader()] if command == 'cxx': return ([('cflags_cc', map(expand_special, cflags_cc + pch_output))], self.output_obj, []) elif command == 'cc': return ([('cflags_c', map(expand_special, cflags_c + pch_output))], self.output_obj, []) return [], output, implicit
[ "def", "GetFlagsModifications", "(", "self", ",", "input", ",", "output", ",", "implicit", ",", "command", ",", "cflags_c", ",", "cflags_cc", ",", "expand_special", ")", ":", "if", "input", "==", "self", ".", "pch_source", ":", "pch_output", "=", "[", "'/Yc'", "+", "self", ".", "_PchHeader", "(", ")", "]", "if", "command", "==", "'cxx'", ":", "return", "(", "[", "(", "'cflags_cc'", ",", "map", "(", "expand_special", ",", "cflags_cc", "+", "pch_output", ")", ")", "]", ",", "self", ".", "output_obj", ",", "[", "]", ")", "elif", "command", "==", "'cc'", ":", "return", "(", "[", "(", "'cflags_c'", ",", "map", "(", "expand_special", ",", "cflags_c", "+", "pch_output", ")", ")", "]", ",", "self", ".", "output_obj", ",", "[", "]", ")", "return", "[", "]", ",", "output", ",", "implicit" ]
https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/tools/gyp/pylib/gyp/msvs_emulation.py#L793-L805
crits/crits
6b357daa5c3060cf622d3a3b0c7b41a9ca69c049
crits/raw_data/views.py
python
raw_data_details
(request, _id)
Generate RawData details page. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param _id: The ObjectId of the RawData. :type _id: str :returns: :class:`django.http.HttpResponse`
Generate RawData details page.
[ "Generate", "RawData", "details", "page", "." ]
def raw_data_details(request, _id): """ Generate RawData details page. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param _id: The ObjectId of the RawData. :type _id: str :returns: :class:`django.http.HttpResponse` """ template = 'raw_data_details.html' user = request.user if user.has_access_to(RawDataACL.READ): (new_template, args) = get_raw_data_details(_id, user) if new_template: template = new_template return render(request, template, args) else: return render(request, "error.html", {'error': 'User does not have permission to view Raw Data Details.'})
[ "def", "raw_data_details", "(", "request", ",", "_id", ")", ":", "template", "=", "'raw_data_details.html'", "user", "=", "request", ".", "user", "if", "user", ".", "has_access_to", "(", "RawDataACL", ".", "READ", ")", ":", "(", "new_template", ",", "args", ")", "=", "get_raw_data_details", "(", "_id", ",", "user", ")", "if", "new_template", ":", "template", "=", "new_template", "return", "render", "(", "request", ",", "template", ",", "args", ")", "else", ":", "return", "render", "(", "request", ",", "\"error.html\"", ",", "{", "'error'", ":", "'User does not have permission to view Raw Data Details.'", "}", ")" ]
https://github.com/crits/crits/blob/6b357daa5c3060cf622d3a3b0c7b41a9ca69c049/crits/raw_data/views.py#L287-L309
atom-community/ide-python
c046f9c2421713b34baa22648235541c5bb284fe
lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/evaluate/context/iterable.py
python
SequenceLiteralContext.py__getitem__
(self, index)
Here the index is an int/str. Raises IndexError/KeyError.
Here the index is an int/str. Raises IndexError/KeyError.
[ "Here", "the", "index", "is", "an", "int", "/", "str", ".", "Raises", "IndexError", "/", "KeyError", "." ]
def py__getitem__(self, index): """Here the index is an int/str. Raises IndexError/KeyError.""" if self.array_type == u'dict': compiled_obj_index = compiled.create_simple_object(self.evaluator, index) for key, value in self._items(): for k in self._defining_context.eval_node(key): if isinstance(k, compiled.CompiledObject) \ and k.execute_operation(compiled_obj_index, u'==').get_safe_value(): return self._defining_context.eval_node(value) raise KeyError('No key found in dictionary %s.' % self) # Can raise an IndexError if isinstance(index, slice): return ContextSet(self) else: return self._defining_context.eval_node(self._items()[index])
[ "def", "py__getitem__", "(", "self", ",", "index", ")", ":", "if", "self", ".", "array_type", "==", "u'dict'", ":", "compiled_obj_index", "=", "compiled", ".", "create_simple_object", "(", "self", ".", "evaluator", ",", "index", ")", "for", "key", ",", "value", "in", "self", ".", "_items", "(", ")", ":", "for", "k", "in", "self", ".", "_defining_context", ".", "eval_node", "(", "key", ")", ":", "if", "isinstance", "(", "k", ",", "compiled", ".", "CompiledObject", ")", "and", "k", ".", "execute_operation", "(", "compiled_obj_index", ",", "u'=='", ")", ".", "get_safe_value", "(", ")", ":", "return", "self", ".", "_defining_context", ".", "eval_node", "(", "value", ")", "raise", "KeyError", "(", "'No key found in dictionary %s.'", "%", "self", ")", "# Can raise an IndexError", "if", "isinstance", "(", "index", ",", "slice", ")", ":", "return", "ContextSet", "(", "self", ")", "else", ":", "return", "self", ".", "_defining_context", ".", "eval_node", "(", "self", ".", "_items", "(", ")", "[", "index", "]", ")" ]
https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/lib/debugger/VendorLib/vs-py-debugger/pythonFiles/jedi/evaluate/context/iterable.py#L287-L302
mozilla/spidernode
aafa9e5273f954f272bb4382fc007af14674b4c2
deps/spidershim/spidermonkey/python/mozbuild/mozpack/packager/formats.py
python
OmniJarSubFormatter.is_resource
(self, path)
return path[0] in [ 'modules', 'greprefs.js', 'hyphenation', 'localization', 'update.locale', ]
Return whether the given path corresponds to a resource to be put in an omnijar archive.
Return whether the given path corresponds to a resource to be put in an omnijar archive.
[ "Return", "whether", "the", "given", "path", "corresponds", "to", "a", "resource", "to", "be", "put", "in", "an", "omnijar", "archive", "." ]
def is_resource(self, path): ''' Return whether the given path corresponds to a resource to be put in an omnijar archive. ''' if any(mozpath.match(path, p.replace('*', '**')) for p in self._non_resources): return False path = mozpath.split(path) if path[0] == 'chrome': return len(path) == 1 or path[1] != 'icons' if path[0] == 'components': return path[-1].endswith(('.js', '.xpt')) if path[0] == 'res': return len(path) == 1 or \ (path[1] != 'cursors' and path[1] != 'MainMenu.nib') if path[0] == 'defaults': return len(path) != 3 or \ not (path[2] == 'channel-prefs.js' and path[1] in ['pref', 'preferences']) return path[0] in [ 'modules', 'greprefs.js', 'hyphenation', 'localization', 'update.locale', ]
[ "def", "is_resource", "(", "self", ",", "path", ")", ":", "if", "any", "(", "mozpath", ".", "match", "(", "path", ",", "p", ".", "replace", "(", "'*'", ",", "'**'", ")", ")", "for", "p", "in", "self", ".", "_non_resources", ")", ":", "return", "False", "path", "=", "mozpath", ".", "split", "(", "path", ")", "if", "path", "[", "0", "]", "==", "'chrome'", ":", "return", "len", "(", "path", ")", "==", "1", "or", "path", "[", "1", "]", "!=", "'icons'", "if", "path", "[", "0", "]", "==", "'components'", ":", "return", "path", "[", "-", "1", "]", ".", "endswith", "(", "(", "'.js'", ",", "'.xpt'", ")", ")", "if", "path", "[", "0", "]", "==", "'res'", ":", "return", "len", "(", "path", ")", "==", "1", "or", "(", "path", "[", "1", "]", "!=", "'cursors'", "and", "path", "[", "1", "]", "!=", "'MainMenu.nib'", ")", "if", "path", "[", "0", "]", "==", "'defaults'", ":", "return", "len", "(", "path", ")", "!=", "3", "or", "not", "(", "path", "[", "2", "]", "==", "'channel-prefs.js'", "and", "path", "[", "1", "]", "in", "[", "'pref'", ",", "'preferences'", "]", ")", "return", "path", "[", "0", "]", "in", "[", "'modules'", ",", "'greprefs.js'", ",", "'hyphenation'", ",", "'localization'", ",", "'update.locale'", ",", "]" ]
https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/spidershim/spidermonkey/python/mozbuild/mozpack/packager/formats.py#L317-L343
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py
python
_DetectVisualStudioVersions
(versions_to_check, force_express)
return versions
Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exists. Only versions 8-10 are considered. Possibilities are: 2005(e) - Visual Studio 2005 (8) 2008(e) - Visual Studio 2008 (9) 2010(e) - Visual Studio 2010 (10) 2012(e) - Visual Studio 2012 (11) 2013(e) - Visual Studio 2013 (12) 2015 - Visual Studio 2015 (14) Where (e) is e for express editions of MSVS and blank otherwise.
Collect the list of installed visual studio versions.
[ "Collect", "the", "list", "of", "installed", "visual", "studio", "versions", "." ]
def _DetectVisualStudioVersions(versions_to_check, force_express): """Collect the list of installed visual studio versions. Returns: A list of visual studio versions installed in descending order of usage preference. Base this on the registry and a quick check if devenv.exe exists. Only versions 8-10 are considered. Possibilities are: 2005(e) - Visual Studio 2005 (8) 2008(e) - Visual Studio 2008 (9) 2010(e) - Visual Studio 2010 (10) 2012(e) - Visual Studio 2012 (11) 2013(e) - Visual Studio 2013 (12) 2015 - Visual Studio 2015 (14) Where (e) is e for express editions of MSVS and blank otherwise. """ version_to_year = { '8.0': '2005', '9.0': '2008', '10.0': '2010', '11.0': '2012', '12.0': '2013', '14.0': '2015', } versions = [] for version in versions_to_check: # Old method of searching for which VS version is installed # We don't use the 2010-encouraged-way because we also want to get the # path to the binaries, which it doesn't offer. keys = [r'HKLM\Software\Microsoft\VisualStudio\%s' % version, r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s' % version, r'HKLM\Software\Microsoft\VCExpress\%s' % version, r'HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s' % version] for index in range(len(keys)): path = _RegistryGetValue(keys[index], 'InstallDir') if not path: continue path = _ConvertToCygpath(path) # Check for full. full_path = os.path.join(path, 'devenv.exe') express_path = os.path.join(path, '*express.exe') if not force_express and os.path.exists(full_path): # Add this one. versions.append(_CreateVersion(version_to_year[version], os.path.join(path, '..', '..'))) # Check for express. elif glob.glob(express_path): # Add this one. versions.append(_CreateVersion(version_to_year[version] + 'e', os.path.join(path, '..', '..'))) # The old method above does not work when only SDK is installed. keys = [r'HKLM\Software\Microsoft\VisualStudio\SxS\VC7', r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7'] for index in range(len(keys)): path = _RegistryGetValue(keys[index], version) if not path: continue path = _ConvertToCygpath(path) if version != '14.0': # There is no Express edition for 2015. versions.append(_CreateVersion(version_to_year[version] + 'e', os.path.join(path, '..'), sdk_based=True)) return versions
[ "def", "_DetectVisualStudioVersions", "(", "versions_to_check", ",", "force_express", ")", ":", "version_to_year", "=", "{", "'8.0'", ":", "'2005'", ",", "'9.0'", ":", "'2008'", ",", "'10.0'", ":", "'2010'", ",", "'11.0'", ":", "'2012'", ",", "'12.0'", ":", "'2013'", ",", "'14.0'", ":", "'2015'", ",", "}", "versions", "=", "[", "]", "for", "version", "in", "versions_to_check", ":", "# Old method of searching for which VS version is installed", "# We don't use the 2010-encouraged-way because we also want to get the", "# path to the binaries, which it doesn't offer.", "keys", "=", "[", "r'HKLM\\Software\\Microsoft\\VisualStudio\\%s'", "%", "version", ",", "r'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\%s'", "%", "version", ",", "r'HKLM\\Software\\Microsoft\\VCExpress\\%s'", "%", "version", ",", "r'HKLM\\Software\\Wow6432Node\\Microsoft\\VCExpress\\%s'", "%", "version", "]", "for", "index", "in", "range", "(", "len", "(", "keys", ")", ")", ":", "path", "=", "_RegistryGetValue", "(", "keys", "[", "index", "]", ",", "'InstallDir'", ")", "if", "not", "path", ":", "continue", "path", "=", "_ConvertToCygpath", "(", "path", ")", "# Check for full.", "full_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'devenv.exe'", ")", "express_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'*express.exe'", ")", "if", "not", "force_express", "and", "os", ".", "path", ".", "exists", "(", "full_path", ")", ":", "# Add this one.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", ",", "os", ".", "path", ".", "join", "(", "path", ",", "'..'", ",", "'..'", ")", ")", ")", "# Check for express.", "elif", "glob", ".", "glob", "(", "express_path", ")", ":", "# Add this one.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", "+", "'e'", ",", "os", ".", "path", ".", "join", "(", "path", ",", "'..'", ",", "'..'", ")", ")", ")", "# The old method above does not work when only SDK is installed.", "keys", "=", "[", "r'HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7'", ",", "r'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7'", "]", "for", "index", "in", "range", "(", "len", "(", "keys", ")", ")", ":", "path", "=", "_RegistryGetValue", "(", "keys", "[", "index", "]", ",", "version", ")", "if", "not", "path", ":", "continue", "path", "=", "_ConvertToCygpath", "(", "path", ")", "if", "version", "!=", "'14.0'", ":", "# There is no Express edition for 2015.", "versions", ".", "append", "(", "_CreateVersion", "(", "version_to_year", "[", "version", "]", "+", "'e'", ",", "os", ".", "path", ".", "join", "(", "path", ",", "'..'", ")", ",", "sdk_based", "=", "True", ")", ")", "return", "versions" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSVersion.py#L334-L398
nodejs/http2
734ad72e3939e62bcff0f686b8ec426b8aaa22e3
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
CLTVersion
()
Returns the version of command-line tools from pkgutil.
Returns the version of command-line tools from pkgutil.
[ "Returns", "the", "version", "of", "command", "-", "line", "tools", "from", "pkgutil", "." ]
def CLTVersion(): """Returns the version of command-line tools from pkgutil.""" # pkgutil output looks like # package-id: com.apple.pkg.CLTools_Executables # version: 5.0.1.0.1.1382131676 # volume: / # location: / # install-time: 1382544035 # groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo" FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" regex = re.compile('version: (?P<version>.+)') for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]: try: output = GetStdout(['/usr/sbin/pkgutil', '--pkg-info', key]) return re.search(regex, output).groupdict()['version'] except: continue
[ "def", "CLTVersion", "(", ")", ":", "# pkgutil output looks like", "# package-id: com.apple.pkg.CLTools_Executables", "# version: 5.0.1.0.1.1382131676", "# volume: /", "# location: /", "# install-time: 1382544035", "# groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group", "STANDALONE_PKG_ID", "=", "\"com.apple.pkg.DeveloperToolsCLILeo\"", "FROM_XCODE_PKG_ID", "=", "\"com.apple.pkg.DeveloperToolsCLI\"", "MAVERICKS_PKG_ID", "=", "\"com.apple.pkg.CLTools_Executables\"", "regex", "=", "re", ".", "compile", "(", "'version: (?P<version>.+)'", ")", "for", "key", "in", "[", "MAVERICKS_PKG_ID", ",", "STANDALONE_PKG_ID", ",", "FROM_XCODE_PKG_ID", "]", ":", "try", ":", "output", "=", "GetStdout", "(", "[", "'/usr/sbin/pkgutil'", ",", "'--pkg-info'", ",", "key", "]", ")", "return", "re", ".", "search", "(", "regex", ",", "output", ")", ".", "groupdict", "(", ")", "[", "'version'", "]", "except", ":", "continue" ]
https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1282-L1301
ctripcorp/tars
d7954fccaf1a17901f22d844d84c5663a3d79c11
tars/api/views/application.py
python
ApplicationViewSet.join_groups
(self, request, pk=None)
post {"aggregate_on": [1, 2, 3]} to generate a new JoinedGroup on this application
post {"aggregate_on": [1, 2, 3]} to generate a new JoinedGroup on this application
[ "post", "{", "aggregate_on", ":", "[", "1", "2", "3", "]", "}", "to", "generate", "a", "new", "JoinedGroup", "on", "this", "application" ]
def join_groups(self, request, pk=None): """ post {"aggregate_on": [1, 2, 3]} to generate a new JoinedGroup on this application """ serializer_class = serializers.JoinedGroupSerializer if request.method == 'POST': data = dict(request.data, application=pk) serializer = serializer_class(data=data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) else: joined_groups = self.get_object().groups.filter(g_type=Group.G_TYPE_ENUM.join) return Response(serializer_class(joined_groups, many=True).data)
[ "def", "join_groups", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "serializer_class", "=", "serializers", ".", "JoinedGroupSerializer", "if", "request", ".", "method", "==", "'POST'", ":", "data", "=", "dict", "(", "request", ".", "data", ",", "application", "=", "pk", ")", "serializer", "=", "serializer_class", "(", "data", "=", "data", ")", "if", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", ":", "serializer", ".", "save", "(", ")", "return", "Response", "(", "serializer", ".", "data", ",", "status", "=", "HTTP_201_CREATED", ")", "else", ":", "joined_groups", "=", "self", ".", "get_object", "(", ")", ".", "groups", ".", "filter", "(", "g_type", "=", "Group", ".", "G_TYPE_ENUM", ".", "join", ")", "return", "Response", "(", "serializer_class", "(", "joined_groups", ",", "many", "=", "True", ")", ".", "data", ")" ]
https://github.com/ctripcorp/tars/blob/d7954fccaf1a17901f22d844d84c5663a3d79c11/tars/api/views/application.py#L454-L468
replit-archive/jsrepl
36d79b6288ca5d26208e8bade2a168c6ebcb2376
extern/python/unclosured/lib/python2.7/decimal.py
python
_dpower
(xc, xe, yc, ye, p)
return coeff, exp
Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: 10**(p-1) <= c <= 10**p, and (c-1)*10**e < x**y < (c+1)*10**e in other words, c*10**e is an approximation to x**y with p digits of precision, and with an error in c of at most 1. (This is almost, but not quite, the same as the error being < 1ulp: when c == 10**(p-1) we can only guarantee error < 10ulp.) We assume that: x is positive and not equal to 1, and y is nonzero.
Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
[ "Given", "integers", "xc", "xe", "yc", "and", "ye", "representing", "Decimals", "x", "=", "xc", "*", "10", "**", "xe", "and", "y", "=", "yc", "*", "10", "**", "ye", "compute", "x", "**", "y", ".", "Returns", "a", "pair", "of", "integers", "(", "c", "e", ")", "such", "that", ":" ]
def _dpower(xc, xe, yc, ye, p): """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: 10**(p-1) <= c <= 10**p, and (c-1)*10**e < x**y < (c+1)*10**e in other words, c*10**e is an approximation to x**y with p digits of precision, and with an error in c of at most 1. (This is almost, but not quite, the same as the error being < 1ulp: when c == 10**(p-1) we can only guarantee error < 10ulp.) We assume that: x is positive and not equal to 1, and y is nonzero. """ # Find b such that 10**(b-1) <= |y| <= 10**b b = len(str(abs(yc))) + ye # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point lxc = _dlog(xc, xe, p+b+1) # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) shift = ye-b if shift >= 0: pc = lxc*yc*10**shift else: pc = _div_nearest(lxc*yc, 10**-shift) if pc == 0: # we prefer a result that isn't exactly 1; this makes it # easier to compute a correctly rounded result in __pow__ if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: coeff, exp = 10**(p-1)+1, 1-p else: coeff, exp = 10**p-1, -p else: coeff, exp = _dexp(pc, -(p+1), p+1) coeff = _div_nearest(coeff, 10) exp += 1 return coeff, exp
[ "def", "_dpower", "(", "xc", ",", "xe", ",", "yc", ",", "ye", ",", "p", ")", ":", "# Find b such that 10**(b-1) <= |y| <= 10**b", "b", "=", "len", "(", "str", "(", "abs", "(", "yc", ")", ")", ")", "+", "ye", "# log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point", "lxc", "=", "_dlog", "(", "xc", ",", "xe", ",", "p", "+", "b", "+", "1", ")", "# compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)", "shift", "=", "ye", "-", "b", "if", "shift", ">=", "0", ":", "pc", "=", "lxc", "*", "yc", "*", "10", "**", "shift", "else", ":", "pc", "=", "_div_nearest", "(", "lxc", "*", "yc", ",", "10", "**", "-", "shift", ")", "if", "pc", "==", "0", ":", "# we prefer a result that isn't exactly 1; this makes it", "# easier to compute a correctly rounded result in __pow__", "if", "(", "(", "len", "(", "str", "(", "xc", ")", ")", "+", "xe", ">=", "1", ")", "==", "(", "yc", ">", "0", ")", ")", ":", "# if x**y > 1:", "coeff", ",", "exp", "=", "10", "**", "(", "p", "-", "1", ")", "+", "1", ",", "1", "-", "p", "else", ":", "coeff", ",", "exp", "=", "10", "**", "p", "-", "1", ",", "-", "p", "else", ":", "coeff", ",", "exp", "=", "_dexp", "(", "pc", ",", "-", "(", "p", "+", "1", ")", ",", "p", "+", "1", ")", "coeff", "=", "_div_nearest", "(", "coeff", ",", "10", ")", "exp", "+=", "1", "return", "coeff", ",", "exp" ]
https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/decimal.py#L5733-L5773
SEL-Columbia/formhub
578fc2c5e9febe8dc68b37f7d2e85a76dc2c4c04
api/tools.py
python
add_xform_to_project
(xform, project, creator)
return instance
Adds an xform to a project
Adds an xform to a project
[ "Adds", "an", "xform", "to", "a", "project" ]
def add_xform_to_project(xform, project, creator): """Adds an xform to a project""" instance = ProjectXForm.objects.create( xform=xform, project=project, created_by=creator) instance.save() return instance
[ "def", "add_xform_to_project", "(", "xform", ",", "project", ",", "creator", ")", ":", "instance", "=", "ProjectXForm", ".", "objects", ".", "create", "(", "xform", "=", "xform", ",", "project", "=", "project", ",", "created_by", "=", "creator", ")", "instance", ".", "save", "(", ")", "return", "instance" ]
https://github.com/SEL-Columbia/formhub/blob/578fc2c5e9febe8dc68b37f7d2e85a76dc2c4c04/api/tools.py#L101-L106
xl7dev/BurpSuite
d1d4bd4981a87f2f4c0c9744ad7c476336c813da
Extender/faraday/shell/controller/env.py
python
ShellEnvironment.check_command_end
(self, output)
return command_finished, output
Checks if the command finished by checking if the last line of the ouput is just our shell custom prompt. It also checks if a generic prompt is detected as the last line, which could mean that the commmand may have resulted in a remote connection to another host or device. This method returns 2 values: first a boolean flag that determines if command ended and then the full command output.
Checks if the command finished by checking if the last line of the ouput is just our shell custom prompt. It also checks if a generic prompt is detected as the last line, which could mean that the commmand may have resulted in a remote connection to another host or device. This method returns 2 values: first a boolean flag that determines if command ended and then the full command output.
[ "Checks", "if", "the", "command", "finished", "by", "checking", "if", "the", "last", "line", "of", "the", "ouput", "is", "just", "our", "shell", "custom", "prompt", ".", "It", "also", "checks", "if", "a", "generic", "prompt", "is", "detected", "as", "the", "last", "line", "which", "could", "mean", "that", "the", "commmand", "may", "have", "resulted", "in", "a", "remote", "connection", "to", "another", "host", "or", "device", ".", "This", "method", "returns", "2", "values", ":", "first", "a", "boolean", "flag", "that", "determines", "if", "command", "ended", "and", "then", "the", "full", "command", "output", "." ]
def check_command_end(self, output): """ Checks if the command finished by checking if the last line of the ouput is just our shell custom prompt. It also checks if a generic prompt is detected as the last line, which could mean that the commmand may have resulted in a remote connection to another host or device. This method returns 2 values: first a boolean flag that determines if command ended and then the full command output. """ # We check if the last line in the output is just our modified shell prompt... # This would mean the command ended and we notify the plugin then api.devlog("check_command_end called...\noutput received = %r" % output) output_lines = output.splitlines() last_line = output_lines[-1].strip() api.devlog("about to test match with line %r" % last_line) command_finished = self.__matchesCustomPrompt(last_line) #command_finished = self.__matchesCustomPrompt(last_line.split()[0]) if command_finished: # if we found this prompt then it means the command ended # we remove that line from output to send it api.devlog("command finished. Removing last line from output because it is just the prompt") output_lines.pop(-1) output = "\n".join(output_lines) # if command finished we need to ignore further output. It will be user input self.__ignore_process_output = True self.__interactive = False self.session.updateLastUserInputLine() else: # if we are here means that last line of the output is not our custom # shell prompt, but we need to check if a generic prompt is there # which means a remote connection may have been established if self.__matchGenericPrompt(last_line): api.devlog("A generic prompt format matched the last line of the command ouput") #TODO: define what to do in this case return command_finished, output
[ "def", "check_command_end", "(", "self", ",", "output", ")", ":", "# We check if the last line in the output is just our modified shell prompt...", "# This would mean the command ended and we notify the plugin then", "api", ".", "devlog", "(", "\"check_command_end called...\\noutput received = %r\"", "%", "output", ")", "output_lines", "=", "output", ".", "splitlines", "(", ")", "last_line", "=", "output_lines", "[", "-", "1", "]", ".", "strip", "(", ")", "api", ".", "devlog", "(", "\"about to test match with line %r\"", "%", "last_line", ")", "command_finished", "=", "self", ".", "__matchesCustomPrompt", "(", "last_line", ")", "#command_finished = self.__matchesCustomPrompt(last_line.split()[0])", "if", "command_finished", ":", "# if we found this prompt then it means the command ended", "# we remove that line from output to send it", "api", ".", "devlog", "(", "\"command finished. Removing last line from output because it is just the prompt\"", ")", "output_lines", ".", "pop", "(", "-", "1", ")", "output", "=", "\"\\n\"", ".", "join", "(", "output_lines", ")", "# if command finished we need to ignore further output. It will be user input", "self", ".", "__ignore_process_output", "=", "True", "self", ".", "__interactive", "=", "False", "self", ".", "session", ".", "updateLastUserInputLine", "(", ")", "else", ":", "# if we are here means that last line of the output is not our custom", "# shell prompt, but we need to check if a generic prompt is there", "# which means a remote connection may have been established", "if", "self", ".", "__matchGenericPrompt", "(", "last_line", ")", ":", "api", ".", "devlog", "(", "\"A generic prompt format matched the last line of the command ouput\"", ")", "#TODO: define what to do in this case", "return", "command_finished", ",", "output" ]
https://github.com/xl7dev/BurpSuite/blob/d1d4bd4981a87f2f4c0c9744ad7c476336c813da/Extender/faraday/shell/controller/env.py#L612-L648
nodejs/node
ac3c33c1646bf46104c15ae035982c06364da9b8
deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
python
XCBuildPhase._AddBuildFileToDicts
(self, pbxbuildfile, path=None)
Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children.
Maintains the _files_by_path and _files_by_xcfilelikeelement dicts.
[ "Maintains", "the", "_files_by_path", "and", "_files_by_xcfilelikeelement", "dicts", "." ]
def _AddBuildFileToDicts(self, pbxbuildfile, path=None): """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children. """ xcfilelikeelement = pbxbuildfile._properties["fileRef"] paths = [] if path is not None: # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) else: # If the caller didn't provide a path, there can be either multiple # paths (PBXVariantGroup) or one. if isinstance(xcfilelikeelement, PBXVariantGroup): for variant in xcfilelikeelement._properties["children"]: paths.append(variant.FullPath()) else: paths.append(xcfilelikeelement.FullPath()) # Add the paths first, because if something's going to raise, the # messages provided by _AddPathToDict are more useful owing to its # having access to a real pathname and not just an object's Name(). for a_path in paths: self._AddPathToDict(pbxbuildfile, a_path) # If another PBXBuildFile references this XCFileLikeElement, there's a # problem. if ( xcfilelikeelement in self._files_by_xcfilelikeelement and self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile ): raise ValueError( "Found multiple build files for " + xcfilelikeelement.Name() ) self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile
[ "def", "_AddBuildFileToDicts", "(", "self", ",", "pbxbuildfile", ",", "path", "=", "None", ")", ":", "xcfilelikeelement", "=", "pbxbuildfile", ".", "_properties", "[", "\"fileRef\"", "]", "paths", "=", "[", "]", "if", "path", "is", "not", "None", ":", "# It's best when the caller provides the path.", "if", "isinstance", "(", "xcfilelikeelement", ",", "PBXVariantGroup", ")", ":", "paths", ".", "append", "(", "path", ")", "else", ":", "# If the caller didn't provide a path, there can be either multiple", "# paths (PBXVariantGroup) or one.", "if", "isinstance", "(", "xcfilelikeelement", ",", "PBXVariantGroup", ")", ":", "for", "variant", "in", "xcfilelikeelement", ".", "_properties", "[", "\"children\"", "]", ":", "paths", ".", "append", "(", "variant", ".", "FullPath", "(", ")", ")", "else", ":", "paths", ".", "append", "(", "xcfilelikeelement", ".", "FullPath", "(", ")", ")", "# Add the paths first, because if something's going to raise, the", "# messages provided by _AddPathToDict are more useful owing to its", "# having access to a real pathname and not just an object's Name().", "for", "a_path", "in", "paths", ":", "self", ".", "_AddPathToDict", "(", "pbxbuildfile", ",", "a_path", ")", "# If another PBXBuildFile references this XCFileLikeElement, there's a", "# problem.", "if", "(", "xcfilelikeelement", "in", "self", ".", "_files_by_xcfilelikeelement", "and", "self", ".", "_files_by_xcfilelikeelement", "[", "xcfilelikeelement", "]", "!=", "pbxbuildfile", ")", ":", "raise", "ValueError", "(", "\"Found multiple build files for \"", "+", "xcfilelikeelement", ".", "Name", "(", ")", ")", "self", ".", "_files_by_xcfilelikeelement", "[", "xcfilelikeelement", "]", "=", "pbxbuildfile" ]
https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py#L1894-L1951