nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
jieter/django-tables2
ce392ee2ee341d7180345a6113919cf9a3925f16
django_tables2/columns/base.py
python
BoundColumn.orderable
(self)
return self._table.orderable
Return whether this column supports ordering.
Return whether this column supports ordering.
[ "Return", "whether", "this", "column", "supports", "ordering", "." ]
def orderable(self): """Return whether this column supports ordering.""" if self.column.orderable is not None: return self.column.orderable return self._table.orderable
[ "def", "orderable", "(", "self", ")", ":", "if", "self", ".", "column", ".", "orderable", "is", "not", "None", ":", "return", "self", ".", "column", ".", "orderable", "return", "self", ".", "_table", ".", "orderable" ]
https://github.com/jieter/django-tables2/blob/ce392ee2ee341d7180345a6113919cf9a3925f16/django_tables2/columns/base.py#L645-L649
IntelAI/models
1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c
models/language_modeling/tensorflow/bert_large/training/bfloat16/optimization.py
python
AdamWeightDecayOptimizer._get_variable_name
(self, param_name)
return param_name
Get the variable name from the tensor name.
Get the variable name from the tensor name.
[ "Get", "the", "variable", "name", "from", "the", "tensor", "name", "." ]
def _get_variable_name(self, param_name): """Get the variable name from the tensor name.""" m = re.match("^(.*):\\d+$", param_name) if m is not None: param_name = m.group(1) return param_name
[ "def", "_get_variable_name", "(", "self", ",", "param_name", ")", ":", "m", "=", "re", ".", "match", "(", "\"^(.*):\\\\d+$\"", ",", "param_name", ")", "if", "m", "is", "not", "None", ":", "param_name", "=", "m", ".", "group", "(", "1", ")", "return", ...
https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/language_modeling/tensorflow/bert_large/training/bfloat16/optimization.py#L233-L238
tangowithcode/tango_with_django_19
cf64796c05eafc73385a6a604de65f3c6b0c1648
code/tango_with_django_project/rango/webhose_search.py
python
run_query
(search_terms, size=10)
return results
Given a string containing search terms (query), and a number of results to return (default of 10), returns a list of results from the Webhose API, with each result consisting of a title, link and summary.
Given a string containing search terms (query), and a number of results to return (default of 10), returns a list of results from the Webhose API, with each result consisting of a title, link and summary.
[ "Given", "a", "string", "containing", "search", "terms", "(", "query", ")", "and", "a", "number", "of", "results", "to", "return", "(", "default", "of", "10", ")", "returns", "a", "list", "of", "results", "from", "the", "Webhose", "API", "with", "each", ...
def run_query(search_terms, size=10): """ Given a string containing search terms (query), and a number of results to return (default of 10), returns a list of results from the Webhose API, with each result consisting of a title, link and summary. """ webhose_api_key = read_webhose_key() if not webhose_api_key: raise KeyError('Webhose key not found') # What's the base URL for the Webhose API? root_url = 'http://webhose.io/search' # Format the query string - escape special characters. query_string = urllib.quote(search_terms) # Use string formatting to construct the complete API URL. search_url = '{root_url}?token={key}&format=json&q={query}&sort=relevancy&size={size}'.format( root_url=root_url, key=webhose_api_key, query=query_string, size=size) results = [] try: # Connect to the Webhose API, and convert the response to a Python dictionary. print(search_url) response = urllib2.urlopen(search_url).read() print(response) json_response = json.loads(response) # Loop through the posts, appendng each to the results list as a dictionary. for post in json_response['posts']: print(post['title']) results.append({'title': post['title'], 'link': post['url'], 'summary': post['text'][:200]}) except Exception as e: print(e) print("Error when querying the Webhose API") # Return the list of results to the calling function. return results
[ "def", "run_query", "(", "search_terms", ",", "size", "=", "10", ")", ":", "webhose_api_key", "=", "read_webhose_key", "(", ")", "if", "not", "webhose_api_key", ":", "raise", "KeyError", "(", "'Webhose key not found'", ")", "# What's the base URL for the Webhose API?"...
https://github.com/tangowithcode/tango_with_django_19/blob/cf64796c05eafc73385a6a604de65f3c6b0c1648/code/tango_with_django_project/rango/webhose_search.py#L24-L68
brendano/tweetmotif
1b0b1e3a941745cd5a26eba01f554688b7c4b27e
everything_else/djfrontend/django-1.0.2/contrib/comments/templatetags/comments.py
python
get_comment_count
(parser, token)
return CommentCountNode.handle_token(parser, token)
Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [object] as [varname] %} {% get_comment_count for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_count for event as comment_count %} {% get_comment_count for calendar.event event.id as comment_count %} {% get_comment_count for calendar.event 17 as comment_count %}
Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause.
[ "Gets", "the", "comment", "count", "for", "the", "given", "params", "and", "populates", "the", "template", "context", "with", "a", "variable", "containing", "that", "value", "whose", "name", "is", "defined", "by", "the", "as", "clause", "." ]
def get_comment_count(parser, token): """ Gets the comment count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_comment_count for [object] as [varname] %} {% get_comment_count for [app].[model] [object_id] as [varname] %} Example usage:: {% get_comment_count for event as comment_count %} {% get_comment_count for calendar.event event.id as comment_count %} {% get_comment_count for calendar.event 17 as comment_count %} """ return CommentCountNode.handle_token(parser, token)
[ "def", "get_comment_count", "(", "parser", ",", "token", ")", ":", "return", "CommentCountNode", ".", "handle_token", "(", "parser", ",", "token", ")" ]
https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/contrib/comments/templatetags/comments.py#L170-L188
Blockstream/satellite
ceb46a00e176c43a6b4170359f6948663a0616bb
blocksatcli/bitcoin.py
python
configure
(args)
Generate bitcoin.conf configuration
Generate bitcoin.conf configuration
[ "Generate", "bitcoin", ".", "conf", "configuration" ]
def configure(args): """Generate bitcoin.conf configuration""" info = config.read_cfg_file(args.cfg, args.cfg_dir) if (info is None): return if (not args.stdout): util.print_header("Bitcoin Conf Generator") if args.datadir is None: home = os.path.expanduser("~") path = os.path.join(home, ".bitcoin") else: path = os.path.abspath(args.datadir) conf_file = "bitcoin.conf" abs_path = os.path.join(path, conf_file) # Network interface ifname = config.get_net_if(info) # Generate configuration object cfg = _gen_cfgs(info, ifname) # Load and concatenate pre-existing configurations if args.concat and os.path.exists(abs_path): with open(abs_path, "r") as fd: prev_cfg_text = fd.read() cfg.load_text_cfg(prev_cfg_text) # Export configurations to text format cfg_text = cfg.text() # Print configurations to stdout and don't save them if (args.stdout): print(cfg_text) return # Proceed to saving configurations print("Save {} at {}".format(conf_file, path)) if (not util.ask_yes_or_no("Proceed?")): print("Aborted") return if not os.path.exists(path): os.makedirs(path) if os.path.exists(abs_path) and not args.concat: if (not util.ask_yes_or_no("File already exists. Overwrite?")): print("Aborted") return with open(abs_path, "w") as fd: fd.write(cfg_text) print("Saved") if (info['setup']['type'] == defs.linux_usb_setup_type): print() util.fill_print( "NOTE: {} was configured assuming the dvbnet interface is " "named {}. You can check if this is the case after launching the " "receiver by running:".format(conf_file, ifname)) print(" ip link show | grep dvb\n") util.fill_print("If the dvb interfaces are numbered differently, " "please update {} accordingly.".format(conf_file)) elif (info['setup']['type'] == defs.standalone_setup_type): print("\n" + textwrap.fill( ("NOTE: {0} was configured assuming the Novra S400 receiver will " "be connected to interface {1}. If this is not the case anymore, " "please update {0} accordingly.").format(conf_file, ifname)))
[ "def", "configure", "(", "args", ")", ":", "info", "=", "config", ".", "read_cfg_file", "(", "args", ".", "cfg", ",", "args", ".", "cfg_dir", ")", "if", "(", "info", "is", "None", ")", ":", "return", "if", "(", "not", "args", ".", "stdout", ")", ...
https://github.com/Blockstream/satellite/blob/ceb46a00e176c43a6b4170359f6948663a0616bb/blocksatcli/bitcoin.py#L120-L192
allegroai/clearml
5953dc6eefadcdfcc2bdbb6a0da32be58823a5af
clearml/utilities/plotlympl/mplexporter/exporter.py
python
Exporter.draw_line
(self, ax, line, force_trans=None)
Process a matplotlib line and call renderer.draw_line
Process a matplotlib line and call renderer.draw_line
[ "Process", "a", "matplotlib", "line", "and", "call", "renderer", ".", "draw_line" ]
def draw_line(self, ax, line, force_trans=None): """Process a matplotlib line and call renderer.draw_line""" coordinates, data = self.process_transform(line.get_transform(), ax, line.get_xydata(), force_trans=force_trans) linestyle = utils.get_line_style(line) if (linestyle['dasharray'] is None and linestyle['drawstyle'] == 'default'): linestyle = None markerstyle = utils.get_marker_style(line) if (markerstyle['marker'] in ['None', 'none', None] or markerstyle['markerpath'][0].size == 0): markerstyle = None label = line.get_label() if markerstyle or linestyle: self.renderer.draw_marked_line(data=data, coordinates=coordinates, linestyle=linestyle, markerstyle=markerstyle, label=label, mplobj=line)
[ "def", "draw_line", "(", "self", ",", "ax", ",", "line", ",", "force_trans", "=", "None", ")", ":", "coordinates", ",", "data", "=", "self", ".", "process_transform", "(", "line", ".", "get_transform", "(", ")", ",", "ax", ",", "line", ".", "get_xydata...
https://github.com/allegroai/clearml/blob/5953dc6eefadcdfcc2bdbb6a0da32be58823a5af/clearml/utilities/plotlympl/mplexporter/exporter.py#L193-L212
snowkylin/TensorFlow-cn
77350fe96841e98f589fe11476cefdf9e5ab5611
source/_static/code/en/model/rnn/rnn.py
python
RNN.call
(self, inputs)
return output
[]
def call(self, inputs): batch_size, seq_length = tf.shape(inputs) inputs = tf.one_hot(inputs, depth=self.num_chars) # [batch_size, seq_length, num_chars] state = self.cell.zero_state(batch_size=batch_size, dtype=tf.float32) for t in range(seq_length.numpy()): output, state = self.cell(inputs[:, t, :], state) output = self.dense(output) return output
[ "def", "call", "(", "self", ",", "inputs", ")", ":", "batch_size", ",", "seq_length", "=", "tf", ".", "shape", "(", "inputs", ")", "inputs", "=", "tf", ".", "one_hot", "(", "inputs", ",", "depth", "=", "self", ".", "num_chars", ")", "# [batch_size, seq...
https://github.com/snowkylin/TensorFlow-cn/blob/77350fe96841e98f589fe11476cefdf9e5ab5611/source/_static/code/en/model/rnn/rnn.py#L14-L21
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/command/alias.py
python
shquote
(arg)
return arg
Quote an argument for later parsing by shlex.split()
Quote an argument for later parsing by shlex.split()
[ "Quote", "an", "argument", "for", "later", "parsing", "by", "shlex", ".", "split", "()" ]
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split() != [arg]: return repr(arg) return arg
[ "def", "shquote", "(", "arg", ")", ":", "for", "c", "in", "'\"'", ",", "\"'\"", ",", "\"\\\\\"", ",", "\"#\"", ":", "if", "c", "in", "arg", ":", "return", "repr", "(", "arg", ")", "if", "arg", ".", "split", "(", ")", "!=", "[", "arg", "]", ":...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/setuptools/command/alias.py#L8-L15
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/noarch/pycparser/c_lexer.py
python
CLexer.t_ppline_NEWLINE
(self, t)
r'\n
r'\n
[ "r", "\\", "n" ]
def t_ppline_NEWLINE(self, t): r'\n' if self.pp_line is None: self._error('line number missing in #line', t) else: self.lexer.lineno = int(self.pp_line) if self.pp_filename is not None: self.filename = self.pp_filename t.lexer.begin('INITIAL')
[ "def", "t_ppline_NEWLINE", "(", "self", ",", "t", ")", ":", "if", "self", ".", "pp_line", "is", "None", ":", "self", ".", "_error", "(", "'line number missing in #line'", ",", "t", ")", "else", ":", "self", ".", "lexer", ".", "lineno", "=", "int", "(",...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/noarch/pycparser/c_lexer.py#L271-L282
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/webapp2-2.5.1/webapp2_extras/appengine/auth/models.py
python
User.create_auth_token
(cls, user_id)
return cls.token_model.create(user_id, 'auth').token
Creates a new authorization token for a given user ID. :param user_id: User unique ID. :returns: A string with the authorization token.
Creates a new authorization token for a given user ID.
[ "Creates", "a", "new", "authorization", "token", "for", "a", "given", "user", "ID", "." ]
def create_auth_token(cls, user_id): """Creates a new authorization token for a given user ID. :param user_id: User unique ID. :returns: A string with the authorization token. """ return cls.token_model.create(user_id, 'auth').token
[ "def", "create_auth_token", "(", "cls", ",", "user_id", ")", ":", "return", "cls", ".", "token_model", ".", "create", "(", "user_id", ",", "'auth'", ")", ".", "token" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.5.1/webapp2_extras/appengine/auth/models.py#L325-L333
openvinotoolkit/open_model_zoo
5a4232f6c35b4916eb6e8750141f4e45761237ef
tools/accuracy_checker/openvino/tools/accuracy_checker/adapters/hit_ratio.py
python
HitRatioAdapter.process
(self, raw, identifiers, frame_meta)
return result
Args: raw: output of model. identifiers: list of input data identifiers. frame_meta: metadata for frame. Returns: list of HitRatioPrediction objects.
Args: raw: output of model. identifiers: list of input data identifiers. frame_meta: metadata for frame. Returns: list of HitRatioPrediction objects.
[ "Args", ":", "raw", ":", "output", "of", "model", ".", "identifiers", ":", "list", "of", "input", "data", "identifiers", ".", "frame_meta", ":", "metadata", "for", "frame", ".", "Returns", ":", "list", "of", "HitRatioPrediction", "objects", "." ]
def process(self, raw, identifiers, frame_meta): """ Args: raw: output of model. identifiers: list of input data identifiers. frame_meta: metadata for frame. Returns: list of HitRatioPrediction objects. """ raw_prediction = self._extract_predictions(raw, frame_meta) self.select_output_blob(raw_prediction) prediction = raw_prediction[self.output_blob] prediction = np.reshape(prediction, -1) result = [] for identifier, output in zip(identifiers, prediction): result.append(HitRatioPrediction(identifier, output)) return result
[ "def", "process", "(", "self", ",", "raw", ",", "identifiers", ",", "frame_meta", ")", ":", "raw_prediction", "=", "self", ".", "_extract_predictions", "(", "raw", ",", "frame_meta", ")", "self", ".", "select_output_blob", "(", "raw_prediction", ")", "predicti...
https://github.com/openvinotoolkit/open_model_zoo/blob/5a4232f6c35b4916eb6e8750141f4e45761237ef/tools/accuracy_checker/openvino/tools/accuracy_checker/adapters/hit_ratio.py#L31-L50
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/cbs/v20170312/models.py
python
Tag.__init__
(self)
:param Key: 标签健。 :type Key: str :param Value: 标签值。 :type Value: str
:param Key: 标签健。 :type Key: str :param Value: 标签值。 :type Value: str
[ ":", "param", "Key", ":", "标签健。", ":", "type", "Key", ":", "str", ":", "param", "Value", ":", "标签值。", ":", "type", "Value", ":", "str" ]
def __init__(self): """ :param Key: 标签健。 :type Key: str :param Value: 标签值。 :type Value: str """ self.Key = None self.Value = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Key", "=", "None", "self", ".", "Value", "=", "None" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/cbs/v20170312/models.py#L1265-L1273
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/admin/widgets.py
python
RelatedFieldWidgetWrapper.get_related_url
(self, info, action, *args)
return reverse("admin:%s_%s_%s" % (info + (action,)), current_app=self.admin_site.name, args=args)
[]
def get_related_url(self, info, action, *args): return reverse("admin:%s_%s_%s" % (info + (action,)), current_app=self.admin_site.name, args=args)
[ "def", "get_related_url", "(", "self", ",", "info", ",", "action", ",", "*", "args", ")", ":", "return", "reverse", "(", "\"admin:%s_%s_%s\"", "%", "(", "info", "+", "(", "action", ",", ")", ")", ",", "current_app", "=", "self", ".", "admin_site", ".",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/admin/widgets.py#L293-L295
rsmusllp/king-phisher
6acbbd856f849d407cc904c075441e0cf13c25cf
king_phisher/server/server_rpc.py
python
rpc_events_is_subscribed
(handler, event_id, event_type)
return event_socket.is_subscribed(event_id, event_type)
Check if the client is currently subscribed to the specified server event. :param str event_id: The identifier of the event to subscribe to. :param str event_type: A sub-type for the corresponding event. :return: Whether or not the client is subscribed to the event. :rtype: bool
Check if the client is currently subscribed to the specified server event.
[ "Check", "if", "the", "client", "is", "currently", "subscribed", "to", "the", "specified", "server", "event", "." ]
def rpc_events_is_subscribed(handler, event_id, event_type): """ Check if the client is currently subscribed to the specified server event. :param str event_id: The identifier of the event to subscribe to. :param str event_type: A sub-type for the corresponding event. :return: Whether or not the client is subscribed to the event. :rtype: bool """ if not isinstance(event_id, str): raise errors.KingPhisherAPIError('a valid event id must be specified') if not isinstance(event_type, str): raise errors.KingPhisherAPIError('a valid event type must be specified') event_socket = handler.rpc_session.event_socket if event_socket is None: raise errors.KingPhisherAPIError('the event socket is not open for this session') return event_socket.is_subscribed(event_id, event_type)
[ "def", "rpc_events_is_subscribed", "(", "handler", ",", "event_id", ",", "event_type", ")", ":", "if", "not", "isinstance", "(", "event_id", ",", "str", ")", ":", "raise", "errors", ".", "KingPhisherAPIError", "(", "'a valid event id must be specified'", ")", "if"...
https://github.com/rsmusllp/king-phisher/blob/6acbbd856f849d407cc904c075441e0cf13c25cf/king_phisher/server/server_rpc.py#L633-L649
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Demo/classes/Complex.py
python
Complex.__str__
(self)
[]
def __str__(self): if not self.im: return repr(self.re) else: return 'Complex(%r, %r)' % (self.re, self.im)
[ "def", "__str__", "(", "self", ")", ":", "if", "not", "self", ".", "im", ":", "return", "repr", "(", "self", ".", "re", ")", "else", ":", "return", "'Complex(%r, %r)'", "%", "(", "self", ".", "re", ",", "self", ".", "im", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Demo/classes/Complex.py#L130-L134
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/google-reauth-python-0.1.0/google_reauth/reauth.py
python
refresh_access_token
( http_request, client_id, client_secret, refresh_token, token_uri, rapt=None, scopes=None, headers=None)
return rapt, content, access_token, refresh_token, expires_in, id_token
Refresh the access_token using the refresh_token. Args: http_request: callable to run http requests. Accepts uri, method, body and headers. Returns a tuple: (response, content) client_id: client id to get access token for reauth scope. client_secret: client secret for the client_id refresh_token: refresh token to refresh access token token_uri: uri to refresh access token scopes: scopes required by the client application Returns: Tuple[str, str, str, Optional[str], Optional[str], Optional[str]]: The rapt token, the access token, new refresh token, expiration, token id and response content returned by the token endpoint. Raises: errors.ReauthError if reauth failed errors.HttpAccessTokenRefreshError it access token refresh failed
Refresh the access_token using the refresh_token.
[ "Refresh", "the", "access_token", "using", "the", "refresh_token", "." ]
def refresh_access_token( http_request, client_id, client_secret, refresh_token, token_uri, rapt=None, scopes=None, headers=None): """Refresh the access_token using the refresh_token. Args: http_request: callable to run http requests. Accepts uri, method, body and headers. Returns a tuple: (response, content) client_id: client id to get access token for reauth scope. client_secret: client secret for the client_id refresh_token: refresh token to refresh access token token_uri: uri to refresh access token scopes: scopes required by the client application Returns: Tuple[str, str, str, Optional[str], Optional[str], Optional[str]]: The rapt token, the access token, new refresh token, expiration, token id and response content returned by the token endpoint. Raises: errors.ReauthError if reauth failed errors.HttpAccessTokenRefreshError it access token refresh failed """ response, content = _reauth_client.refresh_grant( http_request=http_request, client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_uri=token_uri, rapt=rapt, headers=headers) if response.status != http_client.OK: # Check if we need a rapt token or if the rapt token is invalid. # Once we refresh the rapt token, retry the access token refresh. # If we did refresh the rapt token and still got an error, then the # refresh token is expired or revoked. if (_rapt_refresh_required(content)): rapt = get_rapt_token( http_request, client_id, client_secret, refresh_token, token_uri, scopes=scopes, ) # retry with refreshed rapt response, content = _reauth_client.refresh_grant( http_request=http_request, client_id=client_id, client_secret=client_secret, refresh_token=refresh_token, token_uri=token_uri, rapt=rapt, headers=headers) try: content = json.loads(content) except (TypeError, ValueError): raise errors.HttpAccessTokenRefreshError( 'Invalid response {0}'.format(_substr_for_error_message(content)), response.status) if response.status != http_client.OK: raise errors.HttpAccessTokenRefreshError( _get_refresh_error_message(content), response.status) access_token = content['access_token'] refresh_token = content.get('refresh_token', None) expires_in = content.get('expires_in', None) id_token = content.get('id_token', None) return rapt, content, access_token, refresh_token, expires_in, id_token
[ "def", "refresh_access_token", "(", "http_request", ",", "client_id", ",", "client_secret", ",", "refresh_token", ",", "token_uri", ",", "rapt", "=", "None", ",", "scopes", "=", "None", ",", "headers", "=", "None", ")", ":", "response", ",", "content", "=", ...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/google-reauth-python-0.1.0/google_reauth/reauth.py#L239-L311
ryu577/pyray
860b71463e2729a85b1319b5c3571c0b8f3ba50c
pyray/shapes/solid/cube.py
python
Vertice.plot_vid_ready
(self, r, draw, rgba, width=9)
Legacy method. Can be ignored.
Legacy method. Can be ignored.
[ "Legacy", "method", ".", "Can", "be", "ignored", "." ]
def plot_vid_ready(self, r, draw, rgba, width=9): """ Legacy method. Can be ignored. """ dim = r.shape[0] reflection = np.ones(dim) reflection[1] = -1 l = new_vector(r, (self.binary * reflection) * scale + shift[:dim]) draw.ellipse((l[0] - width, l[1] - width, l[0] + width, l[1] + width), fill=rgba, outline=rgba)
[ "def", "plot_vid_ready", "(", "self", ",", "r", ",", "draw", ",", "rgba", ",", "width", "=", "9", ")", ":", "dim", "=", "r", ".", "shape", "[", "0", "]", "reflection", "=", "np", ".", "ones", "(", "dim", ")", "reflection", "[", "1", "]", "=", ...
https://github.com/ryu577/pyray/blob/860b71463e2729a85b1319b5c3571c0b8f3ba50c/pyray/shapes/solid/cube.py#L78-L87
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/code.py
python
InteractiveConsole.interact
(self, banner=None)
Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!).
Closely emulate the interactive Python console.
[ "Closely", "emulate", "the", "interactive", "Python", "console", "." ]
def interact(self, banner=None): """Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter -- since it's so close!). """ try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) else: self.write("%s\n" % str(banner)) more = 0 while 1: try: if more: prompt = sys.ps2 else: prompt = sys.ps1 try: line = self.raw_input(prompt) # Can be None if sys.stdin was redefined encoding = getattr(sys.stdin, "encoding", None) if encoding and not isinstance(line, unicode): line = line.decode(encoding) except EOFError: self.write("\n") break else: more = self.push(line) except KeyboardInterrupt: self.write("\nKeyboardInterrupt\n") self.resetbuffer() more = 0
[ "def", "interact", "(", "self", ",", "banner", "=", "None", ")", ":", "try", ":", "sys", ".", "ps1", "except", "AttributeError", ":", "sys", ".", "ps1", "=", "\">>> \"", "try", ":", "sys", ".", "ps2", "except", "AttributeError", ":", "sys", ".", "ps2...
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/code.py#L200-L247
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/objspace/std/listobject.py
python
W_ListObject.init_from_list_w
(self, list_w)
Initializes listobject by iterating through the given list of wrapped items, unwrapping them if neccessary and creating a new erased object as storage
Initializes listobject by iterating through the given list of wrapped items, unwrapping them if neccessary and creating a new erased object as storage
[ "Initializes", "listobject", "by", "iterating", "through", "the", "given", "list", "of", "wrapped", "items", "unwrapping", "them", "if", "neccessary", "and", "creating", "a", "new", "erased", "object", "as", "storage" ]
def init_from_list_w(self, list_w): """Initializes listobject by iterating through the given list of wrapped items, unwrapping them if neccessary and creating a new erased object as storage""" self.strategy.init_from_list_w(self, list_w)
[ "def", "init_from_list_w", "(", "self", ",", "list_w", ")", ":", "self", ".", "strategy", ".", "init_from_list_w", "(", "self", ",", "list_w", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/objspace/std/listobject.py#L271-L275
google/yapf
b49a261870870e91fe693b1b871a4afbd7af7bd6
yapf/yapflib/format_decision_state.py
python
FormatDecisionState._GetNewlineColumn
(self)
return cont_aligned_indent
Return the new column on the newline.
Return the new column on the newline.
[ "Return", "the", "new", "column", "on", "the", "newline", "." ]
def _GetNewlineColumn(self): """Return the new column on the newline.""" current = self.next_token previous = current.previous_token top_of_stack = self.stack[-1] if isinstance(current.spaces_required_before, list): # Don't set the value here, as we need to look at the lines near # this one to determine the actual horizontal alignment value. return 0 elif current.spaces_required_before > 2 or self.line.disable: return current.spaces_required_before cont_aligned_indent = self._IndentWithContinuationAlignStyle( top_of_stack.indent) if current.OpensScope(): return cont_aligned_indent if self.paren_level else self.first_indent if current.ClosesScope(): if (previous.OpensScope() or (previous.is_comment and previous.previous_token is not None and previous.previous_token.OpensScope())): return max(0, top_of_stack.indent - style.Get('CONTINUATION_INDENT_WIDTH')) return top_of_stack.closing_scope_indent if (previous and previous.is_string and current.is_string and subtypes.DICTIONARY_VALUE in current.subtypes): return previous.column if style.Get('INDENT_DICTIONARY_VALUE'): if previous and (previous.value == ':' or previous.is_pseudo): if subtypes.DICTIONARY_VALUE in current.subtypes: return top_of_stack.indent if (not self.param_list_stack and _IsCompoundStatement(self.line.first) and (not (style.Get('DEDENT_CLOSING_BRACKETS') or style.Get('INDENT_CLOSING_BRACKETS')) or style.Get('SPLIT_BEFORE_FIRST_ARGUMENT'))): token_indent = ( len(self.line.first.whitespace_prefix.split('\n')[-1]) + style.Get('INDENT_WIDTH')) if token_indent == top_of_stack.indent: return token_indent + style.Get('CONTINUATION_INDENT_WIDTH') if (self.param_list_stack and not self.param_list_stack[-1].SplitBeforeClosingBracket( top_of_stack.indent) and top_of_stack.indent == ((self.line.depth + 1) * style.Get('INDENT_WIDTH'))): if (subtypes.PARAMETER_START in current.subtypes or (previous.is_comment and subtypes.PARAMETER_START in previous.subtypes)): return top_of_stack.indent + style.Get('CONTINUATION_INDENT_WIDTH') return cont_aligned_indent
[ "def", "_GetNewlineColumn", "(", "self", ")", ":", "current", "=", "self", ".", "next_token", "previous", "=", "current", ".", "previous_token", "top_of_stack", "=", "self", ".", "stack", "[", "-", "1", "]", "if", "isinstance", "(", "current", ".", "spaces...
https://github.com/google/yapf/blob/b49a261870870e91fe693b1b871a4afbd7af7bd6/yapf/yapflib/format_decision_state.py#L931-L986
CompVis/adaptive-style-transfer
51b4c90dbd998d9efd1dc821ad7a8df69bef61da
evaluation/feature_extractor/preprocessing/vgg_preprocessing.py
python
_crop
(image, offset_height, offset_width, crop_height, crop_width)
return tf.reshape(image, cropped_shape)
Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: an image of shape [height, width, channels]. offset_height: a scalar tensor indicating the height offset. offset_width: a scalar tensor indicating the width offset. crop_height: the height of the cropped image. crop_width: the width of the cropped image. Returns: the cropped (and resized) image. Raises: InvalidArgumentError: if the rank is not 3 or if the image dimensions are less than the crop size.
Crops the given image using the provided offsets and sizes.
[ "Crops", "the", "given", "image", "using", "the", "provided", "offsets", "and", "sizes", "." ]
def _crop(image, offset_height, offset_width, crop_height, crop_width): """Crops the given image using the provided offsets and sizes. Note that the method doesn't assume we know the input image size but it does assume we know the input image rank. Args: image: an image of shape [height, width, channels]. offset_height: a scalar tensor indicating the height offset. offset_width: a scalar tensor indicating the width offset. crop_height: the height of the cropped image. crop_width: the width of the cropped image. Returns: the cropped (and resized) image. Raises: InvalidArgumentError: if the rank is not 3 or if the image dimensions are less than the crop size. """ original_shape = tf.shape(image) rank_assertion = tf.Assert( tf.equal(tf.rank(image), 3), ['Rank of image must be equal to 3.']) cropped_shape = control_flow_ops.with_dependencies( [rank_assertion], tf.stack([crop_height, crop_width, original_shape[2]])) size_assertion = tf.Assert( tf.logical_and( tf.greater_equal(original_shape[0], crop_height), tf.greater_equal(original_shape[1], crop_width)), ['Crop size greater than the image size.']) offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0])) # Use tf.slice instead of crop_to_bounding box as it accepts tensors to # define the crop size. image = control_flow_ops.with_dependencies( [size_assertion], tf.slice(image, offsets, cropped_shape)) return tf.reshape(image, cropped_shape)
[ "def", "_crop", "(", "image", ",", "offset_height", ",", "offset_width", ",", "crop_height", ",", "crop_width", ")", ":", "original_shape", "=", "tf", ".", "shape", "(", "image", ")", "rank_assertion", "=", "tf", ".", "Assert", "(", "tf", ".", "equal", "...
https://github.com/CompVis/adaptive-style-transfer/blob/51b4c90dbd998d9efd1dc821ad7a8df69bef61da/evaluation/feature_extractor/preprocessing/vgg_preprocessing.py#L49-L91
nosmokingbandit/watcher
dadacd21a5790ee609058a98a17fcc8954d24439
lib/hachoir_core/timeout.py
python
signalHandler
(signum, frame)
Signal handler to catch timeout signal: raise Timeout exception.
Signal handler to catch timeout signal: raise Timeout exception.
[ "Signal", "handler", "to", "catch", "timeout", "signal", ":", "raise", "Timeout", "exception", "." ]
def signalHandler(signum, frame): """ Signal handler to catch timeout signal: raise Timeout exception. """ raise Timeout("Timeout exceed!")
[ "def", "signalHandler", "(", "signum", ",", "frame", ")", ":", "raise", "Timeout", "(", "\"Timeout exceed!\"", ")" ]
https://github.com/nosmokingbandit/watcher/blob/dadacd21a5790ee609058a98a17fcc8954d24439/lib/hachoir_core/timeout.py#L15-L19
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_node_selector.py
python
V1NodeSelector.node_selector_terms
(self, node_selector_terms)
Sets the node_selector_terms of this V1NodeSelector. Required. A list of node selector terms. The terms are ORed. :param node_selector_terms: The node_selector_terms of this V1NodeSelector. :type: list[V1NodeSelectorTerm]
Sets the node_selector_terms of this V1NodeSelector. Required. A list of node selector terms. The terms are ORed.
[ "Sets", "the", "node_selector_terms", "of", "this", "V1NodeSelector", ".", "Required", ".", "A", "list", "of", "node", "selector", "terms", ".", "The", "terms", "are", "ORed", "." ]
def node_selector_terms(self, node_selector_terms): """ Sets the node_selector_terms of this V1NodeSelector. Required. A list of node selector terms. The terms are ORed. :param node_selector_terms: The node_selector_terms of this V1NodeSelector. :type: list[V1NodeSelectorTerm] """ if node_selector_terms is None: raise ValueError("Invalid value for `node_selector_terms`, must not be `None`") self._node_selector_terms = node_selector_terms
[ "def", "node_selector_terms", "(", "self", ",", "node_selector_terms", ")", ":", "if", "node_selector_terms", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `node_selector_terms`, must not be `None`\"", ")", "self", ".", "_node_selector_terms", "=", "...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_node_selector.py#L55-L66
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/mailcap.py
python
getcaps
()
return caps
Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view".
Return a dictionary containing the mailcap database.
[ "Return", "a", "dictionary", "containing", "the", "mailcap", "database", "." ]
def getcaps(): """Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dictionary contains key-value pairs for that MIME type, where the viewing command is stored with the key "view". """ caps = {} lineno = 0 for mailcap in listmailcapfiles(): try: fp = open(mailcap, 'r') except OSError: continue with fp: morecaps, lineno = _readmailcapfile(fp, lineno) for key, value in morecaps.items(): if not key in caps: caps[key] = value else: caps[key] = caps[key] + value return caps
[ "def", "getcaps", "(", ")", ":", "caps", "=", "{", "}", "lineno", "=", "0", "for", "mailcap", "in", "listmailcapfiles", "(", ")", ":", "try", ":", "fp", "=", "open", "(", "mailcap", ",", "'r'", ")", "except", "OSError", ":", "continue", "with", "fp...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/mailcap.py#L19-L43
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/ni/daqmx/base.py
python
Task.unreserve
(self)
Release all reserved resources.
Release all reserved resources.
[ "Release", "all", "reserved", "resources", "." ]
def unreserve(self): """Release all reserved resources. """ self.alter_state('unreserve')
[ "def", "unreserve", "(", "self", ")", ":", "self", ".", "alter_state", "(", "'unreserve'", ")" ]
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/ni/daqmx/base.py#L545-L548
django-cms/django-cms
272d62ced15a86c9d34eb21700e6358bb08388ea
cms/utils/placeholder.py
python
get_toolbar_plugin_struct
(plugins, slot=None, page=None)
return sorted(main_list, key=operator.itemgetter("module"))
Return the list of plugins to render in the toolbar. The dictionary contains the label, the classname and the module for the plugin. Names and modules can be defined on a per-placeholder basis using 'plugin_modules' and 'plugin_labels' attributes in CMS_PLACEHOLDER_CONF :param plugins: list of plugins :param slot: placeholder slot name :param page: the page :return: list of dictionaries
Return the list of plugins to render in the toolbar. The dictionary contains the label, the classname and the module for the plugin. Names and modules can be defined on a per-placeholder basis using 'plugin_modules' and 'plugin_labels' attributes in CMS_PLACEHOLDER_CONF
[ "Return", "the", "list", "of", "plugins", "to", "render", "in", "the", "toolbar", ".", "The", "dictionary", "contains", "the", "label", "the", "classname", "and", "the", "module", "for", "the", "plugin", ".", "Names", "and", "modules", "can", "be", "define...
def get_toolbar_plugin_struct(plugins, slot=None, page=None): """ Return the list of plugins to render in the toolbar. The dictionary contains the label, the classname and the module for the plugin. Names and modules can be defined on a per-placeholder basis using 'plugin_modules' and 'plugin_labels' attributes in CMS_PLACEHOLDER_CONF :param plugins: list of plugins :param slot: placeholder slot name :param page: the page :return: list of dictionaries """ template = None if page: template = page.template modules = get_placeholder_conf("plugin_modules", slot, template, default={}) names = get_placeholder_conf("plugin_labels", slot, template, default={}) main_list = [] # plugin.value points to the class name of the plugin # It's added on registration. TIL. for plugin in plugins: main_list.append({'value': plugin.value, 'name': names.get(plugin.value, plugin.name), 'module': modules.get(plugin.value, plugin.module)}) return sorted(main_list, key=operator.itemgetter("module"))
[ "def", "get_toolbar_plugin_struct", "(", "plugins", ",", "slot", "=", "None", ",", "page", "=", "None", ")", ":", "template", "=", "None", "if", "page", ":", "template", "=", "page", ".", "template", "modules", "=", "get_placeholder_conf", "(", "\"plugin_mod...
https://github.com/django-cms/django-cms/blob/272d62ced15a86c9d34eb21700e6358bb08388ea/cms/utils/placeholder.py#L81-L110
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/wsgiref/handlers.py
python
BaseHandler.send_preamble
(self)
Transmit version/status/date/server, via self._write()
Transmit version/status/date/server, via self._write()
[ "Transmit", "version", "/", "status", "/", "date", "/", "server", "via", "self", ".", "_write", "()" ]
def send_preamble(self): """Transmit version/status/date/server, via self._write()""" if self.origin_server: if self.client_is_modern(): self._write('HTTP/%s %s\r\n' % (self.http_version, self.status)) if 'Date' not in self.headers: self._write('Date: %s\r\n' % format_date_time(time.time())) if self.server_software and 'Server' not in self.headers: self._write('Server: %s\r\n' % self.server_software) else: self._write('Status: %s\r\n' % self.status)
[ "def", "send_preamble", "(", "self", ")", ":", "if", "self", ".", "origin_server", ":", "if", "self", ".", "client_is_modern", "(", ")", ":", "self", ".", "_write", "(", "'HTTP/%s %s\\r\\n'", "%", "(", "self", ".", "http_version", ",", "self", ".", "stat...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/wsgiref/handlers.py#L143-L153
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/controls/flatnotebook.py
python
FNBRenderer.CalcTabHeight
(self, pageContainer)
return tabHeight
Calculates the height of the input tab. :param `pageContainer`: an instance of :class:`FlatNotebook`.
Calculates the height of the input tab.
[ "Calculates", "the", "height", "of", "the", "input", "tab", "." ]
def CalcTabHeight(self, pageContainer): """ Calculates the height of the input tab. :param `pageContainer`: an instance of :class:`FlatNotebook`. """ if self._tabHeight: return self._tabHeight pc = pageContainer dc = wx.MemoryDC() dc.SelectObject(wx.Bitmap(1,1)) normalFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont = normalFont boldFont.SetWeight(wx.FONTWEIGHT_BOLD) dc.SetFont(boldFont) height = dc.GetCharHeight() tabHeight = height + FNB_HEIGHT_SPACER # We use 8 pixels as padding if "__WXGTK__" in wx.PlatformInfo: # On GTK the tabs are should be larger tabHeight += 6 self._tabHeight = tabHeight return tabHeight
[ "def", "CalcTabHeight", "(", "self", ",", "pageContainer", ")", ":", "if", "self", ".", "_tabHeight", ":", "return", "self", ".", "_tabHeight", "pc", "=", "pageContainer", "dc", "=", "wx", ".", "MemoryDC", "(", ")", "dc", ".", "SelectObject", "(", "wx", ...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/flatnotebook.py#L2185-L2214
gammapy/gammapy
735b25cd5bbed35e2004d633621896dcd5295e8b
gammapy/data/hdu_index_table.py
python
HDUIndexTable.base_dir
(self)
return make_path(self.meta.get("BASE_DIR", ""))
Base directory.
Base directory.
[ "Base", "directory", "." ]
def base_dir(self): """Base directory.""" return make_path(self.meta.get("BASE_DIR", ""))
[ "def", "base_dir", "(", "self", ")", ":", "return", "make_path", "(", "self", ".", "meta", ".", "get", "(", "\"BASE_DIR\"", ",", "\"\"", ")", ")" ]
https://github.com/gammapy/gammapy/blob/735b25cd5bbed35e2004d633621896dcd5295e8b/gammapy/data/hdu_index_table.py#L57-L59
phantomcyber/playbooks
9e850ecc44cb98c5dde53784744213a1ed5799bd
endace_splunk_search_download_pcap.py
python
Get_PCAP_Status
(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs)
return
[]
def Get_PCAP_Status(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs): phantom.debug('Get_PCAP_Status() called') #phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED'))) # collect data for 'Get_PCAP_Status' call results_data_1 = phantom.collect2(container=container, datapath=['Query_EndaceProbe:action_result.summary.pcap_id', 'Query_EndaceProbe:action_result.parameter.context.artifact_id'], action_results=results) parameters = [] # build parameters list for 'Get_PCAP_Status' call for results_item_1 in results_data_1: if results_item_1[0]: parameters.append({ 'pcap_id': results_item_1[0], # context (artifact id) is added to associate results with the artifact 'context': {'artifact_id': results_item_1[1]}, }) phantom.act(action="get status", parameters=parameters, assets=['endace_probe'], callback=Extract_PCAP_Links, name="Get_PCAP_Status") return
[ "def", "Get_PCAP_Status", "(", "action", "=", "None", ",", "success", "=", "None", ",", "container", "=", "None", ",", "results", "=", "None", ",", "handle", "=", "None", ",", "filtered_artifacts", "=", "None", ",", "filtered_results", "=", "None", ",", ...
https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/endace_splunk_search_download_pcap.py#L153-L174
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/categories/complex_reflection_groups.py
python
ComplexReflectionGroups.additional_structure
(self)
return None
r""" Return ``None``. Indeed, all the structure complex reflection groups have in addition to groups (simple reflections, ...) is already defined in the super category. .. SEEALSO:: :meth:`Category.additional_structure` EXAMPLES:: sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups sage: ComplexReflectionGroups().additional_structure()
r""" Return ``None``.
[ "r", "Return", "None", "." ]
def additional_structure(self): r""" Return ``None``. Indeed, all the structure complex reflection groups have in addition to groups (simple reflections, ...) is already defined in the super category. .. SEEALSO:: :meth:`Category.additional_structure` EXAMPLES:: sage: from sage.categories.complex_reflection_groups import ComplexReflectionGroups sage: ComplexReflectionGroups().additional_structure() """ return None
[ "def", "additional_structure", "(", "self", ")", ":", "return", "None" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/categories/complex_reflection_groups.py#L94-L109
nodesign/weio
1d67d705a5c36a2e825ad13feab910b0aca9a2e8
openWrt/files/usr/lib/python2.7/site-packages/tornado/auth.py
python
TwitterMixin._on_twitter_request
(self, future, response)
[]
def _on_twitter_request(self, future, response): if response.error: future.set_exception(AuthError( "Error response %s fetching %s" % (response.error, response.request.url))) return future.set_result(escape.json_decode(response.body))
[ "def", "_on_twitter_request", "(", "self", ",", "future", ",", "response", ")", ":", "if", "response", ".", "error", ":", "future", ".", "set_exception", "(", "AuthError", "(", "\"Error response %s fetching %s\"", "%", "(", "response", ".", "error", ",", "resp...
https://github.com/nodesign/weio/blob/1d67d705a5c36a2e825ad13feab910b0aca9a2e8/openWrt/files/usr/lib/python2.7/site-packages/tornado/auth.py#L668-L674
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/contrib/auth/hashers.py
python
get_hashers_by_algorithm
()
return {hasher.algorithm: hasher for hasher in get_hashers()}
[]
def get_hashers_by_algorithm(): return {hasher.algorithm: hasher for hasher in get_hashers()}
[ "def", "get_hashers_by_algorithm", "(", ")", ":", "return", "{", "hasher", ".", "algorithm", ":", "hasher", "for", "hasher", "in", "get_hashers", "(", ")", "}" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/contrib/auth/hashers.py#L101-L102
facebookincubator/submitit
e37899bce0c7c58e3cc46ecb5b7fa8ce941fc3d7
submitit/core/core.py
python
Executor.map_array
(self, fn: tp.Callable[..., R], *iterable: tp.Iterable[tp.Any])
return self._internal_process_submissions(submissions)
A distributed equivalent of the map() built-in function Parameters ---------- fn: callable function to compute *iterable: Iterable lists of arguments that are passed as arguments to fn. Returns ------- List[Job] A list of Job instances. Example ------- a = [1, 2, 3] b = [10, 20, 30] executor.submit(add, a, b) # jobs will compute 1 + 10, 2 + 20, 3 + 30
A distributed equivalent of the map() built-in function
[ "A", "distributed", "equivalent", "of", "the", "map", "()", "built", "-", "in", "function" ]
def map_array(self, fn: tp.Callable[..., R], *iterable: tp.Iterable[tp.Any]) -> tp.List[Job[R]]: """A distributed equivalent of the map() built-in function Parameters ---------- fn: callable function to compute *iterable: Iterable lists of arguments that are passed as arguments to fn. Returns ------- List[Job] A list of Job instances. Example ------- a = [1, 2, 3] b = [10, 20, 30] executor.submit(add, a, b) # jobs will compute 1 + 10, 2 + 20, 3 + 30 """ submissions = [utils.DelayedSubmission(fn, *args) for args in zip(*iterable)] if len(submissions) == 0: warnings.warn("Received an empty job array") return [] return self._internal_process_submissions(submissions)
[ "def", "map_array", "(", "self", ",", "fn", ":", "tp", ".", "Callable", "[", "...", ",", "R", "]", ",", "*", "iterable", ":", "tp", ".", "Iterable", "[", "tp", ".", "Any", "]", ")", "->", "tp", ".", "List", "[", "Job", "[", "R", "]", "]", "...
https://github.com/facebookincubator/submitit/blob/e37899bce0c7c58e3cc46ecb5b7fa8ce941fc3d7/submitit/core/core.py#L675-L701
airbnb/knowledge-repo
72f3bbb86a1c2a4a8bea0bcad5305b41c662b3d9
knowledge_repo/app/models.py
python
Post.authors
(self, authors)
Sets the tags of the post to the tags given in comma delimited string form in tags_string
Sets the tags of the post to the tags given in comma delimited string form in tags_string
[ "Sets", "the", "tags", "of", "the", "post", "to", "the", "tags", "given", "in", "comma", "delimited", "string", "form", "in", "tags_string" ]
def authors(self, authors): """ Sets the tags of the post to the tags given in comma delimited string form in tags_string """ user_objs = [] for author in authors: if not isinstance(author, User): author = User(identifier=author.strip()) user_objs.append(author) self._authors = user_objs
[ "def", "authors", "(", "self", ",", "authors", ")", ":", "user_objs", "=", "[", "]", "for", "author", "in", "authors", ":", "if", "not", "isinstance", "(", "author", ",", "User", ")", ":", "author", "=", "User", "(", "identifier", "=", "author", ".",...
https://github.com/airbnb/knowledge-repo/blob/72f3bbb86a1c2a4a8bea0bcad5305b41c662b3d9/knowledge_repo/app/models.py#L391-L403
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/wrappers.py
python
BaseRequest.cookies
(self)
return parse_cookie(self.environ, self.charset, self.encoding_errors, cls=self.dict_storage_class)
Read only access to the retrieved cookie values as dictionary.
Read only access to the retrieved cookie values as dictionary.
[ "Read", "only", "access", "to", "the", "retrieved", "cookie", "values", "as", "dictionary", "." ]
def cookies(self): """Read only access to the retrieved cookie values as dictionary.""" return parse_cookie(self.environ, self.charset, self.encoding_errors, cls=self.dict_storage_class)
[ "def", "cookies", "(", "self", ")", ":", "return", "parse_cookie", "(", "self", ".", "environ", ",", "self", ".", "charset", ",", "self", ".", "encoding_errors", ",", "cls", "=", "self", ".", "dict_storage_class", ")" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/werkzeug/wrappers.py#L515-L519
bjmayor/hacker
e3ce2ad74839c2733b27dac6c0f495e0743e1866
venv/lib/python3.5/site-packages/pygeoip/__init__.py
python
GeoIP.country_code_by_addr
(self, addr)
Returns 2-letter country code (e.g. US) from IP address. :arg addr: IP address (e.g. 203.0.113.30)
Returns 2-letter country code (e.g. US) from IP address.
[ "Returns", "2", "-", "letter", "country", "code", "(", "e", ".", "g", ".", "US", ")", "from", "IP", "address", "." ]
def country_code_by_addr(self, addr): """ Returns 2-letter country code (e.g. US) from IP address. :arg addr: IP address (e.g. 203.0.113.30) """ VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6) if self._databaseType in VALID_EDITIONS: country_id = self.id_by_addr(addr) return const.COUNTRY_CODES[country_id] elif self._databaseType in const.REGION_CITY_EDITIONS: return self.region_by_addr(addr).get('country_code') raise GeoIPError('Invalid database type, expected Country, City or Region')
[ "def", "country_code_by_addr", "(", "self", ",", "addr", ")", ":", "VALID_EDITIONS", "=", "(", "const", ".", "COUNTRY_EDITION", ",", "const", ".", "COUNTRY_EDITION_V6", ")", "if", "self", ".", "_databaseType", "in", "VALID_EDITIONS", ":", "country_id", "=", "s...
https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/pygeoip/__init__.py#L430-L443
pm4py/pm4py-core
7807b09a088b02199cd0149d724d0e28793971bf
pm4py/algo/discovery/inductive/variants/im_f/algorithm.py
python
apply
(log, parameters)
return net, initial_marking, final_marking
Apply the IM_F algorithm to a log obtaining a Petri net along with an initial and final marking Parameters ----------- log Log parameters Parameters of the algorithm, including: Parameters.ACTIVITY_KEY -> attribute of the log to use as activity name (default concept:name) Returns ----------- net Petri net initial_marking Initial marking final_marking Final marking
Apply the IM_F algorithm to a log obtaining a Petri net along with an initial and final marking
[ "Apply", "the", "IM_F", "algorithm", "to", "a", "log", "obtaining", "a", "Petri", "net", "along", "with", "an", "initial", "and", "final", "marking" ]
def apply(log, parameters): """ Apply the IM_F algorithm to a log obtaining a Petri net along with an initial and final marking Parameters ----------- log Log parameters Parameters of the algorithm, including: Parameters.ACTIVITY_KEY -> attribute of the log to use as activity name (default concept:name) Returns ----------- net Petri net initial_marking Initial marking final_marking Final marking """ if pkgutil.find_loader("pandas"): import pandas as pd from pm4py.statistics.variants.pandas import get as variants_get if type(log) is pd.DataFrame: vars = variants_get.get_variants_count(log, parameters=parameters) return apply_variants(vars, parameters=parameters) log = converter.apply(log, parameters=parameters) net, initial_marking, final_marking = tree_to_petri.apply(apply_tree(log, parameters)) return net, initial_marking, final_marking
[ "def", "apply", "(", "log", ",", "parameters", ")", ":", "if", "pkgutil", ".", "find_loader", "(", "\"pandas\"", ")", ":", "import", "pandas", "as", "pd", "from", "pm4py", ".", "statistics", ".", "variants", ".", "pandas", "import", "get", "as", "variant...
https://github.com/pm4py/pm4py-core/blob/7807b09a088b02199cd0149d724d0e28793971bf/pm4py/algo/discovery/inductive/variants/im_f/algorithm.py#L57-L90
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/textbox2/fontmanager.py
python
FontManager.getFontFamilyStyles
(self)
return self.fontStyles
Returns a list where each element of the list is a itself a two element list of [fontName,[fontStyle_names_list]]
Returns a list where each element of the list is a itself a two element list of [fontName,[fontStyle_names_list]]
[ "Returns", "a", "list", "where", "each", "element", "of", "the", "list", "is", "a", "itself", "a", "two", "element", "list", "of", "[", "fontName", "[", "fontStyle_names_list", "]]" ]
def getFontFamilyStyles(self): """Returns a list where each element of the list is a itself a two element list of [fontName,[fontStyle_names_list]] """ return self.fontStyles
[ "def", "getFontFamilyStyles", "(", "self", ")", ":", "return", "self", ".", "fontStyles" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/textbox2/fontmanager.py#L698-L702
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/SophosXGFirewall/Integrations/SophosXGFirewall/SophosXGFirewall.py
python
test_module
(client)
Returning 'ok' indicates that the integration works like it is supposed to. Args: client: Sophos XG Firewall client Returns: 'ok' if test passed, anything else will fail the test.
Returning 'ok' indicates that the integration works like it is supposed to.
[ "Returning", "ok", "indicates", "that", "the", "integration", "works", "like", "it", "is", "supposed", "to", "." ]
def test_module(client): """ Returning 'ok' indicates that the integration works like it is supposed to. Args: client: Sophos XG Firewall client Returns: 'ok' if test passed, anything else will fail the test. """ try: result = client.validate() json_result = json.loads(xml2json(result.text)) status_message = retrieve_dict_item_recursively(json_result, 'status') message = '' if status_message and 'Successful' in status_message: # type: ignore message = 'ok' elif status_message and 'Authentication Failure' in status_message: # type: ignore message = 'Please check your credentials' status_code = dict_safe_get(json_result, ['Response', 'Status', '@code'], 0) if status_code and int(status_code) >= 500: status_message = retrieve_dict_item_recursively(json_result, '#text') if status_message and 'enable the API Configuration' in status_message: # type: ignore message = 'Please enable API configuration from the webconsole ' \ '(in Backup & firmware)' else: message = status_message return message except DemistoException as error: return error.message
[ "def", "test_module", "(", "client", ")", ":", "try", ":", "result", "=", "client", ".", "validate", "(", ")", "json_result", "=", "json", ".", "loads", "(", "xml2json", "(", "result", ".", "text", ")", ")", "status_message", "=", "retrieve_dict_item_recur...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/SophosXGFirewall/Integrations/SophosXGFirewall/SophosXGFirewall.py#L807-L840
mardix/assembly
4c993d19bc9d33c1641323e03231e9ecad711b38
assembly/response.py
python
json
(func)
Decorator to render as JSON :param func: :return:
Decorator to render as JSON :param func: :return:
[ "Decorator", "to", "render", "as", "JSON", ":", "param", "func", ":", ":", "return", ":" ]
def json(func): """ Decorator to render as JSON :param func: :return: """ if inspect.isclass(func): apply_function_to_members(func, json) return func else: @functools.wraps(func) def decorated_view(*args, **kwargs): data = func(*args, **kwargs) return _build_response(data, jsonify) return decorated_view
[ "def", "json", "(", "func", ")", ":", "if", "inspect", ".", "isclass", "(", "func", ")", ":", "apply_function_to_members", "(", "func", ",", "json", ")", "return", "func", "else", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated...
https://github.com/mardix/assembly/blob/4c993d19bc9d33c1641323e03231e9ecad711b38/assembly/response.py#L76-L90
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/core/grr_response_core/lib/rdfvalues/protodict.py
python
Dict.__iter__
(self)
[]
def __iter__(self): for x in self._values.values(): yield x.k.GetValue()
[ "def", "__iter__", "(", "self", ")", ":", "for", "x", "in", "self", ".", "_values", ".", "values", "(", ")", ":", "yield", "x", ".", "k", ".", "GetValue", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/core/grr_response_core/lib/rdfvalues/protodict.py#L299-L301
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/oscrypto/_linux_bsd/trust_list.py
python
system_path
()
return ca_path
Tries to find a CA certs bundle in common locations :raises: OSError - when no valid CA certs bundle was found on the filesystem :return: The full filesystem path to a CA certs bundle file
Tries to find a CA certs bundle in common locations
[ "Tries", "to", "find", "a", "CA", "certs", "bundle", "in", "common", "locations" ]
def system_path(): """ Tries to find a CA certs bundle in common locations :raises: OSError - when no valid CA certs bundle was found on the filesystem :return: The full filesystem path to a CA certs bundle file """ ca_path = None # Common CA cert paths paths = [ '/usr/lib/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/certs/ca-bundle.crt', '/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/ca-bundle.pem', '/usr/local/share/certs/ca-root-nss.crt', '/etc/ssl/cert.pem' ] # First try SSL_CERT_FILE if 'SSL_CERT_FILE' in os.environ: paths.insert(0, os.environ['SSL_CERT_FILE']) for path in paths: if os.path.exists(path) and os.path.getsize(path) > 0: ca_path = path break if not ca_path: raise OSError(pretty_message( ''' Unable to find a CA certs bundle in common locations - try setting the SSL_CERT_FILE environmental variable ''' )) return ca_path
[ "def", "system_path", "(", ")", ":", "ca_path", "=", "None", "# Common CA cert paths", "paths", "=", "[", "'/usr/lib/ssl/certs/ca-certificates.crt'", ",", "'/etc/ssl/certs/ca-certificates.crt'", ",", "'/etc/ssl/certs/ca-bundle.crt'", ",", "'/etc/pki/tls/certs/ca-bundle.crt'", "...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/oscrypto/_linux_bsd/trust_list.py#L16-L57
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/py/filling.py
python
FillingTree.push
(self, command, more)
Receiver for Interpreter.push signal.
Receiver for Interpreter.push signal.
[ "Receiver", "for", "Interpreter", ".", "push", "signal", "." ]
def push(self, command, more): """Receiver for Interpreter.push signal.""" if not self: dispatcher.disconnect(receiver=self.push, signal='Interpreter.push') return self.display()
[ "def", "push", "(", "self", ",", "command", ",", "more", ")", ":", "if", "not", "self", ":", "dispatcher", ".", "disconnect", "(", "receiver", "=", "self", ".", "push", ",", "signal", "=", "'Interpreter.push'", ")", "return", "self", ".", "display", "(...
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/py/filling.py#L67-L72
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/plugins/trustedcoin/qt.py
python
Plugin.waiting_dialog_for_billing_info
(self, window, *, on_finished=None)
return WaitingDialog(parent=window, message=_('Requesting account info from TrustedCoin server...'), task=task, on_success=on_finished, on_error=on_error)
[]
def waiting_dialog_for_billing_info(self, window, *, on_finished=None): def task(): return self.request_billing_info(window.wallet, suppress_connection_error=False) def on_error(exc_info): e = exc_info[1] window.show_error("{header}\n{exc}\n\n{tor}" .format(header=_('Error getting TrustedCoin account info.'), exc=repr(e), tor=_('If you keep experiencing network problems, try using a Tor proxy.'))) return WaitingDialog(parent=window, message=_('Requesting account info from TrustedCoin server...'), task=task, on_success=on_finished, on_error=on_error)
[ "def", "waiting_dialog_for_billing_info", "(", "self", ",", "window", ",", "*", ",", "on_finished", "=", "None", ")", ":", "def", "task", "(", ")", ":", "return", "self", ".", "request_billing_info", "(", "window", ".", "wallet", ",", "suppress_connection_erro...
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/plugins/trustedcoin/qt.py#L132-L145
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/wsgiref/handlers.py
python
BaseHandler.set_content_length
(self)
Compute Content-Length or switch to chunked encoding if possible
Compute Content-Length or switch to chunked encoding if possible
[ "Compute", "Content", "-", "Length", "or", "switch", "to", "chunked", "encoding", "if", "possible" ]
def set_content_length(self): """Compute Content-Length or switch to chunked encoding if possible""" try: blocks = len(self.result) except (TypeError,AttributeError,NotImplementedError): pass else: if blocks==1: self.headers['Content-Length'] = str(self.bytes_sent) return
[ "def", "set_content_length", "(", "self", ")", ":", "try", ":", "blocks", "=", "len", "(", "self", ".", "result", ")", "except", "(", "TypeError", ",", "AttributeError", ",", "NotImplementedError", ")", ":", "pass", "else", ":", "if", "blocks", "==", "1"...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/wsgiref/handlers.py#L191-L200
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
headphones/cache.py
python
getThumb
(ArtistID=None, AlbumID=None)
[]
def getThumb(ArtistID=None, AlbumID=None): c = Cache() artwork_path = c.get_thumb_from_cache(ArtistID, AlbumID) if not artwork_path: return None if artwork_path.startswith(('http://', 'https://')): return artwork_path else: thumbnail_file = os.path.basename(artwork_path) return "cache/artwork/" + thumbnail_file
[ "def", "getThumb", "(", "ArtistID", "=", "None", ",", "AlbumID", "=", "None", ")", ":", "c", "=", "Cache", "(", ")", "artwork_path", "=", "c", ".", "get_thumb_from_cache", "(", "ArtistID", ",", "AlbumID", ")", "if", "not", "artwork_path", ":", "return", ...
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/headphones/cache.py#L577-L588
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_obj.py
python
OpenShiftCLI.openshift_cmd
(self, cmd, oadm=False, output=False, output_type='json', input_data=None)
return rval
Base command for oc
Base command for oc
[ "Base", "command", "for", "oc" ]
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval
[ "def", "openshift_cmd", "(", "self", ",", "cmd", ",", "oadm", "=", "False", ",", "output", "=", "False", ",", "output_type", "=", "'json'", ",", "input_data", "=", "None", ")", ":", "cmds", "=", "[", "self", ".", "oc_binary", "]", "if", "oadm", ":", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_openshift/library/oc_obj.py#L1139-L1183
girder/girder
0766ba8e7f9b25ce81e7c0d19bd343479bceea20
girder/models/folder.py
python
Folder.clean
(self, folder, progress=None, **kwargs)
Delete all contents underneath a folder recursively, but leave the folder itself. :param folder: The folder document to delete. :type folder: dict :param progress: A progress context to record progress on. :type progress: girder.utility.progress.ProgressContext or None.
Delete all contents underneath a folder recursively, but leave the folder itself.
[ "Delete", "all", "contents", "underneath", "a", "folder", "recursively", "but", "leave", "the", "folder", "itself", "." ]
def clean(self, folder, progress=None, **kwargs): """ Delete all contents underneath a folder recursively, but leave the folder itself. :param folder: The folder document to delete. :type folder: dict :param progress: A progress context to record progress on. :type progress: girder.utility.progress.ProgressContext or None. """ from .item import Item setResponseTimeLimit() # Delete all child items itemModel = Item() items = itemModel.find({ 'folderId': folder['_id'] }) for item in items: setResponseTimeLimit() itemModel.remove(item, progress=progress, **kwargs) if progress: progress.update(increment=1, message='Deleted item %s' % item['name']) # subsequent operations take a long time, so free the cursor's resources items.close() # Delete all child folders folders = self.find({ 'parentId': folder['_id'], 'parentCollection': 'folder' }) for subfolder in folders: self.remove(subfolder, progress=progress, **kwargs) folders.close()
[ "def", "clean", "(", "self", ",", "folder", ",", "progress", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "item", "import", "Item", "setResponseTimeLimit", "(", ")", "# Delete all child items", "itemModel", "=", "Item", "(", ")", "items", ...
https://github.com/girder/girder/blob/0766ba8e7f9b25ce81e7c0d19bd343479bceea20/girder/models/folder.py#L327-L360
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/mailbox.py
python
_ProxyFile.__init__
(self, f, pos=None)
Initialize a _ProxyFile.
Initialize a _ProxyFile.
[ "Initialize", "a", "_ProxyFile", "." ]
def __init__(self, f, pos=None): """Initialize a _ProxyFile.""" self._file = f if pos is None: self._pos = f.tell() else: self._pos = pos
[ "def", "__init__", "(", "self", ",", "f", ",", "pos", "=", "None", ")", ":", "self", ".", "_file", "=", "f", "if", "pos", "is", "None", ":", "self", ".", "_pos", "=", "f", ".", "tell", "(", ")", "else", ":", "self", ".", "_pos", "=", "pos" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/mailbox.py#L1923-L1929
lmb-freiburg/deeptam
e0b7df542fa36d4c1527d6e064f0c859557df5ea
mapping/python/deeptam_mapper/mapper.py
python
Mapper.feed_frame
(self, image, pose, keyframe_flag)
feed frame image: np.array rgb normalized in range[-0.5, 0.5], in NCHW format pose: Pose keyframe_flag: bool set self._keyframe if True, else add to self._frames
feed frame image: np.array rgb normalized in range[-0.5, 0.5], in NCHW format pose: Pose keyframe_flag: bool set self._keyframe if True, else add to self._frames
[ "feed", "frame", "image", ":", "np", ".", "array", "rgb", "normalized", "in", "range", "[", "-", "0", ".", "5", "0", ".", "5", "]", "in", "NCHW", "format", "pose", ":", "Pose", "keyframe_flag", ":", "bool", "set", "self", ".", "_keyframe", "if", "T...
def feed_frame(self, image, pose, keyframe_flag): """feed frame image: np.array rgb normalized in range[-0.5, 0.5], in NCHW format pose: Pose keyframe_flag: bool set self._keyframe if True, else add to self._frames """ if keyframe_flag: self._set_keyframe(image=image, pose=pose) else: self._add_curframe(image=image, pose=pose)
[ "def", "feed_frame", "(", "self", ",", "image", ",", "pose", ",", "keyframe_flag", ")", ":", "if", "keyframe_flag", ":", "self", ".", "_set_keyframe", "(", "image", "=", "image", ",", "pose", "=", "pose", ")", "else", ":", "self", ".", "_add_curframe", ...
https://github.com/lmb-freiburg/deeptam/blob/e0b7df542fa36d4c1527d6e064f0c859557df5ea/mapping/python/deeptam_mapper/mapper.py#L278-L292
FSecureLABS/Jandroid
e31d0dab58a2bfd6ed8e0a387172b8bd7c893436
libs/platform-tools/platform-tools_windows/systrace/catapult/common/py_vulcanize/third_party/rjsmin/bench/jsmin_2_0_9.py
python
jsmin
(js)
return outs.getvalue()
returns a minified version of the javascript string
returns a minified version of the javascript string
[ "returns", "a", "minified", "version", "of", "the", "javascript", "string" ]
def jsmin(js): """ returns a minified version of the javascript string """ if not is_3: if cStringIO and not isinstance(js, unicode): # strings can use cStringIO for a 3x performance # improvement, but unicode (in python2) cannot klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass = io.StringIO ins = klass(js) outs = klass() JavascriptMinify(ins, outs).minify() return outs.getvalue()
[ "def", "jsmin", "(", "js", ")", ":", "if", "not", "is_3", ":", "if", "cStringIO", "and", "not", "isinstance", "(", "js", ",", "unicode", ")", ":", "# strings can use cStringIO for a 3x performance", "# improvement, but unicode (in python2) cannot", "klass", "=", "cS...
https://github.com/FSecureLABS/Jandroid/blob/e31d0dab58a2bfd6ed8e0a387172b8bd7c893436/libs/platform-tools/platform-tools_windows/systrace/catapult/common/py_vulcanize/third_party/rjsmin/bench/jsmin_2_0_9.py#L43-L59
sphinx-gallery/sphinx-gallery
a68a48686138741ac38dcc15930293caeebcf484
sphinx_gallery/gen_gallery.py
python
collect_gallery_files
(examples_dirs, gallery_conf)
return files
Collect python files from the gallery example directories.
Collect python files from the gallery example directories.
[ "Collect", "python", "files", "from", "the", "gallery", "example", "directories", "." ]
def collect_gallery_files(examples_dirs, gallery_conf): """Collect python files from the gallery example directories.""" files = [] for example_dir in examples_dirs: for root, dirnames, filenames in os.walk(example_dir): for filename in filenames: if filename.endswith('.py'): if re.search(gallery_conf['ignore_pattern'], filename) is None: files.append(os.path.join(root, filename)) return files
[ "def", "collect_gallery_files", "(", "examples_dirs", ",", "gallery_conf", ")", ":", "files", "=", "[", "]", "for", "example_dir", "in", "examples_dirs", ":", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "example_dir", ")",...
https://github.com/sphinx-gallery/sphinx-gallery/blob/a68a48686138741ac38dcc15930293caeebcf484/sphinx_gallery/gen_gallery.py#L735-L745
CenterForOpenScience/osf.io
cc02691be017e61e2cd64f19b848b2f4c18dcc84
api/base/authentication/drf.py
python
OSFSessionAuthentication.enforce_csrf
(self, request)
Same implementation as django-rest-framework's SessionAuthentication. Enforce CSRF validation for session based authentication.
Same implementation as django-rest-framework's SessionAuthentication. Enforce CSRF validation for session based authentication.
[ "Same", "implementation", "as", "django", "-", "rest", "-", "framework", "s", "SessionAuthentication", ".", "Enforce", "CSRF", "validation", "for", "session", "based", "authentication", "." ]
def enforce_csrf(self, request): """ Same implementation as django-rest-framework's SessionAuthentication. Enforce CSRF validation for session based authentication. """ reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) if not request.COOKIES.get(api_settings.CSRF_COOKIE_NAME): # Make sure the CSRF cookie is set for next time get_token(request)
[ "def", "enforce_csrf", "(", "self", ",", "request", ")", ":", "reason", "=", "CSRFCheck", "(", ")", ".", "process_view", "(", "request", ",", "None", ",", "(", ")", ",", "{", "}", ")", "if", "reason", ":", "# CSRF failed, bail with explicit error message", ...
https://github.com/CenterForOpenScience/osf.io/blob/cc02691be017e61e2cd64f19b848b2f4c18dcc84/api/base/authentication/drf.py#L139-L151
pre-commit/pre-commit-hooks
0d261aaf84419c0c8fe70ff4a23f6a99655868de
pre_commit_hooks/end_of_file_fixer.py
python
main
(argv: Optional[Sequence[str]] = None)
return retv
[]
def main(argv: Optional[Sequence[str]] = None) -> int: parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to fix') args = parser.parse_args(argv) retv = 0 for filename in args.filenames: # Read as binary so we can read byte-by-byte with open(filename, 'rb+') as file_obj: ret_for_file = fix_file(file_obj) if ret_for_file: print(f'Fixing {filename}') retv |= ret_for_file return retv
[ "def", "main", "(", "argv", ":", "Optional", "[", "Sequence", "[", "str", "]", "]", "=", "None", ")", "->", "int", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'filenames'", ",", "nargs", "=", ...
https://github.com/pre-commit/pre-commit-hooks/blob/0d261aaf84419c0c8fe70ff4a23f6a99655868de/pre_commit_hooks/end_of_file_fixer.py#L51-L66
pydicom/pynetdicom
f57d8214c82b63c8e76638af43ce331f584a80fa
pynetdicom/apps/common.py
python
ElementPath.is_sequence
(self)
return False
Return True if the current component is a sequence.
Return True if the current component is a sequence.
[ "Return", "True", "if", "the", "current", "component", "is", "a", "sequence", "." ]
def is_sequence(self): """Return True if the current component is a sequence.""" start = self.components[0].find("[") end = self.components[0].find("]") if start >= 0 or end >= 0: is_valid = True if not (start >= 0 and end >= 0): is_valid = False if start > end: is_valid = False if start + 1 == end: is_valid = False if is_valid: try: item_nr = int(self.components[0][start + 1 : end]) if item_nr < 0: is_valid = False except Exception: is_valid = False if not is_valid: raise ValueError( f"Element path contains an invalid component: " f"'{self.components[0]}'" ) self._item_nr = item_nr return True return False
[ "def", "is_sequence", "(", "self", ")", ":", "start", "=", "self", ".", "components", "[", "0", "]", ".", "find", "(", "\"[\"", ")", "end", "=", "self", ".", "components", "[", "0", "]", ".", "find", "(", "\"]\"", ")", "if", "start", ">=", "0", ...
https://github.com/pydicom/pynetdicom/blob/f57d8214c82b63c8e76638af43ce331f584a80fa/pynetdicom/apps/common.py#L201-L231
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/pathlib.py
python
PurePath.__new__
(cls, *args)
return cls._from_parts(args)
Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.
Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.
[ "Construct", "a", "PurePath", "from", "one", "or", "several", "strings", "and", "or", "existing", "PurePath", "objects", ".", "The", "strings", "and", "path", "objects", "are", "combined", "so", "as", "to", "yield", "a", "canonicalized", "path", "which", "is...
def __new__(cls, *args): """Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object. """ if cls is PurePath: cls = PureWindowsPath if os.name == 'nt' else PurePosixPath return cls._from_parts(args)
[ "def", "__new__", "(", "cls", ",", "*", "args", ")", ":", "if", "cls", "is", "PurePath", ":", "cls", "=", "PureWindowsPath", "if", "os", ".", "name", "==", "'nt'", "else", "PurePosixPath", "return", "cls", ".", "_from_parts", "(", "args", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/pathlib.py#L609-L617
google/tf-quant-finance
8fd723689ebf27ff4bb2bd2acb5f6091c5e07309
tf_quant_finance/examples/demos/option_pricing_basic/data_generator/data_generation.py
python
generate_portfolio
(num_instruments: int, market_data: datatypes.OptionMarketData, start_instrument_id: int = 0)
return datatypes.OptionBatch( strike=strikes, call_put_flag=call_put_flags, expiry_date=expiry_date, trade_id=trade_ids, underlier_id=underlier_ids)
Generates a random portfolio.
Generates a random portfolio.
[ "Generates", "a", "random", "portfolio", "." ]
def generate_portfolio(num_instruments: int, market_data: datatypes.OptionMarketData, start_instrument_id: int = 0) -> datatypes.OptionBatch: """Generates a random portfolio.""" underlier_ids = np.random.choice( market_data.underlier_id, size=num_instruments) # Choose strikes to be within +/- 40% of the spot. call_put_flags = np.random.rand(num_instruments) > 0.5 # datetime.date.toordinal uses the same ordinals as tff's dates module. today = datetime.date.today().toordinal() expiry_date = today + np.random.randint( 1, high=365 * 10, size=num_instruments) strike_multipliers = np.random.rand(num_instruments) * 0.8 + 0.6 underlier_spots = market_data.spot[underlier_ids] strikes = underlier_spots * strike_multipliers trade_ids = np.arange(num_instruments) + start_instrument_id return datatypes.OptionBatch( strike=strikes, call_put_flag=call_put_flags, expiry_date=expiry_date, trade_id=trade_ids, underlier_id=underlier_ids)
[ "def", "generate_portfolio", "(", "num_instruments", ":", "int", ",", "market_data", ":", "datatypes", ".", "OptionMarketData", ",", "start_instrument_id", ":", "int", "=", "0", ")", "->", "datatypes", ".", "OptionBatch", ":", "underlier_ids", "=", "np", ".", ...
https://github.com/google/tf-quant-finance/blob/8fd723689ebf27ff4bb2bd2acb5f6091c5e07309/tf_quant_finance/examples/demos/option_pricing_basic/data_generator/data_generation.py#L86-L107
CGATOxford/cgat
326aad4694bdfae8ddc194171bb5d73911243947
CGAT/scripts/revigo.py
python
PorterStemmer.doublec
(self, j)
return self.cons(j)
doublec(j) is TRUE <=> j,(j-1) contain a double consonant.
doublec(j) is TRUE <=> j,(j-1) contain a double consonant.
[ "doublec", "(", "j", ")", "is", "TRUE", "<", "=", ">", "j", "(", "j", "-", "1", ")", "contain", "a", "double", "consonant", "." ]
def doublec(self, j): """doublec(j) is TRUE <=> j,(j-1) contain a double consonant.""" if j < (self.k0 + 1): return 0 if (self.b[j] != self.b[j - 1]): return 0 return self.cons(j)
[ "def", "doublec", "(", "self", ",", "j", ")", ":", "if", "j", "<", "(", "self", ".", "k0", "+", "1", ")", ":", "return", "0", "if", "(", "self", ".", "b", "[", "j", "]", "!=", "self", ".", "b", "[", "j", "-", "1", "]", ")", ":", "return...
https://github.com/CGATOxford/cgat/blob/326aad4694bdfae8ddc194171bb5d73911243947/CGAT/scripts/revigo.py#L244-L250
lykoss/lykos
7859cb530b66e782b3cc32f0d7d60d1c55d4fef5
src/roles/hag.py
python
hex_cmd
(wrapper: MessageDispatcher, message: str)
Hex someone, preventing them from acting the next day and night.
Hex someone, preventing them from acting the next day and night.
[ "Hex", "someone", "preventing", "them", "from", "acting", "the", "next", "day", "and", "night", "." ]
def hex_cmd(wrapper: MessageDispatcher, message: str): """Hex someone, preventing them from acting the next day and night.""" if wrapper.source in HEXED: wrapper.pm(messages["already_hexed"]) return var = wrapper.game_state target = get_target(wrapper, re.split(" +", message)[0]) if not target: return if LASTHEXED.get(wrapper.source) is target: wrapper.pm(messages["no_multiple_hex"].format(target)) return target = try_misdirection(var, wrapper.source, target) if try_exchange(var, wrapper.source, target): return if is_known_wolf_ally(var, wrapper.source, target): wrapper.pm(messages["no_hex_wolf"]) return HEXED[wrapper.source] = target wrapper.pm(messages["hex_success"].format(target)) send_wolfchat_message(var, wrapper.source, messages["hex_success_wolfchat"].format(wrapper.source, target), {"hag"}, role="hag", command="hex")
[ "def", "hex_cmd", "(", "wrapper", ":", "MessageDispatcher", ",", "message", ":", "str", ")", ":", "if", "wrapper", ".", "source", "in", "HEXED", ":", "wrapper", ".", "pm", "(", "messages", "[", "\"already_hexed\"", "]", ")", "return", "var", "=", "wrappe...
https://github.com/lykoss/lykos/blob/7859cb530b66e782b3cc32f0d7d60d1c55d4fef5/src/roles/hag.py#L25-L53
cms-dev/cms
0401c5336b34b1731736045da4877fef11889274
cmscontrib/loaders/polygon.py
python
PolygonContestLoader.detect
(path)
return os.path.exists(os.path.join(path, "contest.xml")) and \ os.path.exists(os.path.join(path, "problems"))
See docstring in class Loader.
See docstring in class Loader.
[ "See", "docstring", "in", "class", "Loader", "." ]
def detect(path): """See docstring in class Loader. """ return os.path.exists(os.path.join(path, "contest.xml")) and \ os.path.exists(os.path.join(path, "problems"))
[ "def", "detect", "(", "path", ")", ":", "return", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "\"contest.xml\"", ")", ")", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", ...
https://github.com/cms-dev/cms/blob/0401c5336b34b1731736045da4877fef11889274/cmscontrib/loaders/polygon.py#L408-L413
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/agol/services.py
python
FeatureService.url
(self)
return self._url
returns the url for the feature service
returns the url for the feature service
[ "returns", "the", "url", "for", "the", "feature", "service" ]
def url(self): """ returns the url for the feature service""" return self._url
[ "def", "url", "(", "self", ")", ":", "return", "self", ".", "_url" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/agol/services.py#L357-L359
joblib/loky
00fbd9d5e8ebc8f9427096a0f64d7d7ad51b9f9b
loky/backend/context.py
python
_count_physical_cores
()
return cpu_count_physical, exception
Return a tuple (number of physical cores, exception) If the number of physical cores is found, exception is set to None. If it has not been found, return ("not found", exception). The number of physical cores is cached to avoid repeating subprocess calls.
Return a tuple (number of physical cores, exception)
[ "Return", "a", "tuple", "(", "number", "of", "physical", "cores", "exception", ")" ]
def _count_physical_cores(): """Return a tuple (number of physical cores, exception) If the number of physical cores is found, exception is set to None. If it has not been found, return ("not found", exception). The number of physical cores is cached to avoid repeating subprocess calls. """ exception = None # First check if the value is cached global physical_cores_cache if physical_cores_cache is not None: return physical_cores_cache, exception # Not cached yet, find it try: if sys.platform == "linux": cpu_info = subprocess.run( "lscpu --parse=core".split(" "), capture_output=True) cpu_info = cpu_info.stdout.decode("utf-8").splitlines() cpu_info = {line for line in cpu_info if not line.startswith("#")} cpu_count_physical = len(cpu_info) elif sys.platform == "win32": cpu_info = subprocess.run( "wmic CPU Get NumberOfCores /Format:csv".split(" "), capture_output=True) cpu_info = cpu_info.stdout.decode('utf-8').splitlines() cpu_info = [l.split(",")[1] for l in cpu_info if (l and l != "Node,NumberOfCores")] cpu_count_physical = sum(map(int, cpu_info)) elif sys.platform == "darwin": cpu_info = subprocess.run( "sysctl -n hw.physicalcpu".split(" "), capture_output=True) cpu_info = cpu_info.stdout.decode('utf-8') cpu_count_physical = int(cpu_info) else: raise NotImplementedError( "unsupported platform: {}".format(sys.platform)) # if cpu_count_physical < 1, we did not find a valid value if cpu_count_physical < 1: raise ValueError( "found {} physical cores < 1".format(cpu_count_physical)) except Exception as e: exception = e cpu_count_physical = "not found" # Put the result in cache physical_cores_cache = cpu_count_physical return cpu_count_physical, exception
[ "def", "_count_physical_cores", "(", ")", ":", "exception", "=", "None", "# First check if the value is cached", "global", "physical_cores_cache", "if", "physical_cores_cache", "is", "not", "None", ":", "return", "physical_cores_cache", ",", "exception", "# Not cached yet, ...
https://github.com/joblib/loky/blob/00fbd9d5e8ebc8f9427096a0f64d7d7ad51b9f9b/loky/backend/context.py#L203-L255
kubeflow/pipelines
bea751c9259ff0ae85290f873170aae89284ba8e
samples/contrib/pytorch-samples/cifar10/cifar10_handler.py
python
CIFAR10Classification.initialize
(self, ctx)
In this initialize function, the CIFAR10 trained model is loaded and the Integrated Gradients,occlusion and layer_gradcam Algorithm for Captum Explanations is initialized here. Args: ctx (context): It is a JSON Object containing information pertaining to the model artifacts parameters.
In this initialize function, the CIFAR10 trained model is loaded and the Integrated Gradients,occlusion and layer_gradcam Algorithm for Captum Explanations is initialized here. Args: ctx (context): It is a JSON Object containing information pertaining to the model artifacts parameters.
[ "In", "this", "initialize", "function", "the", "CIFAR10", "trained", "model", "is", "loaded", "and", "the", "Integrated", "Gradients", "occlusion", "and", "layer_gradcam", "Algorithm", "for", "Captum", "Explanations", "is", "initialized", "here", ".", "Args", ":",...
def initialize(self, ctx): # pylint: disable=arguments-differ """In this initialize function, the CIFAR10 trained model is loaded and the Integrated Gradients,occlusion and layer_gradcam Algorithm for Captum Explanations is initialized here. Args: ctx (context): It is a JSON Object containing information pertaining to the model artifacts parameters. """ self.manifest = ctx.manifest properties = ctx.system_properties model_dir = properties.get("model_dir") print("Model dir is {}".format(model_dir)) serialized_file = self.manifest["model"]["serializedFile"] model_pt_path = os.path.join(model_dir, serialized_file) self.device = torch.device( "cuda:" + str(properties.get("gpu_id")) if torch.cuda.is_available( ) else "cpu" ) self.model = CIFAR10CLASSIFIER() self.model.load_state_dict(torch.load(model_pt_path)) self.model.to(self.device) self.model.eval() self.model.zero_grad() logger.info("CIFAR10 model from path %s loaded successfully", model_dir) # Read the mapping file, index to object name mapping_file_path = os.path.join(model_dir, "class_mapping.json") if os.path.isfile(mapping_file_path): print("Mapping file present") with open(mapping_file_path) as pointer: self.mapping = json.load(pointer) else: print("Mapping file missing") logger.warning("Missing the class_mapping.json file.") self.ig = IntegratedGradients(self.model) self.layer_gradcam = LayerGradCam( self.model, self.model.model_conv.layer4[2].conv3 ) self.occlusion = Occlusion(self.model) self.initialized = True self.image_processing = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ])
[ "def", "initialize", "(", "self", ",", "ctx", ")", ":", "# pylint: disable=arguments-differ", "self", ".", "manifest", "=", "ctx", ".", "manifest", "properties", "=", "ctx", ".", "system_properties", "model_dir", "=", "properties", ".", "get", "(", "\"model_dir\...
https://github.com/kubeflow/pipelines/blob/bea751c9259ff0ae85290f873170aae89284ba8e/samples/contrib/pytorch-samples/cifar10/cifar10_handler.py#L46-L95
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/cherrypy/lib/sessions.py
python
RamSession.__len__
(self)
return len(self.cache)
Return the number of active sessions.
Return the number of active sessions.
[ "Return", "the", "number", "of", "active", "sessions", "." ]
def __len__(self): """Return the number of active sessions.""" return len(self.cache)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "cache", ")" ]
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/cherrypy/lib/sessions.py#L377-L379
spyder-ide/spyder
55da47c032dfcf519600f67f8b30eab467f965e7
spyder/utils/qstringhelpers.py
python
qstring_length
(text)
return length
Tries to compute what the length of an utf16-encoded QString would be.
Tries to compute what the length of an utf16-encoded QString would be.
[ "Tries", "to", "compute", "what", "the", "length", "of", "an", "utf16", "-", "encoded", "QString", "would", "be", "." ]
def qstring_length(text): """ Tries to compute what the length of an utf16-encoded QString would be. """ if PY2: # I don't know what this is encoded in, so there is nothing I can do. return len(text) utf16_text = text.encode('utf16') length = len(utf16_text) // 2 # Remove Byte order mark. # TODO: All unicode Non-characters should be removed if utf16_text[:2] in [b'\xff\xfe', b'\xff\xff', b'\xfe\xff']: length -= 1 return length
[ "def", "qstring_length", "(", "text", ")", ":", "if", "PY2", ":", "# I don't know what this is encoded in, so there is nothing I can do.", "return", "len", "(", "text", ")", "utf16_text", "=", "text", ".", "encode", "(", "'utf16'", ")", "length", "=", "len", "(", ...
https://github.com/spyder-ide/spyder/blob/55da47c032dfcf519600f67f8b30eab467f965e7/spyder/utils/qstringhelpers.py#L12-L25
pannous/tensorflow-ocr
52579ae55549429a1631193b2e6218087d0c60de
extensions.py
python
exists
(x)
return os.path.isfile(x)
[]
def exists(x): return os.path.isfile(x)
[ "def", "exists", "(", "x", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "x", ")" ]
https://github.com/pannous/tensorflow-ocr/blob/52579ae55549429a1631193b2e6218087d0c60de/extensions.py#L231-L232
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/pkg_resources/_vendor/packaging/specifiers.py
python
BaseSpecifier.__str__
(self)
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
Returns the str representation of this Specifier like object. This should be representative of the Specifier itself.
[ "Returns", "the", "str", "representation", "of", "this", "Specifier", "like", "object", ".", "This", "should", "be", "representative", "of", "the", "Specifier", "itself", "." ]
def __str__(self): """ Returns the str representation of this Specifier like object. This should be representative of the Specifier itself. """
[ "def", "__str__", "(", "self", ")", ":" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/pkg_resources/_vendor/packaging/specifiers.py#L24-L28
tenable/poc
361b6b191eda0bdc4f7338a58c2e2fe79bb8afca
Zoom/zoomster.py
python
Zoomster.spoof_chat
(self, src_attendee_id, msg)
Spoof chat message to come from src attendee :param src_attendee_id: attendee ID to spoof chat :param msg: Chat message
Spoof chat message to come from src attendee
[ "Spoof", "chat", "message", "to", "come", "from", "src", "attendee" ]
def spoof_chat(self, src_attendee_id, msg): ''' Spoof chat message to come from src attendee :param src_attendee_id: attendee ID to spoof chat :param msg: Chat message ''' msg_payload = base64.b64encode(Msg_Templates.CHAT_MSG.format(chr(len(msg)), msg)) packet = Msg_Templates.SSB_SDK_CHAT_HEADER.format( self.P2P_HEADER, chr(src_attendee_id), chr(src_attendee_id), '\x04', # value may be other multiple of 4 depending on call (0x8, 0x10, ...) chr(len(msg_payload)), chr(len(msg_payload)), msg_payload ) self.send(packet)
[ "def", "spoof_chat", "(", "self", ",", "src_attendee_id", ",", "msg", ")", ":", "msg_payload", "=", "base64", ".", "b64encode", "(", "Msg_Templates", ".", "CHAT_MSG", ".", "format", "(", "chr", "(", "len", "(", "msg", ")", ")", ",", "msg", ")", ")", ...
https://github.com/tenable/poc/blob/361b6b191eda0bdc4f7338a58c2e2fe79bb8afca/Zoom/zoomster.py#L29-L47
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/click/utils.py
python
LazyFile.close
(self)
Closes the underlying file, no matter what.
Closes the underlying file, no matter what.
[ "Closes", "the", "underlying", "file", "no", "matter", "what", "." ]
def close(self): """Closes the underlying file, no matter what.""" if self._f is not None: self._f.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_f", "is", "not", "None", ":", "self", ".", "_f", ".", "close", "(", ")" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/click/utils.py#L136-L139
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/currencylayer/sensor.py
python
CurrencylayerSensor.extra_state_attributes
(self)
return {ATTR_ATTRIBUTION: ATTRIBUTION}
Return the state attributes of the sensor.
Return the state attributes of the sensor.
[ "Return", "the", "state", "attributes", "of", "the", "sensor", "." ]
def extra_state_attributes(self): """Return the state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
[ "def", "extra_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/currencylayer/sensor.py#L98-L100
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_yaml_editor/build/src/yedit.py
python
Yedit.append
(self, path, value)
return (True, self.yaml_dict)
append value to a list
append value to a list
[ "append", "value", "to", "a", "list" ]
def append(self, path, value): '''append value to a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry is None: self.put(path, []) entry = Yedit.get_entry(self.yaml_dict, path, self.separator) if not isinstance(entry, list): return (False, self.yaml_dict) # pylint: disable=no-member,maybe-no-member entry.append(value) return (True, self.yaml_dict)
[ "def", "append", "(", "self", ",", "path", ",", "value", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separator", ")", "except", "KeyError", "as", "_", ":", "entry", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_yaml_editor/build/src/yedit.py#L323-L338
shapely/shapely
9258e6dd4dcca61699d69c2a5853a486b132ed86
shapely/geometry/linestring.py
python
LineString.xy
(self)
return self.coords.xy
Separate arrays of X and Y coordinate values Example: >>> x, y = LineString(((0, 0), (1, 1))).xy >>> list(x) [0.0, 1.0] >>> list(y) [0.0, 1.0]
Separate arrays of X and Y coordinate values
[ "Separate", "arrays", "of", "X", "and", "Y", "coordinate", "values" ]
def xy(self): """Separate arrays of X and Y coordinate values Example: >>> x, y = LineString(((0, 0), (1, 1))).xy >>> list(x) [0.0, 1.0] >>> list(y) [0.0, 1.0] """ return self.coords.xy
[ "def", "xy", "(", "self", ")", ":", "return", "self", ".", "coords", ".", "xy" ]
https://github.com/shapely/shapely/blob/9258e6dd4dcca61699d69c2a5853a486b132ed86/shapely/geometry/linestring.py#L100-L111
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/torchie/parallel/distributed.py
python
MegDistributedDataParallel.scatter
(self, inputs, kwargs, device_ids)
return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
[]
def scatter(self, inputs, kwargs, device_ids): return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
[ "def", "scatter", "(", "self", ",", "inputs", ",", "kwargs", ",", "device_ids", ")", ":", "return", "scatter_kwargs", "(", "inputs", ",", "kwargs", ",", "device_ids", ",", "dim", "=", "self", ".", "dim", ")" ]
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/torchie/parallel/distributed.py#L40-L41
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/encodings/utf_16.py
python
IncrementalEncoder.getstate
(self)
return (2 if self.encoder is None else 0)
[]
def getstate(self): # state info we return to the caller: # 0: stream is in natural order for this platform # 2: endianness hasn't been determined yet # (we're never writing in unnatural order) return (2 if self.encoder is None else 0)
[ "def", "getstate", "(", "self", ")", ":", "# state info we return to the caller:", "# 0: stream is in natural order for this platform", "# 2: endianness hasn't been determined yet", "# (we're never writing in unnatural order)", "return", "(", "2", "if", "self", ".", "encoder", "is"...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/encodings/utf_16.py#L37-L42
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/base/templatetags/base_filters.py
python
format_string
(value, arg)
return arg % value
[]
def format_string(value, arg): return arg % value
[ "def", "format_string", "(", "value", ",", "arg", ")", ":", "return", "arg", "%", "value" ]
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/base/templatetags/base_filters.py#L435-L436
pandas-dev/pandas
5ba7d714014ae8feaccc0dd4a98890828cf2832d
pandas/io/formats/style.py
python
Styler.set_table_attributes
(self, attributes: str)
return self
Set the table attributes added to the ``<table>`` HTML element. These are items in addition to automatic (by default) ``id`` attribute. Parameters ---------- attributes : str Returns ------- self : Styler See Also -------- Styler.set_table_styles: Set the table styles included within the ``<style>`` HTML element. Styler.set_td_classes: Set the DataFrame of strings added to the ``class`` attribute of ``<td>`` HTML elements. Examples -------- >>> df = pd.DataFrame(np.random.randn(10, 4)) >>> df.style.set_table_attributes('class="pure-table"') # doctest: +SKIP # ... <table class="pure-table"> ...
Set the table attributes added to the ``<table>`` HTML element.
[ "Set", "the", "table", "attributes", "added", "to", "the", "<table", ">", "HTML", "element", "." ]
def set_table_attributes(self, attributes: str) -> Styler: """ Set the table attributes added to the ``<table>`` HTML element. These are items in addition to automatic (by default) ``id`` attribute. Parameters ---------- attributes : str Returns ------- self : Styler See Also -------- Styler.set_table_styles: Set the table styles included within the ``<style>`` HTML element. Styler.set_td_classes: Set the DataFrame of strings added to the ``class`` attribute of ``<td>`` HTML elements. Examples -------- >>> df = pd.DataFrame(np.random.randn(10, 4)) >>> df.style.set_table_attributes('class="pure-table"') # doctest: +SKIP # ... <table class="pure-table"> ... """ self.table_attributes = attributes return self
[ "def", "set_table_attributes", "(", "self", ",", "attributes", ":", "str", ")", "->", "Styler", ":", "self", ".", "table_attributes", "=", "attributes", "return", "self" ]
https://github.com/pandas-dev/pandas/blob/5ba7d714014ae8feaccc0dd4a98890828cf2832d/pandas/io/formats/style.py#L1942-L1970
baidu/DuReader
43577e29435f5abcb7b02ce6a0019b3f42b1221d
MRQA2019-D-NET/server/bert_server/task_reader/tokenization.py
python
BasicTokenizer._run_split_on_punc
(self, text)
return ["".join(x) for x in output]
Splits punctuation on a piece of text.
Splits punctuation on a piece of text.
[ "Splits", "punctuation", "on", "a", "piece", "of", "text", "." ]
def _run_split_on_punc(self, text): """Splits punctuation on a piece of text.""" chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): char = chars[i] if _is_punctuation(char): output.append([char]) start_new_word = True else: if start_new_word: output.append([]) start_new_word = False output[-1].append(char) i += 1 return ["".join(x) for x in output]
[ "def", "_run_split_on_punc", "(", "self", ",", "text", ")", ":", "chars", "=", "list", "(", "text", ")", "i", "=", "0", "start_new_word", "=", "True", "output", "=", "[", "]", "while", "i", "<", "len", "(", "chars", ")", ":", "char", "=", "chars", ...
https://github.com/baidu/DuReader/blob/43577e29435f5abcb7b02ce6a0019b3f42b1221d/MRQA2019-D-NET/server/bert_server/task_reader/tokenization.py#L206-L224
playframework/play1
0ecac3bc2421ae2dbec27a368bf671eda1c9cba5
python/Lib/logging/config.py
python
fileConfig
(fname, defaults=None, disable_existing_loggers=True)
Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration).
Read the logging configuration from a ConfigParser-format file.
[ "Read", "the", "logging", "configuration", "from", "a", "ConfigParser", "-", "format", "file", "." ]
def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import ConfigParser cp = ConfigParser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.readfp(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock()
[ "def", "fileConfig", "(", "fname", ",", "defaults", "=", "None", ",", "disable_existing_loggers", "=", "True", ")", ":", "import", "ConfigParser", "cp", "=", "ConfigParser", ".", "ConfigParser", "(", "defaults", ")", "if", "hasattr", "(", "fname", ",", "'rea...
https://github.com/playframework/play1/blob/0ecac3bc2421ae2dbec27a368bf671eda1c9cba5/python/Lib/logging/config.py#L60-L88
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/decimal.py
python
Decimal.__rsub__
(self, other, context=None)
return other.__sub__(self, context=context)
Return other - self
Return other - self
[ "Return", "other", "-", "self" ]
def __rsub__(self, other, context=None): """Return other - self""" other = _convert_other(other) if other is NotImplemented: return other return other.__sub__(self, context=context)
[ "def", "__rsub__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__sub__", "(", "self", ",", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/decimal.py#L1252-L1258
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/news/nntp.py
python
NNTPClient.setStreamFailed
(self, error)
Override for notification when setStream() action fails
Override for notification when setStream() action fails
[ "Override", "for", "notification", "when", "setStream", "()", "action", "fails" ]
def setStreamFailed(self, error): "Override for notification when setStream() action fails"
[ "def", "setStreamFailed", "(", "self", ",", "error", ")", ":" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/news/nntp.py#L194-L195
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/policy_v1_api.py
python
PolicyV1Api.replace_namespaced_pod_disruption_budget_with_http_info
(self, name, namespace, body, **kwargs)
return self.api_client.call_api( '/apis/policy/v1/namespaces/{namespace}/poddisruptionbudgets/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1PodDisruptionBudget', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
replace_namespaced_pod_disruption_budget # noqa: E501 replace the specified PodDisruptionBudget # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_pod_disruption_budget_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the PodDisruptionBudget (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1PodDisruptionBudget body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1PodDisruptionBudget, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread.
replace_namespaced_pod_disruption_budget # noqa: E501
[ "replace_namespaced_pod_disruption_budget", "#", "noqa", ":", "E501" ]
def replace_namespaced_pod_disruption_budget_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_pod_disruption_budget # noqa: E501 replace the specified PodDisruptionBudget # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_pod_disruption_budget_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the PodDisruptionBudget (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1PodDisruptionBudget body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1PodDisruptionBudget, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_pod_disruption_budget" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_disruption_budget`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_disruption_budget`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_disruption_budget`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/policy/v1/namespaces/{namespace}/poddisruptionbudgets/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1PodDisruptionBudget', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
[ "def", "replace_namespaced_pod_disruption_budget_with_http_info", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "local_var_params", "=", "locals", "(", ")", "all_params", "=", "[", "'name'", ",", "'na...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/policy_v1_api.py#L1531-L1646
ckan/ckan
b3b01218ad88ed3fb914b51018abe8b07b07bff3
ckan/model/package_relationship.py
python
PackageRelationship.as_dict
(self, package=None, ref_package_by='id')
return {'subject':subject_ref, 'type':relationship_type, 'object':object_ref, 'comment':self.comment}
Returns full relationship info as a dict from the point of view of the given package if specified. e.g. {'subject':u'annakarenina', 'type':u'depends_on', 'object':u'warandpeace', 'comment':u'Since 1843'}
Returns full relationship info as a dict from the point of view of the given package if specified. e.g. {'subject':u'annakarenina', 'type':u'depends_on', 'object':u'warandpeace', 'comment':u'Since 1843'}
[ "Returns", "full", "relationship", "info", "as", "a", "dict", "from", "the", "point", "of", "view", "of", "the", "given", "package", "if", "specified", ".", "e", ".", "g", ".", "{", "subject", ":", "u", "annakarenina", "type", ":", "u", "depends_on", "...
def as_dict(self, package=None, ref_package_by='id'): """Returns full relationship info as a dict from the point of view of the given package if specified. e.g. {'subject':u'annakarenina', 'type':u'depends_on', 'object':u'warandpeace', 'comment':u'Since 1843'}""" subject_pkg = self.subject object_pkg = self.object relationship_type = self.type if package and package == object_pkg: subject_pkg = self.object object_pkg = self.subject relationship_type = self.forward_to_reverse_type(self.type) subject_ref = getattr(subject_pkg, ref_package_by) object_ref = getattr(object_pkg, ref_package_by) return {'subject':subject_ref, 'type':relationship_type, 'object':object_ref, 'comment':self.comment}
[ "def", "as_dict", "(", "self", ",", "package", "=", "None", ",", "ref_package_by", "=", "'id'", ")", ":", "subject_pkg", "=", "self", ".", "subject", "object_pkg", "=", "self", ".", "object", "relationship_type", "=", "self", ".", "type", "if", "package", ...
https://github.com/ckan/ckan/blob/b3b01218ad88ed3fb914b51018abe8b07b07bff3/ckan/model/package_relationship.py#L67-L86
pywinauto/SWAPY
8ac9b53ac2b3fa670dbbb125395fcfbbc476ae5a
proxy.py
python
Pwa_listbox._get_additional_children
(self)
return additional_children
Add ListBox items as children
Add ListBox items as children
[ "Add", "ListBox", "items", "as", "children" ]
def _get_additional_children(self): """ Add ListBox items as children """ additional_children = [] for i, text in enumerate(self.pwa_obj.ItemTexts()): if not text: text = "option #%s" % i additional_children.append((text, virtual_listbox_item(self, i))) else: additional_children.append((text, virtual_listbox_item(self, text))) return additional_children
[ "def", "_get_additional_children", "(", "self", ")", ":", "additional_children", "=", "[", "]", "for", "i", ",", "text", "in", "enumerate", "(", "self", ".", "pwa_obj", ".", "ItemTexts", "(", ")", ")", ":", "if", "not", "text", ":", "text", "=", "\"opt...
https://github.com/pywinauto/SWAPY/blob/8ac9b53ac2b3fa670dbbb125395fcfbbc476ae5a/proxy.py#L1003-L1018
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/hqcase/management/commands/ptop_preindex.py
python
Command.handle
(self, **options)
[]
def handle(self, **options): runs = [] all_es_indices = list(get_all_expected_es_indices()) es = get_es_new() if options['reset']: indices_needing_reindex = all_es_indices else: indices_needing_reindex = [info for info in all_es_indices if not es.indices.exists(info.index)] if not indices_needing_reindex: print('Nothing needs to be reindexed') return print("Reindexing:\n\t", end=' ') print('\n\t'.join(map(str, indices_needing_reindex))) preindex_message = """ Heads up! %s is going to start preindexing the following indices:\n %s This may take a while, so don't deploy until all these have reported finishing. """ % ( settings.EMAIL_SUBJECT_PREFIX, '\n\t'.join(map(str, indices_needing_reindex)) ) mail_admins("Pillow preindexing starting", preindex_message) start = datetime.utcnow() for index_info in indices_needing_reindex: # loop through pillows once before running greenlets # to fail hard on misconfigured pillows reindex_command = get_reindex_commands(index_info.hq_index_name) if not reindex_command: raise Exception( "Error, pillow [%s] is not configured " "with its own management command reindex command " "- it needs one" % index_info.hq_index_name ) for index_info in indices_needing_reindex: print(index_info.hq_index_name) g = gevent.spawn(do_reindex, index_info.hq_index_name, options['reset']) runs.append(g) if len(indices_needing_reindex) > 0: gevent.joinall(runs) try: for job in runs: job.get() except Exception: mail_admins("Pillow preindexing failed", get_traceback_string()) raise else: mail_admins( "Pillow preindexing completed", "Reindexing %s took %s seconds" % ( ', '.join(map(str, indices_needing_reindex)), (datetime.utcnow() - start).seconds ) ) print("All pillowtop reindexing jobs completed")
[ "def", "handle", "(", "self", ",", "*", "*", "options", ")", ":", "runs", "=", "[", "]", "all_es_indices", "=", "list", "(", "get_all_expected_es_indices", "(", ")", ")", "es", "=", "get_es_new", "(", ")", "if", "options", "[", "'reset'", "]", ":", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/hqcase/management/commands/ptop_preindex.py#L90-L153
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/webreport/webcal.py
python
WebCalReport.styled_note
(self, styledtext, format_type)
return htmllist
styledtext : assumed a StyledText object to write format_type : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation
styledtext : assumed a StyledText object to write format_type : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation
[ "styledtext", ":", "assumed", "a", "StyledText", "object", "to", "write", "format_type", ":", "=", "0", ":", "Flowed", "=", "1", ":", "Preformatted", "style_name", ":", "name", "of", "the", "style", "to", "use", "for", "default", "presentation" ]
def styled_note(self, styledtext, format_type): """ styledtext : assumed a StyledText object to write format_type : = 0 : Flowed, = 1 : Preformatted style_name : name of the style to use for default presentation """ text = str(styledtext) if not text: return '' s_tags = styledtext.get_tags() #FIXME: following split should be regex to match \n\s*\n instead? markuptext = self._backend.add_markup_from_styled(text, s_tags, split='\n\n') htmllist = Html("div", id="grampsstylednote") if format_type == 1: #preformatted, retain whitespace. #so use \n\n for paragraph detection #FIXME: following split should be regex to match \n\s*\n instead? htmllist += Html('pre', indent=None, inline=True) for line in markuptext.split('\n\n'): htmllist += Html("p") for realline in line.split('\n'): htmllist += realline htmllist += Html('br') elif format_type == 0: #flowed #FIXME: following split should be regex to match \n\s*\n instead? for line in markuptext.split('\n\n'): htmllist += Html("p") htmllist += line return htmllist
[ "def", "styled_note", "(", "self", ",", "styledtext", ",", "format_type", ")", ":", "text", "=", "str", "(", "styledtext", ")", "if", "not", "text", ":", "return", "''", "s_tags", "=", "styledtext", ".", "get_tags", "(", ")", "#FIXME: following split should ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/webreport/webcal.py#L217-L251
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/xmlrpc/client.py
python
ServerProxy.__init__
(self, uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, context=None)
[]
def __init__(self, uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, context=None): # establish a "logical" server connection # get the url type, uri = urllib.parse.splittype(uri) if type not in ("http", "https"): raise OSError("unsupported XML-RPC protocol") self.__host, self.__handler = urllib.parse.splithost(uri) if not self.__handler: self.__handler = "/RPC2" if transport is None: if type == "https": handler = SafeTransport extra_kwargs = {"context": context} else: handler = Transport extra_kwargs = {} transport = handler(use_datetime=use_datetime, use_builtin_types=use_builtin_types, **extra_kwargs) self.__transport = transport self.__encoding = encoding or 'utf-8' self.__verbose = verbose self.__allow_none = allow_none
[ "def", "__init__", "(", "self", ",", "uri", ",", "transport", "=", "None", ",", "encoding", "=", "None", ",", "verbose", "=", "False", ",", "allow_none", "=", "False", ",", "use_datetime", "=", "False", ",", "use_builtin_types", "=", "False", ",", "*", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/xmlrpc/client.py#L1403-L1430
skorokithakis/python-yeelight
e0805c29c44b56be6918e6fbb19114979b7f105b
yeelight/main.py
python
Bulb.set_power_mode
(self, mode)
return self.turn_on(power_mode=mode)
Set the light power mode. If the light is off it will be turned on. :param yeelight.enums.PowerMode mode: The mode to swith to.
Set the light power mode.
[ "Set", "the", "light", "power", "mode", "." ]
def set_power_mode(self, mode): """ Set the light power mode. If the light is off it will be turned on. :param yeelight.enums.PowerMode mode: The mode to swith to. """ return self.turn_on(power_mode=mode)
[ "def", "set_power_mode", "(", "self", ",", "mode", ")", ":", "return", "self", ".", "turn_on", "(", "power_mode", "=", "mode", ")" ]
https://github.com/skorokithakis/python-yeelight/blob/e0805c29c44b56be6918e6fbb19114979b7f105b/yeelight/main.py#L646-L654
django-oscar/django-oscar
ffcc530844d40283b6b1552778a140536b904f5f
src/oscar/core/context_processors.py
python
strip_language_code
(request)
return path
When using Django's i18n_patterns, we need a language-neutral variant of the current URL to be able to use set_language to change languages. This naive approach strips the language code from the beginning of the URL and will likely fail if using translated URLs.
When using Django's i18n_patterns, we need a language-neutral variant of the current URL to be able to use set_language to change languages. This naive approach strips the language code from the beginning of the URL and will likely fail if using translated URLs.
[ "When", "using", "Django", "s", "i18n_patterns", "we", "need", "a", "language", "-", "neutral", "variant", "of", "the", "current", "URL", "to", "be", "able", "to", "use", "set_language", "to", "change", "languages", ".", "This", "naive", "approach", "strips"...
def strip_language_code(request): """ When using Django's i18n_patterns, we need a language-neutral variant of the current URL to be able to use set_language to change languages. This naive approach strips the language code from the beginning of the URL and will likely fail if using translated URLs. """ path = request.path if settings.USE_I18N and hasattr(request, 'LANGUAGE_CODE'): return re.sub('^/%s/' % request.LANGUAGE_CODE, '/', path) return path
[ "def", "strip_language_code", "(", "request", ")", ":", "path", "=", "request", ".", "path", "if", "settings", ".", "USE_I18N", "and", "hasattr", "(", "request", ",", "'LANGUAGE_CODE'", ")", ":", "return", "re", ".", "sub", "(", "'^/%s/'", "%", "request", ...
https://github.com/django-oscar/django-oscar/blob/ffcc530844d40283b6b1552778a140536b904f5f/src/oscar/core/context_processors.py#L6-L16
yanshao9798/tagger
b902b4cf886e6cf1ddf72dff5c2d72776a7b6999
layers.py
python
HiddenLayer.__call__
(self, input_t)
return self.output
:param input_t: :return:
:param input_t: :return:
[ ":", "param", "input_t", ":", ":", "return", ":" ]
def __call__(self, input_t): """ :param input_t: :return: """ input_shape = input_t.get_shape().as_list() input_t = tf.reshape(input_t, [-1, input_shape[-1]]) linear = tf.matmul(input_t, self.weights) self.linear = tf.reshape(linear, [-1] + input_shape[1:-1] + [self.output_dim]) if self.is_bias: self.linear += self.bias if self.activation is None: self.output = self.linear else: self.output = self.activation(self.linear) return self.output
[ "def", "__call__", "(", "self", ",", "input_t", ")", ":", "input_shape", "=", "input_t", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "input_t", "=", "tf", ".", "reshape", "(", "input_t", ",", "[", "-", "1", ",", "input_shape", "[", "-", "...
https://github.com/yanshao9798/tagger/blob/b902b4cf886e6cf1ddf72dff5c2d72776a7b6999/layers.py#L49-L64
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppDB/appscale/datastore/fdb/fdb_datastore.py
python
FDBDatastore._auto_id
(entity)
return auto_id
Should perform auto identity allocation for entity.
Should perform auto identity allocation for entity.
[ "Should", "perform", "auto", "identity", "allocation", "for", "entity", "." ]
def _auto_id(entity): """ Should perform auto identity allocation for entity. """ last_element = entity.key().path().element(-1) auto_id = False if not last_element.has_name(): auto_id = not (last_element.has_id() and last_element.id() != 0) return auto_id
[ "def", "_auto_id", "(", "entity", ")", ":", "last_element", "=", "entity", ".", "key", "(", ")", ".", "path", "(", ")", ".", "element", "(", "-", "1", ")", "auto_id", "=", "False", "if", "not", "last_element", ".", "has_name", "(", ")", ":", "auto_...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppDB/appscale/datastore/fdb/fdb_datastore.py#L651-L657
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/lib/ImportOTP/eTokenDat.py
python
parse_datetime
(d_string)
return startdate
parse an date string and try to convert it to an datetime object :param d_string: date string :return: datetime object
parse an date string and try to convert it to an datetime object
[ "parse", "an", "date", "string", "and", "try", "to", "convert", "it", "to", "an", "datetime", "object" ]
def parse_datetime(d_string): """ parse an date string and try to convert it to an datetime object :param d_string: date string :return: datetime object """ startdate = None fmts = [ "%d.%m.%Y+%H:%M", "%d.%m.%Y %H:%M", "%d.%m.%Y %H:%M:%S", "%d.%m.%Y", "%Y-%m-%d+%H:%M", "%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d", ] if d_string is not None and len(d_string) > 0: for fmt in fmts: try: startdate = datetime.datetime.strptime(d_string, fmt) break except ValueError: startdate = None return startdate
[ "def", "parse_datetime", "(", "d_string", ")", ":", "startdate", "=", "None", "fmts", "=", "[", "\"%d.%m.%Y+%H:%M\"", ",", "\"%d.%m.%Y %H:%M\"", ",", "\"%d.%m.%Y %H:%M:%S\"", ",", "\"%d.%m.%Y\"", ",", "\"%Y-%m-%d+%H:%M\"", ",", "\"%Y-%m-%d %H:%M\"", ",", "\"%Y-%m-%d %...
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/lib/ImportOTP/eTokenDat.py#L44-L72
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/OpenSSL/crypto.py
python
PKCS7.get_type_name
(self)
return _ffi.string(string_type)
Returns the type name of the PKCS7 structure :return: A string with the typename
Returns the type name of the PKCS7 structure
[ "Returns", "the", "type", "name", "of", "the", "PKCS7", "structure" ]
def get_type_name(self): """ Returns the type name of the PKCS7 structure :return: A string with the typename """ nid = _lib.OBJ_obj2nid(self._pkcs7.type) string_type = _lib.OBJ_nid2sn(nid) return _ffi.string(string_type)
[ "def", "get_type_name", "(", "self", ")", ":", "nid", "=", "_lib", ".", "OBJ_obj2nid", "(", "self", ".", "_pkcs7", ".", "type", ")", "string_type", "=", "_lib", ".", "OBJ_nid2sn", "(", "nid", ")", "return", "_ffi", ".", "string", "(", "string_type", ")...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/OpenSSL/crypto.py#L2331-L2339
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/xml/dom/pulldom.py
python
PullDOM.endPrefixMapping
(self, prefix)
[]
def endPrefixMapping(self, prefix): self._current_context = self._ns_contexts.pop()
[ "def", "endPrefixMapping", "(", "self", ",", "prefix", ")", ":", "self", ".", "_current_context", "=", "self", ".", "_ns_contexts", ".", "pop", "(", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/xml/dom/pulldom.py#L48-L49
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/ttLib/woff2.py
python
WOFF2Writer.__setitem__
(self, tag, data)
Associate new entry named 'tag' with raw table data.
Associate new entry named 'tag' with raw table data.
[ "Associate", "new", "entry", "named", "tag", "with", "raw", "table", "data", "." ]
def __setitem__(self, tag, data): """Associate new entry named 'tag' with raw table data.""" if tag in self.tables: raise TTLibError("cannot rewrite '%s' table" % tag) if tag == 'DSIG': # always drop DSIG table, since the encoding process can invalidate it self.numTables -= 1 return entry = self.DirectoryEntry() entry.tag = Tag(tag) entry.flags = getKnownTagIndex(entry.tag) # WOFF2 table data are written to disk only on close(), after all tags # have been specified entry.data = data self.tables[tag] = entry
[ "def", "__setitem__", "(", "self", ",", "tag", ",", "data", ")", ":", "if", "tag", "in", "self", ".", "tables", ":", "raise", "TTLibError", "(", "\"cannot rewrite '%s' table\"", "%", "tag", ")", "if", "tag", "==", "'DSIG'", ":", "# always drop DSIG table, si...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ttLib/woff2.py#L195-L211
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/iptables.py
python
set_policy
(name, table="filter", family="ipv4", **kwargs)
.. versionadded:: 2014.1.0 Sets the default policy for iptables firewall tables table The table that owns the chain that should be modified family Networking family, either ipv4 or ipv6 policy The requested table policy
.. versionadded:: 2014.1.0
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0" ]
def set_policy(name, table="filter", family="ipv4", **kwargs): """ .. versionadded:: 2014.1.0 Sets the default policy for iptables firewall tables table The table that owns the chain that should be modified family Networking family, either ipv4 or ipv6 policy The requested table policy """ ret = {"name": name, "changes": {}, "result": None, "comment": ""} for ignore in _STATE_INTERNAL_KEYWORDS: if ignore in kwargs: del kwargs[ignore] if ( __salt__["iptables.get_policy"](table, kwargs["chain"], family) == kwargs["policy"] ): ret["result"] = True ret[ "comment" ] = "iptables default policy for chain {} on table {} for {} already set to {}".format( kwargs["chain"], table, family, kwargs["policy"] ) return ret if __opts__["test"]: ret["comment"] = ( "iptables default policy for chain {} on table {} for {} needs to be set" " to {}".format(kwargs["chain"], table, family, kwargs["policy"]) ) return ret if not __salt__["iptables.set_policy"]( table, kwargs["chain"], kwargs["policy"], family ): ret["changes"] = {"locale": name} ret["result"] = True ret["comment"] = "Set default policy for {} to {} family {}".format( kwargs["chain"], kwargs["policy"], family ) if "save" in kwargs and kwargs["save"]: if kwargs["save"] is not True: filename = kwargs["save"] else: filename = None __salt__["iptables.save"](filename=filename, family=family) ret[ "comment" ] = "Set and saved default policy for {} to {} family {}".format( kwargs["chain"], kwargs["policy"], family ) return ret else: ret["result"] = False ret["comment"] = "Failed to set iptables default policy" return ret
[ "def", "set_policy", "(", "name", ",", "table", "=", "\"filter\"", ",", "family", "=", "\"ipv4\"", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "\"name\"", ":", "name", ",", "\"changes\"", ":", "{", "}", ",", "\"result\"", ":", "None", ",", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/iptables.py#L727-L789
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/db/models/fields/files.py
python
FileField.__init__
(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs)
[]
def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): self._primary_key_set_explicitly = 'primary_key' in kwargs self.storage = storage or default_storage self.upload_to = upload_to kwargs['max_length'] = kwargs.get('max_length', 100) super(FileField, self).__init__(verbose_name, name, **kwargs)
[ "def", "__init__", "(", "self", ",", "verbose_name", "=", "None", ",", "name", "=", "None", ",", "upload_to", "=", "''", ",", "storage", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_primary_key_set_explicitly", "=", "'primary_key'", "in...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/db/models/fields/files.py#L230-L237
liangliangyy/DjangoBlog
51d3cb9a29964904b6d59da3b771bb2454fd16ee
djangoblog/elasticsearch_backend.py
python
ElasticSearchBackend.search
(self, query_string, **kwargs)
return { 'results': raw_results, 'hits': hits, 'facets': facets, 'spelling_suggestion': spelling_suggestion, }
[]
def search(self, query_string, **kwargs): logger.info('search query_string:' + query_string) start_offset = kwargs.get('start_offset') end_offset = kwargs.get('end_offset') q = Q('bool', should=[Q('match', body=query_string), Q( 'match', title=query_string)], minimum_should_match="70%") search = ArticleDocument.search() \ .query('bool', filter=[q]) \ .filter('term', status='p') \ .filter('term', type='a') \ .source(False)[start_offset: end_offset] results = search.execute() hits = results['hits'].total raw_results = [] for raw_result in results['hits']['hits']: app_label = 'blog' model_name = 'Article' additional_fields = {} result_class = SearchResult result = result_class( app_label, model_name, raw_result['_id'], raw_result['_score'], **additional_fields) raw_results.append(result) facets = {} spelling_suggestion = None return { 'results': raw_results, 'hits': hits, 'facets': facets, 'spelling_suggestion': spelling_suggestion, }
[ "def", "search", "(", "self", ",", "query_string", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'search query_string:'", "+", "query_string", ")", "start_offset", "=", "kwargs", ".", "get", "(", "'start_offset'", ")", "end_offset", "=", ...
https://github.com/liangliangyy/DjangoBlog/blob/51d3cb9a29964904b6d59da3b771bb2454fd16ee/djangoblog/elasticsearch_backend.py#L55-L95
Rhizome-Conifer/conifer
308fbb98c1b9e668ef4facb66b43f0c362c202de
webrecorder/webrecorder/models/importer.py
python
BaseImporter.handle_upload
(self, stream, upload_id, upload_key, infos, filename, user, force_coll_name, total_size)
return {'upload_id': upload_id, 'user': user.name }
Operate WARC archive upload. :param stream: file object :param str upload_id: upload ID :param str upload_key: upload Redis key :param list infos: list of recordings :param str filename: WARC archive filename :param user User: user :param str force_coll_name: name of collection to upload into :param int total_size: size of WARC archive :returns: upload information :rtype: dict
Operate WARC archive upload.
[ "Operate", "WARC", "archive", "upload", "." ]
def handle_upload(self, stream, upload_id, upload_key, infos, filename, user, force_coll_name, total_size): """Operate WARC archive upload. :param stream: file object :param str upload_id: upload ID :param str upload_key: upload Redis key :param list infos: list of recordings :param str filename: WARC archive filename :param user User: user :param str force_coll_name: name of collection to upload into :param int total_size: size of WARC archive :returns: upload information :rtype: dict """ logger.debug('Begin handle_upload() from: ' + filename + ' force_coll_name: ' + str(force_coll_name)) num_recs = 0 num_recs = len(infos) # first info is for collection, not recording if num_recs >= 2: num_recs -= 1 logger.debug('Parsed {0} recordings, Buffer Size {1}'.format(num_recs, total_size)) first_coll, rec_infos = self.process_upload(user, force_coll_name, infos, stream, filename, total_size, num_recs) if not rec_infos: print('NO ARCHIVES!') #stream.close() return {'error': 'no_archive_data'} with redis_pipeline(self.redis) as pi: pi.hset(upload_key, 'coll', first_coll.name) pi.hset(upload_key, 'coll_title', first_coll.get_prop('title')) pi.hset(upload_key, 'filename', filename) pi.expire(upload_key, self.upload_exp) self.launch_upload(self.run_upload, upload_key, filename, stream, user, rec_infos, total_size, first_coll) return {'upload_id': upload_id, 'user': user.name }
[ "def", "handle_upload", "(", "self", ",", "stream", ",", "upload_id", ",", "upload_key", ",", "infos", ",", "filename", ",", "user", ",", "force_coll_name", ",", "total_size", ")", ":", "logger", ".", "debug", "(", "'Begin handle_upload() from: '", "+", "filen...
https://github.com/Rhizome-Conifer/conifer/blob/308fbb98c1b9e668ef4facb66b43f0c362c202de/webrecorder/webrecorder/models/importer.py#L125-L177
facebookresearch/pyrobot
27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f
src/pyrobot/core.py
python
Arm.pose_ee
(self)
return self.get_ee_pose(base_frame=self.configs.ARM.ARM_BASE_FRAME)
Return the end effector pose w.r.t 'ARM_BASE_FRAME' :return: trans: translational vector (shape: :math:`[3, 1]`) rot_mat: rotational matrix (shape: :math:`[3, 3]`) quat: rotational matrix in the form of quaternion (shape: :math:`[4,]`) :rtype: tuple (trans, rot_mat, quat)
Return the end effector pose w.r.t 'ARM_BASE_FRAME'
[ "Return", "the", "end", "effector", "pose", "w", ".", "r", ".", "t", "ARM_BASE_FRAME" ]
def pose_ee(self): """ Return the end effector pose w.r.t 'ARM_BASE_FRAME' :return: trans: translational vector (shape: :math:`[3, 1]`) rot_mat: rotational matrix (shape: :math:`[3, 3]`) quat: rotational matrix in the form of quaternion (shape: :math:`[4,]`) :rtype: tuple (trans, rot_mat, quat) """ return self.get_ee_pose(base_frame=self.configs.ARM.ARM_BASE_FRAME)
[ "def", "pose_ee", "(", "self", ")", ":", "return", "self", ".", "get_ee_pose", "(", "base_frame", "=", "self", ".", "configs", ".", "ARM", ".", "ARM_BASE_FRAME", ")" ]
https://github.com/facebookresearch/pyrobot/blob/27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f/src/pyrobot/core.py#L519-L533