nwo
stringlengths
5
91
sha
stringlengths
40
40
path
stringlengths
5
174
language
stringclasses
1 value
identifier
stringlengths
1
120
parameters
stringlengths
0
3.15k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
24.1k
docstring
stringlengths
0
27.3k
docstring_summary
stringlengths
0
13.8k
docstring_tokens
sequence
function
stringlengths
22
139k
function_tokens
sequence
url
stringlengths
87
283
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/key.py
python
finger_master
(hash_type=None)
return salt.utils.crypt.pem_finger( os.path.join(__opts__["pki_dir"], "minion_master.pub"), sum_type=hash_type )
Return the fingerprint of the master's public key on the minion. hash_type The hash algorithm used to calculate the fingerprint CLI Example: .. code-block:: bash salt '*' key.finger_master
Return the fingerprint of the master's public key on the minion.
[ "Return", "the", "fingerprint", "of", "the", "master", "s", "public", "key", "on", "the", "minion", "." ]
def finger_master(hash_type=None): """ Return the fingerprint of the master's public key on the minion. hash_type The hash algorithm used to calculate the fingerprint CLI Example: .. code-block:: bash salt '*' key.finger_master """ if hash_type is None: hash_type = __opts__["hash_type"] return salt.utils.crypt.pem_finger( os.path.join(__opts__["pki_dir"], "minion_master.pub"), sum_type=hash_type )
[ "def", "finger_master", "(", "hash_type", "=", "None", ")", ":", "if", "hash_type", "is", "None", ":", "hash_type", "=", "__opts__", "[", "\"hash_type\"", "]", "return", "salt", ".", "utils", ".", "crypt", ".", "pem_finger", "(", "os", ".", "path", ".", "join", "(", "__opts__", "[", "\"pki_dir\"", "]", ",", "\"minion_master.pub\"", ")", ",", "sum_type", "=", "hash_type", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/key.py#L31-L49
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/opflow/state_fns/vector_state_fn.py
python
VectorStateFn.__init__
( self, primitive: Union[list, np.ndarray, Statevector] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, )
Args: primitive: The ``Statevector``, NumPy array, or list, which defines the behavior of the underlying function. coeff: A coefficient multiplying the state function. is_measurement: Whether the StateFn is a measurement operator
Args: primitive: The ``Statevector``, NumPy array, or list, which defines the behavior of the underlying function. coeff: A coefficient multiplying the state function. is_measurement: Whether the StateFn is a measurement operator
[ "Args", ":", "primitive", ":", "The", "Statevector", "NumPy", "array", "or", "list", "which", "defines", "the", "behavior", "of", "the", "underlying", "function", ".", "coeff", ":", "A", "coefficient", "multiplying", "the", "state", "function", ".", "is_measurement", ":", "Whether", "the", "StateFn", "is", "a", "measurement", "operator" ]
def __init__( self, primitive: Union[list, np.ndarray, Statevector] = None, coeff: Union[complex, ParameterExpression] = 1.0, is_measurement: bool = False, ) -> None: """ Args: primitive: The ``Statevector``, NumPy array, or list, which defines the behavior of the underlying function. coeff: A coefficient multiplying the state function. is_measurement: Whether the StateFn is a measurement operator """ # Lists and Numpy arrays representing statevectors are stored # in Statevector objects for easier handling. if isinstance(primitive, (np.ndarray, list)): primitive = Statevector(primitive) super().__init__(primitive, coeff=coeff, is_measurement=is_measurement)
[ "def", "__init__", "(", "self", ",", "primitive", ":", "Union", "[", "list", ",", "np", ".", "ndarray", ",", "Statevector", "]", "=", "None", ",", "coeff", ":", "Union", "[", "complex", ",", "ParameterExpression", "]", "=", "1.0", ",", "is_measurement", ":", "bool", "=", "False", ",", ")", "->", "None", ":", "# Lists and Numpy arrays representing statevectors are stored", "# in Statevector objects for easier handling.", "if", "isinstance", "(", "primitive", ",", "(", "np", ".", "ndarray", ",", "list", ")", ")", ":", "primitive", "=", "Statevector", "(", "primitive", ")", "super", "(", ")", ".", "__init__", "(", "primitive", ",", "coeff", "=", "coeff", ",", "is_measurement", "=", "is_measurement", ")" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/opflow/state_fns/vector_state_fn.py#L39-L57
Emsu/prophet
ea8232a649f0f323cd5aa7b47478b986647e15e0
prophet/app.py
python
Prophet.run_backtest
(self, start, end=None, lookback=0, slippage=0.0, commission=0.0, cash=1000000, # $1,000,000 initial_portfolio=Portfolio(), )
return backtest(cash=cash, data=data, start=effective_start, end=end, slippage=slippage, commission=commission, portfolio=initial_portfolio, order_generator=self._order_generator, )
Runs a backtest over a given time period. Args: start (datetime): The start of the backtest window end (datetime): The end of the backtest windows lookback (int): Number of trading days you want data for before the start date slippage (float): Percent price slippage when executing order commission (float): Amount of commission paid per order cash (int): Amount of starting cash portfolio (prophet.portfolio.Portfolio): Starting portfolio Return: prophet.backtest.BackTest
Runs a backtest over a given time period.
[ "Runs", "a", "backtest", "over", "a", "given", "time", "period", "." ]
def run_backtest(self, start, end=None, lookback=0, slippage=0.0, commission=0.0, cash=1000000, # $1,000,000 initial_portfolio=Portfolio(), ): """ Runs a backtest over a given time period. Args: start (datetime): The start of the backtest window end (datetime): The end of the backtest windows lookback (int): Number of trading days you want data for before the start date slippage (float): Percent price slippage when executing order commission (float): Amount of commission paid per order cash (int): Amount of starting cash portfolio (prophet.portfolio.Portfolio): Starting portfolio Return: prophet.backtest.BackTest """ # Setup if not end: today = dt.date.today() end = dt.datetime.combine(today, dt.time()) if not self._order_generator: raise ProphetException("Must set an order generator by calling" "set_order_generator.") timestamps = trading_days[(trading_days >= start) & (trading_days <= end)] effective_start = timestamps[0] data = self._generate_data(start=effective_start, end=end, lookback=lookback) # Run backtest return backtest(cash=cash, data=data, start=effective_start, end=end, slippage=slippage, commission=commission, portfolio=initial_portfolio, order_generator=self._order_generator, )
[ "def", "run_backtest", "(", "self", ",", "start", ",", "end", "=", "None", ",", "lookback", "=", "0", ",", "slippage", "=", "0.0", ",", "commission", "=", "0.0", ",", "cash", "=", "1000000", ",", "# $1,000,000", "initial_portfolio", "=", "Portfolio", "(", ")", ",", ")", ":", "# Setup", "if", "not", "end", ":", "today", "=", "dt", ".", "date", ".", "today", "(", ")", "end", "=", "dt", ".", "datetime", ".", "combine", "(", "today", ",", "dt", ".", "time", "(", ")", ")", "if", "not", "self", ".", "_order_generator", ":", "raise", "ProphetException", "(", "\"Must set an order generator by calling\"", "\"set_order_generator.\"", ")", "timestamps", "=", "trading_days", "[", "(", "trading_days", ">=", "start", ")", "&", "(", "trading_days", "<=", "end", ")", "]", "effective_start", "=", "timestamps", "[", "0", "]", "data", "=", "self", ".", "_generate_data", "(", "start", "=", "effective_start", ",", "end", "=", "end", ",", "lookback", "=", "lookback", ")", "# Run backtest", "return", "backtest", "(", "cash", "=", "cash", ",", "data", "=", "data", ",", "start", "=", "effective_start", ",", "end", "=", "end", ",", "slippage", "=", "slippage", ",", "commission", "=", "commission", ",", "portfolio", "=", "initial_portfolio", ",", "order_generator", "=", "self", ".", "_order_generator", ",", ")" ]
https://github.com/Emsu/prophet/blob/ea8232a649f0f323cd5aa7b47478b986647e15e0/prophet/app.py#L27-L77
openstack/tacker
a60993fc3b2d4fc0e93ab13a874fe3c314fe48de
tacker/api/extensions.py
python
ExtensionDescriptor.get_request_extensions
(self)
return request_exts
List of extensions.RequestException extension objects. Request extensions are used to handle custom request data.
List of extensions.RequestException extension objects.
[ "List", "of", "extensions", ".", "RequestException", "extension", "objects", "." ]
def get_request_extensions(self): """List of extensions.RequestException extension objects. Request extensions are used to handle custom request data. """ request_exts = [] return request_exts
[ "def", "get_request_extensions", "(", "self", ")", ":", "request_exts", "=", "[", "]", "return", "request_exts" ]
https://github.com/openstack/tacker/blob/a60993fc3b2d4fc0e93ab13a874fe3c314fe48de/tacker/api/extensions.py#L120-L126
aws/sagemaker-python-sdk
9d259b316f7f43838c16f35c10e98a110b56735b
src/sagemaker/estimator.py
python
EstimatorBase._ensure_base_job_name
(self)
Set ``self.base_job_name`` if it is not set already.
Set ``self.base_job_name`` if it is not set already.
[ "Set", "self", ".", "base_job_name", "if", "it", "is", "not", "set", "already", "." ]
def _ensure_base_job_name(self): """Set ``self.base_job_name`` if it is not set already.""" # honor supplied base_job_name or generate it if self.base_job_name is None: self.base_job_name = base_name_from_image(self.training_image_uri())
[ "def", "_ensure_base_job_name", "(", "self", ")", ":", "# honor supplied base_job_name or generate it", "if", "self", ".", "base_job_name", "is", "None", ":", "self", ".", "base_job_name", "=", "base_name_from_image", "(", "self", ".", "training_image_uri", "(", ")", ")" ]
https://github.com/aws/sagemaker-python-sdk/blob/9d259b316f7f43838c16f35c10e98a110b56735b/src/sagemaker/estimator.py#L418-L422
spender-sandbox/cuckoo-modified
eb93ef3d41b8fee51b4330306dcd315d8101e021
modules/machinery/vsphere.py
python
vSphere._wait_task
(self, task)
Wait for a task to complete with timeout
Wait for a task to complete with timeout
[ "Wait", "for", "a", "task", "to", "complete", "with", "timeout" ]
def _wait_task(self, task): """Wait for a task to complete with timeout""" limit = timedelta(seconds=int(self.options_globals.timeouts.vm_state)) start = datetime.utcnow() while True: if task.info.state == "error": raise CuckooMachineError("Task error") if task.info.state == "success": break if datetime.utcnow() - start > limit: raise CuckooMachineError("Task timed out") time.sleep(1)
[ "def", "_wait_task", "(", "self", ",", "task", ")", ":", "limit", "=", "timedelta", "(", "seconds", "=", "int", "(", "self", ".", "options_globals", ".", "timeouts", ".", "vm_state", ")", ")", "start", "=", "datetime", ".", "utcnow", "(", ")", "while", "True", ":", "if", "task", ".", "info", ".", "state", "==", "\"error\"", ":", "raise", "CuckooMachineError", "(", "\"Task error\"", ")", "if", "task", ".", "info", ".", "state", "==", "\"success\"", ":", "break", "if", "datetime", ".", "utcnow", "(", ")", "-", "start", ">", "limit", ":", "raise", "CuckooMachineError", "(", "\"Task timed out\"", ")", "time", ".", "sleep", "(", "1", ")" ]
https://github.com/spender-sandbox/cuckoo-modified/blob/eb93ef3d41b8fee51b4330306dcd315d8101e021/modules/machinery/vsphere.py#L354-L369
aws/aws-parallelcluster
f1fe5679a01c524e7ea904c329bd6d17318c6cd9
cli/src/pcluster/api/models/create_cluster_request_content.py
python
CreateClusterRequestContent.__init__
(self, cluster_name=None, cluster_configuration=None)
CreateClusterRequestContent - a model defined in OpenAPI :param cluster_name: The cluster_name of this CreateClusterRequestContent. # noqa: E501 :type cluster_name: str :param cluster_configuration: The cluster_configuration of this CreateClusterRequestContent. # noqa: E501 :type cluster_configuration: str
CreateClusterRequestContent - a model defined in OpenAPI
[ "CreateClusterRequestContent", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, cluster_name=None, cluster_configuration=None): """CreateClusterRequestContent - a model defined in OpenAPI :param cluster_name: The cluster_name of this CreateClusterRequestContent. # noqa: E501 :type cluster_name: str :param cluster_configuration: The cluster_configuration of this CreateClusterRequestContent. # noqa: E501 :type cluster_configuration: str """ self.openapi_types = {"cluster_name": str, "cluster_configuration": str} self.attribute_map = {"cluster_name": "clusterName", "cluster_configuration": "clusterConfiguration"} self._cluster_name = cluster_name self._cluster_configuration = cluster_configuration
[ "def", "__init__", "(", "self", ",", "cluster_name", "=", "None", ",", "cluster_configuration", "=", "None", ")", ":", "self", ".", "openapi_types", "=", "{", "\"cluster_name\"", ":", "str", ",", "\"cluster_configuration\"", ":", "str", "}", "self", ".", "attribute_map", "=", "{", "\"cluster_name\"", ":", "\"clusterName\"", ",", "\"cluster_configuration\"", ":", "\"clusterConfiguration\"", "}", "self", ".", "_cluster_name", "=", "cluster_name", "self", ".", "_cluster_configuration", "=", "cluster_configuration" ]
https://github.com/aws/aws-parallelcluster/blob/f1fe5679a01c524e7ea904c329bd6d17318c6cd9/cli/src/pcluster/api/models/create_cluster_request_content.py#L24-L37
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/runners/smartos_vmadm.py
python
is_running
(search)
return _action("is_running", search, False)
Return true if vm is running search : string filter vms, see the execution module. .. note:: If the search parameter does not contain an equal (=) symbol it will be assumed it will be tried as uuid, hostname, and alias. .. note:: If multiple vms are matched, the result will be true of ALL vms are running CLI Example: .. code-block:: bash salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9 salt-run vmadm.is_running search='alias=julia'
Return true if vm is running
[ "Return", "true", "if", "vm", "is", "running" ]
def is_running(search): """ Return true if vm is running search : string filter vms, see the execution module. .. note:: If the search parameter does not contain an equal (=) symbol it will be assumed it will be tried as uuid, hostname, and alias. .. note:: If multiple vms are matched, the result will be true of ALL vms are running CLI Example: .. code-block:: bash salt-run vmadm.is_running 91244bba-1146-e4ec-c07e-e825e0223aa9 salt-run vmadm.is_running search='alias=julia' """ return _action("is_running", search, False)
[ "def", "is_running", "(", "search", ")", ":", "return", "_action", "(", "\"is_running\"", ",", "search", ",", "False", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/runners/smartos_vmadm.py#L364-L385
AIChallenger/AI_Challenger_2018
f0e4376152c8fe5a098ed92a973cec96b13e1a24
Baselines/autonomous_driving_perception208_baseline/segmentation/utils/get_dataset_colormap.py
python
create_ade20k_label_colormap
()
return np.asarray([ [0, 0, 0], [120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255], [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224], [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7], [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255], [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255], [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255], [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255], [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0], [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0], [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255], [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255], [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20], [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255], [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255], [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255], [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0], [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0], [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255], [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112], [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160], [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163], [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0], [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0], [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255], [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204], [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255], [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255], [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194], [102, 255, 0], [92, 0, 255], ])
Creates a label colormap used in ADE20K segmentation benchmark. Returns: A colormap for visualizing segmentation results.
Creates a label colormap used in ADE20K segmentation benchmark.
[ "Creates", "a", "label", "colormap", "used", "in", "ADE20K", "segmentation", "benchmark", "." ]
def create_ade20k_label_colormap(): """Creates a label colormap used in ADE20K segmentation benchmark. Returns: A colormap for visualizing segmentation results. """ return np.asarray([ [0, 0, 0], [120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255], [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224], [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7], [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255], [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255], [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255], [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255], [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0], [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0], [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255], [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255], [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20], [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255], [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255], [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255], [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0], [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0], [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255], [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112], [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160], [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163], [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0], [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0], [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255], [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204], [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255], [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255], [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194], [102, 255, 0], [92, 0, 255], ])
[ "def", "create_ade20k_label_colormap", "(", ")", ":", "return", "np", ".", "asarray", "(", "[", "[", "0", ",", "0", ",", "0", "]", ",", "[", "120", ",", "120", ",", "120", "]", ",", "[", "180", ",", "120", ",", "120", "]", ",", "[", "6", ",", "230", ",", "230", "]", ",", "[", "80", ",", "50", ",", "50", "]", ",", "[", "4", ",", "200", ",", "3", "]", ",", "[", "120", ",", "120", ",", "80", "]", ",", "[", "140", ",", "140", ",", "140", "]", ",", "[", "204", ",", "5", ",", "255", "]", ",", "[", "230", ",", "230", ",", "230", "]", ",", "[", "4", ",", "250", ",", "7", "]", ",", "[", "224", ",", "5", ",", "255", "]", ",", "[", "235", ",", "255", ",", "7", "]", ",", "[", "150", ",", "5", ",", "61", "]", ",", "[", "120", ",", "120", ",", "70", "]", ",", "[", "8", ",", "255", ",", "51", "]", ",", "[", "255", ",", "6", ",", "82", "]", ",", "[", "143", ",", "255", ",", "140", "]", ",", "[", "204", ",", "255", ",", "4", "]", ",", "[", "255", ",", "51", ",", "7", "]", ",", "[", "204", ",", "70", ",", "3", "]", ",", "[", "0", ",", "102", ",", "200", "]", ",", "[", "61", ",", "230", ",", "250", "]", ",", "[", "255", ",", "6", ",", "51", "]", ",", "[", "11", ",", "102", ",", "255", "]", ",", "[", "255", ",", "7", ",", "71", "]", ",", "[", "255", ",", "9", ",", "224", "]", ",", "[", "9", ",", "7", ",", "230", "]", ",", "[", "220", ",", "220", ",", "220", "]", ",", "[", "255", ",", "9", ",", "92", "]", ",", "[", "112", ",", "9", ",", "255", "]", ",", "[", "8", ",", "255", ",", "214", "]", ",", "[", "7", ",", "255", ",", "224", "]", ",", "[", "255", ",", "184", ",", "6", "]", ",", "[", "10", ",", "255", ",", "71", "]", ",", "[", "255", ",", "41", ",", "10", "]", ",", "[", "7", ",", "255", ",", "255", "]", ",", "[", "224", ",", "255", ",", "8", "]", ",", "[", "102", ",", "8", ",", "255", "]", ",", "[", "255", ",", "61", ",", "6", "]", ",", "[", "255", ",", "194", ",", "7", "]", ",", "[", "255", ",", "122", ",", "8", "]", ",", "[", "0", ",", "255", ",", "20", "]", ",", "[", "255", ",", "8", ",", "41", "]", ",", "[", "255", ",", "5", ",", "153", "]", ",", "[", "6", ",", "51", ",", "255", "]", ",", "[", "235", ",", "12", ",", "255", "]", ",", "[", "160", ",", "150", ",", "20", "]", ",", "[", "0", ",", "163", ",", "255", "]", ",", "[", "140", ",", "140", ",", "140", "]", ",", "[", "250", ",", "10", ",", "15", "]", ",", "[", "20", ",", "255", ",", "0", "]", ",", "[", "31", ",", "255", ",", "0", "]", ",", "[", "255", ",", "31", ",", "0", "]", ",", "[", "255", ",", "224", ",", "0", "]", ",", "[", "153", ",", "255", ",", "0", "]", ",", "[", "0", ",", "0", ",", "255", "]", ",", "[", "255", ",", "71", ",", "0", "]", ",", "[", "0", ",", "235", ",", "255", "]", ",", "[", "0", ",", "173", ",", "255", "]", ",", "[", "31", ",", "0", ",", "255", "]", ",", "[", "11", ",", "200", ",", "200", "]", ",", "[", "255", ",", "82", ",", "0", "]", ",", "[", "0", ",", "255", ",", "245", "]", ",", "[", "0", ",", "61", ",", "255", "]", ",", "[", "0", ",", "255", ",", "112", "]", ",", "[", "0", ",", "255", ",", "133", "]", ",", "[", "255", ",", "0", ",", "0", "]", ",", "[", "255", ",", "163", ",", "0", "]", ",", "[", "255", ",", "102", ",", "0", "]", ",", "[", "194", ",", "255", ",", "0", "]", ",", "[", "0", ",", "143", ",", "255", "]", ",", "[", "51", ",", "255", ",", "0", "]", ",", "[", "0", ",", "82", ",", "255", "]", ",", "[", "0", ",", "255", ",", "41", "]", ",", "[", "0", ",", "255", ",", "173", "]", ",", "[", "10", ",", "0", ",", "255", "]", ",", "[", "173", ",", "255", ",", "0", "]", ",", "[", "0", ",", "255", ",", "153", "]", ",", "[", "255", ",", "92", ",", "0", "]", ",", "[", "255", ",", "0", ",", "255", "]", ",", "[", "255", ",", "0", ",", "245", "]", ",", "[", "255", ",", "0", ",", "102", "]", ",", "[", "255", ",", "173", ",", "0", "]", ",", "[", "255", ",", "0", ",", "20", "]", ",", "[", "255", ",", "184", ",", "184", "]", ",", "[", "0", ",", "31", ",", "255", "]", ",", "[", "0", ",", "255", ",", "61", "]", ",", "[", "0", ",", "71", ",", "255", "]", ",", "[", "255", ",", "0", ",", "204", "]", ",", "[", "0", ",", "255", ",", "194", "]", ",", "[", "0", ",", "255", ",", "82", "]", ",", "[", "0", ",", "10", ",", "255", "]", ",", "[", "0", ",", "112", ",", "255", "]", ",", "[", "51", ",", "0", ",", "255", "]", ",", "[", "0", ",", "194", ",", "255", "]", ",", "[", "0", ",", "122", ",", "255", "]", ",", "[", "0", ",", "255", ",", "163", "]", ",", "[", "255", ",", "153", ",", "0", "]", ",", "[", "0", ",", "255", ",", "10", "]", ",", "[", "255", ",", "112", ",", "0", "]", ",", "[", "143", ",", "255", ",", "0", "]", ",", "[", "82", ",", "0", ",", "255", "]", ",", "[", "163", ",", "255", ",", "0", "]", ",", "[", "255", ",", "235", ",", "0", "]", ",", "[", "8", ",", "184", ",", "170", "]", ",", "[", "133", ",", "0", ",", "255", "]", ",", "[", "0", ",", "255", ",", "92", "]", ",", "[", "184", ",", "0", ",", "255", "]", ",", "[", "255", ",", "0", ",", "31", "]", ",", "[", "0", ",", "184", ",", "255", "]", ",", "[", "0", ",", "214", ",", "255", "]", ",", "[", "255", ",", "0", ",", "112", "]", ",", "[", "92", ",", "255", ",", "0", "]", ",", "[", "0", ",", "224", ",", "255", "]", ",", "[", "112", ",", "224", ",", "255", "]", ",", "[", "70", ",", "184", ",", "160", "]", ",", "[", "163", ",", "0", ",", "255", "]", ",", "[", "153", ",", "0", ",", "255", "]", ",", "[", "71", ",", "255", ",", "0", "]", ",", "[", "255", ",", "0", ",", "163", "]", ",", "[", "255", ",", "204", ",", "0", "]", ",", "[", "255", ",", "0", ",", "143", "]", ",", "[", "0", ",", "255", ",", "235", "]", ",", "[", "133", ",", "255", ",", "0", "]", ",", "[", "255", ",", "0", ",", "235", "]", ",", "[", "245", ",", "0", ",", "255", "]", ",", "[", "255", ",", "0", ",", "122", "]", ",", "[", "255", ",", "245", ",", "0", "]", ",", "[", "10", ",", "190", ",", "212", "]", ",", "[", "214", ",", "255", ",", "0", "]", ",", "[", "0", ",", "204", ",", "255", "]", ",", "[", "20", ",", "0", ",", "255", "]", ",", "[", "255", ",", "255", ",", "0", "]", ",", "[", "0", ",", "153", ",", "255", "]", ",", "[", "0", ",", "41", ",", "255", "]", ",", "[", "0", ",", "255", ",", "204", "]", ",", "[", "41", ",", "0", ",", "255", "]", ",", "[", "41", ",", "255", ",", "0", "]", ",", "[", "173", ",", "0", ",", "255", "]", ",", "[", "0", ",", "245", ",", "255", "]", ",", "[", "71", ",", "0", ",", "255", "]", ",", "[", "122", ",", "0", ",", "255", "]", ",", "[", "0", ",", "255", ",", "184", "]", ",", "[", "0", ",", "92", ",", "255", "]", ",", "[", "184", ",", "255", ",", "0", "]", ",", "[", "0", ",", "133", ",", "255", "]", ",", "[", "255", ",", "214", ",", "0", "]", ",", "[", "25", ",", "194", ",", "194", "]", ",", "[", "102", ",", "255", ",", "0", "]", ",", "[", "92", ",", "0", ",", "255", "]", ",", "]", ")" ]
https://github.com/AIChallenger/AI_Challenger_2018/blob/f0e4376152c8fe5a098ed92a973cec96b13e1a24/Baselines/autonomous_driving_perception208_baseline/segmentation/utils/get_dataset_colormap.py#L46-L204
python-diamond/Diamond
7000e16cfdf4508ed9291fc4b3800592557b2431
src/collectors/ntpd/ntpd.py
python
NtpdCollector.collect
(self)
[]
def collect(self): for stat, v in self.get_ntpq_stats(): self.publish(stat, v['val'], precision=v['precision']) for stat, v in self.get_ntpdc_kerninfo_stats(): self.publish(stat, v['val'], precision=v['precision']) for stat, v in self.get_ntpdc_sysinfo_stats(): self.publish(stat, v['val'], precision=v['precision'])
[ "def", "collect", "(", "self", ")", ":", "for", "stat", ",", "v", "in", "self", ".", "get_ntpq_stats", "(", ")", ":", "self", ".", "publish", "(", "stat", ",", "v", "[", "'val'", "]", ",", "precision", "=", "v", "[", "'precision'", "]", ")", "for", "stat", ",", "v", "in", "self", ".", "get_ntpdc_kerninfo_stats", "(", ")", ":", "self", ".", "publish", "(", "stat", ",", "v", "[", "'val'", "]", ",", "precision", "=", "v", "[", "'precision'", "]", ")", "for", "stat", ",", "v", "in", "self", ".", "get_ntpdc_sysinfo_stats", "(", ")", ":", "self", ".", "publish", "(", "stat", ",", "v", "[", "'val'", "]", ",", "precision", "=", "v", "[", "'precision'", "]", ")" ]
https://github.com/python-diamond/Diamond/blob/7000e16cfdf4508ed9291fc4b3800592557b2431/src/collectors/ntpd/ntpd.py#L148-L156
wizyoung/googletranslate.popclipext
a3c465685a5a75213e2ec8517eb98d336984bc50
src/httpx/_api.py
python
options
( url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: AuthTypes = None, allow_redirects: bool = True, cert: CertTypes = None, verify: VerifyTypes = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True, )
return request( "OPTIONS", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, cert=cert, verify=verify, timeout=timeout, trust_env=trust_env, )
Sends an `OPTIONS` request. **Parameters**: See `httpx.request`. Note that the `data`, `files`, and `json` parameters are not available on this function, as `OPTIONS` requests should not include a request body.
Sends an `OPTIONS` request.
[ "Sends", "an", "OPTIONS", "request", "." ]
def options( url: URLTypes, *, params: QueryParamTypes = None, headers: HeaderTypes = None, cookies: CookieTypes = None, auth: AuthTypes = None, allow_redirects: bool = True, cert: CertTypes = None, verify: VerifyTypes = True, timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, trust_env: bool = True, ) -> Response: """ Sends an `OPTIONS` request. **Parameters**: See `httpx.request`. Note that the `data`, `files`, and `json` parameters are not available on this function, as `OPTIONS` requests should not include a request body. """ return request( "OPTIONS", url, params=params, headers=headers, cookies=cookies, auth=auth, allow_redirects=allow_redirects, cert=cert, verify=verify, timeout=timeout, trust_env=trust_env, )
[ "def", "options", "(", "url", ":", "URLTypes", ",", "*", ",", "params", ":", "QueryParamTypes", "=", "None", ",", "headers", ":", "HeaderTypes", "=", "None", ",", "cookies", ":", "CookieTypes", "=", "None", ",", "auth", ":", "AuthTypes", "=", "None", ",", "allow_redirects", ":", "bool", "=", "True", ",", "cert", ":", "CertTypes", "=", "None", ",", "verify", ":", "VerifyTypes", "=", "True", ",", "timeout", ":", "TimeoutTypes", "=", "DEFAULT_TIMEOUT_CONFIG", ",", "trust_env", ":", "bool", "=", "True", ",", ")", "->", "Response", ":", "return", "request", "(", "\"OPTIONS\"", ",", "url", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "cookies", "=", "cookies", ",", "auth", "=", "auth", ",", "allow_redirects", "=", "allow_redirects", ",", "cert", "=", "cert", ",", "verify", "=", "verify", ",", "timeout", "=", "timeout", ",", "trust_env", "=", "trust_env", ",", ")" ]
https://github.com/wizyoung/googletranslate.popclipext/blob/a3c465685a5a75213e2ec8517eb98d336984bc50/src/httpx/_api.py#L174-L207
civisanalytics/python-glmnet
813c06f5fcc9604d8e445bd4992f53c4855cc7cb
setup.py
python
read
(fname)
[]
def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as _in: return _in.read()
[ "def", "read", "(", "fname", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "fname", ")", ")", "as", "_in", ":", "return", "_in", ".", "read", "(", ")" ]
https://github.com/civisanalytics/python-glmnet/blob/813c06f5fcc9604d8e445bd4992f53c4855cc7cb/setup.py#L26-L28
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_rule_with_operations.py
python
V1RuleWithOperations.operations
(self, operations)
Sets the operations of this V1RuleWithOperations. Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :param operations: The operations of this V1RuleWithOperations. # noqa: E501 :type: list[str]
Sets the operations of this V1RuleWithOperations.
[ "Sets", "the", "operations", "of", "this", "V1RuleWithOperations", "." ]
def operations(self, operations): """Sets the operations of this V1RuleWithOperations. Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :param operations: The operations of this V1RuleWithOperations. # noqa: E501 :type: list[str] """ self._operations = operations
[ "def", "operations", "(", "self", ",", "operations", ")", ":", "self", ".", "_operations", "=", "operations" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_rule_with_operations.py#L133-L142
kensho-technologies/graphql-compiler
4318443b7b2512a059f3616112bfc40bbf8eec06
graphql_compiler/query_formatting/match_formatting.py
python
insert_arguments_into_match_query
(compilation_result, arguments)
return base_query.format(**sanitized_arguments)
Insert the arguments into the compiled MATCH query to form a complete query. Args: compilation_result: a CompilationResult object derived from the GraphQL compiler arguments: dict, str -> any, mapping argument name to its value, for every parameter the query expects. Returns: string, a MATCH query with inserted argument data
Insert the arguments into the compiled MATCH query to form a complete query.
[ "Insert", "the", "arguments", "into", "the", "compiled", "MATCH", "query", "to", "form", "a", "complete", "query", "." ]
def insert_arguments_into_match_query(compilation_result, arguments): """Insert the arguments into the compiled MATCH query to form a complete query. Args: compilation_result: a CompilationResult object derived from the GraphQL compiler arguments: dict, str -> any, mapping argument name to its value, for every parameter the query expects. Returns: string, a MATCH query with inserted argument data """ if compilation_result.language != MATCH_LANGUAGE: raise AssertionError("Unexpected query output language: {}".format(compilation_result)) base_query = compilation_result.query argument_types = compilation_result.input_metadata # The arguments are assumed to have already been validated against the query. sanitized_arguments = { key: _safe_match_argument(argument_types[key], value) for key, value in six.iteritems(arguments) } return base_query.format(**sanitized_arguments)
[ "def", "insert_arguments_into_match_query", "(", "compilation_result", ",", "arguments", ")", ":", "if", "compilation_result", ".", "language", "!=", "MATCH_LANGUAGE", ":", "raise", "AssertionError", "(", "\"Unexpected query output language: {}\"", ".", "format", "(", "compilation_result", ")", ")", "base_query", "=", "compilation_result", ".", "query", "argument_types", "=", "compilation_result", ".", "input_metadata", "# The arguments are assumed to have already been validated against the query.", "sanitized_arguments", "=", "{", "key", ":", "_safe_match_argument", "(", "argument_types", "[", "key", "]", ",", "value", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "arguments", ")", "}", "return", "base_query", ".", "format", "(", "*", "*", "sanitized_arguments", ")" ]
https://github.com/kensho-technologies/graphql-compiler/blob/4318443b7b2512a059f3616112bfc40bbf8eec06/graphql_compiler/query_formatting/match_formatting.py#L122-L145
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/lib/httputil.py
python
urljoin
(*atoms)
return url or "/"
Return the given path \*atoms, joined into a single URL. This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank.
Return the given path \*atoms, joined into a single URL.
[ "Return", "the", "given", "path", "\\", "*", "atoms", "joined", "into", "a", "single", "URL", "." ]
def urljoin(*atoms): """Return the given path \*atoms, joined into a single URL. This will correctly join a SCRIPT_NAME and PATH_INFO into the original URL, even if either atom is blank. """ url = "/".join([x for x in atoms if x]) while "//" in url: url = url.replace("//", "/") # Special-case the final url of "", and return "/" instead. return url or "/"
[ "def", "urljoin", "(", "*", "atoms", ")", ":", "url", "=", "\"/\"", ".", "join", "(", "[", "x", "for", "x", "in", "atoms", "if", "x", "]", ")", "while", "\"//\"", "in", "url", ":", "url", "=", "url", ".", "replace", "(", "\"//\"", ",", "\"/\"", ")", "# Special-case the final url of \"\", and return \"/\" instead.", "return", "url", "or", "\"/\"" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/lib/httputil.py#L29-L39
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/cron/groctimespecification.py
python
_GetTime
(time_string)
return datetime.time(int(hourstr), int(minutestr))
Converts a string to a datetime.time object. Arguments: time_string: a string representing a time ('hours:minutes') Returns: a datetime.time object
Converts a string to a datetime.time object.
[ "Converts", "a", "string", "to", "a", "datetime", ".", "time", "object", "." ]
def _GetTime(time_string): """Converts a string to a datetime.time object. Arguments: time_string: a string representing a time ('hours:minutes') Returns: a datetime.time object """ hourstr, minutestr = time_string.split(':') return datetime.time(int(hourstr), int(minutestr))
[ "def", "_GetTime", "(", "time_string", ")", ":", "hourstr", ",", "minutestr", "=", "time_string", ".", "split", "(", "':'", ")", "return", "datetime", ".", "time", "(", "int", "(", "hourstr", ")", ",", "int", "(", "minutestr", ")", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/cron/groctimespecification.py#L180-L190
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/db/api.py
python
service_destroy
(context, service_id)
return IMPL.service_destroy(context, service_id)
Destroy the service or raise if it does not exist.
Destroy the service or raise if it does not exist.
[ "Destroy", "the", "service", "or", "raise", "if", "it", "does", "not", "exist", "." ]
def service_destroy(context, service_id): """Destroy the service or raise if it does not exist.""" return IMPL.service_destroy(context, service_id)
[ "def", "service_destroy", "(", "context", ",", "service_id", ")", ":", "return", "IMPL", ".", "service_destroy", "(", "context", ",", "service_id", ")" ]
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/db/api.py#L83-L85
Ultimaker/Cura
a1622c77ea7259ecb956acd6de07b7d34b7ac52b
plugins/DigitalLibrary/src/DigitalFactoryController.py
python
DigitalFactoryController.setHasMoreProjectsToLoad
(self, has_more_projects_to_load: bool)
Set the value that indicates whether there are more pages of projects that can be loaded from the API :param has_more_projects_to_load: Whether there are more pages of projects
Set the value that indicates whether there are more pages of projects that can be loaded from the API
[ "Set", "the", "value", "that", "indicates", "whether", "there", "are", "more", "pages", "of", "projects", "that", "can", "be", "loaded", "from", "the", "API" ]
def setHasMoreProjectsToLoad(self, has_more_projects_to_load: bool) -> None: """ Set the value that indicates whether there are more pages of projects that can be loaded from the API :param has_more_projects_to_load: Whether there are more pages of projects """ if has_more_projects_to_load != self._has_more_projects_to_load: self._has_more_projects_to_load = has_more_projects_to_load self.hasMoreProjectsToLoadChanged.emit()
[ "def", "setHasMoreProjectsToLoad", "(", "self", ",", "has_more_projects_to_load", ":", "bool", ")", "->", "None", ":", "if", "has_more_projects_to_load", "!=", "self", ".", "_has_more_projects_to_load", ":", "self", ".", "_has_more_projects_to_load", "=", "has_more_projects_to_load", "self", ".", "hasMoreProjectsToLoadChanged", ".", "emit", "(", ")" ]
https://github.com/Ultimaker/Cura/blob/a1622c77ea7259ecb956acd6de07b7d34b7ac52b/plugins/DigitalLibrary/src/DigitalFactoryController.py#L358-L366
Borda/pyImSegm
7584b40a8d5bba04d3bf46f540f22b5d923e4b03
imsegm/utilities/data_io.py
python
io_image_decorate
(func)
return wrap
costume decorator to suppers debug messages from the PIL function to suppress PIl debug logging - DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13 :param func: :return:
costume decorator to suppers debug messages from the PIL function to suppress PIl debug logging - DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13
[ "costume", "decorator", "to", "suppers", "debug", "messages", "from", "the", "PIL", "function", "to", "suppress", "PIl", "debug", "logging", "-", "DEBUG", ":", "PIL", ".", "PngImagePlugin", ":", "STREAM", "b", "IHDR", "16", "13" ]
def io_image_decorate(func): """ costume decorator to suppers debug messages from the PIL function to suppress PIl debug logging - DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13 :param func: :return: """ @wraps(func) def wrap(*args, **kwargs): log_level = logging.getLogger().getEffectiveLevel() logging.getLogger().setLevel(logging.INFO) with warnings.catch_warnings(): warnings.simplefilter("ignore") response = func(*args, **kwargs) logging.getLogger().setLevel(log_level) return response return wrap
[ "def", "io_image_decorate", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "log_level", "=", "logging", ".", "getLogger", "(", ")", ".", "getEffectiveLevel", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "INFO", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "response", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "log_level", ")", "return", "response", "return", "wrap" ]
https://github.com/Borda/pyImSegm/blob/7584b40a8d5bba04d3bf46f540f22b5d923e4b03/imsegm/utilities/data_io.py#L295-L314
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/admin/management/commands/resolve-check.py
python
Command.add_arguments
(self, parser)
Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command.
Add arguments to the command.
[ "Add", "arguments", "to", "the", "command", "." ]
def add_arguments(self, parser): """Add arguments to the command. Args: parser (argparse.ArgumentParser): The argument parser for the command. """ parser.add_argument( 'check_name', metavar='NAME', help=_('The name of the check to resolve.'))
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'check_name'", ",", "metavar", "=", "'NAME'", ",", "help", "=", "_", "(", "'The name of the check to resolve.'", ")", ")" ]
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/admin/management/commands/resolve-check.py#L16-L26
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/mail/mail.py
python
FileMonitoringService._setupMonitor
(self)
Schedule the next monitoring call.
Schedule the next monitoring call.
[ "Schedule", "the", "next", "monitoring", "call", "." ]
def _setupMonitor(self): """ Schedule the next monitoring call. """ from twisted.internet import reactor t, self.index = self.intervals.next() self._call = reactor.callLater(t, self._monitor)
[ "def", "_setupMonitor", "(", "self", ")", ":", "from", "twisted", ".", "internet", "import", "reactor", "t", ",", "self", ".", "index", "=", "self", ".", "intervals", ".", "next", "(", ")", "self", ".", "_call", "=", "reactor", ".", "callLater", "(", "t", ",", "self", ".", "_monitor", ")" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/mail.py#L640-L647
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
managerClientTemplate/lib/client/watchdog.py
python
ConnectionWatchdog.run
(self)
Connection watchdog loop that checks the communication channel to the server. :return:
Connection watchdog loop that checks the communication channel to the server. :return:
[ "Connection", "watchdog", "loop", "that", "checks", "the", "communication", "channel", "to", "the", "server", ".", ":", "return", ":" ]
def run(self): """ Connection watchdog loop that checks the communication channel to the server. :return: """ # check every 5 seconds if the client is still connected # and the time of the last received data # from the server lies too far in the past while True: # wait 5 seconds before checking time of last received data for i in range(5): if self._exit_flag: logging.info("[%s]: Exiting Connection Watchdog." % self._log_tag) return time.sleep(1) utc_timestamp = int(time.time()) # Connect to server if communication channel is not connected anymore. if not self._connection.is_connected: logging.error("[%s]: Connection to server has died. " % self._log_tag) # Reconnect to the server. while True: # Check if 5 unsuccessful attempts are made to connect # to the server and if smtp alert is activated # => send eMail alert if self._smtp_alert is not None and (self._connection_retries % 5) == 0: self._smtp_alert.sendCommunicationAlert(self._connection_retries) # try to connect to the server if self._connection.reconnect(): # if smtp alert is activated # => send email that communication problems are solved if self._smtp_alert is not None: self._smtp_alert.sendCommunicationAlertClear() logging.info("[%s] Reconnecting successful after %d attempts." % (self._log_tag, self._connection_retries)) self._connection_retries = 1 break self._connection_retries += 1 logging.error("[%s]: Reconnecting failed. Retrying in 5 seconds." % self._log_tag) time.sleep(5) # Check if the time of the data last received lies too far in the # past => send ping to check connection elif (utc_timestamp - self._connection.last_communication) > self._ping_interval: logging.debug("[%s]: Ping interval exceeded." % self._log_tag) # check if PING failed promise = self._connection.send_ping() # type: Promise # Wait for ping response to finish (in a non-blocking way since otherwise we could # get a deadlock in which we do not re-connect to the server anymore). is_finished = False for _ in range(self._ping_delay_warning): if promise.is_finished(blocking=False): is_finished = True break time.sleep(1) if is_finished: if not promise.was_successful(): logging.error("[%s]: Connection to server has died." % self._log_tag) else: logging.warning("[%s]: Stopped waiting for ping response after %d seconds." % (self._log_tag, self._ping_delay_warning))
[ "def", "run", "(", "self", ")", ":", "# check every 5 seconds if the client is still connected", "# and the time of the last received data", "# from the server lies too far in the past", "while", "True", ":", "# wait 5 seconds before checking time of last received data", "for", "i", "in", "range", "(", "5", ")", ":", "if", "self", ".", "_exit_flag", ":", "logging", ".", "info", "(", "\"[%s]: Exiting Connection Watchdog.\"", "%", "self", ".", "_log_tag", ")", "return", "time", ".", "sleep", "(", "1", ")", "utc_timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "# Connect to server if communication channel is not connected anymore.", "if", "not", "self", ".", "_connection", ".", "is_connected", ":", "logging", ".", "error", "(", "\"[%s]: Connection to server has died. \"", "%", "self", ".", "_log_tag", ")", "# Reconnect to the server.", "while", "True", ":", "# Check if 5 unsuccessful attempts are made to connect", "# to the server and if smtp alert is activated", "# => send eMail alert", "if", "self", ".", "_smtp_alert", "is", "not", "None", "and", "(", "self", ".", "_connection_retries", "%", "5", ")", "==", "0", ":", "self", ".", "_smtp_alert", ".", "sendCommunicationAlert", "(", "self", ".", "_connection_retries", ")", "# try to connect to the server", "if", "self", ".", "_connection", ".", "reconnect", "(", ")", ":", "# if smtp alert is activated", "# => send email that communication problems are solved", "if", "self", ".", "_smtp_alert", "is", "not", "None", ":", "self", ".", "_smtp_alert", ".", "sendCommunicationAlertClear", "(", ")", "logging", ".", "info", "(", "\"[%s] Reconnecting successful after %d attempts.\"", "%", "(", "self", ".", "_log_tag", ",", "self", ".", "_connection_retries", ")", ")", "self", ".", "_connection_retries", "=", "1", "break", "self", ".", "_connection_retries", "+=", "1", "logging", ".", "error", "(", "\"[%s]: Reconnecting failed. Retrying in 5 seconds.\"", "%", "self", ".", "_log_tag", ")", "time", ".", "sleep", "(", "5", ")", "# Check if the time of the data last received lies too far in the", "# past => send ping to check connection", "elif", "(", "utc_timestamp", "-", "self", ".", "_connection", ".", "last_communication", ")", ">", "self", ".", "_ping_interval", ":", "logging", ".", "debug", "(", "\"[%s]: Ping interval exceeded.\"", "%", "self", ".", "_log_tag", ")", "# check if PING failed", "promise", "=", "self", ".", "_connection", ".", "send_ping", "(", ")", "# type: Promise", "# Wait for ping response to finish (in a non-blocking way since otherwise we could", "# get a deadlock in which we do not re-connect to the server anymore).", "is_finished", "=", "False", "for", "_", "in", "range", "(", "self", ".", "_ping_delay_warning", ")", ":", "if", "promise", ".", "is_finished", "(", "blocking", "=", "False", ")", ":", "is_finished", "=", "True", "break", "time", ".", "sleep", "(", "1", ")", "if", "is_finished", ":", "if", "not", "promise", ".", "was_successful", "(", ")", ":", "logging", ".", "error", "(", "\"[%s]: Connection to server has died.\"", "%", "self", ".", "_log_tag", ")", "else", ":", "logging", ".", "warning", "(", "\"[%s]: Stopped waiting for ping response after %d seconds.\"", "%", "(", "self", ".", "_log_tag", ",", "self", ".", "_ping_delay_warning", ")", ")" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/managerClientTemplate/lib/client/watchdog.py#L52-L127
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/pathlib.py
python
Path.read_bytes
(self)
Open the file in bytes mode, read it, and close the file.
Open the file in bytes mode, read it, and close the file.
[ "Open", "the", "file", "in", "bytes", "mode", "read", "it", "and", "close", "the", "file", "." ]
def read_bytes(self): """ Open the file in bytes mode, read it, and close the file. """ with self.open(mode='rb') as f: return f.read()
[ "def", "read_bytes", "(", "self", ")", ":", "with", "self", ".", "open", "(", "mode", "=", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/pathlib.py#L1153-L1158
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python3-alpha/python-libs/pyxmpp2/ext/disco.py
python
register_disco_cache_fetchers
(cache_suite,stream)
Register Service Discovery cache fetchers into given cache suite and using the stream provided. :Parameters: - `cache_suite`: the cache suite where the fetchers are to be registered. - `stream`: the stream to be used by the fetchers. :Types: - `cache_suite`: `cache.CacheSuite` - `stream`: `pyxmpp.stream.Stream`
Register Service Discovery cache fetchers into given cache suite and using the stream provided.
[ "Register", "Service", "Discovery", "cache", "fetchers", "into", "given", "cache", "suite", "and", "using", "the", "stream", "provided", "." ]
def register_disco_cache_fetchers(cache_suite,stream): """Register Service Discovery cache fetchers into given cache suite and using the stream provided. :Parameters: - `cache_suite`: the cache suite where the fetchers are to be registered. - `stream`: the stream to be used by the fetchers. :Types: - `cache_suite`: `cache.CacheSuite` - `stream`: `pyxmpp.stream.Stream` """ tmp=stream class DiscoInfoCacheFetcher(DiscoCacheFetcherBase): """Cache fetcher for DiscoInfo.""" stream=tmp disco_class=DiscoInfo class DiscoItemsCacheFetcher(DiscoCacheFetcherBase): """Cache fetcher for DiscoItems.""" stream=tmp disco_class=DiscoItems cache_suite.register_fetcher(DiscoInfo,DiscoInfoCacheFetcher) cache_suite.register_fetcher(DiscoItems,DiscoItemsCacheFetcher)
[ "def", "register_disco_cache_fetchers", "(", "cache_suite", ",", "stream", ")", ":", "tmp", "=", "stream", "class", "DiscoInfoCacheFetcher", "(", "DiscoCacheFetcherBase", ")", ":", "\"\"\"Cache fetcher for DiscoInfo.\"\"\"", "stream", "=", "tmp", "disco_class", "=", "DiscoInfo", "class", "DiscoItemsCacheFetcher", "(", "DiscoCacheFetcherBase", ")", ":", "\"\"\"Cache fetcher for DiscoItems.\"\"\"", "stream", "=", "tmp", "disco_class", "=", "DiscoItems", "cache_suite", ".", "register_fetcher", "(", "DiscoInfo", ",", "DiscoInfoCacheFetcher", ")", "cache_suite", ".", "register_fetcher", "(", "DiscoItems", ",", "DiscoItemsCacheFetcher", ")" ]
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python3-alpha/python-libs/pyxmpp2/ext/disco.py#L867-L889
tooxie/shiva-server
4d169aae8d4cb01133f62701b14610695e48c297
shiva/utils.py
python
MetadataManager.__init__
(self, filepath)
[]
def __init__(self, filepath): self._original_path = filepath try: self.reader = mutagen.File(filepath, easy=True) except Exception, e: raise MetadataManagerReadError(e.message)
[ "def", "__init__", "(", "self", ",", "filepath", ")", ":", "self", ".", "_original_path", "=", "filepath", "try", ":", "self", ".", "reader", "=", "mutagen", ".", "File", "(", "filepath", ",", "easy", "=", "True", ")", "except", "Exception", ",", "e", ":", "raise", "MetadataManagerReadError", "(", "e", ".", "message", ")" ]
https://github.com/tooxie/shiva-server/blob/4d169aae8d4cb01133f62701b14610695e48c297/shiva/utils.py#L110-L115
ceteri/exelixi
81bb97d3e99fe055e3816a5692b4dc29cdce6c94
src/resource.py
python
MesosScheduler.stop_framework
(driver)
ensure that the driver process terminates
ensure that the driver process terminates
[ "ensure", "that", "the", "driver", "process", "terminates" ]
def stop_framework (driver): """ensure that the driver process terminates""" status = 0 if driver.run() == mesos_pb2.DRIVER_STOPPED else 1 driver.stop(); sys.exit(status)
[ "def", "stop_framework", "(", "driver", ")", ":", "status", "=", "0", "if", "driver", ".", "run", "(", ")", "==", "mesos_pb2", ".", "DRIVER_STOPPED", "else", "1", "driver", ".", "stop", "(", ")", "sys", ".", "exit", "(", "status", ")" ]
https://github.com/ceteri/exelixi/blob/81bb97d3e99fe055e3816a5692b4dc29cdce6c94/src/resource.py#L261-L265
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/docutils/parsers/rst/states.py
python
Body.explicit_markup
(self, match, context, next_state)
return [], next_state, []
Footnotes, hyperlink targets, directives, comments.
Footnotes, hyperlink targets, directives, comments.
[ "Footnotes", "hyperlink", "targets", "directives", "comments", "." ]
def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, []
[ "def", "explicit_markup", "(", "self", ",", "match", ",", "context", ",", "next_state", ")", ":", "nodelist", ",", "blank_finish", "=", "self", ".", "explicit_construct", "(", "match", ")", "self", ".", "parent", "+=", "nodelist", "self", ".", "explicit_list", "(", "blank_finish", ")", "return", "[", "]", ",", "next_state", ",", "[", "]" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/docutils/parsers/rst/states.py#L2324-L2329
mypaint/mypaint
90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33
lib/layer/tree.py
python
path_startswith
(path, prefix)
return True
Returns whether one path starts with another :param tuple path: Path to be tested :param tuple prefix: Prefix path to be tested against >>> path_startswith((1,2,3), (1,2)) True >>> path_startswith((1,2,3), (1,2,3,4)) False >>> path_startswith((1,2,3), (1,0)) False
Returns whether one path starts with another
[ "Returns", "whether", "one", "path", "starts", "with", "another" ]
def path_startswith(path, prefix): """Returns whether one path starts with another :param tuple path: Path to be tested :param tuple prefix: Prefix path to be tested against >>> path_startswith((1,2,3), (1,2)) True >>> path_startswith((1,2,3), (1,2,3,4)) False >>> path_startswith((1,2,3), (1,0)) False """ if len(prefix) > len(path): return False for i in xrange(len(prefix)): if path[i] != prefix[i]: return False return True
[ "def", "path_startswith", "(", "path", ",", "prefix", ")", ":", "if", "len", "(", "prefix", ")", ">", "len", "(", "path", ")", ":", "return", "False", "for", "i", "in", "xrange", "(", "len", "(", "prefix", ")", ")", ":", "if", "path", "[", "i", "]", "!=", "prefix", "[", "i", "]", ":", "return", "False", "return", "True" ]
https://github.com/mypaint/mypaint/blob/90b36dbc7b8bd2f323383f7edf608a5e0a3a1a33/lib/layer/tree.py#L2731-L2749
owid/covid-19-data
936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92
scripts/src/cowidev/oxcgrt/etl.py
python
OxCGRTETL.extract
(self)
return pd.read_csv(self.source_url, low_memory=False)
[]
def extract(self): return pd.read_csv(self.source_url, low_memory=False)
[ "def", "extract", "(", "self", ")", ":", "return", "pd", ".", "read_csv", "(", "self", ".", "source_url", ",", "low_memory", "=", "False", ")" ]
https://github.com/owid/covid-19-data/blob/936aeae6cfbdc0163939ed7bd8ecdbb2582c0a92/scripts/src/cowidev/oxcgrt/etl.py#L8-L9
wxGlade/wxGlade
44ed0d1cba78f27c5c0a56918112a737653b7b27
widgets/datepicker_ctrl/datepicker_ctrl.py
python
initialize
()
return common.make_object_button('EditDatePickerCtrl', 'datepicker_ctrl.png')
initialization function for the module: returns a wxBitmapButton to be added to the main palette
initialization function for the module: returns a wxBitmapButton to be added to the main palette
[ "initialization", "function", "for", "the", "module", ":", "returns", "a", "wxBitmapButton", "to", "be", "added", "to", "the", "main", "palette" ]
def initialize(): "initialization function for the module: returns a wxBitmapButton to be added to the main palette" common.widget_classes['EditDatePickerCtrl'] = EditDatePickerCtrl common.widgets['EditDatePickerCtrl'] = builder common.widgets_from_xml['EditDatePickerCtrl'] = xml_builder return common.make_object_button('EditDatePickerCtrl', 'datepicker_ctrl.png')
[ "def", "initialize", "(", ")", ":", "common", ".", "widget_classes", "[", "'EditDatePickerCtrl'", "]", "=", "EditDatePickerCtrl", "common", ".", "widgets", "[", "'EditDatePickerCtrl'", "]", "=", "builder", "common", ".", "widgets_from_xml", "[", "'EditDatePickerCtrl'", "]", "=", "xml_builder", "return", "common", ".", "make_object_button", "(", "'EditDatePickerCtrl'", ",", "'datepicker_ctrl.png'", ")" ]
https://github.com/wxGlade/wxGlade/blob/44ed0d1cba78f27c5c0a56918112a737653b7b27/widgets/datepicker_ctrl/datepicker_ctrl.py#L68-L74
dongdonghy/Detection-PyTorch-Notebook
b0c4745150cf019fef2fe661dfe16cc25dd81645
chapter4/faster-rcnn-pytorch/lib/datasets/imdb.py
python
imdb.competition_mode
(self, on)
Turn competition mode on or off.
Turn competition mode on or off.
[ "Turn", "competition", "mode", "on", "or", "off", "." ]
def competition_mode(self, on): """Turn competition mode on or off.""" pass
[ "def", "competition_mode", "(", "self", ",", "on", ")", ":", "pass" ]
https://github.com/dongdonghy/Detection-PyTorch-Notebook/blob/b0c4745150cf019fef2fe661dfe16cc25dd81645/chapter4/faster-rcnn-pytorch/lib/datasets/imdb.py#L263-L265
quantumlib/Cirq
89f88b01d69222d3f1ec14d649b7b3a85ed9211f
cirq-google/cirq_google/devices/serializable_device.py
python
_GateDefinition.with_can_serialize_predicate
( self, can_serialize_predicate: Callable[[cirq.Operation], bool] )
return _GateDefinition( self.duration, self.target_set, self.number_of_qubits, self.is_permutation, can_serialize_predicate, )
Creates a new _GateDefinition as a copy of the existing definition but with a new with_can_serialize_predicate. This is useful if multiple definitions exist for the same gate, but with different conditions. An example is if gates at certain angles of a gate take longer or are not allowed.
Creates a new _GateDefinition as a copy of the existing definition but with a new with_can_serialize_predicate. This is useful if multiple definitions exist for the same gate, but with different conditions.
[ "Creates", "a", "new", "_GateDefinition", "as", "a", "copy", "of", "the", "existing", "definition", "but", "with", "a", "new", "with_can_serialize_predicate", ".", "This", "is", "useful", "if", "multiple", "definitions", "exist", "for", "the", "same", "gate", "but", "with", "different", "conditions", "." ]
def with_can_serialize_predicate( self, can_serialize_predicate: Callable[[cirq.Operation], bool] ) -> '_GateDefinition': """Creates a new _GateDefinition as a copy of the existing definition but with a new with_can_serialize_predicate. This is useful if multiple definitions exist for the same gate, but with different conditions. An example is if gates at certain angles of a gate take longer or are not allowed. """ return _GateDefinition( self.duration, self.target_set, self.number_of_qubits, self.is_permutation, can_serialize_predicate, )
[ "def", "with_can_serialize_predicate", "(", "self", ",", "can_serialize_predicate", ":", "Callable", "[", "[", "cirq", ".", "Operation", "]", ",", "bool", "]", ")", "->", "'_GateDefinition'", ":", "return", "_GateDefinition", "(", "self", ".", "duration", ",", "self", ".", "target_set", ",", "self", ".", "number_of_qubits", ",", "self", ".", "is_permutation", ",", "can_serialize_predicate", ",", ")" ]
https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-google/cirq_google/devices/serializable_device.py#L55-L71
jwyang/graph-rcnn.pytorch
0f294ecb86d5f130e82ee85246b6afd5180240e5
lib/utils/pytorch_misc.py
python
accuracy
(output, target, topk=(1,))
return res
Computes the precision@k for the specified values of k
Computes the precision
[ "Computes", "the", "precision" ]
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "[", "]", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "view", "(", "-", "1", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ")", "res", ".", "append", "(", "correct_k", ".", "mul_", "(", "100.0", "/", "batch_size", ")", ")", "return", "res" ]
https://github.com/jwyang/graph-rcnn.pytorch/blob/0f294ecb86d5f130e82ee85246b6afd5180240e5/lib/utils/pytorch_misc.py#L206-L219
wger-project/wger
3a17a2cf133d242d1f8c357faa53cf675a7b3223
wger/gallery/views/images.py
python
ImageUpdateView.get_success_url
(self)
return reverse('gallery:images:overview')
Return to overview
Return to overview
[ "Return", "to", "overview" ]
def get_success_url(self): """ Return to overview """ return reverse('gallery:images:overview')
[ "def", "get_success_url", "(", "self", ")", ":", "return", "reverse", "(", "'gallery:images:overview'", ")" ]
https://github.com/wger-project/wger/blob/3a17a2cf133d242d1f8c357faa53cf675a7b3223/wger/gallery/views/images.py#L100-L104
flexxui/flexx
69b85b308b505a8621305458a5094f2a6addd720
flexx/ui/pywidgets/_filebrowser.py
python
FileBrowserWidget.set_path
(self, dirname=None)
Set the current path. If an invalid directory is given, the path is not changed. The given path can be absolute, or relative to the current path.
Set the current path. If an invalid directory is given, the path is not changed. The given path can be absolute, or relative to the current path.
[ "Set", "the", "current", "path", ".", "If", "an", "invalid", "directory", "is", "given", "the", "path", "is", "not", "changed", ".", "The", "given", "path", "can", "be", "absolute", "or", "relative", "to", "the", "current", "path", "." ]
def set_path(self, dirname=None): """ Set the current path. If an invalid directory is given, the path is not changed. The given path can be absolute, or relative to the current path. """ if dirname is None or not isinstance(dirname, str): dirname = "~" if dirname.startswith("~"): dirname = os.path.expanduser(dirname) if not os.path.isabs(dirname): dirname = os.path.abspath(os.path.join(self.path, dirname)) # Set if valid, otherwise default to home dir if os.path.isdir(dirname): self._mutate("path", dirname) elif not self.path: self._mutate("path", os.path.expanduser("~"))
[ "def", "set_path", "(", "self", ",", "dirname", "=", "None", ")", ":", "if", "dirname", "is", "None", "or", "not", "isinstance", "(", "dirname", ",", "str", ")", ":", "dirname", "=", "\"~\"", "if", "dirname", ".", "startswith", "(", "\"~\"", ")", ":", "dirname", "=", "os", ".", "path", ".", "expanduser", "(", "dirname", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "dirname", ")", ":", "dirname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "dirname", ")", ")", "# Set if valid, otherwise default to home dir", "if", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "self", ".", "_mutate", "(", "\"path\"", ",", "dirname", ")", "elif", "not", "self", ".", "path", ":", "self", ".", "_mutate", "(", "\"path\"", ",", "os", ".", "path", ".", "expanduser", "(", "\"~\"", ")", ")" ]
https://github.com/flexxui/flexx/blob/69b85b308b505a8621305458a5094f2a6addd720/flexx/ui/pywidgets/_filebrowser.py#L117-L132
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/channels/ai_channel.py
python
AIChannel.ai_excit_idle_output_behavior
(self)
[]
def ai_excit_idle_output_behavior(self): cfunc = lib_importer.windll.DAQmxResetAIExcitIdleOutputBehavior if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str] error_code = cfunc( self._handle, self._name) check_for_error(error_code)
[ "def", "ai_excit_idle_output_behavior", "(", "self", ")", ":", "cfunc", "=", "lib_importer", ".", "windll", ".", "DAQmxResetAIExcitIdleOutputBehavior", "if", "cfunc", ".", "argtypes", "is", "None", ":", "with", "cfunc", ".", "arglock", ":", "if", "cfunc", ".", "argtypes", "is", "None", ":", "cfunc", ".", "argtypes", "=", "[", "lib_importer", ".", "task_handle", ",", "ctypes_byte_str", "]", "error_code", "=", "cfunc", "(", "self", ".", "_handle", ",", "self", ".", "_name", ")", "check_for_error", "(", "error_code", ")" ]
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/channels/ai_channel.py#L3833-L3843
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/tarfile.py
python
TarInfo.create_gnu_header
(self, info, encoding, errors)
return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
Return the object as a GNU header block sequence.
Return the object as a GNU header block sequence.
[ "Return", "the", "object", "as", "a", "GNU", "header", "block", "sequence", "." ]
def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"].encode(encoding, errors)) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding, errors) if len(info["name"].encode(encoding, errors)) > LENGTH_NAME: buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME, encoding, errors) return buf + self._create_header(info, GNU_FORMAT, encoding, errors)
[ "def", "create_gnu_header", "(", "self", ",", "info", ",", "encoding", ",", "errors", ")", ":", "info", "[", "\"magic\"", "]", "=", "GNU_MAGIC", "buf", "=", "b\"\"", "if", "len", "(", "info", "[", "\"linkname\"", "]", ".", "encode", "(", "encoding", ",", "errors", ")", ")", ">", "LENGTH_LINK", ":", "buf", "+=", "self", ".", "_create_gnu_long_header", "(", "info", "[", "\"linkname\"", "]", ",", "GNUTYPE_LONGLINK", ",", "encoding", ",", "errors", ")", "if", "len", "(", "info", "[", "\"name\"", "]", ".", "encode", "(", "encoding", ",", "errors", ")", ")", ">", "LENGTH_NAME", ":", "buf", "+=", "self", ".", "_create_gnu_long_header", "(", "info", "[", "\"name\"", "]", ",", "GNUTYPE_LONGNAME", ",", "encoding", ",", "errors", ")", "return", "buf", "+", "self", ".", "_create_header", "(", "info", ",", "GNU_FORMAT", ",", "encoding", ",", "errors", ")" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/tarfile.py#L835-L847
uhlik/bpy
698faa76b614904f4d29586ac10ed1234bd99dca
system_time_tracker.py
python
TIME_TRACKER_OT_clear_data.execute
(self, context)
return {'FINISHED'}
[]
def execute(self, context): prefs = Utils.get_preferences() p = prefs.csv_path with open(p, mode='w', encoding='utf-8') as f: f.write("{0}\n".format(prefs.csv_first_line)) return {'FINISHED'}
[ "def", "execute", "(", "self", ",", "context", ")", ":", "prefs", "=", "Utils", ".", "get_preferences", "(", ")", "p", "=", "prefs", ".", "csv_path", "with", "open", "(", "p", ",", "mode", "=", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "\"{0}\\n\"", ".", "format", "(", "prefs", ".", "csv_first_line", ")", ")", "return", "{", "'FINISHED'", "}" ]
https://github.com/uhlik/bpy/blob/698faa76b614904f4d29586ac10ed1234bd99dca/system_time_tracker.py#L351-L357
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/networkx/algorithms/bipartite/centrality.py
python
degree_centrality
(G, nodes)
return centrality
r"""Compute the degree centrality for nodes in a bipartite network. The degree centrality for a node `v` is the fraction of nodes connected to it. Parameters ---------- G : graph A bipartite network nodes : list or container Container with all nodes in one bipartite node set. Returns ------- centrality : dictionary Dictionary keyed by node with bipartite degree centrality as the value. See Also -------- betweenness_centrality, closeness_centrality, sets, is_bipartite Notes ----- The nodes input parameter must conatin all nodes in one bipartite node set, but the dictionary returned contains all nodes from both bipartite node sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree (which is `n-1` where `n` is the number of nodes in G). In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the opposite node set [1]_. The degree centrality for a node `v` in the bipartite sets `U` with `n` nodes and `V` with `m` nodes is .. math:: d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U , d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V , where `deg(v)` is the degree of node `v`. References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. http://www.steveborgatti.com/research/publications/bhaffiliations.pdf
r"""Compute the degree centrality for nodes in a bipartite network.
[ "r", "Compute", "the", "degree", "centrality", "for", "nodes", "in", "a", "bipartite", "network", "." ]
def degree_centrality(G, nodes): r"""Compute the degree centrality for nodes in a bipartite network. The degree centrality for a node `v` is the fraction of nodes connected to it. Parameters ---------- G : graph A bipartite network nodes : list or container Container with all nodes in one bipartite node set. Returns ------- centrality : dictionary Dictionary keyed by node with bipartite degree centrality as the value. See Also -------- betweenness_centrality, closeness_centrality, sets, is_bipartite Notes ----- The nodes input parameter must conatin all nodes in one bipartite node set, but the dictionary returned contains all nodes from both bipartite node sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree (which is `n-1` where `n` is the number of nodes in G). In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the opposite node set [1]_. The degree centrality for a node `v` in the bipartite sets `U` with `n` nodes and `V` with `m` nodes is .. math:: d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U , d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V , where `deg(v)` is the degree of node `v`. References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. http://www.steveborgatti.com/research/publications/bhaffiliations.pdf """ top = set(nodes) bottom = set(G) - top s = 1.0 / len(bottom) centrality = dict((n, d * s) for n, d in G.degree(top)) s = 1.0 / len(top) centrality.update(dict((n, d * s) for n, d in G.degree(bottom))) return centrality
[ "def", "degree_centrality", "(", "G", ",", "nodes", ")", ":", "top", "=", "set", "(", "nodes", ")", "bottom", "=", "set", "(", "G", ")", "-", "top", "s", "=", "1.0", "/", "len", "(", "bottom", ")", "centrality", "=", "dict", "(", "(", "n", ",", "d", "*", "s", ")", "for", "n", ",", "d", "in", "G", ".", "degree", "(", "top", ")", ")", "s", "=", "1.0", "/", "len", "(", "top", ")", "centrality", ".", "update", "(", "dict", "(", "(", "n", ",", "d", "*", "s", ")", "for", "n", ",", "d", "in", "G", ".", "degree", "(", "bottom", ")", ")", ")", "return", "centrality" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/networkx/algorithms/bipartite/centrality.py#L15-L79
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/smtplib.py
python
SMTP.auth_plain
(self, challenge=None)
return "\0%s\0%s" % (self.user, self.password)
Authobject to use with PLAIN authentication. Requires self.user and self.password to be set.
Authobject to use with PLAIN authentication. Requires self.user and self.password to be set.
[ "Authobject", "to", "use", "with", "PLAIN", "authentication", ".", "Requires", "self", ".", "user", "and", "self", ".", "password", "to", "be", "set", "." ]
def auth_plain(self, challenge=None): """ Authobject to use with PLAIN authentication. Requires self.user and self.password to be set.""" return "\0%s\0%s" % (self.user, self.password)
[ "def", "auth_plain", "(", "self", ",", "challenge", "=", "None", ")", ":", "return", "\"\\0%s\\0%s\"", "%", "(", "self", ".", "user", ",", "self", ".", "password", ")" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/smtplib.py#L653-L656
lad1337/XDM
0c1b7009fe00f06f102a6f67c793478f515e7efe
site-packages/pylint/gui.py
python
BasicStream.fix_contents
(self)
finalize what the contents of the dict should look like before output
finalize what the contents of the dict should look like before output
[ "finalize", "what", "the", "contents", "of", "the", "dict", "should", "look", "like", "before", "output" ]
def fix_contents(self): """finalize what the contents of the dict should look like before output""" for item in self.outdict: numEmpty = self.outdict[item].count('') for i in xrange(numEmpty): self.outdict[item].remove('') if self.outdict[item]: self.outdict[item].pop(0)
[ "def", "fix_contents", "(", "self", ")", ":", "for", "item", "in", "self", ".", "outdict", ":", "numEmpty", "=", "self", ".", "outdict", "[", "item", "]", ".", "count", "(", "''", ")", "for", "i", "in", "xrange", "(", "numEmpty", ")", ":", "self", ".", "outdict", "[", "item", "]", ".", "remove", "(", "''", ")", "if", "self", ".", "outdict", "[", "item", "]", ":", "self", ".", "outdict", "[", "item", "]", ".", "pop", "(", "0", ")" ]
https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/pylint/gui.py#L85-L92
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/glfw.py
python
get_key
(window, key)
return _glfw.glfwGetKey(window, key)
Returns the last reported state of a keyboard key for the specified window. Wrapper for: int glfwGetKey(GLFWwindow* window, int key);
Returns the last reported state of a keyboard key for the specified window.
[ "Returns", "the", "last", "reported", "state", "of", "a", "keyboard", "key", "for", "the", "specified", "window", "." ]
def get_key(window, key): ''' Returns the last reported state of a keyboard key for the specified window. Wrapper for: int glfwGetKey(GLFWwindow* window, int key); ''' return _glfw.glfwGetKey(window, key)
[ "def", "get_key", "(", "window", ",", "key", ")", ":", "return", "_glfw", ".", "glfwGetKey", "(", "window", ",", "key", ")" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/glfw.py#L1256-L1264
danmacnish/cartoonify
39ea84d96b3e93f0480e6d6158bea506d01278ca
cartoonify/app/object_detection/core/losses.py
python
WeightedSoftmaxClassificationLoss.__init__
(self, anchorwise_output=False, logit_scale=1.0)
Constructor. Args: anchorwise_output: Whether to output loss per anchor (default False) logit_scale: When this value is high, the prediction is "diffused" and when this value is low, the prediction is made peakier. (default 1.0)
Constructor.
[ "Constructor", "." ]
def __init__(self, anchorwise_output=False, logit_scale=1.0): """Constructor. Args: anchorwise_output: Whether to output loss per anchor (default False) logit_scale: When this value is high, the prediction is "diffused" and when this value is low, the prediction is made peakier. (default 1.0) """ self._anchorwise_output = anchorwise_output self._logit_scale = logit_scale
[ "def", "__init__", "(", "self", ",", "anchorwise_output", "=", "False", ",", "logit_scale", "=", "1.0", ")", ":", "self", ".", "_anchorwise_output", "=", "anchorwise_output", "self", ".", "_logit_scale", "=", "logit_scale" ]
https://github.com/danmacnish/cartoonify/blob/39ea84d96b3e93f0480e6d6158bea506d01278ca/cartoonify/app/object_detection/core/losses.py#L308-L319
ProgVal/Limnoria
181e34baf90a8cabc281e8349da6e36e1e558608
src/ircdb.py
python
IrcUser.clearAuth
(self)
Unsets a user's authenticated hostmask.
Unsets a user's authenticated hostmask.
[ "Unsets", "a", "user", "s", "authenticated", "hostmask", "." ]
def clearAuth(self): """Unsets a user's authenticated hostmask.""" for (when, hostmask) in self.auth: users.invalidateCache(hostmask=hostmask) self.auth = []
[ "def", "clearAuth", "(", "self", ")", ":", "for", "(", "when", ",", "hostmask", ")", "in", "self", ".", "auth", ":", "users", ".", "invalidateCache", "(", "hostmask", "=", "hostmask", ")", "self", ".", "auth", "=", "[", "]" ]
https://github.com/ProgVal/Limnoria/blob/181e34baf90a8cabc281e8349da6e36e1e558608/src/ircdb.py#L350-L354
google/ipaddr-py
99e55513666db1276596d74f24863e056ca50851
ipaddr.py
python
_BaseV4.is_private
(self)
return (self in IPv4Network('10.0.0.0/8') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.168.0.0/16'))
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918.
Test if this address is allocated for private networks.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918. """ return (self in IPv4Network('10.0.0.0/8') or self in IPv4Network('172.16.0.0/12') or self in IPv4Network('192.168.0.0/16'))
[ "def", "is_private", "(", "self", ")", ":", "return", "(", "self", "in", "IPv4Network", "(", "'10.0.0.0/8'", ")", "or", "self", "in", "IPv4Network", "(", "'172.16.0.0/12'", ")", "or", "self", "in", "IPv4Network", "(", "'192.168.0.0/16'", ")", ")" ]
https://github.com/google/ipaddr-py/blob/99e55513666db1276596d74f24863e056ca50851/ipaddr.py#L1191-L1200
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/_pydecimal.py
python
Decimal.logb
(self, context=None)
return ans._fix(context)
Returns the exponent of the magnitude of self's MSD. The result is the integer which is the exponent of the magnitude of the most significant digit of self (as though it were truncated to a single digit while maintaining the value of that digit and without limiting the resulting exponent).
Returns the exponent of the magnitude of self's MSD.
[ "Returns", "the", "exponent", "of", "the", "magnitude", "of", "self", "s", "MSD", "." ]
def logb(self, context=None): """ Returns the exponent of the magnitude of self's MSD. The result is the integer which is the exponent of the magnitude of the most significant digit of self (as though it were truncated to a single digit while maintaining the value of that digit and without limiting the resulting exponent). """ # logb(NaN) = NaN ans = self._check_nans(context=context) if ans: return ans if context is None: context = getcontext() # logb(+/-Inf) = +Inf if self._isinfinity(): return _Infinity # logb(0) = -Inf, DivisionByZero if not self: return context._raise_error(DivisionByZero, 'logb(0)', 1) # otherwise, simply return the adjusted exponent of self, as a # Decimal. Note that no attempt is made to fit the result # into the current context. ans = Decimal(self.adjusted()) return ans._fix(context)
[ "def", "logb", "(", "self", ",", "context", "=", "None", ")", ":", "# logb(NaN) = NaN", "ans", "=", "self", ".", "_check_nans", "(", "context", "=", "context", ")", "if", "ans", ":", "return", "ans", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "# logb(+/-Inf) = +Inf", "if", "self", ".", "_isinfinity", "(", ")", ":", "return", "_Infinity", "# logb(0) = -Inf, DivisionByZero", "if", "not", "self", ":", "return", "context", ".", "_raise_error", "(", "DivisionByZero", ",", "'logb(0)'", ",", "1", ")", "# otherwise, simply return the adjusted exponent of self, as a", "# Decimal. Note that no attempt is made to fit the result", "# into the current context.", "ans", "=", "Decimal", "(", "self", ".", "adjusted", "(", ")", ")", "return", "ans", ".", "_fix", "(", "context", ")" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/_pydecimal.py#L3319-L3347
mlcommons/ck
558a22c5970eb0d6708d0edc080e62a92566bab0
incubator/cbench/cbench/solution.py
python
publish_result
(i)
return {'return':0}
Input: { uid [str] - portal identifier of the solution } Output: { return [int] - return code = 0 if success or >0 if error (error) [str] - error string if return>0 }
Input: { uid [str] - portal identifier of the solution }
[ "Input", ":", "{", "uid", "[", "str", "]", "-", "portal", "identifier", "of", "the", "solution", "}" ]
def publish_result(i): """ Input: { uid [str] - portal identifier of the solution } Output: { return [int] - return code = 0 if success or >0 if error (error) [str] - error string if return>0 } """ # Get main configuration r=config.load({}) if r['return']>0: return r cfg=r.get('dict',{}) pcfg=r.get('path','') xcmd=i.get('cmd','') if xcmd==None: xcmd='' xcmd=xcmd.strip() cur_dir=os.getcwd() # Check if Windows or Linux # Get platform info r=get_platform_desc(i) # Pass input from init if r['return']>0: return r hos=r['host_os_uid'] hosx=r['host_os_uoa'] hosd=r['host_os_dict'] hosd_extra=r['host_desc'] tos=r['os_uid'] tosx=r['os_uoa'] tosd=r['os_dict'] # Load entry with the solution uid=i['uid'] r=ck.access({'action':'load', 'module_uoa':config.CR_MODULE_UOA, 'data_uoa':uid}) if r['return']>0: return r solution_uoa=r['data_uoa'] solution_uid=r['data_uid'] p=r['path'] dd=r['dict'] # TBD: need to be checked from outside ... host_os=dd.get('host_os','') tos=dd.get('target_os','') tdid=dd.get('device_id','') workflow=dd.get('workflow','') workflow_cmd=dd.get('workflow_cmd','') workflow_cmd_extra=dd.get('workflow_cmd_extra','') workflow_input_dir=dd.get('workflow_input_dir','') workflow_output_dir=dd.get('workflow_output_dir','') result_file=dd.get('result_file','') graphs=dd.get('graphs',[]) ############################################################## ck.out(config.CR_LINE) ck.out('Find path to output file '+result_file+' ...') ck.out('') encoding=locale.getdefaultlocale()[1] cmd0=hosd['change_dir']+' '+hosd['env_quotes_if_space']+p+hosd['env_quotes_if_space']+'\n' cmd0+=hosd['env_set']+' CK_REPOS='+hosd['env_quotes_if_space']+os.path.join(p, 'CK')+hosd['env_quotes_if_space']+'\n' cmd0+=hosd['env_call']+' '+hosd['env_quotes_if_space']+os.path.join(p, 'venv', hosd_extra['venv_bin'], hosd_extra['venv_activate'])+hosd['env_quotes_if_space']+'\n' cmd=cmd0 cmd+='ck find '+workflow+'\n' ii={'action':'shell', 'module_uoa':'os', 'cmd':cmd, 'encoding':encoding} r=ck.access(ii) if r['return']>0: status=-1 return r path_result=r['stdout'].strip() path_result_file=os.path.join(path_result, result_file) ck.out(' Found path: '+path_result_file) # ############################################################## # ck.out(config.CR_LINE) # ck.out('Detecting complete platform info ...') # pinfo=os.path.join(p, 'platform-info.json') # if os.path.isfile(pinfo): os.remove(pinfo) # cmd=cmd0 # # Need to do it from virtual env since it's the correct way for Android devices which may require specific files (adb) # s='ck detect platform' # if i.get('target_os','')!='': s+=' --target_os='+i['target_os'] # if tdid!='': s+=' --device_id='+tdid # s+=' --out=json_file --out_file='+pinfo # cmd+=s+'\n' # ii['cmd']=cmd # r=ck.access(ii) # if r['return']>0: return r # if not os.path.isfile(pinfo): # return {'return':1, 'error':'platform info file was not created'} # # Get some sub-info about deps and platforms # dinfo={} # if os.path.isfile(pinfo): # r=ck.load_json_file({'json_file':pinfo}) # if r['return']==0: # dinfo=r['dict'].get('features',{}) # for k in ['cpu_misc', 'cpu']: # if k in dinfo: del(dinfo[k]) # pdeps=os.path.join(p, 'resolved-deps.json') # ddeps={} # if os.path.isfile(pdeps): # r=ck.load_json_file({'json_file':pdeps}) # if r['return']==0: # ddeps2=r['dict'] # r=deps_summary({'deps':ddeps2}) # if r['return']==0: # ddeps=r['deps_summary'] ############################################################## # status management path_tmpSol=os.path.join(p, "tmp") tmp_solStatus=os.path.join(path_tmpSol, "status.json") status = 0 if not os.path.isdir(path_tmpSol): os.mkdir(path_tmpSol) rdf_st={} rx=ck.load_json_file({'json_file':tmp_solStatus}) if rx['return']>0: rx=ck.save_json_to_file({'json_file':tmp_solStatus, 'dict':{'status': 0}}) return rx rdf_st=rx['dict'] status = rdf_st.get('status','') if status == 2: ############################################################## ck.out(config.CR_LINE) ck.out('Reading output: '+path_result_file) ck.out('') if not os.path.isfile(path_result_file): ck.out(' Error: output file not found!') rdf_st['status'] = -2 rx=ck.save_json_to_file({'json_file':tmp_solStatus, 'dict':rdf_st}) if rx['return']>0: return rx else: rx=ck.load_json_file({'json_file':path_result_file}) if rx['return']>0: return rx crdf=rx['dict'] ################################################################ if len(graphs)>0: ck.out(config.CR_LINE) ck.out('Pushing results to graphs...') rx=ck.gen_tmp_file({'prefix':'tmp-result-', 'suffix':'.json'}) if rx['return']>0: return rx fn=rx['file_name'] rx=ck.save_json_to_file({'json_file':fn, 'dict':crdf}) if rx['return']>0: return rx if solution_uoa not in graphs: graphs.append(solution_uoa) for gr in graphs: ck.out('') ck.out(' * Graph: '+gr) ck.out('') rx=graph.push({'uid':gr, 'version':'1.0.0', 'filename':fn}) if rx['return']>0: return rx rdf_st['status'] = 3 rx=ck.save_json_to_file({'json_file':tmp_solStatus, 'dict':rdf_st}) if rx['return']>0: return rx # Clean temp data file if os.path.isfile(fn): os.remove(fn) ################################################################ pconv=os.path.join(p, 'graph-convertor.json') if os.path.isfile(pconv): rx=ck.load_json_file({'json_file':pconv}) if rx['return']==0: ck.out(config.CR_LINE) ck.out('Converting data for extra graphs ...') dconv=rx['dict'] for eg in dconv: gr=eg['graph_id'] ck.out('') ck.out(' * Graph: '+gr) keys=eg['keys'] cdata={} for k in keys: ok=k['out_key'] kk=[k.get('key1',''), k.get('key2',''), k.get('key3',''), k.get('key4','')] vv='' v=k.get('value','') if v!='' and v!=None: vv=v first=True for kx in kk: if kx!='': if kx.startswith('##'): ry=ck.get_by_flat_key({'dict':crdf, 'key':kx}) if ry['return']>0: return ry v=ry['value'] else: v=crdf.get(kx) vm=k.get('multiply',0) if vm!=0 and vm!='' and vm!=None and (type(v)==float or type(v)==int): v=v*vm if v!='' and v!=None: if first: first=False if type(v)==float or type(v)==int: vv=0 else: vv+=', ' vv+=v if vv!='': cdata[ok]=vv rx=ck.gen_tmp_file({'prefix':'tmp-result-', 'suffix':'.json'}) if rx['return']>0: return rx fn=rx['file_name'] rx=ck.save_json_to_file({'json_file':fn, 'dict':cdata}) if rx['return']>0: return rx ck.out('') rx=graph.push({'uid':gr, 'version':'1.0.0', 'filename':fn}) if rx['return']>0: return rx # Clean temp data file if os.path.isfile(fn): os.remove(fn) return r return {'return':0}
[ "def", "publish_result", "(", "i", ")", ":", "# Get main configuration", "r", "=", "config", ".", "load", "(", "{", "}", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "return", "r", "cfg", "=", "r", ".", "get", "(", "'dict'", ",", "{", "}", ")", "pcfg", "=", "r", ".", "get", "(", "'path'", ",", "''", ")", "xcmd", "=", "i", ".", "get", "(", "'cmd'", ",", "''", ")", "if", "xcmd", "==", "None", ":", "xcmd", "=", "''", "xcmd", "=", "xcmd", ".", "strip", "(", ")", "cur_dir", "=", "os", ".", "getcwd", "(", ")", "# Check if Windows or Linux", "# Get platform info ", "r", "=", "get_platform_desc", "(", "i", ")", "# Pass input from init", "if", "r", "[", "'return'", "]", ">", "0", ":", "return", "r", "hos", "=", "r", "[", "'host_os_uid'", "]", "hosx", "=", "r", "[", "'host_os_uoa'", "]", "hosd", "=", "r", "[", "'host_os_dict'", "]", "hosd_extra", "=", "r", "[", "'host_desc'", "]", "tos", "=", "r", "[", "'os_uid'", "]", "tosx", "=", "r", "[", "'os_uoa'", "]", "tosd", "=", "r", "[", "'os_dict'", "]", "# Load entry with the solution", "uid", "=", "i", "[", "'uid'", "]", "r", "=", "ck", ".", "access", "(", "{", "'action'", ":", "'load'", ",", "'module_uoa'", ":", "config", ".", "CR_MODULE_UOA", ",", "'data_uoa'", ":", "uid", "}", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "return", "r", "solution_uoa", "=", "r", "[", "'data_uoa'", "]", "solution_uid", "=", "r", "[", "'data_uid'", "]", "p", "=", "r", "[", "'path'", "]", "dd", "=", "r", "[", "'dict'", "]", "# TBD: need to be checked from outside ...", "host_os", "=", "dd", ".", "get", "(", "'host_os'", ",", "''", ")", "tos", "=", "dd", ".", "get", "(", "'target_os'", ",", "''", ")", "tdid", "=", "dd", ".", "get", "(", "'device_id'", ",", "''", ")", "workflow", "=", "dd", ".", "get", "(", "'workflow'", ",", "''", ")", "workflow_cmd", "=", "dd", ".", "get", "(", "'workflow_cmd'", ",", "''", ")", "workflow_cmd_extra", "=", "dd", ".", "get", "(", "'workflow_cmd_extra'", ",", "''", ")", "workflow_input_dir", "=", "dd", ".", "get", "(", "'workflow_input_dir'", ",", "''", ")", "workflow_output_dir", "=", "dd", ".", "get", "(", "'workflow_output_dir'", ",", "''", ")", "result_file", "=", "dd", ".", "get", "(", "'result_file'", ",", "''", ")", "graphs", "=", "dd", ".", "get", "(", "'graphs'", ",", "[", "]", ")", "##############################################################", "ck", ".", "out", "(", "config", ".", "CR_LINE", ")", "ck", ".", "out", "(", "'Find path to output file '", "+", "result_file", "+", "' ...'", ")", "ck", ".", "out", "(", "''", ")", "encoding", "=", "locale", ".", "getdefaultlocale", "(", ")", "[", "1", "]", "cmd0", "=", "hosd", "[", "'change_dir'", "]", "+", "' '", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "p", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "'\\n'", "cmd0", "+=", "hosd", "[", "'env_set'", "]", "+", "' CK_REPOS='", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "os", ".", "path", ".", "join", "(", "p", ",", "'CK'", ")", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "'\\n'", "cmd0", "+=", "hosd", "[", "'env_call'", "]", "+", "' '", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "os", ".", "path", ".", "join", "(", "p", ",", "'venv'", ",", "hosd_extra", "[", "'venv_bin'", "]", ",", "hosd_extra", "[", "'venv_activate'", "]", ")", "+", "hosd", "[", "'env_quotes_if_space'", "]", "+", "'\\n'", "cmd", "=", "cmd0", "cmd", "+=", "'ck find '", "+", "workflow", "+", "'\\n'", "ii", "=", "{", "'action'", ":", "'shell'", ",", "'module_uoa'", ":", "'os'", ",", "'cmd'", ":", "cmd", ",", "'encoding'", ":", "encoding", "}", "r", "=", "ck", ".", "access", "(", "ii", ")", "if", "r", "[", "'return'", "]", ">", "0", ":", "status", "=", "-", "1", "return", "r", "path_result", "=", "r", "[", "'stdout'", "]", ".", "strip", "(", ")", "path_result_file", "=", "os", ".", "path", ".", "join", "(", "path_result", ",", "result_file", ")", "ck", ".", "out", "(", "' Found path: '", "+", "path_result_file", ")", "# ##############################################################", "# ck.out(config.CR_LINE)", "# ck.out('Detecting complete platform info ...')", "# pinfo=os.path.join(p, 'platform-info.json')", "# if os.path.isfile(pinfo): os.remove(pinfo)", "# cmd=cmd0", "# # Need to do it from virtual env since it's the correct way for Android devices which may require specific files (adb)", "# s='ck detect platform'", "# if i.get('target_os','')!='': s+=' --target_os='+i['target_os']", "# if tdid!='': s+=' --device_id='+tdid", "# s+=' --out=json_file --out_file='+pinfo", "# cmd+=s+'\\n'", "# ii['cmd']=cmd", "# r=ck.access(ii)", "# if r['return']>0: return r", "# if not os.path.isfile(pinfo):", "# return {'return':1, 'error':'platform info file was not created'}", "# # Get some sub-info about deps and platforms", "# dinfo={}", "# if os.path.isfile(pinfo):", "# r=ck.load_json_file({'json_file':pinfo})", "# if r['return']==0:", "# dinfo=r['dict'].get('features',{})", "# for k in ['cpu_misc', 'cpu']:", "# if k in dinfo: del(dinfo[k])", "# pdeps=os.path.join(p, 'resolved-deps.json')", "# ddeps={}", "# if os.path.isfile(pdeps):", "# r=ck.load_json_file({'json_file':pdeps})", "# if r['return']==0:", "# ddeps2=r['dict']", "# r=deps_summary({'deps':ddeps2})", "# if r['return']==0:", "# ddeps=r['deps_summary']", "##############################################################", "# status management", "path_tmpSol", "=", "os", ".", "path", ".", "join", "(", "p", ",", "\"tmp\"", ")", "tmp_solStatus", "=", "os", ".", "path", ".", "join", "(", "path_tmpSol", ",", "\"status.json\"", ")", "status", "=", "0", "if", "not", "os", ".", "path", ".", "isdir", "(", "path_tmpSol", ")", ":", "os", ".", "mkdir", "(", "path_tmpSol", ")", "rdf_st", "=", "{", "}", "rx", "=", "ck", ".", "load_json_file", "(", "{", "'json_file'", ":", "tmp_solStatus", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "rx", "=", "ck", ".", "save_json_to_file", "(", "{", "'json_file'", ":", "tmp_solStatus", ",", "'dict'", ":", "{", "'status'", ":", "0", "}", "}", ")", "return", "rx", "rdf_st", "=", "rx", "[", "'dict'", "]", "status", "=", "rdf_st", ".", "get", "(", "'status'", ",", "''", ")", "if", "status", "==", "2", ":", "##############################################################", "ck", ".", "out", "(", "config", ".", "CR_LINE", ")", "ck", ".", "out", "(", "'Reading output: '", "+", "path_result_file", ")", "ck", ".", "out", "(", "''", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path_result_file", ")", ":", "ck", ".", "out", "(", "' Error: output file not found!'", ")", "rdf_st", "[", "'status'", "]", "=", "-", "2", "rx", "=", "ck", ".", "save_json_to_file", "(", "{", "'json_file'", ":", "tmp_solStatus", ",", "'dict'", ":", "rdf_st", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "else", ":", "rx", "=", "ck", ".", "load_json_file", "(", "{", "'json_file'", ":", "path_result_file", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "crdf", "=", "rx", "[", "'dict'", "]", "################################################################", "if", "len", "(", "graphs", ")", ">", "0", ":", "ck", ".", "out", "(", "config", ".", "CR_LINE", ")", "ck", ".", "out", "(", "'Pushing results to graphs...'", ")", "rx", "=", "ck", ".", "gen_tmp_file", "(", "{", "'prefix'", ":", "'tmp-result-'", ",", "'suffix'", ":", "'.json'", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "fn", "=", "rx", "[", "'file_name'", "]", "rx", "=", "ck", ".", "save_json_to_file", "(", "{", "'json_file'", ":", "fn", ",", "'dict'", ":", "crdf", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "if", "solution_uoa", "not", "in", "graphs", ":", "graphs", ".", "append", "(", "solution_uoa", ")", "for", "gr", "in", "graphs", ":", "ck", ".", "out", "(", "''", ")", "ck", ".", "out", "(", "' * Graph: '", "+", "gr", ")", "ck", ".", "out", "(", "''", ")", "rx", "=", "graph", ".", "push", "(", "{", "'uid'", ":", "gr", ",", "'version'", ":", "'1.0.0'", ",", "'filename'", ":", "fn", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "rdf_st", "[", "'status'", "]", "=", "3", "rx", "=", "ck", ".", "save_json_to_file", "(", "{", "'json_file'", ":", "tmp_solStatus", ",", "'dict'", ":", "rdf_st", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "# Clean temp data file", "if", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "os", ".", "remove", "(", "fn", ")", "################################################################", "pconv", "=", "os", ".", "path", ".", "join", "(", "p", ",", "'graph-convertor.json'", ")", "if", "os", ".", "path", ".", "isfile", "(", "pconv", ")", ":", "rx", "=", "ck", ".", "load_json_file", "(", "{", "'json_file'", ":", "pconv", "}", ")", "if", "rx", "[", "'return'", "]", "==", "0", ":", "ck", ".", "out", "(", "config", ".", "CR_LINE", ")", "ck", ".", "out", "(", "'Converting data for extra graphs ...'", ")", "dconv", "=", "rx", "[", "'dict'", "]", "for", "eg", "in", "dconv", ":", "gr", "=", "eg", "[", "'graph_id'", "]", "ck", ".", "out", "(", "''", ")", "ck", ".", "out", "(", "' * Graph: '", "+", "gr", ")", "keys", "=", "eg", "[", "'keys'", "]", "cdata", "=", "{", "}", "for", "k", "in", "keys", ":", "ok", "=", "k", "[", "'out_key'", "]", "kk", "=", "[", "k", ".", "get", "(", "'key1'", ",", "''", ")", ",", "k", ".", "get", "(", "'key2'", ",", "''", ")", ",", "k", ".", "get", "(", "'key3'", ",", "''", ")", ",", "k", ".", "get", "(", "'key4'", ",", "''", ")", "]", "vv", "=", "''", "v", "=", "k", ".", "get", "(", "'value'", ",", "''", ")", "if", "v", "!=", "''", "and", "v", "!=", "None", ":", "vv", "=", "v", "first", "=", "True", "for", "kx", "in", "kk", ":", "if", "kx", "!=", "''", ":", "if", "kx", ".", "startswith", "(", "'##'", ")", ":", "ry", "=", "ck", ".", "get_by_flat_key", "(", "{", "'dict'", ":", "crdf", ",", "'key'", ":", "kx", "}", ")", "if", "ry", "[", "'return'", "]", ">", "0", ":", "return", "ry", "v", "=", "ry", "[", "'value'", "]", "else", ":", "v", "=", "crdf", ".", "get", "(", "kx", ")", "vm", "=", "k", ".", "get", "(", "'multiply'", ",", "0", ")", "if", "vm", "!=", "0", "and", "vm", "!=", "''", "and", "vm", "!=", "None", "and", "(", "type", "(", "v", ")", "==", "float", "or", "type", "(", "v", ")", "==", "int", ")", ":", "v", "=", "v", "*", "vm", "if", "v", "!=", "''", "and", "v", "!=", "None", ":", "if", "first", ":", "first", "=", "False", "if", "type", "(", "v", ")", "==", "float", "or", "type", "(", "v", ")", "==", "int", ":", "vv", "=", "0", "else", ":", "vv", "+=", "', '", "vv", "+=", "v", "if", "vv", "!=", "''", ":", "cdata", "[", "ok", "]", "=", "vv", "rx", "=", "ck", ".", "gen_tmp_file", "(", "{", "'prefix'", ":", "'tmp-result-'", ",", "'suffix'", ":", "'.json'", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "fn", "=", "rx", "[", "'file_name'", "]", "rx", "=", "ck", ".", "save_json_to_file", "(", "{", "'json_file'", ":", "fn", ",", "'dict'", ":", "cdata", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "ck", ".", "out", "(", "''", ")", "rx", "=", "graph", ".", "push", "(", "{", "'uid'", ":", "gr", ",", "'version'", ":", "'1.0.0'", ",", "'filename'", ":", "fn", "}", ")", "if", "rx", "[", "'return'", "]", ">", "0", ":", "return", "rx", "# Clean temp data file", "if", "os", ".", "path", ".", "isfile", "(", "fn", ")", ":", "os", ".", "remove", "(", "fn", ")", "return", "r", "return", "{", "'return'", ":", "0", "}" ]
https://github.com/mlcommons/ck/blob/558a22c5970eb0d6708d0edc080e62a92566bab0/incubator/cbench/cbench/solution.py#L1586-L1865
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/perceiver/modeling_perceiver.py
python
PerceiverMultimodalDecoder.__init__
( self, config, modalities, num_outputs, output_num_channels, min_padding_size=2, subsampled_index_dims=None, **decoder_kwargs )
[]
def __init__( self, config, modalities, num_outputs, output_num_channels, min_padding_size=2, subsampled_index_dims=None, **decoder_kwargs ): super().__init__() self.modalities = nn.ModuleDict(modalities) self.subsampled_index_dims = subsampled_index_dims self.min_padding_size = min_padding_size self.output_num_channels = output_num_channels self.num_outputs = num_outputs self.decoder = PerceiverBasicDecoder( config, output_index_dims=(num_outputs,), output_num_channels=output_num_channels, position_encoding_type="none", num_channels=self.num_query_channels, **decoder_kwargs, ) self.padding = nn.ParameterDict( { modality: nn.Parameter(torch.randn(1, self.num_query_channels - decoder.num_query_channels)) for modality, decoder in modalities.items() } )
[ "def", "__init__", "(", "self", ",", "config", ",", "modalities", ",", "num_outputs", ",", "output_num_channels", ",", "min_padding_size", "=", "2", ",", "subsampled_index_dims", "=", "None", ",", "*", "*", "decoder_kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "modalities", "=", "nn", ".", "ModuleDict", "(", "modalities", ")", "self", ".", "subsampled_index_dims", "=", "subsampled_index_dims", "self", ".", "min_padding_size", "=", "min_padding_size", "self", ".", "output_num_channels", "=", "output_num_channels", "self", ".", "num_outputs", "=", "num_outputs", "self", ".", "decoder", "=", "PerceiverBasicDecoder", "(", "config", ",", "output_index_dims", "=", "(", "num_outputs", ",", ")", ",", "output_num_channels", "=", "output_num_channels", ",", "position_encoding_type", "=", "\"none\"", ",", "num_channels", "=", "self", ".", "num_query_channels", ",", "*", "*", "decoder_kwargs", ",", ")", "self", ".", "padding", "=", "nn", ".", "ParameterDict", "(", "{", "modality", ":", "nn", ".", "Parameter", "(", "torch", ".", "randn", "(", "1", ",", "self", ".", "num_query_channels", "-", "decoder", ".", "num_query_channels", ")", ")", "for", "modality", ",", "decoder", "in", "modalities", ".", "items", "(", ")", "}", ")" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/perceiver/modeling_perceiver.py#L2383-L2412
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/_internal/graphy/common.py
python
BaseChart.GetDependentAxes
(self)
return self._axes[AxisPosition.LEFT] + self._axes[AxisPosition.RIGHT]
Return any dependent axes ('left' and 'right' by default for LineCharts, although bar charts would use 'bottom' and 'top').
Return any dependent axes ('left' and 'right' by default for LineCharts, although bar charts would use 'bottom' and 'top').
[ "Return", "any", "dependent", "axes", "(", "left", "and", "right", "by", "default", "for", "LineCharts", "although", "bar", "charts", "would", "use", "bottom", "and", "top", ")", "." ]
def GetDependentAxes(self): """Return any dependent axes ('left' and 'right' by default for LineCharts, although bar charts would use 'bottom' and 'top'). """ return self._axes[AxisPosition.LEFT] + self._axes[AxisPosition.RIGHT]
[ "def", "GetDependentAxes", "(", "self", ")", ":", "return", "self", ".", "_axes", "[", "AxisPosition", ".", "LEFT", "]", "+", "self", ".", "_axes", "[", "AxisPosition", ".", "RIGHT", "]" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/_internal/graphy/common.py#L254-L258
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/locative/__init__.py
python
_validate_test_mode
(obj: dict)
return obj
Validate that id is provided outside of test mode.
Validate that id is provided outside of test mode.
[ "Validate", "that", "id", "is", "provided", "outside", "of", "test", "mode", "." ]
def _validate_test_mode(obj: dict) -> dict: """Validate that id is provided outside of test mode.""" if ATTR_ID not in obj and obj[ATTR_TRIGGER] != "test": raise vol.Invalid("Location id not specified") return obj
[ "def", "_validate_test_mode", "(", "obj", ":", "dict", ")", "->", "dict", ":", "if", "ATTR_ID", "not", "in", "obj", "and", "obj", "[", "ATTR_TRIGGER", "]", "!=", "\"test\"", ":", "raise", "vol", ".", "Invalid", "(", "\"Location id not specified\"", ")", "return", "obj" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/locative/__init__.py#L42-L46
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/autopilot/v1/assistant/task/task_statistics.py
python
TaskStatisticsContext.fetch
(self)
return TaskStatisticsInstance( self._version, payload, assistant_sid=self._solution['assistant_sid'], task_sid=self._solution['task_sid'], )
Fetch the TaskStatisticsInstance :returns: The fetched TaskStatisticsInstance :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance
Fetch the TaskStatisticsInstance
[ "Fetch", "the", "TaskStatisticsInstance" ]
def fetch(self): """ Fetch the TaskStatisticsInstance :returns: The fetched TaskStatisticsInstance :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsInstance """ payload = self._version.fetch(method='GET', uri=self._uri, ) return TaskStatisticsInstance( self._version, payload, assistant_sid=self._solution['assistant_sid'], task_sid=self._solution['task_sid'], )
[ "def", "fetch", "(", "self", ")", ":", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "method", "=", "'GET'", ",", "uri", "=", "self", ".", "_uri", ",", ")", "return", "TaskStatisticsInstance", "(", "self", ".", "_version", ",", "payload", ",", "assistant_sid", "=", "self", ".", "_solution", "[", "'assistant_sid'", "]", ",", "task_sid", "=", "self", ".", "_solution", "[", "'task_sid'", "]", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/autopilot/v1/assistant/task/task_statistics.py#L144-L158
pypiserver/pypiserver
bdbd839a1bbd5bdc20088074b4372531dabd5136
pypiserver/bottle.py
python
BaseRequest.script_name
(self)
return '/' + script_name + '/' if script_name else '/'
The initial portion of the URL's `path` that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes.
The initial portion of the URL's `path` that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes.
[ "The", "initial", "portion", "of", "the", "URL", "s", "path", "that", "was", "removed", "by", "a", "higher", "level", "(", "server", "or", "routing", "middleware", ")", "before", "the", "application", "was", "called", ".", "This", "script", "path", "is", "returned", "with", "leading", "and", "tailing", "slashes", "." ]
def script_name(self): ''' The initial portion of the URL's `path` that was removed by a higher level (server or routing middleware) before the application was called. This script path is returned with leading and tailing slashes. ''' script_name = self.environ.get('SCRIPT_NAME', '').strip('/') return '/' + script_name + '/' if script_name else '/'
[ "def", "script_name", "(", "self", ")", ":", "script_name", "=", "self", ".", "environ", ".", "get", "(", "'SCRIPT_NAME'", ",", "''", ")", ".", "strip", "(", "'/'", ")", "return", "'/'", "+", "script_name", "+", "'/'", "if", "script_name", "else", "'/'" ]
https://github.com/pypiserver/pypiserver/blob/bdbd839a1bbd5bdc20088074b4372531dabd5136/pypiserver/bottle.py#L1287-L1293
enthought/chaco
0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f
chaco/tools/line_segment_tool.py
python
LineSegmentTool.normal_key_pressed
(self, event)
Handles the user pressing a key in the 'normal' state. If the user presses the Enter key, the tool is reset.
Handles the user pressing a key in the 'normal' state.
[ "Handles", "the", "user", "pressing", "a", "key", "in", "the", "normal", "state", "." ]
def normal_key_pressed(self, event): """Handles the user pressing a key in the 'normal' state. If the user presses the Enter key, the tool is reset. """ if event.character == "Enter": self._finalize_selection() self.reset()
[ "def", "normal_key_pressed", "(", "self", ",", "event", ")", ":", "if", "event", ".", "character", "==", "\"Enter\"", ":", "self", ".", "_finalize_selection", "(", ")", "self", ".", "reset", "(", ")" ]
https://github.com/enthought/chaco/blob/0907d1dedd07a499202efbaf2fe2a4e51b4c8e5f/chaco/tools/line_segment_tool.py#L218-L225
williballenthin/python-registry
11e857623469dd28ed14519a08d2db7c8228ca0c
samples/reg_export.py
python
reg_format_value_dword
(value)
return "dword:%08x" % (value.value())
@rtype: str
[]
def reg_format_value_dword(value): """ @rtype: str """ return "dword:%08x" % (value.value())
[ "def", "reg_format_value_dword", "(", "value", ")", ":", "return", "\"dword:%08x\"", "%", "(", "value", ".", "value", "(", ")", ")" ]
https://github.com/williballenthin/python-registry/blob/11e857623469dd28ed14519a08d2db7c8228ca0c/samples/reg_export.py#L48-L52
ehForwarderBot/efb-wechat-slave
36a94c5e5f2fe5dc7247448cf37d5e8b653e8990
efb_wechat_slave/vendor/wxpy/api/bot.py
python
Bot.enable_puid
(self, path='wxpy_puid.pkl', puid_logs=None)
return self.puid_map
**可选操作:** 启用聊天对象的 :any:`puid <Chat.puid>` 属性:: # 启用 puid 属性,并指定 puid 所需的映射数据保存/载入路径 bot.enable_puid('wxpy_puid.pkl') # 指定一个好友 my_friend = bot.friends().search('游否')[0] # 查看他的 puid print(my_friend.puid) # 'edfe8468' .. tip:: | :any:`puid <Chat.puid>` 是 **wxpy 特有的聊天对象/用户ID** | 不同于其他 ID 属性,**puid** 可始终被获取到,且具有稳定的唯一性 :param path: puid 所需的映射数据保存/载入路径 :param puid_logs: PUID log path
**可选操作:** 启用聊天对象的 :any:`puid <Chat.puid>` 属性::
[ "**", "可选操作", ":", "**", "启用聊天对象的", ":", "any", ":", "puid", "<Chat", ".", "puid", ">", "属性", "::" ]
def enable_puid(self, path='wxpy_puid.pkl', puid_logs=None): """ **可选操作:** 启用聊天对象的 :any:`puid <Chat.puid>` 属性:: # 启用 puid 属性,并指定 puid 所需的映射数据保存/载入路径 bot.enable_puid('wxpy_puid.pkl') # 指定一个好友 my_friend = bot.friends().search('游否')[0] # 查看他的 puid print(my_friend.puid) # 'edfe8468' .. tip:: | :any:`puid <Chat.puid>` 是 **wxpy 特有的聊天对象/用户ID** | 不同于其他 ID 属性,**puid** 可始终被获取到,且具有稳定的唯一性 :param path: puid 所需的映射数据保存/载入路径 :param puid_logs: PUID log path """ self.puid_map = PuidMap(path, puid_logs) return self.puid_map
[ "def", "enable_puid", "(", "self", ",", "path", "=", "'wxpy_puid.pkl'", ",", "puid_logs", "=", "None", ")", ":", "self", ".", "puid_map", "=", "PuidMap", "(", "path", ",", "puid_logs", ")", "return", "self", ".", "puid_map" ]
https://github.com/ehForwarderBot/efb-wechat-slave/blob/36a94c5e5f2fe5dc7247448cf37d5e8b653e8990/efb_wechat_slave/vendor/wxpy/api/bot.py#L158-L182
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/apis/core_v1_api.py
python
CoreV1Api.replace_persistent_volume_status
(self, name, body, **kwargs)
replace status of the specified PersistentVolume This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.replace_persistent_volume_status(name, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: name of the PersistentVolume (required) :param V1PersistentVolume body: (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1PersistentVolume If the method is called asynchronously, returns the request thread.
replace status of the specified PersistentVolume This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.replace_persistent_volume_status(name, body, callback=callback_function)
[ "replace", "status", "of", "the", "specified", "PersistentVolume", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "be", "invoked", "when", "receiving", "the", "response", ".", ">>>", "def", "callback_function", "(", "response", ")", ":", ">>>", "pprint", "(", "response", ")", ">>>", ">>>", "thread", "=", "api", ".", "replace_persistent_volume_status", "(", "name", "body", "callback", "=", "callback_function", ")" ]
def replace_persistent_volume_status(self, name, body, **kwargs): """ replace status of the specified PersistentVolume This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.replace_persistent_volume_status(name, body, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str name: name of the PersistentVolume (required) :param V1PersistentVolume body: (required) :param str pretty: If 'true', then the output is pretty printed. :return: V1PersistentVolume If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.replace_persistent_volume_status_with_http_info(name, body, **kwargs) else: (data) = self.replace_persistent_volume_status_with_http_info(name, body, **kwargs) return data
[ "def", "replace_persistent_volume_status", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "replace_persistent_volume_status_with_http_info", "(", "name", ",", "body", ",", "*", "*", "kwargs", ")", "else", ":", "(", "data", ")", "=", "self", ".", "replace_persistent_volume_status_with_http_info", "(", "name", ",", "body", ",", "*", "*", "kwargs", ")", "return", "data" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/apis/core_v1_api.py#L28910-L28935
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/search/search.py
python
Document._CheckRank
(self, rank)
return _CheckInteger(rank, 'rank', upper_bound=sys.maxint)
Checks if rank is valid, then returns it.
Checks if rank is valid, then returns it.
[ "Checks", "if", "rank", "is", "valid", "then", "returns", "it", "." ]
def _CheckRank(self, rank): """Checks if rank is valid, then returns it.""" return _CheckInteger(rank, 'rank', upper_bound=sys.maxint)
[ "def", "_CheckRank", "(", "self", ",", "rank", ")", ":", "return", "_CheckInteger", "(", "rank", ",", "'rank'", ",", "upper_bound", "=", "sys", ".", "maxint", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/api/search/search.py#L1927-L1929
inguma/bokken
6109dd0025093a11631cb88cf48cb5c5ed5e617d
lib/web/db.py
python
reparam
(string_, dictionary)
return SQLQuery.join(result, '')
Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns an `SQLQuery` for the result. >>> reparam("s = $s", dict(s=True)) <sql: "s = 't'"> >>> reparam("s IN $s", dict(s=[1, 2])) <sql: 's IN (1, 2)'>
Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns an `SQLQuery` for the result.
[ "Takes", "a", "string", "and", "a", "dictionary", "and", "interpolates", "the", "string", "using", "values", "from", "the", "dictionary", ".", "Returns", "an", "SQLQuery", "for", "the", "result", "." ]
def reparam(string_, dictionary): """ Takes a string and a dictionary and interpolates the string using values from the dictionary. Returns an `SQLQuery` for the result. >>> reparam("s = $s", dict(s=True)) <sql: "s = 't'"> >>> reparam("s IN $s", dict(s=[1, 2])) <sql: 's IN (1, 2)'> """ dictionary = dictionary.copy() # eval mucks with it vals = [] result = [] for live, chunk in _interpolate(string_): if live: v = eval(chunk, dictionary) result.append(sqlquote(v)) else: result.append(chunk) return SQLQuery.join(result, '')
[ "def", "reparam", "(", "string_", ",", "dictionary", ")", ":", "dictionary", "=", "dictionary", ".", "copy", "(", ")", "# eval mucks with it", "vals", "=", "[", "]", "result", "=", "[", "]", "for", "live", ",", "chunk", "in", "_interpolate", "(", "string_", ")", ":", "if", "live", ":", "v", "=", "eval", "(", "chunk", ",", "dictionary", ")", "result", ".", "append", "(", "sqlquote", "(", "v", ")", ")", "else", ":", "result", ".", "append", "(", "chunk", ")", "return", "SQLQuery", ".", "join", "(", "result", ",", "''", ")" ]
https://github.com/inguma/bokken/blob/6109dd0025093a11631cb88cf48cb5c5ed5e617d/lib/web/db.py#L288-L307
ThilinaRajapakse/simpletransformers
9323c0398baea0157044e080617b2c4be59de7a9
simpletransformers/retrieval/retrieval_utils.py
python
mean_reciprocal_rank_at_k
(rs, k)
return np.mean([1.0 / (r[0] + 1) if r.size else 0.0 for r in rs])
Adapted from https://gist.github.com/bwhite/3726239 Score is reciprocal of the rank of the first relevant item First element is 'rank 1'. Relevance is binary (nonzero is relevant). Example from http://en.wikipedia.org/wiki/Mean_reciprocal_rank Args: rs: Iterator of relevance scores (list or numpy) in rank order (first element is the first item) Returns: Mean reciprocal rank
Adapted from https://gist.github.com/bwhite/3726239
[ "Adapted", "from", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "bwhite", "/", "3726239" ]
def mean_reciprocal_rank_at_k(rs, k): """ Adapted from https://gist.github.com/bwhite/3726239 Score is reciprocal of the rank of the first relevant item First element is 'rank 1'. Relevance is binary (nonzero is relevant). Example from http://en.wikipedia.org/wiki/Mean_reciprocal_rank Args: rs: Iterator of relevance scores (list or numpy) in rank order (first element is the first item) Returns: Mean reciprocal rank """ rs = rs[:, :k] rs = (np.asarray(r).nonzero()[0] for r in rs) return np.mean([1.0 / (r[0] + 1) if r.size else 0.0 for r in rs])
[ "def", "mean_reciprocal_rank_at_k", "(", "rs", ",", "k", ")", ":", "rs", "=", "rs", "[", ":", ",", ":", "k", "]", "rs", "=", "(", "np", ".", "asarray", "(", "r", ")", ".", "nonzero", "(", ")", "[", "0", "]", "for", "r", "in", "rs", ")", "return", "np", ".", "mean", "(", "[", "1.0", "/", "(", "r", "[", "0", "]", "+", "1", ")", "if", "r", ".", "size", "else", "0.0", "for", "r", "in", "rs", "]", ")" ]
https://github.com/ThilinaRajapakse/simpletransformers/blob/9323c0398baea0157044e080617b2c4be59de7a9/simpletransformers/retrieval/retrieval_utils.py#L635-L651
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/idlelib/format.py
python
FormatRegion.set_region
(self, head, tail, chars, lines)
Replace the text between the given indices. Args: head: Starting index of text to replace. tail: Ending index of text to replace. chars: Expected to be string of current text between head and tail. lines: List of new lines to insert between head and tail.
Replace the text between the given indices.
[ "Replace", "the", "text", "between", "the", "given", "indices", "." ]
def set_region(self, head, tail, chars, lines): """Replace the text between the given indices. Args: head: Starting index of text to replace. tail: Ending index of text to replace. chars: Expected to be string of current text between head and tail. lines: List of new lines to insert between head and tail. """ text = self.editwin.text newchars = "\n".join(lines) if newchars == chars: text.bell() return text.tag_remove("sel", "1.0", "end") text.mark_set("insert", head) text.undo_block_start() text.delete(head, tail) text.insert(head, newchars) text.undo_block_stop() text.tag_add("sel", head, "insert")
[ "def", "set_region", "(", "self", ",", "head", ",", "tail", ",", "chars", ",", "lines", ")", ":", "text", "=", "self", ".", "editwin", ".", "text", "newchars", "=", "\"\\n\"", ".", "join", "(", "lines", ")", "if", "newchars", "==", "chars", ":", "text", ".", "bell", "(", ")", "return", "text", ".", "tag_remove", "(", "\"sel\"", ",", "\"1.0\"", ",", "\"end\"", ")", "text", ".", "mark_set", "(", "\"insert\"", ",", "head", ")", "text", ".", "undo_block_start", "(", ")", "text", ".", "delete", "(", "head", ",", "tail", ")", "text", ".", "insert", "(", "head", ",", "newchars", ")", "text", ".", "undo_block_stop", "(", ")", "text", ".", "tag_add", "(", "\"sel\"", ",", "head", ",", "\"insert\"", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/idlelib/format.py#L240-L262
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/urllib.py
python
proxy_bypass_environment
(host, proxies=None)
return 0
Test if proxies should not be used for a particular host. Checks the proxies dict for the value of no_proxy, which should be a list of comma separated DNS suffixes, or '*' for all hosts.
Test if proxies should not be used for a particular host.
[ "Test", "if", "proxies", "should", "not", "be", "used", "for", "a", "particular", "host", "." ]
def proxy_bypass_environment(host, proxies=None): """Test if proxies should not be used for a particular host. Checks the proxies dict for the value of no_proxy, which should be a list of comma separated DNS suffixes, or '*' for all hosts. """ if proxies is None: proxies = getproxies_environment() # don't bypass, if no_proxy isn't specified try: no_proxy = proxies['no'] except KeyError: return 0 # '*' is special case for always bypass if no_proxy == '*': return 1 # strip port off host hostonly, port = splitport(host) # check if the host ends with any of the DNS suffixes no_proxy_list = [proxy.strip() for proxy in no_proxy.split(',')] for name in no_proxy_list: if name: name = re.escape(name) pattern = r'(.+\.)?%s$' % name if (re.match(pattern, hostonly, re.I) or re.match(pattern, host, re.I)): return 1 # otherwise, don't bypass return 0
[ "def", "proxy_bypass_environment", "(", "host", ",", "proxies", "=", "None", ")", ":", "if", "proxies", "is", "None", ":", "proxies", "=", "getproxies_environment", "(", ")", "# don't bypass, if no_proxy isn't specified", "try", ":", "no_proxy", "=", "proxies", "[", "'no'", "]", "except", "KeyError", ":", "return", "0", "# '*' is special case for always bypass", "if", "no_proxy", "==", "'*'", ":", "return", "1", "# strip port off host", "hostonly", ",", "port", "=", "splitport", "(", "host", ")", "# check if the host ends with any of the DNS suffixes", "no_proxy_list", "=", "[", "proxy", ".", "strip", "(", ")", "for", "proxy", "in", "no_proxy", ".", "split", "(", "','", ")", "]", "for", "name", "in", "no_proxy_list", ":", "if", "name", ":", "name", "=", "re", ".", "escape", "(", "name", ")", "pattern", "=", "r'(.+\\.)?%s$'", "%", "name", "if", "(", "re", ".", "match", "(", "pattern", ",", "hostonly", ",", "re", ".", "I", ")", "or", "re", ".", "match", "(", "pattern", ",", "host", ",", "re", ".", "I", ")", ")", ":", "return", "1", "# otherwise, don't bypass", "return", "0" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/urllib.py#L1399-L1427
kpe/bert-for-tf2
55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea
bert/tokenization/bert_tokenization.py
python
whitespace_tokenize
(text)
return tokens
Runs basic whitespace cleaning and splitting on a piece of text.
Runs basic whitespace cleaning and splitting on a piece of text.
[ "Runs", "basic", "whitespace", "cleaning", "and", "splitting", "on", "a", "piece", "of", "text", "." ]
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
[ "def", "whitespace_tokenize", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "not", "text", ":", "return", "[", "]", "tokens", "=", "text", ".", "split", "(", ")", "return", "tokens" ]
https://github.com/kpe/bert-for-tf2/blob/55f6a6fd5d8ea14f96ee19938b7a1bf0cb26aaea/bert/tokenization/bert_tokenization.py#L152-L158
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/lutron_caseta/fan.py
python
LutronCasetaFan.supported_features
(self)
return SUPPORT_SET_SPEED
Flag supported features. Speed Only.
Flag supported features. Speed Only.
[ "Flag", "supported", "features", ".", "Speed", "Only", "." ]
def supported_features(self) -> int: """Flag supported features. Speed Only.""" return SUPPORT_SET_SPEED
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_SET_SPEED" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/lutron_caseta/fan.py#L69-L71
vivisect/vivisect
37b0b655d8dedfcf322e86b0f144b096e48d547e
envi/archs/arm/emu.py
python
ArmEmulator.i_vcvt_TODO
(self, op)
convert each element in a vector as float to int or int to float, 32-bit, round-to-zero/round-to-nearest
convert each element in a vector as float to int or int to float, 32-bit, round-to-zero/round-to-nearest
[ "convert", "each", "element", "in", "a", "vector", "as", "float", "to", "int", "or", "int", "to", "float", "32", "-", "bit", "round", "-", "to", "-", "zero", "/", "round", "-", "to", "-", "nearest" ]
def i_vcvt_TODO(self, op): ''' convert each element in a vector as float to int or int to float, 32-bit, round-to-zero/round-to-nearest ''' logger.warning('%r\t%r', op, op.opers) logger.warning("complete implementing vcvt") if op.iflags & IF_ADV_SIMD: # this is an Advanced SIMD instruction srcwidth = op.opers[0].getWidth() dstwidth = op.opers[1].getWidth() regcnt = srcwidth / 4 if len(op.opers) == 3: # 3rd operand is fbits for Fixed Point numbers pass else: # it's either Floating Point or Integer pass else: # we let the register size sort out the details for non-ADV_SIMD stuff if op.simdflags in ifs_second_F32_F64_F16: val = op.opers[1].getFloatValue(self) else: val = op.opers[1].getOperValue(op, self) if len(op.opers) == 3: # 3rd operand is fbits for Fixed Point numbers pass else: # it's either Floating Point or Integer if op.simdflags in ifs_first_F32_F64: op.opers[0].setFloatValue(self, val) else: op.opers[0].setOperValue(op, self, val) firstOP = None if op.simdflags in ifs_first_F32: # get first vector element as F32 firstOP = OP_F32 elif op.simdflags in ifs_first_S32: firstOP = OP_S32 elif op.simdflags in ifs_first_U32: firstOP = OP_U32 elif op.simdflags in ifs_first_F64: firstOP = OP_F64 elif op.simdflags in ifs_first_F16: firstOP = OP_F16 secOP = None if op.simdflags in ifs_second_F32: # get second vector element as F32 secOP = OP_F32 elif op.simdflags in ifs_second_S32: secOP = OP_S32 elif op.simdflags in ifs_second_U32: secOP = OP_U32 elif op.simdflags in ifs_second_F64: secOP = OP_F64 elif op.simdflags in ifs_second_F16: secOP = OP_F16 raise Exception("IMPLEMENT ME: i_vcvt") if len(op.opers) == 3: for reg in range(regcnt): #frac_bits = 64 - op.opers[2].val # pA8_870 if op.simdflags == IFS_F32_S32: pass elif op.simdflags == IFS_F32_U32: pass elif op.simdflags == IFS_S32_F32: pass elif op.simdflags == IFS_U32_F32: pass # pA8_872 elif op.simdflags == IFS_U16_F32: pass elif op.simdflags == IFS_S16_F32: pass elif op.simdflags == IFS_U32_F32: pass elif op.simdflags == IFS_S32_F32: pass elif op.simdflags == IFS_U16_F64: pass elif op.simdflags == IFS_S16_F64: pass elif op.simdflags == IFS_U32_F64: pass elif op.simdflags == IFS_S32_F64: pass elif op.simdflags == IFS_F32_U16: pass elif op.simdflags == IFS_F32_S16: pass elif op.simdflags == IFS_F32_U32: pass elif op.simdflags == IFS_F32_S32: pass elif op.simdflags == IFS_F64_U16: pass elif op.simdflags == IFS_F64_S16: pass elif op.simdflags == IFS_F64_U32: pass elif op.simdflags == IFS_F64_S32: pass elif len(op.opers) == 2: for reg in range(regcnt): #frac_bits = 64 - op.opers[1].val # pA8_866 (868?) if op.simdflags == IFS_F32_S32: pass elif op.simdflags == IFS_F32_U32: pass elif op.simdflags == IFS_S32_F32: pass elif op.simdflags == IFS_U32_F32: pass # pA8-868 (870?) elif op.simdflags == IFS_F64_S32: pass elif op.simdflags == IFS_F64_U32: pass elif op.simdflags == IFS_S32_F64: pass elif op.simdflags == IFS_U32_F64: pass # pA8-874 elif op.simdflags == IFS_F64_F32: pass elif op.simdflags == IFS_F32_F64: pass # pA8-876 elif op.simdflags == IFS_F16_F32: pass elif op.simdflags == IFS_F32_F16: pass else: raise Exception("i_vcvt with strange number of opers: %r" % op.opers)
[ "def", "i_vcvt_TODO", "(", "self", ",", "op", ")", ":", "logger", ".", "warning", "(", "'%r\\t%r'", ",", "op", ",", "op", ".", "opers", ")", "logger", ".", "warning", "(", "\"complete implementing vcvt\"", ")", "if", "op", ".", "iflags", "&", "IF_ADV_SIMD", ":", "# this is an Advanced SIMD instruction", "srcwidth", "=", "op", ".", "opers", "[", "0", "]", ".", "getWidth", "(", ")", "dstwidth", "=", "op", ".", "opers", "[", "1", "]", ".", "getWidth", "(", ")", "regcnt", "=", "srcwidth", "/", "4", "if", "len", "(", "op", ".", "opers", ")", "==", "3", ":", "# 3rd operand is fbits for Fixed Point numbers", "pass", "else", ":", "# it's either Floating Point or Integer", "pass", "else", ":", "# we let the register size sort out the details for non-ADV_SIMD stuff", "if", "op", ".", "simdflags", "in", "ifs_second_F32_F64_F16", ":", "val", "=", "op", ".", "opers", "[", "1", "]", ".", "getFloatValue", "(", "self", ")", "else", ":", "val", "=", "op", ".", "opers", "[", "1", "]", ".", "getOperValue", "(", "op", ",", "self", ")", "if", "len", "(", "op", ".", "opers", ")", "==", "3", ":", "# 3rd operand is fbits for Fixed Point numbers", "pass", "else", ":", "# it's either Floating Point or Integer", "if", "op", ".", "simdflags", "in", "ifs_first_F32_F64", ":", "op", ".", "opers", "[", "0", "]", ".", "setFloatValue", "(", "self", ",", "val", ")", "else", ":", "op", ".", "opers", "[", "0", "]", ".", "setOperValue", "(", "op", ",", "self", ",", "val", ")", "firstOP", "=", "None", "if", "op", ".", "simdflags", "in", "ifs_first_F32", ":", "# get first vector element as F32", "firstOP", "=", "OP_F32", "elif", "op", ".", "simdflags", "in", "ifs_first_S32", ":", "firstOP", "=", "OP_S32", "elif", "op", ".", "simdflags", "in", "ifs_first_U32", ":", "firstOP", "=", "OP_U32", "elif", "op", ".", "simdflags", "in", "ifs_first_F64", ":", "firstOP", "=", "OP_F64", "elif", "op", ".", "simdflags", "in", "ifs_first_F16", ":", "firstOP", "=", "OP_F16", "secOP", "=", "None", "if", "op", ".", "simdflags", "in", "ifs_second_F32", ":", "# get second vector element as F32", "secOP", "=", "OP_F32", "elif", "op", ".", "simdflags", "in", "ifs_second_S32", ":", "secOP", "=", "OP_S32", "elif", "op", ".", "simdflags", "in", "ifs_second_U32", ":", "secOP", "=", "OP_U32", "elif", "op", ".", "simdflags", "in", "ifs_second_F64", ":", "secOP", "=", "OP_F64", "elif", "op", ".", "simdflags", "in", "ifs_second_F16", ":", "secOP", "=", "OP_F16", "raise", "Exception", "(", "\"IMPLEMENT ME: i_vcvt\"", ")", "if", "len", "(", "op", ".", "opers", ")", "==", "3", ":", "for", "reg", "in", "range", "(", "regcnt", ")", ":", "#frac_bits = 64 - op.opers[2].val", "# pA8_870", "if", "op", ".", "simdflags", "==", "IFS_F32_S32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_U32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S32_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U32_F32", ":", "pass", "# pA8_872", "elif", "op", ".", "simdflags", "==", "IFS_U16_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S16_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U32_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S32_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U16_F64", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S16_F64", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U32_F64", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S32_F64", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_U16", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_S16", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_U32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_S32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F64_U16", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F64_S16", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F64_U32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F64_S32", ":", "pass", "elif", "len", "(", "op", ".", "opers", ")", "==", "2", ":", "for", "reg", "in", "range", "(", "regcnt", ")", ":", "#frac_bits = 64 - op.opers[1].val", "# pA8_866 (868?)", "if", "op", ".", "simdflags", "==", "IFS_F32_S32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_U32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S32_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U32_F32", ":", "pass", "# pA8-868 (870?)", "elif", "op", ".", "simdflags", "==", "IFS_F64_S32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F64_U32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_S32_F64", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_U32_F64", ":", "pass", "# pA8-874", "elif", "op", ".", "simdflags", "==", "IFS_F64_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_F64", ":", "pass", "# pA8-876", "elif", "op", ".", "simdflags", "==", "IFS_F16_F32", ":", "pass", "elif", "op", ".", "simdflags", "==", "IFS_F32_F16", ":", "pass", "else", ":", "raise", "Exception", "(", "\"i_vcvt with strange number of opers: %r\"", "%", "op", ".", "opers", ")" ]
https://github.com/vivisect/vivisect/blob/37b0b655d8dedfcf322e86b0f144b096e48d547e/envi/archs/arm/emu.py#L1068-L1224
GoogleCloudPlatform/ml-on-gcp
ffd88931674e08ef6b0b20de27700ed1da61772c
example_zoo/tensorflow/models/keras_cifar_main/official/utils/flags/_device.py
python
require_cloud_storage
(flag_names)
Register a validator to check directory flags. Args: flag_names: An iterable of strings containing the names of flags to be checked.
Register a validator to check directory flags. Args: flag_names: An iterable of strings containing the names of flags to be checked.
[ "Register", "a", "validator", "to", "check", "directory", "flags", ".", "Args", ":", "flag_names", ":", "An", "iterable", "of", "strings", "containing", "the", "names", "of", "flags", "to", "be", "checked", "." ]
def require_cloud_storage(flag_names): """Register a validator to check directory flags. Args: flag_names: An iterable of strings containing the names of flags to be checked. """ msg = "TPU requires GCS path for {}".format(", ".join(flag_names)) @flags.multi_flags_validator(["tpu"] + flag_names, message=msg) def _path_check(flag_values): # pylint: disable=missing-docstring if flag_values["tpu"] is None: return True valid_flags = True for key in flag_names: if not flag_values[key].startswith("gs://"): tf.logging.error("{} must be a GCS path.".format(key)) valid_flags = False return valid_flags
[ "def", "require_cloud_storage", "(", "flag_names", ")", ":", "msg", "=", "\"TPU requires GCS path for {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "flag_names", ")", ")", "@", "flags", ".", "multi_flags_validator", "(", "[", "\"tpu\"", "]", "+", "flag_names", ",", "message", "=", "msg", ")", "def", "_path_check", "(", "flag_values", ")", ":", "# pylint: disable=missing-docstring", "if", "flag_values", "[", "\"tpu\"", "]", "is", "None", ":", "return", "True", "valid_flags", "=", "True", "for", "key", "in", "flag_names", ":", "if", "not", "flag_values", "[", "key", "]", ".", "startswith", "(", "\"gs://\"", ")", ":", "tf", ".", "logging", ".", "error", "(", "\"{} must be a GCS path.\"", ".", "format", "(", "key", ")", ")", "valid_flags", "=", "False", "return", "valid_flags" ]
https://github.com/GoogleCloudPlatform/ml-on-gcp/blob/ffd88931674e08ef6b0b20de27700ed1da61772c/example_zoo/tensorflow/models/keras_cifar_main/official/utils/flags/_device.py#L27-L45
corelan/mona
fab15136880c62f4e8e8c39830e2b31ef8421c48
mona.py
python
getRopFuncPtr
(apiname,modulecriteria,criteria,mode, objprogressfile, progressfile)
return ropfuncptr,ropfunctext
Will get a pointer to pointer to the given API name in the IAT of the selected modules Arguments : apiname : the name of the function modulecriteria & criteria : module/pointer criteria Returns : a pointer (integer value, 0 if no pointer was found) text (with optional info)
Will get a pointer to pointer to the given API name in the IAT of the selected modules Arguments : apiname : the name of the function modulecriteria & criteria : module/pointer criteria Returns : a pointer (integer value, 0 if no pointer was found) text (with optional info)
[ "Will", "get", "a", "pointer", "to", "pointer", "to", "the", "given", "API", "name", "in", "the", "IAT", "of", "the", "selected", "modules", "Arguments", ":", "apiname", ":", "the", "name", "of", "the", "function", "modulecriteria", "&", "criteria", ":", "module", "/", "pointer", "criteria", "Returns", ":", "a", "pointer", "(", "integer", "value", "0", "if", "no", "pointer", "was", "found", ")", "text", "(", "with", "optional", "info", ")" ]
def getRopFuncPtr(apiname,modulecriteria,criteria,mode, objprogressfile, progressfile): """ Will get a pointer to pointer to the given API name in the IAT of the selected modules Arguments : apiname : the name of the function modulecriteria & criteria : module/pointer criteria Returns : a pointer (integer value, 0 if no pointer was found) text (with optional info) """ global silent oldsilent = silent silent = True global ptr_to_get ptr_to_get = -1 rfuncsearch = apiname.lower() selectedmodules = False if "modules" in modulecriteria: if len(modulecriteria["modules"]) > 0: selectedmodules = True arrfuncsearch = [rfuncsearch] if rfuncsearch == "virtualloc": arrfuncsearch.append("virtuallocstub") ropfuncptr = 0 ropfuncoffsets = {} ropfunctext = "ptr to &" + apiname + "()" objprogressfile.write(" * Ropfunc - Looking for %s (IAT) - modulecriteria: %s" % (ropfunctext, modulecriteria), progressfile) if mode == "iat": if rfuncsearch != "": ropfuncs,ropfuncoffsets = findROPFUNC(modulecriteria,criteria, [rfuncsearch]) else: ropfuncs,ropfuncoffsets = findROPFUNC(modulecriteria) silent = oldsilent #first look for good one objprogressfile.write(" * Ropfunc - Found %d pointers" % len(ropfuncs), progressfile) for ropfunctypes in ropfuncs: #dbg.log("Ropfunc - %s %s" % (ropfunctypes, rfuncsearch)) if ropfunctypes.lower().find(rfuncsearch) > -1 and ropfunctypes.lower().find("rebased") == -1: ropfuncptr = ropfuncs[ropfunctypes][0] break if ropfuncptr == 0: for ropfunctypes in ropfuncs: if ropfunctypes.lower().find(rfuncsearch) > -1: ropfuncptr = ropfuncs[ropfunctypes][0] break #dbg.log("Ropfunc - Selected pointer: 0x%08x" % ropfuncptr) #haven't found pointer, and you were looking at specific modules only? remove module restriction, but still exclude ASLR/rebase if (ropfuncptr == 0) and selectedmodules: objprogressfile.write(" * Ropfunc - No results yet, expanding search to all non ASLR/rebase modules", progressfile) oldsilent = silent silent = True limitedmodulecriteria = {} limitedmodulecriteria["aslr"] = False limitedmodulecriteria["rebase"] = False limitedmodulecriteria["os"] = False ropfuncs,ropfuncoffsets = findROPFUNC(limitedmodulecriteria,criteria) silent = oldsilent for ropfunctypes in ropfuncs: #dbg.log("Ropfunc - %s %s" % (ropfunctypes, rfuncsearch)) if ropfunctypes.lower().find(rfuncsearch) > -1 and ropfunctypes.lower().find("rebased") == -1: ropfuncptr = ropfuncs[ropfunctypes][0] break #still haven't found ? clear out modulecriteria, include ASLR/rebase modules (but not OS modules) if (ropfuncptr == 0) and not selectedmodules: objprogressfile.write(" * Ropfunc - Still no results, now going to search in all application modules", progressfile) oldsilent = silent silent = True limitedmodulecriteria = {} # search in anything except known OS modules - bad idea anyway limitedmodulecriteria["os"] = False ropfuncs2,ropfuncoffsets2 = findROPFUNC(limitedmodulecriteria,criteria) silent = oldsilent for ropfunctypes in ropfuncs2: if ropfunctypes.lower().find(rfuncsearch) > -1 and ropfunctypes.lower().find("rebased") == -1: ropfuncptr = ropfuncs2[ropfunctypes][0] ropfunctext += " (skipped module criteria, check if pointer is reliable !)" break if ropfuncptr == 0: ropfunctext = "[-] Unable to find ptr to &" + apiname+"()" else: ropfptrmodname = MnPointer(ropfuncptr).belongsTo() tmod = MnModule(ropfptrmodname) ropfptrmodinfo = getGadgetAddressInfo(ropfuncptr) ropfunctext += " [IAT " + ropfptrmodname + "]" + ropfptrmodinfo else: # read EAT modulestosearch = getModulesToQuery(modulecriteria) for mod in modulestosearch: tmod = MnModule(mod) funcs = tmod.getEAT() for func in funcs: funcname = funcs[func].lower() if funcname.find(rfuncsearch) > -1: ropfuncptr = func break if ropfuncptr == 0: ropfunctext = "[-] Unable to find required API pointer" return ropfuncptr,ropfunctext
[ "def", "getRopFuncPtr", "(", "apiname", ",", "modulecriteria", ",", "criteria", ",", "mode", ",", "objprogressfile", ",", "progressfile", ")", ":", "global", "silent", "oldsilent", "=", "silent", "silent", "=", "True", "global", "ptr_to_get", "ptr_to_get", "=", "-", "1", "rfuncsearch", "=", "apiname", ".", "lower", "(", ")", "selectedmodules", "=", "False", "if", "\"modules\"", "in", "modulecriteria", ":", "if", "len", "(", "modulecriteria", "[", "\"modules\"", "]", ")", ">", "0", ":", "selectedmodules", "=", "True", "arrfuncsearch", "=", "[", "rfuncsearch", "]", "if", "rfuncsearch", "==", "\"virtualloc\"", ":", "arrfuncsearch", ".", "append", "(", "\"virtuallocstub\"", ")", "ropfuncptr", "=", "0", "ropfuncoffsets", "=", "{", "}", "ropfunctext", "=", "\"ptr to &\"", "+", "apiname", "+", "\"()\"", "objprogressfile", ".", "write", "(", "\" * Ropfunc - Looking for %s (IAT) - modulecriteria: %s\"", "%", "(", "ropfunctext", ",", "modulecriteria", ")", ",", "progressfile", ")", "if", "mode", "==", "\"iat\"", ":", "if", "rfuncsearch", "!=", "\"\"", ":", "ropfuncs", ",", "ropfuncoffsets", "=", "findROPFUNC", "(", "modulecriteria", ",", "criteria", ",", "[", "rfuncsearch", "]", ")", "else", ":", "ropfuncs", ",", "ropfuncoffsets", "=", "findROPFUNC", "(", "modulecriteria", ")", "silent", "=", "oldsilent", "#first look for good one", "objprogressfile", ".", "write", "(", "\" * Ropfunc - Found %d pointers\"", "%", "len", "(", "ropfuncs", ")", ",", "progressfile", ")", "for", "ropfunctypes", "in", "ropfuncs", ":", "#dbg.log(\"Ropfunc - %s %s\" % (ropfunctypes, rfuncsearch))", "if", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "rfuncsearch", ")", ">", "-", "1", "and", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "\"rebased\"", ")", "==", "-", "1", ":", "ropfuncptr", "=", "ropfuncs", "[", "ropfunctypes", "]", "[", "0", "]", "break", "if", "ropfuncptr", "==", "0", ":", "for", "ropfunctypes", "in", "ropfuncs", ":", "if", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "rfuncsearch", ")", ">", "-", "1", ":", "ropfuncptr", "=", "ropfuncs", "[", "ropfunctypes", "]", "[", "0", "]", "break", "#dbg.log(\"Ropfunc - Selected pointer: 0x%08x\" % ropfuncptr)", "#haven't found pointer, and you were looking at specific modules only? remove module restriction, but still exclude ASLR/rebase", "if", "(", "ropfuncptr", "==", "0", ")", "and", "selectedmodules", ":", "objprogressfile", ".", "write", "(", "\" * Ropfunc - No results yet, expanding search to all non ASLR/rebase modules\"", ",", "progressfile", ")", "oldsilent", "=", "silent", "silent", "=", "True", "limitedmodulecriteria", "=", "{", "}", "limitedmodulecriteria", "[", "\"aslr\"", "]", "=", "False", "limitedmodulecriteria", "[", "\"rebase\"", "]", "=", "False", "limitedmodulecriteria", "[", "\"os\"", "]", "=", "False", "ropfuncs", ",", "ropfuncoffsets", "=", "findROPFUNC", "(", "limitedmodulecriteria", ",", "criteria", ")", "silent", "=", "oldsilent", "for", "ropfunctypes", "in", "ropfuncs", ":", "#dbg.log(\"Ropfunc - %s %s\" % (ropfunctypes, rfuncsearch))", "if", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "rfuncsearch", ")", ">", "-", "1", "and", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "\"rebased\"", ")", "==", "-", "1", ":", "ropfuncptr", "=", "ropfuncs", "[", "ropfunctypes", "]", "[", "0", "]", "break", "#still haven't found ? clear out modulecriteria, include ASLR/rebase modules (but not OS modules)", "if", "(", "ropfuncptr", "==", "0", ")", "and", "not", "selectedmodules", ":", "objprogressfile", ".", "write", "(", "\" * Ropfunc - Still no results, now going to search in all application modules\"", ",", "progressfile", ")", "oldsilent", "=", "silent", "silent", "=", "True", "limitedmodulecriteria", "=", "{", "}", "# search in anything except known OS modules - bad idea anyway", "limitedmodulecriteria", "[", "\"os\"", "]", "=", "False", "ropfuncs2", ",", "ropfuncoffsets2", "=", "findROPFUNC", "(", "limitedmodulecriteria", ",", "criteria", ")", "silent", "=", "oldsilent", "for", "ropfunctypes", "in", "ropfuncs2", ":", "if", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "rfuncsearch", ")", ">", "-", "1", "and", "ropfunctypes", ".", "lower", "(", ")", ".", "find", "(", "\"rebased\"", ")", "==", "-", "1", ":", "ropfuncptr", "=", "ropfuncs2", "[", "ropfunctypes", "]", "[", "0", "]", "ropfunctext", "+=", "\" (skipped module criteria, check if pointer is reliable !)\"", "break", "if", "ropfuncptr", "==", "0", ":", "ropfunctext", "=", "\"[-] Unable to find ptr to &\"", "+", "apiname", "+", "\"()\"", "else", ":", "ropfptrmodname", "=", "MnPointer", "(", "ropfuncptr", ")", ".", "belongsTo", "(", ")", "tmod", "=", "MnModule", "(", "ropfptrmodname", ")", "ropfptrmodinfo", "=", "getGadgetAddressInfo", "(", "ropfuncptr", ")", "ropfunctext", "+=", "\" [IAT \"", "+", "ropfptrmodname", "+", "\"]\"", "+", "ropfptrmodinfo", "else", ":", "# read EAT", "modulestosearch", "=", "getModulesToQuery", "(", "modulecriteria", ")", "for", "mod", "in", "modulestosearch", ":", "tmod", "=", "MnModule", "(", "mod", ")", "funcs", "=", "tmod", ".", "getEAT", "(", ")", "for", "func", "in", "funcs", ":", "funcname", "=", "funcs", "[", "func", "]", ".", "lower", "(", ")", "if", "funcname", ".", "find", "(", "rfuncsearch", ")", ">", "-", "1", ":", "ropfuncptr", "=", "func", "break", "if", "ropfuncptr", "==", "0", ":", "ropfunctext", "=", "\"[-] Unable to find required API pointer\"", "return", "ropfuncptr", ",", "ropfunctext" ]
https://github.com/corelan/mona/blob/fab15136880c62f4e8e8c39830e2b31ef8421c48/mona.py#L9615-L9721
mihaip/mail-trends
312b5be7f8f0a5933b05c75e229eda8e44c3c920
stats/table.py
python
ThreadOriginFormatter.Format
(self, thread_info)
return unicode(t)
[]
def Format(self, thread_info): t = Template( file="templates/address-formatter.tmpl", searchList = { "address": thread_info["address"], "name": thread_info["name"], }); return unicode(t)
[ "def", "Format", "(", "self", ",", "thread_info", ")", ":", "t", "=", "Template", "(", "file", "=", "\"templates/address-formatter.tmpl\"", ",", "searchList", "=", "{", "\"address\"", ":", "thread_info", "[", "\"address\"", "]", ",", "\"name\"", ":", "thread_info", "[", "\"name\"", "]", ",", "}", ")", "return", "unicode", "(", "t", ")" ]
https://github.com/mihaip/mail-trends/blob/312b5be7f8f0a5933b05c75e229eda8e44c3c920/stats/table.py#L122-L129
cltk/cltk
1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1
src/cltk/phonology/arb/utils/pyarabic/araby.py
python
strip_shadda
(text)
return text.replace(SHADDA, "")
Strip Shadda from a text and return a result text. @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode.
Strip Shadda from a text and return a result text.
[ "Strip", "Shadda", "from", "a", "text", "and", "return", "a", "result", "text", "." ]
def strip_shadda(text): """ Strip Shadda from a text and return a result text. @param text: arabic text. @type text: unicode. @return: return a striped text. @rtype: unicode. """ return text.replace(SHADDA, "")
[ "def", "strip_shadda", "(", "text", ")", ":", "return", "text", ".", "replace", "(", "SHADDA", ",", "\"\"", ")" ]
https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/phonology/arb/utils/pyarabic/araby.py#L792-L801
Esri/ArcREST
ab240fde2b0200f61d4a5f6df033516e53f2f416
src/arcrest/common/general.py
python
FeatureSet.globalIdFieldName
(self, value)
gets/sets the globalIdFieldName
gets/sets the globalIdFieldName
[ "gets", "/", "sets", "the", "globalIdFieldName" ]
def globalIdFieldName(self, value): """gets/sets the globalIdFieldName""" self._globalIdFieldName = value
[ "def", "globalIdFieldName", "(", "self", ",", "value", ")", ":", "self", ".", "_globalIdFieldName", "=", "value" ]
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/general.py#L720-L722
glutanimate/review-heatmap
c758478125b60a81c66c87c35b12b7968ec0a348
src/review_heatmap/libaddon/anki/configmanager.py
python
ConfigManager.all
(self, config_dict)
Implements assignment of self.all Allows updating all configuration values at once. Arguments: config_dict {dict}: Dictionary of config dictionaries (Same format as config_dict in __init__, only that the current config values should be provided instead of defaults)
Implements assignment of self.all
[ "Implements", "assignment", "of", "self", ".", "all" ]
def all(self, config_dict): """ Implements assignment of self.all Allows updating all configuration values at once. Arguments: config_dict {dict}: Dictionary of config dictionaries (Same format as config_dict in __init__, only that the current config values should be provided instead of defaults) """ self._config = config_dict # Reminder: setting self.all resets defaults, so it's important # that it's followed up by setting self.defaults # TODO: Think of a better way to handle this self._storages = { name: {"default": {}, "dirty": False, "loaded": False} for name in config_dict }
[ "def", "all", "(", "self", ",", "config_dict", ")", ":", "self", ".", "_config", "=", "config_dict", "# Reminder: setting self.all resets defaults, so it's important", "# that it's followed up by setting self.defaults", "# TODO: Think of a better way to handle this", "self", ".", "_storages", "=", "{", "name", ":", "{", "\"default\"", ":", "{", "}", ",", "\"dirty\"", ":", "False", ",", "\"loaded\"", ":", "False", "}", "for", "name", "in", "config_dict", "}" ]
https://github.com/glutanimate/review-heatmap/blob/c758478125b60a81c66c87c35b12b7968ec0a348/src/review_heatmap/libaddon/anki/configmanager.py#L294-L314
XaF/TraktForVLC
7851368d7ce62a15bb245fc078f3eab201c12357
helper/parser.py
python
PrintVersion.__init__
(self, help='show program\'s version number and exit', *args, **kwargs)
[]
def __init__(self, help='show program\'s version number and exit', *args, **kwargs): super(PrintVersion, self).__init__( nargs=0, default=argparse.SUPPRESS, help=help, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "help", "=", "'show program\\'s version number and exit'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "PrintVersion", ",", "self", ")", ".", "__init__", "(", "nargs", "=", "0", ",", "default", "=", "argparse", ".", "SUPPRESS", ",", "help", "=", "help", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/XaF/TraktForVLC/blob/7851368d7ce62a15bb245fc078f3eab201c12357/helper/parser.py#L112-L115
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/names/client.py
python
getResolver
()
return theResolver
Get a Resolver instance. Create twisted.names.client.theResolver if it is C{None}, and then return that value. @rtype: C{IResolver}
Get a Resolver instance.
[ "Get", "a", "Resolver", "instance", "." ]
def getResolver(): """ Get a Resolver instance. Create twisted.names.client.theResolver if it is C{None}, and then return that value. @rtype: C{IResolver} """ global theResolver if theResolver is None: try: theResolver = createResolver() except ValueError: theResolver = createResolver(servers=[('127.0.0.1', 53)]) return theResolver
[ "def", "getResolver", "(", ")", ":", "global", "theResolver", "if", "theResolver", "is", "None", ":", "try", ":", "theResolver", "=", "createResolver", "(", ")", "except", "ValueError", ":", "theResolver", "=", "createResolver", "(", "servers", "=", "[", "(", "'127.0.0.1'", ",", "53", ")", "]", ")", "return", "theResolver" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/names/client.py#L560-L575
blurstudio/cross3d
277968d1227de740fc87ef61005c75034420eadf
cross3d/studiomax/mixer/track.py
python
StudiomaxTrack.isLayerTrack
(self)
return self.track.trackType == mxs.pyhelper.namify('layertrack')
Whether this track is a Layer Track
Whether this track is a Layer Track
[ "Whether", "this", "track", "is", "a", "Layer", "Track" ]
def isLayerTrack(self): """Whether this track is a Layer Track""" return self.track.trackType == mxs.pyhelper.namify('layertrack')
[ "def", "isLayerTrack", "(", "self", ")", ":", "return", "self", ".", "track", ".", "trackType", "==", "mxs", ".", "pyhelper", ".", "namify", "(", "'layertrack'", ")" ]
https://github.com/blurstudio/cross3d/blob/277968d1227de740fc87ef61005c75034420eadf/cross3d/studiomax/mixer/track.py#L46-L48
Kronuz/esprima-python
809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d
esprima/parser.py
python
Parser.parsePattern
(self, params, kind=None)
return pattern
[]
def parsePattern(self, params, kind=None): if self.match('['): pattern = self.parseArrayPattern(params, kind) elif self.match('{'): pattern = self.parseObjectPattern(params, kind) else: if self.matchKeyword('let') and (kind in ('const', 'let')): self.tolerateUnexpectedToken(self.lookahead, Messages.LetInLexicalBinding) params.append(self.lookahead) pattern = self.parseVariableIdentifier(kind) return pattern
[ "def", "parsePattern", "(", "self", ",", "params", ",", "kind", "=", "None", ")", ":", "if", "self", ".", "match", "(", "'['", ")", ":", "pattern", "=", "self", ".", "parseArrayPattern", "(", "params", ",", "kind", ")", "elif", "self", ".", "match", "(", "'{'", ")", ":", "pattern", "=", "self", ".", "parseObjectPattern", "(", "params", ",", "kind", ")", "else", ":", "if", "self", ".", "matchKeyword", "(", "'let'", ")", "and", "(", "kind", "in", "(", "'const'", ",", "'let'", ")", ")", ":", "self", ".", "tolerateUnexpectedToken", "(", "self", ".", "lookahead", ",", "Messages", ".", "LetInLexicalBinding", ")", "params", ".", "append", "(", "self", ".", "lookahead", ")", "pattern", "=", "self", ".", "parseVariableIdentifier", "(", "kind", ")", "return", "pattern" ]
https://github.com/Kronuz/esprima-python/blob/809cb6e257b1d3d5b0d23f2bca7976e21f02fc3d/esprima/parser.py#L1721-L1732
HuobiRDCenter/huobi_Python
c75a7fa8b31e99ffc1c173d74dcfcad83682e943
huobi/utils/url_params_builder.py
python
UrlParamsBuilder.build_url
(self)
return "?" + encoded_param
[]
def build_url(self): if len(self.param_map) == 0: return "" encoded_param = urllib.parse.urlencode(self.param_map) return "?" + encoded_param
[ "def", "build_url", "(", "self", ")", ":", "if", "len", "(", "self", ".", "param_map", ")", "==", "0", ":", "return", "\"\"", "encoded_param", "=", "urllib", ".", "parse", ".", "urlencode", "(", "self", ".", "param_map", ")", "return", "\"?\"", "+", "encoded_param" ]
https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/utils/url_params_builder.py#L26-L30
MycroftAI/mycroft-core
3d963cee402e232174850f36918313e87313fb13
mycroft/tts/cache.py
python
TextToSpeechCache.define_audio_file
(self, sentence_hash: str)
return audio_file
Build an instance of an object representing an audio file.
Build an instance of an object representing an audio file.
[ "Build", "an", "instance", "of", "an", "object", "representing", "an", "audio", "file", "." ]
def define_audio_file(self, sentence_hash: str) -> AudioFile: """Build an instance of an object representing an audio file.""" audio_file = AudioFile( self.temporary_cache_dir, sentence_hash, self.audio_file_type ) return audio_file
[ "def", "define_audio_file", "(", "self", ",", "sentence_hash", ":", "str", ")", "->", "AudioFile", ":", "audio_file", "=", "AudioFile", "(", "self", ".", "temporary_cache_dir", ",", "sentence_hash", ",", "self", ".", "audio_file_type", ")", "return", "audio_file" ]
https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/tts/cache.py#L322-L327
PaddlePaddle/PaddleHub
107ee7e1a49d15e9c94da3956475d88a53fc165f
modules/image/semantic_segmentation/fastscnn_cityscapes/layers.py
python
SyncBatchNorm
(*args, **kwargs)
In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead
In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead
[ "In", "cpu", "environment", "nn", ".", "SyncBatchNorm", "does", "not", "have", "kernel", "so", "use", "nn", ".", "BatchNorm2D", "instead" ]
def SyncBatchNorm(*args, **kwargs): """In cpu environment nn.SyncBatchNorm does not have kernel so use nn.BatchNorm2D instead""" if paddle.get_device() == 'cpu' or os.environ.get('PADDLESEG_EXPORT_STAGE'): return nn.BatchNorm2D(*args, **kwargs) else: return nn.SyncBatchNorm(*args, **kwargs)
[ "def", "SyncBatchNorm", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "paddle", ".", "get_device", "(", ")", "==", "'cpu'", "or", "os", ".", "environ", ".", "get", "(", "'PADDLESEG_EXPORT_STAGE'", ")", ":", "return", "nn", ".", "BatchNorm2D", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "nn", ".", "SyncBatchNorm", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/modules/image/semantic_segmentation/fastscnn_cityscapes/layers.py#L23-L28
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/venv/lib/python2.7/site-packages/setuptools/command/easy_install.py
python
PthDistributions.add
(self, dist)
Add `dist` to the distribution map
Add `dist` to the distribution map
[ "Add", "dist", "to", "the", "distribution", "map" ]
def add(self, dist): """Add `dist` to the distribution map""" new_path = ( dist.location not in self.paths and ( dist.location not in self.sitedirs or # account for '.' being in PYTHONPATH dist.location == os.getcwd() ) ) if new_path: self.paths.append(dist.location) self.dirty = True Environment.add(self, dist)
[ "def", "add", "(", "self", ",", "dist", ")", ":", "new_path", "=", "(", "dist", ".", "location", "not", "in", "self", ".", "paths", "and", "(", "dist", ".", "location", "not", "in", "self", ".", "sitedirs", "or", "# account for '.' being in PYTHONPATH", "dist", ".", "location", "==", "os", ".", "getcwd", "(", ")", ")", ")", "if", "new_path", ":", "self", ".", "paths", ".", "append", "(", "dist", ".", "location", ")", "self", ".", "dirty", "=", "True", "Environment", ".", "add", "(", "self", ",", "dist", ")" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/venv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L1558-L1570
ChineseGLUE/ChineseGLUE
1591b85cf5427c2ff60f718d359ecb71d2b44879
baselines/models_pytorch/classifier_pytorch/convert_albert_original_tf_checkpoint_to_pytorch.py
python
convert_tf_checkpoint_to_pytorch
(tf_checkpoint_path, bert_config_file, pytorch_dump_path)
[]
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path): # Initialise PyTorch model config = BertConfig.from_json_file(bert_config_file) print("Building PyTorch model from configuration: {}".format(str(config))) model = AlbertForPreTraining(config) # Load weights from tf checkpoint load_tf_weights_in_albert(model, config, tf_checkpoint_path) # Save pytorch-model print("Save PyTorch model to {}".format(pytorch_dump_path)) torch.save(model.state_dict(), pytorch_dump_path)
[ "def", "convert_tf_checkpoint_to_pytorch", "(", "tf_checkpoint_path", ",", "bert_config_file", ",", "pytorch_dump_path", ")", ":", "# Initialise PyTorch model", "config", "=", "BertConfig", ".", "from_json_file", "(", "bert_config_file", ")", "print", "(", "\"Building PyTorch model from configuration: {}\"", ".", "format", "(", "str", "(", "config", ")", ")", ")", "model", "=", "AlbertForPreTraining", "(", "config", ")", "# Load weights from tf checkpoint", "load_tf_weights_in_albert", "(", "model", ",", "config", ",", "tf_checkpoint_path", ")", "# Save pytorch-model", "print", "(", "\"Save PyTorch model to {}\"", ".", "format", "(", "pytorch_dump_path", ")", ")", "torch", ".", "save", "(", "model", ".", "state_dict", "(", ")", ",", "pytorch_dump_path", ")" ]
https://github.com/ChineseGLUE/ChineseGLUE/blob/1591b85cf5427c2ff60f718d359ecb71d2b44879/baselines/models_pytorch/classifier_pytorch/convert_albert_original_tf_checkpoint_to_pytorch.py#L29-L40
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/src/gdata/photos/__init__.py
python
UserFeed.GetTagsUri
(self)
return self._feedUri('tag')
Get the uri to this feed, but with entries of the TagEntry kind.
Get the uri to this feed, but with entries of the TagEntry kind.
[ "Get", "the", "uri", "to", "this", "feed", "but", "with", "entries", "of", "the", "TagEntry", "kind", "." ]
def GetTagsUri(self): """Get the uri to this feed, but with entries of the TagEntry kind.""" return self._feedUri('tag')
[ "def", "GetTagsUri", "(", "self", ")", ":", "return", "self", ".", "_feedUri", "(", "'tag'", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/gdata/photos/__init__.py#L1040-L1042
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/django-reversion/src/reversion/storage.py
python
VersionFileStorageWrapper.__init__
(self, storage)
Initializes the VersionFileStorageWrapper.
Initializes the VersionFileStorageWrapper.
[ "Initializes", "the", "VersionFileStorageWrapper", "." ]
def __init__(self, storage): """Initializes the VersionFileStorageWrapper.""" self.wrapped_storage = storage
[ "def", "__init__", "(", "self", ",", "storage", ")", ":", "self", ".", "wrapped_storage", "=", "storage" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/django-reversion/src/reversion/storage.py#L10-L12
mozilla/kitsune
7c7cf9baed57aa776547aea744243ccad6ca91fb
kitsune/wiki/models.py
python
Document._ensure_inherited_attr
(self, attr)
Make sure my `attr` attr is the same as my parent's if I have one. Otherwise, if I have children, make sure their `attr` attr is the same as mine.
Make sure my `attr` attr is the same as my parent's if I have one.
[ "Make", "sure", "my", "attr", "attr", "is", "the", "same", "as", "my", "parent", "s", "if", "I", "have", "one", "." ]
def _ensure_inherited_attr(self, attr): """Make sure my `attr` attr is the same as my parent's if I have one. Otherwise, if I have children, make sure their `attr` attr is the same as mine. """ if self.parent: # We always set the child according to the parent rather than vice # versa, because we do not expose an Archived checkbox in the # translation UI. setattr(self, attr, getattr(self.parent, attr)) else: # An article cannot have both a parent and children. # Make my children the same as me: if self.id: self.translations.all().update(**{attr: getattr(self, attr)})
[ "def", "_ensure_inherited_attr", "(", "self", ",", "attr", ")", ":", "if", "self", ".", "parent", ":", "# We always set the child according to the parent rather than vice", "# versa, because we do not expose an Archived checkbox in the", "# translation UI.", "setattr", "(", "self", ",", "attr", ",", "getattr", "(", "self", ".", "parent", ",", "attr", ")", ")", "else", ":", "# An article cannot have both a parent and children.", "# Make my children the same as me:", "if", "self", ".", "id", ":", "self", ".", "translations", ".", "all", "(", ")", ".", "update", "(", "*", "*", "{", "attr", ":", "getattr", "(", "self", ",", "attr", ")", "}", ")" ]
https://github.com/mozilla/kitsune/blob/7c7cf9baed57aa776547aea744243ccad6ca91fb/kitsune/wiki/models.py#L222-L237
LuxCoreRender/BlendLuxCore
bf31ca58501d54c02acd97001b6db7de81da7cbf
engine/preview.py
python
_create_area_light
(scene, luxcore_scene, props, name, color, position, rotation_matrix, scale, visible=True)
return props
[]
def _create_area_light(scene, luxcore_scene, props, name, color, position, rotation_matrix, scale, visible=True): mat_name = name + "_mat" mesh_name = name + "_mesh" # Material props.Set(pyluxcore.Property("scene.materials." + mat_name + ".type", ["matte"])) props.Set(pyluxcore.Property("scene.materials." + mat_name + ".kd", [0.0] * 3)) props.Set(pyluxcore.Property("scene.materials." + mat_name + ".emission", color)) # assign material to object props.Set(pyluxcore.Property("scene.objects." + name + ".material", [mat_name])) props.Set(pyluxcore.Property("scene.objects." + name + ".camerainvisible", not visible)) scale_matrix = Matrix() scale_matrix[0][0] = scale scale_matrix[1][1] = scale rotation_matrix.resize_4x4() transform_matrix = Matrix() transform_matrix[0][3] = position[0] transform_matrix[1][3] = position[1] transform_matrix[2][3] = position[2] mat = transform_matrix @ rotation_matrix @ scale_matrix transform = utils.matrix_to_list(mat) # add mesh vertices = [ (1, 1, 0), (1, -1, 0), (-1, -1, 0), (-1, 1, 0) ] faces = [ (0, 1, 2), (2, 3, 0) ] luxcore_scene.DefineMesh(mesh_name, vertices, faces, None, None, None, None, transform) # assign mesh to object props.Set(pyluxcore.Property("scene.objects." + name + ".shape", [mesh_name])) return props
[ "def", "_create_area_light", "(", "scene", ",", "luxcore_scene", ",", "props", ",", "name", ",", "color", ",", "position", ",", "rotation_matrix", ",", "scale", ",", "visible", "=", "True", ")", ":", "mat_name", "=", "name", "+", "\"_mat\"", "mesh_name", "=", "name", "+", "\"_mesh\"", "# Material", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.materials.\"", "+", "mat_name", "+", "\".type\"", ",", "[", "\"matte\"", "]", ")", ")", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.materials.\"", "+", "mat_name", "+", "\".kd\"", ",", "[", "0.0", "]", "*", "3", ")", ")", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.materials.\"", "+", "mat_name", "+", "\".emission\"", ",", "color", ")", ")", "# assign material to object", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.objects.\"", "+", "name", "+", "\".material\"", ",", "[", "mat_name", "]", ")", ")", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.objects.\"", "+", "name", "+", "\".camerainvisible\"", ",", "not", "visible", ")", ")", "scale_matrix", "=", "Matrix", "(", ")", "scale_matrix", "[", "0", "]", "[", "0", "]", "=", "scale", "scale_matrix", "[", "1", "]", "[", "1", "]", "=", "scale", "rotation_matrix", ".", "resize_4x4", "(", ")", "transform_matrix", "=", "Matrix", "(", ")", "transform_matrix", "[", "0", "]", "[", "3", "]", "=", "position", "[", "0", "]", "transform_matrix", "[", "1", "]", "[", "3", "]", "=", "position", "[", "1", "]", "transform_matrix", "[", "2", "]", "[", "3", "]", "=", "position", "[", "2", "]", "mat", "=", "transform_matrix", "@", "rotation_matrix", "@", "scale_matrix", "transform", "=", "utils", ".", "matrix_to_list", "(", "mat", ")", "# add mesh", "vertices", "=", "[", "(", "1", ",", "1", ",", "0", ")", ",", "(", "1", ",", "-", "1", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ",", "0", ")", ",", "(", "-", "1", ",", "1", ",", "0", ")", "]", "faces", "=", "[", "(", "0", ",", "1", ",", "2", ")", ",", "(", "2", ",", "3", ",", "0", ")", "]", "luxcore_scene", ".", "DefineMesh", "(", "mesh_name", ",", "vertices", ",", "faces", ",", "None", ",", "None", ",", "None", ",", "None", ",", "transform", ")", "# assign mesh to object", "props", ".", "Set", "(", "pyluxcore", ".", "Property", "(", "\"scene.objects.\"", "+", "name", "+", "\".shape\"", ",", "[", "mesh_name", "]", ")", ")", "return", "props" ]
https://github.com/LuxCoreRender/BlendLuxCore/blob/bf31ca58501d54c02acd97001b6db7de81da7cbf/engine/preview.py#L213-L252
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/terminal/pt_inputhooks/__init__.py
python
register
(name, inputhook)
Register the function *inputhook* as an event loop integration.
Register the function *inputhook* as an event loop integration.
[ "Register", "the", "function", "*", "inputhook", "*", "as", "an", "event", "loop", "integration", "." ]
def register(name, inputhook): """Register the function *inputhook* as an event loop integration.""" registered[name] = inputhook
[ "def", "register", "(", "name", ",", "inputhook", ")", ":", "registered", "[", "name", "]", "=", "inputhook" ]
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/terminal/pt_inputhooks/__init__.py#L28-L30
inasafe/inasafe
355eb2ce63f516b9c26af0c86a24f99e53f63f87
safe/gui/tools/multi_exposure_dialog.py
python
MultiExposureDialog.ordered_expected_layers
(self)
return layers
Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list
Get an ordered list of layers according to users input.
[ "Get", "an", "ordered", "list", "of", "layers", "according", "to", "users", "input", "." ]
def ordered_expected_layers(self): """Get an ordered list of layers according to users input. From top to bottom in the legend: [ ('FromCanvas', layer name, full layer URI, QML), ('FromAnalysis', layer purpose, layer group, None), ... ] The full layer URI is coming from our helper. :return: An ordered list of layers following a structure. :rtype: list """ registry = QgsProject.instance() layers = [] count = self.list_layers_in_map_report.count() for i in range(count): layer = self.list_layers_in_map_report.item(i) origin = layer.data(LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) parent = layer.data(LAYER_PARENT_ANALYSIS_ROLE) layers.append(( FROM_ANALYSIS['key'], key, parent, None )) else: layer_id = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE) layer = registry.mapLayer(layer_id) style_document = QDomDocument() layer.exportNamedStyle(style_document) layers.append(( FROM_CANVAS['key'], layer.name(), full_layer_uri(layer), style_document.toString() )) return layers
[ "def", "ordered_expected_layers", "(", "self", ")", ":", "registry", "=", "QgsProject", ".", "instance", "(", ")", "layers", "=", "[", "]", "count", "=", "self", ".", "list_layers_in_map_report", ".", "count", "(", ")", "for", "i", "in", "range", "(", "count", ")", ":", "layer", "=", "self", ".", "list_layers_in_map_report", ".", "item", "(", "i", ")", "origin", "=", "layer", ".", "data", "(", "LAYER_ORIGIN_ROLE", ")", "if", "origin", "==", "FROM_ANALYSIS", "[", "'key'", "]", ":", "key", "=", "layer", ".", "data", "(", "LAYER_PURPOSE_KEY_OR_ID_ROLE", ")", "parent", "=", "layer", ".", "data", "(", "LAYER_PARENT_ANALYSIS_ROLE", ")", "layers", ".", "append", "(", "(", "FROM_ANALYSIS", "[", "'key'", "]", ",", "key", ",", "parent", ",", "None", ")", ")", "else", ":", "layer_id", "=", "layer", ".", "data", "(", "LAYER_PURPOSE_KEY_OR_ID_ROLE", ")", "layer", "=", "registry", ".", "mapLayer", "(", "layer_id", ")", "style_document", "=", "QDomDocument", "(", ")", "layer", ".", "exportNamedStyle", "(", "style_document", ")", "layers", ".", "append", "(", "(", "FROM_CANVAS", "[", "'key'", "]", ",", "layer", ".", "name", "(", ")", ",", "full_layer_uri", "(", "layer", ")", ",", "style_document", ".", "toString", "(", ")", ")", ")", "return", "layers" ]
https://github.com/inasafe/inasafe/blob/355eb2ce63f516b9c26af0c86a24f99e53f63f87/safe/gui/tools/multi_exposure_dialog.py#L175-L217
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/modules/common.py
python
BaseConfiguration.specs_to_load
(self)
return self._create_list_for('autoload')
List of specs that should be loaded in the module file.
List of specs that should be loaded in the module file.
[ "List", "of", "specs", "that", "should", "be", "loaded", "in", "the", "module", "file", "." ]
def specs_to_load(self): """List of specs that should be loaded in the module file.""" return self._create_list_for('autoload')
[ "def", "specs_to_load", "(", "self", ")", ":", "return", "self", ".", "_create_list_for", "(", "'autoload'", ")" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/modules/common.py#L541-L543
mendersoftware/meta-mender
c350e90337670f7853297b8eaf67341a627af775
meta-mender-core/recipes-bsp/u-boot/files/boolean.py
python
Expression.__hash__
(self)
return hash(self.__class__.__name__) ^ arghash
Expressions are immutable and hashable. The hash of Functions is computed by respecting the structure of the whole expression by mixing the class name hash and the recursive hash of a frozenset of arguments. Hash of elements is based on their boolean equivalent. Hash of symbols is based on their object.
Expressions are immutable and hashable. The hash of Functions is computed by respecting the structure of the whole expression by mixing the class name hash and the recursive hash of a frozenset of arguments. Hash of elements is based on their boolean equivalent. Hash of symbols is based on their object.
[ "Expressions", "are", "immutable", "and", "hashable", ".", "The", "hash", "of", "Functions", "is", "computed", "by", "respecting", "the", "structure", "of", "the", "whole", "expression", "by", "mixing", "the", "class", "name", "hash", "and", "the", "recursive", "hash", "of", "a", "frozenset", "of", "arguments", ".", "Hash", "of", "elements", "is", "based", "on", "their", "boolean", "equivalent", ".", "Hash", "of", "symbols", "is", "based", "on", "their", "object", "." ]
def __hash__(self): """ Expressions are immutable and hashable. The hash of Functions is computed by respecting the structure of the whole expression by mixing the class name hash and the recursive hash of a frozenset of arguments. Hash of elements is based on their boolean equivalent. Hash of symbols is based on their object. """ if not self.args: arghash = id(self) else: arghash = hash(frozenset(map(hash, self.args))) return hash(self.__class__.__name__) ^ arghash
[ "def", "__hash__", "(", "self", ")", ":", "if", "not", "self", ".", "args", ":", "arghash", "=", "id", "(", "self", ")", "else", ":", "arghash", "=", "hash", "(", "frozenset", "(", "map", "(", "hash", ",", "self", ".", "args", ")", ")", ")", "return", "hash", "(", "self", ".", "__class__", ".", "__name__", ")", "^", "arghash" ]
https://github.com/mendersoftware/meta-mender/blob/c350e90337670f7853297b8eaf67341a627af775/meta-mender-core/recipes-bsp/u-boot/files/boolean.py#L714-L726
facebookresearch/mmf
fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f
mmf/trainers/callbacks/base.py
python
Callback.on_update_end
(self, **kwargs)
Called after each train update.
Called after each train update.
[ "Called", "after", "each", "train", "update", "." ]
def on_update_end(self, **kwargs) -> None: """ Called after each train update. """ pass
[ "def", "on_update_end", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "pass" ]
https://github.com/facebookresearch/mmf/blob/fb6fe390287e1da12c3bd28d4ab43c5f7dcdfc9f/mmf/trainers/callbacks/base.py#L71-L75
huxiaoman7/leetcodebook
2bb52713522a0b4b64ad1f3e064d6045d40dfac8
python/25_ReverseNodesinK-Group.py
python
Solution.reverseKGroup
(self, head, k)
:type head: ListNode :type k: int :rtype: ListNode
:type head: ListNode :type k: int :rtype: ListNode
[ ":", "type", "head", ":", "ListNode", ":", "type", "k", ":", "int", ":", "rtype", ":", "ListNode" ]
def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ dummy = jump = ListNode(0) dummy.next = l = r = head while True: count = 0 while r and count < k: r = r.next count += 1 if count == k: pre, cur = r, l for _ in range(k): cur.next, cur, pre = pre, cur.next, cur jump.next, jump, l = pre, l, r else: return dummy.next
[ "def", "reverseKGroup", "(", "self", ",", "head", ",", "k", ")", ":", "dummy", "=", "jump", "=", "ListNode", "(", "0", ")", "dummy", ".", "next", "=", "l", "=", "r", "=", "head", "while", "True", ":", "count", "=", "0", "while", "r", "and", "count", "<", "k", ":", "r", "=", "r", ".", "next", "count", "+=", "1", "if", "count", "==", "k", ":", "pre", ",", "cur", "=", "r", ",", "l", "for", "_", "in", "range", "(", "k", ")", ":", "cur", ".", "next", ",", "cur", ",", "pre", "=", "pre", ",", "cur", ".", "next", ",", "cur", "jump", ".", "next", ",", "jump", ",", "l", "=", "pre", ",", "l", ",", "r", "else", ":", "return", "dummy", ".", "next" ]
https://github.com/huxiaoman7/leetcodebook/blob/2bb52713522a0b4b64ad1f3e064d6045d40dfac8/python/25_ReverseNodesinK-Group.py#L16-L36
rowanz/neural-motifs
d05a251b705cedaa51599bf2906cfa4653b7a761
dataloaders/mscoco.py
python
CocoDetection.__getitem__
(self, index)
return entry
Args: index (int): Index Returns: entry dict
Args: index (int): Index
[ "Args", ":", "index", "(", "int", ")", ":", "Index" ]
def __getitem__(self, index): """ Args: index (int): Index Returns: entry dict """ img_id = self.ids[index] path = self.coco.loadImgs(img_id)[0]['file_name'] image_unpadded = Image.open(os.path.join(self.root, path)).convert('RGB') ann_ids = self.coco.getAnnIds(imgIds=img_id) anns = self.coco.loadAnns(ann_ids) gt_classes = np.array([self.id_to_ind[x['category_id']] for x in anns], dtype=np.int64) if np.any(gt_classes >= len(self.ind_to_classes)): raise ValueError("OH NO {}".format(index)) if len(anns) == 0: raise ValueError("Annotations should not be empty") # gt_boxes = np.array((0, 4), dtype=np.float32) # else: gt_boxes = np.array([x['bbox'] for x in anns], dtype=np.float32) if np.any(gt_boxes[:, [0,1]] < 0): raise ValueError("GT boxes empty columns") if np.any(gt_boxes[:, [2,3]] < 0): raise ValueError("GT boxes empty h/w") gt_boxes[:, [2, 3]] += gt_boxes[:, [0, 1]] # Rescale so that the boxes are at BOX_SCALE if self.is_train: image_unpadded, gt_boxes = random_crop(image_unpadded, gt_boxes * BOX_SCALE / max(image_unpadded.size), BOX_SCALE, round_boxes=False, ) else: # Seems a bit silly because we won't be using GT boxes then but whatever gt_boxes = gt_boxes * BOX_SCALE / max(image_unpadded.size) w, h = image_unpadded.size box_scale_factor = BOX_SCALE / max(w, h) # Optionally flip the image if we're doing training flipped = self.is_train and np.random.random() > 0.5 if flipped: scaled_w = int(box_scale_factor * float(w)) image_unpadded = image_unpadded.transpose(Image.FLIP_LEFT_RIGHT) gt_boxes[:, [0, 2]] = scaled_w - gt_boxes[:, [2, 0]] img_scale_factor = IM_SCALE / max(w, h) if h > w: im_size = (IM_SCALE, int(w*img_scale_factor), img_scale_factor) elif h < w: im_size = (int(h*img_scale_factor), IM_SCALE, img_scale_factor) else: im_size = (IM_SCALE, IM_SCALE, img_scale_factor) entry = { 'img': self.transform_pipeline(image_unpadded), 'img_size': im_size, 'gt_boxes': gt_boxes, 'gt_classes': gt_classes, 'scale': IM_SCALE / BOX_SCALE, 'index': index, 'image_id': img_id, 'flipped': flipped, 'fn': path, } return entry
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "img_id", "=", "self", ".", "ids", "[", "index", "]", "path", "=", "self", ".", "coco", ".", "loadImgs", "(", "img_id", ")", "[", "0", "]", "[", "'file_name'", "]", "image_unpadded", "=", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "root", ",", "path", ")", ")", ".", "convert", "(", "'RGB'", ")", "ann_ids", "=", "self", ".", "coco", ".", "getAnnIds", "(", "imgIds", "=", "img_id", ")", "anns", "=", "self", ".", "coco", ".", "loadAnns", "(", "ann_ids", ")", "gt_classes", "=", "np", ".", "array", "(", "[", "self", ".", "id_to_ind", "[", "x", "[", "'category_id'", "]", "]", "for", "x", "in", "anns", "]", ",", "dtype", "=", "np", ".", "int64", ")", "if", "np", ".", "any", "(", "gt_classes", ">=", "len", "(", "self", ".", "ind_to_classes", ")", ")", ":", "raise", "ValueError", "(", "\"OH NO {}\"", ".", "format", "(", "index", ")", ")", "if", "len", "(", "anns", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Annotations should not be empty\"", ")", "# gt_boxes = np.array((0, 4), dtype=np.float32)", "# else:", "gt_boxes", "=", "np", ".", "array", "(", "[", "x", "[", "'bbox'", "]", "for", "x", "in", "anns", "]", ",", "dtype", "=", "np", ".", "float32", ")", "if", "np", ".", "any", "(", "gt_boxes", "[", ":", ",", "[", "0", ",", "1", "]", "]", "<", "0", ")", ":", "raise", "ValueError", "(", "\"GT boxes empty columns\"", ")", "if", "np", ".", "any", "(", "gt_boxes", "[", ":", ",", "[", "2", ",", "3", "]", "]", "<", "0", ")", ":", "raise", "ValueError", "(", "\"GT boxes empty h/w\"", ")", "gt_boxes", "[", ":", ",", "[", "2", ",", "3", "]", "]", "+=", "gt_boxes", "[", ":", ",", "[", "0", ",", "1", "]", "]", "# Rescale so that the boxes are at BOX_SCALE", "if", "self", ".", "is_train", ":", "image_unpadded", ",", "gt_boxes", "=", "random_crop", "(", "image_unpadded", ",", "gt_boxes", "*", "BOX_SCALE", "/", "max", "(", "image_unpadded", ".", "size", ")", ",", "BOX_SCALE", ",", "round_boxes", "=", "False", ",", ")", "else", ":", "# Seems a bit silly because we won't be using GT boxes then but whatever", "gt_boxes", "=", "gt_boxes", "*", "BOX_SCALE", "/", "max", "(", "image_unpadded", ".", "size", ")", "w", ",", "h", "=", "image_unpadded", ".", "size", "box_scale_factor", "=", "BOX_SCALE", "/", "max", "(", "w", ",", "h", ")", "# Optionally flip the image if we're doing training", "flipped", "=", "self", ".", "is_train", "and", "np", ".", "random", ".", "random", "(", ")", ">", "0.5", "if", "flipped", ":", "scaled_w", "=", "int", "(", "box_scale_factor", "*", "float", "(", "w", ")", ")", "image_unpadded", "=", "image_unpadded", ".", "transpose", "(", "Image", ".", "FLIP_LEFT_RIGHT", ")", "gt_boxes", "[", ":", ",", "[", "0", ",", "2", "]", "]", "=", "scaled_w", "-", "gt_boxes", "[", ":", ",", "[", "2", ",", "0", "]", "]", "img_scale_factor", "=", "IM_SCALE", "/", "max", "(", "w", ",", "h", ")", "if", "h", ">", "w", ":", "im_size", "=", "(", "IM_SCALE", ",", "int", "(", "w", "*", "img_scale_factor", ")", ",", "img_scale_factor", ")", "elif", "h", "<", "w", ":", "im_size", "=", "(", "int", "(", "h", "*", "img_scale_factor", ")", ",", "IM_SCALE", ",", "img_scale_factor", ")", "else", ":", "im_size", "=", "(", "IM_SCALE", ",", "IM_SCALE", ",", "img_scale_factor", ")", "entry", "=", "{", "'img'", ":", "self", ".", "transform_pipeline", "(", "image_unpadded", ")", ",", "'img_size'", ":", "im_size", ",", "'gt_boxes'", ":", "gt_boxes", ",", "'gt_classes'", ":", "gt_classes", ",", "'scale'", ":", "IM_SCALE", "/", "BOX_SCALE", ",", "'index'", ":", "index", ",", "'image_id'", ":", "img_id", ",", "'flipped'", ":", "flipped", ",", "'fn'", ":", "path", ",", "}", "return", "entry" ]
https://github.com/rowanz/neural-motifs/blob/d05a251b705cedaa51599bf2906cfa4653b7a761/dataloaders/mscoco.py#L58-L127
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/python/zipstream.py
python
_FileEntry.close
(self)
Close self (file-like object)
Close self (file-like object)
[ "Close", "self", "(", "file", "-", "like", "object", ")" ]
def close(self): """ Close self (file-like object) """ self.closed = True self.finished = 1 del self.fp
[ "def", "close", "(", "self", ")", ":", "self", ".", "closed", "=", "True", "self", ".", "finished", "=", "1", "del", "self", ".", "fp" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/python/zipstream.py#L107-L113
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/statistics.py
python
NormalDist.__eq__
(x1, x2)
return x1._mu == x2._mu and x1._sigma == x2._sigma
Two NormalDist objects are equal if their mu and sigma are both equal.
Two NormalDist objects are equal if their mu and sigma are both equal.
[ "Two", "NormalDist", "objects", "are", "equal", "if", "their", "mu", "and", "sigma", "are", "both", "equal", "." ]
def __eq__(x1, x2): "Two NormalDist objects are equal if their mu and sigma are both equal." if not isinstance(x2, NormalDist): return NotImplemented return x1._mu == x2._mu and x1._sigma == x2._sigma
[ "def", "__eq__", "(", "x1", ",", "x2", ")", ":", "if", "not", "isinstance", "(", "x2", ",", "NormalDist", ")", ":", "return", "NotImplemented", "return", "x1", ".", "_mu", "==", "x2", ".", "_mu", "and", "x1", ".", "_sigma", "==", "x2", ".", "_sigma" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/statistics.py#L1091-L1095
getnikola/nikola
2da876e9322e42a93f8295f950e336465c6a4ee5
nikola/__main__.py
python
DoitNikola.get_cmds
(self)
return cmds
Get commands.
Get commands.
[ "Get", "commands", "." ]
def get_cmds(self): """Get commands.""" # core doit commands cmds = DoitMain.get_cmds(self) # load nikola commands for name, cmd in self.nikola._commands.items(): cmds[name] = cmd return cmds
[ "def", "get_cmds", "(", "self", ")", ":", "# core doit commands", "cmds", "=", "DoitMain", ".", "get_cmds", "(", "self", ")", "# load nikola commands", "for", "name", ",", "cmd", "in", "self", ".", "nikola", ".", "_commands", ".", "items", "(", ")", ":", "cmds", "[", "name", "]", "=", "cmd", "return", "cmds" ]
https://github.com/getnikola/nikola/blob/2da876e9322e42a93f8295f950e336465c6a4ee5/nikola/__main__.py#L306-L313
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/distributed/worker.py
python
Worker._state_priority
(state)
return state.history.depth
[]
def _state_priority(state): return state.history.depth
[ "def", "_state_priority", "(", "state", ")", ":", "return", "state", ".", "history", ".", "depth" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/distributed/worker.py#L162-L163
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_process.py
python
OCProcess.delete
(self, obj)
return self._delete(obj['kind'], obj['metadata']['name'])
delete a resource
delete a resource
[ "delete", "a", "resource" ]
def delete(self, obj): '''delete a resource''' return self._delete(obj['kind'], obj['metadata']['name'])
[ "def", "delete", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "_delete", "(", "obj", "[", "'kind'", "]", ",", "obj", "[", "'metadata'", "]", "[", "'name'", "]", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_process.py#L1519-L1521
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/k_tableau.py
python
WeakTableau_abstract.pp
(self)
r""" Return a pretty print string of the tableau. EXAMPLES:: sage: t = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3) sage: t.pp() . 1 1 2 2 . 2 1 sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation') sage: t.pp() [s2*s0, s3*s2]
r""" Return a pretty print string of the tableau.
[ "r", "Return", "a", "pretty", "print", "string", "of", "the", "tableau", "." ]
def pp(self): r""" Return a pretty print string of the tableau. EXAMPLES:: sage: t = WeakTableau([[None, 1, 1, 2, 2], [None, 2], [1]], 3) sage: t.pp() . 1 1 2 2 . 2 1 sage: t = WeakTableau([[2,0],[3,2]], 3, inner_shape = [2], representation = 'factorized_permutation') sage: t.pp() [s2*s0, s3*s2] """ if self.parent()._representation in ['core', 'bounded']: print(self._repr_diagram()) else: print(self)
[ "def", "pp", "(", "self", ")", ":", "if", "self", ".", "parent", "(", ")", ".", "_representation", "in", "[", "'core'", ",", "'bounded'", "]", ":", "print", "(", "self", ".", "_repr_diagram", "(", ")", ")", "else", ":", "print", "(", "self", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/k_tableau.py#L399-L417
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/redis/client.py
python
Redis.unwatch
(self)
return self.execute_command('UNWATCH')
Unwatches the value at key ``name``, or None of the key doesn't exist
Unwatches the value at key ``name``, or None of the key doesn't exist
[ "Unwatches", "the", "value", "at", "key", "name", "or", "None", "of", "the", "key", "doesn", "t", "exist" ]
def unwatch(self): """ Unwatches the value at key ``name``, or None of the key doesn't exist """ return self.execute_command('UNWATCH')
[ "def", "unwatch", "(", "self", ")", ":", "return", "self", ".", "execute_command", "(", "'UNWATCH'", ")" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/redis/client.py#L508-L512
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
examples/get_waf_log.py
python
upload_logs_to_object_storage
(waf_logs)
[]
def upload_logs_to_object_storage(waf_logs): object_storage = oci.object_storage.ObjectStorageClient(config) namespace = object_storage.get_namespace().data current_datetime = datetime.now() object_name = "WafLogs-" + str(current_datetime) print("Uploading new object to Object Storage - {!r}".format(object_name)) object_storage.put_object(namespace, bucket_name, object_name, bytes(str(waf_logs), 'utf-8'))
[ "def", "upload_logs_to_object_storage", "(", "waf_logs", ")", ":", "object_storage", "=", "oci", ".", "object_storage", ".", "ObjectStorageClient", "(", "config", ")", "namespace", "=", "object_storage", ".", "get_namespace", "(", ")", ".", "data", "current_datetime", "=", "datetime", ".", "now", "(", ")", "object_name", "=", "\"WafLogs-\"", "+", "str", "(", "current_datetime", ")", "print", "(", "\"Uploading new object to Object Storage - {!r}\"", ".", "format", "(", "object_name", ")", ")", "object_storage", ".", "put_object", "(", "namespace", ",", "bucket_name", ",", "object_name", ",", "bytes", "(", "str", "(", "waf_logs", ")", ",", "'utf-8'", ")", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/examples/get_waf_log.py#L55-L67
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py
python
Utils.create_tmp_file_from_contents
(rname, data, ftype='yaml')
return tmp
create a file in tmp with name and contents
create a file in tmp with name and contents
[ "create", "a", "file", "in", "tmp", "with", "name", "and", "contents" ]
def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp
[ "def", "create_tmp_file_from_contents", "(", "rname", ",", "data", ",", "ftype", "=", "'yaml'", ")", ":", "tmp", "=", "Utils", ".", "create_tmpfile", "(", "prefix", "=", "rname", ")", "if", "ftype", "==", "'yaml'", ":", "# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage", "# pylint: disable=no-member", "if", "hasattr", "(", "yaml", ",", "'RoundTripDumper'", ")", ":", "Utils", ".", "_write", "(", "tmp", ",", "yaml", ".", "dump", "(", "data", ",", "Dumper", "=", "yaml", ".", "RoundTripDumper", ")", ")", "else", ":", "Utils", ".", "_write", "(", "tmp", ",", "yaml", ".", "safe_dump", "(", "data", ",", "default_flow_style", "=", "False", ")", ")", "elif", "ftype", "==", "'json'", ":", "Utils", ".", "_write", "(", "tmp", ",", "json", ".", "dumps", "(", "data", ")", ")", "else", ":", "Utils", ".", "_write", "(", "tmp", ",", "data", ")", "# Register cleanup when module is done", "atexit", ".", "register", "(", "Utils", ".", "cleanup", ",", "[", "tmp", "]", ")", "return", "tmp" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_serviceaccount.py#L1166-L1186
theislab/scvelo
1805ab4a72d3f34496f0ef246500a159f619d3a2
scvelo/tools/utils.py
python
vcorrcoef
(X, y, mode="pearsons", axis=-1)
return corr
Pearsons/Spearmans correlation coefficients. Use Pearsons / Spearmans to test for linear / monotonic relationship. Arguments ---------- X: `np.ndarray` Data vector or matrix y: `np.ndarray` Data vector or matrix mode: 'pearsons' or 'spearmans' (default: `'pearsons'`) Which correlation metric to use.
Pearsons/Spearmans correlation coefficients.
[ "Pearsons", "/", "Spearmans", "correlation", "coefficients", "." ]
def vcorrcoef(X, y, mode="pearsons", axis=-1): """Pearsons/Spearmans correlation coefficients. Use Pearsons / Spearmans to test for linear / monotonic relationship. Arguments ---------- X: `np.ndarray` Data vector or matrix y: `np.ndarray` Data vector or matrix mode: 'pearsons' or 'spearmans' (default: `'pearsons'`) Which correlation metric to use. """ if issparse(X): X = np.array(X.A) if issparse(y): y = np.array(y.A) if axis == 0: if X.ndim > 1: X = np.array(X.T) if y.ndim > 1: y = np.array(y.T) if X.shape[axis] != y.shape[axis]: X = X.T if mode in {"spearmans", "spearman"}: from scipy.stats.stats import rankdata X = np.apply_along_axis(rankdata, axis=-1, arr=X) y = np.apply_along_axis(rankdata, axis=-1, arr=y) Xm = np.array(X - (np.nanmean(X, -1)[:, None] if X.ndim > 1 else np.nanmean(X, -1))) ym = np.array(y - (np.nanmean(y, -1)[:, None] if y.ndim > 1 else np.nanmean(y, -1))) corr = np.nansum(Xm * ym, -1) / np.sqrt( np.nansum(Xm ** 2, -1) * np.nansum(ym ** 2, -1) ) return corr
[ "def", "vcorrcoef", "(", "X", ",", "y", ",", "mode", "=", "\"pearsons\"", ",", "axis", "=", "-", "1", ")", ":", "if", "issparse", "(", "X", ")", ":", "X", "=", "np", ".", "array", "(", "X", ".", "A", ")", "if", "issparse", "(", "y", ")", ":", "y", "=", "np", ".", "array", "(", "y", ".", "A", ")", "if", "axis", "==", "0", ":", "if", "X", ".", "ndim", ">", "1", ":", "X", "=", "np", ".", "array", "(", "X", ".", "T", ")", "if", "y", ".", "ndim", ">", "1", ":", "y", "=", "np", ".", "array", "(", "y", ".", "T", ")", "if", "X", ".", "shape", "[", "axis", "]", "!=", "y", ".", "shape", "[", "axis", "]", ":", "X", "=", "X", ".", "T", "if", "mode", "in", "{", "\"spearmans\"", ",", "\"spearman\"", "}", ":", "from", "scipy", ".", "stats", ".", "stats", "import", "rankdata", "X", "=", "np", ".", "apply_along_axis", "(", "rankdata", ",", "axis", "=", "-", "1", ",", "arr", "=", "X", ")", "y", "=", "np", ".", "apply_along_axis", "(", "rankdata", ",", "axis", "=", "-", "1", ",", "arr", "=", "y", ")", "Xm", "=", "np", ".", "array", "(", "X", "-", "(", "np", ".", "nanmean", "(", "X", ",", "-", "1", ")", "[", ":", ",", "None", "]", "if", "X", ".", "ndim", ">", "1", "else", "np", ".", "nanmean", "(", "X", ",", "-", "1", ")", ")", ")", "ym", "=", "np", ".", "array", "(", "y", "-", "(", "np", ".", "nanmean", "(", "y", ",", "-", "1", ")", "[", ":", ",", "None", "]", "if", "y", ".", "ndim", ">", "1", "else", "np", ".", "nanmean", "(", "y", ",", "-", "1", ")", ")", ")", "corr", "=", "np", ".", "nansum", "(", "Xm", "*", "ym", ",", "-", "1", ")", "/", "np", ".", "sqrt", "(", "np", ".", "nansum", "(", "Xm", "**", "2", ",", "-", "1", ")", "*", "np", ".", "nansum", "(", "ym", "**", "2", ",", "-", "1", ")", ")", "return", "corr" ]
https://github.com/theislab/scvelo/blob/1805ab4a72d3f34496f0ef246500a159f619d3a2/scvelo/tools/utils.py#L475-L510