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
arteria/django-compat
597bd81a635dec7fdfcccf09b5c95df63615dbf2
compat/__init__.py
python
get_user_model_path
()
return getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
Returns 'app_label.ModelName' for User model. Basically if ``AUTH_USER_MODEL`` is set at settings it would be returned, otherwise ``auth.User`` is returned.
Returns 'app_label.ModelName' for User model. Basically if ``AUTH_USER_MODEL`` is set at settings it would be returned, otherwise ``auth.User`` is returned.
[ "Returns", "app_label", ".", "ModelName", "for", "User", "model", ".", "Basically", "if", "AUTH_USER_MODEL", "is", "set", "at", "settings", "it", "would", "be", "returned", "otherwise", "auth", ".", "User", "is", "returned", "." ]
def get_user_model_path(): """ Returns 'app_label.ModelName' for User model. Basically if ``AUTH_USER_MODEL`` is set at settings it would be returned, otherwise ``auth.User`` is returned. """ return getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
[ "def", "get_user_model_path", "(", ")", ":", "return", "getattr", "(", "settings", ",", "'AUTH_USER_MODEL'", ",", "'auth.User'", ")" ]
https://github.com/arteria/django-compat/blob/597bd81a635dec7fdfcccf09b5c95df63615dbf2/compat/__init__.py#L199-L205
plasticityai/magnitude
7ac0baeaf181263b661c3ae00643d21e3fd90216
pymagnitude/third_party/allennlp/data/token_indexers/token_indexer.py
python
TokenIndexer.tokens_to_indices
(self, tokens , vocabulary , index_name )
u""" Takes a list of tokens and converts them to one or more sets of indices. This could be just an ID for each token from the vocabulary. Or it could split each token into characters and return one ID per character. Or (for instance, in the case of byte-pair encoding) there might not be a clean mapping from individual tokens to indices.
u""" Takes a list of tokens and converts them to one or more sets of indices. This could be just an ID for each token from the vocabulary. Or it could split each token into characters and return one ID per character. Or (for instance, in the case of byte-pair encoding) there might not be a clean mapping from individual tokens to indices.
[ "u", "Takes", "a", "list", "of", "tokens", "and", "converts", "them", "to", "one", "or", "more", "sets", "of", "indices", ".", "This", "could", "be", "just", "an", "ID", "for", "each", "token", "from", "the", "vocabulary", ".", "Or", "it", "could", "...
def tokens_to_indices(self, tokens , vocabulary , index_name ) : u""" Takes a list of tokens and converts them to one or more sets of indices. This could be just an ID for each token from the vocabulary. Or it could split each token into characters and return one ID per character. Or (for instance, in the case of byte-pair encoding) there might not be a clean mapping from individual tokens to indices. """ raise NotImplementedError
[ "def", "tokens_to_indices", "(", "self", ",", "tokens", ",", "vocabulary", ",", "index_name", ")", ":", "raise", "NotImplementedError" ]
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/allennlp/data/token_indexers/token_indexer.py#L35-L46
Cadair/jupyter_environment_kernels
3da304550b511bda7d5d39280379b5ca39bb31bc
environment_kernels/envs_conda.py
python
_find_conda_env_paths_from_conda
(mgr)
return envs
Returns a list of path as given by `conda env list --json`. Returns empty list, if conda couldn't be called.
Returns a list of path as given by `conda env list --json`.
[ "Returns", "a", "list", "of", "path", "as", "given", "by", "conda", "env", "list", "--", "json", "." ]
def _find_conda_env_paths_from_conda(mgr): """Returns a list of path as given by `conda env list --json`. Returns empty list, if conda couldn't be called. """ # this is expensive, so make it configureable... if not mgr.use_conda_directly: return [] mgr.log.debug("Looking for conda environments by calling conda directly...") import subprocess import json try: p = subprocess.Popen( ['conda', 'env', 'list', '--json'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) comm = p.communicate() output = comm[0].decode() if p.returncode != 0 or len(output) == 0: mgr.log.error( "Couldn't call 'conda' to get the environments. " "Output:\n%s", str(comm)) return [] except FileNotFoundError: mgr.log.error("'conda' not found in path.") return [] output = json.loads(output) envs = output["envs"] # self.log.info("Found the following kernels from conda: %s", ", ".join(envs)) return envs
[ "def", "_find_conda_env_paths_from_conda", "(", "mgr", ")", ":", "# this is expensive, so make it configureable...", "if", "not", "mgr", ".", "use_conda_directly", ":", "return", "[", "]", "mgr", ".", "log", ".", "debug", "(", "\"Looking for conda environments by calling ...
https://github.com/Cadair/jupyter_environment_kernels/blob/3da304550b511bda7d5d39280379b5ca39bb31bc/environment_kernels/envs_conda.py#L62-L91
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/utils/safestring.py
python
mark_for_escaping
(s)
return EscapeBytes(bytes(s))
Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once).
Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses.
[ "Explicitly", "mark", "a", "string", "as", "requiring", "HTML", "escaping", "upon", "output", ".", "Has", "no", "effect", "on", "SafeData", "subclasses", "." ]
def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ if isinstance(s, (SafeData, EscapeData)): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return EscapeBytes(s) if isinstance(s, (six.text_type, Promise)): return EscapeText(s) return EscapeBytes(bytes(s))
[ "def", "mark_for_escaping", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "(", "SafeData", ",", "EscapeData", ")", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "bytes", ")", "or", "(", "isinstance", "(", "s", ",", "Promise", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/utils/safestring.py#L119-L133
lululxvi/deepxde
730c97282636e86c845ce2ba3253482f2178469e
examples/elliptic_inverse_field.py
python
sol
(x)
return np.sin(np.pi * x ** 2)
[]
def sol(x): # solution is u(x) = sin(pi*x), q(x) = -pi^2 * sin(pi*x) return np.sin(np.pi * x ** 2)
[ "def", "sol", "(", "x", ")", ":", "# solution is u(x) = sin(pi*x), q(x) = -pi^2 * sin(pi*x)", "return", "np", ".", "sin", "(", "np", ".", "pi", "*", "x", "**", "2", ")" ]
https://github.com/lululxvi/deepxde/blob/730c97282636e86c845ce2ba3253482f2178469e/examples/elliptic_inverse_field.py#L20-L22
merenlab/anvio
9b792e2cedc49ecb7c0bed768261595a0d87c012
anvio/programs.py
python
AnvioArtifacts.init_artifacts
(self)
Generate `required_by` and `provided_by` statements. Returns ======= artifacts_info, dict: Running this function will fill in the dictionary `self.artifacts_info`
Generate `required_by` and `provided_by` statements.
[ "Generate", "required_by", "and", "provided_by", "statements", "." ]
def init_artifacts(self): """Generate `required_by` and `provided_by` statements. Returns ======= artifacts_info, dict: Running this function will fill in the dictionary `self.artifacts_info` """ artifacts_with_descriptions = set([]) artifacts_without_descriptions = set([]) for artifact in ANVIO_ARTIFACTS: self.artifacts_info[artifact] = {'required_by': [], 'provided_by': [], 'description': None, 'type': ANVIO_ARTIFACTS[artifact]['type']} # learn about the description of the artifact artifact_description_path = os.path.join(anvio.DOCS_PATH, 'artifacts/%s.md' % (artifact)) if os.path.exists(artifact_description_path): self.artifacts_info[artifact]['description'] = self.read_anvio_markdown(artifact_description_path) artifacts_with_descriptions.add(artifact) else: artifacts_without_descriptions.add(artifact) # learn about what provides or requires this artifact for program in self.programs.values(): if artifact in [a.id for a in program.meta_info['requires']['value']]: self.artifacts_info[artifact]['required_by'].append(program.name) if artifact in [a.id for a in program.meta_info['provides']['value']]: self.artifacts_info[artifact]['provided_by'].append(program.name) # register artifact type artifact_type = self.artifacts_info[artifact]['type'] if artifact_type not in self.artifact_types: self.artifact_types[artifact_type] = [] self.artifact_types[artifact_type].append(artifact) if len(artifacts_without_descriptions): self.run.info_single("Of %d artifacts found, %d did not contain any DESCRIPTION. If you would like to " "see examples and add new descriptions, please see the directory '%s'. Here is the " "full list of artifacts that are not yet explained: %s." \ % (len(ANVIO_ARTIFACTS), len(artifacts_without_descriptions), anvio.DOCS_PATH, ', '.join(artifacts_without_descriptions)), nl_after=1, nl_before=1)
[ "def", "init_artifacts", "(", "self", ")", ":", "artifacts_with_descriptions", "=", "set", "(", "[", "]", ")", "artifacts_without_descriptions", "=", "set", "(", "[", "]", ")", "for", "artifact", "in", "ANVIO_ARTIFACTS", ":", "self", ".", "artifacts_info", "["...
https://github.com/merenlab/anvio/blob/9b792e2cedc49ecb7c0bed768261595a0d87c012/anvio/programs.py#L428-L474
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/xml/sax/_exceptions.py
python
SAXException.__getitem__
(self, ix)
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.
[ "Avoids", "weird", "error", "messages", "if", "someone", "does", "exception", "[", "ix", "]", "by", "mistake", "since", "Exception", "has", "__getitem__", "defined", "." ]
def __getitem__(self, ix): """Avoids weird error messages if someone does exception[ix] by mistake, since Exception has __getitem__ defined.""" raise AttributeError('__getitem__')
[ "def", "__getitem__", "(", "self", ",", "ix", ")", ":", "raise", "AttributeError", "(", "'__getitem__'", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/xml/sax/_exceptions.py#L41-L44
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/reading.py
python
EmptyReader.max_field_length
(self, fieldname)
return 0
[]
def max_field_length(self, fieldname): return 0
[ "def", "max_field_length", "(", "self", ",", "fieldname", ")", ":", "return", "0" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/reading.py#L997-L998
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/qt_gui.py
python
LeoQtGui.makeFilter
(self, filetypes)
return ';;'.join(filters)
Return the Qt-style dialog filter from filetypes list.
Return the Qt-style dialog filter from filetypes list.
[ "Return", "the", "Qt", "-", "style", "dialog", "filter", "from", "filetypes", "list", "." ]
def makeFilter(self, filetypes): """Return the Qt-style dialog filter from filetypes list.""" filters = ['%s (%s)' % (z) for z in filetypes] # Careful: the second %s is *not* replaced. return ';;'.join(filters)
[ "def", "makeFilter", "(", "self", ",", "filetypes", ")", ":", "filters", "=", "[", "'%s (%s)'", "%", "(", "z", ")", "for", "z", "in", "filetypes", "]", "# Careful: the second %s is *not* replaced.", "return", "';;'", ".", "join", "(", "filters", ")" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/qt_gui.py#L208-L212
BMW-InnovationLab/BMW-TensorFlow-Training-GUI
4f10d1f00f9ac312ca833e5b28fd0f8952cfee17
training_api/research/object_detection/models/ssd_resnet_v1_fpn_feature_extractor.py
python
SSDResnet101V1FpnFeatureExtractor.__init__
(self, is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams_fn, fpn_min_level=3, fpn_max_level=7, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False)
SSD Resnet101 V1 FPN feature extractor based on Resnet v1 architecture. Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. UNUSED currently. min_depth: minimum feature extractor depth. UNUSED Currently. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d and separable_conv2d ops in the layers that are added on top of the base feature extractor. fpn_min_level: the minimum level in feature pyramid networks. fpn_max_level: the maximum level in feature pyramid networks. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. UNUSED currently. use_depthwise: Whether to use depthwise convolutions. UNUSED currently. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`.
SSD Resnet101 V1 FPN feature extractor based on Resnet v1 architecture.
[ "SSD", "Resnet101", "V1", "FPN", "feature", "extractor", "based", "on", "Resnet", "v1", "architecture", "." ]
def __init__(self, is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams_fn, fpn_min_level=3, fpn_max_level=7, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False): """SSD Resnet101 V1 FPN feature extractor based on Resnet v1 architecture. Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. UNUSED currently. min_depth: minimum feature extractor depth. UNUSED Currently. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d and separable_conv2d ops in the layers that are added on top of the base feature extractor. fpn_min_level: the minimum level in feature pyramid networks. fpn_max_level: the maximum level in feature pyramid networks. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. UNUSED currently. use_depthwise: Whether to use depthwise convolutions. UNUSED currently. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`. """ super(SSDResnet101V1FpnFeatureExtractor, self).__init__( is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams_fn, resnet_v1.resnet_v1_101, 'resnet_v1_101', 'fpn', fpn_min_level, fpn_max_level, reuse_weights=reuse_weights, use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams)
[ "def", "__init__", "(", "self", ",", "is_training", ",", "depth_multiplier", ",", "min_depth", ",", "pad_to_multiple", ",", "conv_hyperparams_fn", ",", "fpn_min_level", "=", "3", ",", "fpn_max_level", "=", "7", ",", "reuse_weights", "=", "None", ",", "use_explic...
https://github.com/BMW-InnovationLab/BMW-TensorFlow-Training-GUI/blob/4f10d1f00f9ac312ca833e5b28fd0f8952cfee17/training_api/research/object_detection/models/ssd_resnet_v1_fpn_feature_extractor.py#L258-L307
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/controls/ultimatelistctrl.py
python
UltimateListCtrl.OnGetItemAttr
(self, item)
return None
This function may be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the attribute for the specified item or ``None`` to use the default appearance parameters. :param `item`: an integer specifying the item index. :note: :class:`UltimateListCtrl` will not delete the pointer or keep a reference of it. You can return the same :class:`UltimateListItemAttr` pointer for every :meth:`~UltimateListCtrl.OnGetItemAttr` call. :note: The base class version always returns ``None``.
This function may be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the attribute for the specified item or ``None`` to use the default appearance parameters.
[ "This", "function", "may", "be", "overloaded", "in", "the", "derived", "class", "for", "a", "control", "with", "ULC_VIRTUAL", "style", ".", "It", "should", "return", "the", "attribute", "for", "the", "specified", "item", "or", "None", "to", "use", "the", "...
def OnGetItemAttr(self, item): """ This function may be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the attribute for the specified item or ``None`` to use the default appearance parameters. :param `item`: an integer specifying the item index. :note: :class:`UltimateListCtrl` will not delete the pointer or keep a reference of it. You can return the same :class:`UltimateListItemAttr` pointer for every :meth:`~UltimateListCtrl.OnGetItemAttr` call. :note: The base class version always returns ``None``. """ if item < 0 or item > self.GetItemCount(): raise Exception("Invalid item index in OnGetItemAttr()") # no attributes by default return None
[ "def", "OnGetItemAttr", "(", "self", ",", "item", ")", ":", "if", "item", "<", "0", "or", "item", ">", "self", ".", "GetItemCount", "(", ")", ":", "raise", "Exception", "(", "\"Invalid item index in OnGetItemAttr()\"", ")", "# no attributes by default", "return"...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/ultimatelistctrl.py#L12631-L12652
Blazemeter/taurus
6e36b20397cf3e730e181cfebde0c8f19eb31fed
bzt/bza.py
python
Project.tests
(self, name=None, ident=None, test_type=None)
return tests
:rtype: BZAObjectsList[Test]
:rtype: BZAObjectsList[Test]
[ ":", "rtype", ":", "BZAObjectsList", "[", "Test", "]" ]
def tests(self, name=None, ident=None, test_type=None): """ :rtype: BZAObjectsList[Test] """ params = OrderedDict({"projectId": self['id']}) if name is not None: params["name"] = name if ident is not None: params["id"] = ident res = self._request(self.address + '/api/v4/tests?' + urlencode(params)) tests = BZAObjectsList() for item in res['result']: if ident is not None and item['id'] != ident: continue if name is not None and item['name'] != name: continue if test_type is not None and item['configuration']['type'] != test_type: continue tests.append(Test(self, item)) return tests
[ "def", "tests", "(", "self", ",", "name", "=", "None", ",", "ident", "=", "None", ",", "test_type", "=", "None", ")", ":", "params", "=", "OrderedDict", "(", "{", "\"projectId\"", ":", "self", "[", "'id'", "]", "}", ")", "if", "name", "is", "not", ...
https://github.com/Blazemeter/taurus/blob/6e36b20397cf3e730e181cfebde0c8f19eb31fed/bzt/bza.py#L376-L399
JustDoPython/python-100-day
4e75007195aa4cdbcb899aeb06b9b08996a4606c
cherry_tree/cherry_tree.py
python
cherryTree
(branch, t)
[]
def cherryTree(branch, t): if branch > 4: if 7 <= branch <= 13: # 随机数生成 if random.randint(0, 3) == 0: t.color('snow') # 花瓣心的颜色 else: t.color('pink') #花瓣颜色 # 填充的花瓣大小 t.pensize( branch / 6) elif branch < 8: if random.randint(0, 2) == 0: t.color('snow') else: # 设置樱花树叶颜色 t.color('green') # 樱花树颜色 t.pensize(branch / 5) else: t.color('Peru') # 树干颜色 t.pensize(branch / 11) #调整树干的粗细 t.forward(branch) a = 1 * random.random() t.right(20 * a) b = 1 * random.random() cherryTree(branch - 10 * b, t) t.left(60 * a) cherryTree(branch - 10 * b, t) t.right(40 * a) t.up() t.backward(branch) t.down()
[ "def", "cherryTree", "(", "branch", ",", "t", ")", ":", "if", "branch", ">", "4", ":", "if", "7", "<=", "branch", "<=", "13", ":", "# 随机数生成", "if", "random", ".", "randint", "(", "0", ",", "3", ")", "==", "0", ":", "t", ".", "color", "(", "'s...
https://github.com/JustDoPython/python-100-day/blob/4e75007195aa4cdbcb899aeb06b9b08996a4606c/cherry_tree/cherry_tree.py#L4-L35
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/boto/vpc/__init__.py
python
VPCConnection.create_vpn_connection
(self, type, customer_gateway_id, vpn_gateway_id, static_routes_only=None, dry_run=False)
return self.get_object('CreateVpnConnection', params, VpnConnection)
Create a new VPN Connection. :type type: str :param type: The type of VPN Connection. Currently only 'ipsec.1' is supported :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer gateway. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the VPN gateway. :type static_routes_only: bool :param static_routes_only: Indicates whether the VPN connection requires static routes. If you are creating a VPN connection for a device that does not support BGP, you must specify true. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: The newly created VpnConnection :return: A :class:`boto.vpc.vpnconnection.VpnConnection` object
Create a new VPN Connection.
[ "Create", "a", "new", "VPN", "Connection", "." ]
def create_vpn_connection(self, type, customer_gateway_id, vpn_gateway_id, static_routes_only=None, dry_run=False): """ Create a new VPN Connection. :type type: str :param type: The type of VPN Connection. Currently only 'ipsec.1' is supported :type customer_gateway_id: str :param customer_gateway_id: The ID of the customer gateway. :type vpn_gateway_id: str :param vpn_gateway_id: The ID of the VPN gateway. :type static_routes_only: bool :param static_routes_only: Indicates whether the VPN connection requires static routes. If you are creating a VPN connection for a device that does not support BGP, you must specify true. :type dry_run: bool :param dry_run: Set to True if the operation should not actually run. :rtype: The newly created VpnConnection :return: A :class:`boto.vpc.vpnconnection.VpnConnection` object """ params = {'Type': type, 'CustomerGatewayId': customer_gateway_id, 'VpnGatewayId': vpn_gateway_id} if static_routes_only is not None: if isinstance(static_routes_only, bool): static_routes_only = str(static_routes_only).lower() params['Options.StaticRoutesOnly'] = static_routes_only if dry_run: params['DryRun'] = 'true' return self.get_object('CreateVpnConnection', params, VpnConnection)
[ "def", "create_vpn_connection", "(", "self", ",", "type", ",", "customer_gateway_id", ",", "vpn_gateway_id", ",", "static_routes_only", "=", "None", ",", "dry_run", "=", "False", ")", ":", "params", "=", "{", "'Type'", ":", "type", ",", "'CustomerGatewayId'", ...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/boto/vpc/__init__.py#L1386-L1421
itamarst/crochet
deea55f870028c241e0b8c64c317224fb571b78a
crochet/_resultstore.py
python
ResultStore.store
(self, deferred_result)
return self._counter
Store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object.
Store a EventualResult.
[ "Store", "a", "EventualResult", "." ]
def store(self, deferred_result): """ Store a EventualResult. Return an integer, a unique identifier that can be used to retrieve the object. """ self._counter += 1 self._stored[self._counter] = deferred_result return self._counter
[ "def", "store", "(", "self", ",", "deferred_result", ")", ":", "self", ".", "_counter", "+=", "1", "self", ".", "_stored", "[", "self", ".", "_counter", "]", "=", "deferred_result", "return", "self", ".", "_counter" ]
https://github.com/itamarst/crochet/blob/deea55f870028c241e0b8c64c317224fb571b78a/crochet/_resultstore.py#L30-L39
dji-sdk/Tello-Python
693776d65b691525773adf4f320f034946fb15b2
Tello_Video/tello.py
python
Tello.move_left
(self, distance)
return self.move('left', distance)
Moves left for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'.
Moves left for a distance.
[ "Moves", "left", "for", "a", "distance", "." ]
def move_left(self, distance): """Moves left for a distance. See comments for Tello.move(). Args: distance (int): Distance to move. Returns: str: Response from Tello, 'OK' or 'FALSE'. """ return self.move('left', distance)
[ "def", "move_left", "(", "self", ",", "distance", ")", ":", "return", "self", ".", "move", "(", "'left'", ",", "distance", ")" ]
https://github.com/dji-sdk/Tello-Python/blob/693776d65b691525773adf4f320f034946fb15b2/Tello_Video/tello.py#L421-L433
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/ocvp/esxi_host_client.py
python
EsxiHostClient.list_esxi_hosts
(self, **kwargs)
Lists the ESXi hosts in the specified SDDC. The list can be filtered by Compute instance OCID or ESXi display name. Remember that in terms of implementation, an ESXi host is a Compute instance that is configured with the chosen bundle of VMware software. Each `EsxiHost` object has its own OCID (`id`), and a separate attribute for the OCID of the Compute instance (`computeInstanceId`). When filtering the list of ESXi hosts, you can specify the OCID of the Compute instance, not the ESXi host OCID. :param str sddc_id: (optional) The `OCID`__ of the SDDC. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param str compute_instance_id: (optional) The `OCID`__ of the Compute instance. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param str display_name: (optional) A filter to return only resources that match the given display name exactly. :param int limit: (optional) For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine :param str page: (optional) For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine :param str sort_order: (optional) The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive. Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted. Allowed values are: "timeCreated", "displayName" :param str opc_request_id: (optional) Unique identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str lifecycle_state: (optional) The lifecycle state of the resource. Allowed values are: "CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED" :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation uses :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` as default if no retry strategy is provided. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.ocvp.models.EsxiHostCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/ocvp/list_esxi_hosts.py.html>`__ to see an example of how to use list_esxi_hosts API.
Lists the ESXi hosts in the specified SDDC. The list can be filtered by Compute instance OCID or ESXi display name.
[ "Lists", "the", "ESXi", "hosts", "in", "the", "specified", "SDDC", ".", "The", "list", "can", "be", "filtered", "by", "Compute", "instance", "OCID", "or", "ESXi", "display", "name", "." ]
def list_esxi_hosts(self, **kwargs): """ Lists the ESXi hosts in the specified SDDC. The list can be filtered by Compute instance OCID or ESXi display name. Remember that in terms of implementation, an ESXi host is a Compute instance that is configured with the chosen bundle of VMware software. Each `EsxiHost` object has its own OCID (`id`), and a separate attribute for the OCID of the Compute instance (`computeInstanceId`). When filtering the list of ESXi hosts, you can specify the OCID of the Compute instance, not the ESXi host OCID. :param str sddc_id: (optional) The `OCID`__ of the SDDC. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param str compute_instance_id: (optional) The `OCID`__ of the Compute instance. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param str display_name: (optional) A filter to return only resources that match the given display name exactly. :param int limit: (optional) For list pagination. The maximum number of results per page, or items to return in a paginated \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine :param str page: (optional) For list pagination. The value of the `opc-next-page` response header from the previous \"List\" call. For important details about how pagination works, see `List Pagination`__. __ https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine :param str sort_order: (optional) The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order is case sensitive. Allowed values are: "ASC", "DESC" :param str sort_by: (optional) The field to sort by. You can provide one sort order (`sortOrder`). Default order for TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME sort order is case sensitive. **Note:** In general, some \"List\" operations (for example, `ListInstances`) let you optionally filter by availability domain if the scope of the resource type is within a single availability domain. If you call one of these \"List\" operations without specifying an availability domain, the resources are grouped by availability domain, then sorted. Allowed values are: "timeCreated", "displayName" :param str opc_request_id: (optional) Unique identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID. :param str lifecycle_state: (optional) The lifecycle state of the resource. Allowed values are: "CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED" :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation uses :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` as default if no retry strategy is provided. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type :class:`~oci.ocvp.models.EsxiHostCollection` :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/ocvp/list_esxi_hosts.py.html>`__ to see an example of how to use list_esxi_hosts API. """ resource_path = "/esxiHosts" method = "GET" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "sddc_id", "compute_instance_id", "display_name", "limit", "page", "sort_order", "sort_by", "opc_request_id", "lifecycle_state" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "list_esxi_hosts got unknown kwargs: {!r}".format(extra_kwargs)) if 'sort_order' in kwargs: sort_order_allowed_values = ["ASC", "DESC"] if kwargs['sort_order'] not in sort_order_allowed_values: raise ValueError( "Invalid value for `sort_order`, must be one of {0}".format(sort_order_allowed_values) ) if 'sort_by' in kwargs: sort_by_allowed_values = ["timeCreated", "displayName"] if kwargs['sort_by'] not in sort_by_allowed_values: raise ValueError( "Invalid value for `sort_by`, must be one of {0}".format(sort_by_allowed_values) ) if 'lifecycle_state' in kwargs: lifecycle_state_allowed_values = ["CREATING", "UPDATING", "ACTIVE", "DELETING", "DELETED", "FAILED"] if kwargs['lifecycle_state'] not in lifecycle_state_allowed_values: raise ValueError( "Invalid value for `lifecycle_state`, must be one of {0}".format(lifecycle_state_allowed_values) ) query_params = { "sddcId": kwargs.get("sddc_id", missing), "computeInstanceId": kwargs.get("compute_instance_id", missing), "displayName": kwargs.get("display_name", missing), "limit": kwargs.get("limit", missing), "page": kwargs.get("page", missing), "sortOrder": kwargs.get("sort_order", missing), "sortBy": kwargs.get("sort_by", missing), "lifecycleState": kwargs.get("lifecycle_state", missing) } query_params = {k: v for (k, v) in six.iteritems(query_params) if v is not missing and v is not None} header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy is None: retry_strategy = retry.DEFAULT_RETRY_STRATEGY if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="EsxiHostCollection") else: return self.base_client.call_api( resource_path=resource_path, method=method, query_params=query_params, header_params=header_params, response_type="EsxiHostCollection")
[ "def", "list_esxi_hosts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/esxiHosts\"", "method", "=", "\"GET\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"sddc_id\"", ",", "\"compute_instance...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/ocvp/esxi_host_client.py#L375-L541
giswqs/geemap
ba8de85557a8a1bc9c8d19e75bac69416afe7fea
geemap/foliumap.py
python
Map.set_center
(self, lon, lat, zoom=10)
Centers the map view at a given coordinates with the given zoom level. Args: lon (float): The longitude of the center, in degrees. lat (float): The latitude of the center, in degrees. zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10.
Centers the map view at a given coordinates with the given zoom level.
[ "Centers", "the", "map", "view", "at", "a", "given", "coordinates", "with", "the", "given", "zoom", "level", "." ]
def set_center(self, lon, lat, zoom=10): """Centers the map view at a given coordinates with the given zoom level. Args: lon (float): The longitude of the center, in degrees. lat (float): The latitude of the center, in degrees. zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10. """ self.fit_bounds([[lat, lon], [lat, lon]], max_zoom=zoom)
[ "def", "set_center", "(", "self", ",", "lon", ",", "lat", ",", "zoom", "=", "10", ")", ":", "self", ".", "fit_bounds", "(", "[", "[", "lat", ",", "lon", "]", ",", "[", "lat", ",", "lon", "]", "]", ",", "max_zoom", "=", "zoom", ")" ]
https://github.com/giswqs/geemap/blob/ba8de85557a8a1bc9c8d19e75bac69416afe7fea/geemap/foliumap.py#L234-L242
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/pickle.py
python
_Unpickler.load_build
(self)
[]
def load_build(self): stack = self.stack state = stack.pop() inst = stack[-1] setstate = getattr(inst, "__setstate__", None) if setstate is not None: setstate(state) return slotstate = None if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if state: inst_dict = inst.__dict__ intern = sys.intern for k, v in state.items(): if type(k) is str: inst_dict[intern(k)] = v else: inst_dict[k] = v if slotstate: for k, v in slotstate.items(): setattr(inst, k, v)
[ "def", "load_build", "(", "self", ")", ":", "stack", "=", "self", ".", "stack", "state", "=", "stack", ".", "pop", "(", ")", "inst", "=", "stack", "[", "-", "1", "]", "setstate", "=", "getattr", "(", "inst", ",", "\"__setstate__\"", ",", "None", ")...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/pickle.py#L1712-L1733
rabobank-cdc/DeTTECT
0b886c2663bc7a6a15488839c2569785c16d08e9
generic.py
python
get_applicable_data_sources_technique
(technique_data_sources, platform_applicable_data_sources)
return list(applicable_data_sources)
Get the applicable ATT&CK data sources for the provided technique's data sources (for which the source is ATT&CK CTI) :param technique_data_sources: the ATT&CK technique's data sources :param platform_applicable_data_sources: a list of applicable ATT&CK data sources based on 'DATA_SOURCES' :return: a list of applicable data sources
Get the applicable ATT&CK data sources for the provided technique's data sources (for which the source is ATT&CK CTI) :param technique_data_sources: the ATT&CK technique's data sources :param platform_applicable_data_sources: a list of applicable ATT&CK data sources based on 'DATA_SOURCES' :return: a list of applicable data sources
[ "Get", "the", "applicable", "ATT&CK", "data", "sources", "for", "the", "provided", "technique", "s", "data", "sources", "(", "for", "which", "the", "source", "is", "ATT&CK", "CTI", ")", ":", "param", "technique_data_sources", ":", "the", "ATT&CK", "technique",...
def get_applicable_data_sources_technique(technique_data_sources, platform_applicable_data_sources): """ Get the applicable ATT&CK data sources for the provided technique's data sources (for which the source is ATT&CK CTI) :param technique_data_sources: the ATT&CK technique's data sources :param platform_applicable_data_sources: a list of applicable ATT&CK data sources based on 'DATA_SOURCES' :return: a list of applicable data sources """ applicable_data_sources = set() for ds in technique_data_sources: if ':' in ds: # the param technique_data_sources comes from STIX ds = ds.split(':')[1][1:] if ds in platform_applicable_data_sources: applicable_data_sources.add(ds) return list(applicable_data_sources)
[ "def", "get_applicable_data_sources_technique", "(", "technique_data_sources", ",", "platform_applicable_data_sources", ")", ":", "applicable_data_sources", "=", "set", "(", ")", "for", "ds", "in", "technique_data_sources", ":", "if", "':'", "in", "ds", ":", "# the para...
https://github.com/rabobank-cdc/DeTTECT/blob/0b886c2663bc7a6a15488839c2569785c16d08e9/generic.py#L524-L539
carlthome/python-audio-effects
e00c4a33a84df670671a9cc4acae79e96e56feed
pysndfx/dsp.py
python
AudioEffectsChain.lowshelf
(self, gain=-20.0, frequency=100, slope=0.5)
return self
lowshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5, maximum=1.0). Beware of Clipping when using positive gain.
lowshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5, maximum=1.0).
[ "lowshelf", "takes", "3", "parameters", ":", "a", "signed", "number", "for", "gain", "or", "attenuation", "in", "dB", "filter", "frequency", "in", "Hz", "and", "slope", "(", "default", "=", "0", ".", "5", "maximum", "=", "1", ".", "0", ")", "." ]
def lowshelf(self, gain=-20.0, frequency=100, slope=0.5): """lowshelf takes 3 parameters: a signed number for gain or attenuation in dB, filter frequency in Hz and slope (default=0.5, maximum=1.0). Beware of Clipping when using positive gain. """ self.command.append('bass') self.command.append(gain) self.command.append(frequency) self.command.append(slope) return self
[ "def", "lowshelf", "(", "self", ",", "gain", "=", "-", "20.0", ",", "frequency", "=", "100", ",", "slope", "=", "0.5", ")", ":", "self", ".", "command", ".", "append", "(", "'bass'", ")", "self", ".", "command", ".", "append", "(", "gain", ")", "...
https://github.com/carlthome/python-audio-effects/blob/e00c4a33a84df670671a9cc4acae79e96e56feed/pysndfx/dsp.py#L62-L72
python-trio/trio
4edfd41bd5519a2e626e87f6c6ca9fb32b90a6f4
notes-to-self/ntp-example.py
python
extract_transmit_timestamp
(ntp_packet)
return base_time + offset
Given an NTP packet, extract the "transmit timestamp" field, as a Python datetime.
Given an NTP packet, extract the "transmit timestamp" field, as a Python datetime.
[ "Given", "an", "NTP", "packet", "extract", "the", "transmit", "timestamp", "field", "as", "a", "Python", "datetime", "." ]
def extract_transmit_timestamp(ntp_packet): """Given an NTP packet, extract the "transmit timestamp" field, as a Python datetime.""" # The transmit timestamp is the time that the server sent its response. # It's stored in bytes 40-47 of the NTP packet. See: # https://tools.ietf.org/html/rfc5905#page-19 encoded_transmit_timestamp = ntp_packet[40:48] # The timestamp is stored in the "NTP timestamp format", which is a 32 # byte count of whole seconds, followed by a 32 byte count of fractions of # a second. See: # https://tools.ietf.org/html/rfc5905#page-13 seconds, fraction = struct.unpack("!II", encoded_transmit_timestamp) # The timestamp is the number of seconds since January 1, 1900 (ignoring # leap seconds). To convert it to a datetime object, we do some simple # datetime arithmetic: base_time = datetime.datetime(1900, 1, 1) offset = datetime.timedelta(seconds=seconds + fraction / 2**32) return base_time + offset
[ "def", "extract_transmit_timestamp", "(", "ntp_packet", ")", ":", "# The transmit timestamp is the time that the server sent its response.", "# It's stored in bytes 40-47 of the NTP packet. See:", "# https://tools.ietf.org/html/rfc5905#page-19", "encoded_transmit_timestamp", "=", "ntp_packet...
https://github.com/python-trio/trio/blob/4edfd41bd5519a2e626e87f6c6ca9fb32b90a6f4/notes-to-self/ntp-example.py#L30-L50
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/wave.py
python
open
(f, mode=None)
[]
def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Wave_read(f) elif mode in ('w', 'wb'): return Wave_write(f) else: raise Error, "mode must be 'r', 'rb', 'w', or 'wb'"
[ "def", "open", "(", "f", ",", "mode", "=", "None", ")", ":", "if", "mode", "is", "None", ":", "if", "hasattr", "(", "f", ",", "'mode'", ")", ":", "mode", "=", "f", ".", "mode", "else", ":", "mode", "=", "'rb'", "if", "mode", "in", "(", "'r'",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/wave.py#L502-L513
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/s3/s3import.py
python
S3ImportJob.add_item
(self, element = None, original = None, components = None, parent = None, joinby = None, )
return item.item_id
Parse and validate an XML element and add it as new item to the job. Args: element: the element original: the original DB record (if already available, will otherwise be looked-up by this function) components: a dictionary of components (as in S3Resource) to include in the job (defaults to all defined components) parent: the parent item (if this is a component) joinby: the component join key(s) (if this is a component) Returns: A unique identifier for the new item, or None if there was an error. self.error contains the last error, and self.error_tree an element tree with all failing elements including error attributes.
Parse and validate an XML element and add it as new item to the job.
[ "Parse", "and", "validate", "an", "XML", "element", "and", "add", "it", "as", "new", "item", "to", "the", "job", "." ]
def add_item(self, element = None, original = None, components = None, parent = None, joinby = None, ): """ Parse and validate an XML element and add it as new item to the job. Args: element: the element original: the original DB record (if already available, will otherwise be looked-up by this function) components: a dictionary of components (as in S3Resource) to include in the job (defaults to all defined components) parent: the parent item (if this is a component) joinby: the component join key(s) (if this is a component) Returns: A unique identifier for the new item, or None if there was an error. self.error contains the last error, and self.error_tree an element tree with all failing elements including error attributes. """ if element in self.elements: # element has already been added to this job return self.elements[element] # Parse the main element item = S3ImportItem(self) # Update lookup lists item_id = item.item_id self.items[item_id] = item if element is not None: self.elements[element] = item_id if not item.parse(element, original = original, files = self.files, ): self.error = item.error item.accepted = False if parent is None: self.error_tree.append(deepcopy(item.element)) else: # Now parse the components table = item.table s3db = current.s3db components = s3db.get_components(table, names=components) super_keys = s3db.get_super_keys(table) cnames = Storage() cinfos = Storage() for alias in components: component = components[alias] ctable = component.table if ctable._id != "id" and "instance_type" in ctable.fields: # Super-entities cannot be imported to directly => skip continue # Determine the keys pkey = component.pkey if pkey != table._id.name and pkey not in super_keys: # Pseudo-component cannot be imported => skip continue if component.linktable: ctable = component.linktable fkey = component.lkey else: fkey = component.fkey ctablename = ctable._tablename if ctablename in cnames: cnames[ctablename].append(alias) else: cnames[ctablename] = [alias] cinfos[(ctablename, alias)] = Storage(component = component, ctable = ctable, pkey = pkey, fkey = fkey, first = True, ) add_item = self.add_item xml = current.xml UID = xml.UID for celement in xml.components(element, names=list(cnames.keys())): # Get the component tablename ctablename = celement.get(xml.ATTRIBUTE.name, None) if not ctablename or ctablename not in cnames: continue # Get the component alias (for disambiguation) calias = celement.get(xml.ATTRIBUTE.alias, None) if calias is None: aliases = cnames[ctablename] if len(aliases) == 1: calias = aliases[0] else: calias = ctablename.split("_", 1)[1] if (ctablename, calias) not in cinfos: continue else: cinfo = cinfos[(ctablename, calias)] component = cinfo.component ctable = cinfo.ctable pkey = cinfo.pkey fkey = cinfo.fkey original = None if not component.multiple: # Single-component: skip all subsequent items after # the first under the same master record if not cinfo.first: continue cinfo.first = False # Single component = the first component record # under the master record is always the original, # only relevant if the master record exists in # the db and hence item.id is not None if item.id: db = current.db query = (table.id == item.id) & \ (table[pkey] == ctable[fkey]) if UID in ctable.fields: # Load only the UUID now, parse will load any # required data later row = db(query).select(ctable[UID], limitby = (0, 1), ).first() if row: original = row[UID] else: # Not nice, but a rare edge-case original = db(query).select(ctable.ALL, limitby = (0, 1), ).first() # Recurse item_id = add_item(element = celement, original = original, parent = item, joinby = (pkey, fkey)) if item_id is None: item.error = self.error self.error_tree.append(deepcopy(item.element)) else: citem = self.items[item_id] citem.parent = item item.components.append(citem) lookahead = self.lookahead directory = self.directory # Handle references table = item.table data = item.data tree = self.tree def schedule(reference): """ Schedule a referenced item for implicit import """ entry = reference.entry if entry and entry.element is not None and not entry.item_id: item_id = add_item(element=entry.element) if item_id: entry.item_id = item_id # Foreign key fields in table if tree is not None: fields = [table[f] for f in table.fields] rfields = [f for f in fields if s3_has_foreign_key(f)] item.references = lookahead(element, table = table, fields = rfields, tree = tree, directory = directory, ) for reference in item.references: schedule(reference) references = item.references rappend = references.append # Parent reference if parent is not None: entry = Storage(item_id = parent.item_id, element = parent.element, tablename = parent.tablename, ) rappend(Storage(field = joinby, entry = entry, )) # References in JSON field data json_references = s3db.get_config(table, "json_references") if json_references: if json_references is True: # Discover references in any JSON fields fields = table.fields else: # Discover references in fields specified by setting fields = json_references if not isinstance(fields, (tuple, list)): fields = [fields] for fieldname in fields: value = data.get(fieldname) field = table[fieldname] if value and field.type == "json": objref = S3ObjectReferences(value) for ref in objref.refs: rl = lookahead(None, tree = tree, directory = directory, lookup = ref, ) if rl: reference = rl[0] schedule(reference) rappend(Storage(field = fieldname, objref = objref, refkey = ref, entry = reference.entry, )) # Replacement reference deleted = data.get(xml.DELETED, False) if deleted: fieldname = xml.REPLACEDBY replaced_by = data.get(fieldname) if replaced_by: rl = lookahead(element, tree = tree, directory = directory, lookup = (table, replaced_by), ) if rl: reference = rl[0] schedule(reference) rappend(Storage(field = fieldname, entry = reference.entry, )) return item.item_id
[ "def", "add_item", "(", "self", ",", "element", "=", "None", ",", "original", "=", "None", ",", "components", "=", "None", ",", "parent", "=", "None", ",", "joinby", "=", "None", ",", ")", ":", "if", "element", "in", "self", ".", "elements", ":", "...
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3import.py#L3236-L3495
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pandas/core/indexes/category.py
python
CategoricalIndex.delete
(self, loc)
return self._create_from_codes(np.delete(self.codes, loc))
Make new Index with passed location(-s) deleted Returns ------- new_index : Index
Make new Index with passed location(-s) deleted
[ "Make", "new", "Index", "with", "passed", "location", "(", "-", "s", ")", "deleted" ]
def delete(self, loc): """ Make new Index with passed location(-s) deleted Returns ------- new_index : Index """ return self._create_from_codes(np.delete(self.codes, loc))
[ "def", "delete", "(", "self", ",", "loc", ")", ":", "return", "self", ".", "_create_from_codes", "(", "np", ".", "delete", "(", "self", ".", "codes", ",", "loc", ")", ")" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/indexes/category.py#L583-L591
partho-maple/coding-interview-gym
f9b28916da31935a27900794cfb8b91be3b38b9b
leetcode.com/python/289_Game_of_Life.py
python
Solution.gameOfLife
(self, board)
:type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead.
:type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead.
[ ":", "type", "board", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "None", "Do", "not", "return", "anything", "modify", "board", "in", "-", "place", "instead", "." ]
def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead. """ neighbours = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)] rows = len(board) cols = len(board[0]) boardClone = [[board[row][col] for col in range(cols)] for row in range(rows)] for row in range(rows): for col in range(cols): livingNeighbours = 0 for neighbour in neighbours: r = row + neighbour[0] c = col + neighbour[1] if (r < rows and r >= 0) and (c < cols and c >= 0) and (boardClone[r][c] == 1): livingNeighbours += 1 if boardClone[row][col] == 1 and (livingNeighbours < 2 or livingNeighbours > 3): board[row][col] = 0 if boardClone[row][col] == 0 and (livingNeighbours == 3): board[row][col] = 1
[ "def", "gameOfLife", "(", "self", ",", "board", ")", ":", "neighbours", "=", "[", "(", "1", ",", "0", ")", ",", "(", "1", ",", "-", "1", ")", ",", "(", "0", ",", "-", "1", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "(", "-", "1...
https://github.com/partho-maple/coding-interview-gym/blob/f9b28916da31935a27900794cfb8b91be3b38b9b/leetcode.com/python/289_Game_of_Life.py#L3-L23
robinhood/faust
01b4c0ad8390221db71751d80001b0fd879291e2
faust/tables/wrappers.py
python
WindowedItemsView.__iter__
(self)
return wrapper._items(self.event)
Iterate over items. The window is chosen based on the tables time-relativity setting.
Iterate over items.
[ "Iterate", "over", "items", "." ]
def __iter__(self) -> Iterator[Tuple[Any, Any]]: """Iterate over items. The window is chosen based on the tables time-relativity setting. """ wrapper = cast(WindowWrapper, self._mapping) return wrapper._items(self.event)
[ "def", "__iter__", "(", "self", ")", "->", "Iterator", "[", "Tuple", "[", "Any", ",", "Any", "]", "]", ":", "wrapper", "=", "cast", "(", "WindowWrapper", ",", "self", ".", "_mapping", ")", "return", "wrapper", ".", "_items", "(", "self", ".", "event"...
https://github.com/robinhood/faust/blob/01b4c0ad8390221db71751d80001b0fd879291e2/faust/tables/wrappers.py#L103-L109
OpenMDAO/OpenMDAO
f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd
openmdao/solvers/solver.py
python
Solver.__init__
(self, **kwargs)
Initialize all attributes.
Initialize all attributes.
[ "Initialize", "all", "attributes", "." ]
def __init__(self, **kwargs): """ Initialize all attributes. """ self._system = None self._depth = 0 self._mode = 'fwd' self._iter_count = 0 self._problem_meta = None # Solver options self.options = OptionsDictionary(parent_name=self.msginfo) self.options.declare('maxiter', types=int, default=10, desc='maximum number of iterations') self.options.declare('atol', default=1e-10, desc='absolute error tolerance') self.options.declare('rtol', default=1e-10, desc='relative error tolerance') self.options.declare('iprint', types=int, default=1, desc='whether to print output') self.options.declare('err_on_non_converge', types=bool, default=False, desc="When True, AnalysisError will be raised if we don't converge.") # Case recording options self.recording_options = OptionsDictionary(parent_name=self.msginfo) self.recording_options.declare('record_abs_error', types=bool, default=True, desc='Set to True to record absolute error at the \ solver level') self.recording_options.declare('record_rel_error', types=bool, default=True, desc='Set to True to record relative error at the \ solver level') self.recording_options.declare('record_inputs', types=bool, default=True, desc='Set to True to record inputs at the solver level') self.recording_options.declare('record_outputs', types=bool, default=True, desc='Set to True to record outputs at the solver level') self.recording_options.declare('record_solver_residuals', types=bool, default=False, desc='Set to True to record residuals at the solver level') self.recording_options.declare('record_metadata', types=bool, desc='Deprecated. Recording ' 'of metadata will always be done', deprecation="The recording option, record_metadata, on " "Solver is " "deprecated. Recording of metadata will always be done", default=True) self.recording_options.declare('includes', types=list, default=['*'], desc="Patterns for variables to include in recording. \ Paths are relative to solver's Group. \ Uses fnmatch wildcards") self.recording_options.declare('excludes', types=list, default=[], desc="Patterns for vars to exclude in recording. \ (processed post-includes) \ Paths are relative to solver's Group. \ Uses fnmatch wildcards" ) # Case recording related self._filtered_vars_to_record = {} self._norm0 = 0.0 # What the solver supports. self.supports = OptionsDictionary(parent_name=self.msginfo) self.supports.declare('gradients', types=bool, default=False) self.supports.declare('implicit_components', types=bool, default=False) self._declare_options() self.options.update(kwargs) self._rec_mgr = RecordingManager() self.cite = ""
[ "def", "__init__", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_system", "=", "None", "self", ".", "_depth", "=", "0", "self", ".", "_mode", "=", "'fwd'", "self", ".", "_iter_count", "=", "0", "self", ".", "_problem_meta", "=", "N...
https://github.com/OpenMDAO/OpenMDAO/blob/f47eb5485a0bb5ea5d2ae5bd6da4b94dc6b296bd/openmdao/solvers/solver.py#L150-L217
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/examples/particle_systems.py
python
emitter_10
()
return emitter_10.__doc__, e
Burst, emit from center, velocity from angle with spread
Burst, emit from center, velocity from angle with spread
[ "Burst", "emit", "from", "center", "velocity", "from", "angle", "with", "spread" ]
def emitter_10(): """Burst, emit from center, velocity from angle with spread""" e = arcade.Emitter( center_xy=CENTER_POS, emit_controller=arcade.EmitBurst(BURST_PARTICLE_COUNT // 4), particle_factory=lambda emitter: arcade.LifetimeParticle( filename_or_texture=TEXTURE, change_xy=arcade.rand_vec_spread_deg(90, 45, 2.0), lifetime=DEFAULT_PARTICLE_LIFETIME, scale=DEFAULT_SCALE, alpha=DEFAULT_ALPHA ) ) return emitter_10.__doc__, e
[ "def", "emitter_10", "(", ")", ":", "e", "=", "arcade", ".", "Emitter", "(", "center_xy", "=", "CENTER_POS", ",", "emit_controller", "=", "arcade", ".", "EmitBurst", "(", "BURST_PARTICLE_COUNT", "//", "4", ")", ",", "particle_factory", "=", "lambda", "emitte...
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/examples/particle_systems.py#L216-L229
nryoung/algorithms
636a4519832849dcb6516f2ef78428872b3bb81c
algorithms/data_structures/digraph.py
python
Digraph.add_edge
(self, src, dest)
Adds an undirected edge 'src'-'dest' to the graph. Worst Case Complexity O(1)
Adds an undirected edge 'src'-'dest' to the graph.
[ "Adds", "an", "undirected", "edge", "src", "-", "dest", "to", "the", "graph", "." ]
def add_edge(self, src, dest): """ Adds an undirected edge 'src'-'dest' to the graph. Worst Case Complexity O(1) """ if src in self.__adj: self.__adj[src].append(dest) else: self.__adj[src] = [dest] self.__v_count += 1 if dest in self.__adj: pass else: self.__adj[dest] = [] self.__v_count += 1 self.__e_count += 1
[ "def", "add_edge", "(", "self", ",", "src", ",", "dest", ")", ":", "if", "src", "in", "self", ".", "__adj", ":", "self", ".", "__adj", "[", "src", "]", ".", "append", "(", "dest", ")", "else", ":", "self", ".", "__adj", "[", "src", "]", "=", ...
https://github.com/nryoung/algorithms/blob/636a4519832849dcb6516f2ef78428872b3bb81c/algorithms/data_structures/digraph.py#L35-L54
catalyst-cooperative/pudl
40d176313e60dfa9d2481f63842ed23f08f1ad5f
src/pudl/output/pudltabl.py
python
PudlTabl.distribution_systems_eia861
(self, update=False)
return self._dfs["distribution_systems_eia861"]
An interim EIA 861 output function.
An interim EIA 861 output function.
[ "An", "interim", "EIA", "861", "output", "function", "." ]
def distribution_systems_eia861(self, update=False): """An interim EIA 861 output function.""" self.etl_eia861(update=update) return self._dfs["distribution_systems_eia861"]
[ "def", "distribution_systems_eia861", "(", "self", ",", "update", "=", "False", ")", ":", "self", ".", "etl_eia861", "(", "update", "=", "update", ")", "return", "self", ".", "_dfs", "[", "\"distribution_systems_eia861\"", "]" ]
https://github.com/catalyst-cooperative/pudl/blob/40d176313e60dfa9d2481f63842ed23f08f1ad5f/src/pudl/output/pudltabl.py#L282-L285
dpp/simply_lift
cf49f7dcce81c7f1557314dd0f0bb08aaedc73da
elyxer.py
python
RawTemplate.getfooter
(self)
return ['\n\n<!--endhtml-->']
Get the raw footer.
Get the raw footer.
[ "Get", "the", "raw", "footer", "." ]
def getfooter(self): "Get the raw footer." return ['\n\n<!--endhtml-->']
[ "def", "getfooter", "(", "self", ")", ":", "return", "[", "'\\n\\n<!--endhtml-->'", "]" ]
https://github.com/dpp/simply_lift/blob/cf49f7dcce81c7f1557314dd0f0bb08aaedc73da/elyxer.py#L3411-L3413
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/interface.py
python
check_hostname
()
return False
Check if hostname is allowed, to mitigate DNS-rebinding attack. Similar to CVE-2019-5702, we need to add protection even if only allowed to be accessed via localhost.
Check if hostname is allowed, to mitigate DNS-rebinding attack. Similar to CVE-2019-5702, we need to add protection even if only allowed to be accessed via localhost.
[ "Check", "if", "hostname", "is", "allowed", "to", "mitigate", "DNS", "-", "rebinding", "attack", ".", "Similar", "to", "CVE", "-", "2019", "-", "5702", "we", "need", "to", "add", "protection", "even", "if", "only", "allowed", "to", "be", "accessed", "via...
def check_hostname(): """Check if hostname is allowed, to mitigate DNS-rebinding attack. Similar to CVE-2019-5702, we need to add protection even if only allowed to be accessed via localhost. """ # If login is enabled, no API-key can be deducted if cfg.username() and cfg.password(): return True # Don't allow requests without Host host = cherrypy.request.headers.get("Host") if not host: return False # Remove the port-part (like ':8080'), if it is there, always on the right hand side. # Not to be confused with IPv6 colons (within square brackets) host = re.sub(":[0123456789]+$", "", host).lower() # Fine if localhost or IP if host == "localhost" or is_ipv4_addr(host) or is_ipv6_addr(host): return True # Check on the whitelist if host in cfg.host_whitelist(): return True # Fine if ends with ".local" or ".local.", aka mDNS name # See rfc6762 Multicast DNS if host.endswith((".local", ".local.")): return True # Ohoh, bad log_warning_and_ip(T('Refused connection with hostname "%s" from:') % host) return False
[ "def", "check_hostname", "(", ")", ":", "# If login is enabled, no API-key can be deducted", "if", "cfg", ".", "username", "(", ")", "and", "cfg", ".", "password", "(", ")", ":", "return", "True", "# Don't allow requests without Host", "host", "=", "cherrypy", ".", ...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/interface.py#L204-L237
yanx27/Pointnet_Pointnet2_pytorch
e365b9f7b9c3d7d6444278d92e298e3f078794e1
visualizer/plyfile.py
python
PlyElement._parse_multi
(header_lines)
return elements
Parse a list of PLY element definitions.
Parse a list of PLY element definitions.
[ "Parse", "a", "list", "of", "PLY", "element", "definitions", "." ]
def _parse_multi(header_lines): ''' Parse a list of PLY element definitions. ''' elements = [] while header_lines: (elt, header_lines) = PlyElement._parse_one(header_lines) elements.append(elt) return elements
[ "def", "_parse_multi", "(", "header_lines", ")", ":", "elements", "=", "[", "]", "while", "header_lines", ":", "(", "elt", ",", "header_lines", ")", "=", "PlyElement", ".", "_parse_one", "(", "header_lines", ")", "elements", ".", "append", "(", "elt", ")",...
https://github.com/yanx27/Pointnet_Pointnet2_pytorch/blob/e365b9f7b9c3d7d6444278d92e298e3f078794e1/visualizer/plyfile.py#L439-L448
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/lib/picklable_file_io.py
python
pickle_open
(name, mode='rt')
Open file and return a stream with pickle function implemented. This function returns a FileIOPicklable object wrapped in a BufferIOPicklable class when given the "rb" reading mode, or a FileIOPicklable object wrapped in a TextIOPicklable class with the "r" or "rt" reading mode. It can be used as a context manager, and replace the built-in :func:`open` function in read mode that only returns an unpicklable file object. In order to serialize a :class:`MDAnalysis.core.Universe`, this function can used to open trajectory/topology files. This object composition is more flexible and easier than class inheritance to implement pickling for new readers. Note ---- Can be only used with read mode. Parameters ---------- name : str either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened. mode: {'r', 'rt', 'rb'} (optional) 'r': open for reading in text mode; 'rt': read in text mode (default); 'rb': read in binary mode; Returns ------- stream-like object: BufferIOPicklable or TextIOPicklable when mode is 'r' or 'rt', returns TextIOPicklable; when mode is 'rb', returns BufferIOPicklable Raises ------ ValueError if `mode` is not one of the allowed read modes Examples ------- open as context manager:: with pickle_open('filename') as f: line = f.readline() open as function:: f = pickle_open('filename') line = f.readline() f.close() See Also -------- :func:`MDAnalysis.lib.util.anyopen` :func:`io.open` .. versionadded:: 2.0.0
Open file and return a stream with pickle function implemented.
[ "Open", "file", "and", "return", "a", "stream", "with", "pickle", "function", "implemented", "." ]
def pickle_open(name, mode='rt'): """Open file and return a stream with pickle function implemented. This function returns a FileIOPicklable object wrapped in a BufferIOPicklable class when given the "rb" reading mode, or a FileIOPicklable object wrapped in a TextIOPicklable class with the "r" or "rt" reading mode. It can be used as a context manager, and replace the built-in :func:`open` function in read mode that only returns an unpicklable file object. In order to serialize a :class:`MDAnalysis.core.Universe`, this function can used to open trajectory/topology files. This object composition is more flexible and easier than class inheritance to implement pickling for new readers. Note ---- Can be only used with read mode. Parameters ---------- name : str either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened. mode: {'r', 'rt', 'rb'} (optional) 'r': open for reading in text mode; 'rt': read in text mode (default); 'rb': read in binary mode; Returns ------- stream-like object: BufferIOPicklable or TextIOPicklable when mode is 'r' or 'rt', returns TextIOPicklable; when mode is 'rb', returns BufferIOPicklable Raises ------ ValueError if `mode` is not one of the allowed read modes Examples ------- open as context manager:: with pickle_open('filename') as f: line = f.readline() open as function:: f = pickle_open('filename') line = f.readline() f.close() See Also -------- :func:`MDAnalysis.lib.util.anyopen` :func:`io.open` .. versionadded:: 2.0.0 """ if mode not in {'r', 'rt', 'rb'}: raise ValueError("Only read mode ('r', 'rt', 'rb') " "files can be pickled.") name = os.fspath(name) raw = FileIOPicklable(name) if mode == 'rb': return BufferIOPicklable(raw) elif mode in {'r', 'rt'}: return TextIOPicklable(raw)
[ "def", "pickle_open", "(", "name", ",", "mode", "=", "'rt'", ")", ":", "if", "mode", "not", "in", "{", "'r'", ",", "'rt'", ",", "'rb'", "}", ":", "raise", "ValueError", "(", "\"Only read mode ('r', 'rt', 'rb') \"", "\"files can be pickled.\"", ")", "name", "...
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/lib/picklable_file_io.py#L341-L410
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/dis.py
python
get_instructions
(x, *, first_line=None)
return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names, co.co_consts, cell_names, linestarts, line_offset)
Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. If *first_line* is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object.
Iterator for the opcodes in methods, functions or code
[ "Iterator", "for", "the", "opcodes", "in", "methods", "functions", "or", "code" ]
def get_instructions(x, *, first_line=None): """Iterator for the opcodes in methods, functions or code Generates a series of Instruction named tuples giving the details of each operations in the supplied code. If *first_line* is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object. """ co = _get_code_object(x) cell_names = co.co_cellvars + co.co_freevars linestarts = dict(findlinestarts(co)) if first_line is not None: line_offset = first_line - co.co_firstlineno else: line_offset = 0 return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names, co.co_consts, cell_names, linestarts, line_offset)
[ "def", "get_instructions", "(", "x", ",", "*", ",", "first_line", "=", "None", ")", ":", "co", "=", "_get_code_object", "(", "x", ")", "cell_names", "=", "co", ".", "co_cellvars", "+", "co", ".", "co_freevars", "linestarts", "=", "dict", "(", "findlinest...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/dis.py#L261-L281
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/cloud/clouds/digitalocean.py
python
stop
(name, call=None)
return { "success": True, "action": ret["action"]["type"], "state": ret["action"]["status"], }
Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name
Stop a droplet in DigitalOcean.
[ "Stop", "a", "droplet", "in", "DigitalOcean", "." ]
def stop(name, call=None): """ Stop a droplet in DigitalOcean. .. versionadded:: 2015.8.8 name The name of the droplet to stop. CLI Example: .. code-block:: bash salt-cloud -a stop droplet_name """ if call != "action": raise SaltCloudSystemExit("The stop action must be called with -a or --action.") data = show_instance(name, call="action") if data.get("status") == "off": return { "success": True, "action": "stop", "status": "off", "msg": "Machine is already off.", } ret = query( droplet_id=data["id"], command="actions", args={"type": "shutdown"}, http_method="post", ) return { "success": True, "action": ret["action"]["type"], "state": ret["action"]["status"], }
[ "def", "stop", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "\"action\"", ":", "raise", "SaltCloudSystemExit", "(", "\"The stop action must be called with -a or --action.\"", ")", "data", "=", "show_instance", "(", "name", ",", "call", "=...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/cloud/clouds/digitalocean.py#L1377-L1415
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/calendar.py
python
Calendar.__init__
(self, firstweekday=0)
[]
def __init__(self, firstweekday=0): self.firstweekday = firstweekday
[ "def", "__init__", "(", "self", ",", "firstweekday", "=", "0", ")", ":", "self", ".", "firstweekday", "=", "firstweekday" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/calendar.py#L132-L133
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/decimal.py
python
Decimal.number_class
(self, context=None)
Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity
Returns an indication of the class of self.
[ "Returns", "an", "indication", "of", "the", "class", "of", "self", "." ]
def number_class(self, context=None): """Returns an indication of the class of self. The class is one of the following strings: sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity """ if self.is_snan(): return "sNaN" if self.is_qnan(): return "NaN" inf = self._isinfinity() if inf == 1: return "+Infinity" if inf == -1: return "-Infinity" if self.is_zero(): if self._sign: return "-Zero" else: return "+Zero" if context is None: context = getcontext() if self.is_subnormal(context=context): if self._sign: return "-Subnormal" else: return "+Subnormal" # just a normal, regular, boring number, :) if self._sign: return "-Normal" else: return "+Normal"
[ "def", "number_class", "(", "self", ",", "context", "=", "None", ")", ":", "if", "self", ".", "is_snan", "(", ")", ":", "return", "\"sNaN\"", "if", "self", ".", "is_qnan", "(", ")", ":", "return", "\"NaN\"", "inf", "=", "self", ".", "_isinfinity", "(...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/decimal.py#L3484-L3524
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
PySimpleGUI.py
python
TKOutput.__init__
(self, parent, width, height, bd, background_color=None, text_color=None, echo_stdout_stderr=False, font=None, pad=None)
:param parent: The "Root" that the Widget will be in :type parent: tk.Tk | tk.Toplevel :param width: Width in characters :type width: (int) :param height: height in rows :type height: (int) :param bd: Border Depth. How many pixels of border to show :type bd: (int) :param background_color: color of background :type background_color: (str) :param text_color: color of the text :type text_color: (str) :param echo_stdout_stderr: If True then output to stdout will be output to this element AND also to the normal console location :type echo_stdout_stderr: (bool) :param font: specifies the font family, size, etc. Tuple or Single string format 'name size styles'. Styles: italic * roman bold normal underline overstrike :type font: (str or (str, int[, str]) or None) :param pad: Amount of padding to put around element in pixels (left/right, top/bottom) or ((left, right), (top, bottom)) or an int. If an int, then it's converted into a tuple (int, int) :type pad: (int, int) or ((int, int),(int,int)) or (int,(int,int)) or ((int, int),int) | int
:param parent: The "Root" that the Widget will be in :type parent: tk.Tk | tk.Toplevel :param width: Width in characters :type width: (int) :param height: height in rows :type height: (int) :param bd: Border Depth. How many pixels of border to show :type bd: (int) :param background_color: color of background :type background_color: (str) :param text_color: color of the text :type text_color: (str) :param echo_stdout_stderr: If True then output to stdout will be output to this element AND also to the normal console location :type echo_stdout_stderr: (bool) :param font: specifies the font family, size, etc. Tuple or Single string format 'name size styles'. Styles: italic * roman bold normal underline overstrike :type font: (str or (str, int[, str]) or None) :param pad: Amount of padding to put around element in pixels (left/right, top/bottom) or ((left, right), (top, bottom)) or an int. If an int, then it's converted into a tuple (int, int) :type pad: (int, int) or ((int, int),(int,int)) or (int,(int,int)) or ((int, int),int) | int
[ ":", "param", "parent", ":", "The", "Root", "that", "the", "Widget", "will", "be", "in", ":", "type", "parent", ":", "tk", ".", "Tk", "|", "tk", ".", "Toplevel", ":", "param", "width", ":", "Width", "in", "characters", ":", "type", "width", ":", "(...
def __init__(self, parent, width, height, bd, background_color=None, text_color=None, echo_stdout_stderr=False, font=None, pad=None): """ :param parent: The "Root" that the Widget will be in :type parent: tk.Tk | tk.Toplevel :param width: Width in characters :type width: (int) :param height: height in rows :type height: (int) :param bd: Border Depth. How many pixels of border to show :type bd: (int) :param background_color: color of background :type background_color: (str) :param text_color: color of the text :type text_color: (str) :param echo_stdout_stderr: If True then output to stdout will be output to this element AND also to the normal console location :type echo_stdout_stderr: (bool) :param font: specifies the font family, size, etc. Tuple or Single string format 'name size styles'. Styles: italic * roman bold normal underline overstrike :type font: (str or (str, int[, str]) or None) :param pad: Amount of padding to put around element in pixels (left/right, top/bottom) or ((left, right), (top, bottom)) or an int. If an int, then it's converted into a tuple (int, int) :type pad: (int, int) or ((int, int),(int,int)) or (int,(int,int)) or ((int, int),int) | int """ self.frame = tk.Frame(parent) tk.Frame.__init__(self, self.frame) self.output = tk.Text(self.frame, width=width, height=height, bd=bd, font=font) if background_color and background_color != COLOR_SYSTEM_DEFAULT: self.output.configure(background=background_color) self.frame.configure(background=background_color) if text_color and text_color != COLOR_SYSTEM_DEFAULT: self.output.configure(fg=text_color) self.output.configure(insertbackground=text_color) self.vsb = tk.Scrollbar(self.frame, orient="vertical", command=self.output.yview) self.output.configure(yscrollcommand=self.vsb.set) self.output.pack(side="left", fill="both", expand=True) self.vsb.pack(side="left", fill="y", expand=False) self.frame.pack(side="left", padx=pad[0], pady=pad[1], expand=True, fill='y') self.previous_stdout = sys.stdout self.previous_stderr = sys.stderr self.parent = parent self.echo_stdout_stderr = echo_stdout_stderr sys.stdout = self sys.stderr = self self.pack()
[ "def", "__init__", "(", "self", ",", "parent", ",", "width", ",", "height", ",", "bd", ",", "background_color", "=", "None", ",", "text_color", "=", "None", ",", "echo_stdout_stderr", "=", "False", ",", "font", "=", "None", ",", "pad", "=", "None", ")"...
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUI.py#L3826-L3868
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/FCN/tensorflow-fcn2/fcn16_vgg.py
python
FCN16VGG._bias_reshape
(self, bweight, num_orig, num_new)
return avg_bweight
Build bias weights for filter produces with `_summary_reshape`
Build bias weights for filter produces with `_summary_reshape`
[ "Build", "bias", "weights", "for", "filter", "produces", "with", "_summary_reshape" ]
def _bias_reshape(self, bweight, num_orig, num_new): """ Build bias weights for filter produces with `_summary_reshape` """ n_averaged_elements = num_orig//num_new avg_bweight = np.zeros(num_new) for i in range(0, num_orig, n_averaged_elements): start_idx = i end_idx = start_idx + n_averaged_elements avg_idx = start_idx//n_averaged_elements if avg_idx == num_new: break avg_bweight[avg_idx] = np.mean(bweight[start_idx:end_idx]) return avg_bweight
[ "def", "_bias_reshape", "(", "self", ",", "bweight", ",", "num_orig", ",", "num_new", ")", ":", "n_averaged_elements", "=", "num_orig", "//", "num_new", "avg_bweight", "=", "np", ".", "zeros", "(", "num_new", ")", "for", "i", "in", "range", "(", "0", ","...
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/FCN/tensorflow-fcn2/fcn16_vgg.py#L301-L314
xxbb1234021/speech_recognition
d974d98286be5605db3ddb6cd2e39e8c16215d3f
utils.py
python
create_dict
(text_labels)
return words_size, words, word_num_map
构建字典 :param text_labels: :return:
构建字典 :param text_labels: :return:
[ "构建字典", ":", "param", "text_labels", ":", ":", "return", ":" ]
def create_dict(text_labels): """ 构建字典 :param text_labels: :return: """ all_words = [] for label in text_labels: # print(label) all_words += [word for word in label] counter = Counter(all_words) words = sorted(counter) words_size = len(words) word_num_map = dict(zip(words, range(words_size))) print('字表大小:', words_size) return words_size, words, word_num_map
[ "def", "create_dict", "(", "text_labels", ")", ":", "all_words", "=", "[", "]", "for", "label", "in", "text_labels", ":", "# print(label)", "all_words", "+=", "[", "word", "for", "word", "in", "label", "]", "counter", "=", "Counter", "(", "all_words", ")",...
https://github.com/xxbb1234021/speech_recognition/blob/d974d98286be5605db3ddb6cd2e39e8c16215d3f/utils.py#L62-L78
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/template/base.py
python
Lexer.create_token
(self, token_string, in_tag)
return token
Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string.
Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string.
[ "Convert", "the", "given", "token", "string", "into", "a", "new", "Token", "object", "and", "return", "it", ".", "If", "in_tag", "is", "True", "we", "are", "processing", "something", "that", "matched", "a", "tag", "otherwise", "it", "should", "be", "treate...
def create_token(self, token_string, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: # The [2:-2] ranges below strip off *_TAG_START and *_TAG_END. # We could do len(BLOCK_TAG_START) to be more "correct", but we've # hard-coded the 2s here for performance. And it's not like # the TAG_START values are going to change anytime, anyway. if token_string.startswith(VARIABLE_TAG_START): token = Token(TOKEN_VAR, token_string[2:-2].strip()) elif token_string.startswith(BLOCK_TAG_START): token = Token(TOKEN_BLOCK, token_string[2:-2].strip()) elif token_string.startswith(COMMENT_TAG_START): content = '' if token_string.find(TRANSLATOR_COMMENT_MARK): content = token_string[2:-2].strip() token = Token(TOKEN_COMMENT, content) else: token = Token(TOKEN_TEXT, token_string) token.lineno = self.lineno self.lineno += token_string.count('\n') return token
[ "def", "create_token", "(", "self", ",", "token_string", ",", "in_tag", ")", ":", "if", "in_tag", ":", "# The [2:-2] ranges below strip off *_TAG_START and *_TAG_END.", "# We could do len(BLOCK_TAG_START) to be more \"correct\", but we've", "# hard-coded the 2s here for performance. An...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/template/base.py#L200-L224
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/ssl.py
python
SSLSocket.connect
(self, addr)
Connects to remote ADDR, and then wraps the connection in an SSL channel.
Connects to remote ADDR, and then wraps the connection in an SSL channel.
[ "Connects", "to", "remote", "ADDR", "and", "then", "wraps", "the", "connection", "in", "an", "SSL", "channel", "." ]
def connect(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" self._real_connect(addr, False)
[ "def", "connect", "(", "self", ",", "addr", ")", ":", "self", ".", "_real_connect", "(", "addr", ",", "False", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/ssl.py#L319-L322
weechat/scripts
99ec0e7eceefabb9efb0f11ec26d45d6e8e84335
python/nameday.py
python
nameday_config_cb
(data, option, value)
return weechat.WEECHAT_RC_OK
Called each time an option is changed.
Called each time an option is changed.
[ "Called", "each", "time", "an", "option", "is", "changed", "." ]
def nameday_config_cb(data, option, value): """Called each time an option is changed.""" nameday_load_config() nameday_build_item() weechat.bar_item_update('nameday') return weechat.WEECHAT_RC_OK
[ "def", "nameday_config_cb", "(", "data", ",", "option", ",", "value", ")", ":", "nameday_load_config", "(", ")", "nameday_build_item", "(", ")", "weechat", ".", "bar_item_update", "(", "'nameday'", ")", "return", "weechat", ".", "WEECHAT_RC_OK" ]
https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/nameday.py#L495-L500
yeephycho/nasnet-tensorflow
189e22f2de9d6ee1b4abd0a65275d5e6a6c04c45
nets/lenet.py
python
lenet
(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, prediction_fn=slim.softmax, scope='LeNet')
return logits, end_points
Creates a variant of the LeNet model. Note that since the output is a set of 'logits', the values fall in the interval of (-infinity, infinity). Consequently, to convert the outputs to a probability distribution over the characters, one will need to convert them using the softmax function: logits = lenet.lenet(images, is_training=False) probabilities = tf.nn.softmax(logits) predictions = tf.argmax(logits, 1) Args: images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: specifies whether or not we're currently training the model. This variable will determine the behaviour of the dropout layer. dropout_keep_prob: the percentage of activation values that are retained. prediction_fn: a function to get predictions out of logits. scope: Optional variable_scope. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the inon-dropped-out nput to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation.
Creates a variant of the LeNet model.
[ "Creates", "a", "variant", "of", "the", "LeNet", "model", "." ]
def lenet(images, num_classes=10, is_training=False, dropout_keep_prob=0.5, prediction_fn=slim.softmax, scope='LeNet'): """Creates a variant of the LeNet model. Note that since the output is a set of 'logits', the values fall in the interval of (-infinity, infinity). Consequently, to convert the outputs to a probability distribution over the characters, one will need to convert them using the softmax function: logits = lenet.lenet(images, is_training=False) probabilities = tf.nn.softmax(logits) predictions = tf.argmax(logits, 1) Args: images: A batch of `Tensors` of size [batch_size, height, width, channels]. num_classes: the number of classes in the dataset. If 0 or None, the logits layer is omitted and the input features to the logits layer are returned instead. is_training: specifies whether or not we're currently training the model. This variable will determine the behaviour of the dropout layer. dropout_keep_prob: the percentage of activation values that are retained. prediction_fn: a function to get predictions out of logits. scope: Optional variable_scope. Returns: net: a 2D Tensor with the logits (pre-softmax activations) if num_classes is a non-zero integer, or the inon-dropped-out nput to the logits layer if num_classes is 0 or None. end_points: a dictionary from components of the network to the corresponding activation. """ end_points = {} with tf.variable_scope(scope, 'LeNet', [images]): net = end_points['conv1'] = slim.conv2d(images, 32, [5, 5], scope='conv1') net = end_points['pool1'] = slim.max_pool2d(net, [2, 2], 2, scope='pool1') net = end_points['conv2'] = slim.conv2d(net, 64, [5, 5], scope='conv2') net = end_points['pool2'] = slim.max_pool2d(net, [2, 2], 2, scope='pool2') net = slim.flatten(net) end_points['Flatten'] = net net = end_points['fc3'] = slim.fully_connected(net, 1024, scope='fc3') if not num_classes: return net, end_points net = end_points['dropout3'] = slim.dropout( net, dropout_keep_prob, is_training=is_training, scope='dropout3') logits = end_points['Logits'] = slim.fully_connected( net, num_classes, activation_fn=None, scope='fc4') end_points['Predictions'] = prediction_fn(logits, scope='Predictions') return logits, end_points
[ "def", "lenet", "(", "images", ",", "num_classes", "=", "10", ",", "is_training", "=", "False", ",", "dropout_keep_prob", "=", "0.5", ",", "prediction_fn", "=", "slim", ".", "softmax", ",", "scope", "=", "'LeNet'", ")", ":", "end_points", "=", "{", "}", ...
https://github.com/yeephycho/nasnet-tensorflow/blob/189e22f2de9d6ee1b4abd0a65275d5e6a6c04c45/nets/lenet.py#L26-L79
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/interpreter/dependencyfallbacks.py
python
DependencyFallbacksHolder._get_subproject_variable
(self, subproject: SubprojectHolder, varname: str)
return var_dep
[]
def _get_subproject_variable(self, subproject: SubprojectHolder, varname: str) -> T.Optional[Dependency]: try: var_dep = subproject.get_variable_method([varname], {}) except InvalidArguments: var_dep = None if not isinstance(var_dep, Dependency): mlog.warning(f'Variable {varname!r} in the subproject {subproject.subdir!r} is', 'not found' if var_dep is None else 'not a dependency object') return None return var_dep
[ "def", "_get_subproject_variable", "(", "self", ",", "subproject", ":", "SubprojectHolder", ",", "varname", ":", "str", ")", "->", "T", ".", "Optional", "[", "Dependency", "]", ":", "try", ":", "var_dep", "=", "subproject", ".", "get_variable_method", "(", "...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/interpreter/dependencyfallbacks.py#L239-L248
trezor/python-trezor
2813522b05cef4e0e545a101f8b3559a3183b45b
trezorlib/debuglink.py
python
NullDebugLink.__init__
(self)
[]
def __init__(self): super().__init__(None)
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", "None", ")" ]
https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/debuglink.py#L137-L138
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/virt/vmwareapi/vm_util.py
python
_get_allocated_vnc_ports
(session)
return vnc_ports
Return an integer set of all allocated VNC ports.
Return an integer set of all allocated VNC ports.
[ "Return", "an", "integer", "set", "of", "all", "allocated", "VNC", "ports", "." ]
def _get_allocated_vnc_ports(session): """Return an integer set of all allocated VNC ports.""" # TODO(rgerganov): bug #1256944 # The VNC port should be unique per host, not per vCenter vnc_ports = set() result = session._call_method(vim_util, "get_objects", "VirtualMachine", [VNC_CONFIG_KEY]) with vutil.WithRetrieval(session.vim, result) as objects: for obj in objects: if not hasattr(obj, 'propSet') or not obj.propSet: continue dynamic_prop = obj.propSet[0] option_value = dynamic_prop.val vnc_port = option_value.value vnc_ports.add(int(vnc_port)) return vnc_ports
[ "def", "_get_allocated_vnc_ports", "(", "session", ")", ":", "# TODO(rgerganov): bug #1256944", "# The VNC port should be unique per host, not per vCenter", "vnc_ports", "=", "set", "(", ")", "result", "=", "session", ".", "_call_method", "(", "vim_util", ",", "\"get_object...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/virt/vmwareapi/vm_util.py#L1058-L1073
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/plat-mac/pimp.py
python
PimpDatabase.description
(self)
return self._description
[]
def description(self): return self._description
[ "def", "description", "(", "self", ")", ":", "return", "self", ".", "_description" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/pimp.py#L377-L377
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/metrics/__init__.py
python
register_threadpool
(name: str, threadpool: ThreadPool)
Add metrics for the threadpool.
Add metrics for the threadpool.
[ "Add", "metrics", "for", "the", "threadpool", "." ]
def register_threadpool(name: str, threadpool: ThreadPool) -> None: """Add metrics for the threadpool.""" threadpool_total_min_threads.labels(name).set(threadpool.min) threadpool_total_max_threads.labels(name).set(threadpool.max) threadpool_total_threads.labels(name).set_function(lambda: len(threadpool.threads)) threadpool_total_working_threads.labels(name).set_function( lambda: len(threadpool.working) )
[ "def", "register_threadpool", "(", "name", ":", "str", ",", "threadpool", ":", "ThreadPool", ")", "->", "None", ":", "threadpool_total_min_threads", ".", "labels", "(", "name", ")", ".", "set", "(", "threadpool", ".", "min", ")", "threadpool_total_max_threads", ...
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/metrics/__init__.py#L591-L600
enthought/chaco
0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f
chaco/plots/barplot.py
python
BarPlot._draw_plot
(self, gc, view_bounds=None, mode="normal")
Draws the 'plot' layer.
Draws the 'plot' layer.
[ "Draws", "the", "plot", "layer", "." ]
def _draw_plot(self, gc, view_bounds=None, mode="normal"): """Draws the 'plot' layer.""" if not self._cache_valid: self._gather_points() data = self._cached_data_pts if data.size == 0: # Nothing to draw. return with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) gc.set_antialias(self.antialias) gc.set_stroke_color(self.effective_line_color) gc.set_fill_color(self.effective_fill_color) gc.set_line_width(self.line_width) if self.bar_width_type == "data": # map the bar start and stop locations into screen space lower_left_pts = self.map_screen(data[:, (0, 2)]) upper_right_pts = self.map_screen(data[:, (1, 3)]) else: half_width = self.bar_width / 2.0 # map the bar centers into screen space and then compute the bar # start and end positions lower_left_pts = self.map_screen(data[:, (0, 1)]) upper_right_pts = self.map_screen(data[:, (0, 2)]) lower_left_pts[:, 0] -= half_width upper_right_pts[:, 0] += half_width bounds = upper_right_pts - lower_left_pts gc.rects(column_stack((lower_left_pts, bounds))) gc.draw_path()
[ "def", "_draw_plot", "(", "self", ",", "gc", ",", "view_bounds", "=", "None", ",", "mode", "=", "\"normal\"", ")", ":", "if", "not", "self", ".", "_cache_valid", ":", "self", ".", "_gather_points", "(", ")", "data", "=", "self", ".", "_cached_data_pts", ...
https://github.com/enthought/chaco/blob/0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f/chaco/plots/barplot.py#L307-L339
vlachoudis/bCNC
67126b4894dabf6579baf47af8d0f9b7de35e6e3
bCNC/lib/svg_elements.py
python
_Polyshape.property_by_args
(self, *args)
[]
def property_by_args(self, *args): self._init_points(args)
[ "def", "property_by_args", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_init_points", "(", "args", ")" ]
https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/svg_elements.py#L6349-L6350
vispy/vispy
26256fdc2574259dd227022fbce0767cae4e244b
vispy/visuals/scrolling_lines.py
python
ScrollingLinesVisual.roll_data
(self, data)
Append new data to the right side of every line strip and remove as much data from the left. Parameters ---------- data : array-like A data array to append.
Append new data to the right side of every line strip and remove as much data from the left.
[ "Append", "new", "data", "to", "the", "right", "side", "of", "every", "line", "strip", "and", "remove", "as", "much", "data", "from", "the", "left", "." ]
def roll_data(self, data): """Append new data to the right side of every line strip and remove as much data from the left. Parameters ---------- data : array-like A data array to append. """ data = data.astype('float32')[..., np.newaxis] s1 = self._data_shape[1] - self._offset if data.shape[1] > s1: self._pos_tex[:, self._offset:] = data[:, :s1] self._pos_tex[:, :data.shape[1] - s1] = data[:, s1:] self._offset = (self._offset + data.shape[1]) % self._data_shape[1] else: self._pos_tex[:, self._offset:self._offset+data.shape[1]] = data self._offset += data.shape[1] self.shared_program['offset'] = self._offset self.update()
[ "def", "roll_data", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "astype", "(", "'float32'", ")", "[", "...", ",", "np", ".", "newaxis", "]", "s1", "=", "self", ".", "_data_shape", "[", "1", "]", "-", "self", ".", "_offset", "if"...
https://github.com/vispy/vispy/blob/26256fdc2574259dd227022fbce0767cae4e244b/vispy/visuals/scrolling_lines.py#L165-L184
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/networking_v1_api.py
python
NetworkingV1Api.delete_collection_namespaced_network_policy
(self, namespace, **kwargs)
return self.delete_collection_namespaced_network_policy_with_http_info(namespace, **kwargs)
delete_collection_namespaced_network_policy # noqa: E501 delete collection of NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_network_policy(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread.
delete_collection_namespaced_network_policy # noqa: E501
[ "delete_collection_namespaced_network_policy", "#", "noqa", ":", "E501" ]
def delete_collection_namespaced_network_policy(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_network_policy # noqa: E501 delete collection of NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_network_policy(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_network_policy_with_http_info(namespace, **kwargs)
[ "def", "delete_collection_namespaced_network_policy", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "delete_collection_namespaced_network_policy_with_ht...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/networking_v1_api.py#L793-L829
Yang7879/3D-BoNet
201ae46ffc6a00d5a9fae44da486d3702a83a1a3
helper_data_s3dis.py
python
Data_S3DIS.load_train_next_batch
(self)
return bat_pc, bat_sem_labels, bat_ins_labels, bat_psem_onehot_labels, bat_bbvert_padded_labels, bat_pmask_padded_labels
[]
def load_train_next_batch(self): bat_files = self.train_files[self.train_next_bat_index*self.train_batch_size:(self.train_next_bat_index+1)*self.train_batch_size] bat_pc=[] bat_sem_labels=[] bat_ins_labels=[] bat_psem_onehot_labels =[] bat_bbvert_padded_labels=[] bat_pmask_padded_labels =[] for file in bat_files: pc, sem_labels, ins_labels, psem_onehot_labels, bbvert_padded_labels, pmask_padded_labels = Data_S3DIS.load_fixed_points(file) bat_pc.append(pc) bat_sem_labels.append(sem_labels) bat_ins_labels.append(ins_labels) bat_psem_onehot_labels.append(psem_onehot_labels) bat_bbvert_padded_labels.append(bbvert_padded_labels) bat_pmask_padded_labels.append(pmask_padded_labels) bat_pc = np.asarray(bat_pc, dtype=np.float32) bat_sem_labels = np.asarray(bat_sem_labels, dtype=np.float32) bat_ins_labels = np.asarray(bat_ins_labels, dtype=np.float32) bat_psem_onehot_labels = np.asarray(bat_psem_onehot_labels, dtype=np.float32) bat_bbvert_padded_labels = np.asarray(bat_bbvert_padded_labels, dtype=np.float32) bat_pmask_padded_labels = np.asarray(bat_pmask_padded_labels, dtype=np.float32) self.train_next_bat_index+=1 return bat_pc, bat_sem_labels, bat_ins_labels, bat_psem_onehot_labels, bat_bbvert_padded_labels, bat_pmask_padded_labels
[ "def", "load_train_next_batch", "(", "self", ")", ":", "bat_files", "=", "self", ".", "train_files", "[", "self", ".", "train_next_bat_index", "*", "self", ".", "train_batch_size", ":", "(", "self", ".", "train_next_bat_index", "+", "1", ")", "*", "self", "....
https://github.com/Yang7879/3D-BoNet/blob/201ae46ffc6a00d5a9fae44da486d3702a83a1a3/helper_data_s3dis.py#L146-L171
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/ledger/indy.py
python
IndySdkLedger.get_schema
(self, schema_id: str)
Get a schema from the cache if available, otherwise fetch from the ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve
Get a schema from the cache if available, otherwise fetch from the ledger.
[ "Get", "a", "schema", "from", "the", "cache", "if", "available", "otherwise", "fetch", "from", "the", "ledger", "." ]
async def get_schema(self, schema_id: str) -> dict: """ Get a schema from the cache if available, otherwise fetch from the ledger. Args: schema_id: The schema id (or stringified sequence number) to retrieve """ if self.pool.cache: result = await self.pool.cache.get(f"schema::{schema_id}") if result: return result if schema_id.isdigit(): return await self.fetch_schema_by_seq_no(int(schema_id)) else: return await self.fetch_schema_by_id(schema_id)
[ "async", "def", "get_schema", "(", "self", ",", "schema_id", ":", "str", ")", "->", "dict", ":", "if", "self", ".", "pool", ".", "cache", ":", "result", "=", "await", "self", ".", "pool", ".", "cache", ".", "get", "(", "f\"schema::{schema_id}\"", ")", ...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/ledger/indy.py#L536-L552
delneg/noteshrinker-django
a7439accb02a3bc47e9e7d19b4e98f99c8052365
noteshrinker/noteshrink_module.py
python
get_bg_color
(image, bits_per_channel=None)
return unpack_rgb(packed_mode)
Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one.
Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one.
[ "Obtains", "the", "background", "color", "from", "an", "image", "or", "array", "of", "RGB", "colors", "by", "grouping", "similar", "colors", "into", "bins", "and", "finding", "the", "most", "frequent", "one", "." ]
def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb(quantized) unique, counts = np.unique(packed, return_counts=True) packed_mode = unique[counts.argmax()] return unpack_rgb(packed_mode)
[ "def", "get_bg_color", "(", "image", ",", "bits_per_channel", "=", "None", ")", ":", "assert", "image", ".", "shape", "[", "-", "1", "]", "==", "3", "quantized", "=", "quantize", "(", "image", ",", "bits_per_channel", ")", ".", "astype", "(", "int", ")...
https://github.com/delneg/noteshrinker-django/blob/a7439accb02a3bc47e9e7d19b4e98f99c8052365/noteshrinker/noteshrink_module.py#L100-L116
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/hive_metastore/ttypes.py
python
Order.__init__
(self, col=None, order=None,)
[]
def __init__(self, col=None, order=None,): self.col = col self.order = order
[ "def", "__init__", "(", "self", ",", "col", "=", "None", ",", "order", "=", "None", ",", ")", ":", "self", ".", "col", "=", "col", "self", ".", "order", "=", "order" ]
https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ttypes.py#L2373-L2375
laike9m/PyPunchP2P
3b9fcf6a5a6e9801b20793ebb7d8ecd539b817bf
client.py
python
Client.main
(self, test_nat_type=None)
nat_type是自己的nat类型 peer_nat_type是从服务器获取的对方的nat类型 选择哪种chat模式是根据nat_type来选择, 例如我这边的NAT设备是restrict, 那么我必须得一直向对方发包, 我的NAT设备才能识别对方为"我已经发过包的地址". 直到收到对方的包, periodic发送停止
nat_type是自己的nat类型 peer_nat_type是从服务器获取的对方的nat类型 选择哪种chat模式是根据nat_type来选择, 例如我这边的NAT设备是restrict, 那么我必须得一直向对方发包, 我的NAT设备才能识别对方为"我已经发过包的地址". 直到收到对方的包, periodic发送停止
[ "nat_type是自己的nat类型", "peer_nat_type是从服务器获取的对方的nat类型", "选择哪种chat模式是根据nat_type来选择", "例如我这边的NAT设备是restrict", "那么我必须得一直向对方发包", "我的NAT设备才能识别对方为", "我已经发过包的地址", ".", "直到收到对方的包", "periodic发送停止" ]
def main(self, test_nat_type=None): """ nat_type是自己的nat类型 peer_nat_type是从服务器获取的对方的nat类型 选择哪种chat模式是根据nat_type来选择, 例如我这边的NAT设备是restrict, 那么我必须得一直向对方发包, 我的NAT设备才能识别对方为"我已经发过包的地址". 直到收到对方的包, periodic发送停止 """ if not test_nat_type: nat_type, _, _ = self.get_nat_type() else: nat_type = test_nat_type # 假装正在测试某种类型的NAT try: self.request_for_connection(nat_type_id=NATTYPE.index(nat_type)) except ValueError: print("NAT type is %s" % nat_type) self.request_for_connection(nat_type_id=4) # Unknown NAT if nat_type == UnknownNAT or self.peer_nat_type == UnknownNAT: print("Symmetric chat mode") self.chat_symmetric() if nat_type == SymmetricNAT or self.peer_nat_type == SymmetricNAT: print("Symmetric chat mode") self.chat_symmetric() elif nat_type == FullCone: print("FullCone chat mode") self.chat_fullcone() elif nat_type in (RestrictNAT, RestrictPortNAT): print("Restrict chat mode") self.chat_restrict() else: print("NAT type wrong!") while True: try: time.sleep(0.5) except KeyboardInterrupt: print("exit") sys.exit(0)
[ "def", "main", "(", "self", ",", "test_nat_type", "=", "None", ")", ":", "if", "not", "test_nat_type", ":", "nat_type", ",", "_", ",", "_", "=", "self", ".", "get_nat_type", "(", ")", "else", ":", "nat_type", "=", "test_nat_type", "# 假装正在测试某种类型的NAT", "tr...
https://github.com/laike9m/PyPunchP2P/blob/3b9fcf6a5a6e9801b20793ebb7d8ecd539b817bf/client.py#L143-L180
UFAL-DSG/tgen
3c43c0e29faa7ea3857a6e490d9c28a8daafc7d0
cs-restaurant/input/convert.py
python
Writer.write_text
(self, data_file, out_format, insts, delex=False)
Write output sentences for the given data subrange. @param data_file: output file name @param out_format: output format ('conll' -- CoNLL-U morphology, \ 'interleaved' -- lemma/tag interleaved, 'plain' -- plain text) @param insts: instances to write @param delex: delexicalize? false by default
Write output sentences for the given data subrange.
[ "Write", "output", "sentences", "for", "the", "given", "data", "subrange", "." ]
def write_text(self, data_file, out_format, insts, delex=False): """Write output sentences for the given data subrange. @param data_file: output file name @param out_format: output format ('conll' -- CoNLL-U morphology, \ 'interleaved' -- lemma/tag interleaved, 'plain' -- plain text) @param insts: instances to write @param delex: delexicalize? false by default """ texts = [inst.delex_text if delex else inst.text for inst in insts] if out_format == 'interleaved': self._write_interleaved(data_file, texts) elif out_format == 'conll': self._write_conll(data_file, texts) else: self._write_plain(data_file, [" ".join([form for form, _, _ in sent]) for sent in texts])
[ "def", "write_text", "(", "self", ",", "data_file", ",", "out_format", ",", "insts", ",", "delex", "=", "False", ")", ":", "texts", "=", "[", "inst", ".", "delex_text", "if", "delex", "else", "inst", ".", "text", "for", "inst", "in", "insts", "]", "i...
https://github.com/UFAL-DSG/tgen/blob/3c43c0e29faa7ea3857a6e490d9c28a8daafc7d0/cs-restaurant/input/convert.py#L271-L286
isce-framework/isce2
0e5114a8bede3caf1d533d98e44dfe4b983e3f48
components/isceobj/TopsProc/runFineResamp.py
python
convertPoly2D
(poly)
return pPoly
Convert a isceobj.Util.Poly2D {poly} into zerodop.GPUresampslc.GPUresampslc.PyPloy2d
Convert a isceobj.Util.Poly2D {poly} into zerodop.GPUresampslc.GPUresampslc.PyPloy2d
[ "Convert", "a", "isceobj", ".", "Util", ".", "Poly2D", "{", "poly", "}", "into", "zerodop", ".", "GPUresampslc", ".", "GPUresampslc", ".", "PyPloy2d" ]
def convertPoly2D(poly): ''' Convert a isceobj.Util.Poly2D {poly} into zerodop.GPUresampslc.GPUresampslc.PyPloy2d ''' from zerodop.GPUresampslc.GPUresampslc import PyPoly2d import itertools # get parameters from poly azimuthOrder = poly.getAzimuthOrder() rangeOrder = poly.getRangeOrder() azimuthMean = poly.getMeanAzimuth() rangeMean = poly.getMeanRange() azimuthNorm = poly.getNormAzimuth() rangeNorm = poly.getNormRange() # create the PyPoly2d object pPoly = PyPoly2d(azimuthOrder, rangeOrder, azimuthMean, rangeMean, azimuthNorm, rangeNorm) # copy the coeffs, need to flatten into 1d list pPoly.coeffs = list(itertools.chain.from_iterable(poly.getCoeffs())) # all done return pPoly
[ "def", "convertPoly2D", "(", "poly", ")", ":", "from", "zerodop", ".", "GPUresampslc", ".", "GPUresampslc", "import", "PyPoly2d", "import", "itertools", "# get parameters from poly", "azimuthOrder", "=", "poly", ".", "getAzimuthOrder", "(", ")", "rangeOrder", "=", ...
https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/TopsProc/runFineResamp.py#L76-L97
idapython/src
839d93ac969bc1a152982464907445bc0d18a1f8
python/idc.py
python
add_struc_member
(sid, name, offset, flag, typeid, nbytes, target=-1, tdelta=0, reftype=REF_OFF32)
Add structure member @param sid: structure type ID @param name: name of the new member @param offset: offset of the new member -1 means to add at the end of the structure @param flag: type of the new member. Should be one of FF_BYTE..FF_PACKREAL (see above) combined with FF_DATA @param typeid: if is_struct(flag) then typeid specifies the structure id for the member if is_off0(flag) then typeid specifies the offset base. if is_strlit(flag) then typeid specifies the string type (STRTYPE_...). if is_stroff(flag) then typeid specifies the structure id if is_enum(flag) then typeid specifies the enum id if is_custom(flags) then typeid specifies the dtid and fid: dtid|(fid<<16) Otherwise typeid should be -1. @param nbytes: number of bytes in the new member @param target: target address of the offset expr. You may specify it as -1, ida will calculate it itself @param tdelta: offset target delta. usually 0 @param reftype: see REF_... definitions @note: The remaining arguments are allowed only if is_off0(flag) and you want to specify a complex offset expression @return: 0 - ok, otherwise error code (one of STRUC_ERROR_*)
Add structure member
[ "Add", "structure", "member" ]
def add_struc_member(sid, name, offset, flag, typeid, nbytes, target=-1, tdelta=0, reftype=REF_OFF32): """ Add structure member @param sid: structure type ID @param name: name of the new member @param offset: offset of the new member -1 means to add at the end of the structure @param flag: type of the new member. Should be one of FF_BYTE..FF_PACKREAL (see above) combined with FF_DATA @param typeid: if is_struct(flag) then typeid specifies the structure id for the member if is_off0(flag) then typeid specifies the offset base. if is_strlit(flag) then typeid specifies the string type (STRTYPE_...). if is_stroff(flag) then typeid specifies the structure id if is_enum(flag) then typeid specifies the enum id if is_custom(flags) then typeid specifies the dtid and fid: dtid|(fid<<16) Otherwise typeid should be -1. @param nbytes: number of bytes in the new member @param target: target address of the offset expr. You may specify it as -1, ida will calculate it itself @param tdelta: offset target delta. usually 0 @param reftype: see REF_... definitions @note: The remaining arguments are allowed only if is_off0(flag) and you want to specify a complex offset expression @return: 0 - ok, otherwise error code (one of STRUC_ERROR_*) """ if is_off0(flag): return eval_idc('add_struc_member(%d, "%s", %d, %d, %d, %d, %d, %d, %d);' % (sid, ida_kernwin.str2user(name or ""), offset, flag, typeid, nbytes, target, tdelta, reftype)) else: return eval_idc('add_struc_member(%d, "%s", %d, %d, %d, %d);' % (sid, ida_kernwin.str2user(name or ""), offset, flag, typeid, nbytes))
[ "def", "add_struc_member", "(", "sid", ",", "name", ",", "offset", ",", "flag", ",", "typeid", ",", "nbytes", ",", "target", "=", "-", "1", ",", "tdelta", "=", "0", ",", "reftype", "=", "REF_OFF32", ")", ":", "if", "is_off0", "(", "flag", ")", ":",...
https://github.com/idapython/src/blob/839d93ac969bc1a152982464907445bc0d18a1f8/python/idc.py#L3864-L3898
miyakogi/m2r
66f4a5a500cdd9fc59085106bff082c9cadafaf3
m2r.py
python
RestRenderer.list_item
(self, text)
return '\n' + self.list_marker + text
Rendering list item snippet. Like ``<li>``.
Rendering list item snippet. Like ``<li>``.
[ "Rendering", "list", "item", "snippet", ".", "Like", "<li", ">", "." ]
def list_item(self, text): """Rendering list item snippet. Like ``<li>``.""" return '\n' + self.list_marker + text
[ "def", "list_item", "(", "self", ",", "text", ")", ":", "return", "'\\n'", "+", "self", ".", "list_marker", "+", "text" ]
https://github.com/miyakogi/m2r/blob/66f4a5a500cdd9fc59085106bff082c9cadafaf3/m2r.py#L275-L277
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/urllib3/contrib/securetransport.py
python
inject_into_urllib3
()
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
Monkey-patch urllib3 with SecureTransport-backed SSL-support.
[ "Monkey", "-", "patch", "urllib3", "with", "SecureTransport", "-", "backed", "SSL", "-", "support", "." ]
def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.SSLContext = SecureTransportContext util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True
[ "def", "inject_into_urllib3", "(", ")", ":", "util", ".", "SSLContext", "=", "SecureTransportContext", "util", ".", "ssl_", ".", "SSLContext", "=", "SecureTransportContext", "util", ".", "HAS_SNI", "=", "HAS_SNI", "util", ".", "ssl_", ".", "HAS_SNI", "=", "HAS...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/urllib3/contrib/securetransport.py#L189-L198
haiwen/seahub
e92fcd44e3e46260597d8faa9347cb8222b8b10d
seahub/utils/logger.py
python
logger
(func)
return _decorated
[]
def logger(func): def _decorated(request, *args, **kwargs): start = time.time() result = func(request, *args, **kwargs) log.info('%s takes %s secs. ' % (func.__name__, fpformat.fix(time.time()-start, 10))) return result return _decorated
[ "def", "logger", "(", "func", ")", ":", "def", "_decorated", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "start", "=", "time", ".", "time", "(", ")", "result", "=", "func", "(", "request", ",", "*", "args", ",", "*", "*...
https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/utils/logger.py#L8-L14
modin-project/modin
0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee
modin/core/storage_formats/base/query_compiler.py
python
BaseQueryCompiler.getitem_row_array
(self, key)
return DataFrameDefault.register(get_row)(self, key=key)
Get row data for target indices. Parameters ---------- key : list-like Numeric indices of the rows to pick. Returns ------- BaseQueryCompiler New QueryCompiler that contains specified rows.
Get row data for target indices.
[ "Get", "row", "data", "for", "target", "indices", "." ]
def getitem_row_array(self, key): """ Get row data for target indices. Parameters ---------- key : list-like Numeric indices of the rows to pick. Returns ------- BaseQueryCompiler New QueryCompiler that contains specified rows. """ def get_row(df, key): return df.iloc[key] return DataFrameDefault.register(get_row)(self, key=key)
[ "def", "getitem_row_array", "(", "self", ",", "key", ")", ":", "def", "get_row", "(", "df", ",", "key", ")", ":", "return", "df", ".", "iloc", "[", "key", "]", "return", "DataFrameDefault", ".", "register", "(", "get_row", ")", "(", "self", ",", "key...
https://github.com/modin-project/modin/blob/0d9d14e6669be3dd6bb3b72222dbe6a6dffe1bee/modin/core/storage_formats/base/query_compiler.py#L1993-L2011
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
common/djangoapps/course_action_state/managers.py
python
CourseActionUIStateManager.update_state
( self, course_key, new_state, should_display=True, message="", user=None, allow_not_found=False, **kwargs )
return state_object
Updates the state of the given course for this Action with the given data. If allow_not_found is True, automatically creates an entry if it doesn't exist. Raises CourseActionStateException if allow_not_found is False and an entry for the given course for this Action doesn't exist.
Updates the state of the given course for this Action with the given data. If allow_not_found is True, automatically creates an entry if it doesn't exist. Raises CourseActionStateException if allow_not_found is False and an entry for the given course for this Action doesn't exist.
[ "Updates", "the", "state", "of", "the", "given", "course", "for", "this", "Action", "with", "the", "given", "data", ".", "If", "allow_not_found", "is", "True", "automatically", "creates", "an", "entry", "if", "it", "doesn", "t", "exist", ".", "Raises", "Co...
def update_state( self, course_key, new_state, should_display=True, message="", user=None, allow_not_found=False, **kwargs ): """ Updates the state of the given course for this Action with the given data. If allow_not_found is True, automatically creates an entry if it doesn't exist. Raises CourseActionStateException if allow_not_found is False and an entry for the given course for this Action doesn't exist. """ state_object, created = self.get_or_create(course_key=course_key, action=self.ACTION) if created: if allow_not_found: state_object.created_user = user else: raise CourseActionStateItemNotFoundError( "Cannot update non-existent entry for course_key {course_key} and action {action}".format( action=self.ACTION, course_key=course_key, )) # some state changes may not be user-initiated so override the user field only when provided if user: state_object.updated_user = user state_object.state = new_state state_object.should_display = should_display state_object.message = message # update any additional fields in kwargs if kwargs: for key, value in kwargs.items(): setattr(state_object, key, value) state_object.save() return state_object
[ "def", "update_state", "(", "self", ",", "course_key", ",", "new_state", ",", "should_display", "=", "True", ",", "message", "=", "\"\"", ",", "user", "=", "None", ",", "allow_not_found", "=", "False", ",", "*", "*", "kwargs", ")", ":", "state_object", "...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/djangoapps/course_action_state/managers.py#L61-L96
jaheyns/CfdOF
97fab2347e421eaad7cb549006329425112b9e21
CfdMeshTools.py
python
CfdMeshTools.writeMeshCase
(self)
Collect case settings, and finally build a runnable case.
Collect case settings, and finally build a runnable case.
[ "Collect", "case", "settings", "and", "finally", "build", "a", "runnable", "case", "." ]
def writeMeshCase(self): """ Collect case settings, and finally build a runnable case. """ CfdTools.cfdMessage("Populating mesh dictionaries in folder {}\n".format(self.meshCaseDir)) if self.mesh_obj.MeshUtility == "cfMesh": self.cf_settings['ClMax'] = self.clmax*self.scale if len(self.cf_settings['BoundaryLayers']) > 0: self.cf_settings['BoundaryLayerPresent'] = True else: self.cf_settings['BoundaryLayerPresent'] = False if len(self.cf_settings["InternalRegions"]) > 0: self.cf_settings['InternalRefinementRegionsPresent'] = True else: self.cf_settings['InternalRefinementRegionsPresent'] = False elif self.mesh_obj.MeshUtility == "snappyHexMesh": bound_box = self.part_obj.Shape.BoundBox bC = 5 # Number of background mesh buffer cells x_min = (bound_box.XMin - bC*self.clmax)*self.scale x_max = (bound_box.XMax + bC*self.clmax)*self.scale y_min = (bound_box.YMin - bC*self.clmax)*self.scale y_max = (bound_box.YMax + bC*self.clmax)*self.scale z_min = (bound_box.ZMin - bC*self.clmax)*self.scale z_max = (bound_box.ZMax + bC*self.clmax)*self.scale cells_x = int(math.ceil(bound_box.XLength/self.clmax) + 2*bC) cells_y = int(math.ceil(bound_box.YLength/self.clmax) + 2*bC) cells_z = int(math.ceil(bound_box.ZLength/self.clmax) + 2*bC) snappy_settings = self.snappy_settings snappy_settings['BlockMesh'] = { "xMin": x_min, "xMax": x_max, "yMin": y_min, "yMax": y_max, "zMin": z_min, "zMax": z_max, "cellsX": cells_x, "cellsY": cells_y, "cellsZ": cells_z } inside_x = Units.Quantity(self.mesh_obj.PointInMesh.get('x')).Value*self.scale inside_y = Units.Quantity(self.mesh_obj.PointInMesh.get('y')).Value*self.scale inside_z = Units.Quantity(self.mesh_obj.PointInMesh.get('z')).Value*self.scale shape_patch_names_list = [] for k in range(len(self.patch_faces)): for j in range(len(self.patch_faces[k])): if len(self.patch_faces[k][j]): shape_patch_names_list.append(self.patch_names[k][j]) snappy_settings['ShapePatchNames'] = tuple(shape_patch_names_list) snappy_settings['EdgeRefinementLevel'] = CfdTools.relLenToRefinementLevel(self.mesh_obj.EdgeRefinement) snappy_settings['PointInMesh'] = { "x": inside_x, "y": inside_y, "z": inside_z } snappy_settings['CellsBetweenLevels'] = self.mesh_obj.CellsBetweenLevels if len(self.snappy_settings["InternalRegions"]) > 0: self.snappy_settings['InternalRefinementRegionsPresent'] = True else: self.snappy_settings['InternalRefinementRegionsPresent'] = False elif self.mesh_obj.MeshUtility == "gmsh": exe = CfdTools.getGmshExecutable() self.gmsh_settings['Executable'] = CfdTools.translatePath(exe) self.gmsh_settings['HasLengthMap'] = False if self.ele_length_map: self.gmsh_settings['HasLengthMap'] = True print(self.ele_length_map) print(self.ele_node_map) self.gmsh_settings['LengthMap'] = self.ele_length_map self.gmsh_settings['NodeMap'] = {} for e in self.ele_length_map: ele_nodes = (''.join((str(n+1) + ', ') for n in self.ele_node_map[e])).rstrip(', ') self.gmsh_settings['NodeMap'][e] = ele_nodes self.gmsh_settings['ClMax'] = self.clmax self.gmsh_settings['ClMin'] = self.clmin sols = (''.join((str(n+1) + ', ') for n in range(len(self.mesh_obj.Part.Shape.Solids)))).rstrip(', ') self.gmsh_settings['Solids'] = sols self.gmsh_settings['BoundaryFaceMap'] = {} for k in range(len(self.patch_faces)): for l in range(len(self.patch_faces[k])): patch_faces = self.patch_faces[k][l] patch_name = self.patch_names[k][l] if len(patch_faces): self.gmsh_settings['BoundaryFaceMap'][patch_name] = ', '.join(str(fi+1) for fi in patch_faces) # Perform initialisation here rather than __init__ in case of path changes self.template_path = os.path.join(CfdTools.get_module_path(), "data", "defaultsMesh") mesh_region_present = False if self.mesh_obj.MeshUtility == "cfMesh" and len(self.cf_settings['MeshRegions']) > 0 or \ self.mesh_obj.MeshUtility == "snappyHexMesh" and len(self.snappy_settings['MeshRegions']) > 0: mesh_region_present = True self.settings = { 'Name': self.part_obj.Name, 'MeshPath': self.meshCaseDir, 'FoamRuntime': CfdTools.getFoamRuntime(), 'MeshUtility': self.mesh_obj.MeshUtility, 'MeshRegionPresent': mesh_region_present, 'CfSettings': self.cf_settings, 'SnappySettings': self.snappy_settings, 'GmshSettings': self.gmsh_settings, 'TwoDSettings': self.two_d_settings } if CfdTools.getFoamRuntime() != 'WindowsDocker': self.settings['TranslatedFoamPath'] = CfdTools.translatePath(CfdTools.getFoamDir()) if self.mesh_obj.NumberOfProcesses <= 1: self.mesh_obj.NumberOfProcesses = 1 self.settings['ParallelMesh'] = False else: self.settings['ParallelMesh'] = True self.settings['NumberOfProcesses'] = self.mesh_obj.NumberOfProcesses self.settings['NumberOfThreads'] = self.mesh_obj.NumberOfThreads TemplateBuilder.TemplateBuilder(self.meshCaseDir, self.template_path, self.settings) # Update Allmesh permission - will fail silently on Windows fname = os.path.join(self.meshCaseDir, "Allmesh") import stat s = os.stat(fname) os.chmod(fname, s.st_mode | stat.S_IEXEC) CfdTools.cfdMessage("Successfully wrote meshCase to folder {}\n".format(self.meshCaseDir))
[ "def", "writeMeshCase", "(", "self", ")", ":", "CfdTools", ".", "cfdMessage", "(", "\"Populating mesh dictionaries in folder {}\\n\"", ".", "format", "(", "self", ".", "meshCaseDir", ")", ")", "if", "self", ".", "mesh_obj", ".", "MeshUtility", "==", "\"cfMesh\"", ...
https://github.com/jaheyns/CfdOF/blob/97fab2347e421eaad7cb549006329425112b9e21/CfdMeshTools.py#L594-L721
ManiacalLabs/BiblioPixel
afb993fbbe56e75e7c98f252df402b0f3e83bb6e
bibliopixel/project/construct.py
python
construct
(*args, datatype, typename=None, **kwds)
return datatype(*args, **kwds)
Construct an object from a type constructor. A type constructor is a dictionary which has a field "datatype" which has a callable method to construct a class, and a field "typename" which is the Python path of the function or class in "datatype".
Construct an object from a type constructor.
[ "Construct", "an", "object", "from", "a", "type", "constructor", "." ]
def construct(*args, datatype, typename=None, **kwds): """ Construct an object from a type constructor. A type constructor is a dictionary which has a field "datatype" which has a callable method to construct a class, and a field "typename" which is the Python path of the function or class in "datatype". """ return datatype(*args, **kwds)
[ "def", "construct", "(", "*", "args", ",", "datatype", ",", "typename", "=", "None", ",", "*", "*", "kwds", ")", ":", "return", "datatype", "(", "*", "args", ",", "*", "*", "kwds", ")" ]
https://github.com/ManiacalLabs/BiblioPixel/blob/afb993fbbe56e75e7c98f252df402b0f3e83bb6e/bibliopixel/project/construct.py#L5-L13
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/PcapAnalysis/Scripts/PcapFileExtractor/PcapFileExtractor.py
python
get_file_path_from_id
(entry_id: str)
return file_obj.get('path'), file_obj.get('name')
Gets a file path and name from entry_id. Args: entry_id: ID of the file from context. Returns: file path, name of file
Gets a file path and name from entry_id.
[ "Gets", "a", "file", "path", "and", "name", "from", "entry_id", "." ]
def get_file_path_from_id(entry_id: str) -> Tuple[str, str]: """Gets a file path and name from entry_id. Args: entry_id: ID of the file from context. Returns: file path, name of file """ file_obj = demisto.getFilePath(entry_id) return file_obj.get('path'), file_obj.get('name')
[ "def", "get_file_path_from_id", "(", "entry_id", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "file_obj", "=", "demisto", ".", "getFilePath", "(", "entry_id", ")", "return", "file_obj", ".", "get", "(", "'path'", ")", ",", "file_obj"...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/PcapAnalysis/Scripts/PcapFileExtractor/PcapFileExtractor.py#L71-L81
KenT2/pipresents-gapless
31a347bb8b45898a3fe08b1daf765e31d47b7a87
remi/gui.py
python
InputDialog.confirm_value
(self, widget)
return self.eventManager.propagate(self.EVENT_ONCONFIRMVALUE, (self.inputText.get_text(),))
Event called pressing on OK button.
Event called pressing on OK button.
[ "Event", "called", "pressing", "on", "OK", "button", "." ]
def confirm_value(self, widget): """Event called pressing on OK button.""" self.hide() return self.eventManager.propagate(self.EVENT_ONCONFIRMVALUE, (self.inputText.get_text(),))
[ "def", "confirm_value", "(", "self", ",", "widget", ")", ":", "self", ".", "hide", "(", ")", "return", "self", ".", "eventManager", ".", "propagate", "(", "self", ".", "EVENT_ONCONFIRMVALUE", ",", "(", "self", ".", "inputText", ".", "get_text", "(", ")",...
https://github.com/KenT2/pipresents-gapless/blob/31a347bb8b45898a3fe08b1daf765e31d47b7a87/remi/gui.py#L1383-L1386
tensorflow/federated
5a60a032360087b8f4c7fcfd97ed1c0131c3eac3
tensorflow_federated/python/learning/model_examples.py
python
LinearRegression.report_local_unfinalized_metrics
( self)
return collections.OrderedDict( loss=[self._loss_sum, tf.cast(self._num_examples, tf.float32)], num_examples=self._num_examples)
Creates an `OrderedDict` of metric names to unfinalized values. Returns: An `OrderedDict` of metric names to unfinalized values. The `OrderedDict` has the same keys (metric names) as the `OrderedDict` returned by the method `metric_finalizers()`, and can be used as input to the finalizers to get the finalized metric values. This method and `metric_finalizers()` method can be used together to build a cross-client metrics aggregator when defining the federated training processes or evaluation computations.
Creates an `OrderedDict` of metric names to unfinalized values.
[ "Creates", "an", "OrderedDict", "of", "metric", "names", "to", "unfinalized", "values", "." ]
def report_local_unfinalized_metrics( self) -> OrderedDict[str, Union[tf.Tensor, List[tf.Tensor]]]: """Creates an `OrderedDict` of metric names to unfinalized values. Returns: An `OrderedDict` of metric names to unfinalized values. The `OrderedDict` has the same keys (metric names) as the `OrderedDict` returned by the method `metric_finalizers()`, and can be used as input to the finalizers to get the finalized metric values. This method and `metric_finalizers()` method can be used together to build a cross-client metrics aggregator when defining the federated training processes or evaluation computations. """ return collections.OrderedDict( loss=[self._loss_sum, tf.cast(self._num_examples, tf.float32)], num_examples=self._num_examples)
[ "def", "report_local_unfinalized_metrics", "(", "self", ")", "->", "OrderedDict", "[", "str", ",", "Union", "[", "tf", ".", "Tensor", ",", "List", "[", "tf", ".", "Tensor", "]", "]", "]", ":", "return", "collections", ".", "OrderedDict", "(", "loss", "="...
https://github.com/tensorflow/federated/blob/5a60a032360087b8f4c7fcfd97ed1c0131c3eac3/tensorflow_federated/python/learning/model_examples.py#L155-L170
smicallef/spiderfoot
fd4bf9394c9ab3ecc90adc3115c56349fb23165b
modules/sfp_greynoise.py
python
sfp_greynoise.handleEvent
(self, event)
[]
def handleEvent(self, event): eventName = event.eventType srcModuleName = event.module eventData = event.data if self.errorState: return self.debug(f"Received event, {eventName}, from {srcModuleName}") if self.opts["api_key"] == "": self.error("You enabled sfp_greynoise but did not set an API key!") self.errorState = True return if eventData in self.results: self.debug(f"Skipping {eventData}, already checked.") return self.results[eventData] = True if eventName == "NETBLOCK_OWNER": if not self.opts["netblocklookup"]: return else: if IPNetwork(eventData).prefixlen < self.opts["maxnetblock"]: self.debug( "Network size bigger than permitted: " + str(IPNetwork(eventData).prefixlen) + " > " + str(self.opts["maxnetblock"]) ) return if eventName == "NETBLOCK_MEMBER": if not self.opts["subnetlookup"]: return else: if IPNetwork(eventData).prefixlen < self.opts["maxsubnet"]: self.debug( "Network size bigger than permitted: " + str(IPNetwork(eventData).prefixlen) + " > " + str(self.opts["maxsubnet"]) ) return if eventName == "IP_ADDRESS": evtType = "MALICIOUS_IPADDR" qryType = "ip" if eventName.startswith("NETBLOCK_"): evtType = "MALICIOUS_IPADDR" qryType = "netblock" if eventName == "AFFILIATE_IPADDR": evtType = "MALICIOUS_AFFILIATE_IPADDR" qryType = "ip" ret = self.queryIP(eventData, qryType) if not ret: return if "data" not in ret and "seen" not in ret and "riot" not in ret: return if "data" in ret and len(ret["data"]) > 0: for rec in ret["data"]: if rec.get("seen", None): self.debug(f"Found threat info in Greynoise: {rec['ip']}") lastseen = rec.get("last_seen", "1970-01-01") lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d") lastseen_ts = int(time.mktime(lastseen_dt.timetuple())) age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"]) if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts: self.debug(f"Record [{rec['ip']}] found but too old, skipping.") return # Only report meta data about the target, not affiliates if rec.get("metadata") and eventName == "IP_ADDRESS": met = rec.get("metadata") if met.get("country", "unknown") != "unknown": loc = "" if met.get("city"): loc = met.get("city") + ", " loc += met.get("country") e = SpiderFootEvent("GEOINFO", loc, self.__name__, event) self.notifyListeners(e) if met.get("asn", "unknown") != "unknown": asn = met.get("asn").replace("AS", "") e = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event) self.notifyListeners(e) if met.get("organization", "unknown") != "unknown": e = SpiderFootEvent("COMPANY_NAME", met.get("organization"), self.__name__, event) self.notifyListeners(e) if met.get("os", "unknown") != "unknown": e = SpiderFootEvent("OPERATING_SYSTEM", met.get("os"), self.__name__, event) self.notifyListeners(e) e = SpiderFootEvent("RAW_RIR_DATA", str(rec), self.__name__, event) self.notifyListeners(e) if rec.get("classification"): descr = ( "GreyNoise - Mass-Scanning IP Detected [" + rec.get("ip") + "]\n - Classification: " + rec.get("classification") ) if rec.get("tags"): descr += "\n - " + "Scans For Tags: " + ", ".join(rec.get("tags")) if rec.get("cve"): descr += "\n - " + "Scans For CVEs: " + ", ".join(rec.get("cve")) if rec.get("raw_data") and not (rec.get("tags") or ret.get("cve")): descr += "\n - " + "Raw data: " + str(rec.get("raw_data")) descr += "\n<SFURL>https://www.greynoise.io/viz/ip/" + rec.get("ip") + "</SFURL>" e = SpiderFootEvent(evtType, descr, self.__name__, event) self.notifyListeners(e) if "seen" in ret: if ret.get("seen", None): lastseen = ret.get("last_seen", "1970-01-01") lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d") lastseen_ts = int(time.mktime(lastseen_dt.timetuple())) age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"]) if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts: self.debug("Record found but too old, skipping.") return # Only report meta data about the target, not affiliates if ret.get("metadata") and eventName == "IP_ADDRESS": met = ret.get("metadata") if met.get("country", "unknown") != "unknown": loc = "" if met.get("city"): loc = met.get("city") + ", " loc += met.get("country") e = SpiderFootEvent("GEOINFO", loc, self.__name__, event) self.notifyListeners(e) if met.get("asn", "unknown") != "unknown": asn = met.get("asn").replace("AS", "") e = SpiderFootEvent("BGP_AS_MEMBER", asn, self.__name__, event) self.notifyListeners(e) if met.get("organization", "unknown") != "unknown": e = SpiderFootEvent("COMPANY_NAME", met.get("organization"), self.__name__, event) self.notifyListeners(e) if met.get("os", "unknown") != "unknown": e = SpiderFootEvent("OPERATING_SYSTEM", met.get("os"), self.__name__, event) self.notifyListeners(e) e = SpiderFootEvent("RAW_RIR_DATA", str(ret), self.__name__, event) self.notifyListeners(e) if ret.get("classification"): descr = ( "GreyNoise - Mass-Scanning IP Detected [" + eventData + "]\n - Classification: " + ret.get("classification") ) if ret.get("tags"): descr += "\n - " + "Scans For Tags: " + ", ".join(ret.get("tags")) if ret.get("cve"): descr += "\n - " + "Scans For CVEs: " + ", ".join(ret.get("cve")) if ret.get("raw_data") and not (ret.get("tags") or ret.get("cve")): descr += "\n - " + "Raw data: " + str(ret.get("raw_data")) descr += "\n<SFURL>https://www.greynoise.io/viz/ip/" + ret.get("ip") + "</SFURL>" e = SpiderFootEvent(evtType, descr, self.__name__, event) self.notifyListeners(e) if "riot" in ret: if ret.get("riot", None): lastseen = ret.get("last_updated", "1970-01-01") lastseen = lastseen.split("T")[0] lastseen_dt = datetime.strptime(lastseen, "%Y-%m-%d") lastseen_ts = int(time.mktime(lastseen_dt.timetuple())) age_limit_ts = int(time.time()) - (86400 * self.opts["age_limit_days"]) if self.opts["age_limit_days"] > 0 and lastseen_ts < age_limit_ts: self.debug("Record found but too old, skipping.") return if ret.get("trust_level"): descr = ( "GreyNoise - Common-Business Service IP Detected [" + eventData + "]\n - Trust Level: " + ret.get("trust_level") ) if ret.get("name"): descr += "\n - " + "Provider Name: " + ret.get("name") if ret.get("category"): descr += "\n - " + "Provider Category: " + ret.get("category") descr += "\n<SFURL>https://www.greynoise.io/viz/ip/" + ret.get("ip") + "</SFURL>" e = SpiderFootEvent(evtType, descr, self.__name__, event) self.notifyListeners(e)
[ "def", "handleEvent", "(", "self", ",", "event", ")", ":", "eventName", "=", "event", ".", "eventType", "srcModuleName", "=", "event", ".", "module", "eventData", "=", "event", ".", "data", "if", "self", ".", "errorState", ":", "return", "self", ".", "de...
https://github.com/smicallef/spiderfoot/blob/fd4bf9394c9ab3ecc90adc3115c56349fb23165b/modules/sfp_greynoise.py#L162-L353
City-Bureau/city-scrapers
b295d0aa612e3979a9fccab7c5f55ecea9ed074c
city_scrapers/spiders/chi_ssa_60.py
python
ChiSsa60Spider._parse_description
(self, item)
return re.sub(r"\s+", " ", desc_text).strip()
Parse or generate meeting description.
Parse or generate meeting description.
[ "Parse", "or", "generate", "meeting", "description", "." ]
def _parse_description(self, item): """Parse or generate meeting description.""" desc_text = " ".join( Selector(text=html.unescape(item["description"])).css("*::text").extract() ) return re.sub(r"\s+", " ", desc_text).strip()
[ "def", "_parse_description", "(", "self", ",", "item", ")", ":", "desc_text", "=", "\" \"", ".", "join", "(", "Selector", "(", "text", "=", "html", ".", "unescape", "(", "item", "[", "\"description\"", "]", ")", ")", ".", "css", "(", "\"*::text\"", ")"...
https://github.com/City-Bureau/city-scrapers/blob/b295d0aa612e3979a9fccab7c5f55ecea9ed074c/city_scrapers/spiders/chi_ssa_60.py#L84-L89
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/ipaddr/__init__.py
python
_BaseNet.address_exclude
(self, other)
return sorted(ret_addrs, key=_BaseNet._get_networks_key)
Remove an address from a larger block. For example: addr1 = IPNetwork('10.1.1.0/24') addr2 = IPNetwork('10.1.1.0/26') addr1.address_exclude(addr2) = [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')] or IPv6: addr1 = IPNetwork('::1/32') addr2 = IPNetwork('::1/128') addr1.address_exclude(addr2) = [IPNetwork('::0/128'), IPNetwork('::2/127'), IPNetwork('::4/126'), IPNetwork('::8/125'), ... IPNetwork('0:0:8000::/33')] Args: other: An IPvXNetwork object of the same type. Returns: A sorted list of IPvXNetwork objects addresses which is self minus other. Raises: TypeError: If self and other are of difffering address versions, or if other is not a network object. ValueError: If other is not completely contained by self.
Remove an address from a larger block.
[ "Remove", "an", "address", "from", "a", "larger", "block", "." ]
def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = IPNetwork('10.1.1.0/24') addr2 = IPNetwork('10.1.1.0/26') addr1.address_exclude(addr2) = [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')] or IPv6: addr1 = IPNetwork('::1/32') addr2 = IPNetwork('::1/128') addr1.address_exclude(addr2) = [IPNetwork('::0/128'), IPNetwork('::2/127'), IPNetwork('::4/126'), IPNetwork('::8/125'), ... IPNetwork('0:0:8000::/33')] Args: other: An IPvXNetwork object of the same type. Returns: A sorted list of IPvXNetwork objects addresses which is self minus other. Raises: TypeError: If self and other are of difffering address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( str(self), str(other))) if not isinstance(other, _BaseNet): raise TypeError("%s is not a network object" % str(other)) if other not in self: raise ValueError('%s not contained in %s' % (str(other), str(self))) if other == self: return [] ret_addrs = [] # Make sure we're comparing the network of other. other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)), version=other._version) s1, s2 = self.subnet() while s1 != other and s2 != other: if other in s1: ret_addrs.append(s2) s1, s2 = s1.subnet() elif other in s2: ret_addrs.append(s1) s1, s2 = s2.subnet() else: # If we got here, there's a bug somewhere. assert True == False, ('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) if s1 == other: ret_addrs.append(s2) elif s2 == other: ret_addrs.append(s1) else: # If we got here, there's a bug somewhere. assert True == False, ('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) return sorted(ret_addrs, key=_BaseNet._get_networks_key)
[ "def", "address_exclude", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "_version", "==", "other", ".", "_version", ":", "raise", "TypeError", "(", "\"%s and %s are not of the same version\"", "%", "(", "str", "(", "self", ")", ",", "str", ...
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/ipaddr/__init__.py#L703-L779
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.devtools/src/openmdao/devtools/releasetools.py
python
_rollback_releaseinfo_file
(projname)
Creates a releaseinfo.py file in the current directory
Creates a releaseinfo.py file in the current directory
[ "Creates", "a", "releaseinfo", ".", "py", "file", "in", "the", "current", "directory" ]
def _rollback_releaseinfo_file(projname): """Creates a releaseinfo.py file in the current directory""" dirs = projname.split('.') os.chdir(os.path.join(*dirs)) print 'rolling back releaseinfo.py for %s' % projname os.system('git checkout -- releaseinfo.py')
[ "def", "_rollback_releaseinfo_file", "(", "projname", ")", ":", "dirs", "=", "projname", ".", "split", "(", "'.'", ")", "os", ".", "chdir", "(", "os", ".", "path", ".", "join", "(", "*", "dirs", ")", ")", "print", "'rolling back releaseinfo.py for %s'", "%...
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.devtools/src/openmdao/devtools/releasetools.py#L102-L107
JinpengLI/deep_ocr
450148c0c51b3565a96ac2f3c94ee33022e55307
deep_ocr/ocrolib/lstm.py
python
MLP1
(Ni,Ns,No)
return stacked
An MLP implementation by stacking two `Logreg` networks on top of each other.
An MLP implementation by stacking two `Logreg` networks on top of each other.
[ "An", "MLP", "implementation", "by", "stacking", "two", "Logreg", "networks", "on", "top", "of", "each", "other", "." ]
def MLP1(Ni,Ns,No): """An MLP implementation by stacking two `Logreg` networks on top of each other.""" lr1 = Logreg(Ni,Ns) lr2 = Logreg(Ns,No) stacked = Stacked([lr1,lr2]) return stacked
[ "def", "MLP1", "(", "Ni", ",", "Ns", ",", "No", ")", ":", "lr1", "=", "Logreg", "(", "Ni", ",", "Ns", ")", "lr2", "=", "Logreg", "(", "Ns", ",", "No", ")", "stacked", "=", "Stacked", "(", "[", "lr1", ",", "lr2", "]", ")", "return", "stacked" ...
https://github.com/JinpengLI/deep_ocr/blob/450148c0c51b3565a96ac2f3c94ee33022e55307/deep_ocr/ocrolib/lstm.py#L694-L700
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/bin/config_updater_util.py
python
FleetspeakConfig.Write
(self, config)
[]
def Write(self, config): if self.use_fleetspeak: self._WriteEnabled(config) else: self._WriteDisabled(config)
[ "def", "Write", "(", "self", ",", "config", ")", ":", "if", "self", ".", "use_fleetspeak", ":", "self", ".", "_WriteEnabled", "(", "config", ")", "else", ":", "self", ".", "_WriteDisabled", "(", "config", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/bin/config_updater_util.py#L370-L374
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/ply-3.11/example/ansic/cparse.py
python
p_direct_abstract_declarator_2
(t)
direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET
direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET
[ "direct_abstract_declarator", ":", "direct_abstract_declarator", "LBRACKET", "constant_expression_opt", "RBRACKET" ]
def p_direct_abstract_declarator_2(t): 'direct_abstract_declarator : direct_abstract_declarator LBRACKET constant_expression_opt RBRACKET' pass
[ "def", "p_direct_abstract_declarator_2", "(", "t", ")", ":", "pass" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/ply-3.11/example/ansic/cparse.py#L509-L511
nilearn/nilearn
9edba4471747efacf21260bf470a346307f52706
nilearn/plotting/html_document.py
python
HTMLDocument.get_iframe
(self, width=None, height=None)
return wrapped
Get the document wrapped in an inline frame. For inserting in another HTML page of for display in a Jupyter notebook.
Get the document wrapped in an inline frame.
[ "Get", "the", "document", "wrapped", "in", "an", "inline", "frame", "." ]
def get_iframe(self, width=None, height=None): """ Get the document wrapped in an inline frame. For inserting in another HTML page of for display in a Jupyter notebook. """ if width is None: width = self.width if height is None: height = self.height escaped = escape(self.html, quote=True) wrapped = ('<iframe srcdoc="{}" width="{}" height="{}" ' 'frameBorder="0"></iframe>').format(escaped, width, height) return wrapped
[ "def", "get_iframe", "(", "self", ",", "width", "=", "None", ",", "height", "=", "None", ")", ":", "if", "width", "is", "None", ":", "width", "=", "self", ".", "width", "if", "height", "is", "None", ":", "height", "=", "self", ".", "height", "escap...
https://github.com/nilearn/nilearn/blob/9edba4471747efacf21260bf470a346307f52706/nilearn/plotting/html_document.py#L67-L82
IntelLabs/coach
dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d
rl_coach/memories/episodic/episodic_experience_replay.py
python
EpisodicExperienceReplay.close_last_episode
(self, lock=True)
Close the last episode in the replay buffer and open a new one :return: None
Close the last episode in the replay buffer and open a new one :return: None
[ "Close", "the", "last", "episode", "in", "the", "replay", "buffer", "and", "open", "a", "new", "one", ":", "return", ":", "None" ]
def close_last_episode(self, lock=True) -> None: """ Close the last episode in the replay buffer and open a new one :return: None """ if lock: self.reader_writer_lock.lock_writing_and_reading() last_episode = self._buffer[-1] self._num_transitions_in_complete_episodes += last_episode.length() self._length += 1 # create a new Episode for the next transitions to be placed into self._buffer.append(Episode(n_step=self.n_step)) # if update episode adds to the buffer, a new Episode needs to be ready first # it would be better if this were less state full self._update_episode(last_episode) self._enforce_max_length() if lock: self.reader_writer_lock.release_writing_and_reading()
[ "def", "close_last_episode", "(", "self", ",", "lock", "=", "True", ")", "->", "None", ":", "if", "lock", ":", "self", ".", "reader_writer_lock", ".", "lock_writing_and_reading", "(", ")", "last_episode", "=", "self", ".", "_buffer", "[", "-", "1", "]", ...
https://github.com/IntelLabs/coach/blob/dea46ae0d22b0a0cd30b9fc138a4a2642e1b9d9d/rl_coach/memories/episodic/episodic_experience_replay.py#L240-L263
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/senseme/switch.py
python
async_setup_entry
( hass: HomeAssistant, entry: config_entries.ConfigEntry, async_add_entities: AddEntitiesCallback, )
Set up SenseME fans.
Set up SenseME fans.
[ "Set", "up", "SenseME", "fans", "." ]
async def async_setup_entry( hass: HomeAssistant, entry: config_entries.ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up SenseME fans.""" device = hass.data[DOMAIN][entry.entry_id] descriptions: list[SenseMESwitchEntityDescription] = [] if device.is_fan: descriptions.extend(FAN_SWITCHES) if device.has_light: descriptions.extend(FAN_LIGHT_SWITCHES) elif device.is_light: descriptions.extend(LIGHT_SWITCHES) async_add_entities( HASensemeSwitch(device, description) for description in descriptions )
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "config_entries", ".", "ConfigEntry", ",", "async_add_entities", ":", "AddEntitiesCallback", ",", ")", "->", "None", ":", "device", "=", "hass", ".", "data", "[", "DOMAI...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/senseme/switch.py#L92-L110
mithril-global/GoAgentX
788fbd5e1c824c75cf98a9aef8a6d4ec8df25e95
GoAgentX.app/Contents/PlugIns/shadowsocks.gxbundle/Contents/Resources/bin/python/M2Crypto/DSA.py
python
DSA.sign
(self, digest)
return m2.dsa_sign(self.dsa, digest)
Sign the digest. @type digest: str @param digest: SHA-1 hash of message (same as output from MessageDigest, a "byte string") @rtype: tuple @return: DSA signature, a tuple of two values, r and s, both "byte strings".
Sign the digest.
[ "Sign", "the", "digest", "." ]
def sign(self, digest): """ Sign the digest. @type digest: str @param digest: SHA-1 hash of message (same as output from MessageDigest, a "byte string") @rtype: tuple @return: DSA signature, a tuple of two values, r and s, both "byte strings". """ assert self.check_key(), 'key is not initialised' return m2.dsa_sign(self.dsa, digest)
[ "def", "sign", "(", "self", ",", "digest", ")", ":", "assert", "self", ".", "check_key", "(", ")", ",", "'key is not initialised'", "return", "m2", ".", "dsa_sign", "(", "self", ".", "dsa", ",", "digest", ")" ]
https://github.com/mithril-global/GoAgentX/blob/788fbd5e1c824c75cf98a9aef8a6d4ec8df25e95/GoAgentX.app/Contents/PlugIns/shadowsocks.gxbundle/Contents/Resources/bin/python/M2Crypto/DSA.py#L198-L210
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
copy_bits
(v, s, e=-1)
return (v & mask) >> s
Copy bits from a value @param v: the value @param s: starting bit (0-based) @param e: ending bit
Copy bits from a value
[ "Copy", "bits", "from", "a", "value" ]
def copy_bits(v, s, e=-1): """ Copy bits from a value @param v: the value @param s: starting bit (0-based) @param e: ending bit """ # end-bit not specified? use start bit (thus extract one bit) if e == -1: e = s # swap start and end if start > end if s > e: e, s = s, e mask = ~(((1 << (e-s+1))-1) << s) return (v & mask) >> s
[ "def", "copy_bits", "(", "v", ",", "s", ",", "e", "=", "-", "1", ")", ":", "# end-bit not specified? use start bit (thus extract one bit)", "if", "e", "==", "-", "1", ":", "e", "=", "s", "# swap start and end if start > end", "if", "s", ">", "e", ":", "e", ...
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L512-L528
poljar/matrix-nio
ecb548144a5c4f6a5d18e23b6a844374526c1bd1
nio/api.py
python
Api.delete_devices
( access_token, # type: str devices, # type: List[str] auth_dict=None # type: Optional[Dict[str, str]] )
return ( "POST", Api._build_path(path, query_parameters), Api.to_json(content) )
Delete a device. This API endpoint uses the User-Interactive Authentication API. This tells the server to delete the given devices and invalidate their associated access tokens. Should first be called with no additional authentication information. Returns the HTTP method, HTTP path and data for the request. Args: access_token (str): The access token to be used with the request. devices (List[str]): A list of devices which will be deleted. auth_dict (Dict): Additional authentication information for the user-interactive authentication API.
Delete a device.
[ "Delete", "a", "device", "." ]
def delete_devices( access_token, # type: str devices, # type: List[str] auth_dict=None # type: Optional[Dict[str, str]] ): # type: (...) -> Tuple[str, str, str] """Delete a device. This API endpoint uses the User-Interactive Authentication API. This tells the server to delete the given devices and invalidate their associated access tokens. Should first be called with no additional authentication information. Returns the HTTP method, HTTP path and data for the request. Args: access_token (str): The access token to be used with the request. devices (List[str]): A list of devices which will be deleted. auth_dict (Dict): Additional authentication information for the user-interactive authentication API. """ query_parameters = {"access_token": access_token} path = ["delete_devices"] content = { "devices": devices } # type: Dict[str, Any] if auth_dict: content["auth"] = auth_dict return ( "POST", Api._build_path(path, query_parameters), Api.to_json(content) )
[ "def", "delete_devices", "(", "access_token", ",", "# type: str", "devices", ",", "# type: List[str]", "auth_dict", "=", "None", "# type: Optional[Dict[str, str]]", ")", ":", "# type: (...) -> Tuple[str, str, str]", "query_parameters", "=", "{", "\"access_token\"", ":", "ac...
https://github.com/poljar/matrix-nio/blob/ecb548144a5c4f6a5d18e23b6a844374526c1bd1/nio/api.py#L1202-L1239
MatthewJA/Inverse-Reinforcement-Learning
56983aeee85eacb07164c313c03457bfaaa62778
irl/linear_irl.py
python
v_tensor
(value, transition_probability, feature_dimension, n_states, n_actions, policy)
return v
Finds the v tensor used in large linear IRL. value: NumPy matrix for the value function. The (i, j)th component represents the value of the jth state under the ith basis function. transition_probability: NumPy array mapping (state_i, action, state_k) to the probability of transitioning from state_i to state_k under action. Shape (N, A, N). feature_dimension: Dimension of the feature matrix. int. n_states: Number of states sampled. int. n_actions: Number of actions. int. policy: NumPy array mapping state ints to action ints. -> v helper tensor.
Finds the v tensor used in large linear IRL.
[ "Finds", "the", "v", "tensor", "used", "in", "large", "linear", "IRL", "." ]
def v_tensor(value, transition_probability, feature_dimension, n_states, n_actions, policy): """ Finds the v tensor used in large linear IRL. value: NumPy matrix for the value function. The (i, j)th component represents the value of the jth state under the ith basis function. transition_probability: NumPy array mapping (state_i, action, state_k) to the probability of transitioning from state_i to state_k under action. Shape (N, A, N). feature_dimension: Dimension of the feature matrix. int. n_states: Number of states sampled. int. n_actions: Number of actions. int. policy: NumPy array mapping state ints to action ints. -> v helper tensor. """ v = np.zeros((n_states, n_actions-1, feature_dimension)) for i in range(n_states): a1 = policy[i] exp_on_policy = np.dot(transition_probability[i, a1], value.T) seen_policy_action = False for j in range(n_actions): # Skip this if it's the on-policy action. if a1 == j: seen_policy_action = True continue exp_off_policy = np.dot(transition_probability[i, j], value.T) if seen_policy_action: v[i, j-1] = exp_on_policy - exp_off_policy else: v[i, j] = exp_on_policy - exp_off_policy return v
[ "def", "v_tensor", "(", "value", ",", "transition_probability", ",", "feature_dimension", ",", "n_states", ",", "n_actions", ",", "policy", ")", ":", "v", "=", "np", ".", "zeros", "(", "(", "n_states", ",", "n_actions", "-", "1", ",", "feature_dimension", ...
https://github.com/MatthewJA/Inverse-Reinforcement-Learning/blob/56983aeee85eacb07164c313c03457bfaaa62778/irl/linear_irl.py#L100-L133
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
txdav/common/datastore/sql_sharing.py
python
SharingMixIn.migrateBindRecords
(self, bindUID)
The user that owns this collection is being migrated to another pod. We need to switch over the sharing details to point to the new external user.
The user that owns this collection is being migrated to another pod. We need to switch over the sharing details to point to the new external user.
[ "The", "user", "that", "owns", "this", "collection", "is", "being", "migrated", "to", "another", "pod", ".", "We", "need", "to", "switch", "over", "the", "sharing", "details", "to", "point", "to", "the", "new", "external", "user", "." ]
def migrateBindRecords(self, bindUID): """ The user that owns this collection is being migrated to another pod. We need to switch over the sharing details to point to the new external user. """ if self.owned(): return self.migrateSharedByRecords(bindUID) else: return self.migrateSharedToRecords()
[ "def", "migrateBindRecords", "(", "self", ",", "bindUID", ")", ":", "if", "self", ".", "owned", "(", ")", ":", "return", "self", ".", "migrateSharedByRecords", "(", "bindUID", ")", "else", ":", "return", "self", ".", "migrateSharedToRecords", "(", ")" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/txdav/common/datastore/sql_sharing.py#L1063-L1071
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/nntplib.py
python
NNTP.shortcmd
(self, line)
return self.getresp()
Internal: send a command and get the response.
Internal: send a command and get the response.
[ "Internal", ":", "send", "a", "command", "and", "get", "the", "response", "." ]
def shortcmd(self, line): """Internal: send a command and get the response.""" self.putcmd(line) return self.getresp()
[ "def", "shortcmd", "(", "self", ",", "line", ")", ":", "self", ".", "putcmd", "(", "line", ")", "return", "self", ".", "getresp", "(", ")" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/nntplib.py#L265-L268
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_config_map_env_source.py
python
V1ConfigMapEnvSource.__ne__
(self, other)
return not self == other
Returns true if both objects are not equal
Returns true if both objects are not equal
[ "Returns", "true", "if", "both", "objects", "are", "not", "equal" ]
def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "return", "not", "self", "==", "other" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_config_map_env_source.py#L139-L143
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/dc/v20180410/dc_client.py
python
DcClient.DescribeDirectConnects
(self, request)
查询物理专线列表。 :param request: Request instance for DescribeDirectConnects. :type request: :class:`tencentcloud.dc.v20180410.models.DescribeDirectConnectsRequest` :rtype: :class:`tencentcloud.dc.v20180410.models.DescribeDirectConnectsResponse`
查询物理专线列表。
[ "查询物理专线列表。" ]
def DescribeDirectConnects(self, request): """查询物理专线列表。 :param request: Request instance for DescribeDirectConnects. :type request: :class:`tencentcloud.dc.v20180410.models.DescribeDirectConnectsRequest` :rtype: :class:`tencentcloud.dc.v20180410.models.DescribeDirectConnectsResponse` """ try: params = request._serialize() body = self.call("DescribeDirectConnects", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.DescribeDirectConnectsResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "DescribeDirectConnects", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"DescribeDirectConnects\"", ",", "params", ")", "response", "=", "json", "."...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/dc/v20180410/dc_client.py#L285-L310
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/scheduler/utils.py
python
build_filter_properties
( scheduler_hints, forced_host, forced_node, flavor, )
return filter_properties
Build the filter_properties dict from data in the boot request.
Build the filter_properties dict from data in the boot request.
[ "Build", "the", "filter_properties", "dict", "from", "data", "in", "the", "boot", "request", "." ]
def build_filter_properties( scheduler_hints, forced_host, forced_node, flavor, ): """Build the filter_properties dict from data in the boot request.""" filter_properties = dict(scheduler_hints=scheduler_hints) filter_properties['instance_type'] = flavor # TODO(alaski): It doesn't seem necessary that these are conditionally # added. Let's just add empty lists if not forced_host/node. if forced_host: filter_properties['force_hosts'] = [forced_host] if forced_node: filter_properties['force_nodes'] = [forced_node] return filter_properties
[ "def", "build_filter_properties", "(", "scheduler_hints", ",", "forced_host", ",", "forced_node", ",", "flavor", ",", ")", ":", "filter_properties", "=", "dict", "(", "scheduler_hints", "=", "scheduler_hints", ")", "filter_properties", "[", "'instance_type'", "]", "...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/scheduler/utils.py#L916-L928
taypo/redial
581f5ebbc814bff7e524fc96cd952f1b712b4c43
src/redial/config.py
python
Config.__get_or_create_config_file
()
return full_path
[]
def __get_or_create_config_file() -> str: full_path = Config.__CONFIG_PATH + "/" + Config.__CONFIG_FILE if not os.path.isfile(full_path): file = open(full_path, "w") file.close() return full_path
[ "def", "__get_or_create_config_file", "(", ")", "->", "str", ":", "full_path", "=", "Config", ".", "__CONFIG_PATH", "+", "\"/\"", "+", "Config", ".", "__CONFIG_FILE", "if", "not", "os", ".", "path", ".", "isfile", "(", "full_path", ")", ":", "file", "=", ...
https://github.com/taypo/redial/blob/581f5ebbc814bff7e524fc96cd952f1b712b4c43/src/redial/config.py#L76-L81
owid/covid-19-data
936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92
scripts/src/cowidev/vax/incremental/hungary.py
python
Hungary.parse_data
(self, soup: BeautifulSoup, last_update: str)
return records, True
[]
def parse_data(self, soup: BeautifulSoup, last_update: str) -> tuple: elems = self.get_elements(soup) # print(elems) records = [] for elem in elems: # print(elem) soup = get_soup(elem["link"]) record = { "source_url": elem["link"], **self.parse_data_news_page(soup), } # print("----") # print(record) if record["date"] > last_update: # print(record, "added") records.append(record) else: # print(record["date"], "END") return records, False return records, True
[ "def", "parse_data", "(", "self", ",", "soup", ":", "BeautifulSoup", ",", "last_update", ":", "str", ")", "->", "tuple", ":", "elems", "=", "self", ".", "get_elements", "(", "soup", ")", "# print(elems)", "records", "=", "[", "]", "for", "elem", "in", ...
https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/vax/incremental/hungary.py#L37-L56
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/multiclass.py
python
OutputCodeClassifier.fit
(self, X, y)
return self
Fit underlying estimators. Parameters ---------- X : (sparse) array-like, shape = [n_samples, n_features] Data. y : numpy array of shape [n_samples] Multi-class targets. Returns ------- self
Fit underlying estimators.
[ "Fit", "underlying", "estimators", "." ]
def fit(self, X, y): """Fit underlying estimators. Parameters ---------- X : (sparse) array-like, shape = [n_samples, n_features] Data. y : numpy array of shape [n_samples] Multi-class targets. Returns ------- self """ if self.code_size <= 0: raise ValueError("code_size should be greater than 0, got {1}" "".format(self.code_size)) _check_estimator(self.estimator) random_state = check_random_state(self.random_state) self.classes_ = np.unique(y) n_classes = self.classes_.shape[0] code_size_ = int(n_classes * self.code_size) # FIXME: there are more elaborate methods than generating the codebook # randomly. self.code_book_ = random_state.random_sample((n_classes, code_size_)) self.code_book_[self.code_book_ > 0.5] = 1 if hasattr(self.estimator, "decision_function"): self.code_book_[self.code_book_ != 1] = -1 else: self.code_book_[self.code_book_ != 1] = 0 classes_index = dict((c, i) for i, c in enumerate(self.classes_)) Y = np.array([self.code_book_[classes_index[y[i]]] for i in range(X.shape[0])], dtype=np.int) self.estimators_ = Parallel(n_jobs=self.n_jobs)( delayed(_fit_binary)(self.estimator, X, Y[:, i]) for i in range(Y.shape[1])) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "if", "self", ".", "code_size", "<=", "0", ":", "raise", "ValueError", "(", "\"code_size should be greater than 0, got {1}\"", "\"\"", ".", "format", "(", "self", ".", "code_size", ")", ")", "_check_...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/multiclass.py#L686-L731
pwnieexpress/raspberry_pwn
86f80e781cfb9f130a21a7ff41ef3d5c0340f287
src/pexpect-2.3/pexpect.py
python
searcher_re.__init__
(self, patterns)
This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.
This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.
[ "This", "creates", "an", "instance", "that", "searches", "for", "patterns", "Where", "patterns", "may", "be", "a", "list", "or", "other", "sequence", "of", "compiled", "regular", "expressions", "or", "the", "EOF", "or", "TIMEOUT", "types", "." ]
def __init__(self, patterns): """This creates an instance that searches for 'patterns' Where 'patterns' may be a list or other sequence of compiled regular expressions, or the EOF or TIMEOUT types.""" self.eof_index = -1 self.timeout_index = -1 self._searches = [] for n, s in zip(range(len(patterns)), patterns): if s is EOF: self.eof_index = n continue if s is TIMEOUT: self.timeout_index = n continue self._searches.append((n, s))
[ "def", "__init__", "(", "self", ",", "patterns", ")", ":", "self", ".", "eof_index", "=", "-", "1", "self", ".", "timeout_index", "=", "-", "1", "self", ".", "_searches", "=", "[", "]", "for", "n", ",", "s", "in", "zip", "(", "range", "(", "len",...
https://github.com/pwnieexpress/raspberry_pwn/blob/86f80e781cfb9f130a21a7ff41ef3d5c0340f287/src/pexpect-2.3/pexpect.py#L1695-L1711
mardix/propel-legacy
9f786bb4a1e04fe97e408ae5cebf71fcff468174
propel/__init__.py
python
get_venv_bin
(bin_program=None, virtualenv=None)
return (bin + "/%s") % bin_program if bin_program else bin
Get the bin path of a virtualenv program
Get the bin path of a virtualenv program
[ "Get", "the", "bin", "path", "of", "a", "virtualenv", "program" ]
def get_venv_bin(bin_program=None, virtualenv=None): """ Get the bin path of a virtualenv program """ bin = (VIRTUALENV_DIRECTORY + "/%s/bin") % virtualenv if virtualenv else LOCAL_BIN return (bin + "/%s") % bin_program if bin_program else bin
[ "def", "get_venv_bin", "(", "bin_program", "=", "None", ",", "virtualenv", "=", "None", ")", ":", "bin", "=", "(", "VIRTUALENV_DIRECTORY", "+", "\"/%s/bin\"", ")", "%", "virtualenv", "if", "virtualenv", "else", "LOCAL_BIN", "return", "(", "bin", "+", "\"/%s\...
https://github.com/mardix/propel-legacy/blob/9f786bb4a1e04fe97e408ae5cebf71fcff468174/propel/__init__.py#L295-L300
ganglia/gmond_python_modules
2f7fcab3d27926ef4a2feb1b53c09af16a43e729
hhvm/python_modules/hhvm.py
python
JemallocData.get
(self, name)
[]
def get(self, name): try: logging.debug('JemallocData get method called') root = ET.parse(fetch_url(self.url)).getroot() for child in root: self.data['hhvm_jemalloc_' + child.tag] = child.text return int(self.data[name_map[name]]) except: logging.error('JemallocData get method failed, ' 'could not parse output data, retval=0') return 0
[ "def", "get", "(", "self", ",", "name", ")", ":", "try", ":", "logging", ".", "debug", "(", "'JemallocData get method called'", ")", "root", "=", "ET", ".", "parse", "(", "fetch_url", "(", "self", ".", "url", ")", ")", ".", "getroot", "(", ")", "for"...
https://github.com/ganglia/gmond_python_modules/blob/2f7fcab3d27926ef4a2feb1b53c09af16a43e729/hhvm/python_modules/hhvm.py#L196-L206
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/combinatorics/partitions.py
python
IntegerPartition.next_lex
(self)
return IntegerPartition(self.integer, d)
Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([3, 1]) >>> print(p.next_lex()) [4] >>> p.partition < p.next_lex().partition True
Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1].
[ "Return", "the", "next", "partition", "of", "the", "integer", "n", "in", "lexical", "order", "wrapping", "around", "to", "[", "n", "]", "if", "the", "partition", "is", "[", "1", "...", "1", "]", "." ]
def next_lex(self): """Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([3, 1]) >>> print(p.next_lex()) [4] >>> p.partition < p.next_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) key = self._keys a = key[-1] if a == self.integer: d.clear() d[1] = self.integer elif a == 1: if d[a] > 1: d[a + 1] += 1 d[a] -= 2 else: b = key[-2] d[b + 1] += 1 d[1] = (d[b] - 1)*b d[b] = 0 else: if d[a] > 1: if len(key) == 1: d.clear() d[a + 1] = 1 d[1] = self.integer - a - 1 else: a1 = a + 1 d[a1] += 1 d[1] = d[a]*a - a1 d[a] = 0 else: b = key[-2] b1 = b + 1 d[b1] += 1 need = d[b]*b + d[a]*a - b1 d[a] = d[b] = 0 d[1] = need return IntegerPartition(self.integer, d)
[ "def", "next_lex", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "int", ")", "d", ".", "update", "(", "self", ".", "as_dict", "(", ")", ")", "key", "=", "self", ".", "_keys", "a", "=", "key", "[", "-", "1", "]", "if", "a", "==", "self"...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/combinatorics/partitions.py#L425-L473
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/internals.py
python
Block.apply
(self, func, mgr=None, **kwargs)
return result
apply the function to my values; return a block if we are not one
apply the function to my values; return a block if we are not one
[ "apply", "the", "function", "to", "my", "values", ";", "return", "a", "block", "if", "we", "are", "not", "one" ]
def apply(self, func, mgr=None, **kwargs): """ apply the function to my values; return a block if we are not one """ with np.errstate(all='ignore'): result = func(self.values, **kwargs) if not isinstance(result, Block): result = self.make_block(values=_block_shape(result, ndim=self.ndim)) return result
[ "def", "apply", "(", "self", ",", "func", ",", "mgr", "=", "None", ",", "*", "*", "kwargs", ")", ":", "with", "np", ".", "errstate", "(", "all", "=", "'ignore'", ")", ":", "result", "=", "func", "(", "self", ".", "values", ",", "*", "*", "kwarg...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/internals.py#L346-L356