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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py | python | _BaseNetwork.num_addresses | (self) | return int(self.broadcast_address) - int(self.network_address) + 1 | Number of hosts in the current subnet. | Number of hosts in the current subnet. | [
"Number",
"of",
"hosts",
"in",
"the",
"current",
"subnet",
"."
] | def num_addresses(self):
"""Number of hosts in the current subnet."""
return int(self.broadcast_address) - int(self.network_address) + 1 | [
"def",
"num_addresses",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"-",
"int",
"(",
"self",
".",
"network_address",
")",
"+",
"1"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_vendor/ipaddress.py#L847-L849 |
|
facebookarchive/nuclide | 2a2a0a642d136768b7d2a6d35a652dc5fb77d70a | modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py | python | Thread.get_stack_trace_with_labels | (self, depth = 16, bMakePretty = True) | return trace | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error. | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue. | [
"Tries",
"to",
"get",
"a",
"stack",
"trace",
"for",
"the",
"current",
"function",
".",
"Only",
"works",
"for",
"functions",
"with",
"standard",
"prologue",
"and",
"epilogue",
"."
] | def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error.
"""
try:
trace = self.__get_stack_trace(depth, True, bMakePretty)
except Exception:
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, True, bMakePretty)
return trace | [
"def",
"get_stack_trace_with_labels",
"(",
"self",
",",
"depth",
"=",
"16",
",",
"bMakePretty",
"=",
"True",
")",
":",
"try",
":",
"trace",
"=",
"self",
".",
"__get_stack_trace",
"(",
"depth",
",",
"True",
",",
"bMakePretty",
")",
"except",
"Exception",
":",
"trace",
"=",
"(",
")",
"if",
"not",
"trace",
":",
"trace",
"=",
"self",
".",
"__get_stack_trace_manually",
"(",
"depth",
",",
"True",
",",
"bMakePretty",
")",
"return",
"trace"
] | https://github.com/facebookarchive/nuclide/blob/2a2a0a642d136768b7d2a6d35a652dc5fb77d70a/modules/atom-ide-debugger-python/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py#L1258-L1286 |
|
Opentrons/opentrons | 466e0567065d8773a81c25cd1b5c7998e00adf2c | api/src/opentrons/hardware_control/api.py | python | API.resume | (self, pause_type: PauseType) | Resume motion after a call to :py:meth:`pause`. | Resume motion after a call to :py:meth:`pause`. | [
"Resume",
"motion",
"after",
"a",
"call",
"to",
":",
"py",
":",
"meth",
":",
"pause",
"."
] | def resume(self, pause_type: PauseType):
"""
Resume motion after a call to :py:meth:`pause`.
"""
self._pause_manager.resume(pause_type)
if self._pause_manager.should_pause:
return
# Resume must be called immediately to awaken thread running hardware
# methods (ThreadManager)
self._backend.resume()
async def _chained_calls():
# mirror what happens API.pause.
await self._execution_manager.resume()
self._backend.resume()
asyncio.run_coroutine_threadsafe(_chained_calls(), self._loop) | [
"def",
"resume",
"(",
"self",
",",
"pause_type",
":",
"PauseType",
")",
":",
"self",
".",
"_pause_manager",
".",
"resume",
"(",
"pause_type",
")",
"if",
"self",
".",
"_pause_manager",
".",
"should_pause",
":",
"return",
"# Resume must be called immediately to awaken thread running hardware",
"# methods (ThreadManager)",
"self",
".",
"_backend",
".",
"resume",
"(",
")",
"async",
"def",
"_chained_calls",
"(",
")",
":",
"# mirror what happens API.pause.",
"await",
"self",
".",
"_execution_manager",
".",
"resume",
"(",
")",
"self",
".",
"_backend",
".",
"resume",
"(",
")",
"asyncio",
".",
"run_coroutine_threadsafe",
"(",
"_chained_calls",
"(",
")",
",",
"self",
".",
"_loop",
")"
] | https://github.com/Opentrons/opentrons/blob/466e0567065d8773a81c25cd1b5c7998e00adf2c/api/src/opentrons/hardware_control/api.py#L639-L657 |
||
webrtc/apprtc | db975e22ea07a0c11a4179d4beb2feb31cf344f4 | src/third_party/oauth2client/client.py | python | OAuth2WebServerFlow.step2_exchange | (self, code, http=None) | Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token. | Exhanges a code for OAuth2Credentials. | [
"Exhanges",
"a",
"code",
"for",
"OAuth2Credentials",
"."
] | def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
d = _parse_exchange_token_response(content)
if resp.status == 200 and 'access_token' in d:
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token')
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
revoke_uri=self.revoke_uri,
id_token=d.get('id_token', None),
token_response=d)
else:
logger.info('Failed to retrieve access token: %s' % content)
if 'error' in d:
# you never know what those providers got to say
error_msg = unicode(d['error'])
else:
error_msg = 'Invalid response: %s.' % str(resp.status)
raise FlowExchangeError(error_msg) | [
"def",
"step2_exchange",
"(",
"self",
",",
"code",
",",
"http",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"code",
",",
"str",
")",
"or",
"isinstance",
"(",
"code",
",",
"unicode",
")",
")",
":",
"if",
"'code'",
"not",
"in",
"code",
":",
"if",
"'error'",
"in",
"code",
":",
"error_msg",
"=",
"code",
"[",
"'error'",
"]",
"else",
":",
"error_msg",
"=",
"'No code was supplied in the query parameters.'",
"raise",
"FlowExchangeError",
"(",
"error_msg",
")",
"else",
":",
"code",
"=",
"code",
"[",
"'code'",
"]",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"{",
"'grant_type'",
":",
"'authorization_code'",
",",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'client_secret'",
":",
"self",
".",
"client_secret",
",",
"'code'",
":",
"code",
",",
"'redirect_uri'",
":",
"self",
".",
"redirect_uri",
",",
"'scope'",
":",
"self",
".",
"scope",
",",
"}",
")",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/x-www-form-urlencoded'",
",",
"}",
"if",
"self",
".",
"user_agent",
"is",
"not",
"None",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"self",
".",
"user_agent",
"if",
"http",
"is",
"None",
":",
"http",
"=",
"httplib2",
".",
"Http",
"(",
")",
"resp",
",",
"content",
"=",
"http",
".",
"request",
"(",
"self",
".",
"token_uri",
",",
"method",
"=",
"'POST'",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"headers",
")",
"d",
"=",
"_parse_exchange_token_response",
"(",
"content",
")",
"if",
"resp",
".",
"status",
"==",
"200",
"and",
"'access_token'",
"in",
"d",
":",
"access_token",
"=",
"d",
"[",
"'access_token'",
"]",
"refresh_token",
"=",
"d",
".",
"get",
"(",
"'refresh_token'",
",",
"None",
")",
"token_expiry",
"=",
"None",
"if",
"'expires_in'",
"in",
"d",
":",
"token_expiry",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"int",
"(",
"d",
"[",
"'expires_in'",
"]",
")",
")",
"if",
"'id_token'",
"in",
"d",
":",
"d",
"[",
"'id_token'",
"]",
"=",
"_extract_id_token",
"(",
"d",
"[",
"'id_token'",
"]",
")",
"logger",
".",
"info",
"(",
"'Successfully retrieved access token'",
")",
"return",
"OAuth2Credentials",
"(",
"access_token",
",",
"self",
".",
"client_id",
",",
"self",
".",
"client_secret",
",",
"refresh_token",
",",
"token_expiry",
",",
"self",
".",
"token_uri",
",",
"self",
".",
"user_agent",
",",
"revoke_uri",
"=",
"self",
".",
"revoke_uri",
",",
"id_token",
"=",
"d",
".",
"get",
"(",
"'id_token'",
",",
"None",
")",
",",
"token_response",
"=",
"d",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Failed to retrieve access token: %s'",
"%",
"content",
")",
"if",
"'error'",
"in",
"d",
":",
"# you never know what those providers got to say",
"error_msg",
"=",
"unicode",
"(",
"d",
"[",
"'error'",
"]",
")",
"else",
":",
"error_msg",
"=",
"'Invalid response: %s.'",
"%",
"str",
"(",
"resp",
".",
"status",
")",
"raise",
"FlowExchangeError",
"(",
"error_msg",
")"
] | https://github.com/webrtc/apprtc/blob/db975e22ea07a0c11a4179d4beb2feb31cf344f4/src/third_party/oauth2client/client.py#L1237-L1310 |
||
axa-group/Parsr | 3a2193b15c56a8fbcafe5efbddd83adbb0f8fd9d | clients/python-client/parsr_client/parsr_client.py | python | ParsrClient.set_server | (self, server: str) | Setter for the Parsr server's address | Setter for the Parsr server's address | [
"Setter",
"for",
"the",
"Parsr",
"server",
"s",
"address"
] | def set_server(self, server: str):
"""Setter for the Parsr server's address
"""
self.server = server | [
"def",
"set_server",
"(",
"self",
",",
"server",
":",
"str",
")",
":",
"self",
".",
"server",
"=",
"server"
] | https://github.com/axa-group/Parsr/blob/3a2193b15c56a8fbcafe5efbddd83adbb0f8fd9d/clients/python-client/parsr_client/parsr_client.py#L58-L61 |
||
prometheus-ar/vot.ar | 72d8fa1ea08fe417b64340b98dff68df8364afdf | msa/core/armve/protocol.py | python | Printer.do_print | (self) | Envia el comando CMD_PRINTER_PRINT al ARM. | Envia el comando CMD_PRINTER_PRINT al ARM. | [
"Envia",
"el",
"comando",
"CMD_PRINTER_PRINT",
"al",
"ARM",
"."
] | def do_print(self):
"""Envia el comando CMD_PRINTER_PRINT al ARM."""
self._send_command(CMD_PRINTER_PRINT) | [
"def",
"do_print",
"(",
"self",
")",
":",
"self",
".",
"_send_command",
"(",
"CMD_PRINTER_PRINT",
")"
] | https://github.com/prometheus-ar/vot.ar/blob/72d8fa1ea08fe417b64340b98dff68df8364afdf/msa/core/armve/protocol.py#L1458-L1460 |
||
sagemath/cloud | 054854b87817edfa95e9044c793059bddc361e67 | sage_salvus.py | python | exercise | (code) | r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional):
- a ``question`` variable, as an HTML string with math in dollar
signs
- an ``answer`` variable, which can be any object, or a pair
(correct_value, interact control) -- see the docstring for
interact for controls.
- an optional callable ``check(answer)`` that returns a boolean or
a 2-tuple
(True or False, message),
where the first argument is True if the answer is correct, and
the optional second argument is a message that should be
displayed in response to the given answer. NOTE: Often the
input "answer" will be a string, so you may have to use Integer,
RealNumber, or sage_eval to evaluate it, depending
on what you want to allow the user to do.
- hints -- optional list of strings to display in sequence each
time the user enters a wrong answer. The last string is
displayed repeatedly. If hints is omitted, the correct answer
is displayed after three attempts.
NOTE: The code that defines the exercise is executed so that it
does not impact (and is not impacted by) the global scope of your
variables elsewhere in your session. Thus you can have many
%exercise cells in a single worksheet with no interference between
them.
The following examples further illustrate how %exercise works.
An exercise to test your ability to sum the first $n$ integers::
%exercise
title = "Sum the first n integers, like Gauss did."
n = randint(3, 100)
question = "What is the sum $1 + 2 + \\cdots + %s$ of the first %s positive integers?"%(n,n)
answer = n*(n+1)//2
Transpose a matrix::
%exercise
title = r"Transpose a $2 \times 2$ Matrix"
A = random_matrix(ZZ,2)
question = "What is the transpose of $%s?$"%latex(A)
answer = A.transpose()
Add together a few numbers::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
The trace of a matrix::
%exercise
title = "Compute the trace of a matrix."
A = random_matrix(ZZ, 3, x=-5, y = 5)^2
question = "What is the trace of $$%s?$$"%latex(A)
answer = A.trace()
Some basic arithmetic with hints and dynamic feedback::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
hints = ['This is basic arithmetic.', 'The sum is near %s.'%(answer+randint(1,5)), "The answer is %s."%answer]
def check(attempt):
c = Integer(attempt) - answer
if c == 0:
return True
if abs(c) >= 10:
return False, "Gees -- not even close!"
if c < 0:
return False, "too low"
if c > 0:
return False, "too high" | r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional): | [
"r",
"Use",
"the",
"%exercise",
"cell",
"decorator",
"to",
"create",
"interactive",
"exercise",
"sets",
".",
"Put",
"%exercise",
"at",
"the",
"top",
"of",
"the",
"cell",
"then",
"write",
"Sage",
"code",
"in",
"the",
"cell",
"that",
"defines",
"the",
"following",
"(",
"all",
"are",
"optional",
")",
":"
] | def exercise(code):
r"""
Use the %exercise cell decorator to create interactive exercise
sets. Put %exercise at the top of the cell, then write Sage code
in the cell that defines the following (all are optional):
- a ``question`` variable, as an HTML string with math in dollar
signs
- an ``answer`` variable, which can be any object, or a pair
(correct_value, interact control) -- see the docstring for
interact for controls.
- an optional callable ``check(answer)`` that returns a boolean or
a 2-tuple
(True or False, message),
where the first argument is True if the answer is correct, and
the optional second argument is a message that should be
displayed in response to the given answer. NOTE: Often the
input "answer" will be a string, so you may have to use Integer,
RealNumber, or sage_eval to evaluate it, depending
on what you want to allow the user to do.
- hints -- optional list of strings to display in sequence each
time the user enters a wrong answer. The last string is
displayed repeatedly. If hints is omitted, the correct answer
is displayed after three attempts.
NOTE: The code that defines the exercise is executed so that it
does not impact (and is not impacted by) the global scope of your
variables elsewhere in your session. Thus you can have many
%exercise cells in a single worksheet with no interference between
them.
The following examples further illustrate how %exercise works.
An exercise to test your ability to sum the first $n$ integers::
%exercise
title = "Sum the first n integers, like Gauss did."
n = randint(3, 100)
question = "What is the sum $1 + 2 + \\cdots + %s$ of the first %s positive integers?"%(n,n)
answer = n*(n+1)//2
Transpose a matrix::
%exercise
title = r"Transpose a $2 \times 2$ Matrix"
A = random_matrix(ZZ,2)
question = "What is the transpose of $%s?$"%latex(A)
answer = A.transpose()
Add together a few numbers::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
The trace of a matrix::
%exercise
title = "Compute the trace of a matrix."
A = random_matrix(ZZ, 3, x=-5, y = 5)^2
question = "What is the trace of $$%s?$$"%latex(A)
answer = A.trace()
Some basic arithmetic with hints and dynamic feedback::
%exercise
k = randint(2,5)
title = "Add %s numbers"%k
v = [randint(1,10) for _ in range(k)]
question = "What is the sum $%s$?"%(' + '.join([str(x) for x in v]))
answer = sum(v)
hints = ['This is basic arithmetic.', 'The sum is near %s.'%(answer+randint(1,5)), "The answer is %s."%answer]
def check(attempt):
c = Integer(attempt) - answer
if c == 0:
return True
if abs(c) >= 10:
return False, "Gees -- not even close!"
if c < 0:
return False, "too low"
if c > 0:
return False, "too high"
"""
f = closure(code)
def g():
x = f()
return x.get('title',''), x.get('question', ''), x.get('answer',''), x.get('check',None), x.get('hints',None)
title, question, answer, check, hints = g()
obj = {}
obj['E'] = Exercise(question, answer, check, hints)
obj['title'] = title
def title_control(t):
return text_control('<h3 class="lighten">%s</h3>'%t)
the_times = []
@interact(layout=[[('go',1), ('title',11,'')],[('')], [('times',12, "<b>Times:</b>")]], flicker=True)
def h(go = button(" "*5 + "Go" + " "*7, label='', icon='fa-refresh', classes="btn-large btn-success"),
title = title_control(title),
times = text_control('')):
c = interact.changed()
if 'go' in c or 'another' in c:
interact.title = title_control(obj['title'])
def cb(obj):
the_times.append("%.1f"%obj['time'])
h.times = ', '.join(the_times)
obj['E'].ask(cb)
title, question, answer, check, hints = g() # get ready for next time.
obj['title'] = title
obj['E'] = Exercise(question, answer, check, hints) | [
"def",
"exercise",
"(",
"code",
")",
":",
"f",
"=",
"closure",
"(",
"code",
")",
"def",
"g",
"(",
")",
":",
"x",
"=",
"f",
"(",
")",
"return",
"x",
".",
"get",
"(",
"'title'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'question'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'answer'",
",",
"''",
")",
",",
"x",
".",
"get",
"(",
"'check'",
",",
"None",
")",
",",
"x",
".",
"get",
"(",
"'hints'",
",",
"None",
")",
"title",
",",
"question",
",",
"answer",
",",
"check",
",",
"hints",
"=",
"g",
"(",
")",
"obj",
"=",
"{",
"}",
"obj",
"[",
"'E'",
"]",
"=",
"Exercise",
"(",
"question",
",",
"answer",
",",
"check",
",",
"hints",
")",
"obj",
"[",
"'title'",
"]",
"=",
"title",
"def",
"title_control",
"(",
"t",
")",
":",
"return",
"text_control",
"(",
"'<h3 class=\"lighten\">%s</h3>'",
"%",
"t",
")",
"the_times",
"=",
"[",
"]",
"@",
"interact",
"(",
"layout",
"=",
"[",
"[",
"(",
"'go'",
",",
"1",
")",
",",
"(",
"'title'",
",",
"11",
",",
"''",
")",
"]",
",",
"[",
"(",
"''",
")",
"]",
",",
"[",
"(",
"'times'",
",",
"12",
",",
"\"<b>Times:</b>\"",
")",
"]",
"]",
",",
"flicker",
"=",
"True",
")",
"def",
"h",
"(",
"go",
"=",
"button",
"(",
"\" \"",
"*",
"5",
"+",
"\"Go\"",
"+",
"\" \"",
"*",
"7",
",",
"label",
"=",
"''",
",",
"icon",
"=",
"'fa-refresh'",
",",
"classes",
"=",
"\"btn-large btn-success\"",
")",
",",
"title",
"=",
"title_control",
"(",
"title",
")",
",",
"times",
"=",
"text_control",
"(",
"''",
")",
")",
":",
"c",
"=",
"interact",
".",
"changed",
"(",
")",
"if",
"'go'",
"in",
"c",
"or",
"'another'",
"in",
"c",
":",
"interact",
".",
"title",
"=",
"title_control",
"(",
"obj",
"[",
"'title'",
"]",
")",
"def",
"cb",
"(",
"obj",
")",
":",
"the_times",
".",
"append",
"(",
"\"%.1f\"",
"%",
"obj",
"[",
"'time'",
"]",
")",
"h",
".",
"times",
"=",
"', '",
".",
"join",
"(",
"the_times",
")",
"obj",
"[",
"'E'",
"]",
".",
"ask",
"(",
"cb",
")",
"title",
",",
"question",
",",
"answer",
",",
"check",
",",
"hints",
"=",
"g",
"(",
")",
"# get ready for next time.",
"obj",
"[",
"'title'",
"]",
"=",
"title",
"obj",
"[",
"'E'",
"]",
"=",
"Exercise",
"(",
"question",
",",
"answer",
",",
"check",
",",
"hints",
")"
] | https://github.com/sagemath/cloud/blob/054854b87817edfa95e9044c793059bddc361e67/sage_salvus.py#L2498-L2617 |
||
kemayo/maphilight | e00d927f648c00b634470bc6c4750378b4953cc0 | tools/parse_path.py | python | Sequence | (token) | return OneOrMore(token + maybeComma) | A sequence of the token | A sequence of the token | [
"A",
"sequence",
"of",
"the",
"token"
] | def Sequence(token):
""" A sequence of the token"""
return OneOrMore(token + maybeComma) | [
"def",
"Sequence",
"(",
"token",
")",
":",
"return",
"OneOrMore",
"(",
"token",
"+",
"maybeComma",
")"
] | https://github.com/kemayo/maphilight/blob/e00d927f648c00b634470bc6c4750378b4953cc0/tools/parse_path.py#L25-L27 |
|
openwisp/openwisp-controller | 0bfda7a28c86092f165b177c551c07babcb40630 | openwisp_controller/subnet_division/rule_types/base.py | python | BaseSubnetDivisionRuleType.should_create_subnets_ips | (cls, instance, **kwargs) | return a boolean value whether subnets and IPs should
be provisioned for "instance" object | return a boolean value whether subnets and IPs should
be provisioned for "instance" object | [
"return",
"a",
"boolean",
"value",
"whether",
"subnets",
"and",
"IPs",
"should",
"be",
"provisioned",
"for",
"instance",
"object"
] | def should_create_subnets_ips(cls, instance, **kwargs):
"""
return a boolean value whether subnets and IPs should
be provisioned for "instance" object
"""
raise NotImplementedError() | [
"def",
"should_create_subnets_ips",
"(",
"cls",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/openwisp/openwisp-controller/blob/0bfda7a28c86092f165b177c551c07babcb40630/openwisp_controller/subnet_division/rule_types/base.py#L99-L104 |
||
sbrshk/whatever | f7ba72effd6f836ca701ed889c747db804d5ea8f | node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeAndroidModule | (self, spec) | return ''.join([prefix, middle, suffix]) | Return the Android module name used for a gyp spec.
We use the complete qualified target name to avoid collisions between
duplicate targets in different directories. We also add a suffix to
distinguish gyp-generated module names. | Return the Android module name used for a gyp spec. | [
"Return",
"the",
"Android",
"module",
"name",
"used",
"for",
"a",
"gyp",
"spec",
"."
] | def ComputeAndroidModule(self, spec):
"""Return the Android module name used for a gyp spec.
We use the complete qualified target name to avoid collisions between
duplicate targets in different directories. We also add a suffix to
distinguish gyp-generated module names.
"""
if int(spec.get('android_unmangled_name', 0)):
assert self.type != 'shared_library' or self.target.startswith('lib')
return self.target
if self.type == 'shared_library':
# For reasons of convention, the Android build system requires that all
# shared library modules are named 'libfoo' when generating -l flags.
prefix = 'lib_'
else:
prefix = ''
if spec['toolset'] == 'host':
suffix = '_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'
else:
suffix = '_gyp'
if self.path:
middle = make.StringToMakefileVariable('%s_%s' % (self.path, self.target))
else:
middle = make.StringToMakefileVariable(self.target)
return ''.join([prefix, middle, suffix]) | [
"def",
"ComputeAndroidModule",
"(",
"self",
",",
"spec",
")",
":",
"if",
"int",
"(",
"spec",
".",
"get",
"(",
"'android_unmangled_name'",
",",
"0",
")",
")",
":",
"assert",
"self",
".",
"type",
"!=",
"'shared_library'",
"or",
"self",
".",
"target",
".",
"startswith",
"(",
"'lib'",
")",
"return",
"self",
".",
"target",
"if",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"# For reasons of convention, the Android build system requires that all",
"# shared library modules are named 'libfoo' when generating -l flags.",
"prefix",
"=",
"'lib_'",
"else",
":",
"prefix",
"=",
"''",
"if",
"spec",
"[",
"'toolset'",
"]",
"==",
"'host'",
":",
"suffix",
"=",
"'_$(TARGET_$(GYP_VAR_PREFIX)ARCH)_host_gyp'",
"else",
":",
"suffix",
"=",
"'_gyp'",
"if",
"self",
".",
"path",
":",
"middle",
"=",
"make",
".",
"StringToMakefileVariable",
"(",
"'%s_%s'",
"%",
"(",
"self",
".",
"path",
",",
"self",
".",
"target",
")",
")",
"else",
":",
"middle",
"=",
"make",
".",
"StringToMakefileVariable",
"(",
"self",
".",
"target",
")",
"return",
"''",
".",
"join",
"(",
"[",
"prefix",
",",
"middle",
",",
"suffix",
"]",
")"
] | https://github.com/sbrshk/whatever/blob/f7ba72effd6f836ca701ed889c747db804d5ea8f/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L585-L614 |
|
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | bt5/erp5_big_file/DocumentTemplateItem/portal_components/document.erp5.BigFile.py | python | BigFile._appendData | (self, data_chunk, content_type=None) | append data chunk to the end of the file
NOTE if content_type is specified, it will change content_type for the
whole file. | append data chunk to the end of the file | [
"append",
"data",
"chunk",
"to",
"the",
"end",
"of",
"the",
"file"
] | def _appendData(self, data_chunk, content_type=None):
"""append data chunk to the end of the file
NOTE if content_type is specified, it will change content_type for the
whole file.
"""
data, size = self._read_data(data_chunk, data=self._baseGetData())
content_type=self._get_content_type(data_chunk, data, self.__name__,
content_type or self.content_type)
self.update_data(data, content_type, size) | [
"def",
"_appendData",
"(",
"self",
",",
"data_chunk",
",",
"content_type",
"=",
"None",
")",
":",
"data",
",",
"size",
"=",
"self",
".",
"_read_data",
"(",
"data_chunk",
",",
"data",
"=",
"self",
".",
"_baseGetData",
"(",
")",
")",
"content_type",
"=",
"self",
".",
"_get_content_type",
"(",
"data_chunk",
",",
"data",
",",
"self",
".",
"__name__",
",",
"content_type",
"or",
"self",
".",
"content_type",
")",
"self",
".",
"update_data",
"(",
"data",
",",
"content_type",
",",
"size",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/bt5/erp5_big_file/DocumentTemplateItem/portal_components/document.erp5.BigFile.py#L398-L407 |
||
GoogleCloudPlatform/PerfKitExplorer | 9efa61015d50c25f6d753f0212ad3bf16876d496 | server/perfkit/explorer/samples_mart/explorer_method.py | python | ExplorerQueryBase.__init__ | (self, data_client=None, dataset_name=None) | Create credentials and storage service.
If a data_client is not provided, a credential_file will be used to get
a data connection.
Args:
data_client: A class that provides data connectivity. Typically a
BigQueryClient instance or specialization.
dataset_name: The name of the BigQuery dataset that contains the results. | Create credentials and storage service. | [
"Create",
"credentials",
"and",
"storage",
"service",
"."
] | def __init__(self, data_client=None, dataset_name=None):
"""Create credentials and storage service.
If a data_client is not provided, a credential_file will be used to get
a data connection.
Args:
data_client: A class that provides data connectivity. Typically a
BigQueryClient instance or specialization.
dataset_name: The name of the BigQuery dataset that contains the results.
"""
self._data_client = data_client
self.dataset_name = dataset_name or big_query_client.DATASET_ID
self._Initialize() | [
"def",
"__init__",
"(",
"self",
",",
"data_client",
"=",
"None",
",",
"dataset_name",
"=",
"None",
")",
":",
"self",
".",
"_data_client",
"=",
"data_client",
"self",
".",
"dataset_name",
"=",
"dataset_name",
"or",
"big_query_client",
".",
"DATASET_ID",
"self",
".",
"_Initialize",
"(",
")"
] | https://github.com/GoogleCloudPlatform/PerfKitExplorer/blob/9efa61015d50c25f6d753f0212ad3bf16876d496/server/perfkit/explorer/samples_mart/explorer_method.py#L49-L63 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/difflib.py | python | unified_diff | (a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n') | r"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with ---, +++, or @@) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The unidiff format normally has a header for filenames and modification
times. Any or all of these may be specified using strings for
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
Example:
>>> for line in unified_diff('one two three four'.split(),
... 'zero one tree four'.split(), 'Original', 'Current',
... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
... lineterm=''):
... print line # doctest: +NORMALIZE_WHITESPACE
--- Original 2005-01-26 23:30:50
+++ Current 2010-04-02 10:20:52
@@ -1,4 +1,4 @@
+zero
one
-two
-three
+tree
four | r"""
Compare two sequences of lines; generate the delta as a unified diff. | [
"r",
"Compare",
"two",
"sequences",
"of",
"lines",
";",
"generate",
"the",
"delta",
"as",
"a",
"unified",
"diff",
"."
] | def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n'):
r"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with ---, +++, or @@) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The unidiff format normally has a header for filenames and modification
times. Any or all of these may be specified using strings for
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
Example:
>>> for line in unified_diff('one two three four'.split(),
... 'zero one tree four'.split(), 'Original', 'Current',
... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
... lineterm=''):
... print line # doctest: +NORMALIZE_WHITESPACE
--- Original 2005-01-26 23:30:50
+++ Current 2010-04-02 10:20:52
@@ -1,4 +1,4 @@
+zero
one
-two
-three
+tree
four
"""
started = False
for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
if not started:
started = True
fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
todate = '\t{}'.format(tofiledate) if tofiledate else ''
yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
yield '+++ {}{}{}'.format(tofile, todate, lineterm)
first, last = group[0], group[-1]
file1_range = _format_range_unified(first[1], last[2])
file2_range = _format_range_unified(first[3], last[4])
yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in a[i1:i2]:
yield ' ' + line
continue
if tag in ('replace', 'delete'):
for line in a[i1:i2]:
yield '-' + line
if tag in ('replace', 'insert'):
for line in b[j1:j2]:
yield '+' + line | [
"def",
"unified_diff",
"(",
"a",
",",
"b",
",",
"fromfile",
"=",
"''",
",",
"tofile",
"=",
"''",
",",
"fromfiledate",
"=",
"''",
",",
"tofiledate",
"=",
"''",
",",
"n",
"=",
"3",
",",
"lineterm",
"=",
"'\\n'",
")",
":",
"started",
"=",
"False",
"for",
"group",
"in",
"SequenceMatcher",
"(",
"None",
",",
"a",
",",
"b",
")",
".",
"get_grouped_opcodes",
"(",
"n",
")",
":",
"if",
"not",
"started",
":",
"started",
"=",
"True",
"fromdate",
"=",
"'\\t{}'",
".",
"format",
"(",
"fromfiledate",
")",
"if",
"fromfiledate",
"else",
"''",
"todate",
"=",
"'\\t{}'",
".",
"format",
"(",
"tofiledate",
")",
"if",
"tofiledate",
"else",
"''",
"yield",
"'--- {}{}{}'",
".",
"format",
"(",
"fromfile",
",",
"fromdate",
",",
"lineterm",
")",
"yield",
"'+++ {}{}{}'",
".",
"format",
"(",
"tofile",
",",
"todate",
",",
"lineterm",
")",
"first",
",",
"last",
"=",
"group",
"[",
"0",
"]",
",",
"group",
"[",
"-",
"1",
"]",
"file1_range",
"=",
"_format_range_unified",
"(",
"first",
"[",
"1",
"]",
",",
"last",
"[",
"2",
"]",
")",
"file2_range",
"=",
"_format_range_unified",
"(",
"first",
"[",
"3",
"]",
",",
"last",
"[",
"4",
"]",
")",
"yield",
"'@@ -{} +{} @@{}'",
".",
"format",
"(",
"file1_range",
",",
"file2_range",
",",
"lineterm",
")",
"for",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
"in",
"group",
":",
"if",
"tag",
"==",
"'equal'",
":",
"for",
"line",
"in",
"a",
"[",
"i1",
":",
"i2",
"]",
":",
"yield",
"' '",
"+",
"line",
"continue",
"if",
"tag",
"in",
"(",
"'replace'",
",",
"'delete'",
")",
":",
"for",
"line",
"in",
"a",
"[",
"i1",
":",
"i2",
"]",
":",
"yield",
"'-'",
"+",
"line",
"if",
"tag",
"in",
"(",
"'replace'",
",",
"'insert'",
")",
":",
"for",
"line",
"in",
"b",
"[",
"j1",
":",
"j2",
"]",
":",
"yield",
"'+'",
"+",
"line"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/difflib.py#L1158-L1223 |
||
oldj/SwitchHosts | d0eb2321fe36780ec32c914cbc69a818fc1918d3 | alfred/workflow/web.py | python | request | (method, url, params=None, data=None, headers=None, cookies=None,
files=None, auth=None, timeout=60, allow_redirects=False,
stream=False) | return Response(req, stream) | Initiate an HTTP(S) request. Returns :class:`Response` object.
:param method: 'GET' or 'POST'
:type method: unicode
:param url: URL to open
:type url: unicode
:param params: mapping of URL parameters
:type params: dict
:param data: mapping of form data ``{'field_name': 'value'}`` or
:class:`str`
:type data: dict or str
:param headers: HTTP headers
:type headers: dict
:param cookies: cookies to send to server
:type cookies: dict
:param files: files to upload (see below).
:type files: dict
:param auth: username, password
:type auth: tuple
:param timeout: connection timeout limit in seconds
:type timeout: int
:param allow_redirects: follow redirections
:type allow_redirects: bool
:param stream: Stream content instead of fetching it all at once.
:type stream: bool
:returns: Response object
:rtype: :class:`Response`
The ``files`` argument is a dictionary::
{'fieldname' : { 'filename': 'blah.txt',
'content': '<binary data>',
'mimetype': 'text/plain'}
}
* ``fieldname`` is the name of the field in the HTML form.
* ``mimetype`` is optional. If not provided, :mod:`mimetypes` will
be used to guess the mimetype, or ``application/octet-stream``
will be used. | Initiate an HTTP(S) request. Returns :class:`Response` object. | [
"Initiate",
"an",
"HTTP",
"(",
"S",
")",
"request",
".",
"Returns",
":",
"class",
":",
"Response",
"object",
"."
] | def request(method, url, params=None, data=None, headers=None, cookies=None,
files=None, auth=None, timeout=60, allow_redirects=False,
stream=False):
"""Initiate an HTTP(S) request. Returns :class:`Response` object.
:param method: 'GET' or 'POST'
:type method: unicode
:param url: URL to open
:type url: unicode
:param params: mapping of URL parameters
:type params: dict
:param data: mapping of form data ``{'field_name': 'value'}`` or
:class:`str`
:type data: dict or str
:param headers: HTTP headers
:type headers: dict
:param cookies: cookies to send to server
:type cookies: dict
:param files: files to upload (see below).
:type files: dict
:param auth: username, password
:type auth: tuple
:param timeout: connection timeout limit in seconds
:type timeout: int
:param allow_redirects: follow redirections
:type allow_redirects: bool
:param stream: Stream content instead of fetching it all at once.
:type stream: bool
:returns: Response object
:rtype: :class:`Response`
The ``files`` argument is a dictionary::
{'fieldname' : { 'filename': 'blah.txt',
'content': '<binary data>',
'mimetype': 'text/plain'}
}
* ``fieldname`` is the name of the field in the HTML form.
* ``mimetype`` is optional. If not provided, :mod:`mimetypes` will
be used to guess the mimetype, or ``application/octet-stream``
will be used.
"""
# TODO: cookies
socket.setdefaulttimeout(timeout)
# Default handlers
openers = []
if not allow_redirects:
openers.append(NoRedirectHandler())
if auth is not None: # Add authorisation handler
username, password = auth
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, url, username, password)
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
openers.append(auth_manager)
# Install our custom chain of openers
opener = urllib2.build_opener(*openers)
urllib2.install_opener(opener)
if not headers:
headers = CaseInsensitiveDictionary()
else:
headers = CaseInsensitiveDictionary(headers)
if 'user-agent' not in headers:
headers['user-agent'] = USER_AGENT
# Accept gzip-encoded content
encodings = [s.strip() for s in
headers.get('accept-encoding', '').split(',')]
if 'gzip' not in encodings:
encodings.append('gzip')
headers['accept-encoding'] = ', '.join(encodings)
if files:
if not data:
data = {}
new_headers, data = encode_multipart_formdata(data, files)
headers.update(new_headers)
elif data and isinstance(data, dict):
data = urllib.urlencode(str_dict(data))
# Make sure everything is encoded text
headers = str_dict(headers)
if isinstance(url, unicode):
url = url.encode('utf-8')
if params: # GET args (POST args are handled in encode_multipart_formdata)
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
if query: # Combine query string and `params`
url_params = urlparse.parse_qs(query)
# `params` take precedence over URL query string
url_params.update(params)
params = url_params
query = urllib.urlencode(str_dict(params), doseq=True)
url = urlparse.urlunsplit((scheme, netloc, path, query, fragment))
req = Request(url, data, headers, method=method)
return Response(req, stream) | [
"def",
"request",
"(",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"cookies",
"=",
"None",
",",
"files",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"timeout",
"=",
"60",
",",
"allow_redirects",
"=",
"False",
",",
"stream",
"=",
"False",
")",
":",
"# TODO: cookies",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"# Default handlers",
"openers",
"=",
"[",
"]",
"if",
"not",
"allow_redirects",
":",
"openers",
".",
"append",
"(",
"NoRedirectHandler",
"(",
")",
")",
"if",
"auth",
"is",
"not",
"None",
":",
"# Add authorisation handler",
"username",
",",
"password",
"=",
"auth",
"password_manager",
"=",
"urllib2",
".",
"HTTPPasswordMgrWithDefaultRealm",
"(",
")",
"password_manager",
".",
"add_password",
"(",
"None",
",",
"url",
",",
"username",
",",
"password",
")",
"auth_manager",
"=",
"urllib2",
".",
"HTTPBasicAuthHandler",
"(",
"password_manager",
")",
"openers",
".",
"append",
"(",
"auth_manager",
")",
"# Install our custom chain of openers",
"opener",
"=",
"urllib2",
".",
"build_opener",
"(",
"*",
"openers",
")",
"urllib2",
".",
"install_opener",
"(",
"opener",
")",
"if",
"not",
"headers",
":",
"headers",
"=",
"CaseInsensitiveDictionary",
"(",
")",
"else",
":",
"headers",
"=",
"CaseInsensitiveDictionary",
"(",
"headers",
")",
"if",
"'user-agent'",
"not",
"in",
"headers",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"USER_AGENT",
"# Accept gzip-encoded content",
"encodings",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"headers",
".",
"get",
"(",
"'accept-encoding'",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"]",
"if",
"'gzip'",
"not",
"in",
"encodings",
":",
"encodings",
".",
"append",
"(",
"'gzip'",
")",
"headers",
"[",
"'accept-encoding'",
"]",
"=",
"', '",
".",
"join",
"(",
"encodings",
")",
"if",
"files",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"new_headers",
",",
"data",
"=",
"encode_multipart_formdata",
"(",
"data",
",",
"files",
")",
"headers",
".",
"update",
"(",
"new_headers",
")",
"elif",
"data",
"and",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"urllib",
".",
"urlencode",
"(",
"str_dict",
"(",
"data",
")",
")",
"# Make sure everything is encoded text",
"headers",
"=",
"str_dict",
"(",
"headers",
")",
"if",
"isinstance",
"(",
"url",
",",
"unicode",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"params",
":",
"# GET args (POST args are handled in encode_multipart_formdata)",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"query",
":",
"# Combine query string and `params`",
"url_params",
"=",
"urlparse",
".",
"parse_qs",
"(",
"query",
")",
"# `params` take precedence over URL query string",
"url_params",
".",
"update",
"(",
"params",
")",
"params",
"=",
"url_params",
"query",
"=",
"urllib",
".",
"urlencode",
"(",
"str_dict",
"(",
"params",
")",
",",
"doseq",
"=",
"True",
")",
"url",
"=",
"urlparse",
".",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
")",
")",
"req",
"=",
"Request",
"(",
"url",
",",
"data",
",",
"headers",
",",
"method",
"=",
"method",
")",
"return",
"Response",
"(",
"req",
",",
"stream",
")"
] | https://github.com/oldj/SwitchHosts/blob/d0eb2321fe36780ec32c914cbc69a818fc1918d3/alfred/workflow/web.py#L482-L591 |
|
redapple0204/my-boring-python | 1ab378e9d4f39ad920ff542ef3b2db68f0575a98 | pythonenv3.8/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.py | python | TempDirectory.create | (self) | Create a temporary directory and store its path in self.path | Create a temporary directory and store its path in self.path | [
"Create",
"a",
"temporary",
"directory",
"and",
"store",
"its",
"path",
"in",
"self",
".",
"path"
] | def create(self):
"""Create a temporary directory and store its path in self.path
"""
if self.path is not None:
logger.debug(
"Skipped creation of temporary directory: {}".format(self.path)
)
return
# We realpath here because some systems have their default tmpdir
# symlinked to another directory. This tends to confuse build
# scripts, so we canonicalize the path by traversing potential
# symlinks here.
self.path = os.path.realpath(
tempfile.mkdtemp(prefix="pip-{}-".format(self.kind))
)
logger.debug("Created temporary directory: {}".format(self.path)) | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
"is",
"not",
"None",
":",
"logger",
".",
"debug",
"(",
"\"Skipped creation of temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")",
"return",
"# We realpath here because some systems have their default tmpdir",
"# symlinked to another directory. This tends to confuse build",
"# scripts, so we canonicalize the path by traversing potential",
"# symlinks here.",
"self",
".",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"\"pip-{}-\"",
".",
"format",
"(",
"self",
".",
"kind",
")",
")",
")",
"logger",
".",
"debug",
"(",
"\"Created temporary directory: {}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")"
] | https://github.com/redapple0204/my-boring-python/blob/1ab378e9d4f39ad920ff542ef3b2db68f0575a98/pythonenv3.8/lib/python3.8/site-packages/pip/_internal/utils/temp_dir.py#L62-L77 |
||
mdipierro/web2py-appliances | f97658293d51519e5f06e1ed503ee85f8154fcf3 | FacebookConnectExample/modules/plugin_fbconnect/facebook.py | python | PhotosProxy.upload | (self, image, aid=None, caption=None, size=(604, 1024)) | return self._client._parse_response(response, 'facebook.photos.upload') | Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload
size -- an optional size (width, height) to resize the image to before uploading. Resizes by default
to Facebook's maximum display width of 604. | Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload | [
"Facebook",
"API",
"call",
".",
"See",
"http",
":",
"//",
"developers",
".",
"facebook",
".",
"com",
"/",
"documentation",
".",
"php?v",
"=",
"1",
".",
"0&method",
"=",
"photos",
".",
"upload"
] | def upload(self, image, aid=None, caption=None, size=(604, 1024)):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=photos.upload
size -- an optional size (width, height) to resize the image to before uploading. Resizes by default
to Facebook's maximum display width of 604.
"""
args = {}
if aid is not None:
args['aid'] = aid
if caption is not None:
args['caption'] = caption
args = self._client._build_post_args('facebook.photos.upload', self._client._add_session_args(args))
try:
import cStringIO as StringIO
except ImportError:
import StringIO
try:
import Image
except ImportError:
data = StringIO.StringIO(open(image, 'rb').read())
else:
img = Image.open(image)
if size:
img.thumbnail(size, Image.ANTIALIAS)
data = StringIO.StringIO()
img.save(data, img.format)
content_type, body = self.__encode_multipart_formdata(list(args.iteritems()), [(image, data)])
h = httplib.HTTP('api.facebook.com')
h.putrequest('POST', '/restserver.php')
h.putheader('Content-Type', content_type)
h.putheader('Content-Length', str(len(body)))
h.putheader('MIME-Version', '1.0')
h.putheader('User-Agent', 'PyFacebook Client Library')
h.endheaders()
h.send(body)
reply = h.getreply()
if reply[0] != 200:
raise Exception('Error uploading photo: Facebook returned HTTP %s (%s)' % (reply[0], reply[1]))
response = h.file.read()
return self._client._parse_response(response, 'facebook.photos.upload') | [
"def",
"upload",
"(",
"self",
",",
"image",
",",
"aid",
"=",
"None",
",",
"caption",
"=",
"None",
",",
"size",
"=",
"(",
"604",
",",
"1024",
")",
")",
":",
"args",
"=",
"{",
"}",
"if",
"aid",
"is",
"not",
"None",
":",
"args",
"[",
"'aid'",
"]",
"=",
"aid",
"if",
"caption",
"is",
"not",
"None",
":",
"args",
"[",
"'caption'",
"]",
"=",
"caption",
"args",
"=",
"self",
".",
"_client",
".",
"_build_post_args",
"(",
"'facebook.photos.upload'",
",",
"self",
".",
"_client",
".",
"_add_session_args",
"(",
"args",
")",
")",
"try",
":",
"import",
"cStringIO",
"as",
"StringIO",
"except",
"ImportError",
":",
"import",
"StringIO",
"try",
":",
"import",
"Image",
"except",
"ImportError",
":",
"data",
"=",
"StringIO",
".",
"StringIO",
"(",
"open",
"(",
"image",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
"else",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"image",
")",
"if",
"size",
":",
"img",
".",
"thumbnail",
"(",
"size",
",",
"Image",
".",
"ANTIALIAS",
")",
"data",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"img",
".",
"save",
"(",
"data",
",",
"img",
".",
"format",
")",
"content_type",
",",
"body",
"=",
"self",
".",
"__encode_multipart_formdata",
"(",
"list",
"(",
"args",
".",
"iteritems",
"(",
")",
")",
",",
"[",
"(",
"image",
",",
"data",
")",
"]",
")",
"h",
"=",
"httplib",
".",
"HTTP",
"(",
"'api.facebook.com'",
")",
"h",
".",
"putrequest",
"(",
"'POST'",
",",
"'/restserver.php'",
")",
"h",
".",
"putheader",
"(",
"'Content-Type'",
",",
"content_type",
")",
"h",
".",
"putheader",
"(",
"'Content-Length'",
",",
"str",
"(",
"len",
"(",
"body",
")",
")",
")",
"h",
".",
"putheader",
"(",
"'MIME-Version'",
",",
"'1.0'",
")",
"h",
".",
"putheader",
"(",
"'User-Agent'",
",",
"'PyFacebook Client Library'",
")",
"h",
".",
"endheaders",
"(",
")",
"h",
".",
"send",
"(",
"body",
")",
"reply",
"=",
"h",
".",
"getreply",
"(",
")",
"if",
"reply",
"[",
"0",
"]",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"'Error uploading photo: Facebook returned HTTP %s (%s)'",
"%",
"(",
"reply",
"[",
"0",
"]",
",",
"reply",
"[",
"1",
"]",
")",
")",
"response",
"=",
"h",
".",
"file",
".",
"read",
"(",
")",
"return",
"self",
".",
"_client",
".",
"_parse_response",
"(",
"response",
",",
"'facebook.photos.upload'",
")"
] | https://github.com/mdipierro/web2py-appliances/blob/f97658293d51519e5f06e1ed503ee85f8154fcf3/FacebookConnectExample/modules/plugin_fbconnect/facebook.py#L471-L520 |
|
aosabook/500lines | fba689d101eb5600f5c8f4d7fd79912498e950e2 | contingent/code/contingent/graphlib.py | python | Graph.immediate_consequences_of | (self, task) | return self.sorted(self._consequences_of[task]) | Return the tasks that use `task` as an input. | Return the tasks that use `task` as an input. | [
"Return",
"the",
"tasks",
"that",
"use",
"task",
"as",
"an",
"input",
"."
] | def immediate_consequences_of(self, task):
"""Return the tasks that use `task` as an input."""
return self.sorted(self._consequences_of[task]) | [
"def",
"immediate_consequences_of",
"(",
"self",
",",
"task",
")",
":",
"return",
"self",
".",
"sorted",
"(",
"self",
".",
"_consequences_of",
"[",
"task",
"]",
")"
] | https://github.com/aosabook/500lines/blob/fba689d101eb5600f5c8f4d7fd79912498e950e2/contingent/code/contingent/graphlib.py#L70-L72 |
|
SteeltoeOSS/Samples | a27be0f2fd2af0e263f32aceb131df21fb54c82b | steps/browser_steps.py | python | step_impl | (context, data, url) | :type context: behave.runner.Context
:type data: str
:type url: str | :type context: behave.runner.Context
:type data: str
:type url: str | [
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context",
":",
"type",
"data",
":",
"str",
":",
"type",
"url",
":",
"str"
] | def step_impl(context, data, url):
"""
:type context: behave.runner.Context
:type data: str
:type url: str
"""
url = dns.resolve_url(context, url)
fields = data.split('=')
assert len(fields) == 2, 'Invalid data format: {}'.format(data)
payload = {fields[0]: fields[1]}
context.log.info('posting url {} {}'.format(url, payload))
context.browser = mechanicalsoup.StatefulBrowser()
resp = context.browser.post(url, data=payload)
context.log.info('POST {} [{}]'.format(url, resp.status_code)) | [
"def",
"step_impl",
"(",
"context",
",",
"data",
",",
"url",
")",
":",
"url",
"=",
"dns",
".",
"resolve_url",
"(",
"context",
",",
"url",
")",
"fields",
"=",
"data",
".",
"split",
"(",
"'='",
")",
"assert",
"len",
"(",
"fields",
")",
"==",
"2",
",",
"'Invalid data format: {}'",
".",
"format",
"(",
"data",
")",
"payload",
"=",
"{",
"fields",
"[",
"0",
"]",
":",
"fields",
"[",
"1",
"]",
"}",
"context",
".",
"log",
".",
"info",
"(",
"'posting url {} {}'",
".",
"format",
"(",
"url",
",",
"payload",
")",
")",
"context",
".",
"browser",
"=",
"mechanicalsoup",
".",
"StatefulBrowser",
"(",
")",
"resp",
"=",
"context",
".",
"browser",
".",
"post",
"(",
"url",
",",
"data",
"=",
"payload",
")",
"context",
".",
"log",
".",
"info",
"(",
"'POST {} [{}]'",
".",
"format",
"(",
"url",
",",
"resp",
".",
"status_code",
")",
")"
] | https://github.com/SteeltoeOSS/Samples/blob/a27be0f2fd2af0e263f32aceb131df21fb54c82b/steps/browser_steps.py#L34-L47 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/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/closured/lib/python2.7/xml/dom/expatbuilder.py#L732-L737 |
||
opencoweb/coweb | 7b3a87ee9eda735a859447d404ee16edde1c5671 | servers/python/coweb/service/manager/object.py | python | ObjectServiceManager.get_manager_id | (self) | return 'object' | Manager id is object matching wrapper module name. | Manager id is object matching wrapper module name. | [
"Manager",
"id",
"is",
"object",
"matching",
"wrapper",
"module",
"name",
"."
] | def get_manager_id(self):
'''Manager id is object matching wrapper module name.'''
return 'object' | [
"def",
"get_manager_id",
"(",
"self",
")",
":",
"return",
"'object'"
] | https://github.com/opencoweb/coweb/blob/7b3a87ee9eda735a859447d404ee16edde1c5671/servers/python/coweb/service/manager/object.py#L10-L12 |
|
ctripcorp/tars | d7954fccaf1a17901f22d844d84c5663a3d79c11 | tars/api/views/deployment.py | python | DeploymentViewSet.reset | (self, request, pk=None, format=None) | return self.retrieve(request) | temp for develop | temp for develop | [
"temp",
"for",
"develop"
] | def reset(self, request, pk=None, format=None):
"""
temp for develop
"""
deployment = self.get_object()
deployment.reset()
return self.retrieve(request) | [
"def",
"reset",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"deployment",
"=",
"self",
".",
"get_object",
"(",
")",
"deployment",
".",
"reset",
"(",
")",
"return",
"self",
".",
"retrieve",
"(",
"request",
")"
] | https://github.com/ctripcorp/tars/blob/d7954fccaf1a17901f22d844d84c5663a3d79c11/tars/api/views/deployment.py#L363-L369 |
|
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/pypng-0.0.9/code/png.py | python | Reader.validate_signature | (self) | If signature (header) has not been read then read and
validate it; otherwise do nothing. | If signature (header) has not been read then read and
validate it; otherwise do nothing. | [
"If",
"signature",
"(",
"header",
")",
"has",
"not",
"been",
"read",
"then",
"read",
"and",
"validate",
"it",
";",
"otherwise",
"do",
"nothing",
"."
] | def validate_signature(self):
"""If signature (header) has not been read then read and
validate it; otherwise do nothing.
"""
if self.signature:
return
self.signature = self.file.read(8)
if self.signature != _signature:
raise FormatError("PNG file has invalid signature.") | [
"def",
"validate_signature",
"(",
"self",
")",
":",
"if",
"self",
".",
"signature",
":",
"return",
"self",
".",
"signature",
"=",
"self",
".",
"file",
".",
"read",
"(",
"8",
")",
"if",
"self",
".",
"signature",
"!=",
"_signature",
":",
"raise",
"FormatError",
"(",
"\"PNG file has invalid signature.\"",
")"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/pypng-0.0.9/code/png.py#L1428-L1437 |
||
mceSystems/node-jsc | 90634f3064fab8e89a85b3942f0cc5054acc86fa | deps/v8/gypfiles/vs_toolchain.py | python | Update | (force=False) | return 0 | Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|. | Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|. | [
"Requests",
"an",
"update",
"of",
"the",
"toolchain",
"to",
"the",
"specific",
"hashes",
"we",
"have",
"at",
"this",
"revision",
".",
"The",
"update",
"outputs",
"a",
".",
"json",
"of",
"the",
"various",
"configuration",
"information",
"required",
"to",
"pass",
"to",
"gyp",
"which",
"we",
"use",
"in",
"|GetToolchainDir",
"()",
"|",
"."
] | def Update(force=False):
"""Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|.
"""
if force != False and force != '--force':
print >>sys.stderr, 'Unknown parameter "%s"' % force
return 1
if force == '--force' or os.path.exists(json_data_file):
force = True
depot_tools_win_toolchain = \
bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
if ((sys.platform in ('win32', 'cygwin') or force) and
depot_tools_win_toolchain):
import find_depot_tools
depot_tools_path = find_depot_tools.add_depot_tools_to_path()
# Necessary so that get_toolchain_if_necessary.py will put the VS toolkit
# in the correct directory.
os.environ['GYP_MSVS_VERSION'] = GetVisualStudioVersion()
get_toolchain_args = [
sys.executable,
os.path.join(depot_tools_path,
'win_toolchain',
'get_toolchain_if_necessary.py'),
'--output-json', json_data_file,
] + _GetDesiredVsToolchainHashes()
if force:
get_toolchain_args.append('--force')
subprocess.check_call(get_toolchain_args)
return 0 | [
"def",
"Update",
"(",
"force",
"=",
"False",
")",
":",
"if",
"force",
"!=",
"False",
"and",
"force",
"!=",
"'--force'",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"'Unknown parameter \"%s\"'",
"%",
"force",
"return",
"1",
"if",
"force",
"==",
"'--force'",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"json_data_file",
")",
":",
"force",
"=",
"True",
"depot_tools_win_toolchain",
"=",
"bool",
"(",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'DEPOT_TOOLS_WIN_TOOLCHAIN'",
",",
"'1'",
")",
")",
")",
"if",
"(",
"(",
"sys",
".",
"platform",
"in",
"(",
"'win32'",
",",
"'cygwin'",
")",
"or",
"force",
")",
"and",
"depot_tools_win_toolchain",
")",
":",
"import",
"find_depot_tools",
"depot_tools_path",
"=",
"find_depot_tools",
".",
"add_depot_tools_to_path",
"(",
")",
"# Necessary so that get_toolchain_if_necessary.py will put the VS toolkit",
"# in the correct directory.",
"os",
".",
"environ",
"[",
"'GYP_MSVS_VERSION'",
"]",
"=",
"GetVisualStudioVersion",
"(",
")",
"get_toolchain_args",
"=",
"[",
"sys",
".",
"executable",
",",
"os",
".",
"path",
".",
"join",
"(",
"depot_tools_path",
",",
"'win_toolchain'",
",",
"'get_toolchain_if_necessary.py'",
")",
",",
"'--output-json'",
",",
"json_data_file",
",",
"]",
"+",
"_GetDesiredVsToolchainHashes",
"(",
")",
"if",
"force",
":",
"get_toolchain_args",
".",
"append",
"(",
"'--force'",
")",
"subprocess",
".",
"check_call",
"(",
"get_toolchain_args",
")",
"return",
"0"
] | https://github.com/mceSystems/node-jsc/blob/90634f3064fab8e89a85b3942f0cc5054acc86fa/deps/v8/gypfiles/vs_toolchain.py#L294-L325 |
|
nodejs/http2 | 734ad72e3939e62bcff0f686b8ec426b8aaa22e3 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py | python | OrderedDict.values | (self) | return [self[key] for key in self] | od.values() -> list of values in od | od.values() -> list of values in od | [
"od",
".",
"values",
"()",
"-",
">",
"list",
"of",
"values",
"in",
"od"
] | def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self] | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"[",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"]"
] | https://github.com/nodejs/http2/blob/734ad72e3939e62bcff0f686b8ec426b8aaa22e3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/ordered_dict.py#L147-L149 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | agora_site/agora_core/resources/agora.py | python | AgoraResource.join_action | (self, request, agora, **kwargs) | return self.create_response(request, dict(status="success")) | Action that an user can execute to join an agora if it has permissions | Action that an user can execute to join an agora if it has permissions | [
"Action",
"that",
"an",
"user",
"can",
"execute",
"to",
"join",
"an",
"agora",
"if",
"it",
"has",
"permissions"
] | def join_action(self, request, agora, **kwargs):
'''
Action that an user can execute to join an agora if it has permissions
'''
request.user.get_profile().add_to_agora(agora_id=agora.id, request=request)
return self.create_response(request, dict(status="success")) | [
"def",
"join_action",
"(",
"self",
",",
"request",
",",
"agora",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
".",
"user",
".",
"get_profile",
"(",
")",
".",
"add_to_agora",
"(",
"agora_id",
"=",
"agora",
".",
"id",
",",
"request",
"=",
"request",
")",
"return",
"self",
".",
"create_response",
"(",
"request",
",",
"dict",
"(",
"status",
"=",
"\"success\"",
")",
")"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/agora_core/resources/agora.py#L622-L628 |
|
odoo/odoo | 8de8c196a137f4ebbf67d7c7c83fee36f873f5c8 | odoo/tools/translate.py | python | trans_load_data | (cr, fileobj, fileformat, lang,
verbose=True, create_empty_translation=False, overwrite=False) | Populates the ir_translation table.
:param fileobj: buffer open to a translation file
:param fileformat: format of the `fielobj` file, one of 'po' or 'csv'
:param lang: language code of the translations contained in `fileobj`
language must be present and activated in the database
:param verbose: increase log output
:param create_empty_translation: create an ir.translation record, even if no value
is provided in the translation entry
:param overwrite: if an ir.translation already exists for a term, replace it with
the one in `fileobj` | Populates the ir_translation table. | [
"Populates",
"the",
"ir_translation",
"table",
"."
] | def trans_load_data(cr, fileobj, fileformat, lang,
verbose=True, create_empty_translation=False, overwrite=False):
"""Populates the ir_translation table.
:param fileobj: buffer open to a translation file
:param fileformat: format of the `fielobj` file, one of 'po' or 'csv'
:param lang: language code of the translations contained in `fileobj`
language must be present and activated in the database
:param verbose: increase log output
:param create_empty_translation: create an ir.translation record, even if no value
is provided in the translation entry
:param overwrite: if an ir.translation already exists for a term, replace it with
the one in `fileobj`
"""
if verbose:
_logger.info('loading translation file for language %s', lang)
env = odoo.api.Environment(cr, odoo.SUPERUSER_ID, {})
try:
if not env['res.lang']._lang_get(lang):
_logger.error("Couldn't read translation for lang '%s', language not found", lang)
return None
# now, the serious things: we read the language file
fileobj.seek(0)
reader = TranslationFileReader(fileobj, fileformat=fileformat)
# read the rest of the file with a cursor-like object for fast inserting translations"
Translation = env['ir.translation']
irt_cursor = Translation._get_import_cursor(overwrite)
def process_row(row):
"""Process a single PO (or POT) entry."""
# dictionary which holds values for this line of the csv file
# {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
# 'src': ..., 'value': ..., 'module':...}
dic = dict.fromkeys(('type', 'name', 'res_id', 'src', 'value',
'comments', 'imd_model', 'imd_name', 'module'))
dic['lang'] = lang
dic.update(row)
# do not import empty values
if not create_empty_translation and not dic['value']:
return
irt_cursor.push(dic)
# First process the entries from the PO file (doing so also fills/removes
# the entries from the POT file).
for row in reader:
process_row(row)
irt_cursor.finish()
Translation.clear_caches()
if verbose:
_logger.info("translation file loaded successfully")
except IOError:
iso_lang = get_iso_codes(lang)
filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
_logger.exception("couldn't read translation file %s", filename) | [
"def",
"trans_load_data",
"(",
"cr",
",",
"fileobj",
",",
"fileformat",
",",
"lang",
",",
"verbose",
"=",
"True",
",",
"create_empty_translation",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"_logger",
".",
"info",
"(",
"'loading translation file for language %s'",
",",
"lang",
")",
"env",
"=",
"odoo",
".",
"api",
".",
"Environment",
"(",
"cr",
",",
"odoo",
".",
"SUPERUSER_ID",
",",
"{",
"}",
")",
"try",
":",
"if",
"not",
"env",
"[",
"'res.lang'",
"]",
".",
"_lang_get",
"(",
"lang",
")",
":",
"_logger",
".",
"error",
"(",
"\"Couldn't read translation for lang '%s', language not found\"",
",",
"lang",
")",
"return",
"None",
"# now, the serious things: we read the language file",
"fileobj",
".",
"seek",
"(",
"0",
")",
"reader",
"=",
"TranslationFileReader",
"(",
"fileobj",
",",
"fileformat",
"=",
"fileformat",
")",
"# read the rest of the file with a cursor-like object for fast inserting translations\"",
"Translation",
"=",
"env",
"[",
"'ir.translation'",
"]",
"irt_cursor",
"=",
"Translation",
".",
"_get_import_cursor",
"(",
"overwrite",
")",
"def",
"process_row",
"(",
"row",
")",
":",
"\"\"\"Process a single PO (or POT) entry.\"\"\"",
"# dictionary which holds values for this line of the csv file",
"# {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,",
"# 'src': ..., 'value': ..., 'module':...}",
"dic",
"=",
"dict",
".",
"fromkeys",
"(",
"(",
"'type'",
",",
"'name'",
",",
"'res_id'",
",",
"'src'",
",",
"'value'",
",",
"'comments'",
",",
"'imd_model'",
",",
"'imd_name'",
",",
"'module'",
")",
")",
"dic",
"[",
"'lang'",
"]",
"=",
"lang",
"dic",
".",
"update",
"(",
"row",
")",
"# do not import empty values",
"if",
"not",
"create_empty_translation",
"and",
"not",
"dic",
"[",
"'value'",
"]",
":",
"return",
"irt_cursor",
".",
"push",
"(",
"dic",
")",
"# First process the entries from the PO file (doing so also fills/removes",
"# the entries from the POT file).",
"for",
"row",
"in",
"reader",
":",
"process_row",
"(",
"row",
")",
"irt_cursor",
".",
"finish",
"(",
")",
"Translation",
".",
"clear_caches",
"(",
")",
"if",
"verbose",
":",
"_logger",
".",
"info",
"(",
"\"translation file loaded successfully\"",
")",
"except",
"IOError",
":",
"iso_lang",
"=",
"get_iso_codes",
"(",
"lang",
")",
"filename",
"=",
"'[lang: %s][format: %s]'",
"%",
"(",
"iso_lang",
"or",
"'new'",
",",
"fileformat",
")",
"_logger",
".",
"exception",
"(",
"\"couldn't read translation file %s\"",
",",
"filename",
")"
] | https://github.com/odoo/odoo/blob/8de8c196a137f4ebbf67d7c7c83fee36f873f5c8/odoo/tools/translate.py#L1169-L1230 |
||
nodejs/node-chakracore | 770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43 | deps/chakrashim/third_party/jinja2/jinja2/utils.py | python | LRUCache.__setitem__ | (self, key, value) | Sets the value for an item. Moves the item up so that it
has the highest priority then. | Sets the value for an item. Moves the item up so that it
has the highest priority then. | [
"Sets",
"the",
"value",
"for",
"an",
"item",
".",
"Moves",
"the",
"item",
"up",
"so",
"that",
"it",
"has",
"the",
"highest",
"priority",
"then",
"."
] | def __setitem__(self, key, value):
"""Sets the value for an item. Moves the item up so that it
has the highest priority then.
"""
self._wlock.acquire()
try:
if key in self._mapping:
self._remove(key)
elif len(self._mapping) == self.capacity:
del self._mapping[self._popleft()]
self._append(key)
self._mapping[key] = value
finally:
self._wlock.release() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"_wlock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"key",
"in",
"self",
".",
"_mapping",
":",
"self",
".",
"_remove",
"(",
"key",
")",
"elif",
"len",
"(",
"self",
".",
"_mapping",
")",
"==",
"self",
".",
"capacity",
":",
"del",
"self",
".",
"_mapping",
"[",
"self",
".",
"_popleft",
"(",
")",
"]",
"self",
".",
"_append",
"(",
"key",
")",
"self",
".",
"_mapping",
"[",
"key",
"]",
"=",
"value",
"finally",
":",
"self",
".",
"_wlock",
".",
"release",
"(",
")"
] | https://github.com/nodejs/node-chakracore/blob/770c8dcd1bc3e0fce2d4497b4eec3fe49d829d43/deps/chakrashim/third_party/jinja2/jinja2/utils.py#L413-L426 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py | python | AndroidMkWriter.ComputeOutput | (self, spec) | return os.path.join(path, self.ComputeOutputBasename(spec)) | Return the 'output' (full output path) of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'$(obj)/baz/libfoobar.so' | Return the 'output' (full output path) of a gyp spec. | [
"Return",
"the",
"output",
"(",
"full",
"output",
"path",
")",
"of",
"a",
"gyp",
"spec",
"."
] | def ComputeOutput(self, spec):
"""Return the 'output' (full output path) of a gyp spec.
E.g., the loadable module 'foobar' in directory 'baz' will produce
'$(obj)/baz/libfoobar.so'
"""
if self.type == 'executable':
# We install host executables into shared_intermediate_dir so they can be
# run by gyp rules that refer to PRODUCT_DIR.
path = '$(gyp_shared_intermediate_dir)'
elif self.type == 'shared_library':
if self.toolset == 'host':
path = '$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'
else:
path = '$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'
else:
# Other targets just get built into their intermediate dir.
if self.toolset == 'host':
path = ('$(call intermediates-dir-for,%s,%s,true,,'
'$(GYP_HOST_VAR_PREFIX))' % (self.android_class,
self.android_module))
else:
path = ('$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'
% (self.android_class, self.android_module))
assert spec.get('product_dir') is None # TODO: not supported?
return os.path.join(path, self.ComputeOutputBasename(spec)) | [
"def",
"ComputeOutput",
"(",
"self",
",",
"spec",
")",
":",
"if",
"self",
".",
"type",
"==",
"'executable'",
":",
"# We install host executables into shared_intermediate_dir so they can be",
"# run by gyp rules that refer to PRODUCT_DIR.",
"path",
"=",
"'$(gyp_shared_intermediate_dir)'",
"elif",
"self",
".",
"type",
"==",
"'shared_library'",
":",
"if",
"self",
".",
"toolset",
"==",
"'host'",
":",
"path",
"=",
"'$($(GYP_HOST_VAR_PREFIX)HOST_OUT_INTERMEDIATE_LIBRARIES)'",
"else",
":",
"path",
"=",
"'$($(GYP_VAR_PREFIX)TARGET_OUT_INTERMEDIATE_LIBRARIES)'",
"else",
":",
"# Other targets just get built into their intermediate dir.",
"if",
"self",
".",
"toolset",
"==",
"'host'",
":",
"path",
"=",
"(",
"'$(call intermediates-dir-for,%s,%s,true,,'",
"'$(GYP_HOST_VAR_PREFIX))'",
"%",
"(",
"self",
".",
"android_class",
",",
"self",
".",
"android_module",
")",
")",
"else",
":",
"path",
"=",
"(",
"'$(call intermediates-dir-for,%s,%s,,,$(GYP_VAR_PREFIX))'",
"%",
"(",
"self",
".",
"android_class",
",",
"self",
".",
"android_module",
")",
")",
"assert",
"spec",
".",
"get",
"(",
"'product_dir'",
")",
"is",
"None",
"# TODO: not supported?",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"self",
".",
"ComputeOutputBasename",
"(",
"spec",
")",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L662-L688 |
|
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.GetLdflags | (self, config, gyp_to_build_path, expand_special,
manifest_base_name, output_name, is_executable, build_dir) | return ldflags, intermediate_manifest, manifest_files | Returns the flags that need to be added to link commands, and the
manifest files. | Returns the flags that need to be added to link commands, and the
manifest files. | [
"Returns",
"the",
"flags",
"that",
"need",
"to",
"be",
"added",
"to",
"link",
"commands",
"and",
"the",
"manifest",
"files",
"."
] | def GetLdflags(self, config, gyp_to_build_path, expand_special,
manifest_base_name, output_name, is_executable, build_dir):
"""Returns the flags that need to be added to link commands, and the
manifest files."""
config = self._TargetConfig(config)
ldflags = []
ld = self._GetWrapper(self, self.msvs_settings[config],
'VCLinkerTool', append=ldflags)
self._GetDefFileAsLdflags(ldflags, gyp_to_build_path)
ld('GenerateDebugInformation', map={'true': '/DEBUG'})
ld('TargetMachine', map={'1': 'X86', '17': 'X64', '3': 'ARM'},
prefix='/MACHINE:')
ldflags.extend(self._GetAdditionalLibraryDirectories(
'VCLinkerTool', config, gyp_to_build_path))
ld('DelayLoadDLLs', prefix='/DELAYLOAD:')
ld('TreatLinkerWarningAsErrors', prefix='/WX',
map={'true': '', 'false': ':NO'})
out = self.GetOutputName(config, expand_special)
if out:
ldflags.append('/OUT:' + out)
pdb = self.GetPDBName(config, expand_special, output_name + '.pdb')
if pdb:
ldflags.append('/PDB:' + pdb)
pgd = self.GetPGDName(config, expand_special)
if pgd:
ldflags.append('/PGD:' + pgd)
map_file = self.GetMapFileName(config, expand_special)
ld('GenerateMapFile', map={'true': '/MAP:' + map_file if map_file
else '/MAP'})
ld('MapExports', map={'true': '/MAPINFO:EXPORTS'})
ld('AdditionalOptions', prefix='')
minimum_required_version = self._Setting(
('VCLinkerTool', 'MinimumRequiredVersion'), config, default='')
if minimum_required_version:
minimum_required_version = ',' + minimum_required_version
ld('SubSystem',
map={'1': 'CONSOLE%s' % minimum_required_version,
'2': 'WINDOWS%s' % minimum_required_version},
prefix='/SUBSYSTEM:')
ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE')
ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL')
ld('BaseAddress', prefix='/BASE:')
ld('FixedBaseAddress', map={'1': ':NO', '2': ''}, prefix='/FIXED')
ld('RandomizedBaseAddress',
map={'1': ':NO', '2': ''}, prefix='/DYNAMICBASE')
ld('DataExecutionPrevention',
map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT')
ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:')
ld('ForceSymbolReferences', prefix='/INCLUDE:')
ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:')
ld('LinkTimeCodeGeneration',
map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE',
'4': ':PGUPDATE'},
prefix='/LTCG')
ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:')
ld('ResourceOnlyDLL', map={'true': '/NOENTRY'})
ld('EntryPointSymbol', prefix='/ENTRY:')
ld('Profile', map={'true': '/PROFILE'})
ld('LargeAddressAware',
map={'1': ':NO', '2': ''}, prefix='/LARGEADDRESSAWARE')
# TODO(scottmg): This should sort of be somewhere else (not really a flag).
ld('AdditionalDependencies', prefix='')
if self.GetArch(config) == 'x86':
safeseh_default = 'true'
else:
safeseh_default = None
ld('ImageHasSafeExceptionHandlers',
map={'false': ':NO', 'true': ''}, prefix='/SAFESEH',
default=safeseh_default)
# If the base address is not specifically controlled, DYNAMICBASE should
# be on by default.
base_flags = filter(lambda x: 'DYNAMICBASE' in x or x == '/FIXED',
ldflags)
if not base_flags:
ldflags.append('/DYNAMICBASE')
# If the NXCOMPAT flag has not been specified, default to on. Despite the
# documentation that says this only defaults to on when the subsystem is
# Vista or greater (which applies to the linker), the IDE defaults it on
# unless it's explicitly off.
if not filter(lambda x: 'NXCOMPAT' in x, ldflags):
ldflags.append('/NXCOMPAT')
have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags)
manifest_flags, intermediate_manifest, manifest_files = \
self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path,
is_executable and not have_def_file, build_dir)
ldflags.extend(manifest_flags)
return ldflags, intermediate_manifest, manifest_files | [
"def",
"GetLdflags",
"(",
"self",
",",
"config",
",",
"gyp_to_build_path",
",",
"expand_special",
",",
"manifest_base_name",
",",
"output_name",
",",
"is_executable",
",",
"build_dir",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"ldflags",
"=",
"[",
"]",
"ld",
"=",
"self",
".",
"_GetWrapper",
"(",
"self",
",",
"self",
".",
"msvs_settings",
"[",
"config",
"]",
",",
"'VCLinkerTool'",
",",
"append",
"=",
"ldflags",
")",
"self",
".",
"_GetDefFileAsLdflags",
"(",
"ldflags",
",",
"gyp_to_build_path",
")",
"ld",
"(",
"'GenerateDebugInformation'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/DEBUG'",
"}",
")",
"ld",
"(",
"'TargetMachine'",
",",
"map",
"=",
"{",
"'1'",
":",
"'X86'",
",",
"'17'",
":",
"'X64'",
",",
"'3'",
":",
"'ARM'",
"}",
",",
"prefix",
"=",
"'/MACHINE:'",
")",
"ldflags",
".",
"extend",
"(",
"self",
".",
"_GetAdditionalLibraryDirectories",
"(",
"'VCLinkerTool'",
",",
"config",
",",
"gyp_to_build_path",
")",
")",
"ld",
"(",
"'DelayLoadDLLs'",
",",
"prefix",
"=",
"'/DELAYLOAD:'",
")",
"ld",
"(",
"'TreatLinkerWarningAsErrors'",
",",
"prefix",
"=",
"'/WX'",
",",
"map",
"=",
"{",
"'true'",
":",
"''",
",",
"'false'",
":",
"':NO'",
"}",
")",
"out",
"=",
"self",
".",
"GetOutputName",
"(",
"config",
",",
"expand_special",
")",
"if",
"out",
":",
"ldflags",
".",
"append",
"(",
"'/OUT:'",
"+",
"out",
")",
"pdb",
"=",
"self",
".",
"GetPDBName",
"(",
"config",
",",
"expand_special",
",",
"output_name",
"+",
"'.pdb'",
")",
"if",
"pdb",
":",
"ldflags",
".",
"append",
"(",
"'/PDB:'",
"+",
"pdb",
")",
"pgd",
"=",
"self",
".",
"GetPGDName",
"(",
"config",
",",
"expand_special",
")",
"if",
"pgd",
":",
"ldflags",
".",
"append",
"(",
"'/PGD:'",
"+",
"pgd",
")",
"map_file",
"=",
"self",
".",
"GetMapFileName",
"(",
"config",
",",
"expand_special",
")",
"ld",
"(",
"'GenerateMapFile'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/MAP:'",
"+",
"map_file",
"if",
"map_file",
"else",
"'/MAP'",
"}",
")",
"ld",
"(",
"'MapExports'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/MAPINFO:EXPORTS'",
"}",
")",
"ld",
"(",
"'AdditionalOptions'",
",",
"prefix",
"=",
"''",
")",
"minimum_required_version",
"=",
"self",
".",
"_Setting",
"(",
"(",
"'VCLinkerTool'",
",",
"'MinimumRequiredVersion'",
")",
",",
"config",
",",
"default",
"=",
"''",
")",
"if",
"minimum_required_version",
":",
"minimum_required_version",
"=",
"','",
"+",
"minimum_required_version",
"ld",
"(",
"'SubSystem'",
",",
"map",
"=",
"{",
"'1'",
":",
"'CONSOLE%s'",
"%",
"minimum_required_version",
",",
"'2'",
":",
"'WINDOWS%s'",
"%",
"minimum_required_version",
"}",
",",
"prefix",
"=",
"'/SUBSYSTEM:'",
")",
"ld",
"(",
"'TerminalServerAware'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/TSAWARE'",
")",
"ld",
"(",
"'LinkIncremental'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/INCREMENTAL'",
")",
"ld",
"(",
"'BaseAddress'",
",",
"prefix",
"=",
"'/BASE:'",
")",
"ld",
"(",
"'FixedBaseAddress'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/FIXED'",
")",
"ld",
"(",
"'RandomizedBaseAddress'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/DYNAMICBASE'",
")",
"ld",
"(",
"'DataExecutionPrevention'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/NXCOMPAT'",
")",
"ld",
"(",
"'OptimizeReferences'",
",",
"map",
"=",
"{",
"'1'",
":",
"'NOREF'",
",",
"'2'",
":",
"'REF'",
"}",
",",
"prefix",
"=",
"'/OPT:'",
")",
"ld",
"(",
"'ForceSymbolReferences'",
",",
"prefix",
"=",
"'/INCLUDE:'",
")",
"ld",
"(",
"'EnableCOMDATFolding'",
",",
"map",
"=",
"{",
"'1'",
":",
"'NOICF'",
",",
"'2'",
":",
"'ICF'",
"}",
",",
"prefix",
"=",
"'/OPT:'",
")",
"ld",
"(",
"'LinkTimeCodeGeneration'",
",",
"map",
"=",
"{",
"'1'",
":",
"''",
",",
"'2'",
":",
"':PGINSTRUMENT'",
",",
"'3'",
":",
"':PGOPTIMIZE'",
",",
"'4'",
":",
"':PGUPDATE'",
"}",
",",
"prefix",
"=",
"'/LTCG'",
")",
"ld",
"(",
"'IgnoreDefaultLibraryNames'",
",",
"prefix",
"=",
"'/NODEFAULTLIB:'",
")",
"ld",
"(",
"'ResourceOnlyDLL'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/NOENTRY'",
"}",
")",
"ld",
"(",
"'EntryPointSymbol'",
",",
"prefix",
"=",
"'/ENTRY:'",
")",
"ld",
"(",
"'Profile'",
",",
"map",
"=",
"{",
"'true'",
":",
"'/PROFILE'",
"}",
")",
"ld",
"(",
"'LargeAddressAware'",
",",
"map",
"=",
"{",
"'1'",
":",
"':NO'",
",",
"'2'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/LARGEADDRESSAWARE'",
")",
"# TODO(scottmg): This should sort of be somewhere else (not really a flag).",
"ld",
"(",
"'AdditionalDependencies'",
",",
"prefix",
"=",
"''",
")",
"if",
"self",
".",
"GetArch",
"(",
"config",
")",
"==",
"'x86'",
":",
"safeseh_default",
"=",
"'true'",
"else",
":",
"safeseh_default",
"=",
"None",
"ld",
"(",
"'ImageHasSafeExceptionHandlers'",
",",
"map",
"=",
"{",
"'false'",
":",
"':NO'",
",",
"'true'",
":",
"''",
"}",
",",
"prefix",
"=",
"'/SAFESEH'",
",",
"default",
"=",
"safeseh_default",
")",
"# If the base address is not specifically controlled, DYNAMICBASE should",
"# be on by default.",
"base_flags",
"=",
"filter",
"(",
"lambda",
"x",
":",
"'DYNAMICBASE'",
"in",
"x",
"or",
"x",
"==",
"'/FIXED'",
",",
"ldflags",
")",
"if",
"not",
"base_flags",
":",
"ldflags",
".",
"append",
"(",
"'/DYNAMICBASE'",
")",
"# If the NXCOMPAT flag has not been specified, default to on. Despite the",
"# documentation that says this only defaults to on when the subsystem is",
"# Vista or greater (which applies to the linker), the IDE defaults it on",
"# unless it's explicitly off.",
"if",
"not",
"filter",
"(",
"lambda",
"x",
":",
"'NXCOMPAT'",
"in",
"x",
",",
"ldflags",
")",
":",
"ldflags",
".",
"append",
"(",
"'/NXCOMPAT'",
")",
"have_def_file",
"=",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"startswith",
"(",
"'/DEF:'",
")",
",",
"ldflags",
")",
"manifest_flags",
",",
"intermediate_manifest",
",",
"manifest_files",
"=",
"self",
".",
"_GetLdManifestFlags",
"(",
"config",
",",
"manifest_base_name",
",",
"gyp_to_build_path",
",",
"is_executable",
"and",
"not",
"have_def_file",
",",
"build_dir",
")",
"ldflags",
".",
"extend",
"(",
"manifest_flags",
")",
"return",
"ldflags",
",",
"intermediate_manifest",
",",
"manifest_files"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L555-L647 |
|
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py | python | TCPServer.fileno | (self) | return self.socket.fileno() | Return socket file number.
Interface required by select(). | Return socket file number. | [
"Return",
"socket",
"file",
"number",
"."
] | def fileno(self):
"""Return socket file number.
Interface required by select().
"""
return self.socket.fileno() | [
"def",
"fileno",
"(",
"self",
")",
":",
"return",
"self",
".",
"socket",
".",
"fileno",
"(",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/_pydev_imps/_pydev_SocketServer.py#L438-L444 |
|
datahuborg/datahub | f066b472c2b66cc3b868bbe433aed2d4557aea32 | src/examples/python/gen_py/datahub/DataHub.py | python | Iface.create_repo | (self, con, repo_name) | Parameters:
- con
- repo_name | Parameters:
- con
- repo_name | [
"Parameters",
":",
"-",
"con",
"-",
"repo_name"
] | def create_repo(self, con, repo_name):
"""
Parameters:
- con
- repo_name
"""
pass | [
"def",
"create_repo",
"(",
"self",
",",
"con",
",",
"repo_name",
")",
":",
"pass"
] | https://github.com/datahuborg/datahub/blob/f066b472c2b66cc3b868bbe433aed2d4557aea32/src/examples/python/gen_py/datahub/DataHub.py#L31-L37 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/urllib.py | python | ftperrors | () | return _ftperrors | Return the set of errors raised by the FTP class. | Return the set of errors raised by the FTP class. | [
"Return",
"the",
"set",
"of",
"errors",
"raised",
"by",
"the",
"FTP",
"class",
"."
] | def ftperrors():
"""Return the set of errors raised by the FTP class."""
global _ftperrors
if _ftperrors is None:
import ftplib
_ftperrors = ftplib.all_errors
return _ftperrors | [
"def",
"ftperrors",
"(",
")",
":",
"global",
"_ftperrors",
"if",
"_ftperrors",
"is",
"None",
":",
"import",
"ftplib",
"_ftperrors",
"=",
"ftplib",
".",
"all_errors",
"return",
"_ftperrors"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/urllib.py#L824-L830 |
|
ayojs/ayo | 45a1c8cf6384f5bcc81d834343c3ed9d78b97df3 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py | python | _Type.ValidateMSVS | (self, value) | Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS. | Verifies that the value is legal for MSVS. | [
"Verifies",
"that",
"the",
"value",
"is",
"legal",
"for",
"MSVS",
"."
] | def ValidateMSVS(self, value):
"""Verifies that the value is legal for MSVS.
Args:
value: the value to check for this type.
Raises:
ValueError if value is not valid for MSVS.
""" | [
"def",
"ValidateMSVS",
"(",
"self",
",",
"value",
")",
":"
] | https://github.com/ayojs/ayo/blob/45a1c8cf6384f5bcc81d834343c3ed9d78b97df3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings.py#L70-L78 |
||
xtk/X | 04c1aa856664a8517d23aefd94c470d47130aead | lib/selenium/selenium/webdriver/common/alert.py | python | Alert.accept | (self) | Accepts the alert available | Accepts the alert available | [
"Accepts",
"the",
"alert",
"available"
] | def accept(self):
""" Accepts the alert available """
self.driver.execute(Command.ACCEPT_ALERT) | [
"def",
"accept",
"(",
"self",
")",
":",
"self",
".",
"driver",
".",
"execute",
"(",
"Command",
".",
"ACCEPT_ALERT",
")"
] | https://github.com/xtk/X/blob/04c1aa856664a8517d23aefd94c470d47130aead/lib/selenium/selenium/webdriver/common/alert.py#L33-L35 |
||
CaliOpen/Caliopen | 5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8 | src/backend/components/py.pi/caliopen_pi/qualifiers/base.py | python | BaseQualifier.get_participant | (self, message, participant) | return p, c | Try to find a related contact and return a Participant instance. | Try to find a related contact and return a Participant instance. | [
"Try",
"to",
"find",
"a",
"related",
"contact",
"and",
"return",
"a",
"Participant",
"instance",
"."
] | def get_participant(self, message, participant):
"""Try to find a related contact and return a Participant instance."""
p = Participant()
p.address = participant.address.lower()
p.type = participant.type
p.label = participant.label
p.protocol = message.message_protocol
log.debug('Will lookup contact {} for user {}'.
format(participant.address, self.user.user_id))
try:
c = Contact.lookup(self.user, participant.address)
except Exception as exc:
log.error("Contact lookup failed in get_participant for participant {} : {}".format(vars(participant), exc))
raise exc
if c:
p.contact_ids = [c.contact_id]
else:
if p.address == self.identity.identifier and self.user.contact_id:
p.contact_ids = [self.user.contact_id]
return p, c | [
"def",
"get_participant",
"(",
"self",
",",
"message",
",",
"participant",
")",
":",
"p",
"=",
"Participant",
"(",
")",
"p",
".",
"address",
"=",
"participant",
".",
"address",
".",
"lower",
"(",
")",
"p",
".",
"type",
"=",
"participant",
".",
"type",
"p",
".",
"label",
"=",
"participant",
".",
"label",
"p",
".",
"protocol",
"=",
"message",
".",
"message_protocol",
"log",
".",
"debug",
"(",
"'Will lookup contact {} for user {}'",
".",
"format",
"(",
"participant",
".",
"address",
",",
"self",
".",
"user",
".",
"user_id",
")",
")",
"try",
":",
"c",
"=",
"Contact",
".",
"lookup",
"(",
"self",
".",
"user",
",",
"participant",
".",
"address",
")",
"except",
"Exception",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"\"Contact lookup failed in get_participant for participant {} : {}\"",
".",
"format",
"(",
"vars",
"(",
"participant",
")",
",",
"exc",
")",
")",
"raise",
"exc",
"if",
"c",
":",
"p",
".",
"contact_ids",
"=",
"[",
"c",
".",
"contact_id",
"]",
"else",
":",
"if",
"p",
".",
"address",
"==",
"self",
".",
"identity",
".",
"identifier",
"and",
"self",
".",
"user",
".",
"contact_id",
":",
"p",
".",
"contact_ids",
"=",
"[",
"self",
".",
"user",
".",
"contact_id",
"]",
"return",
"p",
",",
"c"
] | https://github.com/CaliOpen/Caliopen/blob/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8/src/backend/components/py.pi/caliopen_pi/qualifiers/base.py#L59-L78 |
|
nodejs/node | ac3c33c1646bf46104c15ae035982c06364da9b8 | tools/gyp/pylib/gyp/generator/ninja.py | python | Target.PreCompileInput | (self) | return self.actions_stamp or self.precompile_stamp | Return the path, if any, that should be used as a dependency of
any dependent compile step. | Return the path, if any, that should be used as a dependency of
any dependent compile step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"compile",
"step",
"."
] | def PreCompileInput(self):
"""Return the path, if any, that should be used as a dependency of
any dependent compile step."""
return self.actions_stamp or self.precompile_stamp | [
"def",
"PreCompileInput",
"(",
"self",
")",
":",
"return",
"self",
".",
"actions_stamp",
"or",
"self",
".",
"precompile_stamp"
] | https://github.com/nodejs/node/blob/ac3c33c1646bf46104c15ae035982c06364da9b8/tools/gyp/pylib/gyp/generator/ninja.py#L177-L180 |
|
UWFlow/rmc | 00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9 | server/view_helpers.py | python | redirect_to_profile | (user) | Returns a flask.redirect() to a given user's profile.
Basically redirect the request to the /profile endpoint with their ObjectId
Args:
user: The user's profile to redirects to. Should NOT be None. | Returns a flask.redirect() to a given user's profile. | [
"Returns",
"a",
"flask",
".",
"redirect",
"()",
"to",
"a",
"given",
"user",
"s",
"profile",
"."
] | def redirect_to_profile(user):
"""
Returns a flask.redirect() to a given user's profile.
Basically redirect the request to the /profile endpoint with their ObjectId
Args:
user: The user's profile to redirects to. Should NOT be None.
"""
if user is None:
# This should only happen during development time...
logging.error('redirect_to_profile(user) called with user=None')
return flask.redirect('/profile', 302)
if flask.request.query_string:
return flask.redirect('/profile/%s?%s' % (
user.id, flask.request.query_string), 302)
else:
return flask.redirect('/profile/%s' % user.id, 302) | [
"def",
"redirect_to_profile",
"(",
"user",
")",
":",
"if",
"user",
"is",
"None",
":",
"# This should only happen during development time...",
"logging",
".",
"error",
"(",
"'redirect_to_profile(user) called with user=None'",
")",
"return",
"flask",
".",
"redirect",
"(",
"'/profile'",
",",
"302",
")",
"if",
"flask",
".",
"request",
".",
"query_string",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/profile/%s?%s'",
"%",
"(",
"user",
".",
"id",
",",
"flask",
".",
"request",
".",
"query_string",
")",
",",
"302",
")",
"else",
":",
"return",
"flask",
".",
"redirect",
"(",
"'/profile/%s'",
"%",
"user",
".",
"id",
",",
"302",
")"
] | https://github.com/UWFlow/rmc/blob/00bcc1450ffbec3a6c8d956a2a5d1bb3a04bfcb9/server/view_helpers.py#L134-L152 |
||
jxcore/jxcore | b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | Target.PreActionInput | (self, flavor) | return self.FinalOutput() or self.preaction_stamp | Return the path, if any, that should be used as a dependency of
any dependent action step. | Return the path, if any, that should be used as a dependency of
any dependent action step. | [
"Return",
"the",
"path",
"if",
"any",
"that",
"should",
"be",
"used",
"as",
"a",
"dependency",
"of",
"any",
"dependent",
"action",
"step",
"."
] | def PreActionInput(self, flavor):
"""Return the path, if any, that should be used as a dependency of
any dependent action step."""
if self.UsesToc(flavor):
return self.FinalOutput() + '.TOC'
return self.FinalOutput() or self.preaction_stamp | [
"def",
"PreActionInput",
"(",
"self",
",",
"flavor",
")",
":",
"if",
"self",
".",
"UsesToc",
"(",
"flavor",
")",
":",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"+",
"'.TOC'",
"return",
"self",
".",
"FinalOutput",
"(",
")",
"or",
"self",
".",
"preaction_stamp"
] | https://github.com/jxcore/jxcore/blob/b05f1f2d2c9d62c813c7d84f3013dbbf30b6e410/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L163-L168 |
|
Southpaw-TACTIC/TACTIC | ba9b87aef0ee3b3ea51446f25b285ebbca06f62c | src/pyasm/prod/service/base_xmlrpc.py | python | BaseXMLRPC.create_set | (self, ticket, project_code, set_name, cat_name, selected) | return [xml, asset_code] | an xml to create a new set node | an xml to create a new set node | [
"an",
"xml",
"to",
"create",
"a",
"new",
"set",
"node"
] | def create_set(self, ticket, project_code, set_name, cat_name, selected):
'''an xml to create a new set node'''
xml = ''
asset_code = ''
try:
self.init(ticket)
Project.set_project(project_code)
cmd = MayaSetCreateCmd()
cmd.set_set_name(set_name)
cmd.set_cat_name(cat_name)
Command.execute_cmd(cmd)
asset_code = cmd.get_asset_code()
if asset_code:
cmd = CreateSetNodeCmd()
cmd.set_asset_code(asset_code)
cmd.set_instance(set_name)
cmd.set_contents(selected)
cmd.execute()
execute_xml = cmd.get_execute_xml()
xml = execute_xml.get_xml()
finally:
DbContainer.close_all()
return [xml, asset_code] | [
"def",
"create_set",
"(",
"self",
",",
"ticket",
",",
"project_code",
",",
"set_name",
",",
"cat_name",
",",
"selected",
")",
":",
"xml",
"=",
"''",
"asset_code",
"=",
"''",
"try",
":",
"self",
".",
"init",
"(",
"ticket",
")",
"Project",
".",
"set_project",
"(",
"project_code",
")",
"cmd",
"=",
"MayaSetCreateCmd",
"(",
")",
"cmd",
".",
"set_set_name",
"(",
"set_name",
")",
"cmd",
".",
"set_cat_name",
"(",
"cat_name",
")",
"Command",
".",
"execute_cmd",
"(",
"cmd",
")",
"asset_code",
"=",
"cmd",
".",
"get_asset_code",
"(",
")",
"if",
"asset_code",
":",
"cmd",
"=",
"CreateSetNodeCmd",
"(",
")",
"cmd",
".",
"set_asset_code",
"(",
"asset_code",
")",
"cmd",
".",
"set_instance",
"(",
"set_name",
")",
"cmd",
".",
"set_contents",
"(",
"selected",
")",
"cmd",
".",
"execute",
"(",
")",
"execute_xml",
"=",
"cmd",
".",
"get_execute_xml",
"(",
")",
"xml",
"=",
"execute_xml",
".",
"get_xml",
"(",
")",
"finally",
":",
"DbContainer",
".",
"close_all",
"(",
")",
"return",
"[",
"xml",
",",
"asset_code",
"]"
] | https://github.com/Southpaw-TACTIC/TACTIC/blob/ba9b87aef0ee3b3ea51446f25b285ebbca06f62c/src/pyasm/prod/service/base_xmlrpc.py#L232-L258 |
|
jeeliz/jeelizFaceFilter | be3ffa5a76c930a98b2b7895c1dfa1faa4a1fa82 | libs/three/blenderExporter/io_three/exporter/api/object.py | python | _valid_node | (obj, valid_types, options) | return True | :param obj:
:param valid_types:
:param options: | [] | def _valid_node(obj, valid_types, options):
"""
:param obj:
:param valid_types:
:param options:
"""
if obj.type not in valid_types:
return False
# skip objects that are not on visible layers
visible_layers = _visible_scene_layers()
if not _on_visible_layer(obj, visible_layers):
return False
try:
export = obj.THREE_export
except AttributeError:
export = True
if not export:
return False
mesh_node = mesh(obj, options)
is_mesh = obj.type == MESH
# skip objects that a mesh could not be resolved
if is_mesh and not mesh_node:
return False
# secondary test; if a mesh node was resolved but no
# faces are detected then bow out
if is_mesh:
mesh_node = data.meshes[mesh_node]
if len(mesh_node.tessfaces) is 0:
return False
# if we get this far assume that the mesh is valid
return True | [
"def",
"_valid_node",
"(",
"obj",
",",
"valid_types",
",",
"options",
")",
":",
"if",
"obj",
".",
"type",
"not",
"in",
"valid_types",
":",
"return",
"False",
"# skip objects that are not on visible layers",
"visible_layers",
"=",
"_visible_scene_layers",
"(",
")",
"if",
"not",
"_on_visible_layer",
"(",
"obj",
",",
"visible_layers",
")",
":",
"return",
"False",
"try",
":",
"export",
"=",
"obj",
".",
"THREE_export",
"except",
"AttributeError",
":",
"export",
"=",
"True",
"if",
"not",
"export",
":",
"return",
"False",
"mesh_node",
"=",
"mesh",
"(",
"obj",
",",
"options",
")",
"is_mesh",
"=",
"obj",
".",
"type",
"==",
"MESH",
"# skip objects that a mesh could not be resolved",
"if",
"is_mesh",
"and",
"not",
"mesh_node",
":",
"return",
"False",
"# secondary test; if a mesh node was resolved but no",
"# faces are detected then bow out",
"if",
"is_mesh",
":",
"mesh_node",
"=",
"data",
".",
"meshes",
"[",
"mesh_node",
"]",
"if",
"len",
"(",
"mesh_node",
".",
"tessfaces",
")",
"is",
"0",
":",
"return",
"False",
"# if we get this far assume that the mesh is valid",
"return",
"True"
] | https://github.com/jeeliz/jeelizFaceFilter/blob/be3ffa5a76c930a98b2b7895c1dfa1faa4a1fa82/libs/three/blenderExporter/io_three/exporter/api/object.py#L700-L738 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/main.py | python | main | (fixer_pkg, args=None) | return int(bool(rt.errors)) | Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2). | Main program. | [
"Main",
"program",
"."
] | def main(fixer_pkg, args=None):
"""Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2).
"""
# Set up option parser
parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
parser.add_option("-d", "--doctests_only", action="store_true",
help="Fix up doctests only")
parser.add_option("-f", "--fix", action="append", default=[],
help="Each FIX specifies a transformation; default: all")
parser.add_option("-j", "--processes", action="store", default=1,
type="int", help="Run 2to3 concurrently")
parser.add_option("-x", "--nofix", action="append", default=[],
help="Prevent a transformation from being run")
parser.add_option("-l", "--list-fixes", action="store_true",
help="List available transformations")
parser.add_option("-p", "--print-function", action="store_true",
help="Modify the grammar so that print() is a function")
parser.add_option("-v", "--verbose", action="store_true",
help="More verbose logging")
parser.add_option("--no-diffs", action="store_true",
help="Don't show diffs of the refactoring")
parser.add_option("-w", "--write", action="store_true",
help="Write back modified files")
parser.add_option("-n", "--nobackups", action="store_true", default=False,
help="Don't write backups for modified files")
parser.add_option("-o", "--output-dir", action="store", type="str",
default="", help="Put output files in this directory "
"instead of overwriting the input files. Requires -n.")
parser.add_option("-W", "--write-unchanged-files", action="store_true",
help="Also write files even if no changes were required"
" (useful with --output-dir); implies -w.")
parser.add_option("--add-suffix", action="store", type="str", default="",
help="Append this string to all output filenames."
" Requires -n if non-empty. "
"ex: --add-suffix='3' will generate .py3 files.")
# Parse command line arguments
refactor_stdin = False
flags = {}
options, args = parser.parse_args(args)
if options.write_unchanged_files:
flags["write_unchanged_files"] = True
if not options.write:
warn("--write-unchanged-files/-W implies -w.")
options.write = True
# If we allowed these, the original files would be renamed to backup names
# but not replaced.
if options.output_dir and not options.nobackups:
parser.error("Can't use --output-dir/-o without -n.")
if options.add_suffix and not options.nobackups:
parser.error("Can't use --add-suffix without -n.")
if not options.write and options.no_diffs:
warn("not writing files and not printing diffs; that's not very useful")
if not options.write and options.nobackups:
parser.error("Can't use -n without -w")
if options.list_fixes:
print "Available transformations for the -f/--fix option:"
for fixname in refactor.get_all_fix_names(fixer_pkg):
print fixname
if not args:
return 0
if not args:
print >> sys.stderr, "At least one file or directory argument required."
print >> sys.stderr, "Use --help to show usage."
return 2
if "-" in args:
refactor_stdin = True
if options.write:
print >> sys.stderr, "Can't write to stdin."
return 2
if options.print_function:
flags["print_function"] = True
# Set up logging handler
level = logging.DEBUG if options.verbose else logging.INFO
logging.basicConfig(format='%(name)s: %(message)s', level=level)
logger = logging.getLogger('lib2to3.main')
# Initialize the refactoring tool
avail_fixes = set(refactor.get_fixers_from_package(fixer_pkg))
unwanted_fixes = set(fixer_pkg + ".fix_" + fix for fix in options.nofix)
explicit = set()
if options.fix:
all_present = False
for fix in options.fix:
if fix == "all":
all_present = True
else:
explicit.add(fixer_pkg + ".fix_" + fix)
requested = avail_fixes.union(explicit) if all_present else explicit
else:
requested = avail_fixes.union(explicit)
fixer_names = requested.difference(unwanted_fixes)
input_base_dir = os.path.commonprefix(args)
if (input_base_dir and not input_base_dir.endswith(os.sep)
and not os.path.isdir(input_base_dir)):
# One or more similar names were passed, their directory is the base.
# os.path.commonprefix() is ignorant of path elements, this corrects
# for that weird API.
input_base_dir = os.path.dirname(input_base_dir)
if options.output_dir:
input_base_dir = input_base_dir.rstrip(os.sep)
logger.info('Output in %r will mirror the input directory %r layout.',
options.output_dir, input_base_dir)
rt = StdoutRefactoringTool(
sorted(fixer_names), flags, sorted(explicit),
options.nobackups, not options.no_diffs,
input_base_dir=input_base_dir,
output_dir=options.output_dir,
append_suffix=options.add_suffix)
# Refactor all files and directories passed as arguments
if not rt.errors:
if refactor_stdin:
rt.refactor_stdin()
else:
try:
rt.refactor(args, options.write, options.doctests_only,
options.processes)
except refactor.MultiprocessingUnsupported:
assert options.processes > 1
print >> sys.stderr, "Sorry, -j isn't " \
"supported on this platform."
return 1
rt.summarize()
# Return error status (0 if rt.errors is zero)
return int(bool(rt.errors)) | [
"def",
"main",
"(",
"fixer_pkg",
",",
"args",
"=",
"None",
")",
":",
"# Set up option parser",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"\"2to3 [options] file|dir ...\"",
")",
"parser",
".",
"add_option",
"(",
"\"-d\"",
",",
"\"--doctests_only\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Fix up doctests only\"",
")",
"parser",
".",
"add_option",
"(",
"\"-f\"",
",",
"\"--fix\"",
",",
"action",
"=",
"\"append\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Each FIX specifies a transformation; default: all\"",
")",
"parser",
".",
"add_option",
"(",
"\"-j\"",
",",
"\"--processes\"",
",",
"action",
"=",
"\"store\"",
",",
"default",
"=",
"1",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Run 2to3 concurrently\"",
")",
"parser",
".",
"add_option",
"(",
"\"-x\"",
",",
"\"--nofix\"",
",",
"action",
"=",
"\"append\"",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Prevent a transformation from being run\"",
")",
"parser",
".",
"add_option",
"(",
"\"-l\"",
",",
"\"--list-fixes\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"List available transformations\"",
")",
"parser",
".",
"add_option",
"(",
"\"-p\"",
",",
"\"--print-function\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Modify the grammar so that print() is a function\"",
")",
"parser",
".",
"add_option",
"(",
"\"-v\"",
",",
"\"--verbose\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"More verbose logging\"",
")",
"parser",
".",
"add_option",
"(",
"\"--no-diffs\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Don't show diffs of the refactoring\"",
")",
"parser",
".",
"add_option",
"(",
"\"-w\"",
",",
"\"--write\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Write back modified files\"",
")",
"parser",
".",
"add_option",
"(",
"\"-n\"",
",",
"\"--nobackups\"",
",",
"action",
"=",
"\"store_true\"",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Don't write backups for modified files\"",
")",
"parser",
".",
"add_option",
"(",
"\"-o\"",
",",
"\"--output-dir\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"\"str\"",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Put output files in this directory \"",
"\"instead of overwriting the input files. Requires -n.\"",
")",
"parser",
".",
"add_option",
"(",
"\"-W\"",
",",
"\"--write-unchanged-files\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Also write files even if no changes were required\"",
"\" (useful with --output-dir); implies -w.\"",
")",
"parser",
".",
"add_option",
"(",
"\"--add-suffix\"",
",",
"action",
"=",
"\"store\"",
",",
"type",
"=",
"\"str\"",
",",
"default",
"=",
"\"\"",
",",
"help",
"=",
"\"Append this string to all output filenames.\"",
"\" Requires -n if non-empty. \"",
"\"ex: --add-suffix='3' will generate .py3 files.\"",
")",
"# Parse command line arguments",
"refactor_stdin",
"=",
"False",
"flags",
"=",
"{",
"}",
"options",
",",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"if",
"options",
".",
"write_unchanged_files",
":",
"flags",
"[",
"\"write_unchanged_files\"",
"]",
"=",
"True",
"if",
"not",
"options",
".",
"write",
":",
"warn",
"(",
"\"--write-unchanged-files/-W implies -w.\"",
")",
"options",
".",
"write",
"=",
"True",
"# If we allowed these, the original files would be renamed to backup names",
"# but not replaced.",
"if",
"options",
".",
"output_dir",
"and",
"not",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use --output-dir/-o without -n.\"",
")",
"if",
"options",
".",
"add_suffix",
"and",
"not",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use --add-suffix without -n.\"",
")",
"if",
"not",
"options",
".",
"write",
"and",
"options",
".",
"no_diffs",
":",
"warn",
"(",
"\"not writing files and not printing diffs; that's not very useful\"",
")",
"if",
"not",
"options",
".",
"write",
"and",
"options",
".",
"nobackups",
":",
"parser",
".",
"error",
"(",
"\"Can't use -n without -w\"",
")",
"if",
"options",
".",
"list_fixes",
":",
"print",
"\"Available transformations for the -f/--fix option:\"",
"for",
"fixname",
"in",
"refactor",
".",
"get_all_fix_names",
"(",
"fixer_pkg",
")",
":",
"print",
"fixname",
"if",
"not",
"args",
":",
"return",
"0",
"if",
"not",
"args",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"At least one file or directory argument required.\"",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Use --help to show usage.\"",
"return",
"2",
"if",
"\"-\"",
"in",
"args",
":",
"refactor_stdin",
"=",
"True",
"if",
"options",
".",
"write",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Can't write to stdin.\"",
"return",
"2",
"if",
"options",
".",
"print_function",
":",
"flags",
"[",
"\"print_function\"",
"]",
"=",
"True",
"# Set up logging handler",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"options",
".",
"verbose",
"else",
"logging",
".",
"INFO",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"'%(name)s: %(message)s'",
",",
"level",
"=",
"level",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'lib2to3.main'",
")",
"# Initialize the refactoring tool",
"avail_fixes",
"=",
"set",
"(",
"refactor",
".",
"get_fixers_from_package",
"(",
"fixer_pkg",
")",
")",
"unwanted_fixes",
"=",
"set",
"(",
"fixer_pkg",
"+",
"\".fix_\"",
"+",
"fix",
"for",
"fix",
"in",
"options",
".",
"nofix",
")",
"explicit",
"=",
"set",
"(",
")",
"if",
"options",
".",
"fix",
":",
"all_present",
"=",
"False",
"for",
"fix",
"in",
"options",
".",
"fix",
":",
"if",
"fix",
"==",
"\"all\"",
":",
"all_present",
"=",
"True",
"else",
":",
"explicit",
".",
"add",
"(",
"fixer_pkg",
"+",
"\".fix_\"",
"+",
"fix",
")",
"requested",
"=",
"avail_fixes",
".",
"union",
"(",
"explicit",
")",
"if",
"all_present",
"else",
"explicit",
"else",
":",
"requested",
"=",
"avail_fixes",
".",
"union",
"(",
"explicit",
")",
"fixer_names",
"=",
"requested",
".",
"difference",
"(",
"unwanted_fixes",
")",
"input_base_dir",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"args",
")",
"if",
"(",
"input_base_dir",
"and",
"not",
"input_base_dir",
".",
"endswith",
"(",
"os",
".",
"sep",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"input_base_dir",
")",
")",
":",
"# One or more similar names were passed, their directory is the base.",
"# os.path.commonprefix() is ignorant of path elements, this corrects",
"# for that weird API.",
"input_base_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"input_base_dir",
")",
"if",
"options",
".",
"output_dir",
":",
"input_base_dir",
"=",
"input_base_dir",
".",
"rstrip",
"(",
"os",
".",
"sep",
")",
"logger",
".",
"info",
"(",
"'Output in %r will mirror the input directory %r layout.'",
",",
"options",
".",
"output_dir",
",",
"input_base_dir",
")",
"rt",
"=",
"StdoutRefactoringTool",
"(",
"sorted",
"(",
"fixer_names",
")",
",",
"flags",
",",
"sorted",
"(",
"explicit",
")",
",",
"options",
".",
"nobackups",
",",
"not",
"options",
".",
"no_diffs",
",",
"input_base_dir",
"=",
"input_base_dir",
",",
"output_dir",
"=",
"options",
".",
"output_dir",
",",
"append_suffix",
"=",
"options",
".",
"add_suffix",
")",
"# Refactor all files and directories passed as arguments",
"if",
"not",
"rt",
".",
"errors",
":",
"if",
"refactor_stdin",
":",
"rt",
".",
"refactor_stdin",
"(",
")",
"else",
":",
"try",
":",
"rt",
".",
"refactor",
"(",
"args",
",",
"options",
".",
"write",
",",
"options",
".",
"doctests_only",
",",
"options",
".",
"processes",
")",
"except",
"refactor",
".",
"MultiprocessingUnsupported",
":",
"assert",
"options",
".",
"processes",
">",
"1",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Sorry, -j isn't \"",
"\"supported on this platform.\"",
"return",
"1",
"rt",
".",
"summarize",
"(",
")",
"# Return error status (0 if rt.errors is zero)",
"return",
"int",
"(",
"bool",
"(",
"rt",
".",
"errors",
")",
")"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/third_party/pep8/lib2to3/lib2to3/main.py#L134-L269 |
|
NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application | b9b1f9e9aa84e379c573063fc5622ef50d38898d | tracker/code/mctrack/mctracker.py | python | MulticamTracker.select_rep_member_from_list | (self, json_list) | return retval | This method selects one representative dict from the list
of vehicle detections (in json_list)
Returns:
[dict] -- A representative day2 schema dictionary of
selected representative vehicle detection | This method selects one representative dict from the list
of vehicle detections (in json_list) | [
"This",
"method",
"selects",
"one",
"representative",
"dict",
"from",
"the",
"list",
"of",
"vehicle",
"detections",
"(",
"in",
"json_list",
")"
] | def select_rep_member_from_list(self, json_list):
"""
This method selects one representative dict from the list
of vehicle detections (in json_list)
Returns:
[dict] -- A representative day2 schema dictionary of
selected representative vehicle detection
"""
retval = None
if json_list:
retval = json_list[0]
pref = 100
min_obj_id = None
for ele in json_list:
# 1st pref = entry/exit
# 2nd pref = one with videopath
if ele["event"]["type"] in ["entry", "exit"]:
retval = ele
pref = 1
elif(pref > 1) and (ele["videoPath"] != ""):
retval = ele
pref = 2
elif(pref > 2) and (min_obj_id is None or
min_obj_id > ele["object"]["id"]):
retval = ele
min_obj_id = ele["object"]["id"]
pref = 3
return retval | [
"def",
"select_rep_member_from_list",
"(",
"self",
",",
"json_list",
")",
":",
"retval",
"=",
"None",
"if",
"json_list",
":",
"retval",
"=",
"json_list",
"[",
"0",
"]",
"pref",
"=",
"100",
"min_obj_id",
"=",
"None",
"for",
"ele",
"in",
"json_list",
":",
"# 1st pref = entry/exit",
"# 2nd pref = one with videopath",
"if",
"ele",
"[",
"\"event\"",
"]",
"[",
"\"type\"",
"]",
"in",
"[",
"\"entry\"",
",",
"\"exit\"",
"]",
":",
"retval",
"=",
"ele",
"pref",
"=",
"1",
"elif",
"(",
"pref",
">",
"1",
")",
"and",
"(",
"ele",
"[",
"\"videoPath\"",
"]",
"!=",
"\"\"",
")",
":",
"retval",
"=",
"ele",
"pref",
"=",
"2",
"elif",
"(",
"pref",
">",
"2",
")",
"and",
"(",
"min_obj_id",
"is",
"None",
"or",
"min_obj_id",
">",
"ele",
"[",
"\"object\"",
"]",
"[",
"\"id\"",
"]",
")",
":",
"retval",
"=",
"ele",
"min_obj_id",
"=",
"ele",
"[",
"\"object\"",
"]",
"[",
"\"id\"",
"]",
"pref",
"=",
"3",
"return",
"retval"
] | https://github.com/NVIDIA-AI-IOT/deepstream_360_d_smart_parking_application/blob/b9b1f9e9aa84e379c573063fc5622ef50d38898d/tracker/code/mctrack/mctracker.py#L554-L582 |
|
agoravoting/agora-ciudadana | a7701035ea77d7a91baa9b5c2d0c05d91d1b4262 | agora_site/misc/utils.py | python | rest | (path, query={}, data={}, headers={}, method="GET", request=None) | return (res.status_code, res._container) | Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result.
Args:
path: a uri-like string representing an API endpoint. e.g. /resource/27.
/api/v2/ is automatically prepended to the path.
query: dictionary of GET-like query parameters to pass to view
data: dictionary of POST-like parameters to pass to view
headers: dictionary of extra headers to pass to view (will end up in request.META)
method: HTTP verb for the emulated request
Returns:
a tuple of (status, content):
status: integer representing an HTTP response code
content: string, body of response; may be empty | Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result. | [
"Converts",
"a",
"RPC",
"-",
"like",
"call",
"to",
"something",
"like",
"a",
"HttpRequest",
"passes",
"it",
"to",
"the",
"right",
"view",
"function",
"(",
"via",
"django",
"s",
"url",
"resolver",
")",
"and",
"returns",
"the",
"result",
"."
] | def rest(path, query={}, data={}, headers={}, method="GET", request=None):
"""
Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result.
Args:
path: a uri-like string representing an API endpoint. e.g. /resource/27.
/api/v2/ is automatically prepended to the path.
query: dictionary of GET-like query parameters to pass to view
data: dictionary of POST-like parameters to pass to view
headers: dictionary of extra headers to pass to view (will end up in request.META)
method: HTTP verb for the emulated request
Returns:
a tuple of (status, content):
status: integer representing an HTTP response code
content: string, body of response; may be empty
"""
#adjust for lack of trailing slash, just in case
if path[-1] != '/':
path += '/'
hreq = FakeHttpRequest()
hreq.path = '/api/v1' + path
hreq.GET = query
if isinstance(data, basestring):
hreq.POST = customstr(data)
else:
hreq.POST = customstr(json.dumps(data))
hreq.META = headers
hreq.method = method
if request:
hreq.user = request.user
try:
view = resolve(hreq.path)
res = view.func(hreq, *view.args, **view.kwargs)
except Resolver404:
return (404, '')
#container is the untouched content before HttpResponse mangles it
return (res.status_code, res._container) | [
"def",
"rest",
"(",
"path",
",",
"query",
"=",
"{",
"}",
",",
"data",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"method",
"=",
"\"GET\"",
",",
"request",
"=",
"None",
")",
":",
"#adjust for lack of trailing slash, just in case",
"if",
"path",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"path",
"+=",
"'/'",
"hreq",
"=",
"FakeHttpRequest",
"(",
")",
"hreq",
".",
"path",
"=",
"'/api/v1'",
"+",
"path",
"hreq",
".",
"GET",
"=",
"query",
"if",
"isinstance",
"(",
"data",
",",
"basestring",
")",
":",
"hreq",
".",
"POST",
"=",
"customstr",
"(",
"data",
")",
"else",
":",
"hreq",
".",
"POST",
"=",
"customstr",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"hreq",
".",
"META",
"=",
"headers",
"hreq",
".",
"method",
"=",
"method",
"if",
"request",
":",
"hreq",
".",
"user",
"=",
"request",
".",
"user",
"try",
":",
"view",
"=",
"resolve",
"(",
"hreq",
".",
"path",
")",
"res",
"=",
"view",
".",
"func",
"(",
"hreq",
",",
"*",
"view",
".",
"args",
",",
"*",
"*",
"view",
".",
"kwargs",
")",
"except",
"Resolver404",
":",
"return",
"(",
"404",
",",
"''",
")",
"#container is the untouched content before HttpResponse mangles it",
"return",
"(",
"res",
".",
"status_code",
",",
"res",
".",
"_container",
")"
] | https://github.com/agoravoting/agora-ciudadana/blob/a7701035ea77d7a91baa9b5c2d0c05d91d1b4262/agora_site/misc/utils.py#L375-L415 |
|
CaliOpen/Caliopen | 5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8 | src/backend/tools/py.CLI/caliopen_cli/commands/setup_storage.py | python | setup_storage | (settings=None) | Create cassandra models. | Create cassandra models. | [
"Create",
"cassandra",
"models",
"."
] | def setup_storage(settings=None):
"""Create cassandra models."""
from caliopen_storage.core import core_registry
# Make discovery happen
from caliopen_main.user.core import User
from caliopen_main.user.core import (UserIdentity,
IdentityLookup,
IdentityTypeLookup)
from caliopen_main.contact.objects.contact import Contact
from caliopen_main.message.objects.message import Message
from caliopen_main.common.objects.tag import ResourceTag
from caliopen_main.device.core import Device
from caliopen_main.notification.core import Notification, NotificationTtl
from caliopen_main.protocol.core import Provider
from cassandra.cqlengine.management import sync_table, \
create_keyspace_simple
keyspace = Configuration('global').get('cassandra.keyspace')
if not keyspace:
raise Exception('Configuration missing for cassandra keyspace')
# XXX tofix : define strategy and replication_factor in configuration
create_keyspace_simple(keyspace, 1)
for name, kls in core_registry.items():
log.info('Creating cassandra model %s' % name)
if hasattr(kls._model_class, 'pk'):
# XXX find a better way to detect model from udt
sync_table(kls._model_class) | [
"def",
"setup_storage",
"(",
"settings",
"=",
"None",
")",
":",
"from",
"caliopen_storage",
".",
"core",
"import",
"core_registry",
"# Make discovery happen",
"from",
"caliopen_main",
".",
"user",
".",
"core",
"import",
"User",
"from",
"caliopen_main",
".",
"user",
".",
"core",
"import",
"(",
"UserIdentity",
",",
"IdentityLookup",
",",
"IdentityTypeLookup",
")",
"from",
"caliopen_main",
".",
"contact",
".",
"objects",
".",
"contact",
"import",
"Contact",
"from",
"caliopen_main",
".",
"message",
".",
"objects",
".",
"message",
"import",
"Message",
"from",
"caliopen_main",
".",
"common",
".",
"objects",
".",
"tag",
"import",
"ResourceTag",
"from",
"caliopen_main",
".",
"device",
".",
"core",
"import",
"Device",
"from",
"caliopen_main",
".",
"notification",
".",
"core",
"import",
"Notification",
",",
"NotificationTtl",
"from",
"caliopen_main",
".",
"protocol",
".",
"core",
"import",
"Provider",
"from",
"cassandra",
".",
"cqlengine",
".",
"management",
"import",
"sync_table",
",",
"create_keyspace_simple",
"keyspace",
"=",
"Configuration",
"(",
"'global'",
")",
".",
"get",
"(",
"'cassandra.keyspace'",
")",
"if",
"not",
"keyspace",
":",
"raise",
"Exception",
"(",
"'Configuration missing for cassandra keyspace'",
")",
"# XXX tofix : define strategy and replication_factor in configuration",
"create_keyspace_simple",
"(",
"keyspace",
",",
"1",
")",
"for",
"name",
",",
"kls",
"in",
"core_registry",
".",
"items",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Creating cassandra model %s'",
"%",
"name",
")",
"if",
"hasattr",
"(",
"kls",
".",
"_model_class",
",",
"'pk'",
")",
":",
"# XXX find a better way to detect model from udt",
"sync_table",
"(",
"kls",
".",
"_model_class",
")"
] | https://github.com/CaliOpen/Caliopen/blob/5361ebc5d4d2c525a87f737468b8a8e2aefbe3e8/src/backend/tools/py.CLI/caliopen_cli/commands/setup_storage.py#L9-L35 |
||
nodejs/quic | 5baab3f3a05548d3b51bea98868412b08766e34d | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py | python | MsvsSettings.AdjustMidlIncludeDirs | (self, midl_include_dirs, config) | return [self.ConvertVSMacros(p, config=config) for p in includes] | Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar. | Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar. | [
"Updates",
"midl_include_dirs",
"to",
"expand",
"VS",
"specific",
"paths",
"and",
"adds",
"the",
"system",
"include",
"dirs",
"used",
"for",
"platform",
"SDK",
"and",
"similar",
"."
] | def AdjustMidlIncludeDirs(self, midl_include_dirs, config):
"""Updates midl_include_dirs to expand VS specific paths, and adds the
system include dirs used for platform SDK and similar."""
config = self._TargetConfig(config)
includes = midl_include_dirs + self.msvs_system_include_dirs[config]
includes.extend(self._Setting(
('VCMIDLTool', 'AdditionalIncludeDirectories'), config, default=[]))
return [self.ConvertVSMacros(p, config=config) for p in includes] | [
"def",
"AdjustMidlIncludeDirs",
"(",
"self",
",",
"midl_include_dirs",
",",
"config",
")",
":",
"config",
"=",
"self",
".",
"_TargetConfig",
"(",
"config",
")",
"includes",
"=",
"midl_include_dirs",
"+",
"self",
".",
"msvs_system_include_dirs",
"[",
"config",
"]",
"includes",
".",
"extend",
"(",
"self",
".",
"_Setting",
"(",
"(",
"'VCMIDLTool'",
",",
"'AdditionalIncludeDirectories'",
")",
",",
"config",
",",
"default",
"=",
"[",
"]",
")",
")",
"return",
"[",
"self",
".",
"ConvertVSMacros",
"(",
"p",
",",
"config",
"=",
"config",
")",
"for",
"p",
"in",
"includes",
"]"
] | https://github.com/nodejs/quic/blob/5baab3f3a05548d3b51bea98868412b08766e34d/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py#L349-L356 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/smtplib.py | python | SMTP.starttls | (self, keyfile=None, certfile=None) | return (resp, reply) | Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting. | Puts the connection to the SMTP server into TLS mode. | [
"Puts",
"the",
"connection",
"to",
"the",
"SMTP",
"server",
"into",
"TLS",
"mode",
"."
] | def starttls(self, keyfile=None, certfile=None):
"""Puts the connection to the SMTP server into TLS mode.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
"""
self.ehlo_or_helo_if_needed()
if not self.has_extn("starttls"):
raise SMTPException("STARTTLS extension not supported by server.")
(resp, reply) = self.docmd("STARTTLS")
if resp == 220:
if not _have_ssl:
raise RuntimeError("No SSL support included in this Python")
self.sock = ssl.wrap_socket(self.sock, keyfile, certfile)
self.file = SSLFakeFile(self.sock)
# RFC 3207:
# The client MUST discard any knowledge obtained from
# the server, such as the list of SMTP service extensions,
# which was not obtained from the TLS negotiation itself.
self.helo_resp = None
self.ehlo_resp = None
self.esmtp_features = {}
self.does_esmtp = 0
return (resp, reply) | [
"def",
"starttls",
"(",
"self",
",",
"keyfile",
"=",
"None",
",",
"certfile",
"=",
"None",
")",
":",
"self",
".",
"ehlo_or_helo_if_needed",
"(",
")",
"if",
"not",
"self",
".",
"has_extn",
"(",
"\"starttls\"",
")",
":",
"raise",
"SMTPException",
"(",
"\"STARTTLS extension not supported by server.\"",
")",
"(",
"resp",
",",
"reply",
")",
"=",
"self",
".",
"docmd",
"(",
"\"STARTTLS\"",
")",
"if",
"resp",
"==",
"220",
":",
"if",
"not",
"_have_ssl",
":",
"raise",
"RuntimeError",
"(",
"\"No SSL support included in this Python\"",
")",
"self",
".",
"sock",
"=",
"ssl",
".",
"wrap_socket",
"(",
"self",
".",
"sock",
",",
"keyfile",
",",
"certfile",
")",
"self",
".",
"file",
"=",
"SSLFakeFile",
"(",
"self",
".",
"sock",
")",
"# RFC 3207:",
"# The client MUST discard any knowledge obtained from",
"# the server, such as the list of SMTP service extensions,",
"# which was not obtained from the TLS negotiation itself.",
"self",
".",
"helo_resp",
"=",
"None",
"self",
".",
"ehlo_resp",
"=",
"None",
"self",
".",
"esmtp_features",
"=",
"{",
"}",
"self",
".",
"does_esmtp",
"=",
"0",
"return",
"(",
"resp",
",",
"reply",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/smtplib.py#L607-L641 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/closured/lib/python2.7/collections.py | python | Counter.__missing__ | (self, key) | return 0 | The count of elements not in the Counter is zero. | The count of elements not in the Counter is zero. | [
"The",
"count",
"of",
"elements",
"not",
"in",
"the",
"Counter",
"is",
"zero",
"."
] | def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0 | [
"def",
"__missing__",
"(",
"self",
",",
"key",
")",
":",
"# Needed so that self[missing_item] does not raise KeyError",
"return",
"0"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/closured/lib/python2.7/collections.py#L420-L423 |
|
nkrode/RedisLive | e1d7763baee558ce4681b7764025d38df5ee5798 | src/dataprovider/redisprovider.py | python | RedisStatsProvider.save_info_command | (self, server, timestamp, info) | Save Redis info command dump
Args:
server (str): id of server
timestamp (datetime): Timestamp.
info (dict): The result of a Redis INFO command. | Save Redis info command dump | [
"Save",
"Redis",
"info",
"command",
"dump"
] | def save_info_command(self, server, timestamp, info):
"""Save Redis info command dump
Args:
server (str): id of server
timestamp (datetime): Timestamp.
info (dict): The result of a Redis INFO command.
"""
self.conn.set(server + ":Info", json.dumps(info)) | [
"def",
"save_info_command",
"(",
"self",
",",
"server",
",",
"timestamp",
",",
"info",
")",
":",
"self",
".",
"conn",
".",
"set",
"(",
"server",
"+",
"\":Info\"",
",",
"json",
".",
"dumps",
"(",
"info",
")",
")"
] | https://github.com/nkrode/RedisLive/blob/e1d7763baee558ce4681b7764025d38df5ee5798/src/dataprovider/redisprovider.py#L32-L40 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/reloop-closured/lib/python2.7/random.py | python | WichmannHill.seed | (self, a=None) | Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator). | Initialize internal state from hashable object. | [
"Initialize",
"internal",
"state",
"from",
"hashable",
"object",
"."
] | def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If a is not None or an int or long, hash(a) is used instead.
If a is an int or long, a is used directly. Distinct values between
0 and 27814431486575L inclusive are guaranteed to yield distinct
internal states (this guarantee is specific to the default
Wichmann-Hill generator).
"""
if a is None:
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long(time.time() * 256) # use fractional seconds
if not isinstance(a, (int, long)):
a = hash(a)
a, x = divmod(a, 30268)
a, y = divmod(a, 30306)
a, z = divmod(a, 30322)
self._seed = int(x)+1, int(y)+1, int(z)+1
self.gauss_next = None | [
"def",
"seed",
"(",
"self",
",",
"a",
"=",
"None",
")",
":",
"if",
"a",
"is",
"None",
":",
"try",
":",
"a",
"=",
"long",
"(",
"_hexlify",
"(",
"_urandom",
"(",
"16",
")",
")",
",",
"16",
")",
"except",
"NotImplementedError",
":",
"import",
"time",
"a",
"=",
"long",
"(",
"time",
".",
"time",
"(",
")",
"*",
"256",
")",
"# use fractional seconds",
"if",
"not",
"isinstance",
"(",
"a",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"a",
"=",
"hash",
"(",
"a",
")",
"a",
",",
"x",
"=",
"divmod",
"(",
"a",
",",
"30268",
")",
"a",
",",
"y",
"=",
"divmod",
"(",
"a",
",",
"30306",
")",
"a",
",",
"z",
"=",
"divmod",
"(",
"a",
",",
"30322",
")",
"self",
".",
"_seed",
"=",
"int",
"(",
"x",
")",
"+",
"1",
",",
"int",
"(",
"y",
")",
"+",
"1",
",",
"int",
"(",
"z",
")",
"+",
"1",
"self",
".",
"gauss_next",
"=",
"None"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/reloop-closured/lib/python2.7/random.py#L657-L686 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/experimental/ptvsd/ptvsd/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/user32.py | python | Point._as_parameter_ | (self) | return POINT(self.x, self.y) | Compatibility with ctypes.
Allows passing transparently a Point object to an API call. | Compatibility with ctypes.
Allows passing transparently a Point object to an API call. | [
"Compatibility",
"with",
"ctypes",
".",
"Allows",
"passing",
"transparently",
"a",
"Point",
"object",
"to",
"an",
"API",
"call",
"."
] | def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Point object to an API call.
"""
return POINT(self.x, self.y) | [
"def",
"_as_parameter_",
"(",
"self",
")",
":",
"return",
"POINT",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")"
] | 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/win32/user32.py#L438-L443 |
|
TeamvisionCorp/TeamVision | aa2a57469e430ff50cce21174d8f280efa0a83a7 | distribute/0.0.4/build_shell/teamvision/teamvision/issue/views/dashboard_view.py | python | index | (request,env_id) | return page_worker.get_dashboard_index(request,"all") | index page | index page | [
"index",
"page"
] | def index(request,env_id):
''' index page'''
page_worker=ENVDashBoardPageWorker(request)
return page_worker.get_dashboard_index(request,"all") | [
"def",
"index",
"(",
"request",
",",
"env_id",
")",
":",
"page_worker",
"=",
"ENVDashBoardPageWorker",
"(",
"request",
")",
"return",
"page_worker",
".",
"get_dashboard_index",
"(",
"request",
",",
"\"all\"",
")"
] | https://github.com/TeamvisionCorp/TeamVision/blob/aa2a57469e430ff50cce21174d8f280efa0a83a7/distribute/0.0.4/build_shell/teamvision/teamvision/issue/views/dashboard_view.py#L18-L21 |
|
aaPanel/aaPanel | d2a66661dbd66948cce5a074214257550aec91ee | class/pyotp/totp.py | python | TOTP.__init__ | (self, *args, **kwargs) | :param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int | :param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int | [
":",
"param",
"interval",
":",
"the",
"time",
"interval",
"in",
"seconds",
"for",
"OTP",
".",
"This",
"defaults",
"to",
"30",
".",
":",
"type",
"interval",
":",
"int"
] | def __init__(self, *args, **kwargs):
"""
:param interval: the time interval in seconds
for OTP. This defaults to 30.
:type interval: int
"""
self.interval = kwargs.pop('interval', 30)
super(TOTP, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"interval",
"=",
"kwargs",
".",
"pop",
"(",
"'interval'",
",",
"30",
")",
"super",
"(",
"TOTP",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/aaPanel/aaPanel/blob/d2a66661dbd66948cce5a074214257550aec91ee/class/pyotp/totp.py#L14-L21 |
||
Nexedi/erp5 | 44df1959c0e21576cf5e9803d602d95efb4b695b | product/Zelenium/zuite.py | python | Zuite._getZipFile | ( self, include_selenium=True ) | return stream.getvalue() | Generate a zip file containing both tests and scaffolding. | Generate a zip file containing both tests and scaffolding. | [
"Generate",
"a",
"zip",
"file",
"containing",
"both",
"tests",
"and",
"scaffolding",
"."
] | def _getZipFile( self, include_selenium=True ):
""" Generate a zip file containing both tests and scaffolding.
"""
stream = StringIO.StringIO()
archive = zipfile.ZipFile( stream, 'w' )
def convertToBytes(body):
if isinstance(body, types.UnicodeType):
return body.encode(_DEFAULTENCODING)
else:
return body
archive.writestr( 'index.html'
, convertToBytes(self.index_html( suite_name='testSuite.html' ) ) )
test_cases = self.listTestCases()
paths = { '' : [] }
def _ensurePath( prefix, element ):
elements = paths.setdefault( prefix, [] )
if element not in elements:
elements.append( element )
for info in test_cases:
# ensure suffixes
path = self._getFilename( info[ 'path' ] )
info[ 'path' ] = path
info[ 'url' ] = self._getFilename( info[ 'url' ] )
elements = path.split( os.path.sep )
_ensurePath( '', elements[ 0 ] )
for i in range( 1, len( elements ) ):
prefix = '/'.join( elements[ : i ] )
_ensurePath( prefix, elements[ i ] )
archive.writestr( 'testSuite.html'
, convertToBytes(self.test_suite_html( test_cases=test_cases ) ) )
for pathname, filenames in paths.items():
if pathname == '':
filename = '.objects'
else:
filename = '%s/.objects' % pathname
archive.writestr( convertToBytes(filename)
, convertToBytes(u'\n'.join( filenames ) ) )
for info in test_cases:
test_case = info[ 'test_case' ]
if getattr( test_case, '__call__', None ) is not None:
body = test_case() # XXX: DTML?
else:
body = test_case.manage_FTPget()
archive.writestr( convertToBytes(info[ 'path' ])
, convertToBytes(body) )
if include_selenium:
for k, v in _SUPPORT_FILES.items():
archive.writestr( convertToBytes(k),
convertToBytes(v.__of__(self).manage_FTPget() ) )
archive.close()
return stream.getvalue() | [
"def",
"_getZipFile",
"(",
"self",
",",
"include_selenium",
"=",
"True",
")",
":",
"stream",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"stream",
",",
"'w'",
")",
"def",
"convertToBytes",
"(",
"body",
")",
":",
"if",
"isinstance",
"(",
"body",
",",
"types",
".",
"UnicodeType",
")",
":",
"return",
"body",
".",
"encode",
"(",
"_DEFAULTENCODING",
")",
"else",
":",
"return",
"body",
"archive",
".",
"writestr",
"(",
"'index.html'",
",",
"convertToBytes",
"(",
"self",
".",
"index_html",
"(",
"suite_name",
"=",
"'testSuite.html'",
")",
")",
")",
"test_cases",
"=",
"self",
".",
"listTestCases",
"(",
")",
"paths",
"=",
"{",
"''",
":",
"[",
"]",
"}",
"def",
"_ensurePath",
"(",
"prefix",
",",
"element",
")",
":",
"elements",
"=",
"paths",
".",
"setdefault",
"(",
"prefix",
",",
"[",
"]",
")",
"if",
"element",
"not",
"in",
"elements",
":",
"elements",
".",
"append",
"(",
"element",
")",
"for",
"info",
"in",
"test_cases",
":",
"# ensure suffixes",
"path",
"=",
"self",
".",
"_getFilename",
"(",
"info",
"[",
"'path'",
"]",
")",
"info",
"[",
"'path'",
"]",
"=",
"path",
"info",
"[",
"'url'",
"]",
"=",
"self",
".",
"_getFilename",
"(",
"info",
"[",
"'url'",
"]",
")",
"elements",
"=",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"_ensurePath",
"(",
"''",
",",
"elements",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"elements",
")",
")",
":",
"prefix",
"=",
"'/'",
".",
"join",
"(",
"elements",
"[",
":",
"i",
"]",
")",
"_ensurePath",
"(",
"prefix",
",",
"elements",
"[",
"i",
"]",
")",
"archive",
".",
"writestr",
"(",
"'testSuite.html'",
",",
"convertToBytes",
"(",
"self",
".",
"test_suite_html",
"(",
"test_cases",
"=",
"test_cases",
")",
")",
")",
"for",
"pathname",
",",
"filenames",
"in",
"paths",
".",
"items",
"(",
")",
":",
"if",
"pathname",
"==",
"''",
":",
"filename",
"=",
"'.objects'",
"else",
":",
"filename",
"=",
"'%s/.objects'",
"%",
"pathname",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"filename",
")",
",",
"convertToBytes",
"(",
"u'\\n'",
".",
"join",
"(",
"filenames",
")",
")",
")",
"for",
"info",
"in",
"test_cases",
":",
"test_case",
"=",
"info",
"[",
"'test_case'",
"]",
"if",
"getattr",
"(",
"test_case",
",",
"'__call__'",
",",
"None",
")",
"is",
"not",
"None",
":",
"body",
"=",
"test_case",
"(",
")",
"# XXX: DTML?",
"else",
":",
"body",
"=",
"test_case",
".",
"manage_FTPget",
"(",
")",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"info",
"[",
"'path'",
"]",
")",
",",
"convertToBytes",
"(",
"body",
")",
")",
"if",
"include_selenium",
":",
"for",
"k",
",",
"v",
"in",
"_SUPPORT_FILES",
".",
"items",
"(",
")",
":",
"archive",
".",
"writestr",
"(",
"convertToBytes",
"(",
"k",
")",
",",
"convertToBytes",
"(",
"v",
".",
"__of__",
"(",
"self",
")",
".",
"manage_FTPget",
"(",
")",
")",
")",
"archive",
".",
"close",
"(",
")",
"return",
"stream",
".",
"getvalue",
"(",
")"
] | https://github.com/Nexedi/erp5/blob/44df1959c0e21576cf5e9803d602d95efb4b695b/product/Zelenium/zuite.py#L497-L566 |
|
carlosperate/ardublockly | 04fa48273b5651386d0ef1ce6dd446795ffc2594 | ardublocklyserver/local-packages/serial/threaded/__init__.py | python | LineReader.handle_line | (self, line) | Process one line - to be overridden by subclassing | Process one line - to be overridden by subclassing | [
"Process",
"one",
"line",
"-",
"to",
"be",
"overridden",
"by",
"subclassing"
] | def handle_line(self, line):
"""Process one line - to be overridden by subclassing"""
raise NotImplementedError('please implement functionality in handle_line') | [
"def",
"handle_line",
"(",
"self",
",",
"line",
")",
":",
"raise",
"NotImplementedError",
"(",
"'please implement functionality in handle_line'",
")"
] | https://github.com/carlosperate/ardublockly/blob/04fa48273b5651386d0ef1ce6dd446795ffc2594/ardublocklyserver/local-packages/serial/threaded/__init__.py#L134-L136 |
||
aws-samples/aws-lex-web-ui | 370f11286062957faf51448cb3bd93c5776be8e0 | templates/custom-resources/lex-manager.py | python | get_parsed_args | () | return args | Parse arguments passed when running as a shell script | Parse arguments passed when running as a shell script | [
"Parse",
"arguments",
"passed",
"when",
"running",
"as",
"a",
"shell",
"script"
] | def get_parsed_args():
""" Parse arguments passed when running as a shell script
"""
parser = argparse.ArgumentParser(
description='Lex bot manager. Import, export or delete a Lex bot.'
' Used to import/export/delete Lex bots and associated resources'
' (i.e. intents, slot types).'
)
format_group = parser.add_mutually_exclusive_group()
format_group.add_argument('-i', '--import',
nargs='?',
default=argparse.SUPPRESS,
const=BOT_DEFINITION_FILENAME,
metavar='file',
help='Import bot definition from file into account. Defaults to: {}'
.format(BOT_DEFINITION_FILENAME),
)
format_group.add_argument('-e', '--export',
nargs='?',
default=argparse.SUPPRESS,
metavar='botname',
help='Export bot definition as JSON to stdout'
' Defaults to reading the botname from the definition file: {}'
.format(BOT_DEFINITION_FILENAME),
)
format_group.add_argument('-d', '--delete',
nargs=1,
default=argparse.SUPPRESS,
metavar='botname',
help='Deletes the bot passed as argument and its associated resources.'
)
args = parser.parse_args()
if not bool(vars(args)):
parser.print_help()
sys.exit(1)
return args | [
"def",
"get_parsed_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Lex bot manager. Import, export or delete a Lex bot.'",
"' Used to import/export/delete Lex bots and associated resources'",
"' (i.e. intents, slot types).'",
")",
"format_group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"format_group",
".",
"add_argument",
"(",
"'-i'",
",",
"'--import'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"const",
"=",
"BOT_DEFINITION_FILENAME",
",",
"metavar",
"=",
"'file'",
",",
"help",
"=",
"'Import bot definition from file into account. Defaults to: {}'",
".",
"format",
"(",
"BOT_DEFINITION_FILENAME",
")",
",",
")",
"format_group",
".",
"add_argument",
"(",
"'-e'",
",",
"'--export'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"metavar",
"=",
"'botname'",
",",
"help",
"=",
"'Export bot definition as JSON to stdout'",
"' Defaults to reading the botname from the definition file: {}'",
".",
"format",
"(",
"BOT_DEFINITION_FILENAME",
")",
",",
")",
"format_group",
".",
"add_argument",
"(",
"'-d'",
",",
"'--delete'",
",",
"nargs",
"=",
"1",
",",
"default",
"=",
"argparse",
".",
"SUPPRESS",
",",
"metavar",
"=",
"'botname'",
",",
"help",
"=",
"'Deletes the bot passed as argument and its associated resources.'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"if",
"not",
"bool",
"(",
"vars",
"(",
"args",
")",
")",
":",
"parser",
".",
"print_help",
"(",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"args"
] | https://github.com/aws-samples/aws-lex-web-ui/blob/370f11286062957faf51448cb3bd93c5776be8e0/templates/custom-resources/lex-manager.py#L105-L142 |
|
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/ftplib.py | python | FTP.size | (self, filename) | Retrieve the size of a file. | Retrieve the size of a file. | [
"Retrieve",
"the",
"size",
"of",
"a",
"file",
"."
] | def size(self, filename):
'''Retrieve the size of a file.'''
# The SIZE command is defined in RFC-3659
resp = self.sendcmd('SIZE ' + filename)
if resp[:3] == '213':
s = resp[3:].strip()
try:
return int(s)
except (OverflowError, ValueError):
return long(s) | [
"def",
"size",
"(",
"self",
",",
"filename",
")",
":",
"# The SIZE command is defined in RFC-3659",
"resp",
"=",
"self",
".",
"sendcmd",
"(",
"'SIZE '",
"+",
"filename",
")",
"if",
"resp",
"[",
":",
"3",
"]",
"==",
"'213'",
":",
"s",
"=",
"resp",
"[",
"3",
":",
"]",
".",
"strip",
"(",
")",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
"(",
"OverflowError",
",",
"ValueError",
")",
":",
"return",
"long",
"(",
"s",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/ftplib.py#L545-L554 |
||
mozilla/spidernode | aafa9e5273f954f272bb4382fc007af14674b4c2 | deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py | python | _ValidateSourcesForMSVSProject | (spec, version) | Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target.
version: The VisualStudioVersion object. | Makes sure if duplicate basenames are not specified in the source list. | [
"Makes",
"sure",
"if",
"duplicate",
"basenames",
"are",
"not",
"specified",
"in",
"the",
"source",
"list",
"."
] | def _ValidateSourcesForMSVSProject(spec, version):
"""Makes sure if duplicate basenames are not specified in the source list.
Arguments:
spec: The target dictionary containing the properties of the target.
version: The VisualStudioVersion object.
"""
# This validation should not be applied to MSVC2010 and later.
assert not version.UsesVcxproj()
# TODO: Check if MSVC allows this for loadable_module targets.
if spec.get('type', None) not in ('static_library', 'shared_library'):
return
sources = spec.get('sources', [])
basenames = {}
for source in sources:
name, ext = os.path.splitext(source)
is_compiled_file = ext in [
'.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S']
if not is_compiled_file:
continue
basename = os.path.basename(name) # Don't include extension.
basenames.setdefault(basename, []).append(source)
error = ''
for basename, files in basenames.iteritems():
if len(files) > 1:
error += ' %s: %s\n' % (basename, ' '.join(files))
if error:
print('static library %s has several files with the same basename:\n' %
spec['target_name'] + error + 'MSVC08 cannot handle that.')
raise GypError('Duplicate basenames in sources section, see list above') | [
"def",
"_ValidateSourcesForMSVSProject",
"(",
"spec",
",",
"version",
")",
":",
"# This validation should not be applied to MSVC2010 and later.",
"assert",
"not",
"version",
".",
"UsesVcxproj",
"(",
")",
"# TODO: Check if MSVC allows this for loadable_module targets.",
"if",
"spec",
".",
"get",
"(",
"'type'",
",",
"None",
")",
"not",
"in",
"(",
"'static_library'",
",",
"'shared_library'",
")",
":",
"return",
"sources",
"=",
"spec",
".",
"get",
"(",
"'sources'",
",",
"[",
"]",
")",
"basenames",
"=",
"{",
"}",
"for",
"source",
"in",
"sources",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"source",
")",
"is_compiled_file",
"=",
"ext",
"in",
"[",
"'.c'",
",",
"'.cc'",
",",
"'.cpp'",
",",
"'.cxx'",
",",
"'.m'",
",",
"'.mm'",
",",
"'.s'",
",",
"'.S'",
"]",
"if",
"not",
"is_compiled_file",
":",
"continue",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"name",
")",
"# Don't include extension.",
"basenames",
".",
"setdefault",
"(",
"basename",
",",
"[",
"]",
")",
".",
"append",
"(",
"source",
")",
"error",
"=",
"''",
"for",
"basename",
",",
"files",
"in",
"basenames",
".",
"iteritems",
"(",
")",
":",
"if",
"len",
"(",
"files",
")",
">",
"1",
":",
"error",
"+=",
"' %s: %s\\n'",
"%",
"(",
"basename",
",",
"' '",
".",
"join",
"(",
"files",
")",
")",
"if",
"error",
":",
"print",
"(",
"'static library %s has several files with the same basename:\\n'",
"%",
"spec",
"[",
"'target_name'",
"]",
"+",
"error",
"+",
"'MSVC08 cannot handle that.'",
")",
"raise",
"GypError",
"(",
"'Duplicate basenames in sources section, see list above'",
")"
] | https://github.com/mozilla/spidernode/blob/aafa9e5273f954f272bb4382fc007af14674b4c2/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L947-L979 |
||
atom-community/ide-python | c046f9c2421713b34baa22648235541c5bb284fe | dist/debugger/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py | python | ReplBackend.run_command | (self, command) | runs the specified command which is a string containing code | runs the specified command which is a string containing code | [
"runs",
"the",
"specified",
"command",
"which",
"is",
"a",
"string",
"containing",
"code"
] | def run_command(self, command):
"""runs the specified command which is a string containing code"""
raise NotImplementedError | [
"def",
"run_command",
"(",
"self",
",",
"command",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/atom-community/ide-python/blob/c046f9c2421713b34baa22648235541c5bb284fe/dist/debugger/VendorLib/vs-py-debugger/pythonFiles/PythonTools/visualstudio_py_repl.py#L469-L471 |
||
depjs/dep | cb8def92812d80b1fd8e5ffbbc1ae129a207fff6 | node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py | python | NinjaWriter.GypPathToNinja | (self, path, env=None) | return os.path.normpath(os.path.join(self.build_to_base, path)) | Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions. | Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|. | [
"Translate",
"a",
"gyp",
"path",
"to",
"a",
"ninja",
"path",
"optionally",
"expanding",
"environment",
"variable",
"references",
"in",
"|path|",
"with",
"|env|",
"."
] | def GypPathToNinja(self, path, env=None):
"""Translate a gyp path to a ninja path, optionally expanding environment
variable references in |path| with |env|.
See the above discourse on path conversions."""
if env:
if self.flavor == "mac":
path = gyp.xcode_emulation.ExpandEnvVars(path, env)
elif self.flavor == "win":
path = gyp.msvs_emulation.ExpandMacros(path, env)
if path.startswith("$!"):
expanded = self.ExpandSpecial(path)
if self.flavor == "win":
expanded = os.path.normpath(expanded)
return expanded
if "$|" in path:
path = self.ExpandSpecial(path)
assert "$" not in path, path
return os.path.normpath(os.path.join(self.build_to_base, path)) | [
"def",
"GypPathToNinja",
"(",
"self",
",",
"path",
",",
"env",
"=",
"None",
")",
":",
"if",
"env",
":",
"if",
"self",
".",
"flavor",
"==",
"\"mac\"",
":",
"path",
"=",
"gyp",
".",
"xcode_emulation",
".",
"ExpandEnvVars",
"(",
"path",
",",
"env",
")",
"elif",
"self",
".",
"flavor",
"==",
"\"win\"",
":",
"path",
"=",
"gyp",
".",
"msvs_emulation",
".",
"ExpandMacros",
"(",
"path",
",",
"env",
")",
"if",
"path",
".",
"startswith",
"(",
"\"$!\"",
")",
":",
"expanded",
"=",
"self",
".",
"ExpandSpecial",
"(",
"path",
")",
"if",
"self",
".",
"flavor",
"==",
"\"win\"",
":",
"expanded",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"expanded",
")",
"return",
"expanded",
"if",
"\"$|\"",
"in",
"path",
":",
"path",
"=",
"self",
".",
"ExpandSpecial",
"(",
"path",
")",
"assert",
"\"$\"",
"not",
"in",
"path",
",",
"path",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"build_to_base",
",",
"path",
")",
")"
] | https://github.com/depjs/dep/blob/cb8def92812d80b1fd8e5ffbbc1ae129a207fff6/node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py#L304-L322 |
|
ipython-contrib/jupyter_contrib_nbextensions | a186b18efaa1f55fba64f08cd9d8bf85cba56d25 | src/jupyter_contrib_nbextensions/application.py | python | BaseContribNbextensionsApp._log_datefmt_default | (self) | return "%H:%M:%S" | Exclude date from timestamp. | Exclude date from timestamp. | [
"Exclude",
"date",
"from",
"timestamp",
"."
] | def _log_datefmt_default(self):
"""Exclude date from timestamp."""
return "%H:%M:%S" | [
"def",
"_log_datefmt_default",
"(",
"self",
")",
":",
"return",
"\"%H:%M:%S\""
] | https://github.com/ipython-contrib/jupyter_contrib_nbextensions/blob/a186b18efaa1f55fba64f08cd9d8bf85cba56d25/src/jupyter_contrib_nbextensions/application.py#L28-L30 |
|
ivendrov/order-embedding | 2057e6056a887ea00d304fc43a8a7e4810f4d669 | utils.py | python | ortho_weight | (ndim) | return u.astype('float32') | Orthogonal weight init, for recurrent layers | Orthogonal weight init, for recurrent layers | [
"Orthogonal",
"weight",
"init",
"for",
"recurrent",
"layers"
] | def ortho_weight(ndim):
"""
Orthogonal weight init, for recurrent layers
"""
W = numpy.random.randn(ndim, ndim)
u, s, v = numpy.linalg.svd(W)
return u.astype('float32') | [
"def",
"ortho_weight",
"(",
"ndim",
")",
":",
"W",
"=",
"numpy",
".",
"random",
".",
"randn",
"(",
"ndim",
",",
"ndim",
")",
"u",
",",
"s",
",",
"v",
"=",
"numpy",
".",
"linalg",
".",
"svd",
"(",
"W",
")",
"return",
"u",
".",
"astype",
"(",
"'float32'",
")"
] | https://github.com/ivendrov/order-embedding/blob/2057e6056a887ea00d304fc43a8a7e4810f4d669/utils.py#L61-L67 |
|
wtx358/wtxlog | 5e0dd09309ff98b26009a9eac48b01afd344cd99 | wtxlog/main/views.py | python | upload | () | return json.dumps(result) | 文件上传函数 | 文件上传函数 | [
"文件上传函数"
] | def upload():
''' 文件上传函数 '''
result = {"err": "", "msg": {"url": "", "localfile": ""}}
fname = ''
fext = ''
data = None
if request.method == 'POST' and 'filedata' in request.files:
# 传统上传模式,IE浏览器使用这种模式
fileobj = request.files['filedata']
result["msg"]["localfile"] = fileobj.filename
fname, fext = os.path.splitext(fileobj.filename)
data = fileobj.read()
elif 'CONTENT_DISPOSITION' in request.headers:
# HTML5上传模式,FIREFOX等默认使用此模式
pattern = re.compile(r"""\s.*?\s?filename\s*=\s*['|"]?([^\s'"]+).*?""", re.I)
_d = request.headers.get('CONTENT_DISPOSITION').encode('utf-8')
if urllib.quote(_d).count('%25') > 0:
_d = urllib.unquote(_d)
filenames = pattern.findall(_d)
if len(filenames) == 1:
result["msg"]["localfile"] = urllib.unquote(filenames[0])
fname, fext = os.path.splitext(filenames[0])
data = request.data
ONLINE = False
if ONLINE:
obj = SaveUploadFile(fext, data)
url = obj.save()
result["msg"]["url"] = '!%s' % url
else:
obj = SaveUploadFile(fext, data)
url = obj.save()
result["msg"]["url"] = '!%s' % url
pass
return json.dumps(result) | [
"def",
"upload",
"(",
")",
":",
"result",
"=",
"{",
"\"err\"",
":",
"\"\"",
",",
"\"msg\"",
":",
"{",
"\"url\"",
":",
"\"\"",
",",
"\"localfile\"",
":",
"\"\"",
"}",
"}",
"fname",
"=",
"''",
"fext",
"=",
"''",
"data",
"=",
"None",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"'filedata'",
"in",
"request",
".",
"files",
":",
"# 传统上传模式,IE浏览器使用这种模式",
"fileobj",
"=",
"request",
".",
"files",
"[",
"'filedata'",
"]",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"localfile\"",
"]",
"=",
"fileobj",
".",
"filename",
"fname",
",",
"fext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fileobj",
".",
"filename",
")",
"data",
"=",
"fileobj",
".",
"read",
"(",
")",
"elif",
"'CONTENT_DISPOSITION'",
"in",
"request",
".",
"headers",
":",
"# HTML5上传模式,FIREFOX等默认使用此模式",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"\\s.*?\\s?filename\\s*=\\s*['|\"]?([^\\s'\"]+).*?\"\"\"",
",",
"re",
".",
"I",
")",
"_d",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'CONTENT_DISPOSITION'",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"urllib",
".",
"quote",
"(",
"_d",
")",
".",
"count",
"(",
"'%25'",
")",
">",
"0",
":",
"_d",
"=",
"urllib",
".",
"unquote",
"(",
"_d",
")",
"filenames",
"=",
"pattern",
".",
"findall",
"(",
"_d",
")",
"if",
"len",
"(",
"filenames",
")",
"==",
"1",
":",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"localfile\"",
"]",
"=",
"urllib",
".",
"unquote",
"(",
"filenames",
"[",
"0",
"]",
")",
"fname",
",",
"fext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filenames",
"[",
"0",
"]",
")",
"data",
"=",
"request",
".",
"data",
"ONLINE",
"=",
"False",
"if",
"ONLINE",
":",
"obj",
"=",
"SaveUploadFile",
"(",
"fext",
",",
"data",
")",
"url",
"=",
"obj",
".",
"save",
"(",
")",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"url\"",
"]",
"=",
"'!%s'",
"%",
"url",
"else",
":",
"obj",
"=",
"SaveUploadFile",
"(",
"fext",
",",
"data",
")",
"url",
"=",
"obj",
".",
"save",
"(",
")",
"result",
"[",
"\"msg\"",
"]",
"[",
"\"url\"",
"]",
"=",
"'!%s'",
"%",
"url",
"pass",
"return",
"json",
".",
"dumps",
"(",
"result",
")"
] | https://github.com/wtx358/wtxlog/blob/5e0dd09309ff98b26009a9eac48b01afd344cd99/wtxlog/main/views.py#L311-L348 |
|
liftoff/GateOne | 6ae1d01f7fe21e2703bdf982df7353e7bb81a500 | termio/termio.py | python | MultiplexPOSIXIOLoop._write | (self, chars) | Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken. | Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken. | [
"Writes",
"*",
"chars",
"*",
"to",
"self",
".",
"fd",
"(",
"pretty",
"straightforward",
")",
".",
"If",
"IOError",
"or",
"OSError",
"exceptions",
"are",
"encountered",
"will",
"run",
"terminate",
".",
"All",
"other",
"exceptions",
"are",
"logged",
"but",
"no",
"action",
"will",
"be",
"taken",
"."
] | def _write(self, chars):
"""
Writes *chars* to `self.fd` (pretty straightforward). If IOError or
OSError exceptions are encountered, will run `terminate`. All other
exceptions are logged but no action will be taken.
"""
#logging.debug("MultiplexPOSIXIOLoop._write(%s)" % repr(chars))
try:
with io.open(
self.fd, 'wt', encoding='UTF-8', closefd=False) as writer:
writer.write(chars)
if self.ratelimiter_engaged:
if u'\x03' in chars: # Ctrl-C
# This will force self._read() to discard the buffer
self.ctrl_c_pressed = True
# Reattach the fd so the user can continue immediately
self._reenable_output()
except OSError as e:
logging.error(_(
"Encountered error writing to terminal program: %s") % e)
if self.isalive():
self.terminate()
except IOError as e:
# We can safely ignore most of these... They tend to crop up when
# writing big chunks of data to dtach'd terminals.
if not 'raw write()' in e.message:
logging.error("write() exception: %s" % e)
except Exception as e:
logging.error("write() exception: %s" % e) | [
"def",
"_write",
"(",
"self",
",",
"chars",
")",
":",
"#logging.debug(\"MultiplexPOSIXIOLoop._write(%s)\" % repr(chars))",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"fd",
",",
"'wt'",
",",
"encoding",
"=",
"'UTF-8'",
",",
"closefd",
"=",
"False",
")",
"as",
"writer",
":",
"writer",
".",
"write",
"(",
"chars",
")",
"if",
"self",
".",
"ratelimiter_engaged",
":",
"if",
"u'\\x03'",
"in",
"chars",
":",
"# Ctrl-C",
"# This will force self._read() to discard the buffer",
"self",
".",
"ctrl_c_pressed",
"=",
"True",
"# Reattach the fd so the user can continue immediately",
"self",
".",
"_reenable_output",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"_",
"(",
"\"Encountered error writing to terminal program: %s\"",
")",
"%",
"e",
")",
"if",
"self",
".",
"isalive",
"(",
")",
":",
"self",
".",
"terminate",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"# We can safely ignore most of these... They tend to crop up when",
"# writing big chunks of data to dtach'd terminals.",
"if",
"not",
"'raw write()'",
"in",
"e",
".",
"message",
":",
"logging",
".",
"error",
"(",
"\"write() exception: %s\"",
"%",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"write() exception: %s\"",
"%",
"e",
")"
] | https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/termio/termio.py#L1750-L1778 |
||
replit-archive/jsrepl | 36d79b6288ca5d26208e8bade2a168c6ebcb2376 | extern/python/unclosured/lib/python2.7/mailbox.py | python | Babyl.__setitem__ | (self, key, message) | Replace the keyed message; raise KeyError if it doesn't exist. | Replace the keyed message; raise KeyError if it doesn't exist. | [
"Replace",
"the",
"keyed",
"message",
";",
"raise",
"KeyError",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | def __setitem__(self, key, message):
"""Replace the keyed message; raise KeyError if it doesn't exist."""
_singlefileMailbox.__setitem__(self, key, message)
if isinstance(message, BabylMessage):
self._labels[key] = message.get_labels() | [
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
":",
"_singlefileMailbox",
".",
"__setitem__",
"(",
"self",
",",
"key",
",",
"message",
")",
"if",
"isinstance",
"(",
"message",
",",
"BabylMessage",
")",
":",
"self",
".",
"_labels",
"[",
"key",
"]",
"=",
"message",
".",
"get_labels",
"(",
")"
] | https://github.com/replit-archive/jsrepl/blob/36d79b6288ca5d26208e8bade2a168c6ebcb2376/extern/python/unclosured/lib/python2.7/mailbox.py#L1192-L1196 |
||
liftoff/GateOne | 6ae1d01f7fe21e2703bdf982df7353e7bb81a500 | termio/termio.py | python | MultiplexPOSIXIOLoop._read | (self, bytes=-1) | return result | Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output.
Returns the result of all that reading.
.. note:: Non-blocking. | Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output. | [
"Reads",
"at",
"most",
"*",
"bytes",
"*",
"from",
"the",
"incoming",
"stream",
"writes",
"the",
"result",
"to",
"the",
"terminal",
"emulator",
"using",
"term_write",
"and",
"returns",
"what",
"was",
"read",
".",
"If",
"*",
"bytes",
"*",
"is",
"-",
"1",
"(",
"default",
")",
"it",
"will",
"read",
"self",
".",
"fd",
"until",
"there",
"s",
"no",
"more",
"output",
"."
] | def _read(self, bytes=-1):
"""
Reads at most *bytes* from the incoming stream, writes the result to
the terminal emulator using `term_write`, and returns what was read.
If *bytes* is -1 (default) it will read `self.fd` until there's no more
output.
Returns the result of all that reading.
.. note:: Non-blocking.
"""
# Commented out because it can be really noisy. Uncomment only if you
# *really* need to debug this method.
#logging.debug("MultiplexPOSIXIOLoop._read()")
result = b""
def restore_capture_limit():
self.capture_limit = -1
self.restore_rate = None
try:
with io.open(self.fd, 'rb', closefd=False, buffering=0) as reader:
if bytes == -1:
# 2 seconds of blocking is too much.
timeout = timedelta(seconds=2)
loop_start = datetime.now()
if self.ctrl_c_pressed:
# If the user pressed Ctrl-C and the ratelimiter was
# engaged then we'd best discard the (possibly huge)
# buffer so we don't waste CPU cyles processing it.
reader.read(-1)
self.ctrl_c_pressed = False
return u'^C\n' # Let the user know what happened
if self.restore_rate:
# Need at least three seconds of inactivity to go back
# to unlimited reads
self.io_loop.remove_timeout(self.restore_rate)
self.restore_rate = self.io_loop.add_timeout(
timedelta(seconds=6), restore_capture_limit)
while True:
updated = reader.read(self.capture_limit)
if not updated:
break
result += updated
self.term_write(updated)
if self.ratelimiter_engaged or self.capture_ratelimiter:
break # Only allow one read per IOLoop loop
if self.capture_limit == 2048:
# Block for a little while: Enough to keep things
# moving but not fast enough to slow everyone else
# down
self._blocked_io_handler(wait=1000)
break
if datetime.now() - loop_start > timeout:
# Engage the rate limiter
if self.term.capture:
self.capture_ratelimiter = True
self.capture_limit = 65536
# Make sure we eventually get back to defaults:
self.io_loop.add_timeout(
timedelta(seconds=10),
restore_capture_limit)
# NOTE: The capture_ratelimiter doesn't remove
# self.fd from the IOLoop (that's the diff)
else:
# Set the capture limit to a smaller value so
# when we re-start output again the noisy
# program won't be able to take over again.
self.capture_limit = 2048
self.restore_rate = self.io_loop.add_timeout(
timedelta(seconds=6),
restore_capture_limit)
self._blocked_io_handler()
break
elif bytes:
result = reader.read(bytes)
self.term_write(result)
except IOError as e:
# IOErrors can happen when self.fd is closed before we finish
# reading from it. Not a big deal.
pass
except OSError as e:
logging.error("Got exception in read: %s" % repr(e))
# This can be useful in debugging:
#except Exception as e:
#import traceback
#logging.error(
#"Got unhandled exception in read (???): %s" % repr(e))
#traceback.print_exc(file=sys.stdout)
#if self.isalive():
#self.terminate()
if self.debug:
if result:
print("_read(): %s" % repr(result))
return result | [
"def",
"_read",
"(",
"self",
",",
"bytes",
"=",
"-",
"1",
")",
":",
"# Commented out because it can be really noisy. Uncomment only if you",
"# *really* need to debug this method.",
"#logging.debug(\"MultiplexPOSIXIOLoop._read()\")",
"result",
"=",
"b\"\"",
"def",
"restore_capture_limit",
"(",
")",
":",
"self",
".",
"capture_limit",
"=",
"-",
"1",
"self",
".",
"restore_rate",
"=",
"None",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"fd",
",",
"'rb'",
",",
"closefd",
"=",
"False",
",",
"buffering",
"=",
"0",
")",
"as",
"reader",
":",
"if",
"bytes",
"==",
"-",
"1",
":",
"# 2 seconds of blocking is too much.",
"timeout",
"=",
"timedelta",
"(",
"seconds",
"=",
"2",
")",
"loop_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"self",
".",
"ctrl_c_pressed",
":",
"# If the user pressed Ctrl-C and the ratelimiter was",
"# engaged then we'd best discard the (possibly huge)",
"# buffer so we don't waste CPU cyles processing it.",
"reader",
".",
"read",
"(",
"-",
"1",
")",
"self",
".",
"ctrl_c_pressed",
"=",
"False",
"return",
"u'^C\\n'",
"# Let the user know what happened",
"if",
"self",
".",
"restore_rate",
":",
"# Need at least three seconds of inactivity to go back",
"# to unlimited reads",
"self",
".",
"io_loop",
".",
"remove_timeout",
"(",
"self",
".",
"restore_rate",
")",
"self",
".",
"restore_rate",
"=",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"6",
")",
",",
"restore_capture_limit",
")",
"while",
"True",
":",
"updated",
"=",
"reader",
".",
"read",
"(",
"self",
".",
"capture_limit",
")",
"if",
"not",
"updated",
":",
"break",
"result",
"+=",
"updated",
"self",
".",
"term_write",
"(",
"updated",
")",
"if",
"self",
".",
"ratelimiter_engaged",
"or",
"self",
".",
"capture_ratelimiter",
":",
"break",
"# Only allow one read per IOLoop loop",
"if",
"self",
".",
"capture_limit",
"==",
"2048",
":",
"# Block for a little while: Enough to keep things",
"# moving but not fast enough to slow everyone else",
"# down",
"self",
".",
"_blocked_io_handler",
"(",
"wait",
"=",
"1000",
")",
"break",
"if",
"datetime",
".",
"now",
"(",
")",
"-",
"loop_start",
">",
"timeout",
":",
"# Engage the rate limiter",
"if",
"self",
".",
"term",
".",
"capture",
":",
"self",
".",
"capture_ratelimiter",
"=",
"True",
"self",
".",
"capture_limit",
"=",
"65536",
"# Make sure we eventually get back to defaults:",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"10",
")",
",",
"restore_capture_limit",
")",
"# NOTE: The capture_ratelimiter doesn't remove",
"# self.fd from the IOLoop (that's the diff)",
"else",
":",
"# Set the capture limit to a smaller value so",
"# when we re-start output again the noisy",
"# program won't be able to take over again.",
"self",
".",
"capture_limit",
"=",
"2048",
"self",
".",
"restore_rate",
"=",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"timedelta",
"(",
"seconds",
"=",
"6",
")",
",",
"restore_capture_limit",
")",
"self",
".",
"_blocked_io_handler",
"(",
")",
"break",
"elif",
"bytes",
":",
"result",
"=",
"reader",
".",
"read",
"(",
"bytes",
")",
"self",
".",
"term_write",
"(",
"result",
")",
"except",
"IOError",
"as",
"e",
":",
"# IOErrors can happen when self.fd is closed before we finish",
"# reading from it. Not a big deal.",
"pass",
"except",
"OSError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Got exception in read: %s\"",
"%",
"repr",
"(",
"e",
")",
")",
"# This can be useful in debugging:",
"#except Exception as e:",
"#import traceback",
"#logging.error(",
"#\"Got unhandled exception in read (???): %s\" % repr(e))",
"#traceback.print_exc(file=sys.stdout)",
"#if self.isalive():",
"#self.terminate()",
"if",
"self",
".",
"debug",
":",
"if",
"result",
":",
"print",
"(",
"\"_read(): %s\"",
"%",
"repr",
"(",
"result",
")",
")",
"return",
"result"
] | https://github.com/liftoff/GateOne/blob/6ae1d01f7fe21e2703bdf982df7353e7bb81a500/termio/termio.py#L1583-L1675 |
|
romanvm/django-tinymce4-lite | eef7af8ff6e9de844e14e89b084b86c4b2ba8eba | tinymce/views.py | python | spell_check | (request) | return JsonResponse(output, status=status) | Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse | Implements the TinyMCE 4 spellchecker protocol | [
"Implements",
"the",
"TinyMCE",
"4",
"spellchecker",
"protocol"
] | def spell_check(request):
"""
Implements the TinyMCE 4 spellchecker protocol
:param request: Django http request with JSON-RPC payload from TinyMCE 4
containing a language code and a text to check for errors.
:type request: django.http.request.HttpRequest
:return: Django http response containing JSON-RPC payload
with spellcheck results for TinyMCE 4
:rtype: django.http.JsonResponse
"""
data = json.loads(request.body.decode('utf-8'))
output = {'id': data['id']}
error = None
status = 200
try:
if data['params']['lang'] not in list_languages():
error = 'Missing {0} dictionary!'.format(data['params']['lang'])
raise LookupError(error)
spell_checker = checker.SpellChecker(data['params']['lang'])
spell_checker.set_text(strip_tags(data['params']['text']))
output['result'] = {spell_checker.word: spell_checker.suggest()
for err in spell_checker}
except NameError:
error = 'The pyenchant package is not installed!'
logger.exception(error)
except LookupError:
logger.exception(error)
except Exception:
error = 'Unknown error!'
logger.exception(error)
if error is not None:
output['error'] = error
status = 500
return JsonResponse(output, status=status) | [
"def",
"spell_check",
"(",
"request",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"output",
"=",
"{",
"'id'",
":",
"data",
"[",
"'id'",
"]",
"}",
"error",
"=",
"None",
"status",
"=",
"200",
"try",
":",
"if",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
"not",
"in",
"list_languages",
"(",
")",
":",
"error",
"=",
"'Missing {0} dictionary!'",
".",
"format",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
")",
"raise",
"LookupError",
"(",
"error",
")",
"spell_checker",
"=",
"checker",
".",
"SpellChecker",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'lang'",
"]",
")",
"spell_checker",
".",
"set_text",
"(",
"strip_tags",
"(",
"data",
"[",
"'params'",
"]",
"[",
"'text'",
"]",
")",
")",
"output",
"[",
"'result'",
"]",
"=",
"{",
"spell_checker",
".",
"word",
":",
"spell_checker",
".",
"suggest",
"(",
")",
"for",
"err",
"in",
"spell_checker",
"}",
"except",
"NameError",
":",
"error",
"=",
"'The pyenchant package is not installed!'",
"logger",
".",
"exception",
"(",
"error",
")",
"except",
"LookupError",
":",
"logger",
".",
"exception",
"(",
"error",
")",
"except",
"Exception",
":",
"error",
"=",
"'Unknown error!'",
"logger",
".",
"exception",
"(",
"error",
")",
"if",
"error",
"is",
"not",
"None",
":",
"output",
"[",
"'error'",
"]",
"=",
"error",
"status",
"=",
"500",
"return",
"JsonResponse",
"(",
"output",
",",
"status",
"=",
"status",
")"
] | https://github.com/romanvm/django-tinymce4-lite/blob/eef7af8ff6e9de844e14e89b084b86c4b2ba8eba/tinymce/views.py#L25-L59 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 48