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
openstack/kuryr-kubernetes
513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba
kuryr_kubernetes/cni/daemon/service.py
python
CNIDaemonWatcherService.on_done
(self, kuryrport, vifs)
[]
def on_done(self, kuryrport, vifs): kp_name = utils.get_res_unique_name(kuryrport) with lockutils.lock(kp_name, external=True): if (kp_name not in self.registry or self.registry[kp_name]['kp']['metadata']['uid'] != kuryrport['metadata']['uid']): self.registry[kp_name] = {'kp': kuryrport, 'vifs': vifs, 'containerid': None, 'vif_unplugged': False, 'del_received': False} else: old_vifs = self.registry[kp_name]['vifs'] for iface in vifs: if old_vifs[iface].active != vifs[iface].active: kp_dict = self.registry[kp_name] kp_dict['vifs'] = vifs self.registry[kp_name] = kp_dict
[ "def", "on_done", "(", "self", ",", "kuryrport", ",", "vifs", ")", ":", "kp_name", "=", "utils", ".", "get_res_unique_name", "(", "kuryrport", ")", "with", "lockutils", ".", "lock", "(", "kp_name", ",", "external", "=", "True", ")", ":", "if", "(", "kp...
https://github.com/openstack/kuryr-kubernetes/blob/513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba/kuryr_kubernetes/cni/daemon/service.py#L289-L306
facebookresearch/detectron2
cb92ae1763cd7d3777c243f07749574cdaec6cb8
projects/DensePose/densepose/modeling/build.py
python
build_densepose_data_filter
(cfg: CfgNode)
return dp_filter
Build DensePose data filter which selects data for training Args: cfg (CfgNode): configuration options Return: Callable: list(Tensor), list(Instances) -> list(Tensor), list(Instances) An instance of DensePose filter, which takes feature tensors and proposals as an input and returns filtered features and proposals
Build DensePose data filter which selects data for training
[ "Build", "DensePose", "data", "filter", "which", "selects", "data", "for", "training" ]
def build_densepose_data_filter(cfg: CfgNode): """ Build DensePose data filter which selects data for training Args: cfg (CfgNode): configuration options Return: Callable: list(Tensor), list(Instances) -> list(Tensor), list(Instances) An instance of DensePose filter, which takes feature tensors and proposals as an input and returns filtered features and proposals """ dp_filter = DensePoseDataFilter(cfg) return dp_filter
[ "def", "build_densepose_data_filter", "(", "cfg", ":", "CfgNode", ")", ":", "dp_filter", "=", "DensePoseDataFilter", "(", "cfg", ")", "return", "dp_filter" ]
https://github.com/facebookresearch/detectron2/blob/cb92ae1763cd7d3777c243f07749574cdaec6cb8/projects/DensePose/densepose/modeling/build.py#L28-L41
jiangsir404/POC-S
eb06d3f54b1698362ad0b62f1b26d22ecafa5624
pocs/thirdparty/IPy/IPy.py
python
IPint.net
(self)
return self.int()
Return the base (first) address of a network as an (long) integer.
Return the base (first) address of a network as an (long) integer.
[ "Return", "the", "base", "(", "first", ")", "address", "of", "a", "network", "as", "an", "(", "long", ")", "integer", "." ]
def net(self): """ Return the base (first) address of a network as an (long) integer. """ return self.int()
[ "def", "net", "(", "self", ")", ":", "return", "self", ".", "int", "(", ")" ]
https://github.com/jiangsir404/POC-S/blob/eb06d3f54b1698362ad0b62f1b26d22ecafa5624/pocs/thirdparty/IPy/IPy.py#L291-L295
kenziyuliu/MS-G3D
5f0f7740ed8543bd0e288affca2a76541c83669e
utils.py
python
import_class
(name)
return mod
[]
def import_class(name): components = name.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod
[ "def", "import_class", "(", "name", ")", ":", "components", "=", "name", ".", "split", "(", "'.'", ")", "mod", "=", "__import__", "(", "components", "[", "0", "]", ")", "for", "comp", "in", "components", "[", "1", ":", "]", ":", "mod", "=", "getatt...
https://github.com/kenziyuliu/MS-G3D/blob/5f0f7740ed8543bd0e288affca2a76541c83669e/utils.py#L2-L7
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/cleanup/management/commands/undo_uuid_clash.py
python
rebuild_ledgers
(ledgers_to_rebuild_by_domain, logger)
[]
def rebuild_ledgers(ledgers_to_rebuild_by_domain, logger): for domain, ledger_ids in ledgers_to_rebuild_by_domain.items(): for ledger_id in ledger_ids: LedgerProcessorSQL.hard_rebuild_ledgers(domain, **ledger_ids._asdict()) logger.log('Ledger %s rebuilt' % ledger_id.as_id())
[ "def", "rebuild_ledgers", "(", "ledgers_to_rebuild_by_domain", ",", "logger", ")", ":", "for", "domain", ",", "ledger_ids", "in", "ledgers_to_rebuild_by_domain", ".", "items", "(", ")", ":", "for", "ledger_id", "in", "ledger_ids", ":", "LedgerProcessorSQL", ".", "...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/cleanup/management/commands/undo_uuid_clash.py#L164-L168
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/wfau/core.py
python
BaseWFAUClass.list_catalogs
(self, style='short')
Returns a list of available catalogs in WFAU. These can be used as ``programme_id`` in queries. Parameters ---------- style : str, optional Must be one of ``'short'``, ``'long'``. Defaults to ``'short'``. Determines whether to print long names or abbreviations for catalogs. Returns ------- list : list containing catalog name strings in long or short style.
Returns a list of available catalogs in WFAU. These can be used as ``programme_id`` in queries.
[ "Returns", "a", "list", "of", "available", "catalogs", "in", "WFAU", ".", "These", "can", "be", "used", "as", "programme_id", "in", "queries", "." ]
def list_catalogs(self, style='short'): """ Returns a list of available catalogs in WFAU. These can be used as ``programme_id`` in queries. Parameters ---------- style : str, optional Must be one of ``'short'``, ``'long'``. Defaults to ``'short'``. Determines whether to print long names or abbreviations for catalogs. Returns ------- list : list containing catalog name strings in long or short style. """ if style == 'short': return list(self.programmes_short.keys()) elif style == 'long': return list(self.programmes_long.keys()) else: warnings.warn("Style must be one of 'long', 'short'.\n" "Returning catalog list in short format.\n") return list(self.programmes_short.keys())
[ "def", "list_catalogs", "(", "self", ",", "style", "=", "'short'", ")", ":", "if", "style", "==", "'short'", ":", "return", "list", "(", "self", ".", "programmes_short", ".", "keys", "(", ")", ")", "elif", "style", "==", "'long'", ":", "return", "list"...
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/wfau/core.py#L633-L656
joxeankoret/nightmare
11b22bb7c346611de90f479ee781c9228af453ea
runtime/BeautifulSoup.py
python
BeautifulStoneSoup.__init__
(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False)
The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke sgmllib: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.
The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser.
[ "The", "Soup", "object", "is", "initialized", "as", "the", "root", "tag", "and", "the", "provided", "markup", "(", "which", "can", "be", "a", "string", "or", "a", "file", "-", "like", "object", ")", "is", "fed", "into", "the", "underlying", "parser", "...
def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False): """The Soup object is initialized as the 'root tag', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless choke or lose data if your data uses self-closing tags or declarations incorrectly. By default, Beautiful Soup uses regexes to sanitize input, avoiding the vast majority of these problems. If the problems don't apply to you, pass in False for markupMassage, and you'll get better performance. The default parser massage techniques fix the two most common instances of invalid HTML that choke sgmllib: <br/> (No space between name of closing tag and tag close) <! --Comment--> (Extraneous whitespace in declaration) You can pass in a custom list of (RE object, replace method) tuples to get Beautiful Soup to scrub your input the way you want.""" self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities # Set the rules for how we'll deal with the entities we # encounter if self.convertEntities: # It doesn't make sense to convert encoded characters to # entities even while you're converting entities to Unicode. # Just convert it all to Unicode. self.smartQuotesTo = None if convertEntities == self.HTML_ENTITIES: self.convertXMLEntities = False self.convertHTMLEntities = True self.escapeUnrecognizedEntities = True elif convertEntities == self.XHTML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = True self.escapeUnrecognizedEntities = False elif convertEntities == self.XML_ENTITIES: self.convertXMLEntities = True self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False else: self.convertXMLEntities = False self.convertHTMLEntities = False self.escapeUnrecognizedEntities = False self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags) SGMLParser.__init__(self) if hasattr(markup, 'read'): # It's a file-type object. markup = markup.read() self.markup = markup self.markupMassage = markupMassage try: self._feed(isHTML=isHTML) except StopParsing: pass self.markup = None
[ "def", "__init__", "(", "self", ",", "markup", "=", "\"\"", ",", "parseOnlyThese", "=", "None", ",", "fromEncoding", "=", "None", ",", "markupMassage", "=", "True", ",", "smartQuotesTo", "=", "XML_ENTITIES", ",", "convertEntities", "=", "None", ",", "selfClo...
https://github.com/joxeankoret/nightmare/blob/11b22bb7c346611de90f479ee781c9228af453ea/runtime/BeautifulSoup.py#L1077-L1144
RaphielGang/Telegram-Paperplane
d9e6c466902dd573ddf8c805e9dc484f972a62f1
userbot/modules/www.py
python
pingme
(pong)
FOr .pingme command, ping the userbot from any chat.
FOr .pingme command, ping the userbot from any chat.
[ "FOr", ".", "pingme", "command", "ping", "the", "userbot", "from", "any", "chat", "." ]
async def pingme(pong): """FOr .pingme command, ping the userbot from any chat.""" start = datetime.now() await pong.edit("`Pong!`") end = datetime.now() duration = (end - start).microseconds / 1000 await pong.edit("`Pong!\n%sms`" % (duration))
[ "async", "def", "pingme", "(", "pong", ")", ":", "start", "=", "datetime", ".", "now", "(", ")", "await", "pong", ".", "edit", "(", "\"`Pong!`\"", ")", "end", "=", "datetime", ".", "now", "(", ")", "duration", "=", "(", "end", "-", "start", ")", ...
https://github.com/RaphielGang/Telegram-Paperplane/blob/d9e6c466902dd573ddf8c805e9dc484f972a62f1/userbot/modules/www.py#L74-L80
steeve/xbmctorrent
e6bcb1037668959e1e3cb5ba8cf3e379c6638da9
resources/site-packages/xbmctorrent/tvdb.py
python
update_image_urls
(meta)
return meta
[]
def update_image_urls(meta): if isinstance(meta, dict): for k, v in meta.items(): if isinstance(v, list): map(update_image_urls, v) elif isinstance(v, dict): update_image_urls(v) elif k in ["banner", "fanart", "poster", "filename", "bannerpath", "vignettepath", "thumbnailpath"] and isinstance(v, basestring): meta[k] = image_url(v) return meta
[ "def", "update_image_urls", "(", "meta", ")", ":", "if", "isinstance", "(", "meta", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "meta", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "map", "(", "update_i...
https://github.com/steeve/xbmctorrent/blob/e6bcb1037668959e1e3cb5ba8cf3e379c6638da9/resources/site-packages/xbmctorrent/tvdb.py#L38-L47
luyishisi/tensorflow
448e72bfb64f826aff8672d74fd7e59c0112e924
4.Object_Detection/object_detection/core/box_predictor.py
python
RfcnBoxPredictor._predict
(self, image_features, num_predictions_per_location, proposal_boxes)
return {BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background}
Computes encoded object locations and corresponding confidences. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. Currently, this must be set to 1, or an error will be raised. proposal_boxes: A float tensor of shape [batch_size, num_proposals, box_code_size]. Returns: box_encodings: A float tensor of shape [batch_size, 1, num_classes, code_size] representing the location of the objects. class_predictions_with_background: A float tensor of shape [batch_size, 1, num_classes + 1] representing the class predictions for the proposals. Raises: ValueError: if num_predictions_per_location is not 1.
Computes encoded object locations and corresponding confidences.
[ "Computes", "encoded", "object", "locations", "and", "corresponding", "confidences", "." ]
def _predict(self, image_features, num_predictions_per_location, proposal_boxes): """Computes encoded object locations and corresponding confidences. Args: image_features: A float tensor of shape [batch_size, height, width, channels] containing features for a batch of images. num_predictions_per_location: an integer representing the number of box predictions to be made per spatial location in the feature map. Currently, this must be set to 1, or an error will be raised. proposal_boxes: A float tensor of shape [batch_size, num_proposals, box_code_size]. Returns: box_encodings: A float tensor of shape [batch_size, 1, num_classes, code_size] representing the location of the objects. class_predictions_with_background: A float tensor of shape [batch_size, 1, num_classes + 1] representing the class predictions for the proposals. Raises: ValueError: if num_predictions_per_location is not 1. """ if num_predictions_per_location != 1: raise ValueError('Currently RfcnBoxPredictor only supports ' 'predicting a single box per class per location.') batch_size = tf.shape(proposal_boxes)[0] num_boxes = tf.shape(proposal_boxes)[1] def get_box_indices(proposals): proposals_shape = proposals.get_shape().as_list() if any(dim is None for dim in proposals_shape): proposals_shape = tf.shape(proposals) ones_mat = tf.ones(proposals_shape[:2], dtype=tf.int32) multiplier = tf.expand_dims( tf.range(start=0, limit=proposals_shape[0]), 1) return tf.reshape(ones_mat * multiplier, [-1]) net = image_features with slim.arg_scope(self._conv_hyperparams): net = slim.conv2d(net, self._depth, [1, 1], scope='reduce_depth') # Location predictions. location_feature_map_depth = (self._num_spatial_bins[0] * self._num_spatial_bins[1] * self.num_classes * self._box_code_size) location_feature_map = slim.conv2d(net, location_feature_map_depth, [1, 1], activation_fn=None, scope='refined_locations') box_encodings = ops.position_sensitive_crop_regions( location_feature_map, boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]), box_ind=get_box_indices(proposal_boxes), crop_size=self._crop_size, num_spatial_bins=self._num_spatial_bins, global_pool=True) box_encodings = tf.squeeze(box_encodings, squeeze_dims=[1, 2]) box_encodings = tf.reshape(box_encodings, [batch_size * num_boxes, 1, self.num_classes, self._box_code_size]) # Class predictions. total_classes = self.num_classes + 1 # Account for background class. class_feature_map_depth = (self._num_spatial_bins[0] * self._num_spatial_bins[1] * total_classes) class_feature_map = slim.conv2d(net, class_feature_map_depth, [1, 1], activation_fn=None, scope='class_predictions') class_predictions_with_background = ops.position_sensitive_crop_regions( class_feature_map, boxes=tf.reshape(proposal_boxes, [-1, self._box_code_size]), box_ind=get_box_indices(proposal_boxes), crop_size=self._crop_size, num_spatial_bins=self._num_spatial_bins, global_pool=True) class_predictions_with_background = tf.squeeze( class_predictions_with_background, squeeze_dims=[1, 2]) class_predictions_with_background = tf.reshape( class_predictions_with_background, [batch_size * num_boxes, 1, total_classes]) return {BOX_ENCODINGS: box_encodings, CLASS_PREDICTIONS_WITH_BACKGROUND: class_predictions_with_background}
[ "def", "_predict", "(", "self", ",", "image_features", ",", "num_predictions_per_location", ",", "proposal_boxes", ")", ":", "if", "num_predictions_per_location", "!=", "1", ":", "raise", "ValueError", "(", "'Currently RfcnBoxPredictor only supports '", "'predicting a singl...
https://github.com/luyishisi/tensorflow/blob/448e72bfb64f826aff8672d74fd7e59c0112e924/4.Object_Detection/object_detection/core/box_predictor.py#L167-L251
merixstudio/django-trench
27b61479e6d494d7c2e94732c1d186247dac8dd9
trench/backends/base.py
python
AbstractMessageDispatcher._get_valid_window
(self)
return self._config.get( VALIDITY_PERIOD, trench_settings.DEFAULT_VALIDITY_PERIOD )
[]
def _get_valid_window(self) -> int: return self._config.get( VALIDITY_PERIOD, trench_settings.DEFAULT_VALIDITY_PERIOD )
[ "def", "_get_valid_window", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_config", ".", "get", "(", "VALIDITY_PERIOD", ",", "trench_settings", ".", "DEFAULT_VALIDITY_PERIOD", ")" ]
https://github.com/merixstudio/django-trench/blob/27b61479e6d494d7c2e94732c1d186247dac8dd9/trench/backends/base.py#L83-L86
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/barthez/tokenization_barthez.py
python
BarthezTokenizer.__init__
( self, vocab_file, bos_token="<s>", eos_token="</s>", sep_token="</s>", cls_token="<s>", unk_token="<unk>", pad_token="<pad>", mask_token="<mask>", sp_model_kwargs: Optional[Dict[str, Any]] = None, **kwargs )
[]
def __init__( self, vocab_file, bos_token="<s>", eos_token="</s>", sep_token="</s>", cls_token="<s>", unk_token="<unk>", pad_token="<pad>", mask_token="<mask>", sp_model_kwargs: Optional[Dict[str, Any]] = None, **kwargs ) -> None: # Mask token behave like a normal word, i.e. include the space before it mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, sep_token=sep_token, cls_token=cls_token, pad_token=pad_token, mask_token=mask_token, sp_model_kwargs=self.sp_model_kwargs, **kwargs, ) self.vocab_file = vocab_file self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(vocab_file)) self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} self.fairseq_tokens_to_ids["<mask>"] = len(self.sp_model) - 1 self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
[ "def", "__init__", "(", "self", ",", "vocab_file", ",", "bos_token", "=", "\"<s>\"", ",", "eos_token", "=", "\"</s>\"", ",", "sep_token", "=", "\"</s>\"", ",", "cls_token", "=", "\"<s>\"", ",", "unk_token", "=", "\"<unk>\"", ",", "pad_token", "=", "\"<pad>\"...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/barthez/tokenization_barthez.py#L124-L161
MDudek-ICS/TRISIS-TRITON-HATMAN
15a00af7fd1040f0430729d024427601f84886a1
decompiled_code/library/codecs.py
python
StreamReader.reset
(self)
return
Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.
[ "Resets", "the", "codec", "buffers", "used", "for", "keeping", "state", ".", "Note", "that", "no", "stream", "repositioning", "should", "take", "place", ".", "This", "method", "is", "primarily", "intended", "to", "be", "able", "to", "recover", "from", "decod...
def reset(self): """ Resets the codec buffers used for keeping state. Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors. """ self.bytebuffer = '' self.charbuffer = u'' self.linebuffer = None return
[ "def", "reset", "(", "self", ")", ":", "self", ".", "bytebuffer", "=", "''", "self", ".", "charbuffer", "=", "u''", "self", ".", "linebuffer", "=", "None", "return" ]
https://github.com/MDudek-ICS/TRISIS-TRITON-HATMAN/blob/15a00af7fd1040f0430729d024427601f84886a1/decompiled_code/library/codecs.py#L527-L538
kylebebak/Requester
4a9f9f051fa5fc951a8f7ad098a328261ca2db97
deps/urllib3/response.py
python
HTTPResponse.from_httplib
(ResponseCls, r, **response_kw)
return resp
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.
Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object.
[ "Given", "an", ":", "class", ":", "httplib", ".", "HTTPResponse", "instance", "r", "return", "a", "corresponding", ":", "class", ":", "urllib3", ".", "response", ".", "HTTPResponse", "object", "." ]
def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp
[ "def", "from_httplib", "(", "ResponseCls", ",", "r", ",", "*", "*", "response_kw", ")", ":", "headers", "=", "r", ".", "msg", "if", "not", "isinstance", "(", "headers", ",", "HTTPHeaderDict", ")", ":", "if", "PY3", ":", "# Python 3", "headers", "=", "H...
https://github.com/kylebebak/Requester/blob/4a9f9f051fa5fc951a8f7ad098a328261ca2db97/deps/urllib3/response.py#L442-L468
andreafioraldi/angrgdb
0c8f1f2b1c8c84b161177801588baeeb9abf62d9
angrgdb/context_view.py
python
ContextView.pstr_call_info
(self, state, function)
return [ self.pstr_call_argument(*arg) for arg in function.calling_convention.get_arg_info(state)]
:param angr.SimState state: :param angr.knowledge_plugins.functions.Function function: :return:
[]
def pstr_call_info(self, state, function): """ :param angr.SimState state: :param angr.knowledge_plugins.functions.Function function: :return: """ return [ self.pstr_call_argument(*arg) for arg in function.calling_convention.get_arg_info(state)]
[ "def", "pstr_call_info", "(", "self", ",", "state", ",", "function", ")", ":", "return", "[", "self", ".", "pstr_call_argument", "(", "*", "arg", ")", "for", "arg", "in", "function", ".", "calling_convention", ".", "get_arg_info", "(", "state", ")", "]" ]
https://github.com/andreafioraldi/angrgdb/blob/0c8f1f2b1c8c84b161177801588baeeb9abf62d9/angrgdb/context_view.py#L406-L413
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/androguard/androguard/core/bytecodes/dvm.py
python
DalvikVMFormat.get_cm_string
(self, idx)
return self.CM.get_raw_string(idx)
Get a specific string by using an index :param idx: index of the string :type idx: int
Get a specific string by using an index
[ "Get", "a", "specific", "string", "by", "using", "an", "index" ]
def get_cm_string(self, idx): """ Get a specific string by using an index :param idx: index of the string :type idx: int """ return self.CM.get_raw_string(idx)
[ "def", "get_cm_string", "(", "self", ",", "idx", ")", ":", "return", "self", ".", "CM", ".", "get_raw_string", "(", "idx", ")" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/androguard/androguard/core/bytecodes/dvm.py#L7841-L7848
Qianlitp/WatchAD
825fa89858a8792b2c7b95d9519193f9b4297032
modules/alert/activity.py
python
Activity._generate_invasion
(self, activity_doc)
生成入侵事件 多个相同来源IP 不同类型的威胁活动 可以生成一个入侵事件 返回入侵事件的ID
生成入侵事件 多个相同来源IP 不同类型的威胁活动 可以生成一个入侵事件
[ "生成入侵事件", "多个相同来源IP", "不同类型的威胁活动", "可以生成一个入侵事件" ]
def _generate_invasion(self, activity_doc) -> ObjectId: """ 生成入侵事件 多个相同来源IP 不同类型的威胁活动 可以生成一个入侵事件 返回入侵事件的ID """ # 首先查找是否已存在对应的入侵事件,尝试合并 invasion_id = self._merge_activity(activity_doc) if invasion_id: assert isinstance(invasion_id, ObjectId) return invasion_id # 没有已存在的入侵事件,则按照条件,查找是否已存在不同类型的威胁活动 query = { "form_data.source_ip": activity_doc["form_data"]["source_ip"], "end_time": {"$gte": activity_doc["start_time"] + timedelta(hours=-main_config.merge_invasion_time)}, "alert_code": {"$ne": activity_doc["alert_code"]} } # 如果存在不同类型的威胁活动 another_activities = list(self.activity_mongo.find_all(query).sort("start_time", ASCENDING)) if len(another_activities) > 0: invasion_id = self.invasion.new(*another_activities, activity_doc) # 创建完入侵事件之后,将之前查询的到威胁活动全部加上对应的ID for activity in another_activities: self.update(activity["_id"], { "$set": { "invasion_id": invasion_id } })
[ "def", "_generate_invasion", "(", "self", ",", "activity_doc", ")", "->", "ObjectId", ":", "# 首先查找是否已存在对应的入侵事件,尝试合并", "invasion_id", "=", "self", ".", "_merge_activity", "(", "activity_doc", ")", "if", "invasion_id", ":", "assert", "isinstance", "(", "invasion_id", ...
https://github.com/Qianlitp/WatchAD/blob/825fa89858a8792b2c7b95d9519193f9b4297032/modules/alert/activity.py#L58-L88
airbnb/streamalert
26cf1d08432ca285fd4f7410511a6198ca104bbb
streamalert/scheduled_queries/query_packs/configuration.py
python
QueryPackConfiguration.generate_query
(self, **kwargs)
Returns a raw SQL query string
Returns a raw SQL query string
[ "Returns", "a", "raw", "SQL", "query", "string" ]
def generate_query(self, **kwargs): """Returns a raw SQL query string""" try: return self.query_template.format(**kwargs) except KeyError as e: msg = ''' Failed to generate query for pack: "{name}" The provided query parameters were: {kwargs} Error: {error} '''.strip().format(name=self.name, error=e, kwargs=kwargs) raise KeyError(msg)
[ "def", "generate_query", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "query_template", ".", "format", "(", "*", "*", "kwargs", ")", "except", "KeyError", "as", "e", ":", "msg", "=", "'''\nFailed to generate query for ...
https://github.com/airbnb/streamalert/blob/26cf1d08432ca285fd4f7410511a6198ca104bbb/streamalert/scheduled_queries/query_packs/configuration.py#L40-L53
readthedocs/readthedocs.org
0852d7c10d725d954d3e9a93513171baa1116d9f
readthedocs/organizations/managers.py
python
TeamMemberManager.sorted
(self)
return ( self.get_queryset().annotate( null_member=models.Count('member'), ).order_by('-null_member', 'member') )
Return sorted list of members and invites. Return list of members and invites sorted by members first, and null members (invites) last.
Return sorted list of members and invites.
[ "Return", "sorted", "list", "of", "members", "and", "invites", "." ]
def sorted(self): """ Return sorted list of members and invites. Return list of members and invites sorted by members first, and null members (invites) last. """ return ( self.get_queryset().annotate( null_member=models.Count('member'), ).order_by('-null_member', 'member') )
[ "def", "sorted", "(", "self", ")", ":", "return", "(", "self", ".", "get_queryset", "(", ")", ".", "annotate", "(", "null_member", "=", "models", ".", "Count", "(", "'member'", ")", ",", ")", ".", "order_by", "(", "'-null_member'", ",", "'member'", ")"...
https://github.com/readthedocs/readthedocs.org/blob/0852d7c10d725d954d3e9a93513171baa1116d9f/readthedocs/organizations/managers.py#L58-L69
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_group.py
python
Yedit.get_entry
(data, key, sep='.')
return data
Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c
Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c
[ "Get", "an", "item", "from", "a", "dictionary", "with", "key", "notation", "a", ".", "b", ".", "c", "d", "=", "{", "a", ":", "{", "b", ":", "c", "}}}", "key", "=", "a", ".", "b", "return", "c" ]
def get_entry(data, key, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c ''' if key == '': pass elif (not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict))): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None return data
[ "def", "get_entry", "(", "data", ",", "key", ",", "sep", "=", "'.'", ")", ":", "if", "key", "==", "''", ":", "pass", "elif", "(", "not", "(", "key", "and", "Yedit", ".", "valid_key", "(", "key", ",", "sep", ")", ")", "and", "isinstance", "(", "...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L316-L338
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/task/base.py
python
move_to_nearest_project_dir
(args)
[]
def move_to_nearest_project_dir(args): nearest_project_dir = get_nearest_project_dir(args) os.chdir(nearest_project_dir)
[ "def", "move_to_nearest_project_dir", "(", "args", ")", ":", "nearest_project_dir", "=", "get_nearest_project_dir", "(", "args", ")", "os", ".", "chdir", "(", "nearest_project_dir", ")" ]
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/task/base.py#L156-L158
SolidCode/SolidPython
4715c827ad90db26ee37df57bc425e6f2de3cf8d
solid/examples/mazebox/inset.py
python
Vec2D.set
(self, x, y)
[]
def set(self, x, y): self.x = x self.y = y
[ "def", "set", "(", "self", ",", "x", ",", "y", ")", ":", "self", ".", "x", "=", "x", "self", ".", "y", "=", "y" ]
https://github.com/SolidCode/SolidPython/blob/4715c827ad90db26ee37df57bc425e6f2de3cf8d/solid/examples/mazebox/inset.py#L10-L12
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/bulkexports/v1/export/day.py
python
DayInstance.fetch
(self)
return self._proxy.fetch()
Fetch the DayInstance :returns: The fetched DayInstance :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance
Fetch the DayInstance
[ "Fetch", "the", "DayInstance" ]
def fetch(self): """ Fetch the DayInstance :returns: The fetched DayInstance :rtype: twilio.rest.bulkexports.v1.export.day.DayInstance """ return self._proxy.fetch()
[ "def", "fetch", "(", "self", ")", ":", "return", "self", ".", "_proxy", ".", "fetch", "(", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/bulkexports/v1/export/day.py#L319-L326
PaddlePaddle/PaddleX
2bab73f81ab54e328204e7871e6ae4a82e719f5d
paddlex/ppdet/modeling/backbones/shufflenet_v2.py
python
InvertedResidualDS.forward
(self, inputs)
return channel_shuffle(out, 2)
[]
def forward(self, inputs): x1 = self._conv_dw_1(inputs) x1 = self._conv_linear_1(x1) x2 = self._conv_pw_2(inputs) x2 = self._conv_dw_2(x2) x2 = self._conv_linear_2(x2) out = paddle.concat([x1, x2], axis=1) return channel_shuffle(out, 2)
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "x1", "=", "self", ".", "_conv_dw_1", "(", "inputs", ")", "x1", "=", "self", ".", "_conv_linear_1", "(", "x1", ")", "x2", "=", "self", ".", "_conv_pw_2", "(", "inputs", ")", "x2", "=", "self",...
https://github.com/PaddlePaddle/PaddleX/blob/2bab73f81ab54e328204e7871e6ae4a82e719f5d/paddlex/ppdet/modeling/backbones/shufflenet_v2.py#L158-L166
huawei-noah/vega
d9f13deede7f2b584e4b1d32ffdb833856129989
vega/networks/pytorch/backbones/backbone_tools.py
python
remove_layers
(layer_arch, p_arch, len_dis)
return remove_name, bn_layers
Remove expand layers in serailnet than pretrained architecture. :param layer_arch: current serailnet encode :type layer_arch: str :param p_arch: pretrained serailnet encode :type p_arch: str :param len_dis: num of blocks more than pretrain :type len_dis: int :return: more expand block name :rtype: list
Remove expand layers in serailnet than pretrained architecture.
[ "Remove", "expand", "layers", "in", "serailnet", "than", "pretrained", "architecture", "." ]
def remove_layers(layer_arch, p_arch, len_dis): """Remove expand layers in serailnet than pretrained architecture. :param layer_arch: current serailnet encode :type layer_arch: str :param p_arch: pretrained serailnet encode :type p_arch: str :param len_dis: num of blocks more than pretrain :type len_dis: int :return: more expand block name :rtype: list """ def map_index_to_name(index, layer_arch): name = [] for i in index: for layer in range(1, len(layer_arch) + 1): if i < len(''.join(layer_arch[:layer])): block_i = i - len(''.join(layer_arch[:layer - 1])) n = 'layer' + str(layer) + '.' + str(block_i) + '.' name.append(n) break return name def find_diff_index(pos, new_arch, old_arch): agg_arch = zip(new_arch, old_arch) for i, tup in enumerate(agg_arch): if tup[0] != tup[1]: if len(pos) < 1: pos.append(i) else: pos.append(i + pos[-1] + 1) return find_diff_index(pos, new_arch[i + 1:], old_arch[i:]) break return pos def get_bn_layers(remove_name, layer_arch, p_arch): bn_layers = [n + 'bn{}'.format(i) for n in remove_name for i in range(1, 4)] p_len = len(p_arch.split('-')) for i in range(1, len(layer_arch) - p_len + 1): bn_layers.append('layer{}.0.downsample.1'.format(p_len + i)) return bn_layers pretrained_arch = ''.join(p_arch.split('-')) remove_index = find_diff_index([], ''.join(layer_arch), pretrained_arch) if len(remove_index) < len_dis: if len(layer_arch) > len(p_arch.split('-')): len_dis = len_dis - (len(layer_arch) - len(p_arch.split('-'))) remove_index = remove_index + list(range(len(''.join(layer_arch)) - len_dis + len(remove_index), len(''.join(layer_arch)))) remove_name = map_index_to_name(remove_index, layer_arch) bn_layers = get_bn_layers(remove_name, layer_arch, p_arch) return remove_name, bn_layers
[ "def", "remove_layers", "(", "layer_arch", ",", "p_arch", ",", "len_dis", ")", ":", "def", "map_index_to_name", "(", "index", ",", "layer_arch", ")", ":", "name", "=", "[", "]", "for", "i", "in", "index", ":", "for", "layer", "in", "range", "(", "1", ...
https://github.com/huawei-noah/vega/blob/d9f13deede7f2b584e4b1d32ffdb833856129989/vega/networks/pytorch/backbones/backbone_tools.py#L125-L178
NLPatVCU/medaCy
c8d7e9d4104095629ddc92f8d3338c799be5537f
medacy/model/multi_model.py
python
_activate_model
(model_path, pipeline_class, args, kwargs)
return model
Creates a Model with the given pipeline configuration and sets its weights to the pickled model path :param model_path: path to the model pickle file :param pipeline_class: the pipeline class for the pickled model :param args, kwargs: arguments to pass to the pipeline constructor :return: a usable Model instance
Creates a Model with the given pipeline configuration and sets its weights to the pickled model path :param model_path: path to the model pickle file :param pipeline_class: the pipeline class for the pickled model :param args, kwargs: arguments to pass to the pipeline constructor :return: a usable Model instance
[ "Creates", "a", "Model", "with", "the", "given", "pipeline", "configuration", "and", "sets", "its", "weights", "to", "the", "pickled", "model", "path", ":", "param", "model_path", ":", "path", "to", "the", "model", "pickle", "file", ":", "param", "pipeline_c...
def _activate_model(model_path, pipeline_class, args, kwargs): """ Creates a Model with the given pipeline configuration and sets its weights to the pickled model path :param model_path: path to the model pickle file :param pipeline_class: the pipeline class for the pickled model :param args, kwargs: arguments to pass to the pipeline constructor :return: a usable Model instance """ pipeline_instance = pipeline_class(*args, **kwargs) model = Model(pipeline_instance) model.load(model_path) return model
[ "def", "_activate_model", "(", "model_path", ",", "pipeline_class", ",", "args", ",", "kwargs", ")", ":", "pipeline_instance", "=", "pipeline_class", "(", "*", "args", ",", "*", "*", "kwargs", ")", "model", "=", "Model", "(", "pipeline_instance", ")", "model...
https://github.com/NLPatVCU/medaCy/blob/c8d7e9d4104095629ddc92f8d3338c799be5537f/medacy/model/multi_model.py#L10-L21
Unbabel/OpenKiwi
07d7cfed880457d95daf189dd8282e5b02ac2954
kiwi/modules/common/activations.py
python
gelu
(x)
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
gelu activation function copied from pytorch-pretrained-BERT.
gelu activation function copied from pytorch-pretrained-BERT.
[ "gelu", "activation", "function", "copied", "from", "pytorch", "-", "pretrained", "-", "BERT", "." ]
def gelu(x): """gelu activation function copied from pytorch-pretrained-BERT.""" return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
[ "def", "gelu", "(", "x", ")", ":", "return", "x", "*", "0.5", "*", "(", "1.0", "+", "torch", ".", "erf", "(", "x", "/", "math", ".", "sqrt", "(", "2.0", ")", ")", ")" ]
https://github.com/Unbabel/OpenKiwi/blob/07d7cfed880457d95daf189dd8282e5b02ac2954/kiwi/modules/common/activations.py#L22-L24
paramiko/paramiko
88f35a537428e430f7f26eee8026715e357b55d6
paramiko/server.py
python
ServerInterface.check_channel_exec_request
(self, channel, command)
return False
Determine if a shell command will be executed for the client. If this method returns ``True``, the channel should be connected to the stdin, stdout, and stderr of the shell command. The default implementation always returns ``False``. :param .Channel channel: the `.Channel` the request arrived on. :param str command: the command to execute. :return: ``True`` if this channel is now hooked up to the stdin, stdout, and stderr of the executing command; ``False`` if the command will not be executed. .. versionadded:: 1.1
Determine if a shell command will be executed for the client. If this method returns ``True``, the channel should be connected to the stdin, stdout, and stderr of the shell command.
[ "Determine", "if", "a", "shell", "command", "will", "be", "executed", "for", "the", "client", ".", "If", "this", "method", "returns", "True", "the", "channel", "should", "be", "connected", "to", "the", "stdin", "stdout", "and", "stderr", "of", "the", "shel...
def check_channel_exec_request(self, channel, command): """ Determine if a shell command will be executed for the client. If this method returns ``True``, the channel should be connected to the stdin, stdout, and stderr of the shell command. The default implementation always returns ``False``. :param .Channel channel: the `.Channel` the request arrived on. :param str command: the command to execute. :return: ``True`` if this channel is now hooked up to the stdin, stdout, and stderr of the executing command; ``False`` if the command will not be executed. .. versionadded:: 1.1 """ return False
[ "def", "check_channel_exec_request", "(", "self", ",", "channel", ",", "command", ")", ":", "return", "False" ]
https://github.com/paramiko/paramiko/blob/88f35a537428e430f7f26eee8026715e357b55d6/paramiko/server.py#L416-L433
bbc/brave
88d4454412ee5acfa5ecf2ac5bc8cf75766c7be5
brave/outputs/output.py
python
Output.source
(self)
return connection.source if connection else None
Returns the Input or Mixer object that is the source for this output. Can be None if this output thas no source.
Returns the Input or Mixer object that is the source for this output. Can be None if this output thas no source.
[ "Returns", "the", "Input", "or", "Mixer", "object", "that", "is", "the", "source", "for", "this", "output", ".", "Can", "be", "None", "if", "this", "output", "thas", "no", "source", "." ]
def source(self): ''' Returns the Input or Mixer object that is the source for this output. Can be None if this output thas no source. ''' connection = self.source_connection() return connection.source if connection else None
[ "def", "source", "(", "self", ")", ":", "connection", "=", "self", ".", "source_connection", "(", ")", "return", "connection", ".", "source", "if", "connection", "else", "None" ]
https://github.com/bbc/brave/blob/88d4454412ee5acfa5ecf2ac5bc8cf75766c7be5/brave/outputs/output.py#L44-L50
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/aifc.py
python
Aifc_read.initfp
(self, file)
[]
def initfp(self, file): self._version = 0 self._convert = None self._markers = [] self._soundpos = 0 self._file = file chunk = Chunk(file) if chunk.getname() != b'FORM': raise Error('file does not start with FORM id') formdata = chunk.read(4) if formdata == b'AIFF': self._aifc = 0 elif formdata == b'AIFC': self._aifc = 1 else: raise Error('not an AIFF or AIFF-C file') self._comm_chunk_read = 0 self._ssnd_chunk = None while 1: self._ssnd_seek_needed = 1 try: chunk = Chunk(self._file) except EOFError: break chunkname = chunk.getname() if chunkname == b'COMM': self._read_comm_chunk(chunk) self._comm_chunk_read = 1 elif chunkname == b'SSND': self._ssnd_chunk = chunk dummy = chunk.read(8) self._ssnd_seek_needed = 0 elif chunkname == b'FVER': self._version = _read_ulong(chunk) elif chunkname == b'MARK': self._readmark(chunk) chunk.skip() if not self._comm_chunk_read or not self._ssnd_chunk: raise Error('COMM chunk and/or SSND chunk missing')
[ "def", "initfp", "(", "self", ",", "file", ")", ":", "self", ".", "_version", "=", "0", "self", ".", "_convert", "=", "None", "self", ".", "_markers", "=", "[", "]", "self", ".", "_soundpos", "=", "0", "self", ".", "_file", "=", "file", "chunk", ...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/aifc.py#L308-L346
kashif/firedup
9e6605dbb6f564c8e1e35121681581e103c476b5
fireup/utils/run_utils.py
python
call_experiment
( exp_name, thunk, seed=0, num_cpu=1, data_dir=None, datestamp=False, **kwargs )
Run a function (thunk) with hyperparameters (kwargs), plus configuration. This wraps a few pieces of functionality which are useful when you want to run many experiments in sequence, including logger configuration and splitting into multiple processes for MPI. There's also a Fired Up specific convenience added into executing the thunk: if ``env_name`` is one of the kwargs passed to call_experiment, it's assumed that the thunk accepts an argument called ``env_fn``, and that the ``env_fn`` should make a gym environment with the given ``env_name``. The way the experiment is actually executed is slightly complicated: the function is serialized to a string, and then ``run_entrypoint.py`` is executed in a subprocess call with the serialized string as an argument. ``run_entrypoint.py`` unserializes the function call and executes it. We choose to do it this way---instead of just calling the function directly here---to avoid leaking state between successive experiments. Args: exp_name (string): Name for experiment. thunk (callable): A python function. seed (int): Seed for random number generators. num_cpu (int): Number of MPI processes to split into. Also accepts 'auto', which will set up as many procs as there are cpus on the machine. data_dir (string): Used in configuring the logger, to decide where to store experiment results. Note: if left as None, data_dir will default to ``DEFAULT_DATA_DIR`` from ``fireup/user_config.py``. **kwargs: All kwargs to pass to thunk.
Run a function (thunk) with hyperparameters (kwargs), plus configuration.
[ "Run", "a", "function", "(", "thunk", ")", "with", "hyperparameters", "(", "kwargs", ")", "plus", "configuration", "." ]
def call_experiment( exp_name, thunk, seed=0, num_cpu=1, data_dir=None, datestamp=False, **kwargs ): """ Run a function (thunk) with hyperparameters (kwargs), plus configuration. This wraps a few pieces of functionality which are useful when you want to run many experiments in sequence, including logger configuration and splitting into multiple processes for MPI. There's also a Fired Up specific convenience added into executing the thunk: if ``env_name`` is one of the kwargs passed to call_experiment, it's assumed that the thunk accepts an argument called ``env_fn``, and that the ``env_fn`` should make a gym environment with the given ``env_name``. The way the experiment is actually executed is slightly complicated: the function is serialized to a string, and then ``run_entrypoint.py`` is executed in a subprocess call with the serialized string as an argument. ``run_entrypoint.py`` unserializes the function call and executes it. We choose to do it this way---instead of just calling the function directly here---to avoid leaking state between successive experiments. Args: exp_name (string): Name for experiment. thunk (callable): A python function. seed (int): Seed for random number generators. num_cpu (int): Number of MPI processes to split into. Also accepts 'auto', which will set up as many procs as there are cpus on the machine. data_dir (string): Used in configuring the logger, to decide where to store experiment results. Note: if left as None, data_dir will default to ``DEFAULT_DATA_DIR`` from ``fireup/user_config.py``. **kwargs: All kwargs to pass to thunk. """ # Determine number of CPU cores to run on num_cpu = psutil.cpu_count(logical=False) if num_cpu == "auto" else num_cpu # Send random seed to thunk kwargs["seed"] = seed # Be friendly and print out your kwargs, so we all know what's up print(colorize("Running experiment:\n", color="cyan", bold=True)) print(exp_name + "\n") print(colorize("with kwargs:\n", color="cyan", bold=True)) kwargs_json = convert_json(kwargs) print(json.dumps(kwargs_json, separators=(",", ":\t"), indent=4, sort_keys=True)) print("\n") # Set up logger output directory if "logger_kwargs" not in kwargs: kwargs["logger_kwargs"] = setup_logger_kwargs( exp_name, seed, data_dir, datestamp ) else: print("Note: Call experiment is not handling logger_kwargs.\n") def thunk_plus(): # Make 'env_fn' from 'env_name' if "env_name" in kwargs: import gym env_name = kwargs["env_name"] kwargs["env_fn"] = lambda: gym.make(env_name) del kwargs["env_name"] # Fork into multiple processes mpi_fork(num_cpu) # Run thunk thunk(**kwargs) # Prepare to launch a script to run the experiment pickled_thunk = cloudpickle.dumps(thunk_plus) encoded_thunk = base64.b64encode(zlib.compress(pickled_thunk)).decode("utf-8") entrypoint = osp.join(osp.abspath(osp.dirname(__file__)), "run_entrypoint.py") cmd = [sys.executable if sys.executable else "python", entrypoint, encoded_thunk] try: subprocess.check_call(cmd, env=os.environ) except CalledProcessError: err_msg = ( "\n" * 3 + "=" * DIV_LINE_WIDTH + "\n" + dedent( """ There appears to have been an error in your experiment. Check the traceback above to see what actually went wrong. The traceback below, included for completeness (but probably not useful for diagnosing the error), shows the stack leading up to the experiment launch. """ ) + "=" * DIV_LINE_WIDTH + "\n" * 3 ) print(err_msg) raise # Tell the user about where results are, and how to check them logger_kwargs = kwargs["logger_kwargs"] plot_cmd = "python3 -m fireup.run plot " + logger_kwargs["output_dir"] plot_cmd = colorize(plot_cmd, "green") test_cmd = "python3 -m fireup.run test_policy " + logger_kwargs["output_dir"] test_cmd = colorize(test_cmd, "green") output_msg = ( "\n" * 5 + "=" * DIV_LINE_WIDTH + "\n" + dedent( """\ End of experiment. Plot results from this run with: %s Watch the trained agent with: %s """ % (plot_cmd, test_cmd) ) + "=" * DIV_LINE_WIDTH + "\n" * 5 ) print(output_msg)
[ "def", "call_experiment", "(", "exp_name", ",", "thunk", ",", "seed", "=", "0", ",", "num_cpu", "=", "1", ",", "data_dir", "=", "None", ",", "datestamp", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Determine number of CPU cores to run on", "num_cpu",...
https://github.com/kashif/firedup/blob/9e6605dbb6f564c8e1e35121681581e103c476b5/fireup/utils/run_utils.py#L94-L239
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/trigonometric.py
python
sin._eval_as_leading_term
(self, x)
[]
def _eval_as_leading_term(self, x): arg = self.args[0].as_leading_term(x) if x in arg.free_symbols and C.Order(1, x).contains(arg): return arg else: return self.func(arg)
[ "def", "_eval_as_leading_term", "(", "self", ",", "x", ")", ":", "arg", "=", "self", ".", "args", "[", "0", "]", ".", "as_leading_term", "(", "x", ")", "if", "x", "in", "arg", ".", "free_symbols", "and", "C", ".", "Order", "(", "1", ",", "x", ")"...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/functions/elementary/trigonometric.py#L340-L346
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/_osx_support.py
python
_override_all_archs
(_config_vars)
return _config_vars
Allow override of all archs with ARCHFLAGS env var
Allow override of all archs with ARCHFLAGS env var
[ "Allow", "override", "of", "all", "archs", "with", "ARCHFLAGS", "env", "var" ]
def _override_all_archs(_config_vars): """Allow override of all archs with ARCHFLAGS env var""" # NOTE: This name was introduced by Apple in OSX 10.5 and # is used by several scripting languages distributed with # that OS release. if 'ARCHFLAGS' in os.environ: arch = os.environ['ARCHFLAGS'] for cv in _UNIVERSAL_CONFIG_VARS: if cv in _config_vars and '-arch' in _config_vars[cv]: flags = _config_vars[cv] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = flags + ' ' + arch _save_modified_value(_config_vars, cv, flags) return _config_vars
[ "def", "_override_all_archs", "(", "_config_vars", ")", ":", "# NOTE: This name was introduced by Apple in OSX 10.5 and", "# is used by several scripting languages distributed with", "# that OS release.", "if", "'ARCHFLAGS'", "in", "os", ".", "environ", ":", "arch", "=", "os", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/_osx_support.py#L260-L274
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/progress/__init__.py
python
Infinite.__init__
(self, *args, **kwargs)
[]
def __init__(self, *args, **kwargs): self.index = 0 self.start_ts = time() self._ts = self.start_ts self._dt = deque(maxlen=self.sma_window) for key, val in kwargs.items(): setattr(self, key, val)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "index", "=", "0", "self", ".", "start_ts", "=", "time", "(", ")", "self", ".", "_ts", "=", "self", ".", "start_ts", "self", ".", "_dt", "=", "deq...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/progress/__init__.py#L31-L37
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/example-python/package_examples/resnet/logs/logger.py
python
_collect_run_params
(run_info, run_params)
Log the parameter information for the benchmark run.
Log the parameter information for the benchmark run.
[ "Log", "the", "parameter", "information", "for", "the", "benchmark", "run", "." ]
def _collect_run_params(run_info, run_params): """Log the parameter information for the benchmark run.""" def process_param(name, value): type_check = { str: {"name": name, "string_value": value}, int: {"name": name, "long_value": value}, bool: {"name": name, "bool_value": str(value)}, float: {"name": name, "float_value": value}, } return type_check.get(type(value), {"name": name, "string_value": str(value)}) if run_params: run_info["run_parameters"] = [ process_param(k, v) for k, v in sorted(run_params.items())]
[ "def", "_collect_run_params", "(", "run_info", ",", "run_params", ")", ":", "def", "process_param", "(", "name", ",", "value", ")", ":", "type_check", "=", "{", "str", ":", "{", "\"name\"", ":", "name", ",", "\"string_value\"", ":", "value", "}", ",", "i...
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/example-python/package_examples/resnet/logs/logger.py#L208-L221
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py
python
QuotedString.__init__
( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True)
[]
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True): super(QuotedString,self).__init__() # remove white space from quote chars - wont work anyway quoteChar = quoteChar.strip() if not quoteChar: warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() if endQuoteChar is None: endQuoteChar = quoteChar else: endQuoteChar = endQuoteChar.strip() if not endQuoteChar: warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() self.quoteChar = quoteChar self.quoteCharLen = len(quoteChar) self.firstQuoteChar = quoteChar[0] self.endQuoteChar = endQuoteChar self.endQuoteCharLen = len(endQuoteChar) self.escChar = escChar self.escQuote = escQuote self.unquoteResults = unquoteResults self.convertWhitespaceEscapes = convertWhitespaceEscapes if multiline: self.flags = re.MULTILINE | re.DOTALL self.pattern = r'%s(?:[^%s%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) else: self.flags = 0 self.pattern = r'%s(?:[^%s\n\r%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) if len(self.endQuoteChar) > 1: self.pattern += ( '|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]), _escapeRegexRangeChars(self.endQuoteChar[i])) for i in range(len(self.endQuoteChar)-1,0,-1)) + ')' ) if escQuote: self.pattern += (r'|(?:%s)' % re.escape(escQuote)) if escChar: self.pattern += (r'|(?:%s.)' % re.escape(escChar)) self.escCharReplacePattern = re.escape(self.escChar)+"(.)" self.pattern += (r')*%s' % re.escape(self.endQuoteChar)) try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, SyntaxWarning, stacklevel=2) raise self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayIndexError = False self.mayReturnEmpty = True
[ "def", "__init__", "(", "self", ",", "quoteChar", ",", "escChar", "=", "None", ",", "escQuote", "=", "None", ",", "multiline", "=", "False", ",", "unquoteResults", "=", "True", ",", "endQuoteChar", "=", "None", ",", "convertWhitespaceEscapes", "=", "True", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pyparsing.py#L2841-L2904
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/core/bbox/box_np_ops.py
python
bev_box_decode
( box_encodings, anchors, encode_angle_to_vector=False, smooth_dim=False )
return np.concatenate([xg, yg, wg, lg, rg], axis=-1)
box decode for VoxelNet in lidar Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, w, l, h, r anchors ([N, 7] Tensor): anchors
box decode for VoxelNet in lidar Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, w, l, h, r anchors ([N, 7] Tensor): anchors
[ "box", "decode", "for", "VoxelNet", "in", "lidar", "Args", ":", "boxes", "(", "[", "N", "7", "]", "Tensor", ")", ":", "normal", "boxes", ":", "x", "y", "z", "w", "l", "h", "r", "anchors", "(", "[", "N", "7", "]", "Tensor", ")", ":", "anchors" ]
def bev_box_decode( box_encodings, anchors, encode_angle_to_vector=False, smooth_dim=False ): """box decode for VoxelNet in lidar Args: boxes ([N, 7] Tensor): normal boxes: x, y, z, w, l, h, r anchors ([N, 7] Tensor): anchors """ # need to convert box_encodings to z-bottom format xa, ya, wa, la, ra = np.split(anchors, 5, axis=-1) if encode_angle_to_vector: xt, yt, wt, lt, rtx, rty = np.split(box_encodings, 6, axis=-1) else: xt, yt, wt, lt, rt = np.split(box_encodings, 5, axis=-1) diagonal = np.sqrt(la ** 2 + wa ** 2) xg = xt * diagonal + xa yg = yt * diagonal + ya if smooth_dim: lg = (lt + 1) * la wg = (wt + 1) * wa else: lg = np.exp(lt) * la wg = np.exp(wt) * wa if encode_angle_to_vector: rax = np.cos(ra) ray = np.sin(ra) rgx = rtx + rax rgy = rty + ray rg = np.arctan2(rgy, rgx) else: rg = rt + ra return np.concatenate([xg, yg, wg, lg, rg], axis=-1)
[ "def", "bev_box_decode", "(", "box_encodings", ",", "anchors", ",", "encode_angle_to_vector", "=", "False", ",", "smooth_dim", "=", "False", ")", ":", "# need to convert box_encodings to z-bottom format", "xa", ",", "ya", ",", "wa", ",", "la", ",", "ra", "=", "n...
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/core/bbox/box_np_ops.py#L233-L264
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/network/lib/socks.py
python
_makemethod
(name)
return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
[]
def _makemethod(name): return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
[ "def", "_makemethod", "(", "name", ")", ":", "return", "lambda", "self", ",", "*", "pos", ",", "*", "*", "kw", ":", "self", ".", "_savedmethods", "[", "name", "]", "(", "*", "pos", ",", "*", "*", "kw", ")" ]
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/network/lib/socks.py#L300-L301
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/gruneisen/mesh.py
python
GruneisenMesh.write_yaml
(self, comment=None, filename=None, compression=None)
Write results in yaml file.
Write results in yaml file.
[ "Write", "results", "in", "yaml", "file", "." ]
def write_yaml(self, comment=None, filename=None, compression=None): """Write results in yaml file.""" if filename is not None: _filename = filename if compression is None: if filename is None: _filename = "gruneisen.yaml" with open(_filename, "w") as w: self._write_yaml(w, comment) elif compression == "gzip": if filename is None: _filename = "gruneisen.yaml.gz" with gzip.open(_filename, "wb") as w: self._write_yaml(w, comment, is_binary=True) elif compression == "lzma": try: import lzma except ImportError: raise ( "Reading a lzma compressed file is not supported " "by this python version." ) if filename is None: _filename = "gruneisen.yaml.xz" with lzma.open(_filename, "w") as w: self._write_yaml(w, comment, is_binary=True)
[ "def", "write_yaml", "(", "self", ",", "comment", "=", "None", ",", "filename", "=", "None", ",", "compression", "=", "None", ")", ":", "if", "filename", "is", "not", "None", ":", "_filename", "=", "filename", "if", "compression", "is", "None", ":", "i...
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/gruneisen/mesh.py#L111-L137
edgedb/edgedb
872bf5abbb10f7c72df21f57635238ed27b9f280
edb/schema/pointers.py
python
PointerCommand.validate_object
( self, schema: s_schema.Schema, context: sd.CommandContext, )
Check that pointer definition is sound.
Check that pointer definition is sound.
[ "Check", "that", "pointer", "definition", "is", "sound", "." ]
def validate_object( self, schema: s_schema.Schema, context: sd.CommandContext, ) -> None: """Check that pointer definition is sound.""" from edb.ir import ast as irast referrer_ctx = self.get_referrer_context(context) if referrer_ctx is None: return self._validate_computables(schema, context) scls = self.scls if not scls.get_owned(schema): return default_expr = scls.get_default(schema) if default_expr is not None: if default_expr.irast is None: default_expr = default_expr.compiled(default_expr, schema) assert isinstance(default_expr.irast, irast.Statement) default_type = default_expr.irast.stype assert default_type is not None ptr_target = scls.get_target(schema) assert ptr_target is not None source_context = self.get_attribute_source_context('default') if not default_type.assignment_castable_to(ptr_target, schema): raise errors.SchemaDefinitionError( f'default expression is of invalid type: ' f'{default_type.get_displayname(schema)}, ' f'expected {ptr_target.get_displayname(schema)}', context=source_context, ) # "required" status of defaults should not be enforced # because it's impossible to actually guarantee that any # SELECT involving a path is non-empty ptr_cardinality = scls.get_cardinality(schema) default_required, default_cardinality = \ default_expr.irast.cardinality.to_schema_value() if (ptr_cardinality is qltypes.SchemaCardinality.One and default_cardinality != ptr_cardinality): raise errors.SchemaDefinitionError( f'possibly more than one element returned by ' f'the default expression for ' f'{scls.get_verbosename(schema)} declared as ' f"'single'", context=source_context, )
[ "def", "validate_object", "(", "self", ",", "schema", ":", "s_schema", ".", "Schema", ",", "context", ":", "sd", ".", "CommandContext", ",", ")", "->", "None", ":", "from", "edb", ".", "ir", "import", "ast", "as", "irast", "referrer_ctx", "=", "self", ...
https://github.com/edgedb/edgedb/blob/872bf5abbb10f7c72df21f57635238ed27b9f280/edb/schema/pointers.py#L1507-L1561
dropbox/PyHive
b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0
TCLIService/ttypes.py
python
TTypeDesc.__ne__
(self, other)
return not (self == other)
[]
def __ne__(self, other): return not (self == other)
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "(", "self", "==", "other", ")" ]
https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/ttypes.py#L1178-L1179
pytorch/fairseq
1575f30dd0a9f7b3c499db0b4767aa4e9f79056c
fairseq/utils.py
python
resolve_max_positions
(*args)
return max_positions
Resolve max position constraints from multiple sources.
Resolve max position constraints from multiple sources.
[ "Resolve", "max", "position", "constraints", "from", "multiple", "sources", "." ]
def resolve_max_positions(*args): """Resolve max position constraints from multiple sources.""" def map_value_update(d1, d2): updated_value = copy.deepcopy(d1) for key in d2: if key not in updated_value: updated_value[key] = d2[key] else: updated_value[key] = min(d1[key], d2[key]) return updated_value def nullsafe_min(l): minim = None for item in l: if minim is None: minim = item elif item is not None and item < minim: minim = item return minim max_positions = None for arg in args: if max_positions is None: max_positions = arg elif arg is not None: max_positions, arg = _match_types(max_positions, arg) if isinstance(arg, float) or isinstance(arg, int): max_positions = min(max_positions, arg) elif isinstance(arg, dict): max_positions = map_value_update(max_positions, arg) else: max_positions = tuple(map(nullsafe_min, zip(max_positions, arg))) return max_positions
[ "def", "resolve_max_positions", "(", "*", "args", ")", ":", "def", "map_value_update", "(", "d1", ",", "d2", ")", ":", "updated_value", "=", "copy", ".", "deepcopy", "(", "d1", ")", "for", "key", "in", "d2", ":", "if", "key", "not", "in", "updated_valu...
https://github.com/pytorch/fairseq/blob/1575f30dd0a9f7b3c499db0b4767aa4e9f79056c/fairseq/utils.py#L427-L461
kevinzg/facebook-scraper
e4c43a07c06fadec6890d35e500a4a52ede9c653
facebook_scraper/utils.py
python
remove_control_characters
(html)
return html
Strip invalid XML characters that `lxml` cannot parse.
Strip invalid XML characters that `lxml` cannot parse.
[ "Strip", "invalid", "XML", "characters", "that", "lxml", "cannot", "parse", "." ]
def remove_control_characters(html): # type: (t.Text) -> t.Text """ Strip invalid XML characters that `lxml` cannot parse. """ # See: https://github.com/html5lib/html5lib-python/issues/96 # # The XML 1.0 spec defines the valid character range as: # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] # # We can instead match the invalid characters by inverting that range into: # InvalidChar ::= #xb | #xc | #xFFFE | #xFFFF | [#x0-#x8] | [#xe-#x1F] | [#xD800-#xDFFF] # # Sources: # https://www.w3.org/TR/REC-xml/#charsets, # https://lsimons.wordpress.com/2011/03/17/stripping-illegal-characters-out-of-xml-in-python/ def strip_illegal_xml_characters(s, default, base=10): # Compare the "invalid XML character range" numerically n = int(s, base) if ( n in (0xB, 0xC, 0xFFFE, 0xFFFF) or 0x0 <= n <= 0x8 or 0xE <= n <= 0x1F or 0xD800 <= n <= 0xDFFF ): return "" return default # We encode all non-ascii characters to XML char-refs, so for example "💖" becomes: "&#x1F496;" # Otherwise we'd remove emojis by mistake on narrow-unicode builds of Python html = html.encode("ascii", "xmlcharrefreplace").decode("utf-8") html = re.sub( r"&#(\d+);?", lambda c: strip_illegal_xml_characters(c.group(1), c.group(0)), html ) html = re.sub( r"&#[xX]([0-9a-fA-F]+);?", lambda c: strip_illegal_xml_characters(c.group(1), c.group(0), base=16), html, ) # A regex matching the "invalid XML character range" html = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1F\uD800-\uDFFF\uFFFE\uFFFF]").sub("", html) return html
[ "def", "remove_control_characters", "(", "html", ")", ":", "# type: (t.Text) -> t.Text", "# See: https://github.com/html5lib/html5lib-python/issues/96", "#", "# The XML 1.0 spec defines the valid character range as:", "# Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10F...
https://github.com/kevinzg/facebook-scraper/blob/e4c43a07c06fadec6890d35e500a4a52ede9c653/facebook_scraper/utils.py#L84-L125
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/virt/driver.py
python
ComputeDriver.set_admin_password
(self, instance, new_pass)
Set the root password on the specified instance. :param instance: nova.objects.instance.Instance :param new_pass: the new password
Set the root password on the specified instance.
[ "Set", "the", "root", "password", "on", "the", "specified", "instance", "." ]
def set_admin_password(self, instance, new_pass): """Set the root password on the specified instance. :param instance: nova.objects.instance.Instance :param new_pass: the new password """ raise NotImplementedError()
[ "def", "set_admin_password", "(", "self", ",", "instance", ",", "new_pass", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/driver.py#L1341-L1347
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/google_ads_service/transports/grpc.py
python
GoogleAdsServiceGrpcTransport.search
( self, )
return self._stubs["search"]
r"""Return a callable for the search method over gRPC. Returns all rows that match the search query. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `ChangeEventError <>`__ `ChangeStatusError <>`__ `ClickViewError <>`__ `HeaderError <>`__ `InternalError <>`__ `QueryError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.SearchGoogleAdsRequest], ~.SearchGoogleAdsResponse]: A function that, when called, will call the underlying RPC on the server.
r"""Return a callable for the search method over gRPC.
[ "r", "Return", "a", "callable", "for", "the", "search", "method", "over", "gRPC", "." ]
def search( self, ) -> Callable[ [google_ads_service.SearchGoogleAdsRequest], google_ads_service.SearchGoogleAdsResponse, ]: r"""Return a callable for the search method over gRPC. Returns all rows that match the search query. List of thrown errors: `AuthenticationError <>`__ `AuthorizationError <>`__ `ChangeEventError <>`__ `ChangeStatusError <>`__ `ClickViewError <>`__ `HeaderError <>`__ `InternalError <>`__ `QueryError <>`__ `QuotaError <>`__ `RequestError <>`__ Returns: Callable[[~.SearchGoogleAdsRequest], ~.SearchGoogleAdsResponse]: A function that, when called, will call the underlying RPC on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "search" not in self._stubs: self._stubs["search"] = self.grpc_channel.unary_unary( "/google.ads.googleads.v8.services.GoogleAdsService/Search", request_serializer=google_ads_service.SearchGoogleAdsRequest.serialize, response_deserializer=google_ads_service.SearchGoogleAdsResponse.deserialize, ) return self._stubs["search"]
[ "def", "search", "(", "self", ",", ")", "->", "Callable", "[", "[", "google_ads_service", ".", "SearchGoogleAdsRequest", "]", ",", "google_ads_service", ".", "SearchGoogleAdsResponse", ",", "]", ":", "# Generate a \"stub function\" on-the-fly which will actually make", "#...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/google_ads_service/transports/grpc.py#L212-L244
okpy/ok
50a00190f05363d096478dd8e53aa1a36dd40c4a
server/forms.py
python
CanvasCourseForm.populate_canvas_course
(self, canvas_course)
[]
def populate_canvas_course(self, canvas_course): match = re.search(CANVAS_COURSE_URL_REGEX, self.url.data) canvas_course.api_domain = match.group(1) canvas_course.external_id = int(match.group(3)) canvas_course.access_token = self.access_token.data
[ "def", "populate_canvas_course", "(", "self", ",", "canvas_course", ")", ":", "match", "=", "re", ".", "search", "(", "CANVAS_COURSE_URL_REGEX", ",", "self", ".", "url", ".", "data", ")", "canvas_course", ".", "api_domain", "=", "match", ".", "group", "(", ...
https://github.com/okpy/ok/blob/50a00190f05363d096478dd8e53aa1a36dd40c4a/server/forms.py#L821-L825
google/capirca
679e3885e3a5e5e129dc2dfab204ec44d63b26a4
capirca/lib/windows_advfirewall.py
python
Term._ComposeRule
(self, srcaddr, dstaddr, proto, srcport, dstport, action)
return (self.CMD_PREFIX + self._RULE_FORMAT.substitute( name=self.term_name, atoms=' '.join(atoms)))
Convert the given parameters into a netsh add rule string.
Convert the given parameters into a netsh add rule string.
[ "Convert", "the", "given", "parameters", "into", "a", "netsh", "add", "rule", "string", "." ]
def _ComposeRule(self, srcaddr, dstaddr, proto, srcport, dstport, action): """Convert the given parameters into a netsh add rule string.""" atoms = [] src_label = 'local' dst_label = 'remote' # We assume a default direction of OUT, but if it's IN, the Windows # advfirewall changes around the remote and local labels. if 'in' == self.filter.lower(): src_label = 'remote' dst_label = 'local' atoms.append(self._DIR_ATOM.substitute(dir=self.filter)) if srcaddr.prefixlen == 0: atoms.append(self._ADDR_ATOM.substitute(dir=src_label, addr='any')) else: atoms.append(self._ADDR_ATOM.substitute(dir=src_label, addr=str(srcaddr))) if dstaddr.prefixlen == 0: atoms.append(self._ADDR_ATOM.substitute(dir=dst_label, addr='any')) else: atoms.append(self._ADDR_ATOM.substitute(dir=dst_label, addr=str(dstaddr))) if srcport: atoms.append(self._PORT_ATOM.substitute(dir=src_label, port=srcport)) if dstport: atoms.append(self._PORT_ATOM.substitute(dir=dst_label, port=dstport)) if proto: if proto == 'vrrp': proto = '112' elif proto == 'ah': proto = '51' elif proto == 'hopopt': proto = '0' atoms.append(self._PROTO_ATOM.substitute(protocol=proto)) atoms.append(self._ACTION_ATOM.substitute( action=self._ACTION_TABLE[action])) return (self.CMD_PREFIX + self._RULE_FORMAT.substitute( name=self.term_name, atoms=' '.join(atoms)))
[ "def", "_ComposeRule", "(", "self", ",", "srcaddr", ",", "dstaddr", ",", "proto", ",", "srcport", ",", "dstport", ",", "action", ")", ":", "atoms", "=", "[", "]", "src_label", "=", "'local'", "dst_label", "=", "'remote'", "# We assume a default direction of OU...
https://github.com/google/capirca/blob/679e3885e3a5e5e129dc2dfab204ec44d63b26a4/capirca/lib/windows_advfirewall.py#L90-L133
adobe/ops-cli
2384257c4199b3ff37e366f48b4dfce3ac282524
src/ops/inventory/generator.py
python
PluginInventoryGenerator.supports
(self, config)
return config.get('plugin') is not None
[]
def supports(self, config): return config.get('plugin') is not None
[ "def", "supports", "(", "self", ",", "config", ")", ":", "return", "config", ".", "get", "(", "'plugin'", ")", "is", "not", "None" ]
https://github.com/adobe/ops-cli/blob/2384257c4199b3ff37e366f48b4dfce3ac282524/src/ops/inventory/generator.py#L217-L218
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/case_importer/tracking/models.py
python
CaseUploadRecord.get_task_status_json
(self)
[]
def get_task_status_json(self): if self.task_status_json: return TaskStatus.wrap(self.task_status_json) else: return get_task_status_json(str(self.task_id))
[ "def", "get_task_status_json", "(", "self", ")", ":", "if", "self", ".", "task_status_json", ":", "return", "TaskStatus", ".", "wrap", "(", "self", ".", "task_status_json", ")", "else", ":", "return", "get_task_status_json", "(", "str", "(", "self", ".", "ta...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/case_importer/tracking/models.py#L44-L48
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/__init__.py
python
WorkingSet.find_plugins
( self, plugin_env, full_env=None, installer=None, fallback=True)
return distributions, error_info
Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance.
Find all activatable distributions in `plugin_env`
[ "Find", "all", "activatable", "distributions", "in", "plugin_env" ]
def find_plugins( self, plugin_env, full_env=None, installer=None, fallback=True): """Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) ) # add plugins+libs to sys.path map(working_set.add, distributions) # display errors print('Could not load', errors) The `plugin_env` should be an ``Environment`` instance that contains only distributions that are in the project's "plugin directory" or directories. The `full_env`, if supplied, should be an ``Environment`` contains all currently-available distributions. If `full_env` is not supplied, one is created automatically from the ``WorkingSet`` this method is called on, which will typically mean that every directory on ``sys.path`` will be scanned for distributions. `installer` is a standard installer callback as used by the ``resolve()`` method. The `fallback` flag indicates whether we should attempt to resolve older versions of a plugin if the newest version cannot be resolved. This method returns a 2-tuple: (`distributions`, `error_info`), where `distributions` is a list of the distributions found in `plugin_env` that were loadable, along with any other distributions that are needed to resolve their dependencies. `error_info` is a dictionary mapping unloadable plugin distributions to an exception instance describing the error that occurred. Usually this will be a ``DistributionNotFound`` or ``VersionConflict`` instance. """ plugin_projects = list(plugin_env) # scan project names in alphabetic order plugin_projects.sort() error_info = {} distributions = {} if full_env is None: env = Environment(self.entries) env += plugin_env else: env = full_env + plugin_env shadow_set = self.__class__([]) # put all our entries in shadow_set list(map(shadow_set.add, self)) for project_name in plugin_projects: for dist in plugin_env[project_name]: req = [dist.as_requirement()] try: resolvees = shadow_set.resolve(req, env, installer) except ResolutionError as v: # save error info error_info[dist] = v if fallback: # try the next older version of project continue else: # give up on this project, keep going break else: list(map(shadow_set.add, resolvees)) distributions.update(dict.fromkeys(resolvees)) # success, no need to try any more versions of this project break distributions = list(distributions) distributions.sort() return distributions, error_info
[ "def", "find_plugins", "(", "self", ",", "plugin_env", ",", "full_env", "=", "None", ",", "installer", "=", "None", ",", "fallback", "=", "True", ")", ":", "plugin_projects", "=", "list", "(", "plugin_env", ")", "# scan project names in alphabetic order", "plugi...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pkg_resources/__init__.py#L891-L973
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymongo/collection.py
python
Collection.distinct
(self, key, filter=None, **kwargs)
Get a list of distinct values for `key` among all documents in this collection. Raises :class:`TypeError` if `key` is not an instance of :class:`basestring` (:class:`str` in python 3). All optional distinct parameters should be passed as keyword arguments to this method. Valid options include: - `maxTimeMS` (int): The maximum amount of time to allow the count command to run, in milliseconds. The :meth:`distinct` method obeys the :attr:`read_preference` of this :class:`Collection`. :Parameters: - `key`: name of the field for which we want to get the distinct values - `filter` (optional): A query document that specifies the documents from which to retrieve the distinct values. - `**kwargs` (optional): See list of options above.
Get a list of distinct values for `key` among all documents in this collection.
[ "Get", "a", "list", "of", "distinct", "values", "for", "key", "among", "all", "documents", "in", "this", "collection", "." ]
def distinct(self, key, filter=None, **kwargs): """Get a list of distinct values for `key` among all documents in this collection. Raises :class:`TypeError` if `key` is not an instance of :class:`basestring` (:class:`str` in python 3). All optional distinct parameters should be passed as keyword arguments to this method. Valid options include: - `maxTimeMS` (int): The maximum amount of time to allow the count command to run, in milliseconds. The :meth:`distinct` method obeys the :attr:`read_preference` of this :class:`Collection`. :Parameters: - `key`: name of the field for which we want to get the distinct values - `filter` (optional): A query document that specifies the documents from which to retrieve the distinct values. - `**kwargs` (optional): See list of options above. """ if not isinstance(key, string_type): raise TypeError("key must be an " "instance of %s" % (string_type.__name__,)) cmd = SON([("distinct", self.__name), ("key", key)]) if filter is not None: if "query" in kwargs: raise ConfigurationError("can't pass both filter and query") kwargs["query"] = filter cmd.update(kwargs) with self._socket_for_reads() as (sock_info, slave_ok): return self._command(sock_info, cmd, slave_ok, read_concern=self.read_concern)["values"]
[ "def", "distinct", "(", "self", ",", "key", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "key", ",", "string_type", ")", ":", "raise", "TypeError", "(", "\"key must be an \"", "\"instance of %s\"", "%", "...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymongo/collection.py#L1770-L1805
evennia/evennia
fa79110ba6b219932f22297838e8ac72ebc0be0e
evennia/utils/evmore.py
python
EvMore.page_end
(self)
Display the bottom page.
Display the bottom page.
[ "Display", "the", "bottom", "page", "." ]
def page_end(self): """ Display the bottom page. """ self._npos = self._npages - 1 self.display()
[ "def", "page_end", "(", "self", ")", ":", "self", ".", "_npos", "=", "self", ".", "_npages", "-", "1", "self", ".", "display", "(", ")" ]
https://github.com/evennia/evennia/blob/fa79110ba6b219932f22297838e8ac72ebc0be0e/evennia/utils/evmore.py#L305-L310
jgyates/genmon
2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e
genmqtt.py
python
MyMQTT.on_disconnect
(self, client, userdata, rc=0)
[]
def on_disconnect(self, client, userdata, rc=0): self.LogInfo("Disconnected from " + self.MQTTAddress + " result code: " + str(rc)) self.MQTTclient.publish(self.LastWillTopic, payload = "Offline", retain = True)
[ "def", "on_disconnect", "(", "self", ",", "client", ",", "userdata", ",", "rc", "=", "0", ")", ":", "self", ".", "LogInfo", "(", "\"Disconnected from \"", "+", "self", ".", "MQTTAddress", "+", "\" result code: \"", "+", "str", "(", "rc", ")", ")", "self"...
https://github.com/jgyates/genmon/blob/2cb2ed2945f55cd8c259b09ccfa9a51e23f1341e/genmqtt.py#L470-L473
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/core/base/constraint.py
python
_GeneralConstraintData.equality
(self)
return False
A boolean indicating whether this is an equality constraint.
A boolean indicating whether this is an equality constraint.
[ "A", "boolean", "indicating", "whether", "this", "is", "an", "equality", "constraint", "." ]
def equality(self): """A boolean indicating whether this is an equality constraint.""" if self._expr.__class__ is logical_expr.EqualityExpression: return True elif self._expr.__class__ is logical_expr.RangedExpression: # TODO: this is a very restrictive form of structural equality. lb = self._expr.arg(0) if lb is not None and lb is self._expr.arg(2): return True return False
[ "def", "equality", "(", "self", ")", ":", "if", "self", ".", "_expr", ".", "__class__", "is", "logical_expr", ".", "EqualityExpression", ":", "return", "True", "elif", "self", ".", "_expr", ".", "__class__", "is", "logical_expr", ".", "RangedExpression", ":"...
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/base/constraint.py#L410-L419
Tribler/tribler
f1de8bd54f293b01b2646a1dead1c1dc9dfdb356
src/tribler-core/tribler_core/start_core.py
python
run_tribler_core
(api_port, api_key, state_dir, gui_test_mode=False)
This method will start a new Tribler session. Note that there is no direct communication between the GUI process and the core: all communication is performed through the HTTP API.
This method will start a new Tribler session. Note that there is no direct communication between the GUI process and the core: all communication is performed through the HTTP API.
[ "This", "method", "will", "start", "a", "new", "Tribler", "session", ".", "Note", "that", "there", "is", "no", "direct", "communication", "between", "the", "GUI", "process", "and", "the", "core", ":", "all", "communication", "is", "performed", "through", "th...
def run_tribler_core(api_port, api_key, state_dir, gui_test_mode=False): """ This method will start a new Tribler session. Note that there is no direct communication between the GUI process and the core: all communication is performed through the HTTP API. """ logger.info(f'Start tribler core. API port: "{api_port}". ' f'API key: "{api_key}". State dir: "{state_dir}". ' f'Core test mode: "{gui_test_mode}"') config = TriblerConfig.load( file=state_dir / CONFIG_FILE_NAME, state_dir=state_dir, reset_config_on_error=True) config.gui_test_mode = gui_test_mode if SentryReporter.is_in_test_mode(): default_core_exception_handler.sentry_reporter.global_strategy = SentryStrategy.SEND_ALLOWED config.api.http_port = int(api_port) # If the API key is set to an empty string, it will remain disabled if config.api.key not in ('', api_key): config.api.key = api_key config.write() # Immediately write the API key so other applications can use it config.api.http_enabled = True priority_order = config.resource_monitor.cpu_priority set_process_priority(pid=os.getpid(), priority_order=priority_order) # Enable tracer if --trace-debug or --trace-exceptions flag is present in sys.argv log_dir = config.general.get_path_as_absolute('log_dir', config.state_dir) trace_logger = check_and_enable_code_tracing('core', log_dir) logging.getLogger('asyncio').setLevel(logging.WARNING) if sys.platform.startswith('win'): # TODO for the moment being, we use the SelectorEventLoop on Windows, since with the ProactorEventLoop, ipv8 # peer discovery becomes unstable. Also see issue #5485. asyncio.set_event_loop(asyncio.SelectorEventLoop()) loop = asyncio.get_event_loop() exception_handler = default_core_exception_handler loop.set_exception_handler(exception_handler.unhandled_error_observer) try: loop.run_until_complete(core_session(config, components=list(components_gen(config)))) finally: if trace_logger: trace_logger.close() # Flush the logs to the file before exiting for handler in logging.getLogger().handlers: handler.flush()
[ "def", "run_tribler_core", "(", "api_port", ",", "api_key", ",", "state_dir", ",", "gui_test_mode", "=", "False", ")", ":", "logger", ".", "info", "(", "f'Start tribler core. API port: \"{api_port}\". '", "f'API key: \"{api_key}\". State dir: \"{state_dir}\". '", "f'Core test...
https://github.com/Tribler/tribler/blob/f1de8bd54f293b01b2646a1dead1c1dc9dfdb356/src/tribler-core/tribler_core/start_core.py#L108-L160
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/ldap3/protocol/rfc2849.py
python
decode_persistent_search_control
(change)
return None
[]
def decode_persistent_search_control(change): if 'controls' in change and '2.16.840.1.113730.3.4.7' in change['controls']: decoded = dict() decoded_control, unprocessed = decoder.decode(change['controls']['2.16.840.1.113730.3.4.7']['value'], asn1Spec=EntryChangeNotificationControl()) if unprocessed: raise LDAPExtensionError('unprocessed value in EntryChangeNotificationControl') if decoded_control['changeType'] == 1: # add decoded['changeType'] = 'add' elif decoded_control['changeType'] == 2: # delete decoded['changeType'] = 'delete' elif decoded_control['changeType'] == 4: # modify decoded['changeType'] = 'modify' elif decoded_control['changeType'] == 8: # modify_dn decoded['changeType'] = 'modify dn' else: raise LDAPExtensionError('unknown Persistent Search changeType ' + str(decoded_control['changeType'])) decoded['changeNumber'] = decoded_control['changeNumber'] if 'changeNumber' in decoded_control and decoded_control['changeNumber'] is not None and decoded_control['changeNumber'].hasValue() else None decoded['previousDN'] = decoded_control['previousDN'] if 'previousDN' in decoded_control and decoded_control['previousDN'] is not None and decoded_control['previousDN'].hasValue() else None return decoded return None
[ "def", "decode_persistent_search_control", "(", "change", ")", ":", "if", "'controls'", "in", "change", "and", "'2.16.840.1.113730.3.4.7'", "in", "change", "[", "'controls'", "]", ":", "decoded", "=", "dict", "(", ")", "decoded_control", ",", "unprocessed", "=", ...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/ldap3/protocol/rfc2849.py#L260-L280
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/core/leoVim.py
python
VimCommands.vis_J
(self)
Join the highlighted lines.
Join the highlighted lines.
[ "Join", "the", "highlighted", "lines", "." ]
def vis_J(self): """Join the highlighted lines.""" self.state = 'normal' self.not_ready()
[ "def", "vis_J", "(", "self", ")", ":", "self", ".", "state", "=", "'normal'", "self", ".", "not_ready", "(", ")" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/core/leoVim.py#L1841-L1844
readthedocs/readthedocs.org
0852d7c10d725d954d3e9a93513171baa1116d9f
readthedocs/notifications/storages.py
python
NonPersistentStorage.process_message
(self, message, *args, **kwargs)
return None
Convert messages to models and save them. If its level is into non-persistent levels, convert the message to models and save it
Convert messages to models and save them.
[ "Convert", "messages", "to", "models", "and", "save", "them", "." ]
def process_message(self, message, *args, **kwargs): """ Convert messages to models and save them. If its level is into non-persistent levels, convert the message to models and save it """ if message.level not in NON_PERSISTENT_MESSAGE_LEVELS: return message user = kwargs.get('user') or self.get_user() try: anonymous = user.is_anonymous except TypeError: anonymous = user.is_anonymous if anonymous: raise NotImplementedError( 'Persistent message levels cannot be used for anonymous users.', ) message_persistent = PersistentMessage() message_persistent.level = message.level message_persistent.message = message.message message_persistent.extra_tags = message.extra_tags message_persistent.user = user if 'expires' in kwargs: message_persistent.expires = kwargs['expires'] message_persistent.save() return None
[ "def", "process_message", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "message", ".", "level", "not", "in", "NON_PERSISTENT_MESSAGE_LEVELS", ":", "return", "message", "user", "=", "kwargs", ".", "get", "(", "'u...
https://github.com/readthedocs/readthedocs.org/blob/0852d7c10d725d954d3e9a93513171baa1116d9f/readthedocs/notifications/storages.py#L130-L159
openstack/octavia
27e5b27d31c695ba72fb6750de2bdafd76e0d7d9
octavia/amphorae/drivers/keepalived/vrrp_rest_driver.py
python
KeepalivedAmphoraDriverMixin.update_vrrp_conf
(self, loadbalancer, amphorae_network_config, amphora, timeout_dict=None)
Update amphora of the loadbalancer with a new VRRP configuration :param loadbalancer: loadbalancer object :param amphorae_network_config: amphorae network configurations :param amphora: The amphora object to update. :param timeout_dict: Dictionary of timeout values for calls to the amphora. May contain: req_conn_timeout, req_read_timeout, conn_max_retries, conn_retry_interval
Update amphora of the loadbalancer with a new VRRP configuration
[ "Update", "amphora", "of", "the", "loadbalancer", "with", "a", "new", "VRRP", "configuration" ]
def update_vrrp_conf(self, loadbalancer, amphorae_network_config, amphora, timeout_dict=None): """Update amphora of the loadbalancer with a new VRRP configuration :param loadbalancer: loadbalancer object :param amphorae_network_config: amphorae network configurations :param amphora: The amphora object to update. :param timeout_dict: Dictionary of timeout values for calls to the amphora. May contain: req_conn_timeout, req_read_timeout, conn_max_retries, conn_retry_interval """ if amphora.status != constants.AMPHORA_ALLOCATED: LOG.debug('update_vrrp_conf called for un-allocated amphora %s. ' 'Ignoring.', amphora.id) return templater = jinja_cfg.KeepalivedJinjaTemplater() LOG.debug("Update amphora %s VRRP configuration.", amphora.id) self._populate_amphora_api_version(amphora) # Get the VIP subnet prefix for the amphora # For amphorav2 amphorae_network_config will be list of dicts try: vip_cidr = amphorae_network_config[amphora.id].vip_subnet.cidr except AttributeError: vip_cidr = amphorae_network_config[amphora.id][ constants.VIP_SUBNET][constants.CIDR] # Generate Keepalived configuration from loadbalancer object config = templater.build_keepalived_config( loadbalancer, amphora, vip_cidr) self.clients[amphora.api_version].upload_vrrp_config(amphora, config)
[ "def", "update_vrrp_conf", "(", "self", ",", "loadbalancer", ",", "amphorae_network_config", ",", "amphora", ",", "timeout_dict", "=", "None", ")", ":", "if", "amphora", ".", "status", "!=", "constants", ".", "AMPHORA_ALLOCATED", ":", "LOG", ".", "debug", "(",...
https://github.com/openstack/octavia/blob/27e5b27d31c695ba72fb6750de2bdafd76e0d7d9/octavia/amphorae/drivers/keepalived/vrrp_rest_driver.py#L32-L65
GoogleCloudPlatform/endpoints-proto-datastore
99bed0b39762a86606dd22de57b5eaf1cfa8f40f
endpoints_proto_datastore/utils.py
python
MessageFieldsSchema._DefaultName
(self, basename='')
return '_'.join(name_parts)
The default name of the fields schema. Can potentially use a basename at the front, but otherwise uses the instance fields and joins all the values together using an underscore. Args: basename: An optional string, defaults to the empty string. If not empty, is used at the front of the default name. Returns: A string containing the default name of the fields schema.
The default name of the fields schema.
[ "The", "default", "name", "of", "the", "fields", "schema", "." ]
def _DefaultName(self, basename=''): """The default name of the fields schema. Can potentially use a basename at the front, but otherwise uses the instance fields and joins all the values together using an underscore. Args: basename: An optional string, defaults to the empty string. If not empty, is used at the front of the default name. Returns: A string containing the default name of the fields schema. """ name_parts = [] if basename: name_parts.append(basename) name_parts.extend(self._data) return '_'.join(name_parts)
[ "def", "_DefaultName", "(", "self", ",", "basename", "=", "''", ")", ":", "name_parts", "=", "[", "]", "if", "basename", ":", "name_parts", ".", "append", "(", "basename", ")", "name_parts", ".", "extend", "(", "self", ".", "_data", ")", "return", "'_'...
https://github.com/GoogleCloudPlatform/endpoints-proto-datastore/blob/99bed0b39762a86606dd22de57b5eaf1cfa8f40f/endpoints_proto_datastore/utils.py#L166-L183
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
docs/conch/benchmarks/buffering_mixin.py
python
main
(args=None)
Perform a single benchmark run, starting and stopping the reactor and logging system as necessary.
Perform a single benchmark run, starting and stopping the reactor and logging system as necessary.
[ "Perform", "a", "single", "benchmark", "run", "starting", "and", "stopping", "the", "reactor", "and", "logging", "system", "as", "necessary", "." ]
def main(args=None): """ Perform a single benchmark run, starting and stopping the reactor and logging system as necessary. """ startLogging(stdout) options = BufferingBenchmark() options.parseOptions(args) d = benchmark(options["scale"]) def cbBenchmark(result): pprint(result) def ebBenchmark(err): print(err.getTraceback()) d.addCallbacks(cbBenchmark, ebBenchmark) def stopReactor(ign): reactor.stop() d.addBoth(stopReactor) reactor.run()
[ "def", "main", "(", "args", "=", "None", ")", ":", "startLogging", "(", "stdout", ")", "options", "=", "BufferingBenchmark", "(", ")", "options", ".", "parseOptions", "(", "args", ")", "d", "=", "benchmark", "(", "options", "[", "\"scale\"", "]", ")", ...
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/docs/conch/benchmarks/buffering_mixin.py#L161-L185
cantools/cantools
8d86d61bc010f328cf414150331fecfd4b6f4dc3
cantools/database/can/message.py
python
Message.encode
(self, data: Dict[str, float], scaling: bool = True, padding: bool = False, strict: bool = True, )
return binascii.unhexlify(encoded)[:self._length]
Encode given data as a message of this type. If `scaling` is ``False`` no scaling of signals is performed. If `padding` is ``True`` unused bits are encoded as 1. If `strict` is ``True`` the specified signals must exactly be the ones expected, and their values must be within their allowed ranges, or an `EncodeError` exception is raised. >>> foo = db.get_message_by_name('Foo') >>> foo.encode({'Bar': 1, 'Fum': 5.0}) b'\\x01\\x45\\x23\\x00\\x11'
Encode given data as a message of this type.
[ "Encode", "given", "data", "as", "a", "message", "of", "this", "type", "." ]
def encode(self, data: Dict[str, float], scaling: bool = True, padding: bool = False, strict: bool = True, ) -> bytes: """Encode given data as a message of this type. If `scaling` is ``False`` no scaling of signals is performed. If `padding` is ``True`` unused bits are encoded as 1. If `strict` is ``True`` the specified signals must exactly be the ones expected, and their values must be within their allowed ranges, or an `EncodeError` exception is raised. >>> foo = db.get_message_by_name('Foo') >>> foo.encode({'Bar': 1, 'Fum': 5.0}) b'\\x01\\x45\\x23\\x00\\x11' """ encoded, padding_mask, all_signals = \ self._encode(self._codecs, data, scaling, strict=strict) if strict: self._check_unknown_signals(all_signals, data) if padding: encoded |= padding_mask encoded |= (0x80 << (8 * self._length)) encoded = hex(encoded)[4:].rstrip('L') return binascii.unhexlify(encoded)[:self._length]
[ "def", "encode", "(", "self", ",", "data", ":", "Dict", "[", "str", ",", "float", "]", ",", "scaling", ":", "bool", "=", "True", ",", "padding", ":", "bool", "=", "False", ",", "strict", ":", "bool", "=", "True", ",", ")", "->", "bytes", ":", "...
https://github.com/cantools/cantools/blob/8d86d61bc010f328cf414150331fecfd4b6f4dc3/cantools/database/can/message.py#L464-L498
Cysu/dgd_person_reid
19c2a056219574b0f64aaf7993c51339e28d81a1
tools/save_joint_impact_score.py
python
main
(args)
[]
def main(args): domain_datum = load_domain_impact(args.impact_dir) file_paths = read_list(args.image_list_file) if osp.isdir(args.output_lmdb): shutil.rmtree(args.output_lmdb) with lmdb.open(args.output_lmdb, map_size=1099511627776) as db: with db.begin(write=True) as txn: for i, file_path in enumerate(file_paths): find_match = False for domain, datum in domain_datum.iteritems(): if domain not in file_path: continue txn.put('{:010d}_{}'.format(i, domain), datum) find_match = True break if not find_match: print "Warning: cannot find the domain of {}".format( file_path)
[ "def", "main", "(", "args", ")", ":", "domain_datum", "=", "load_domain_impact", "(", "args", ".", "impact_dir", ")", "file_paths", "=", "read_list", "(", "args", ".", "image_list_file", ")", "if", "osp", ".", "isdir", "(", "args", ".", "output_lmdb", ")",...
https://github.com/Cysu/dgd_person_reid/blob/19c2a056219574b0f64aaf7993c51339e28d81a1/tools/save_joint_impact_score.py#L38-L53
facebookresearch/SlowFast
39ef35c9a086443209b458cceaec86a02e27b369
slowfast/utils/ava_evaluation/np_box_list_ops.py
python
intersection
(boxlist1, boxlist2)
return np_box_ops.intersection(boxlist1.get(), boxlist2.get())
Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area
Compute pairwise intersection areas between boxes.
[ "Compute", "pairwise", "intersection", "areas", "between", "boxes", "." ]
def intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes Returns: a numpy array with shape [N*M] representing pairwise intersection area """ return np_box_ops.intersection(boxlist1.get(), boxlist2.get())
[ "def", "intersection", "(", "boxlist1", ",", "boxlist2", ")", ":", "return", "np_box_ops", ".", "intersection", "(", "boxlist1", ".", "get", "(", ")", ",", "boxlist2", ".", "get", "(", ")", ")" ]
https://github.com/facebookresearch/SlowFast/blob/39ef35c9a086443209b458cceaec86a02e27b369/slowfast/utils/ava_evaluation/np_box_list_ops.py#L58-L68
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/pyrepl/reader.py
python
Reader.bow
(self, p=None)
return p + 1
Return the 0-based index of the word break preceding p most immediately. p defaults to self.pos; word boundaries are determined using self.syntax_table.
Return the 0-based index of the word break preceding p most immediately.
[ "Return", "the", "0", "-", "based", "index", "of", "the", "word", "break", "preceding", "p", "most", "immediately", "." ]
def bow(self, p=None): """Return the 0-based index of the word break preceding p most immediately. p defaults to self.pos; word boundaries are determined using self.syntax_table.""" if p is None: p = self.pos st = self.syntax_table b = self.buffer p -= 1 while p >= 0 and st.get(b[p], SYNTAX_WORD) <> SYNTAX_WORD: p -= 1 while p >= 0 and st.get(b[p], SYNTAX_WORD) == SYNTAX_WORD: p -= 1 return p + 1
[ "def", "bow", "(", "self", ",", "p", "=", "None", ")", ":", "if", "p", "is", "None", ":", "p", "=", "self", ".", "pos", "st", "=", "self", ".", "syntax_table", "b", "=", "self", ".", "buffer", "p", "-=", "1", "while", "p", ">=", "0", "and", ...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/pyrepl/reader.py#L339-L354
realsirjoe/instagram-scraper
0b71972eecb239724c8dbe23e35b9c366b889619
igramscraper/instagram.py
python
Instagram.set_account_medias_request_count
(count)
Set how many media objects should be retrieved in a single request param int count
Set how many media objects should be retrieved in a single request param int count
[ "Set", "how", "many", "media", "objects", "should", "be", "retrieved", "in", "a", "single", "request", "param", "int", "count" ]
def set_account_medias_request_count(count): """ Set how many media objects should be retrieved in a single request param int count """ endpoints.request_media_count = count
[ "def", "set_account_medias_request_count", "(", "count", ")", ":", "endpoints", ".", "request_media_count", "=", "count" ]
https://github.com/realsirjoe/instagram-scraper/blob/0b71972eecb239724c8dbe23e35b9c366b889619/igramscraper/instagram.py#L106-L111
makerdao/pymaker
9245b3e22bcb257004d54337df6c2b0c9cbe42c8
pymaker/shutdown.py
python
End.flow
(self, ilk: Ilk)
return Transact(self, self.web3, self.abi, self.address, self._contract, 'flow', [ilk.toBytes()])
Calculate the `fix`, the cash price for a given collateral
Calculate the `fix`, the cash price for a given collateral
[ "Calculate", "the", "fix", "the", "cash", "price", "for", "a", "given", "collateral" ]
def flow(self, ilk: Ilk) -> Transact: """Calculate the `fix`, the cash price for a given collateral""" assert isinstance(ilk, Ilk) return Transact(self, self.web3, self.abi, self.address, self._contract, 'flow', [ilk.toBytes()])
[ "def", "flow", "(", "self", ",", "ilk", ":", "Ilk", ")", "->", "Transact", ":", "assert", "isinstance", "(", "ilk", ",", "Ilk", ")", "return", "Transact", "(", "self", ",", "self", ".", "web3", ",", "self", ".", "abi", ",", "self", ".", "address", ...
https://github.com/makerdao/pymaker/blob/9245b3e22bcb257004d54337df6c2b0c9cbe42c8/pymaker/shutdown.py#L187-L190
menpo/menpofit
5f2f45bab26df206d43292fd32d19cd8f62f0443
menpofit/modelinstance.py
python
ModelInstance._as_vector
(self)
return self.weights
r""" Return the current parameters of this transform - this is the just the linear model's weights Returns ------- params : (`n_parameters`,) ndarray The vector of parameters
r""" Return the current parameters of this transform - this is the just the linear model's weights
[ "r", "Return", "the", "current", "parameters", "of", "this", "transform", "-", "this", "is", "the", "just", "the", "linear", "model", "s", "weights" ]
def _as_vector(self): r""" Return the current parameters of this transform - this is the just the linear model's weights Returns ------- params : (`n_parameters`,) ndarray The vector of parameters """ return self.weights
[ "def", "_as_vector", "(", "self", ")", ":", "return", "self", ".", "weights" ]
https://github.com/menpo/menpofit/blob/5f2f45bab26df206d43292fd32d19cd8f62f0443/menpofit/modelinstance.py#L162-L172
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/scripts/documentation/script_utils.py
python
generate_and_save_artifact
( full_name: str, *, dst_dir: tfds.core.PathLike, overwrite: bool, file_extension: str, get_artifact_fn: Callable[[tf.data.Dataset, tfds.core.DatasetInfo], T], save_artifact_fn: Callable[[str, T], None], )
Builds and save the generated artifact for the dataset in dst_dir. Args: full_name: Name of the dataset to build `dataset`, `dataset/config`. dst_dir: Destination where the dataset will be saved (as `dataset-config-version`) overwrite: If True, recompute the image even if it exists. file_extension: File extension of the artifact (e.g. `.png`) get_artifact_fn: Function which extracts the dataset artifact to save. save_artifact_fn: Function which save the extracted artifact.
Builds and save the generated artifact for the dataset in dst_dir.
[ "Builds", "and", "save", "the", "generated", "artifact", "for", "the", "dataset", "in", "dst_dir", "." ]
def generate_and_save_artifact( full_name: str, *, dst_dir: tfds.core.PathLike, overwrite: bool, file_extension: str, get_artifact_fn: Callable[[tf.data.Dataset, tfds.core.DatasetInfo], T], save_artifact_fn: Callable[[str, T], None], ) -> None: """Builds and save the generated artifact for the dataset in dst_dir. Args: full_name: Name of the dataset to build `dataset`, `dataset/config`. dst_dir: Destination where the dataset will be saved (as `dataset-config-version`) overwrite: If True, recompute the image even if it exists. file_extension: File extension of the artifact (e.g. `.png`) get_artifact_fn: Function which extracts the dataset artifact to save. save_artifact_fn: Function which save the extracted artifact. """ dst_filename = full_name.replace('/', '-') + file_extension dst_path = os.path.join(dst_dir, dst_filename) # If the file already exists, skip the generation if not overwrite and tf.io.gfile.exists(dst_path): logging.info(f'Skipping generation for {full_name} (already exists)') return logging.info(f'Generating for {full_name}...') # Load the dataset. builder_name, _, version = full_name.rpartition('/') builder = tfds.builder(f'{builder_name}:{version}') split_names = list(builder.info.splits.keys()) if not split_names: logging.info(f'Dataset `{full_name}` not generated.') return elif 'train' in split_names: split = 'train' else: split = split_names[0] ds = builder.as_dataset(split=split, shuffle_files=False) if not tf.io.gfile.exists(dst_dir): tf.io.gfile.makedirs(dst_dir) try: artifact = get_artifact_fn(ds.take(10), builder.info) except Exception: # pylint: disable=broad-except logging.info(f'Generation not supported for dataset `{full_name}`') return save_artifact_fn(dst_path, artifact)
[ "def", "generate_and_save_artifact", "(", "full_name", ":", "str", ",", "*", ",", "dst_dir", ":", "tfds", ".", "core", ".", "PathLike", ",", "overwrite", ":", "bool", ",", "file_extension", ":", "str", ",", "get_artifact_fn", ":", "Callable", "[", "[", "tf...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/scripts/documentation/script_utils.py#L55-L103
huseinzol05/Gather-Deployment
f8c71f387356b43a73039a629fae025825b1013c
tensorflow/6.inception-flasksocketio/inception_utils.py
python
inception_arg_scope
(weight_decay=0.00004, use_batch_norm=True, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS)
Defines the default arg scope for inception models. Args: weight_decay: The weight decay to use for regularizing the model. use_batch_norm: "If `True`, batch_norm is applied after each convolution. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. Returns: An `arg_scope` to use for the inception models.
Defines the default arg scope for inception models.
[ "Defines", "the", "default", "arg", "scope", "for", "inception", "models", "." ]
def inception_arg_scope(weight_decay=0.00004, use_batch_norm=True, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS): """Defines the default arg scope for inception models. Args: weight_decay: The weight decay to use for regularizing the model. use_batch_norm: "If `True`, batch_norm is applied after each convolution. batch_norm_decay: Decay for batch norm moving average. batch_norm_epsilon: Small float added to variance to avoid dividing by zero in batch norm. activation_fn: Activation function for conv2d. batch_norm_updates_collections: Collection for the update ops for batch norm. Returns: An `arg_scope` to use for the inception models. """ batch_norm_params = { # Decay for the moving averages. 'decay': batch_norm_decay, # epsilon to prevent 0s in variance. 'epsilon': batch_norm_epsilon, # collection containing update_ops. 'updates_collections': batch_norm_updates_collections, # use fused batch norm if possible. 'fused': None, } if use_batch_norm: normalizer_fn = slim.batch_norm normalizer_params = batch_norm_params else: normalizer_fn = None normalizer_params = {} # Set weight_decay for weights in Conv and FC layers. with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay)): with slim.arg_scope( [slim.conv2d], weights_initializer=slim.variance_scaling_initializer(), activation_fn=activation_fn, normalizer_fn=normalizer_fn, normalizer_params=normalizer_params) as sc: return sc
[ "def", "inception_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "use_batch_norm", "=", "True", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "batch_norm_upda...
https://github.com/huseinzol05/Gather-Deployment/blob/f8c71f387356b43a73039a629fae025825b1013c/tensorflow/6.inception-flasksocketio/inception_utils.py#L32-L78
deepchem/deepchem
054eb4b2b082e3df8e1a8e77f36a52137ae6e375
contrib/one_shot_models/graph_topology.py
python
WeaveGraphTopology.__init__
(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14, name='Weave_topology')
Parameters ---------- max_atoms: int, optional maximum number of atoms in a molecule n_atom_feat: int, optional number of basic features of each atom n_pair_feat: int, optional number of basic features of each pair
Parameters ---------- max_atoms: int, optional maximum number of atoms in a molecule n_atom_feat: int, optional number of basic features of each atom n_pair_feat: int, optional number of basic features of each pair
[ "Parameters", "----------", "max_atoms", ":", "int", "optional", "maximum", "number", "of", "atoms", "in", "a", "molecule", "n_atom_feat", ":", "int", "optional", "number", "of", "basic", "features", "of", "each", "atom", "n_pair_feat", ":", "int", "optional", ...
def __init__(self, max_atoms=50, n_atom_feat=75, n_pair_feat=14, name='Weave_topology'): """ Parameters ---------- max_atoms: int, optional maximum number of atoms in a molecule n_atom_feat: int, optional number of basic features of each atom n_pair_feat: int, optional number of basic features of each pair """ warnings.warn("WeaveGraphTopology is deprecated. " "Will be removed in DeepChem 1.4.", DeprecationWarning) #self.n_atoms = n_atoms self.name = name self.max_atoms = max_atoms self.n_atom_feat = n_atom_feat self.n_pair_feat = n_pair_feat self.atom_features_placeholder = tf.placeholder( dtype='float32', shape=(None, self.max_atoms, self.n_atom_feat), name=self.name + '_atom_features') self.atom_mask_placeholder = tf.placeholder( dtype='float32', shape=(None, self.max_atoms), name=self.name + '_atom_mask') self.pair_features_placeholder = tf.placeholder( dtype='float32', shape=(None, self.max_atoms, self.max_atoms, self.n_pair_feat), name=self.name + '_pair_features') self.pair_mask_placeholder = tf.placeholder( dtype='float32', shape=(None, self.max_atoms, self.max_atoms), name=self.name + '_pair_mask') self.membership_placeholder = tf.placeholder( dtype='int32', shape=(None,), name=self.name + '_membership') # Define the list of tensors to be used as topology self.topology = [self.atom_mask_placeholder, self.pair_mask_placeholder] self.inputs = [self.atom_features_placeholder] self.inputs += self.topology
[ "def", "__init__", "(", "self", ",", "max_atoms", "=", "50", ",", "n_atom_feat", "=", "75", ",", "n_pair_feat", "=", "14", ",", "name", "=", "'Weave_topology'", ")", ":", "warnings", ".", "warn", "(", "\"WeaveGraphTopology is deprecated. \"", "\"Will be removed ...
https://github.com/deepchem/deepchem/blob/054eb4b2b082e3df8e1a8e77f36a52137ae6e375/contrib/one_shot_models/graph_topology.py#L389-L434
deanishe/alfred-stackexchange
b2047b76165900d55f0c7d18fd7c40131bee94ed
src/workflow/notify.py
python
install_notifier
()
Extract ``Notify.app`` from the workflow to data directory. Changes the bundle ID of the installed app and gives it the workflow's icon.
Extract ``Notify.app`` from the workflow to data directory.
[ "Extract", "Notify", ".", "app", "from", "the", "workflow", "to", "data", "directory", "." ]
def install_notifier(): """Extract ``Notify.app`` from the workflow to data directory. Changes the bundle ID of the installed app and gives it the workflow's icon. """ archive = os.path.join(os.path.dirname(__file__), 'Notify.tgz') destdir = wf().datadir app_path = os.path.join(destdir, 'Notify.app') n = notifier_program() log().debug('installing Notify.app to %r ...', destdir) # z = zipfile.ZipFile(archive, 'r') # z.extractall(destdir) tgz = tarfile.open(archive, 'r:gz') tgz.extractall(destdir) assert os.path.exists(n), \ 'Notify.app could not be installed in %s' % destdir # Replace applet icon icon = notifier_icon_path() workflow_icon = wf().workflowfile('icon.png') if os.path.exists(icon): os.unlink(icon) png_to_icns(workflow_icon, icon) # Set file icon # PyObjC isn't available for 2.6, so this is 2.7 only. Actually, # none of this code will "work" on pre-10.8 systems. Let it run # until I figure out a better way of excluding this module # from coverage in py2.6. if sys.version_info >= (2, 7): # pragma: no cover from AppKit import NSWorkspace, NSImage ws = NSWorkspace.sharedWorkspace() img = NSImage.alloc().init() img.initWithContentsOfFile_(icon) ws.setIcon_forFile_options_(img, app_path, 0) # Change bundle ID of installed app ip_path = os.path.join(app_path, 'Contents/Info.plist') bundle_id = '{0}.{1}'.format(wf().bundleid, uuid.uuid4().hex) data = plistlib.readPlist(ip_path) log().debug('changing bundle ID to %r', bundle_id) data['CFBundleIdentifier'] = bundle_id plistlib.writePlist(data, ip_path)
[ "def", "install_notifier", "(", ")", ":", "archive", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'Notify.tgz'", ")", "destdir", "=", "wf", "(", ")", ".", "datadir", "app_path", "=", "os", ...
https://github.com/deanishe/alfred-stackexchange/blob/b2047b76165900d55f0c7d18fd7c40131bee94ed/src/workflow/notify.py#L105-L150
trailofbits/manticore
b050fdf0939f6c63f503cdf87ec0ab159dd41159
manticore/utils/helpers.py
python
interval_intersection
(min1, max1, min2, max2)
return None
Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval, or None if they do not overlap.
Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval, or None if they do not overlap.
[ "Given", "two", "intervals", "(", "min1", "max1", ")", "and", "(", "min2", "max2", ")", "return", "their", "intersecting", "interval", "or", "None", "if", "they", "do", "not", "overlap", "." ]
def interval_intersection(min1, max1, min2, max2): """ Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval, or None if they do not overlap. """ left, right = max(min1, min2), min(max1, max2) if left < right: return left, right return None
[ "def", "interval_intersection", "(", "min1", ",", "max1", ",", "min2", ",", "max2", ")", ":", "left", ",", "right", "=", "max", "(", "min1", ",", "min2", ")", ",", "min", "(", "max1", ",", "max2", ")", "if", "left", "<", "right", ":", "return", "...
https://github.com/trailofbits/manticore/blob/b050fdf0939f6c63f503cdf87ec0ab159dd41159/manticore/utils/helpers.py#L28-L36
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_13/paramiko/agent.py
python
AgentKey.__init__
(self, agent, blob)
[]
def __init__(self, agent, blob): self.agent = agent self.blob = blob self.name = Message(blob).get_string()
[ "def", "__init__", "(", "self", ",", "agent", ",", "blob", ")", ":", "self", ".", "agent", "=", "agent", "self", ".", "blob", "=", "blob", "self", ".", "name", "=", "Message", "(", "blob", ")", ".", "get_string", "(", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/paramiko/agent.py#L360-L363
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/pptx/oxml/slide.py
python
CT_Slide._childTnLst
(self)
return childTnLsts[0]
Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. Return None if that element is not present.
Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
[ "Return", ".", "/", "p", ":", "timing", "/", "p", ":", "tnLst", "/", "p", ":", "par", "/", "p", ":", "cTn", "/", "p", ":", "childTnLst", "descendant", "." ]
def _childTnLst(self): """Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant. Return None if that element is not present. """ childTnLsts = self.xpath( './p:timing/p:tnLst/p:par/p:cTn/p:childTnLst' ) if not childTnLsts: return None return childTnLsts[0]
[ "def", "_childTnLst", "(", "self", ")", ":", "childTnLsts", "=", "self", ".", "xpath", "(", "'./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst'", ")", "if", "not", "childTnLsts", ":", "return", "None", "return", "childTnLsts", "[", "0", "]" ]
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/pptx/oxml/slide.py#L129-L139
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Tools/webchecker/webchecker.py
python
Checker.run
(self)
[]
def run(self): while self.todo: self.round = self.round + 1 self.note(0, "\nRound %d (%s)\n", self.round, self.status()) urls = self.todo.keys() urls.sort() del urls[self.roundsize:] for url in urls: self.dopage(url)
[ "def", "run", "(", "self", ")", ":", "while", "self", ".", "todo", ":", "self", ".", "round", "=", "self", ".", "round", "+", "1", "self", ".", "note", "(", "0", ",", "\"\\nRound %d (%s)\\n\"", ",", "self", ".", "round", ",", "self", ".", "status",...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Tools/webchecker/webchecker.py#L341-L349
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dns/rdtypes/ANY/CERT.py
python
_ctype_from_text
(what)
return int(what)
[]
def _ctype_from_text(what): v = _ctype_by_name.get(what) if v is not None: return v return int(what)
[ "def", "_ctype_from_text", "(", "what", ")", ":", "v", "=", "_ctype_by_name", ".", "get", "(", "what", ")", "if", "v", "is", "not", "None", ":", "return", "v", "return", "int", "(", "what", ")" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dns/rdtypes/ANY/CERT.py#L43-L47
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
PySimpleGUIWx/PySimpleGUIWx.py
python
Window.Finalize
(self)
return self
[]
def Finalize(self): if self.TKrootDestroyed: return self if not self.Shown: self.Show(non_blocking=True) # else: # try: # self.QTApplication.processEvents() # refresh the window # except: # print('* ERROR FINALIZING *') # self.TKrootDestroyed = True # Window.DecrementOpenCount() return self
[ "def", "Finalize", "(", "self", ")", ":", "if", "self", ".", "TKrootDestroyed", ":", "return", "self", "if", "not", "self", ".", "Shown", ":", "self", ".", "Show", "(", "non_blocking", "=", "True", ")", "# else:", "# try:", "# self.QTApplication....
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUIWx/PySimpleGUIWx.py#L3192-L3204
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
cacti/datadog_checks/cacti/config_models/instance.py
python
InstanceConfig._ensure_defaults
(cls, v, field)
return getattr(defaults, f'instance_{field.name}')(field, v)
[]
def _ensure_defaults(cls, v, field): if v is not None or field.required: return v return getattr(defaults, f'instance_{field.name}')(field, v)
[ "def", "_ensure_defaults", "(", "cls", ",", "v", ",", "field", ")", ":", "if", "v", "is", "not", "None", "or", "field", ".", "required", ":", "return", "v", "return", "getattr", "(", "defaults", ",", "f'instance_{field.name}'", ")", "(", "field", ",", ...
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/cacti/datadog_checks/cacti/config_models/instance.py#L45-L49
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
calendarserver/tap/caldav.py
python
DelayedStartupProcessMonitor.addProcess
(self, name, args, uid=None, gid=None, env={})
Add a new monitored process and start it immediately if the L{DelayedStartupProcessMonitor} service is running. Note that args are passed to the system call, not to the shell. If running the shell is desired, the common idiom is to use C{ProcessMonitor.addProcess("name", ['/bin/sh', '-c', shell_script])} @param name: A name for this process. This value must be unique across all processes added to this monitor. @type name: C{str} @param args: The argv sequence for the process to launch. @param uid: The user ID to use to run the process. If C{None}, the current UID is used. @type uid: C{int} @param gid: The group ID to use to run the process. If C{None}, the current GID is used. @type uid: C{int} @param env: The environment to give to the launched process. See L{IReactorProcess.spawnProcess}'s C{env} parameter. @type env: C{dict} @raises: C{KeyError} if a process with the given name already exists
Add a new monitored process and start it immediately if the L{DelayedStartupProcessMonitor} service is running.
[ "Add", "a", "new", "monitored", "process", "and", "start", "it", "immediately", "if", "the", "L", "{", "DelayedStartupProcessMonitor", "}", "service", "is", "running", "." ]
def addProcess(self, name, args, uid=None, gid=None, env={}): """ Add a new monitored process and start it immediately if the L{DelayedStartupProcessMonitor} service is running. Note that args are passed to the system call, not to the shell. If running the shell is desired, the common idiom is to use C{ProcessMonitor.addProcess("name", ['/bin/sh', '-c', shell_script])} @param name: A name for this process. This value must be unique across all processes added to this monitor. @type name: C{str} @param args: The argv sequence for the process to launch. @param uid: The user ID to use to run the process. If C{None}, the current UID is used. @type uid: C{int} @param gid: The group ID to use to run the process. If C{None}, the current GID is used. @type uid: C{int} @param env: The environment to give to the launched process. See L{IReactorProcess.spawnProcess}'s C{env} parameter. @type env: C{dict} @raises: C{KeyError} if a process with the given name already exists """ class SimpleProcessObject(object): def starting(self): pass def stopped(self): pass def getName(self): return name def getCommandLine(self): return args def getFileDescriptors(self): return [] self.addProcessObject(SimpleProcessObject(), env, uid, gid)
[ "def", "addProcess", "(", "self", ",", "name", ",", "args", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "env", "=", "{", "}", ")", ":", "class", "SimpleProcessObject", "(", "object", ")", ":", "def", "starting", "(", "self", ")", ":", ...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/calendarserver/tap/caldav.py#L2258-L2300
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/teams/serializers.py
python
CountryField.to_internal_value
(self, data)
return data
Check that the code is a valid country code. We leave the data in its original format so that the Django model's CountryField can convert it to the internal representation used by the django-countries library.
Check that the code is a valid country code.
[ "Check", "that", "the", "code", "is", "a", "valid", "country", "code", "." ]
def to_internal_value(self, data): """ Check that the code is a valid country code. We leave the data in its original format so that the Django model's CountryField can convert it to the internal representation used by the django-countries library. """ if data and data not in self.COUNTRY_CODES: raise serializers.ValidationError( f"{data} is not a valid country code" ) return data
[ "def", "to_internal_value", "(", "self", ",", "data", ")", ":", "if", "data", "and", "data", "not", "in", "self", ".", "COUNTRY_CODES", ":", "raise", "serializers", ".", "ValidationError", "(", "f\"{data} is not a valid country code\"", ")", "return", "data" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/teams/serializers.py#L33-L45
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/multiprocessing/pool.py
python
Pool._handle_results
(outqueue, get, cache)
[]
def _handle_results(outqueue, get, cache): thread = threading.current_thread() while 1: try: task = get() except (IOError, EOFError): debug('result handler got EOFError/IOError -- exiting') return if thread._state: assert thread._state == TERMINATE debug('result handler found thread._state=TERMINATE') break if task is None: debug('result handler got sentinel') break job, i, obj = task try: cache[job]._set(i, obj) except KeyError: pass while cache and thread._state != TERMINATE: try: task = get() except (IOError, EOFError): debug('result handler got EOFError/IOError -- exiting') return if task is None: debug('result handler ignoring extra sentinel') continue job, i, obj = task try: cache[job]._set(i, obj) except KeyError: pass if hasattr(outqueue, '_reader'): debug('ensuring that outqueue is not full') # If we don't make room available in outqueue then # attempts to add the sentinel (None) to outqueue may # block. There is guaranteed to be no more than 2 sentinels. try: for i in range(10): if not outqueue._reader.poll(): break get() except (IOError, EOFError): pass debug('result handler exiting: len(cache)=%s, thread._state=%s', len(cache), thread._state)
[ "def", "_handle_results", "(", "outqueue", ",", "get", ",", "cache", ")", ":", "thread", "=", "threading", ".", "current_thread", "(", ")", "while", "1", ":", "try", ":", "task", "=", "get", "(", ")", "except", "(", "IOError", ",", "EOFError", ")", "...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/multiprocessing/pool.py#L375-L430
schemathesis/schemathesis
2eaea40be33067af5f5f6b6b7a79000224e1bbd2
src/schemathesis/specs/openapi/_hypothesis.py
python
get_parameters_strategy
( operation: APIOperation, to_strategy: StrategyFactory, location: str, exclude: Iterable[str] = (), )
return st.none()
Create a new strategy for the case's component from the API operation parameters.
Create a new strategy for the case's component from the API operation parameters.
[ "Create", "a", "new", "strategy", "for", "the", "case", "s", "component", "from", "the", "API", "operation", "parameters", "." ]
def get_parameters_strategy( operation: APIOperation, to_strategy: StrategyFactory, location: str, exclude: Iterable[str] = (), ) -> st.SearchStrategy: """Create a new strategy for the case's component from the API operation parameters.""" parameters = getattr(operation, LOCATION_TO_CONTAINER[location]) if parameters: # The cache key relies on object ids, which means that the parameter should not be mutated nested_cache_key = (to_strategy, location, tuple(sorted(exclude))) if operation in _PARAMETER_STRATEGIES_CACHE and nested_cache_key in _PARAMETER_STRATEGIES_CACHE[operation]: return _PARAMETER_STRATEGIES_CACHE[operation][nested_cache_key] schema = parameters_to_json_schema(parameters) if not operation.schema.validate_schema and location == "path": # If schema validation is disabled, we try to generate data even if the parameter definition # contains errors. # In this case, we know that the `required` keyword should always be `True`. schema["required"] = list(schema["properties"]) schema = operation.schema.prepare_schema(schema) for name in exclude: # Values from `exclude` are not necessarily valid for the schema - they come from user-defined examples # that may be invalid schema["properties"].pop(name, None) with suppress(ValueError): schema["required"].remove(name) strategy = to_strategy(schema, operation.verbose_name, location, None) serialize = operation.get_parameter_serializer(location) if serialize is not None: strategy = strategy.map(serialize) filter_func = { "path": is_valid_path, "header": is_valid_header, "cookie": is_valid_header, "query": is_valid_query, }[location] # Headers with special format do not need filtration if not (is_header_location(location) and _can_skip_header_filter(schema)): strategy = strategy.filter(filter_func) # Path & query parameters will be cast to string anyway, but having their JSON equivalents for # `True` / `False` / `None` improves chances of them passing validation in apps that expect boolean / null types # and not aware of Python-specific representation of those types map_func = { "path": compose(quote_all, jsonify_python_specific_types), "query": jsonify_python_specific_types, }.get(location) if map_func: strategy = strategy.map(map_func) # type: ignore _PARAMETER_STRATEGIES_CACHE.setdefault(operation, {})[nested_cache_key] = strategy return strategy # No parameters defined for this location return st.none()
[ "def", "get_parameters_strategy", "(", "operation", ":", "APIOperation", ",", "to_strategy", ":", "StrategyFactory", ",", "location", ":", "str", ",", "exclude", ":", "Iterable", "[", "str", "]", "=", "(", ")", ",", ")", "->", "st", ".", "SearchStrategy", ...
https://github.com/schemathesis/schemathesis/blob/2eaea40be33067af5f5f6b6b7a79000224e1bbd2/src/schemathesis/specs/openapi/_hypothesis.py#L253-L304
GadgetReactor/pyHS100
e03c192c8ca5a22116fd7605151d8bb10d0255e1
pyHS100/smartbulb.py
python
SmartBulb.color_temp
(self)
Return color temperature of the device. :return: Color temperature in Kelvin :rtype: int
Return color temperature of the device.
[ "Return", "color", "temperature", "of", "the", "device", "." ]
def color_temp(self) -> int: """Return color temperature of the device. :return: Color temperature in Kelvin :rtype: int """ if not self.is_variable_color_temp: raise SmartDeviceException("Bulb does not support colortemp.") light_state = self.get_light_state() if not self.is_on: return int(light_state["dft_on_state"]["color_temp"]) else: return int(light_state["color_temp"])
[ "def", "color_temp", "(", "self", ")", "->", "int", ":", "if", "not", "self", ".", "is_variable_color_temp", ":", "raise", "SmartDeviceException", "(", "\"Bulb does not support colortemp.\"", ")", "light_state", "=", "self", ".", "get_light_state", "(", ")", "if",...
https://github.com/GadgetReactor/pyHS100/blob/e03c192c8ca5a22116fd7605151d8bb10d0255e1/pyHS100/smartbulb.py#L191-L204
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/mako/runtime.py
python
CallerStack._get_caller
(self)
return self[-1]
[]
def _get_caller(self): # this method can be removed once # codegen MAGIC_NUMBER moves past 7 return self[-1]
[ "def", "_get_caller", "(", "self", ")", ":", "# this method can be removed once", "# codegen MAGIC_NUMBER moves past 7", "return", "self", "[", "-", "1", "]" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mako/runtime.py#L195-L198
getsentry/sentry
83b1f25aac3e08075e0e2495bc29efaf35aca18a
src/sentry/runner/commands/django.py
python
django
(ctx, management_args)
Execute Django subcommands.
Execute Django subcommands.
[ "Execute", "Django", "subcommands", "." ]
def django(ctx, management_args): "Execute Django subcommands." from django.core.management import execute_from_command_line execute_from_command_line(argv=[ctx.command_path] + list(management_args))
[ "def", "django", "(", "ctx", ",", "management_args", ")", ":", "from", "django", ".", "core", ".", "management", "import", "execute_from_command_line", "execute_from_command_line", "(", "argv", "=", "[", "ctx", ".", "command_path", "]", "+", "list", "(", "mana...
https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/runner/commands/django.py#L10-L14
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/cryptography/x509/ocsp.py
python
OCSPRequestBuilder.build
(self)
return backend.create_ocsp_request(self)
[]
def build(self): from cryptography.hazmat.backends.openssl.backend import backend if self._request is None: raise ValueError("You must add a certificate before building") return backend.create_ocsp_request(self)
[ "def", "build", "(", "self", ")", ":", "from", "cryptography", ".", "hazmat", ".", "backends", ".", "openssl", ".", "backend", "import", "backend", "if", "self", ".", "_request", "is", "None", ":", "raise", "ValueError", "(", "\"You must add a certificate befo...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/cryptography/x509/ocsp.py#L106-L111
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modular/modform_hecketriangle/hecke_triangle_group_element.py
python
HeckeTriangleGroupElement.primitive_power
(self, method="cf")
return power*power_sign
r""" Return the primitive power of ``self``. I.e. an integer ``power`` such that ``self = sign * primitive_part^power``, where ``sign = self.sign()`` and ``primitive_part = self.primitive_part(method)``. Warning: For the parabolic case the sign depends on the method: The "cf" method may return a negative power but the "block" method never will. Warning: The case ``n=infinity`` is not verified at all and probably wrong! INPUT: - ``method`` -- The method used to determine the primitive power (see :meth:`primitive_representative`), default: "cf". The parameter is ignored for elliptic elements or +- the identity. OUTPUT: An integer. For +- the identity element ``0`` is returned, for parabolic and hyperbolic elements a positive integer. And for elliptic elements a (non-zero) integer with minimal absolute value such that ``primitive_part^power`` still has a positive sign. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup sage: G = HeckeTriangleGroup(n=7) sage: G.T().primitive_power() -1 sage: G.V(2).acton(G.T(-3)).primitive_power() 3 sage: (-G.V(2)^2).primitive_power() 2 sage: el = (-G.V(2)*G.V(6)*G.V(3)*G.V(2)*G.V(6)*G.V(3)) sage: el.primitive_power() 2 sage: (G.U()^4*G.S()*G.V(2)).acton(el).primitive_power() 2 sage: (G.V(2)*G.V(3)).acton(G.U()^6).primitive_power() -1 sage: G.V(2).acton(G.T(-3)).primitive_power() == G.V(2).acton(G.T(-3)).primitive_power(method="block") True sage: (-G.I()).primitive_power() 0 sage: G.U().primitive_power() 1 sage: (-G.S()).primitive_power() 1 sage: el = (G.V(2)*G.V(3)).acton(G.U()^6) sage: el.primitive_power() -1 sage: el.primitive_power() == (-el).primitive_power() True sage: (G.U()^(-6)).primitive_power() 1 sage: G = HeckeTriangleGroup(n=8) sage: (G.U()^4).primitive_power() 4 sage: (G.U()^(-4)).primitive_power() 4
r""" Return the primitive power of ``self``. I.e. an integer ``power`` such that ``self = sign * primitive_part^power``, where ``sign = self.sign()`` and ``primitive_part = self.primitive_part(method)``.
[ "r", "Return", "the", "primitive", "power", "of", "self", ".", "I", ".", "e", ".", "an", "integer", "power", "such", "that", "self", "=", "sign", "*", "primitive_part^power", "where", "sign", "=", "self", ".", "sign", "()", "and", "primitive_part", "=", ...
def primitive_power(self, method="cf"): r""" Return the primitive power of ``self``. I.e. an integer ``power`` such that ``self = sign * primitive_part^power``, where ``sign = self.sign()`` and ``primitive_part = self.primitive_part(method)``. Warning: For the parabolic case the sign depends on the method: The "cf" method may return a negative power but the "block" method never will. Warning: The case ``n=infinity`` is not verified at all and probably wrong! INPUT: - ``method`` -- The method used to determine the primitive power (see :meth:`primitive_representative`), default: "cf". The parameter is ignored for elliptic elements or +- the identity. OUTPUT: An integer. For +- the identity element ``0`` is returned, for parabolic and hyperbolic elements a positive integer. And for elliptic elements a (non-zero) integer with minimal absolute value such that ``primitive_part^power`` still has a positive sign. EXAMPLES:: sage: from sage.modular.modform_hecketriangle.hecke_triangle_groups import HeckeTriangleGroup sage: G = HeckeTriangleGroup(n=7) sage: G.T().primitive_power() -1 sage: G.V(2).acton(G.T(-3)).primitive_power() 3 sage: (-G.V(2)^2).primitive_power() 2 sage: el = (-G.V(2)*G.V(6)*G.V(3)*G.V(2)*G.V(6)*G.V(3)) sage: el.primitive_power() 2 sage: (G.U()^4*G.S()*G.V(2)).acton(el).primitive_power() 2 sage: (G.V(2)*G.V(3)).acton(G.U()^6).primitive_power() -1 sage: G.V(2).acton(G.T(-3)).primitive_power() == G.V(2).acton(G.T(-3)).primitive_power(method="block") True sage: (-G.I()).primitive_power() 0 sage: G.U().primitive_power() 1 sage: (-G.S()).primitive_power() 1 sage: el = (G.V(2)*G.V(3)).acton(G.U()^6) sage: el.primitive_power() -1 sage: el.primitive_power() == (-el).primitive_power() True sage: (G.U()^(-6)).primitive_power() 1 sage: G = HeckeTriangleGroup(n=8) sage: (G.U()^4).primitive_power() 4 sage: (G.U()^(-4)).primitive_power() 4 """ if self.parent().n() == infinity: from warnings import warn warn("The case n=infinity here is not verified at all and probably wrong!") zero = ZZ.zero() one = ZZ.one() two = ZZ(2) if self.is_identity(): return zero if self.is_elliptic(): if self.parent().n() == infinity: raise NotImplementedError (data, R) = self._primitive_block_decomposition_data() if data[0] == 0: return one else: G = self.parent() U = G.U() U_power = R.inverse() * self * R Uj = G.I() for j in range(1, G.n()): Uj *= U if U_power == Uj: #L = [one, ZZ(j)] break elif U_power == -Uj: #L = [one, ZZ(-j)] break else: raise RuntimeError("There is a problem in the method " "'primitive_power'. Please contact sage-devel@googlegroups.com") if abs(j) < G.n()/two: return j elif two*j == G.n(): return j # for the cases fom here on the sign has to be adjusted to the # sign of self (in self._block_decomposition_data()) elif two*j == -G.n(): return -j elif j > 0: return j - G.n() else: return j + G.n() primitive_part = self.primitive_part(method=method) if method == "cf" and self.is_parabolic(): power_sign = coerce_AA(self.trace() * (self[1][0] - self[0][1])).sign() else: power_sign = one normalized_self = self.sign() * self**power_sign M = primitive_part power = 1 while M != normalized_self: M *= primitive_part power += 1 return power*power_sign
[ "def", "primitive_power", "(", "self", ",", "method", "=", "\"cf\"", ")", ":", "if", "self", ".", "parent", "(", ")", ".", "n", "(", ")", "==", "infinity", ":", "from", "warnings", "import", "warn", "warn", "(", "\"The case n=infinity here is not verified at...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modular/modform_hecketriangle/hecke_triangle_group_element.py#L1260-L1392
opencobra/optlang
47c0ded00abf115cfedfc2a0b8fbcd9c9cbfbde5
src/optlang/osqp_interface.py
python
OSQPProblem.rename_variable
(self, old, new)
Rename a variable.
Rename a variable.
[ "Rename", "a", "variable", "." ]
def rename_variable(self, old, new): """Rename a variable.""" self.reset() self.variables.remove(old) self.variables.add(new) name_map = {k: k for k in self.variables} name_map[old] = new self.constraint_coefs = { (k[0], name_map[k[1]]): v for k, v in six.iteritems(self.constraint_coefs) } self.obj_quadratic_coefs = { (name_map[k[0]], name_map[k[1]]): v for k, v in six.iteritems(self.obj_quadratic_coefs) } self.obj_linear_coefs = { name_map[k]: v for k, v in six.iteritems(self.obj_linear_coefs) } self.variable_lbs[new] = self.variable_lbs.pop(old) self.variable_ubs[new] = self.variable_ubs.pop(old)
[ "def", "rename_variable", "(", "self", ",", "old", ",", "new", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "variables", ".", "remove", "(", "old", ")", "self", ".", "variables", ".", "add", "(", "new", ")", "name_map", "=", "{", "k", "...
https://github.com/opencobra/optlang/blob/47c0ded00abf115cfedfc2a0b8fbcd9c9cbfbde5/src/optlang/osqp_interface.py#L281-L299
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/numpy/core/defchararray.py
python
rjust
(a, width, fillchar=' ')
return _vec_string( a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar))
Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.rjust
Return an array with the elements of `a` right-justified in a string of length `width`.
[ "Return", "an", "array", "with", "the", "elements", "of", "a", "right", "-", "justified", "in", "a", "string", "of", "length", "width", "." ]
def rjust(a, width, fillchar=' '): """ Return an array with the elements of `a` right-justified in a string of length `width`. Calls `str.rjust` element-wise. Parameters ---------- a : array_like of str or unicode width : int The length of the resulting strings fillchar : str or unicode, optional The character to use for padding Returns ------- out : ndarray Output array of str or unicode, depending on input type See also -------- str.rjust """ a_arr = numpy.asarray(a) width_arr = numpy.asarray(width) size = long(numpy.max(width_arr.flat)) if numpy.issubdtype(a_arr.dtype, numpy.string_): fillchar = asbytes(fillchar) return _vec_string( a_arr, (a_arr.dtype.type, size), 'rjust', (width_arr, fillchar))
[ "def", "rjust", "(", "a", ",", "width", ",", "fillchar", "=", "' '", ")", ":", "a_arr", "=", "numpy", ".", "asarray", "(", "a", ")", "width_arr", "=", "numpy", ".", "asarray", "(", "width", ")", "size", "=", "long", "(", "numpy", ".", "max", "(",...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/numpy/core/defchararray.py#L1253-L1285
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenType.py
python
OpaqueByValueType.passInput
(self, name)
return name
[]
def passInput(self, name): return name
[ "def", "passInput", "(", "self", ",", "name", ")", ":", "return", "name" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/bgen/bgen/bgenType.py#L282-L283
microsoft/TextWorld
c419bb63a92c7f6960aa004a367fb18894043e7f
textworld/gym/spaces/text_spaces.py
python
Word.__init__
(self, max_length, vocab)
Parameters ---------- max_length : int Maximum number of words in a text. vocab : list of strings Vocabulary defining this space. It shouldn't contain any duplicate words.
Parameters ---------- max_length : int Maximum number of words in a text. vocab : list of strings Vocabulary defining this space. It shouldn't contain any duplicate words.
[ "Parameters", "----------", "max_length", ":", "int", "Maximum", "number", "of", "words", "in", "a", "text", ".", "vocab", ":", "list", "of", "strings", "Vocabulary", "defining", "this", "space", ".", "It", "shouldn", "t", "contain", "any", "duplicate", "wor...
def __init__(self, max_length, vocab): """ Parameters ---------- max_length : int Maximum number of words in a text. vocab : list of strings Vocabulary defining this space. It shouldn't contain any duplicate words. """ if len(vocab) != len(set(vocab)): raise VocabularyHasDuplicateTokens() self.max_length = max_length self.PAD = "<PAD>" self.UNK = "<UNK>" self.BOS = "<S>" self.EOS = "</S>" self.SEP = "<|>" special_tokens = [self.PAD, self.UNK, self.EOS, self.BOS, self.SEP] self.vocab = [w for w in special_tokens if w not in vocab] self.vocab += list(vocab) self.vocab_set = set(self.vocab) # For faster lookup. self.vocab_size = len(self.vocab) self.id2w = {i: w for i, w in enumerate(self.vocab)} self.w2id = {w: i for i, w in self.id2w.items()} self.PAD_id = self.w2id[self.PAD] self.UNK_id = self.w2id[self.UNK] self.BOS_id = self.w2id[self.BOS] self.EOS_id = self.w2id[self.EOS] self.SEP_id = self.w2id[self.SEP] super().__init__([len(self.vocab) - 1] * self.max_length) self.dtype = np.int64
[ "def", "__init__", "(", "self", ",", "max_length", ",", "vocab", ")", ":", "if", "len", "(", "vocab", ")", "!=", "len", "(", "set", "(", "vocab", ")", ")", ":", "raise", "VocabularyHasDuplicateTokens", "(", ")", "self", ".", "max_length", "=", "max_len...
https://github.com/microsoft/TextWorld/blob/c419bb63a92c7f6960aa004a367fb18894043e7f/textworld/gym/spaces/text_spaces.py#L118-L150
enthought/chaco
0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f
chaco/plots/scatterplot.py
python
ScatterPlot._render
(self, gc, points, icon_mode=False)
This same method is used both to render the scatterplot and to draw just the iconified version of this plot, with the latter simply requiring that a few steps be skipped.
This same method is used both to render the scatterplot and to draw just the iconified version of this plot, with the latter simply requiring that a few steps be skipped.
[ "This", "same", "method", "is", "used", "both", "to", "render", "the", "scatterplot", "and", "to", "draw", "just", "the", "iconified", "version", "of", "this", "plot", "with", "the", "latter", "simply", "requiring", "that", "a", "few", "steps", "be", "skip...
def _render(self, gc, points, icon_mode=False): """ This same method is used both to render the scatterplot and to draw just the iconified version of this plot, with the latter simply requiring that a few steps be skipped. """ if not icon_mode: gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) self.render_markers_func( gc, points, self.marker, self.marker_size, self.effective_color, self.line_width, self.effective_outline_color, self.custom_symbol, point_mask=self._cached_point_mask, ) if ( self._cached_selected_pts is not None and len(self._cached_selected_pts) > 0 ): sel_pts = self.map_screen(self._cached_selected_pts) self.render_markers_func( gc, sel_pts, self.selection_marker, self.selection_marker_size, self.selection_color_, self.selection_line_width, self.selection_outline_color_, self.custom_symbol, point_mask=self._cached_point_mask, ) if not icon_mode: # Draw the default axes, if necessary self._draw_default_axes(gc) gc.restore_state()
[ "def", "_render", "(", "self", ",", "gc", ",", "points", ",", "icon_mode", "=", "False", ")", ":", "if", "not", "icon_mode", ":", "gc", ".", "save_state", "(", ")", "gc", ".", "clip_to_rect", "(", "self", ".", "x", ",", "self", ".", "y", ",", "se...
https://github.com/enthought/chaco/blob/0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f/chaco/plots/scatterplot.py#L530-L573
bungnoid/glTools
8ff0899de43784a18bd4543285655e68e28fb5e5
utils/blendShape.py
python
isBlendShape
(blendShape)
return True
Test if node is a valid blendShape deformer @param blendShape: Name of blendShape to query @type blendShape: str
Test if node is a valid blendShape deformer
[ "Test", "if", "node", "is", "a", "valid", "blendShape", "deformer" ]
def isBlendShape(blendShape): ''' Test if node is a valid blendShape deformer @param blendShape: Name of blendShape to query @type blendShape: str ''' # Check blendShape exists if not mc.objExists(blendShape): return False # Check object type if mc.objectType(blendShape) != 'blendShape': return False # Return result return True
[ "def", "isBlendShape", "(", "blendShape", ")", ":", "# Check blendShape exists", "if", "not", "mc", ".", "objExists", "(", "blendShape", ")", ":", "return", "False", "# Check object type", "if", "mc", ".", "objectType", "(", "blendShape", ")", "!=", "'blendShape...
https://github.com/bungnoid/glTools/blob/8ff0899de43784a18bd4543285655e68e28fb5e5/utils/blendShape.py#L7-L18
yuanxiaosc/Schema-based-Knowledge-Extraction
ac0f07cd1088f24cb8f76c271fd2b49ea6100ca8
bert/tokenization.py
python
convert_tokens_to_ids
(vocab, tokens)
return convert_by_vocab(vocab, tokens)
[]
def convert_tokens_to_ids(vocab, tokens): return convert_by_vocab(vocab, tokens)
[ "def", "convert_tokens_to_ids", "(", "vocab", ",", "tokens", ")", ":", "return", "convert_by_vocab", "(", "vocab", ",", "tokens", ")" ]
https://github.com/yuanxiaosc/Schema-based-Knowledge-Extraction/blob/ac0f07cd1088f24cb8f76c271fd2b49ea6100ca8/bert/tokenization.py#L144-L145
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/ratingscale.py
python
RatingScale._getMarkerFromPos
(self, mouseX)
return rounded/self.scaledPrecision
Convert mouseX into units of tick marks, 0 .. high-low. Will be fractional if precision > 1
Convert mouseX into units of tick marks, 0 .. high-low.
[ "Convert", "mouseX", "into", "units", "of", "tick", "marks", "0", "..", "high", "-", "low", "." ]
def _getMarkerFromPos(self, mouseX): """Convert mouseX into units of tick marks, 0 .. high-low. Will be fractional if precision > 1 """ value = min(max(mouseX, self.lineLeftEnd), self.lineRightEnd) # map mouseX==0 -> mid-point of tick scale: _tickStretch = self.tickMarks/self.hStretchTotal adjValue = value - self.offsetHoriz markerPos = adjValue * _tickStretch + self.tickMarks/2.0 # We need float value in getRating(), but round() returns # numpy.float64 if argument is numpy.float64 in Python3. # So we have to convert return value of round() to float. rounded = float(round(markerPos * self.scaledPrecision)) return rounded/self.scaledPrecision
[ "def", "_getMarkerFromPos", "(", "self", ",", "mouseX", ")", ":", "value", "=", "min", "(", "max", "(", "mouseX", ",", "self", ".", "lineLeftEnd", ")", ",", "self", ".", "lineRightEnd", ")", "# map mouseX==0 -> mid-point of tick scale:", "_tickStretch", "=", "...
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/ratingscale.py#L1016-L1030
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/sparse/extract.py
python
tril
(A, k=0, format=None)
return _masked_coo(A, mask).asformat(format)
Return the lower triangular portion of a matrix in sparse format Returns the elements on or below the k-th diagonal of the matrix A. - k = 0 corresponds to the main diagonal - k > 0 is above the main diagonal - k < 0 is below the main diagonal Parameters ---------- A : dense or sparse matrix Matrix whose lower trianglar portion is desired. k : integer : optional The top-most diagonal of the lower triangle. format : string Sparse format of the result, e.g. format="csr", etc. Returns ------- L : sparse matrix Lower triangular portion of A in sparse format. See Also -------- triu : upper triangle in sparse format Examples -------- >>> from scipy.sparse import csr_matrix, tril >>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]], ... dtype='int32') >>> A.toarray() array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]]) >>> tril(A).toarray() array([[1, 0, 0, 0, 0], [4, 5, 0, 0, 0], [0, 0, 8, 0, 0]]) >>> tril(A).nnz 4 >>> tril(A, k=1).toarray() array([[1, 2, 0, 0, 0], [4, 5, 0, 0, 0], [0, 0, 8, 9, 0]]) >>> tril(A, k=-1).toarray() array([[0, 0, 0, 0, 0], [4, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) >>> tril(A, format='csc') <3x5 sparse matrix of type '<type 'numpy.int32'>' with 4 stored elements in Compressed Sparse Column format>
Return the lower triangular portion of a matrix in sparse format
[ "Return", "the", "lower", "triangular", "portion", "of", "a", "matrix", "in", "sparse", "format" ]
def tril(A, k=0, format=None): """Return the lower triangular portion of a matrix in sparse format Returns the elements on or below the k-th diagonal of the matrix A. - k = 0 corresponds to the main diagonal - k > 0 is above the main diagonal - k < 0 is below the main diagonal Parameters ---------- A : dense or sparse matrix Matrix whose lower trianglar portion is desired. k : integer : optional The top-most diagonal of the lower triangle. format : string Sparse format of the result, e.g. format="csr", etc. Returns ------- L : sparse matrix Lower triangular portion of A in sparse format. See Also -------- triu : upper triangle in sparse format Examples -------- >>> from scipy.sparse import csr_matrix, tril >>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]], ... dtype='int32') >>> A.toarray() array([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]]) >>> tril(A).toarray() array([[1, 0, 0, 0, 0], [4, 5, 0, 0, 0], [0, 0, 8, 0, 0]]) >>> tril(A).nnz 4 >>> tril(A, k=1).toarray() array([[1, 2, 0, 0, 0], [4, 5, 0, 0, 0], [0, 0, 8, 9, 0]]) >>> tril(A, k=-1).toarray() array([[0, 0, 0, 0, 0], [4, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) >>> tril(A, format='csc') <3x5 sparse matrix of type '<type 'numpy.int32'>' with 4 stored elements in Compressed Sparse Column format> """ # convert to COOrdinate format where things are easy A = coo_matrix(A, copy=False) mask = A.row + k >= A.col return _masked_coo(A, mask).asformat(format)
[ "def", "tril", "(", "A", ",", "k", "=", "0", ",", "format", "=", "None", ")", ":", "# convert to COOrdinate format where things are easy", "A", "=", "coo_matrix", "(", "A", ",", "copy", "=", "False", ")", "mask", "=", "A", ".", "row", "+", "k", ">=", ...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/sparse/extract.py#L45-L103
XKNX/xknx
1deeeb3dc0978aebacf14492a84e1f1eaf0970ed
xknx/core/telegram_queue.py
python
TelegramQueue.stop
(self)
Stop telegram queue.
Stop telegram queue.
[ "Stop", "telegram", "queue", "." ]
async def stop(self) -> None: """Stop telegram queue.""" logger.debug("Stopping TelegramQueue") # If a None object is pushed to the queue, the queue stops await self.xknx.telegrams.put(None) if self._consumer_task is not None: await self._consumer_task
[ "async", "def", "stop", "(", "self", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"Stopping TelegramQueue\"", ")", "# If a None object is pushed to the queue, the queue stops", "await", "self", ".", "xknx", ".", "telegrams", ".", "put", "(", "None", ")",...
https://github.com/XKNX/xknx/blob/1deeeb3dc0978aebacf14492a84e1f1eaf0970ed/xknx/core/telegram_queue.py#L106-L112
sqlmapproject/sqlmap
3b07b70864624dff4c29dcaa8a61c78e7f9189f7
lib/parse/configfile.py
python
configFileParser
(configFile)
Parse configuration file and save settings into the configuration advanced dictionary.
Parse configuration file and save settings into the configuration advanced dictionary.
[ "Parse", "configuration", "file", "and", "save", "settings", "into", "the", "configuration", "advanced", "dictionary", "." ]
def configFileParser(configFile): """ Parse configuration file and save settings into the configuration advanced dictionary. """ global config debugMsg = "parsing configuration file" logger.debug(debugMsg) checkFile(configFile) configFP = openFile(configFile, "rb") try: config = UnicodeRawConfigParser() config.readfp(configFP) except Exception as ex: errMsg = "you have provided an invalid and/or unreadable configuration file ('%s')" % getSafeExString(ex) raise SqlmapSyntaxException(errMsg) if not config.has_section("Target"): errMsg = "missing a mandatory section 'Target' in the configuration file" raise SqlmapMissingMandatoryOptionException(errMsg) mandatory = False for option in ("direct", "url", "logFile", "bulkFile", "googleDork", "requestFile", "wizard"): if config.has_option("Target", option) and config.get("Target", option) or cmdLineOptions.get(option): mandatory = True break if not mandatory: errMsg = "missing a mandatory option in the configuration file " errMsg += "(direct, url, logFile, bulkFile, googleDork, requestFile or wizard)" raise SqlmapMissingMandatoryOptionException(errMsg) for family, optionData in optDict.items(): for option, datatype in optionData.items(): datatype = unArrayizeValue(datatype) configFileProxy(family, option, datatype)
[ "def", "configFileParser", "(", "configFile", ")", ":", "global", "config", "debugMsg", "=", "\"parsing configuration file\"", "logger", ".", "debug", "(", "debugMsg", ")", "checkFile", "(", "configFile", ")", "configFP", "=", "openFile", "(", "configFile", ",", ...
https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/lib/parse/configfile.py#L55-L95
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/permutation.py
python
Arrangements_setk._repr_
(self)
return "Arrangements of the set %s of length %s"%(list(self._set),self._k)
TESTS:: sage: Arrangements([1,2,3],2) Arrangements of the set [1, 2, 3] of length 2
TESTS::
[ "TESTS", "::" ]
def _repr_(self): """ TESTS:: sage: Arrangements([1,2,3],2) Arrangements of the set [1, 2, 3] of length 2 """ return "Arrangements of the set %s of length %s"%(list(self._set),self._k)
[ "def", "_repr_", "(", "self", ")", ":", "return", "\"Arrangements of the set %s of length %s\"", "%", "(", "list", "(", "self", ".", "_set", ")", ",", "self", ".", "_k", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/permutation.py#L6348-L6355