hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
7951684d640b59b7ee5ea4acae1115ef617b7d4d
5,757
py
Python
Src/solver.py
yashchandak/UnO
caa709679236ec70d37c249e0cebace27fb30c51
[ "Apache-2.0" ]
null
null
null
Src/solver.py
yashchandak/UnO
caa709679236ec70d37c249e0cebace27fb30c51
[ "Apache-2.0" ]
null
null
null
Src/solver.py
yashchandak/UnO
caa709679236ec70d37c249e0cebace27fb30c51
[ "Apache-2.0" ]
null
null
null
#!~miniconda3/envs/pytorch/bin python # from __future__ import print_function # from memory_profiler import profile import argparse from datetime import datetime import numpy as np import Src.Utils.utils as utils from Src.config import Config from time import time import matplotlib.pyplot as plt class Solver: def __init__(self, config): # Initialize the required variables self.config = config self.env = self.config.env self.state_dim = np.shape(self.env.reset())[0] if len(self.env.action_space.shape) > 0: self.action_dim = self.env.action_space.shape[0] else: self.action_dim = self.env.action_space.n print("Actions space: {} :: State space: {}".format(self.action_dim, self.state_dim)) self.model = config.algo(config=config) def train(self, max_episodes): # Learn the model on the environment return_history = [] true_rewards = [] action_prob = [] ckpt = self.config.save_after rm_history, regret, rm, start_ep = [], 0, 0, 0 steps = 0 t0 = time() for episode in range(start_ep, max_episodes): # Reset both environment and model before a new episode state = self.env.reset() self.model.reset() step, total_r = 0, 0 done = False while not done: # self.env.render(mode='human') action, dist = self.model.get_action(state) new_state, reward, done, info = self.env.step(action=action) self.model.update(state, action, dist, reward, new_state, done) state = new_state # Tracking intra-episode progress total_r += reward step += 1 # if step >= self.config.max_steps: # break # track inter-episode progress # returns.append(total_r) steps += step rm = 0.9*rm + 0.1*total_r # rm = total_r if episode%ckpt == 0 or episode == self.config.max_episodes-1: rm_history.append(rm) return_history.append(total_r) print("{} :: Rewards {:.3f} :: steps: {:.2f} :: Time: {:.3f}({:.5f}/step) :: Entropy : {:.3f} :: Grads : {}". format(episode, rm, steps/ckpt, (time() - t0)/ckpt, (time() - t0)/steps, self.model.entropy, self.model.get_grads())) self.model.save() utils.save_plots(return_history, config=self.config, name='{}_rewards'.format(self.config.seed)) t0 = time() steps = 0 def eval(self, max_episodes): self.model.load() temp = max_episodes/100 returns = [] for episode in range(max_episodes): # Reset both environment and model before a new episode state = self.env.reset() self.model.reset() step, total_r = 0, 0 done = False while not done: # self.env.render(mode='human') # IMPORTANT: Switch between the following two lines depending on # whether the domain is MDP or POMDP # action, dist = self.model.get_action(state) action, dist = self.model.get_action_POMDP(state) new_state, reward, done, info = self.env.step(action=action) state = new_state # Tracking intra-episode progress total_r += self.config.gamma**step * reward step += 1 # if step >= self.config.max_steps: # break returns.append(total_r) if episode % temp == 0: print("Eval Collected {}/{} :: Mean return {}".format(episode, max_episodes, np.mean(returns))) np.save(self.config.paths['results'] + 'eval_returns_' + str(self.config.alpha) + '_' + str(self.config.seed) , returns) def collect(self, max_episodes): self.model.load() temp = max_episodes/100 trajectories = [] for episode in range(max_episodes): # Reset both environment and model before a new episode state = self.env.reset() self.model.reset() traj = [] step, total_r = 0, 0 done = False while not done: # self.env.render(mode='human') # IMPORTANT: Switch between the following two lines depending on # whether the domain is MDP or POMDP # action, rho = self.model.get_action(state, behavior=True) action, rho = self.model.get_action_POMDP(state, behavior=True) new_state, reward, done, info = self.env.step(action=action) state = new_state # Track importance ratio of current action, and current reward traj.append((rho, reward)) step += 1 # if step >= self.config.max_steps: # break # Make the length of all trajectories the same. # Make rho = 1 and reward = 0, which corresponds to a self loop in the terminal state for i in range(step, self.env.max_horizon): traj.append((1, 0)) trajectories.append(traj) if episode % temp == 0: print("Beta Collected {}/{}".format(episode, max_episodes)) np.save(self.config.paths['results'] + 'beta_trajectories_' + str(self.config.alpha) + '_' + str(self.config.seed) , trajectories)
34.890909
146
0.543339
79516858f2e3fc6578279f7f9d0a930a0b6e929c
20,279
py
Python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_web_application_firewall_policies_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
8
2021-01-13T23:44:08.000Z
2021-03-17T10:13:36.000Z
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_web_application_firewall_policies_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_web_application_firewall_policies_operations.py
vbarbaresi/azure-sdk-for-python
397ba46c51d001ff89c66b170f5576cf8f49c05f
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class WebApplicationFirewallPoliciesOperations(object): """WebApplicationFirewallPoliciesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_06_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, resource_group_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["models.WebApplicationFirewallPolicyListResult"] """Lists all of the protection policies within a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WebApplicationFirewallPolicyListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicyListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.WebApplicationFirewallPolicyListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-06-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WebApplicationFirewallPolicyListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies'} # type: ignore def list_all( self, **kwargs # type: Any ): # type: (...) -> Iterable["models.WebApplicationFirewallPolicyListResult"] """Gets all the WAF policies in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WebApplicationFirewallPolicyListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicyListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.WebApplicationFirewallPolicyListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-06-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('WebApplicationFirewallPolicyListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies'} # type: ignore def get( self, resource_group_name, # type: str policy_name, # type: str **kwargs # type: Any ): # type: (...) -> "models.WebApplicationFirewallPolicy" """Retrieve protection policy with specified name within a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param policy_name: The name of the policy. :type policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: WebApplicationFirewallPolicy, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicy :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.WebApplicationFirewallPolicy"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-06-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128, min_length=0), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('WebApplicationFirewallPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'} # type: ignore def create_or_update( self, resource_group_name, # type: str policy_name, # type: str parameters, # type: "models.WebApplicationFirewallPolicy" **kwargs # type: Any ): # type: (...) -> "models.WebApplicationFirewallPolicy" """Creates or update policy with specified rule set name within a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param policy_name: The name of the policy. :type policy_name: str :param parameters: Policy to be created. :type parameters: ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicy :keyword callable cls: A custom type or function that will be passed the direct response :return: WebApplicationFirewallPolicy, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_06_01.models.WebApplicationFirewallPolicy :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.WebApplicationFirewallPolicy"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-06-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128, min_length=0), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'WebApplicationFirewallPolicy') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('WebApplicationFirewallPolicy', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('WebApplicationFirewallPolicy', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'} # type: ignore def _delete_initial( self, resource_group_name, # type: str policy_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-06-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128, min_length=0), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str policy_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes Policy. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param policy_name: The name of the policy. :type policy_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, policy_name=policy_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'} # type: ignore
48.398568
215
0.664382
7951697711dded50f5652cdc4e4a5e23c94ef2b6
2,886
py
Python
test/functional/interface_bitcoin_cli.py
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
test/functional/interface_bitcoin_cli.py
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
test/functional/interface_bitcoin_cli.py
PlutusCapital/core
9a02ab820245afdb2b3ab4bea621a78bfef37590
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test plutus-cli""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, assert_raises_process_error, get_auth_cookie import time class TestBitcoinCli(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): """Main test logic""" self.log.info("Sleeping 30 seconds...") time.sleep(30) self.log.info("Compare responses from gewalletinfo RPC and `plutus-cli getwalletinfo`") cli_response = self.nodes[0].cli.getwalletinfo() rpc_response = self.nodes[0].getwalletinfo() assert_equal(cli_response, rpc_response) self.log.info("Compare responses from getblockchaininfo RPC and `plutus-cli getblockchaininfo`") cli_response = self.nodes[0].cli.getblockchaininfo() rpc_response = self.nodes[0].getblockchaininfo() assert_equal(cli_response, rpc_response) user, password = get_auth_cookie(self.nodes[0].datadir) self.log.info("Compare responses from `plutus-cli -getinfo` and the RPCs data is retrieved from.") cli_get_info = self.nodes[0].cli('getinfo').send_cli() wallet_info = self.nodes[0].getwalletinfo() network_info = self.nodes[0].getnetworkinfo() blockchain_info = self.nodes[0].getblockchaininfo() assert_equal(cli_get_info['version'], network_info['version']) assert_equal(cli_get_info['protocolversion'], network_info['protocolversion']) assert_equal(cli_get_info['walletversion'], wallet_info['walletversion']) assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['blocks'], blockchain_info['blocks']) assert_equal(cli_get_info['timeoffset'], network_info['timeoffset']) assert_equal(cli_get_info['connections'], network_info['connections']) assert_equal(cli_get_info['proxy'], network_info['networks'][0]['proxy']) assert_equal(cli_get_info['difficulty'], blockchain_info['difficulty']) assert_equal(cli_get_info['testnet'], blockchain_info['chain'] == "test") assert_equal(cli_get_info['balance'], wallet_info['balance']) assert_equal(cli_get_info['keypoololdest'], wallet_info['keypoololdest']) assert_equal(cli_get_info['keypoolsize'], wallet_info['keypoolsize']) assert_equal(cli_get_info['paytxfee'], wallet_info['paytxfee']) assert_equal(cli_get_info['relayfee'], network_info['relayfee']) # unlocked_until is not tested because the wallet is not encrypted if __name__ == '__main__': TestBitcoinCli().main()
48.915254
106
0.71483
7951698ad67e30ef9f20a7222fb37ac08aa74f1f
7,763
py
Python
docs/conf.py
agconti/njode
404b1af5319467d1fef59d2875f24b1a5d4ab13f
[ "BSD-3-Clause" ]
1
2015-12-31T10:24:25.000Z
2015-12-31T10:24:25.000Z
docs/conf.py
agconti/njode
404b1af5319467d1fef59d2875f24b1a5d4ab13f
[ "BSD-3-Clause" ]
null
null
null
docs/conf.py
agconti/njode
404b1af5319467d1fef59d2875f24b1a5d4ab13f
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # # njode documentation build configuration file, created by # sphinx-quickstart. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'njode' copyright = u'2014, Your Name' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'njodedoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'njode.tex', u'njode Documentation', u'Your Name', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'njode', u'njode Documentation', [u'Your Name'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'njode', u'njode Documentation', u'Your Name', 'njode', 'Run a node server with a main django sever', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
31.685714
80
0.705011
79516bd02d97028a0d032b4da9b43c3aac2b20eb
3,930
py
Python
ajax_backend/ajax_comments.py
PatchyVideo/PatchyVideo
cafbdfa34591d7292090d5e67bb633b974447b64
[ "MIT" ]
13
2020-06-04T00:25:24.000Z
2022-03-31T13:12:17.000Z
ajax_backend/ajax_comments.py
PatchyVideo/PatchyVideo
cafbdfa34591d7292090d5e67bb633b974447b64
[ "MIT" ]
1
2021-01-03T04:17:45.000Z
2021-02-07T14:19:04.000Z
ajax_backend/ajax_comments.py
PatchyVideo/PatchyVideo
cafbdfa34591d7292090d5e67bb633b974447b64
[ "MIT" ]
null
null
null
from flask import render_template, request, current_app, jsonify, redirect, session from init import app from utils.interceptors import jsonRequest, loginRequiredJSON, loginOptional from utils.jsontools import * from utils.exceptions import UserError from utils import getDefaultJSON from services.comment import addToVideo, addToPlaylist, addToUser, addComment, addReply, listThread, hideComment, delComment, editComment, pinComment from services.tcb import filterOperation from bson import ObjectId @app.route('/comments/add_to_video.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_video(rd, user, data): thread_id, cid = addToVideo(user, ObjectId(data.vid), data.text) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/add_to_video_unfiltered.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_video_unfiltered(rd, user, data): thread_id, cid = addToVideo(user, ObjectId(data.vid), data.text, use_bleach = False) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/add_to_playlist.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_playlist(rd, user, data): thread_id, cid = addToPlaylist(user, ObjectId(data.pid), data.text) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/add_to_playlist_unfiltered.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_playlist_unfiltered(rd, user, data): thread_id, cid = addToPlaylist(user, ObjectId(data.pid), data.text, use_bleach = False) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/add_to_user.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_user(rd, user, data): thread_id, cid = addToUser(user, ObjectId(data.uid), data.text) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/add_to_user_unfiltered.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_add_to_user_unfiltered(rd, user, data): thread_id, cid = addToUser(user, ObjectId(data.uid), data.text, use_bleach = False) return "json", makeResponseSuccess({'thread_id': str(thread_id), 'cid': cid}) @app.route('/comments/reply.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_reply(rd, user, data): addReply(user, ObjectId(data.reply_to), data.text) @app.route('/comments/reply_unfiltered.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_reply_unfiltered(rd, user, data): addReply(user, ObjectId(data.reply_to), data.text, use_bleach = False) @app.route('/comments/hide.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_hide(rd, user, data): hideComment(user, ObjectId(data.cid)) @app.route('/comments/del.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_del(rd, user, data): delComment(user, ObjectId(data.cid)) @app.route('/comments/edit.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_edit(rd, user, data): editComment(user, data.text, ObjectId(data.cid)) @app.route('/comments/edit_unfiltered.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_edit_unfiltered(rd, user, data): editComment(user, data.text, ObjectId(data.cid), use_bleach = False) @app.route('/comments/pin.do', methods = ['POST']) @loginRequiredJSON @jsonRequest def ajax_comments_pin(rd, user, data): pinComment(user, ObjectId(data.cid), data.pinned) @app.route('/comments/view.do', methods = ['POST']) @loginOptional @jsonRequest def ajax_comments_view(rd, user, data): comments, users, thread = listThread(ObjectId(data.thread_id)) return "json", makeResponseSuccess({'comments': comments, 'users': users, 'thread': thread})
37.075472
149
0.764631
79516c466a350013c33f7119e1f13e568964c606
2,528
py
Python
blueprints/headers/__init__.py
mariussteffens/security-crawl-maze
7bfa4e58344633016e2b5f2f30bd2dacea0a819b
[ "Apache-2.0" ]
103
2019-05-25T00:44:52.000Z
2022-03-30T17:21:28.000Z
blueprints/headers/__init__.py
mariussteffens/security-crawl-maze
7bfa4e58344633016e2b5f2f30bd2dacea0a819b
[ "Apache-2.0" ]
3
2020-08-10T09:36:30.000Z
2022-03-11T11:59:20.000Z
blueprints/headers/__init__.py
mariussteffens/security-crawl-maze
7bfa4e58344633016e2b5f2f30bd2dacea0a819b
[ "Apache-2.0" ]
22
2019-06-27T11:25:16.000Z
2022-03-18T16:24:11.000Z
# Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Module serving all the traffic for response headers test cases.""" import os from flask import abort from flask import Blueprint from flask import make_response from flask import render_template from flask import Response from flask import send_from_directory headers_module = Blueprint( "headers_module", __name__, template_folder="templates") # Global app.instance_path is not accessible from blueprints ¯\_(ツ)_/¯. TEST_CASES_PATH = os.path.abspath(__file__ + "/../../../test-cases/headers/") @headers_module.route("/content-location/") def content_location(): r = make_response(render_template("content-location-header.html"), 201) r.headers["Content-Location"] = "/test/headers/content-location.found" return r @headers_module.route("/link/") def link(): r = make_response(render_template("link-header.html"), 200) r.headers["Link"] = "</test/headers/link.found>; rel=\"preload\"" return r @headers_module.route("/location/") def location(): # Not rendering a response because it will be redirected anyway. r = Response(status=301) r.headers["Location"] = "/test/headers/location.found" return r @headers_module.route("/refresh/") def refresh(): r = make_response(render_template("refresh-header.html"), 200) r.headers["Refresh"] = "999; url=/test/headers/refresh.found" return r @headers_module.route("/", defaults={"path": ""}) @headers_module.route("/<path:path>") def html_dir(path): """Lists contents of requested directory.""" requested_path = os.path.join(TEST_CASES_PATH, path) if not os.path.exists(requested_path): return abort(404) if os.path.isdir(requested_path): files = os.listdir(requested_path) return render_template("list-headers-dir.html", files=files, path=path) if os.path.isfile(requested_path): return send_from_directory("test-cases/headers", path)
34.162162
80
0.718354
79516d2bec2f8011c05f6a9a733eca1351d7bf45
1,276
py
Python
examples/transceiver.py
jookies/smpp.twisted
6b826ad34e547c96736e65a7695c904d117d78f4
[ "Apache-2.0" ]
3
2021-02-08T02:51:50.000Z
2022-02-20T07:56:59.000Z
examples/transceiver.py
jookies/smpp.twisted
6b826ad34e547c96736e65a7695c904d117d78f4
[ "Apache-2.0" ]
null
null
null
examples/transceiver.py
jookies/smpp.twisted
6b826ad34e547c96736e65a7695c904d117d78f4
[ "Apache-2.0" ]
1
2021-11-07T21:54:47.000Z
2021-11-07T21:54:47.000Z
import logging from twisted.internet import reactor, defer from smpp.twisted.client import SMPPClientTransceiver, SMPPClientService from smpp.twisted.config import SMPPClientConfig class SMPP: def __init__(self, config=None): if config is None: config = SMPPClientConfig(host='localhost', port=999, username='uname', password='pwd') # Uncomment line below to recv SMS via #322223322 only # config = SMPPClientConfig(host='localhost', port=999, username='uname', password='pwd', addressTon=AddrTon.UNKNOWN, addressNpi=AddrNpi.ISDN, addressRange='^322223322$') self.config = config @defer.inlineCallbacks def run(self): try: #Bind smpp = yield SMPPClientTransceiver(self.config, self.handleMsg).connectAndBind() #Wait for disconnect yield smpp.getDisconnectedDeferred() except Exception, e: print "ERROR: %s" % str(e) finally: reactor.stop() def handleMsg(self, smpp, pdu): """ NOTE: you can return a Deferred here """ print "Received pdu %s" % pdu if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) SMPP().run() reactor.run()
33.578947
182
0.632445
79516ddbd538ddd8b66abdbfe6be36a8f75a81b0
249,247
py
Python
third_party/python/cpplint/cpplint.py
ajorgensen/heron
6430c51a4a6030e93018e0ed40e5936a64317636
[ "Apache-2.0" ]
1
2021-06-29T07:00:10.000Z
2021-06-29T07:00:10.000Z
third_party/python/cpplint/cpplint.py
ajorgensen/heron
6430c51a4a6030e93018e0ed40e5936a64317636
[ "Apache-2.0" ]
null
null
null
third_party/python/cpplint/cpplint.py
ajorgensen/heron
6430c51a4a6030e93018e0ed40e5936a64317636
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by /* and // inside strings! We do a small hack, which is to ignore //'s with "'s after them on the same line, but it is far from perfect (in either direction). """ import codecs import copy import getopt import glob import itertools import math # for log import os import re import sre_compile import string import sys import unicodedata import xml.etree.ElementTree # if empty, use defaults _header_extensions = set([]) # if empty, use defaults _valid_extensions = set([]) # Files with any of these extensions are considered to be # header files (and will undergo different style checks). # This set can be extended by using the --headers # option (also supported in CPPLINT.cfg) def GetHeaderExtensions(): if not _header_extensions: return set(['h', 'hpp', 'hxx', 'h++', 'cuh']) return _header_extensions # The allowed extensions for file names # This is set by --extensions flag def GetAllExtensions(): if not _valid_extensions: return GetHeaderExtensions().union(set(['c', 'cc', 'cpp', 'cxx', 'c++', 'cu'])) return _valid_extensions def GetNonHeaderExtensions(): return GetAllExtensions().difference(GetHeaderExtensions()) _USAGE = """ Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit] [--filter=-x,+y,...] [--counting=total|toplevel|detailed] [--repository=path] [--root=subdir] [--linelength=digits] [--recursive] [--exclude=path] [--headers=ext1,ext2] [--extensions=hpp,cpp,...] <file> [file] ... The style guidelines this tries to follow are those in https://google.github.io/styleguide/cppguide.html Every problem is given a confidence score from 1-5, with 5 meaning we are certain of the problem, and 1 meaning it could be a legitimate construct. This will miss some errors, and is not a substitute for a code review. To suppress false-positive errors of a certain category, add a 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) suppresses errors of all categories on that line. The files passed in will be linted; at least one file must be provided. Default linted extensions are %s. Other file types will be ignored. Change the extensions with the --extensions flag. Flags: output=emacs|eclipse|vs7|junit By default, the output is formatted to ease emacs parsing. Output compatible with eclipse (eclipse), Visual Studio (vs7), and JUnit XML parsers such as those used in Jenkins and Bamboo may also be used. Other formats are unsupported. verbose=# Specify a number 0-5 to restrict errors to certain verbosity levels. Errors with lower verbosity levels have lower confidence and are more likely to be false positives. quiet Supress output other than linting errors, such as information about which files have been processed and excluded. filter=-x,+y,... Specify a comma-separated list of category-filters to apply: only error messages whose category names pass the filters will be printed. (Category names are printed with the message and look like "[whitespace/indent]".) Filters are evaluated left to right. "-FOO" and "FOO" means "do not print categories that start with FOO". "+FOO" means "do print categories that start with FOO". Examples: --filter=-whitespace,+whitespace/braces --filter=whitespace,runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use To see a list of all the categories used in cpplint, pass no arg: --filter= counting=total|toplevel|detailed The total number of errors found is always printed. If 'toplevel' is provided, then the count of errors in each of the top-level categories like 'build' and 'whitespace' will also be printed. If 'detailed' is provided, then a count is provided for each category like 'build/class'. repository=path The top level directory of the repository, used to derive the header guard CPP variable. By default, this is determined by searching for a path that contains .git, .hg, or .svn. When this flag is specified, the given path is used instead. This option allows the header guard CPP variable to remain consistent even if members of a team have different repository root directories (such as when checking out a subdirectory with SVN). In addition, users of non-mainstream version control systems can use this flag to ensure readable header guard CPP variables. Examples: Assuming that Alice checks out ProjectName and Bob checks out ProjectName/trunk and trunk contains src/chrome/ui/browser.h, then with no --repository flag, the header guard CPP variable will be: Alice => TRUNK_SRC_CHROME_BROWSER_UI_BROWSER_H_ Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ If Alice uses the --repository=trunk flag and Bob omits the flag or uses --repository=. then the header guard CPP variable will be: Alice => SRC_CHROME_BROWSER_UI_BROWSER_H_ Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_ root=subdir The root directory used for deriving header guard CPP variables. This directory is relative to the top level directory of the repository which by default is determined by searching for a directory that contains .git, .hg, or .svn but can also be controlled with the --repository flag. If the specified directory does not exist, this flag is ignored. Examples: Assuming that src is the top level directory of the repository, the header guard CPP variables for src/chrome/browser/ui/browser.h are: No flag => CHROME_BROWSER_UI_BROWSER_H_ --root=chrome => BROWSER_UI_BROWSER_H_ --root=chrome/browser => UI_BROWSER_H_ linelength=digits This is the allowed line length for the project. The default value is 80 characters. Examples: --linelength=120 recursive Search for files to lint recursively. Each directory given in the list of files to be linted is replaced by all files that descend from that directory. Files with extensions not in the valid extensions list are excluded. exclude=path Exclude the given path from the list of files to be linted. Relative paths are evaluated relative to the current directory and shell globbing is performed. This flag can be provided multiple times to exclude multiple files. Examples: --exclude=one.cc --exclude=src/*.cc --exclude=src/*.cc --exclude=test/*.cc extensions=extension,extension,... The allowed file extensions that cpplint will check Examples: --extensions=%s headers=extension,extension,... The allowed header extensions that cpplint will consider to be header files (by default, only files with extensions %s will be assumed to be headers) Examples: --headers=%s cpplint.py supports per-directory configurations specified in CPPLINT.cfg files. CPPLINT.cfg file can contain a number of key=value pairs. Currently the following options are supported: set noparent filter=+filter1,-filter2,... exclude_files=regex linelength=80 root=subdir "set noparent" option prevents cpplint from traversing directory tree upwards looking for more .cfg files in parent directories. This option is usually placed in the top-level project directory. The "filter" option is similar in function to --filter flag. It specifies message filters in addition to the |_DEFAULT_FILTERS| and those specified through --filter command-line flag. "exclude_files" allows to specify a regular expression to be matched against a file name. If the expression matches, the file is skipped and not run through the linter. "linelength" specifies the allowed line length for the project. The "root" option is similar in function to the --root flag (see example above). CPPLINT.cfg has an effect on files in the same directory and all subdirectories, unless overridden by a nested configuration file. Example file: filter=-build/include_order,+build/include_alpha exclude_files=.*\\.cc The above example disables build/include_order warning and enables build/include_alpha as well as excludes all .cc from being processed by linter, in the current directory (where the .cfg file is located) and all subdirectories. """ % (list(GetAllExtensions()), ','.join(list(GetAllExtensions())), GetHeaderExtensions(), ','.join(GetHeaderExtensions())) # We categorize each error message we print. Here are the categories. # We want an explicit list so we can list them all in cpplint --filter=. # If you add a new error message with a new category, add it to the list # here! cpplint_unittest.py should tell you if you forget to do this. _ERROR_CATEGORIES = [ 'build/class', 'build/c++11', 'build/c++14', 'build/c++tr1', 'build/deprecated', 'build/endif_comment', 'build/explicit_make_pair', 'build/forward_decl', 'build/header_guard', 'build/include', 'build/include_subdir', 'build/include_alpha', 'build/include_order', 'build/include_what_you_use', 'build/namespaces_literals', 'build/namespaces', 'build/printf_format', 'build/storage_class', 'legal/copyright', 'readability/alt_tokens', 'readability/braces', 'readability/casting', 'readability/check', 'readability/constructors', 'readability/fn_size', 'readability/inheritance', 'readability/multiline_comment', 'readability/multiline_string', 'readability/namespace', 'readability/nolint', 'readability/nul', 'readability/strings', 'readability/todo', 'readability/utf8', 'runtime/arrays', 'runtime/casting', 'runtime/explicit', 'runtime/int', 'runtime/init', 'runtime/invalid_increment', 'runtime/member_string_references', 'runtime/memset', 'runtime/indentation_namespace', 'runtime/operator', 'runtime/printf', 'runtime/printf_format', 'runtime/references', 'runtime/string', 'runtime/threadsafe_fn', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/braces', 'whitespace/comma', 'whitespace/comments', 'whitespace/empty_conditional_body', 'whitespace/empty_if_body', 'whitespace/empty_loop_body', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/newline', 'whitespace/operators', 'whitespace/parens', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/todo', ] # These error categories are no longer enforced by cpplint, but for backwards- # compatibility they may still appear in NOLINT comments. _LEGACY_ERROR_CATEGORIES = [ 'readability/streams', 'readability/function', ] # The default state of the category filter. This is overridden by the --filter= # flag. By default all errors are on, so only add here categories that should be # off by default (i.e., categories that must be enabled by the --filter= flags). # All entries here should start with a '-' or '+', as in the --filter= flag. _DEFAULT_FILTERS = ['-build/include_alpha'] # The default list of categories suppressed for C (not C++) files. _DEFAULT_C_SUPPRESSED_CATEGORIES = [ 'readability/casting', ] # The default list of categories suppressed for Linux Kernel files. _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [ 'whitespace/tab', ] # We used to check for high-bit characters, but after much discussion we # decided those were OK, as long as they were in UTF-8 and didn't represent # hard-coded international strings, which belong in a separate i18n file. # C++ headers _CPP_HEADERS = frozenset([ # Legacy 'algobase.h', 'algo.h', 'alloc.h', 'builtinbuf.h', 'bvector.h', 'complex.h', 'defalloc.h', 'deque.h', 'editbuf.h', 'fstream.h', 'function.h', 'hash_map', 'hash_map.h', 'hash_set', 'hash_set.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip.h', 'iostream.h', 'istream.h', 'iterator.h', 'list.h', 'map.h', 'multimap.h', 'multiset.h', 'ostream.h', 'pair.h', 'parsestream.h', 'pfstream.h', 'procbuf.h', 'pthread_alloc', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', 'set.h', 'slist', 'slist.h', 'stack.h', 'stdiostream.h', 'stl_alloc.h', 'stl_relops.h', 'streambuf.h', 'stream.h', 'strfile.h', 'strstream.h', 'tempbuf.h', 'tree.h', 'type_traits.h', 'vector.h', # 17.6.1.2 C++ library headers 'algorithm', 'array', 'atomic', 'bitset', 'chrono', 'codecvt', 'complex', 'condition_variable', 'deque', 'exception', 'forward_list', 'fstream', 'functional', 'future', 'initializer_list', 'iomanip', 'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'limits', 'list', 'locale', 'map', 'memory', 'mutex', 'new', 'numeric', 'ostream', 'queue', 'random', 'ratio', 'regex', 'scoped_allocator', 'set', 'sstream', 'stack', 'stdexcept', 'streambuf', 'string', 'strstream', 'system_error', 'thread', 'tuple', 'typeindex', 'typeinfo', 'type_traits', 'unordered_map', 'unordered_set', 'utility', 'valarray', 'vector', # 17.6.1.2 C++ headers for C library facilities 'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat', 'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp', 'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar', 'cwchar', 'cwctype', ]) # Type names _TYPES = re.compile( r'^(?:' # [dcl.type.simple] r'(char(16_t|32_t)?)|wchar_t|' r'bool|short|int|long|signed|unsigned|float|double|' # [support.types] r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|' # [cstdint.syn] r'(u?int(_fast|_least)?(8|16|32|64)_t)|' r'(u?int(max|ptr)_t)|' r')$') # These headers are excluded from [build/include] and [build/include_order] # checks: # - Anything not following google file name conventions (containing an # uppercase character, such as Python.h or nsStringAPI.h, for example). # - Lua headers. _THIRD_PARTY_HEADERS_PATTERN = re.compile( r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') # Pattern for matching FileInfo.BaseName() against test file name _test_suffixes = ['_test', '_regtest', '_unittest'] _TEST_FILE_SUFFIX = '(' + '|'.join(_test_suffixes) + r')$' # Pattern that matches only complete whitespace, possibly across multiple lines. _EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL) # Assertion macros. These are defined in base/logging.h and # testing/base/public/gunit.h. _CHECK_MACROS = [ 'DCHECK', 'CHECK', 'EXPECT_TRUE', 'ASSERT_TRUE', 'EXPECT_FALSE', 'ASSERT_FALSE', ] # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE _CHECK_REPLACEMENT = dict([(macro_var, {}) for macro_var in _CHECK_MACROS]) for op, replacement in [('==', 'EQ'), ('!=', 'NE'), ('>=', 'GE'), ('>', 'GT'), ('<=', 'LE'), ('<', 'LT')]: _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), ('>=', 'LT'), ('>', 'LE'), ('<=', 'GT'), ('<', 'GE')]: _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement # Alternative tokens and their replacements. For full list, see section 2.5 # Alternative tokens [lex.digraph] in the C++ standard. # # Digraphs (such as '%:') are not included here since it's a mess to # match those on a word boundary. _ALT_TOKEN_REPLACEMENT = { 'and': '&&', 'bitor': '|', 'or': '||', 'xor': '^', 'compl': '~', 'bitand': '&', 'and_eq': '&=', 'or_eq': '|=', 'xor_eq': '^=', 'not': '!', 'not_eq': '!=' } # Compile regular expression that matches all the above keywords. The "[ =()]" # bit is meant to avoid matching these keywords outside of boolean expressions. # # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') # These constants define types of headers for use with # _IncludeState.CheckNextIncludeOrder(). _C_SYS_HEADER = 1 _CPP_SYS_HEADER = 2 _LIKELY_MY_HEADER = 3 _POSSIBLE_MY_HEADER = 4 _OTHER_HEADER = 5 # These constants define the current inline assembly state _NO_ASM = 0 # Outside of inline assembly block _INSIDE_ASM = 1 # Inside inline assembly block _END_ASM = 2 # Last line of inline assembly block _BLOCK_ASM = 3 # The whole block is an inline assembly block # Match start of assembly blocks _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' r'(?:\s+(volatile|__volatile__))?' r'\s*[{(]') # Match strings that indicate we're working on a C (not C++) file. _SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|' r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))') # Match string that indicates we're working on a Linux Kernel file. _SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)') _regexp_compile_cache = {} # {str, set(int)}: a map from error categories to sets of linenumbers # on which those errors are expected and should be suppressed. _error_suppressions = {} # The root directory used for deriving header guard CPP variable. # This is set by --root flag. _root = None # The top level repository directory. If set, _root is calculated relative to # this directory instead of the directory containing version control artifacts. # This is set by the --repository flag. _repository = None # Files to exclude from linting. This is set by the --exclude flag. _excludes = None # Whether to supress PrintInfo messages _quiet = False # The allowed line length of files. # This is set by --linelength flag. _line_length = 80 try: xrange(1, 0) except NameError: # -- pylint: disable=redefined-builtin xrange = range try: unicode except NameError: # -- pylint: disable=redefined-builtin basestring = unicode = str try: long(2) except NameError: # -- pylint: disable=redefined-builtin long = int if sys.version_info < (3,): # -- pylint: disable=no-member # BINARY_TYPE = str itervalues = dict.itervalues iteritems = dict.iteritems else: # BINARY_TYPE = bytes itervalues = dict.values iteritems = dict.items def unicode_escape_decode(x): if sys.version_info < (3,): return codecs.unicode_escape_decode(x)[0] else: return x # {str, bool}: a map from error categories to booleans which indicate if the # category should be suppressed for every line. _global_error_suppressions = {} def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of line error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) if matched: if matched.group(1): suppressed_line = linenum + 1 else: suppressed_line = linenum category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(suppressed_line) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(suppressed_line) elif category not in _LEGACY_ERROR_CATEGORIES: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category) def ProcessGlobalSuppresions(lines): """Updates the list of global error suppressions. Parses any lint directives in the file that have global effect. Args: lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. """ for line in lines: if _SEARCH_C_FILE.search(line): for category in _DEFAULT_C_SUPPRESSED_CATEGORIES: _global_error_suppressions[category] = True if _SEARCH_KERNEL_FILE.search(line): for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES: _global_error_suppressions[category] = True def ResetNolintSuppressions(): """Resets the set of NOLINT suppressions to empty.""" _error_suppressions.clear() _global_error_suppressions.clear() def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment or global suppression. """ return (_global_error_suppressions.get(category, False) or linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set())) def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s) def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s) def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s) def _IsSourceExtension(s): """File extension (excluding dot) matches a source file extension.""" return s in GetNonHeaderExtensions() class _IncludeState(object): """Tracks line numbers for includes, and the order in which includes appear. include_list contains list of lists of (header, line number) pairs. It's a lists of lists rather than just one flat list to make it easier to update across preprocessor boundaries. Call CheckNextIncludeOrder() once for each header in the file, passing in the type constants defined above. Calls in an illegal order will raise an _IncludeError with an appropriate error message. """ # self._section will move monotonically through this set. If it ever # needs to move backwards, CheckNextIncludeOrder will raise an error. _INITIAL_SECTION = 0 _MY_H_SECTION = 1 _C_SECTION = 2 _CPP_SECTION = 3 _OTHER_H_SECTION = 4 _TYPE_NAMES = { _C_SYS_HEADER: 'C system header', _CPP_SYS_HEADER: 'C++ system header', _LIKELY_MY_HEADER: 'header this file implements', _POSSIBLE_MY_HEADER: 'header this file may implement', _OTHER_HEADER: 'other header', } _SECTION_NAMES = { _INITIAL_SECTION: "... nothing. (This can't be an error.)", _MY_H_SECTION: 'a header this file implements', _C_SECTION: 'C system header', _CPP_SECTION: 'C++ system header', _OTHER_H_SECTION: 'other header', } def __init__(self): self.include_list = [[]] self._section = None self._last_header = None self.ResetSection('') def FindHeader(self, header): """Check if a header has already been included. Args: header: header to check. Returns: Line number of previous occurrence, or -1 if the header has not been seen before. """ for section_list in self.include_list: for f in section_list: if f[0] == header: return f[1] return -1 def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = [] def SetLastHeader(self, header_path): self._last_header = header_path def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower() def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): return False return True def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return '' class _CppLintState(object): """Maintains module-wide state..""" def __init__(self): self.verbose_level = 1 # global setting. self.error_count = 0 # global count of reported errors # filters to apply when emitting error messages self.filters = _DEFAULT_FILTERS[:] # backup of filter list. Used to restore the state after each file. self._filters_backup = self.filters[:] self.counting = 'total' # In what way are we counting errors? self.errors_by_category = {} # string to int dict storing error counts # output format: # "emacs" - format that emacs can parse (default) # "eclipse" - format that eclipse can parse # "vs7" - format that Microsoft Visual Studio 7 can parse # "junit" - format that Jenkins, Bamboo, etc can parse self.output_format = 'emacs' # For JUnit output, save errors and failures until the end so that they # can be written into the XML self._junit_errors = [] self._junit_failures = [] def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] self.AddFilters(filters) def AddFilters(self, filters): """ Adds more filters to the existing list of error-message filters. """ for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:] def RestoreFilters(self): """ Restores filters previously backed up.""" self.filters = self._filters_backup[:] def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {} def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1 def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in sorted(iteritems(self.errors_by_category)): self.PrintInfo('Category \'%s\' errors found: %d\n' % (category, count)) if self.error_count > 0: self.PrintInfo('Total errors found: %d\n' % self.error_count) def PrintInfo(self, message): if not _quiet and self.output_format != 'junit': sys.stderr.write(message) def PrintError(self, message): if self.output_format == 'junit': self._junit_errors.append(message) else: sys.stderr.write(message) def AddJUnitFailure(self, filename, linenum, message, category, confidence): self._junit_failures.append((filename, linenum, message, category, confidence)) def FormatJUnitXML(self): num_errors = len(self._junit_errors) num_failures = len(self._junit_failures) testsuite = xml.etree.ElementTree.Element('testsuite') testsuite.attrib['name'] = 'cpplint' testsuite.attrib['errors'] = str(num_errors) testsuite.attrib['failures'] = str(num_failures) if num_errors == 0 and num_failures == 0: testsuite.attrib['tests'] = str(1) xml.etree.ElementTree.SubElement(testsuite, 'testcase', name='passed') else: testsuite.attrib['tests'] = str(num_errors + num_failures) if num_errors > 0: testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') testcase.attrib['name'] = 'errors' error = xml.etree.ElementTree.SubElement(testcase, 'error') error.text = '\n'.join(self._junit_errors) if num_failures > 0: # Group failures by file failed_file_order = [] failures_by_file = {} for failure in self._junit_failures: failed_file = failure[0] if failed_file not in failed_file_order: failed_file_order.append(failed_file) failures_by_file[failed_file] = [] failures_by_file[failed_file].append(failure) # Create a testcase for each file for failed_file in failed_file_order: failures = failures_by_file[failed_file] testcase = xml.etree.ElementTree.SubElement(testsuite, 'testcase') testcase.attrib['name'] = failed_file failure = xml.etree.ElementTree.SubElement(testcase, 'failure') template = '{0}: {1} [{2}] [{3}]' texts = [template.format(f[1], f[2], f[3], f[4]) for f in failures] failure.text = '\n'.join(texts) xml_decl = '<?xml version="1.0" encoding="UTF-8" ?>\n' return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8') _cpplint_state = _CppLintState() def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format) def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level) def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level) def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters) def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters) def _BackupFilters(): """ Saves the current filter list to backup storage.""" _cpplint_state.BackupFilters() def _RestoreFilters(): """ Restores filters previously backed up.""" _cpplint_state.RestoreFilters() class _FunctionState(object): """Tracks current function name and the number of lines in its body.""" _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. def __init__(self): self.in_a_function = False self.lines_in_function = 0 self.current_function = '' def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1 def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if not self.in_a_function: return if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger)) def End(self): """Stop analyzing function body.""" self.in_a_function = False class _IncludeError(Exception): """Indicates a problem with the include order in a file.""" pass class FileInfo(object): """Provides utility functions for filenames. FileInfo provides easy access to the components of a file's path relative to the project root. """ def __init__(self, filename): self._filename = filename def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/') def RepositoryName(self): r"""FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) # If the user specified a repository path, it exists, and the file is # contained in it, use the specified repository path if _repository: repo = FileInfo(_repository).FullName() root_dir = project_dir while os.path.exists(root_dir): # allow case insensitive compare on Windows if os.path.normcase(root_dir) == os.path.normcase(repo): return os.path.relpath(fullname, root_dir).replace('\\', '/') one_up_dir = os.path.dirname(root_dir) if one_up_dir == root_dir: break root_dir = one_up_dir if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = current_dir = os.path.dirname(fullname) while current_dir != os.path.dirname(current_dir): if (os.path.exists(os.path.join(current_dir, ".git")) or os.path.exists(os.path.join(current_dir, ".hg")) or os.path.exists(os.path.join(current_dir, ".svn"))): root_dir = current_dir current_dir = os.path.dirname(current_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest) def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1] def Extension(self): """File extension - text following the final period, includes that period.""" return self.Split()[2] def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2]) def IsSource(self): """File has a source file extension.""" return _IsSourceExtension(self.Extension()[1:]) def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': _cpplint_state.PrintError('%s(%s): warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'junit': _cpplint_state.AddJUnitFailure(filename, linenum, message, category, confidence) else: final_message = '%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence) sys.stderr.write(final_message) # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') # Match a single C style comment on the same line. _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' # Matches multi-line C style comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + _RE_PATTERN_C_COMMENTS + r'\s+|' + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + _RE_PATTERN_C_COMMENTS + r')') def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '""' # Look for beginning of a raw string, and replace them with # empty strings. This is done in a loop to handle multiple raw # strings on the same line. while delimiter is None: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. # # Once we have matched a raw string, we check the prefix of the # line to make sure that the line is not part of a single line # comment. It's done this way because we remove raw strings # before removing comments as opposed to removing comments # before removing raw strings. This is because there are some # cpplint checks that requires the comments to be preserved, but # we don't want to check comments that are inside raw strings. matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if (matched and not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//', matched.group(1))): delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' else: break lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 4 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments. 2) lines member contains lines without comments. 3) raw_lines member contains all the lines without processing. 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw strings removed. All these members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) self.lines_without_raw_strings = CleanseRawStrings(lines) for linenum in range(len(self.lines_without_raw_strings)): self.lines.append(CleanseComments( self.lines_without_raw_strings[linenum])) elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(elided): return elided # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) # Replace quoted strings and digit separators. Both single quotes # and double quotes are processed in the same loop, otherwise # nested quotes wouldn't work. collapsed = '' while True: # Find the first quote character match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == '"': # Collapse double quoted strings second_quote = tail.find('"') if second_quote >= 0: collapsed += head + '""' elided = tail[second_quote + 1:] else: # Unmatched double quote, don't bother processing the rest # of the line since this is probably a multiline string. collapsed += elided break else: # Found single quote, check nearby text to eliminate digit separators. # # There is no special handling for floating point here, because # the integer/fractional/exponent parts would all be parsed # correctly as long as there are digits on both sides of the # separator. So we are fine as long as we don't see something # like "0.'3" (gcc 4.9.0 will not allow this literal). if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) collapsed += head + match_literal.group(1).replace("'", '') elided = match_literal.group(2) else: second_quote = tail.find('\'') if second_quote >= 0: collapsed += head + "''" elided = tail[second_quote + 1:] else: # Unmatched single quote collapsed += elided break return collapsed def FindEndOfExpressionInLine(line, startpos, stack): """Find the position just after the end of current parenthesized expression. Args: line: a CleansedLines line. startpos: start searching at this position. stack: nesting stack at startpos. Returns: On finding matching end: (index just after matching end, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at end of this line) """ for i in xrange(startpos, len(line)): char = line[i] if char in '([{': # Found start of parenthesized expression, push to expression stack stack.append(char) elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator if stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) elif i > 0 and Search(r'\boperator\s*$', line[0:i]): # operator<, don't add to stack continue else: # Tentative start of template argument list stack.append('<') elif char in ')]}': # Found end of parenthesized expression. # # If we are currently expecting a matching '>', the pending '<' # must have been an operator. Remove them from expression stack. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) if ((stack[-1] == '(' and char == ')') or (stack[-1] == '[' and char == ']') or (stack[-1] == '{' and char == '}')): stack.pop() if not stack: return (i + 1, None) else: # Mismatched parentheses return (-1, None) elif char == '>': # Found potential end of template argument list. # Ignore "->" and operator functions if (i > 0 and (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): continue # Pop the stack if there is a matching '<'. Otherwise, ignore # this '>' since it must be an operator. if stack: if stack[-1] == '<': stack.pop() if not stack: return (i + 1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '>', the matching '<' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) # Did not find end of expression or unbalanced parentheses on this line return (-1, stack) def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1) def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack) def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if line[pos] not in ')}]>': return (line, 0, -1) # Check last line (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while stack and linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) if start_pos > -1: return (line, linenum, start_pos) # Did not find start of expression before beginning of file, give up return (line, 0, -1) def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in range(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"') def GetIndentLevel(line): """Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero. """ indent = Match(r'^( *)\S', line) if indent: return len(indent.group(1)) else: return 0 def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) # Replace 'c++' with 'cpp'. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: suffix = os.sep # On Windows using directory separator will leave us with # "bogus escape error" unless we properly escape regex. if suffix == '\\': suffix += '\\' file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root) return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return # Allow pragma once instead of header guards for i in raw_lines: if Search(r'^\s*#pragma\s+once', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar) def CheckHeaderFileIncluded(filename, include_state, error): """Logs an error if a source file does not include its header.""" # Do not check test files fileinfo = FileInfo(filename) if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): return for ext in GetHeaderExtensions(): basefilename = filename[0:len(filename) - len(fileinfo.Extension())] headerfile = basefilename + '.' + ext if not os.path.exists(headerfile): continue headername = FileInfo(headerfile).RepositoryName() first_include = None for section_list in include_state.include_list: for f in section_list: if headername in f[0] or f[0] in headername: return if not first_include: first_include = f[1] error(filename, first_include, 'build/include', 5, '%s should include its header file %s' % (fileinfo.RepositoryName(), headername)) def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if unicode_escape_decode('\ufffd') in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.') # (non-threadsafe name, thread-safe alternative, validation pattern) # # The validation pattern is used to eliminate false positives such as: # _rand(); // false positive due to substring match. # ->rand(); // some member function rand(). # ACMRandom rand(seed); // some variable named rand. # ISAACRandom rand(); // another variable named rand. # # Basically we require the return value of these functions to be used # in some expression context on the same line by matching on some # operator before the function name. This eliminates constructors and # member function calls. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' _THREADING_LIST = ( ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), ('strtok(', 'strtok_r(', _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: # Additional pattern matching check to confirm that this is the # function we are looking for if Search(pattern, line): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_func + '...) instead of ' + single_thread_func + '...) for improved thread safety.') def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') def IsMacroDefinition(clean_lines, linenum): if Search(r'^#define', clean_lines[linenum]): return True if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): return True return False def IsForwardClassDeclaration(clean_lines, linenum): return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, linenum, seen_open_brace): self.starting_linenum = linenum self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM self.check_namespace_indentation = False def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def IsBlockInfo(self): """Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes. """ return self.__class__ == _BlockInfo class _ExternCInfo(_BlockInfo): """Stores information about an 'extern "C"' block.""" def __init__(self, linenum): _BlockInfo.__init__(self, linenum, True) class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, linenum, False) self.name = name self.is_derived = False self.check_namespace_indentation = True if class_or_struct == 'struct': self.access = 'public' self.is_struct = True else: self.access = 'private' self.is_struct = False # Remember initial indentation level for this class. Using raw_lines here # instead of elided to account for leading comments. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True def CheckEnd(self, filename, clean_lines, linenum, error): # If there is a DISALLOW macro, it should appear near the end of # the class. seen_last_thing_in_class = False for i in xrange(linenum - 1, self.starting_linenum, -1): match = Search( r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + self.name + r'\)', clean_lines.elided[i]) if match: if seen_last_thing_in_class: error(filename, i, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') break if not Match(r'^\s*$', clean_lines.elided[i]): seen_last_thing_in_class = True # Check that closing brace is aligned with beginning of the class. # Only do this if the closing brace is indented by only whitespaces. # This means we will not check single-line class definitions. indent = Match(r'^( *)\}', clean_lines.elided[linenum]) if indent and len(indent.group(1)) != self.class_indent: if self.is_struct: parent = 'struct ' + self.name else: parent = 'class ' + self.name error(filename, linenum, 'whitespace/indent', 3, 'Closing brace should be aligned with beginning of %s' % parent) class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, linenum, False) self.name = name or '' self.check_namespace_indentation = True def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Top of the previous stack before each Update(). # # Because the nesting_stack is updated at the end of each line, we # had to do some convoluted checks to find out what is the current # scope at the beginning of the line. This check is simplified by # saving the previous top of nesting stack. # # We could save the full stack, but we only need the top. Copying # the full nesting stack would slow down cpplint by ~10%. self.previous_stack_top = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def InExternC(self): """Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ExternCInfo) def InClassDeclaration(self): """Check if we are currently one level inside a class or struct declaration. Returns: True if top of the stack is a class/struct, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ClassInfo) def InAsmBlock(self): """Check if we are currently one level inside an inline ASM block. Returns: True if the top of the stack is a block containing inline ASM. """ return self.stack and self.stack[-1].inline_asm != _NO_ASM def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass # TODO(unknown): Update() is too long, but we will refactor later. def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo(linenum)) else: self.stack.append(_BlockInfo(linenum, True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage-class specifier (static, extern, typedef, etc) should be ' 'at the beginning of the declaration.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. explicit_constructor_match = Match( r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 variadic_args = [arg for arg in constructor_args if '&&...' in arg] defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1) or # variadic arguments with zero or one argument (len(constructor_args) <= 2 and len(variadic_args) >= 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args or variadic_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.') def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error): is_namespace_indent_item = ( len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and nesting_state.previous_stack_top == nesting_state.stack[-2]) if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, clean_lines.elided, line): CheckItemIndentationInNamespace(filename, clean_lines.elided, line, error) def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in range(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. # # Also skip blank line checks for 'extern "C"' blocks, which are formatted # like namespaces. if (IsBlankLine(line) and not nesting_state.InNamespaceBody() and not nesting_state.InExternC()): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, check comments next_line_start = 0 if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] next_line_start = len(next_line) - len(next_line.lstrip()) CheckComment(line, filename, linenum, next_line_start, error) # get rid of comments and strings line = clean_lines.elided[linenum] # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'return []() {};' if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search(r'for *\(.*[^:]:[^: ]', line) or Search(r'for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckOperatorSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around operators. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Don't try to do spacing checks for operator methods. Do this by # replacing the troublesome characters with something else, # preserving column position for all other characters. # # The replacement is done repeatedly to avoid false positives from # operators that call operators. while True: match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) if match: line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) else: break # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if ((Search(r'[\w.]=', line) or Search(r'=[\w.]', line)) and not Search(r'\b(if|while|for) ', line) # Operators taken from [lex.operators] in C++11 standard. and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) and not Search(r'operator=', line)): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. # # If the operator is followed by a comma, assume it's be used in a # macro context and don't do any checks. This avoids false # positives. # # Note that && is not included here. This is because there are too # many false positives due to RValue references. match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) elif not Match(r'#.*include', line): # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Match(r'^(.*[^\s<])<[^\s=<,]', line) if match: (_, _, end_pos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if end_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) if match: (_, _, start_pos) = ReverseCloseExpression( clean_lines, linenum, len(match.group(1))) if start_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # # We also allow operators following an opening parenthesis, since # those tend to be macros that deal with operators. match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) def CheckParenthesisSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around parentheses. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # No spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) def CheckCommaSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas and semicolons. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.lines_without_raw_strings line = clean_lines.elided[linenum] # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and Search(r',[^,\s]', raw[linenum])): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') def _IsType(clean_lines, nesting_state, expr): """Check if expression looks like a type name, returns true if so. Args: clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. expr: The expression to check. Returns: True, if token looks like a type. """ # Keep only the last token in the expression last_word = Match(r'^.*(\b\S+)$', expr) if last_word: token = last_word.group(1) else: token = expr # Match native types and stdint types if _TYPES.match(token): return True # Try a bit harder to match templated types. Walk up the nesting # stack until we find something that resembles a typename # declaration for what we are looking for. typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) + r'\b') block_index = len(nesting_state.stack) - 1 while block_index >= 0: if isinstance(nesting_state.stack[block_index], _NamespaceInfo): return False # Found where the opening brace is. We want to scan from this # line up to the beginning of the function, minus a few lines. # template <typename Type1, // stop scanning here # ...> # class C # : public ... { // start scanning here last_line = nesting_state.stack[block_index].starting_linenum next_block_start = 0 if block_index > 0: next_block_start = nesting_state.stack[block_index - 1].starting_linenum first_line = last_line while first_line >= next_block_start: if clean_lines.elided[first_line].find('template') >= 0: break first_line -= 1 if first_line < next_block_start: # Didn't find any "template" keyword before reaching the next block, # there are probably no template things to check for this block block_index -= 1 continue # Look for typename in the specified range for i in xrange(first_line, last_line + 1, 1): if Search(typename_pattern, clean_lines.elided[i]): return True block_index -= 1 return False def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for horizontal spacing near commas. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces when they are delimiting blocks, classes, namespaces etc. # And since you should never have braces at the beginning of a line, # this is an easy test. Except that braces used for initialization don't # follow the same rule; we often don't want spaces before those. match = Match(r'^(.*[^ ({>]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # ternary = expr ? new type{} : nullptr; # OuterTemplate<InnerTemplateConstructor<Type>{}> # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<>]:". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. leading_text = match.group(1) (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] # We also suppress warnings for `uint64_t{expression}` etc., as the style # guide recommends brace initialization for integral types to avoid # overflow/truncation. if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text) and not _IsType(clean_lines, nesting_state, leading_text)): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1)) def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1) def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. We also allow a brace on the # following line if it is part of an array initialization and would not fit # within the 80 character limit of the preceding line. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline) and not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'else if\s*\(', line): # could be multi-line if brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) brace_on_right = endline[endpos:].find('{') != -1 if brace_on_left != brace_on_right: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Check single-line if/else bodies. The style guide says 'curly braces are not # required for single-line statements'. We additionally allow multi-line, # single statements, but we reject anything with more than one semicolon in # it. This means that the first semicolon after the if should be at the end of # its line, and the line after that should have an indent level equal to or # lower than the if. We also check for ambiguous if/else nesting without # braces. if_else_match = Search(r'\b(if\s*\(|else\b)', line) if if_else_match and not Match(r'\s*#', line): if_indent = GetIndentLevel(line) endline, endlinenum, endpos = line, linenum, if_else_match.end() if_match = Search(r'\bif\s*\(', line) if if_match: # This could be a multiline if condition, so find the end first. pos = if_match.end() - 1 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) # Check for an opening brace, either directly after the if or on the next # line. If found, this isn't a single-statement conditional. if (not Match(r'\s*{', endline[endpos:]) and not (Match(r'\s*$', endline[endpos:]) and endlinenum < (len(clean_lines.elided) - 1) and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): while (endlinenum < len(clean_lines.elided) and ';' not in clean_lines.elided[endlinenum][endpos:]): endlinenum += 1 endpos = 0 if endlinenum < len(clean_lines.elided): endline = clean_lines.elided[endlinenum] # We allow a mix of whitespace and closing braces (e.g. for one-liner # methods) and a single \ after the semicolon (for macros) endpos = endline.find(';') if not Match(r';[\s}]*(\\?)$', endline[endpos:]): # Semicolon isn't the last character, there's something trailing. # Output a warning if the semicolon is not contained inside # a lambda expression. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', endline): error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') elif endlinenum < len(clean_lines.elided) - 1: # Make sure the next line is dedented next_line = clean_lines.elided[endlinenum + 1] next_indent = GetIndentLevel(next_line) # With ambiguous nested if statements, this will error out on the # if that *doesn't* match the else, regardless of whether it's the # inner one or outer one. if (if_match and Match(r'\s*else\b', next_line) and next_indent != if_indent): error(filename, linenum, 'readability/braces', 4, 'Else clause should be indented at the same level as if. ' 'Ambiguous nested if/else chains require braces.') elif next_indent > if_indent: error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') def CheckTrailingSemicolon(filename, clean_lines, linenum, error): """Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on # - Compound literals # - Lambdas # - alignas specifier with anonymous structs # - decltype closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix) func = Match(r'^(.*\])\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or Search(r'\bdecltype$', line_prefix) or Search(r'\s+=\s*$', line_prefix)): match = None if (match and opening_parenthesis[1] > 1 and Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): # Multi-line lambda-expression match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. # We need to check the line forward for NOLINT raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1, error) ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, error) error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }") def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression. (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') # Check for if statements that have completely empty bodies (no comments) # and no else clauses. if end_pos >= 0 and matched.group(1) == 'if': # Find the position of the opening { for the if statement. # Return without logging an error if it has no brackets. opening_linenum = end_linenum opening_line_fragment = end_line[end_pos:] # Loop until EOF or find anything that's not whitespace or opening {. while not Search(r'^\s*\{', opening_line_fragment): if Search(r'^(?!\s*$)', opening_line_fragment): # Conditional has no brackets. return opening_linenum += 1 if opening_linenum == len(clean_lines.elided): # Couldn't find conditional's opening { or any code before EOF. return opening_line_fragment = clean_lines.elided[opening_linenum] # Set opening_line (opening_line_fragment may not be entire opening line). opening_line = clean_lines.elided[opening_linenum] # Find the position of the closing }. opening_pos = opening_line_fragment.find('{') if opening_linenum == end_linenum: # We need to make opening_pos relative to the start of the entire line. opening_pos += end_pos (closing_line, closing_linenum, closing_pos) = CloseExpression( clean_lines, opening_linenum, opening_pos) if closing_pos < 0: return # Now construct the body of the conditional. This consists of the portion # of the opening line after the {, all lines until the closing line, # and the portion of the closing line before the }. if (clean_lines.raw_lines[opening_linenum] != CleanseComments(clean_lines.raw_lines[opening_linenum])): # Opening line ends with a comment, so conditional isn't empty. return if closing_linenum > opening_linenum: # Opening line after the {. Ignore comments here since we checked above. bodylist = list(opening_line[opening_pos+1:]) # All lines until closing line, excluding closing line, with comments. bodylist.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum]) # Closing line before the }. Won't (and can't) have comments. bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1]) body = '\n'.join(bodylist) else: # If statement has brackets and fits on a single line. body = opening_line[opening_pos+1:closing_pos-1] # Check if the body is empty if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body): return # The body is empty. Now make sure there's not an else clause. current_linenum = closing_linenum current_line_fragment = closing_line[closing_pos:] # Loop until EOF or find anything that's not whitespace or else clause. while Search(r'^\s*$|^(?=\s*else)', current_line_fragment): if Search(r'^(?=\s*else)', current_line_fragment): # Found an else clause, so don't log an error. return current_linenum += 1 if current_linenum == len(clean_lines.elided): break current_line_fragment = clean_lines.elided[current_linenum] # The body is empty and there's no else clause until EOF or other code. error(filename, end_linenum, 'whitespace/empty_if_body', 4, ('If statement had no body and no else clause')) def FindCheckMacro(line): """Find a replaceable CHECK-like macro. Args: line: line to search on. Returns: (macro name, start position), or (None, -1) if no replaceable macro is found. """ for macro in _CHECK_MACROS: i = line.find(macro) if i >= 0: # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) if not matched: continue return (macro, len(matched.group(1))) return (None, -1) def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided (check_macro, start_pos) = FindCheckMacro(lines[linenum]) if not check_macro: return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return # If the check macro is followed by something other than a # semicolon, assume users will log their own custom error messages # and don't suggest any replacements. if not Match(r'\s*;', last_line[end_pos:]): return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator)) def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line) def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] prev = raw_lines[linenum - 1] if linenum > 0 else '' if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' classinfo = nesting_state.InnermostClass() initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 # There are certain situations we allow one space, notably for # section labels, and also lines containing multi-line raw strings. # We also don't check for lines that look like continuation lines # (of lines ending in double quotes, commas, equals, or angle brackets) # because the rules for how to indent those are non-trivial. if (not Search(r'[",=><] *$', prev) and (initial_spaces == 1 or initial_spaces == 3) and not Match(scope_or_label_pattern, cleansed_line) and not (clean_lines.raw_lines[linenum] != line and Match(r'^\s*""', line))): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # Check if the line is a header guard. is_header_guard = False if file_extension in GetHeaderExtensions(): cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. # # Doxygen documentation copying can get pretty long when using an overloaded # function declaration if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^\s*//\s*[^\s]*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and not Match(r'^\s*/// [@\\](copydoc|copydetails|copybrief) .*$', line)): line_width = GetLineWidth(line) if line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # allow simple single line lambdas not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}\n\r]*\}', line) and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckTrailingSemicolon(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckOperatorSpacing(filename, clean_lines, linenum, error) CheckParenthesisSpacing(filename, clean_lines, linenum, error) CheckCommaSpacing(filename, clean_lines, linenum, error) CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error) CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') # Matches the first component of a filename delimited by -s and _s. That is: # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in itertools.chain( ('%s.%s' % (test_suffix.lstrip('_'), ext) for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())), ('%s.%s' % (suffix, ext) for suffix, ext in itertools.product(['inl', 'imp', 'internal'], GetHeaderExtensions()))): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0] def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS # Headers with C++ extensions shouldn't be considered C system headers if is_system and os.path.splitext(include)[1] in ['.hpp', '.hxx', '.h++']: is_system = False if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) target_dir_pub = os.path.normpath(target_dir + '/../public') target_dir_pub = target_dir_pub.replace('\\', '/') if target_base == include_base and ( include_dir == target_dir or include_dir == target_dir_pub): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" # Only do this check if the included header follows google naming # conventions. If not, assume that it's a 3rd party API that # requires special include conventions. # # We also make an exception for Lua headers, which follow google # naming convention but not the include convention. match = Match(r'#include\s*"([^/]+\.h)"', line) if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): error(filename, linenum, 'build/include_subdir', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') duplicate_line = include_state.FindHeader(include) if duplicate_line >= 0: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, duplicate_line)) return for extension in GetNonHeaderExtensions(): if (include.endswith('.' + extension) and os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): error(filename, linenum, 'build/include', 4, 'Do not include .' + extension + ' files from other packages') return if not _THIRD_PARTY_HEADERS_PATTERN.match(include): include_state.include_list[-1].append((include, linenum)) # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(unknown): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(itervalues(matching_punctuation)) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1] # Patterns for matching call-by-reference parameters. # # Supports nested templates up to 2 levels deep using this messy pattern: # < (?: < (?: < [^<>]* # > # | [^<>] )* # > # | [^<>] )* # > _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* _RE_PATTERN_TYPE = ( r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' r'(?:\w|' r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' r'::)+') # A call-by-reference parameter ends with '& identifier'. _RE_PATTERN_REF_PARAM = re.compile( r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') # A call-by-const-reference parameter either ends with 'const& identifier' # or looks like 'const type& identifier' when 'type' is atomic. _RE_PATTERN_CONST_REF_PARAM = ( r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') # Stream types. _RE_PATTERN_REF_STREAM_PARAM = ( r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')') def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) if match: include_state.ResetSection(match.group(1)) # Perform other checks now that we are sure that this is not an include line CheckCasts(filename, clean_lines, linenum, error) CheckGlobalStatic(filename, clean_lines, linenum, error) CheckPrintf(filename, clean_lines, linenum, error) if file_extension in GetHeaderExtensions(): # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes declare or disable copy/assign # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(unknown): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): if Search(r'\bliterals\b', line): error(filename, linenum, 'build/namespaces_literals', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') else: error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension in GetHeaderExtensions() and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.') def CheckGlobalStatic(filename, clean_lines, linenum, error): """Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Match two lines at a time to support multiline declarations if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): line += clean_lines.elided[linenum + 1].strip() # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access, and # also because globals can be destroyed when some threads are still running. # TODO(unknown): Generalize this to also find static unique_ptr instances. # TODO(unknown): File bugs for clang-tidy to find these. match = Match( r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +' r'([a-zA-Z0-9_:]+)\b(.*)', line) # Remove false positives: # - String pointers (as opposed to values). # string *pointer # const string *pointer # string const *pointer # string *const pointer # # - Functions and template specializations. # string Function<Type>(... # string Class<Type>::Method(... # # - Operators. These are matched separately because operator names # cross non-word boundaries, and trying to match both operators # and functions at the same time would decrease accuracy of # matching identifiers. # string Class::operator*() if (match and not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and not Search(r'\boperator\W', line) and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))): if Search(r'\bconst\b', line): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string ' 'instead: "%schar%s %s[]".' % (match.group(1), match.group(2) or '', match.group(3))) else: error(filename, linenum, 'runtime/string', 4, 'Static/global string variables are not permitted.') if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') def CheckPrintf(filename, clean_lines, linenum, error): """Check for printf related issues. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\s*\(', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\s*\(', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) def IsDerivedFunction(clean_lines, linenum): """Check if current line contains an inherited function. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains a function with "override" virt-specifier. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) if match: # Look for "override" after the matching closing parenthesis line, _, closing_paren = CloseExpression( clean_lines, i, len(match.group(1))) return (closing_paren >= 0 and Search(r'\boverride\b', line[closing_paren:])) return False def IsOutOfLineMethodDefinition(clean_lines, linenum): """Check if current line contains an out-of-line method definition. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains an out-of-line method definition. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None return False def IsInitializerList(clean_lines, linenum): """Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise. """ for i in xrange(linenum, 1, -1): line = clean_lines.elided[i] if i == linenum: remove_function_body = Match(r'^(.*)\{\s*$', line) if remove_function_body: line = remove_function_body.group(1) if Search(r'\s:\s*\w+[({]', line): # A lone colon tend to indicate the start of a constructor # initializer list. It could also be a ternary operator, which # also tend to appear in constructor initializer lists as # opposed to parameter lists. return True if Search(r'\}\s*,\s*$', line): # A closing brace followed by a comma is probably the end of a # brace-initialized member in constructor initializer list. return True if Search(r'[{};]\s*$', line): # Found one of the following: # - A closing brace or semicolon, probably the end of the previous # function. # - An opening brace, probably the start of current class or namespace. # # Current line is probably not inside an initializer list since # we saw one of those things without seeing the starting colon. return False # Got to the beginning of the file without seeing the start of # constructor initializer list. return False def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Don't warn on out-of-line method definitions, as we would warn on the # in-line declaration, if it isn't marked with 'override'. if IsOutOfLineMethodDefinition(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter)) def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match: # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old style cast. # If we see those, don't issue warnings for deprecated casts. remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): return False # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True def ExpectingFunctionArgs(clean_lines, linenum): """Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types. """ line = clean_lines.elided[linenum] return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1])))) _HEADERS_CONTAINING_TEMPLATES = ( ('<deque>', ('deque',)), ('<functional>', ('unary_function', 'binary_function', 'plus', 'minus', 'multiplies', 'divides', 'modulus', 'negate', 'equal_to', 'not_equal_to', 'greater', 'less', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_not', 'unary_negate', 'not1', 'binary_negate', 'not2', 'bind1st', 'bind2nd', 'pointer_to_unary_function', 'pointer_to_binary_function', 'ptr_fun', 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', 'mem_fun_ref_t', 'const_mem_fun_t', 'const_mem_fun1_t', 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', 'mem_fun_ref', )), ('<limits>', ('numeric_limits',)), ('<list>', ('list',)), ('<map>', ('map', 'multimap',)), ('<memory>', ('allocator',)), ('<queue>', ('queue', 'priority_queue',)), ('<set>', ('set', 'multiset',)), ('<stack>', ('stack',)), ('<string>', ('char_traits', 'basic_string',)), ('<tuple>', ('tuple',)), ('<utility>', ('pair',)), ('<vector>', ('vector',)), # gcc extensions. # Note: std::hash is their hash, ::hash is our hash ('<hash_map>', ('hash_map', 'hash_multimap',)), ('<hash_set>', ('hash_set', 'hash_multiset',)), ('<slist>', ('slist',)), ) _HEADERS_MAYBE_TEMPLATES = ( ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort', 'transform', )), ('<utility>', ('swap',)), ) _RE_PATTERN_STRING = re.compile(r'\bstring\b') _re_pattern_headers_maybe_templates = [] for _header, _templates in _HEADERS_MAYBE_TEMPLATES: for _template in _templates: # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or # type::max(). _re_pattern_headers_maybe_templates.append( (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), _template, _header)) # Other scripts may reach in and modify this pattern. _re_pattern_templates = [] for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: for _template in _templates: _re_pattern_templates.append( (re.compile(r'(\<|\b)' + _template + r'\s*\<'), _template + '<>', _header)) def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ fileinfo_cc = FileInfo(filename_cc) if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): return (False, '') fileinfo_h = FileInfo(filename_h) if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions(): return (False, '') filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) if matched_test_suffix: filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') filename_h = filename_h[:-(len(fileinfo_h.Extension()))] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path def UpdateIncludeState(filename, include_dict, io=codecs): """Fill up the include_dict with new includes found from the file. Args: filename: the name of the header to read. include_dict: a dictionary in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) include_dict.setdefault(include, linenum) return True def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in range(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_headers_maybe_templates: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's flatten the include_state include_list and copy it into a dictionary. include_dict = dict([item for sublist in include_state.include_list for item in sublist]) # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_dict is modified during iteration, so we iterate over a copy of # the keys. header_keys = list(include_dict.keys()) for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_dict, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if not header_found: for extension in GetNonHeaderExtensions(): if filename.endswith('.' + extension): return # All the lines have been processed, report the errors found. for required_header_unstripped in sorted(required, key=required.__getitem__): template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_dict: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template) _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly') def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for "virtual" on current line. line = clean_lines.elided[linenum] virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) if not virtual: return # Ignore "virtual" keywords that are near access-specifiers. These # are only used in class base-specifier and do not apply to member # functions. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or Match(r'^\s+(public|protected|private)\b', virtual.group(3))): return # Ignore the "virtual" keyword from virtual base classes. Usually # there is a column on the same line in these cases (virtual base # classes are rare in google3 because multiple inheritance is rare). if Match(r'^.*[^:]:[^:].*$', line): return # Look for the next opening parenthesis. This is the start of the # parameter list (possibly on the next line shortly after virtual). # TODO(unknown): doesn't work if there are virtual functions with # decltype() or other things that use parentheses, but csearch suggests # that this is rare. end_col = -1 end_line = -1 start_col = len(virtual.group(2)) for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): line = clean_lines.elided[start_line][start_col:] parameter_list = Match(r'^([^(]*)\(', line) if parameter_list: # Match parentheses to find the end of the parameter list (_, end_line, end_col) = CloseExpression( clean_lines, start_line, start_col + len(parameter_list.group(1))) break start_col = 0 if end_col < 0: return # Couldn't find end of parameter list, give up # Look for "override" or "final" after the parameter list # (possibly on the next few lines). for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): line = clean_lines.elided[i][end_col:] match = Search(r'\b(override|final)\b', line) if match: error(filename, linenum, 'readability/inheritance', 4, ('"virtual" is redundant since function is ' 'already declared as "%s"' % match.group(1))) # Set end_col to check whole lines after we are done with the # first line. end_col = 0 if Search(r'[^\w]\s*$', line): break def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): """Check if line contains a redundant "override" or "final" virt-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for closing parenthesis nearby. We need one to confirm where # the declarator ends and where the virt-specifier starts to avoid # false positives. line = clean_lines.elided[linenum] declarator_end = line.rfind(')') if declarator_end >= 0: fragment = line[declarator_end:] else: if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: fragment = line else: return # Check that at most one of "override" or "final" is present, not both if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): error(filename, linenum, 'readability/inheritance', 4, ('"override" is redundant since function is ' 'already declared as "final"')) # Returns true if we are at a new block, and it is directly # inside of a namespace. def IsBlockInNameSpace(nesting_state, is_forward_declaration): """Checks that the new block is directly in a namespace. Args: nesting_state: The _NestingState object that contains info about our state. is_forward_declaration: If the class is a forward declared class. Returns: Whether or not the new block is directly in a namespace. """ if is_forward_declaration: return len(nesting_state.stack) >= 1 and ( isinstance(nesting_state.stack[-1], _NamespaceInfo)) return (len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.stack[-2], _NamespaceInfo)) def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, raw_lines_no_comments, linenum): """This method determines if we should apply our namespace indentation check. Args: nesting_state: The current nesting state. is_namespace_indent_item: If we just put a new class on the stack, True. If the top of the stack is not a class, or we did not recently add the class, False. raw_lines_no_comments: The lines without the comments. linenum: The current line number we are processing. Returns: True if we should apply our namespace indentation check. Currently, it only works for classes and namespaces inside of a namespace. """ is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, linenum) if not (is_namespace_indent_item or is_forward_declaration): return False # If we are in a macro, we do not want to check the namespace indentation. if IsMacroDefinition(raw_lines_no_comments, linenum): return False return IsBlockInNameSpace(nesting_state, is_forward_declaration) # Call this method if the line is directly inside of a namespace. # If the line above is blank (excluding comments) or the start of # an inner namespace, it cannot be indented. def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, error): line = raw_lines_no_comments[linenum] if Match(r'^\s+', line): error(filename, linenum, 'runtime/indentation_namespace', 4, 'Do not indent within a namespace') def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=None): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error) if nesting_state.InAsmBlock(): return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) CheckRedundantVirtual(filename, clean_lines, line, error) CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) if extra_check_functions: for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) def FlagCxx11Features(filename, clean_lines, linenum, error): """Flag those c++11 features that we only allow in certain places. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) # Flag unapproved C++ TR1 headers. if include and include.group(1).startswith('tr1/'): error(filename, linenum, 'build/c++tr1', 5, ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1)) # Flag unapproved C++11 headers. if include and include.group(1) in ('cfenv', 'fenv.h', 'ratio', 'regex', 'system_error', ): error(filename, linenum, 'build/c++11', 5, ('<%s> is an unapproved C++11 header.') % include.group(1)) # The only place where we need to worry about C++11 keywords and library # features in preprocessor directives is in macro definitions. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return # These are classes and free functions. The classes are always # mentioned as std::*, but we only catch the free functions if # they're not found by ADL. They're alphabetical by header. for top_name in ( # type_traits 'alignment_of', 'aligned_union', ): if Search(r'\bstd::%s\b' % top_name, line): error(filename, linenum, 'build/c++11', 5, ('std::%s is an unapproved C++11 class or function. Send c-style ' 'an example of where it would make your code more readable, and ' 'they may let you use it.') % top_name) def FlagCxx14Features(filename, clean_lines, linenum, error): """Flag those C++14 features that we restrict. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) # Flag unapproved C++14 headers. if include and include.group(1) in ('scoped_allocator', 'shared_mutex'): error(filename, linenum, 'build/c++14', 5, ('<%s> is an unapproved C++14 header.') % include.group(1)) def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=None): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) ProcessGlobalSuppresions(lines) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) if file_extension in GetHeaderExtensions(): CheckForHeaderGuard(filename, clean_lines, error) for line in range(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) FlagCxx11Features(filename, clean_lines, line, error) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # Check that the .cc file has included its header if it exists. if _IsSourceExtension(file_extension): CheckHeaderFileIncluded(filename, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error) def ProcessConfigOverrides(filename): """ Loads the configuration files and processes the config overrides. Args: filename: The name of the file being processed by the linter. Returns: False if the current |filename| should not be processed further. """ abs_filename = os.path.abspath(filename) cfg_filters = [] keep_looking = True while keep_looking: abs_path, base_name = os.path.split(abs_filename) if not base_name: break # Reached the root directory. cfg_file = os.path.join(abs_path, "CPPLINT.cfg") abs_filename = abs_path if not os.path.isfile(cfg_file): continue try: with open(cfg_file) as file_handle: for line in file_handle: line, _, _ = line.partition('#') # Remove comments. if not line.strip(): continue name, _, val = line.partition('=') name = name.strip() val = val.strip() if name == 'set noparent': keep_looking = False elif name == 'filter': cfg_filters.append(val) elif name == 'exclude_files': # When matching exclude_files pattern, use the base_name of # the current file name or the directory name we are processing. # For example, if we are checking for lint errors in /foo/bar/baz.cc # and we found the .cfg file at /foo/CPPLINT.cfg, then the config # file's "exclude_files" filter is meant to be checked against "bar" # and not "baz" nor "bar/baz.cc". if base_name: pattern = re.compile(val) if pattern.match(base_name): _cpplint_state.PrintInfo('Ignoring "%s": file excluded by ' '"%s". File path component "%s" matches pattern "%s"\n' % (filename, cfg_file, base_name, val)) return False elif name == 'linelength': global _line_length try: _line_length = int(val) except ValueError: _cpplint_state.PrintError('Line length must be numeric.') elif name == 'extensions': global _valid_extensions try: extensions = [ext.strip() for ext in val.split(',')] _valid_extensions = set(extensions) except ValueError: sys.stderr.write('Extensions should be a comma-separated list of values;' 'for example: extensions=hpp,cpp\n' 'This could not be parsed: "%s"' % (val,)) elif name == 'headers': global _header_extensions try: extensions = [ext.strip() for ext in val.split(',')] _header_extensions = set(extensions) except ValueError: sys.stderr.write('Extensions should be a comma-separated list of values;' 'for example: extensions=hpp,cpp\n' 'This could not be parsed: "%s"' % (val,)) elif name == 'root': global _root _root = val else: _cpplint_state.PrintError( 'Invalid configuration option (%s) in file %s\n' % (name, cfg_file)) except IOError: _cpplint_state.PrintError( "Skipping config file '%s': Can't open for reading\n" % cfg_file) keep_looking = False # Apply all the accumulated filters in reverse order (top-level directory # config options having the least priority). for cfg_filter in reversed(cfg_filters): _AddFilters(cfg_filter) return True def ProcessFile(filename, vlevel, extra_check_functions=None): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: _cpplint_state.PrintError( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in GetAllExtensions(): # bazel 0.5.1> uses four distinct generated files that gives a warning # we suppress the warning for these files bazel_gen_files = set([ "external/local_config_cc/libtool", "external/local_config_cc/make_hashed_objlist.py", "external/local_config_cc/wrapped_ar", "external/local_config_cc/wrapped_clang", "external/local_config_cc/xcrunwrapper.sh", ]) if not filename in bazel_gen_files: _cpplint_state.PrintError('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(GetAllExtensions()))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') _RestoreFilters() def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(0) def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0) def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'repository=', 'linelength=', 'extensions=', 'exclude=', 'headers=', 'quiet', 'recursive']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' recursive = False for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse', 'junit'): PrintUsage('The only allowed output formats are emacs, vs7, eclipse ' 'and junit.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--repository': global _repository _repository = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--exclude': global _excludes if not _excludes: _excludes = set() _excludes.update(glob.glob(val)) elif opt == '--extensions': global _valid_extensions try: _valid_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma seperated list.') elif opt == '--headers': global _header_extensions try: _header_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma seperated list.') elif opt == '--recursive': recursive = True elif opt == '--quiet': global _quiet _quiet = True if not filenames: PrintUsage('No files were specified.') if recursive: filenames = _ExpandDirectories(filenames) if _excludes: filenames = _FilterExcludedFiles(filenames) _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames def _ExpandDirectories(filenames): """Searches a list of filenames and replaces directories in the list with all files descending from those directories. Files with extensions not in the valid extensions list are excluded. Args: filenames: A list of files or directories Returns: A list of all files that are members of filenames or descended from a directory in filenames """ expanded = set() for filename in filenames: if not os.path.isdir(filename): expanded.add(filename) continue for root, _, files in os.walk(filename): for loopfile in files: fullname = os.path.join(root, loopfile) if fullname.startswith('.' + os.path.sep): fullname = fullname[len('.' + os.path.sep):] expanded.add(fullname) filtered = [] for filename in expanded: if os.path.splitext(filename)[1][1:] in GetAllExtensions(): filtered.append(filename) return filtered def _FilterExcludedFiles(filenames): """Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory """ exclude_paths = [os.path.abspath(f) for f in _excludes] return [f for f in filenames if os.path.abspath(f) not in exclude_paths] def main(): filenames = ParseArguments(sys.argv[1:]) backup_err = sys.stderr try: # Change stderr to write with replacement characters so we don't die # if we try to print something containing non-ASCII characters. sys.stderr = codecs.StreamReader(sys.stderr, 'replace') _cpplint_state.ResetErrorCounts() for filename in filenames: ProcessFile(filename, _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() if _cpplint_state.output_format == 'junit': sys.stderr.write(_cpplint_state.FormatJUnitXML()) finally: sys.stderr = backup_err sys.exit(_cpplint_state.error_count > 0) if __name__ == '__main__': main()
38.511588
97
0.653316
79516ddc8cf4068672a8914c2961c1ea4e19bf9d
4,293
py
Python
binaries/build_wheels.py
meryacine/shaka-streamer
7b7e90143f531c52d96c162cc7393862db0830b7
[ "Apache-2.0" ]
154
2019-08-29T16:53:24.000Z
2022-02-25T00:29:56.000Z
binaries/build_wheels.py
meryacine/shaka-streamer
7b7e90143f531c52d96c162cc7393862db0830b7
[ "Apache-2.0" ]
101
2019-08-30T17:34:51.000Z
2022-03-02T18:46:22.000Z
binaries/build_wheels.py
meryacine/shaka-streamer
7b7e90143f531c52d96c162cc7393862db0830b7
[ "Apache-2.0" ]
56
2019-09-08T17:47:22.000Z
2022-02-23T17:35:11.000Z
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A script that downloads ffmpeg, ffprobe, and packager static builds for all the platforms we build for and then builds distribution wheels for them. """ import os import shutil import subprocess import urllib.request import streamer_binaries # Version constants. # Change to download different versions. FFMPEG_VERSION = 'n4.4-2' PACKAGER_VERSION = 'v2.6.1' # A map of suffixes that will be combined with the binary download links # to achieve a full download link. Different suffix for each platform. # Extend this dictionary to add more platforms. PLATFORM_SUFFIXES = { # 64-bit Windows 'win_amd64': '-win-x64.exe', # 64-bit Linux 'manylinux1_x86_64': '-linux-x64', # Linux on ARM 'manylinux2014_aarch64': '-linux-arm64', # 64-bit with 10.9 SDK 'macosx_10_9_x86_64': '-osx-x64', } FFMPEG_DL_PREFIX = 'https://github.com/joeyparrish/static-ffmpeg-binaries/releases/download/' + FFMPEG_VERSION PACKAGER_DL_PREFIX = 'https://github.com/google/shaka-packager/releases/download/' + PACKAGER_VERSION # The download links to each binary. These download links # aren't complete, they miss the platfrom-specific suffix. BINARIES_DL = [ FFMPEG_DL_PREFIX + '/ffmpeg', FFMPEG_DL_PREFIX + '/ffprobe', PACKAGER_DL_PREFIX + '/packager', ] BINARIES_ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) def build_bdist_wheel(platform_name, platform_binaries): """Builds a wheel distribution for `platform_name` adding the files in `platform_binaries` to it using the `package_data` parameter.""" args = [ 'python3', 'setup.py', # Build binary as a wheel. 'bdist_wheel', # Platform name to embed in generated filenames. '--plat-name', platform_name, # Temporary directory for creating the distribution. '--bdist-dir', platform_name, # Python tag to embed in the generated filenames. '--python-tag', 'py3', # Run quietly. '--quiet', ] # After '--', we send the platform specific binaries that we want to include. args += ['--'] args += platform_binaries subprocess.check_call(args, cwd=BINARIES_ROOT_DIR) # Remove the build directory so that it is not reused by 'setup.py'. shutil.rmtree(os.path.join(BINARIES_ROOT_DIR, 'build')) def download_binary(download_url: str, download_dir: str) -> str: """Downloads a file and writes it to the file system. Returns the file name. """ binary_name = download_url.split('/')[-1] binary_path = os.path.join(download_dir, binary_name) print('downloading', binary_name, flush=True, end=' ') urllib.request.urlretrieve(download_url, binary_path) print('(finished)') # Set executable permissions for the downloaded binaries. default_permissions = 0o755 os.chmod(binary_path, default_permissions) return binary_name def main(): # For each platform(OS+CPU), we download the its binaries and # create a binary wheel distribution that contains the executable # binaries specific to this platform. download_dir = os.path.join(BINARIES_ROOT_DIR, streamer_binaries.__name__) for platform_name, suffix in PLATFORM_SUFFIXES.items(): binaries_to_include = [] # Use the `suffix` specific to this platfrom to achieve # the full download link for each binary. for binary_dl in BINARIES_DL: download_link = binary_dl + suffix binary_name = download_binary(download_url=download_link, download_dir=download_dir) binaries_to_include.append(binary_name) # Build a wheel distribution for this platform # and include the binaries we have just downloaded. build_bdist_wheel(platform_name, binaries_to_include) if __name__ == '__main__': main()
34.620968
110
0.726532
79516e778e457b0c3496e743c755e12a385851e4
107,643
py
Python
futu/quote/quote_query.py
zhuzhenping/py-futu-api
540cf951738e387fd001064a76ceef6284c75d41
[ "Apache-2.0" ]
1
2021-01-10T00:54:39.000Z
2021-01-10T00:54:39.000Z
futu/quote/quote_query.py
GOGOYAO/py-futu-api
540cf951738e387fd001064a76ceef6284c75d41
[ "Apache-2.0" ]
null
null
null
futu/quote/quote_query.py
GOGOYAO/py-futu-api
540cf951738e387fd001064a76ceef6284c75d41
[ "Apache-2.0" ]
1
2021-02-17T17:46:36.000Z
2021-02-17T17:46:36.000Z
# -*- coding: utf-8 -*- """ Quote query """ from futu.common.utils import * from futu.common.pb import Common_pb2 from futu.quote.quote_stockfilter_info import * # 无数据时的值 NoneDataType = 'N/A' def get_optional_from_pb(pb, field_name, conv=None): if pb.HasField(field_name): val = getattr(pb, field_name) if conv: val = conv(val) return val return NoneDataType def set_item_from_pb(item, pb, field_map): for python_name, pb_name, is_required, conv in field_map: exist_val = item.get(python_name, None) if exist_val is not None and exist_val != NoneDataType: continue if is_required: val = getattr(pb, pb_name) if conv: val = conv(val) item[python_name] = val else: item[python_name] = get_optional_from_pb(pb, pb_name, conv) def set_item_none(item, field_map): for row in field_map: exist_val = item.get(row[0], None) if exist_val is None or exist_val == NoneDataType: item[row[0]] = NoneDataType def conv_pb_security_to_code(security): return merge_qot_mkt_stock_str(security.market, security.code) def merge_pb_cnipoexdata_winningnumdata(winningnumdata): data = '' for item in winningnumdata: if data == '': data = item.winningName + ":" + item.winningInfo else: data = data + '\n' + item.winningName + ":" + item.winningInfo data = data.rstrip() return data # python_name, pb_name, is_required, conv_func pb_field_map_OptionBasicQotExData = [ ('strike_price', 'strikePrice', True, None), ('contract_size', 'contractSize', True, None), ('open_interest', 'openInterest', True, None), ('implied_volatility', 'impliedVolatility', True, None), ('premium', 'premium', True, None), ('delta', 'delta', True, None), ('gamma', 'gamma', True, None), ('vega', 'vega', True, None), ('theta', 'theta', True, None), ('rho', 'rho', True, None), ('net_open_interest', 'netOpenInterest', False, None), ('expiry_date_distance', 'expiryDateDistance', False, None), ('contract_nominal_value', 'contractNominalValue', False, None), ('owner_lot_multiplier', 'ownerLotMultiplier', False, None), ('option_area_type', 'optionAreaType', False, None), ('contract_multiplier', 'contractMultiplier', False, None), ] pb_field_map_PreAfterMarketData_pre = [ ("pre_price", "price", False, None), ("pre_high_price", "highPrice", False, None), ("pre_low_price", "lowPrice", False, None), ("pre_volume", "volume", False, None), ("pre_turnover", "turnover", False, None), ("pre_change_val", "changeVal", False, None), ("pre_change_rate", "changeRate", False, None), ("pre_amplitude", "amplitude", False, None), ] pb_field_map_PreAfterMarketData_after = [ ("after_price", "price", False, None), ("after_high_price", "highPrice", False, None), ("after_low_price", "lowPrice", False, None), ("after_volume", "volume", False, None), ("after_turnover", "turnover", False, None), ("after_change_val", "changeVal", False, None), ("after_change_rate", "changeRate", False, None), ("after_amplitude", "amplitude", False, None), ] pb_field_map_BasicIpoData = [ ("code", "security", True, conv_pb_security_to_code), ("name", "name", True, None), ("list_time", "listTime", False, None), ("list_timestamp", "listTimestamp", False, None), ] pb_field_map_CNIpoExData = [ ("apply_code", "applyCode", True, None), ("issue_size", "issueSize", True, None), ("online_issue_size", "onlineIssueSize", True, None), ("apply_upper_limit", "applyUpperLimit", True, None), ("apply_limit_market_value", "applyLimitMarketValue", True, None), ("is_estimate_ipo_price", "isEstimateIpoPrice", True, None), ("ipo_price", "ipoPrice", True, None), ("industry_pe_rate", "industryPeRate", True, None), ("is_estimate_winning_ratio", "isEstimateWinningRatio", True, None), ("winning_ratio", "winningRatio", True, None), ("issue_pe_rate", "issuePeRate", True, None), ("apply_time", "applyTime", False, None), ("apply_timestamp", "applyTimestamp", False, None), ("winning_time", "winningTime", False, None), ("winning_timestamp", "winningTimestamp", False, None), ("is_has_won", "isHasWon", True, None), ("winning_num_data", "winningNumData", True, merge_pb_cnipoexdata_winningnumdata), ] pb_field_map_HKIpoExData = [ ("ipo_price_min", "ipoPriceMin", True, None), ("ipo_price_max", "ipoPriceMax", True, None), ("list_price", "listPrice", True, None), ("lot_size", "lotSize", True, None), ("entrance_price", "entrancePrice", True, None), ("is_subscribe_status", "isSubscribeStatus", True, None), ("apply_end_time", "applyEndTime", False, None), ("apply_end_timestamp", "applyEndTimestamp", False, None), ] pb_field_map_USIpoExData = [ ("ipo_price_min", "ipoPriceMin", True, None), ("ipo_price_max", "ipoPriceMax", True, None), ("issue_size", "issueSize", True, None) ] class InitConnect: """ A InitConnect request must be sent first """ def __init__(self): pass @classmethod def pack_req(cls, client_ver, client_id, recv_notify, is_encrypt): from futu.common.pb.InitConnect_pb2 import Request req = Request() req.c2s.clientVer = client_ver req.c2s.clientID = client_id req.c2s.recvNotify = recv_notify if is_encrypt: req.c2s.packetEncAlgo = Common_pb2.PacketEncAlgo_AES_CBC else: req.c2s.packetEncAlgo = Common_pb2.PacketEncAlgo_None return pack_pb_req(req, ProtoId.InitConnect, 0) @classmethod def unpack_rsp(cls, rsp_pb): """Unpack the init connect response""" ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None res = {} if rsp_pb.HasField('s2c'): res['server_version'] = rsp_pb.s2c.serverVer res['login_user_id'] = rsp_pb.s2c.loginUserID res['conn_id'] = rsp_pb.s2c.connID res['conn_key'] = rsp_pb.s2c.connAESKey res['conn_iv'] = rsp_pb.s2c.aesCBCiv if rsp_pb.s2c.HasField('aesCBCiv') else None res['keep_alive_interval'] = rsp_pb.s2c.keepAliveInterval else: return RET_ERROR, "rsp_pb error", None return RET_OK, "", res class TradeDayQuery: """ Query Conversion for getting trading days. """ def __init__(self): pass @classmethod def pack_req(cls, market, conn_id, start_date=None, end_date=None): # '''Parameter check''' if market not in MKT_MAP: error_str = ERROR_STR_PREFIX + " market is %s, which is not valid. (%s)" \ % (market, ",".join([x for x in MKT_MAP])) return RET_ERROR, error_str, None if start_date is None: today = datetime.today() start = today - timedelta(days=365) start_date = start.strftime("%Y-%m-%d") else: ret, msg = normalize_date_format(start_date) if ret != RET_OK: return ret, msg, None start_date = msg if end_date is None: today = datetime.today() end_date = today.strftime("%Y-%m-%d") else: ret, msg = normalize_date_format(end_date) if ret != RET_OK: return ret, msg, None end_date = msg # pack to json mkt = MKT_MAP[market] from futu.common.pb.Qot_GetTradeDate_pb2 import Request req = Request() req.c2s.market = mkt req.c2s.beginTime = start_date req.c2s.endTime = end_date return pack_pb_req(req, ProtoId.Qot_GetTradeDate, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): # response check and unpack response json to objects ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None raw_trading_day_list = rsp_pb.s2c.tradeDateList trading_day_list = list() for x in raw_trading_day_list: if x.time is not None and len(x.time) > 0: trading_day_list.append( {"time": x.time, "trade_date_type": TradeDateType.to_string2(x.tradeDateType)}) return RET_OK, "", trading_day_list class StockBasicInfoQuery: """ Query Conversion for getting stock basic information. """ def __init__(self): pass @classmethod def pack_req(cls, market, conn_id, stock_type='STOCK', code_list=None): if market not in MKT_MAP: error_str = ERROR_STR_PREFIX + " market is %s, which is not valid. (%s)" \ % (market, ",".join([x for x in MKT_MAP])) return RET_ERROR, error_str, None if stock_type not in SEC_TYPE_MAP: error_str = ERROR_STR_PREFIX + " stock_type is %s, which is not valid. (%s)" \ % (stock_type, ",".join([x for x in SEC_TYPE_MAP])) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetStaticInfo_pb2 import Request req = Request() req.c2s.market = MKT_MAP[market] req.c2s.secType = SEC_TYPE_MAP[stock_type] if code_list is not None: for code in code_list: sec = req.c2s.securityList.add() ret, data = split_stock_str(code) if ret == RET_OK: sec.market, sec.code = data else: return RET_ERROR, data, None return pack_pb_req(req, ProtoId.Qot_GetStaticInfo, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None raw_basic_info_list = rsp_pb.s2c.staticInfoList basic_info_list = [{ "code": merge_qot_mkt_stock_str(record.basic.security.market, record.basic.security.code), "stock_id": record.basic.id, "name": record.basic.name, "lot_size": record.basic.lotSize, "stock_type": QUOTE.REV_SEC_TYPE_MAP[record.basic.secType] if record.basic.secType in QUOTE.REV_SEC_TYPE_MAP else SecurityType.NONE, "stock_child_type": WrtType.to_string2(record.warrantExData.type), "stock_owner":merge_qot_mkt_stock_str( record.warrantExData.owner.market, record.warrantExData.owner.code) if record.HasField('warrantExData') else ( merge_qot_mkt_stock_str( record.optionExData.owner.market, record.optionExData.owner.code) if record.HasField('optionExData') else ""), "listing_date": "N/A" if record.HasField('optionExData') else record.basic.listTime, "option_type": QUOTE.REV_OPTION_TYPE_CLASS_MAP[record.optionExData.type] if record.HasField('optionExData') else "", "strike_time": record.optionExData.strikeTime, "strike_price": record.optionExData.strikePrice if record.HasField('optionExData') else NoneDataType, "suspension": record.optionExData.suspend if record.HasField('optionExData') else NoneDataType, "delisting": record.basic.delisting if record.basic.HasField('delisting') else NoneDataType, "index_option_type": IndexOptionType.to_string2(record.optionExData.indexOptionType) if record.HasField('optionExData') else NoneDataType, } for record in raw_basic_info_list] return RET_OK, "", basic_info_list class MarketSnapshotQuery: """ Query Conversion for getting market snapshot. """ def __init__(self): pass @classmethod def pack_req(cls, stock_list, conn_id): """Convert from user request for trading days to PLS request""" stock_tuple_list = [] failure_tuple_list = [] for stock_str in stock_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: error_str = content failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetSecuritySnapshot_pb2 import Request req = Request() for market, code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market stock_inst.code = code return pack_pb_req(req, ProtoId.Qot_GetSecuritySnapshot, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): """Convert from PLS response to user response""" ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None raw_snapshot_list = rsp_pb.s2c.snapshotList snapshot_list = [] for record in raw_snapshot_list: snapshot_tmp = {} snapshot_tmp['code'] = merge_qot_mkt_stock_str( int(record.basic.security.market), record.basic.security.code) snapshot_tmp['update_time'] = record.basic.updateTime snapshot_tmp['last_price'] = record.basic.curPrice snapshot_tmp['open_price'] = record.basic.openPrice snapshot_tmp['high_price'] = record.basic.highPrice snapshot_tmp['low_price'] = record.basic.lowPrice snapshot_tmp['prev_close_price'] = record.basic.lastClosePrice snapshot_tmp['volume'] = record.basic.volume snapshot_tmp['turnover'] = record.basic.turnover snapshot_tmp['turnover_rate'] = record.basic.turnoverRate snapshot_tmp['suspension'] = record.basic.isSuspend snapshot_tmp['listing_date'] = "N/A" if record.HasField( 'optionExData') else record.basic.listTime snapshot_tmp['price_spread'] = record.basic.priceSpread snapshot_tmp['lot_size'] = record.basic.lotSize snapshot_tmp['ask_price'] = record.basic.askPrice snapshot_tmp['bid_price'] = record.basic.bidPrice snapshot_tmp['ask_vol'] = record.basic.askVol snapshot_tmp['bid_vol'] = record.basic.bidVol # 2019.02.25 增加一批数据 if record.basic.HasField("enableMargin"): # 是否可融资,如果为true,后两个字段才有意 snapshot_tmp['enable_margin'] = record.basic.enableMargin if snapshot_tmp['enable_margin'] is True: snapshot_tmp['mortgage_ratio'] = record.basic.mortgageRatio snapshot_tmp['long_margin_initial_ratio'] = record.basic.longMarginInitialRatio if record.basic.HasField("enableShortSell"): # 是否可卖空,如果为true,后三个字段才有意义 snapshot_tmp['enable_short_sell'] = record.basic.enableShortSell if snapshot_tmp['enable_short_sell'] is True: snapshot_tmp['short_sell_rate'] = record.basic.shortSellRate snapshot_tmp['short_available_volume'] = record.basic.shortAvailableVolume snapshot_tmp['short_margin_initial_ratio'] = record.basic.shortMarginInitialRatio # 2019.05.10 增加一批数据================================ # 振幅(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["amplitude"] = record.basic.amplitude # 平均价 type=double snapshot_tmp["avg_price"] = record.basic.avgPrice # 委比(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["bid_ask_ratio"] = record.basic.bidAskRatio # 量比 type=double snapshot_tmp["volume_ratio"] = record.basic.volumeRatio # 52周最高价 type=double snapshot_tmp["highest52weeks_price"] = record.basic.highest52WeeksPrice # 52周最低价 type=double snapshot_tmp["lowest52weeks_price"] = record.basic.lowest52WeeksPrice # 历史最高价 type=double snapshot_tmp["highest_history_price"] = record.basic.highestHistoryPrice # 历史最低价 type=double snapshot_tmp["lowest_history_price"] = record.basic.lowestHistoryPrice # 盘后成交量 type=int64 snapshot_tmp["after_volume"] = record.basic.afterMarket.volume # 盘后成交额 type=double snapshot_tmp["after_turnover"] = record.basic.afterMarket.turnover # 股票状态 type=str snapshot_tmp["sec_status"] = SecurityStatus.to_string2(record.basic.secStatus) if record.basic.HasField('preMarket'): set_item_from_pb(snapshot_tmp, record.basic.preMarket, pb_field_map_PreAfterMarketData_pre) else: set_item_none(snapshot_tmp, pb_field_map_PreAfterMarketData_pre) if record.basic.HasField('afterMarket'): set_item_from_pb(snapshot_tmp, record.basic.afterMarket, pb_field_map_PreAfterMarketData_after) else: set_item_none(snapshot_tmp, pb_field_map_PreAfterMarketData_after) # ================================ snapshot_tmp['equity_valid'] = False # equityExData if record.HasField('equityExData'): snapshot_tmp['equity_valid'] = True snapshot_tmp['issued_shares'] = record.equityExData.issuedShares snapshot_tmp['total_market_val'] = record.equityExData.issuedMarketVal snapshot_tmp['net_asset'] = record.equityExData.netAsset snapshot_tmp['net_profit'] = record.equityExData.netProfit snapshot_tmp['earning_per_share'] = record.equityExData.earningsPershare snapshot_tmp['outstanding_shares'] = record.equityExData.outstandingShares snapshot_tmp['circular_market_val'] = record.equityExData.outstandingMarketVal snapshot_tmp['net_asset_per_share'] = record.equityExData.netAssetPershare snapshot_tmp['ey_ratio'] = record.equityExData.eyRate snapshot_tmp['pe_ratio'] = record.equityExData.peRate snapshot_tmp['pb_ratio'] = record.equityExData.pbRate snapshot_tmp['pe_ttm_ratio'] = record.equityExData.peTTMRate snapshot_tmp["dividend_ttm"] = record.equityExData.dividendTTM # 股息率TTM(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["dividend_ratio_ttm"] = record.equityExData.dividendRatioTTM # 股息LFY,上一年度派息 type=double snapshot_tmp["dividend_lfy"] = record.equityExData.dividendLFY # 股息率LFY(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["dividend_lfy_ratio"] = record.equityExData.dividendLFYRatio snapshot_tmp['wrt_valid'] = False if record.basic.type == SEC_TYPE_MAP[SecurityType.WARRANT]: snapshot_tmp['wrt_valid'] = True snapshot_tmp['wrt_conversion_ratio'] = record.warrantExData.conversionRate snapshot_tmp['wrt_type'] = WrtType.to_string2( record.warrantExData.warrantType) snapshot_tmp['wrt_strike_price'] = record.warrantExData.strikePrice snapshot_tmp['wrt_maturity_date'] = record.warrantExData.maturityTime snapshot_tmp['wrt_end_trade'] = record.warrantExData.endTradeTime snapshot_tmp['stock_owner'] = merge_qot_mkt_stock_str( record.warrantExData.owner.market, record.warrantExData.owner.code) snapshot_tmp['wrt_recovery_price'] = record.warrantExData.recoveryPrice snapshot_tmp['wrt_street_vol'] = record.warrantExData.streetVolumn snapshot_tmp['wrt_issue_vol'] = record.warrantExData.issueVolumn snapshot_tmp['wrt_street_ratio'] = record.warrantExData.streetRate snapshot_tmp['wrt_delta'] = record.warrantExData.delta snapshot_tmp['wrt_implied_volatility'] = record.warrantExData.impliedVolatility snapshot_tmp['wrt_premium'] = record.warrantExData.premium # 杠杆比率(倍) type=double snapshot_tmp["wrt_leverage"] = record.warrantExData.leverage # 价内/价外(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["wrt_ipop"] = record.warrantExData.ipop # 打和点 type=double snapshot_tmp["wrt_break_even_point"] = record.warrantExData.breakEvenPoint # 换股价 type=double snapshot_tmp["wrt_conversion_price"] = record.warrantExData.conversionPrice # 距收回价(该字段为百分比字段,默认不展示%) type=double snapshot_tmp["wrt_price_recovery_ratio"] = record.warrantExData.priceRecoveryRatio # 综合评分 type=double snapshot_tmp["wrt_score"] = record.warrantExData.score # 上限价,仅界内证支持该字段 type=double snapshot_tmp["wrt_upper_strike_price"] = record.warrantExData.upperStrikePrice # 下限价,仅界内证支持该字段 type=double snapshot_tmp["wrt_lowe_strike_price"] = record.warrantExData.lowerStrikePrice # 界内界外,仅界内证支持该字段 type=double snapshot_tmp["wrt_inline_price_status"] = PriceType.to_string2( record.warrantExData.inLinePriceStatus) snapshot_tmp['option_valid'] = False if record.basic.type == SEC_TYPE_MAP[SecurityType.DRVT]: snapshot_tmp['option_valid'] = True snapshot_tmp['option_type'] = QUOTE.REV_OPTION_TYPE_CLASS_MAP[record.optionExData.type] snapshot_tmp['stock_owner'] = merge_qot_mkt_stock_str( record.optionExData.owner.market, record.optionExData.owner.code) snapshot_tmp['strike_time'] = record.optionExData.strikeTime snapshot_tmp['option_strike_price'] = record.optionExData.strikePrice snapshot_tmp['option_contract_size'] = record.optionExData.contractSize snapshot_tmp['option_open_interest'] = record.optionExData.openInterest snapshot_tmp['option_implied_volatility'] = record.optionExData.impliedVolatility snapshot_tmp['option_premium'] = record.optionExData.premium snapshot_tmp['option_delta'] = record.optionExData.delta snapshot_tmp['option_gamma'] = record.optionExData.gamma snapshot_tmp['option_vega'] = record.optionExData.vega snapshot_tmp['option_theta'] = record.optionExData.theta snapshot_tmp['option_rho'] = record.optionExData.rho snapshot_tmp['net_open_interest'] = record.optionExData.netOpenInterest if record.optionExData.HasField('netOpenInterest') else 'N/A' snapshot_tmp['expiry_date_distance'] = record.optionExData.expiryDateDistance if record.optionExData.HasField('expiryDateDistance') else 'N/A' snapshot_tmp['contract_nominal_value'] = record.optionExData.contractNominalValue if record.optionExData.HasField('contractNominalValue') else 'N/A' snapshot_tmp['owner_lot_multiplier'] = record.optionExData.ownerLotMultiplier if record.optionExData.HasField('ownerLotMultiplier') else 'N/A' snapshot_tmp['option_area_type'] = OptionAreaType.to_string2(record.optionExData.optionAreaType) if record.optionExData.HasField('optionAreaType') else 'N/A' snapshot_tmp['contract_multiplier'] = record.optionExData.contractMultiplier if record.optionExData.HasField('contractMultiplier') else 'N/A' snapshot_tmp['index_valid'] = False if record.HasField('indexExData'): snapshot_tmp['index_valid'] = True # 指数类型上涨支数 type=int32 snapshot_tmp["index_raise_count"] = record.indexExData.raiseCount # 指数类型下跌支数 type=int32 snapshot_tmp["index_fall_count"] = record.indexExData.fallCount # 指数类型平盘支数 type=int32 snapshot_tmp["index_equal_count"] = record.indexExData.equalCount snapshot_tmp['plate_valid'] = False if record.HasField('plateExData'): snapshot_tmp['plate_valid'] = True # 板块类型上涨支数 type=int32 snapshot_tmp["plate_raise_count"] = record.plateExData.raiseCount # 板块类型下跌支数 type=int32 snapshot_tmp["plate_fall_count"] = record.plateExData.fallCount # 板块类型平盘支数 type=int32 snapshot_tmp["plate_equal_count"] = record.plateExData.equalCount snapshot_list.append(snapshot_tmp) return RET_OK, "", snapshot_list class RtDataQuery: """ Query Conversion for getting stock real-time data. """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content from futu.common.pb.Qot_GetRT_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetRT, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None raw_rt_data_list = rsp_pb.s2c.rtList rt_list = [ { "code": merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code), "time": record.time, "is_blank": True if record.isBlank else False, "opened_mins": record.minute, "cur_price": record.price, "last_close": record.lastClosePrice, "avg_price": record.avgPrice if record.HasField('avgPrice') else None, "turnover": record.turnover, "volume": record.volume } for record in raw_rt_data_list ] return RET_OK, "", rt_list class SubplateQuery: """ Query Conversion for getting sub-plate stock list. """ def __init__(self): pass @classmethod def pack_req(cls, market, plate_class, conn_id): from futu.common.pb.Qot_GetPlateSet_pb2 import Request req = Request() req.c2s.market = MKT_MAP[market] req.c2s.plateSetType = PLATE_CLASS_MAP[plate_class] return pack_pb_req(req, ProtoId.Qot_GetPlateSet, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None raw_plate_list = rsp_pb.s2c.plateInfoList plate_list = [{ "code": merge_qot_mkt_stock_str(record.plate.market, record.plate.code), "plate_name": record.name, "plate_id": record.plate.code } for record in raw_plate_list] return RET_OK, "", plate_list class PlateStockQuery: """ Query Conversion for getting all the stock list of a given plate. """ def __init__(self): pass @classmethod def pack_req(cls, plate_code, sort_field, ascend, conn_id): ret_code, content = split_stock_str(plate_code) if ret_code != RET_OK: msg = content error_str = ERROR_STR_PREFIX + msg return RET_ERROR, error_str, None market, code = content if market not in QUOTE.REV_MKT_MAP: error_str = ERROR_STR_PREFIX + "market is %s, which is not valid. (%s)" \ % (market, ",".join([x for x in MKT_MAP])) return RET_ERROR, error_str, None r, v = SortField.to_number(sort_field) from futu.common.pb.Qot_GetPlateSecurity_pb2 import Request req = Request() req.c2s.plate.market = market req.c2s.plate.code = code req.c2s.sortField = v req.c2s.ascend = ascend return pack_pb_req(req, ProtoId.Qot_GetPlateSecurity, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None raw_stock_list = rsp_pb.s2c.staticInfoList stock_list = [] for record in raw_stock_list: stock_tmp = {} stock_tmp['stock_id'] = record.basic.id stock_tmp['lot_size'] = record.basic.lotSize stock_tmp['code'] = merge_qot_mkt_stock_str( record.basic.security.market, record.basic.security.code) stock_tmp['stock_name'] = record.basic.name stock_tmp['list_time'] = record.basic.listTime stock_tmp['stock_type'] = QUOTE.REV_SEC_TYPE_MAP[record.basic.secType] if record.basic.secType in QUOTE.REV_SEC_TYPE_MAP else SecurityType.NONE stock_list.append(stock_tmp) return RET_OK, "", stock_list class BrokerQueueQuery: """ Query Conversion for getting broker queue information. """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): ret_code, content = split_stock_str(code) if ret_code == RET_ERROR: error_str = content return RET_ERROR, error_str, None market, code = content from futu.common.pb.Qot_GetBroker_pb2 import Request req = Request() req.c2s.security.market = market req.c2s.security.code = code return pack_pb_req(req, ProtoId.Qot_GetBroker, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) raw_broker_bid = rsp_pb.s2c.brokerBidList bid_list = [] if raw_broker_bid is not None: bid_list = [{ "bid_broker_id": record.id, "bid_broker_name": record.name, "bid_broker_pos": record.pos, "code": merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) } for record in raw_broker_bid] raw_broker_ask = rsp_pb.s2c.brokerAskList ask_list = [] if raw_broker_ask is not None: ask_list = [{ "ask_broker_id": record.id, "ask_broker_name": record.name, "ask_broker_pos": record.pos, "code": merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) } for record in raw_broker_ask] return RET_OK, "", (stock_code, bid_list, ask_list) class GetHistoryKlineQuery: """ Query Conversion for getting historic Kline data. """ def __init__(self): pass @classmethod def pack_req(cls, code, start_date, end_date, ktype, autype, fields, max_num, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content # check k line type if ktype not in KTYPE_MAP: error_str = ERROR_STR_PREFIX + "ktype is %s, which is not valid. (%s)" \ % (ktype, ", ".join([x for x in KTYPE_MAP])) return RET_ERROR, error_str, None if autype not in AUTYPE_MAP: error_str = ERROR_STR_PREFIX + "autype is %s, which is not valid. (%s)" \ % (autype, ", ".join([str(x) for x in AUTYPE_MAP])) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetHistoryKL_pb2 import Request req = Request() req.c2s.rehabType = AUTYPE_MAP[autype] req.c2s.klType = KTYPE_MAP[ktype] req.c2s.security.market = market_code req.c2s.security.code = stock_code if start_date: req.c2s.beginTime = start_date if end_date: req.c2s.endTime = end_date req.c2s.maxAckKLNum = max_num req.c2s.needKLFieldsFlag = KL_FIELD.kl_fields_to_flag_val(fields) return pack_pb_req(req, ProtoId.Qot_GetHistoryKL, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None has_next = False next_time = "" if rsp_pb.s2c.HasField('nextKLTime'): has_next = True next_time = rsp_pb.s2c.nextKLTime stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) list_ret = [] dict_data = {} raw_kline_list = rsp_pb.s2c.klList for record in raw_kline_list: dict_data['code'] = stock_code dict_data['time_key'] = record.time if record.isBlank: continue if record.HasField('openPrice'): dict_data['open'] = record.openPrice if record.HasField('highPrice'): dict_data['high'] = record.highPrice if record.HasField('lowPrice'): dict_data['low'] = record.lowPrice if record.HasField('closePrice'): dict_data['close'] = record.closePrice if record.HasField('volume'): dict_data['volume'] = record.volume if record.HasField('turnover'): dict_data['turnover'] = record.turnover if record.HasField('pe'): dict_data['pe_ratio'] = record.pe if record.HasField('turnoverRate'): dict_data['turnover_rate'] = record.turnoverRate if record.HasField('changeRate'): dict_data['change_rate'] = record.changeRate if record.HasField('lastClosePrice'): dict_data['last_close'] = record.lastClosePrice list_ret.append(dict_data.copy()) return RET_OK, "", (list_ret, has_next, next_time) class RequestHistoryKlineQuery: def __init__(self): pass @classmethod def pack_req(cls, code, start_date, end_date, ktype, autype, fields, max_num, conn_id, next_req_key): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content # check k line type if ktype not in KTYPE_MAP: error_str = ERROR_STR_PREFIX + "ktype is %s, which is not valid. (%s)" \ % (ktype, ", ".join([x for x in KTYPE_MAP])) return RET_ERROR, error_str, None if autype not in AUTYPE_MAP: error_str = ERROR_STR_PREFIX + "autype is %s, which is not valid. (%s)" \ % (autype, ", ".join([str(x) for x in AUTYPE_MAP])) return RET_ERROR, error_str, None from futu.common.pb.Qot_RequestHistoryKL_pb2 import Request req = Request() req.c2s.rehabType = AUTYPE_MAP[autype] req.c2s.klType = KTYPE_MAP[ktype] req.c2s.security.market = market_code req.c2s.security.code = stock_code if start_date: req.c2s.beginTime = start_date if end_date: req.c2s.endTime = end_date req.c2s.maxAckKLNum = max_num req.c2s.needKLFieldsFlag = KL_FIELD.kl_fields_to_flag_val(fields) if next_req_key is not None: req.c2s.nextReqKey = next_req_key return pack_pb_req(req, ProtoId.Qot_RequestHistoryKL, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None has_next = False next_req_key = None if rsp_pb.s2c.HasField('nextReqKey'): has_next = True next_req_key = bytes(rsp_pb.s2c.nextReqKey) stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) list_ret = [] dict_data = {} raw_kline_list = rsp_pb.s2c.klList for record in raw_kline_list: dict_data['code'] = stock_code dict_data['time_key'] = record.time if record.isBlank: continue if record.HasField('openPrice'): dict_data['open'] = record.openPrice if record.HasField('highPrice'): dict_data['high'] = record.highPrice if record.HasField('lowPrice'): dict_data['low'] = record.lowPrice if record.HasField('closePrice'): dict_data['close'] = record.closePrice if record.HasField('volume'): dict_data['volume'] = record.volume if record.HasField('turnover'): dict_data['turnover'] = record.turnover if record.HasField('pe'): dict_data['pe_ratio'] = record.pe if record.HasField('turnoverRate'): dict_data['turnover_rate'] = record.turnoverRate if record.HasField('changeRate'): dict_data['change_rate'] = record.changeRate if record.HasField('lastClosePrice'): dict_data['last_close'] = record.lastClosePrice list_ret.append(dict_data.copy()) return RET_OK, "", (list_ret, has_next, next_req_key) class ExrightQuery: """ Query Conversion for getting exclude-right information of stock. """ def __init__(self): pass @classmethod def pack_req(cls, stock_list, conn_id): stock_tuple_list = [] failure_tuple_list = [] for stock_str in stock_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: msg = content error_str = ERROR_STR_PREFIX + msg failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetRehab_pb2 import Request req = Request() for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetRehab, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None class KLRehabFlag(object): SPLIT = 1 JOIN = 2 BONUS = 4 TRANSFER = 8 ALLOT = 16 ADD = 32 DIVIDED = 64 SP_DIVIDED = 128 raw_exr_list = rsp_pb.s2c.securityRehabList exr_list = [] for stock_rehab in raw_exr_list: code = merge_qot_mkt_stock_str(stock_rehab.security.market, stock_rehab.security.code) for rehab in stock_rehab.rehabList: stock_rehab_tmp = {} stock_rehab_tmp['code'] = code stock_rehab_tmp['ex_div_date'] = rehab.time.split()[0] stock_rehab_tmp['forward_adj_factorA'] = rehab.fwdFactorA stock_rehab_tmp['forward_adj_factorB'] = rehab.fwdFactorB stock_rehab_tmp['backward_adj_factorA'] = rehab.bwdFactorA stock_rehab_tmp['backward_adj_factorB'] = rehab.bwdFactorB act_flag = rehab.companyActFlag if act_flag == 0: continue if act_flag & KLRehabFlag.SP_DIVIDED: stock_rehab_tmp['special_dividend'] = rehab.spDividend if act_flag & KLRehabFlag.DIVIDED: stock_rehab_tmp['per_cash_div'] = rehab.dividend if act_flag & KLRehabFlag.ADD: stock_rehab_tmp[ 'stk_spo_ratio'] = rehab.addBase / rehab.addErt stock_rehab_tmp['stk_spo_price'] = rehab.addPrice if act_flag & KLRehabFlag.ALLOT: stock_rehab_tmp[ 'allotment_ratio'] = rehab.allotBase / rehab.allotErt stock_rehab_tmp['allotment_price'] = rehab.allotPrice if act_flag & KLRehabFlag.TRANSFER: stock_rehab_tmp[ 'per_share_trans_ratio'] = rehab.transferBase / rehab.transferErt if act_flag & KLRehabFlag.BONUS: stock_rehab_tmp[ 'per_share_div_ratio'] = rehab.bonusBase / rehab.bonusErt if act_flag & KLRehabFlag.JOIN: stock_rehab_tmp[ 'join_ratio'] = rehab.joinBase / rehab.joinErt if act_flag & KLRehabFlag.SPLIT: stock_rehab_tmp[ 'split_ratio'] = rehab.splitBase / rehab.splitErt exr_list.append(stock_rehab_tmp) return RET_OK, "", exr_list class SubscriptionQuery: """ Query Conversion for getting user's subscription information. """ def __init__(self): pass @classmethod def pack_sub_or_unsub_req(cls, code_list, subtype_list, is_sub, conn_id, is_first_push, reg_or_unreg_push, unsub_all=False): stock_tuple_list = [] if code_list is not None: for code in code_list: ret_code, content = split_stock_str(code) if ret_code != RET_OK: return ret_code, content, None market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) from futu.common.pb.Qot_Sub_pb2 import Request req = Request() if unsub_all is True: req.c2s.isUnsubAll = True req.c2s.isSubOrUnSub = False else: for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.code = stock_code stock_inst.market = market_code for subtype in subtype_list: req.c2s.subTypeList.append(SUBTYPE_MAP[subtype]) req.c2s.isSubOrUnSub = is_sub req.c2s.isFirstPush = is_first_push req.c2s.isRegOrUnRegPush = reg_or_unreg_push return pack_pb_req(req, ProtoId.Qot_Sub, conn_id) @classmethod def pack_subscribe_req(cls, code_list, subtype_list, conn_id, is_first_push, subscribe_push): return SubscriptionQuery.pack_sub_or_unsub_req(code_list, subtype_list, True, conn_id, is_first_push, subscribe_push) # True @classmethod def unpack_subscribe_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, "", None @classmethod def pack_unsubscribe_req(cls, code_list, subtype_list, unsubscribe_all, conn_id): return SubscriptionQuery.pack_sub_or_unsub_req(code_list, subtype_list, False, conn_id, False, False, unsubscribe_all) @classmethod def unpack_unsubscribe_rsp(cls, rsp_pb): """Unpack the un-subscribed response""" if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, "", None @classmethod def pack_subscription_query_req(cls, is_all_conn, conn_id): from futu.common.pb.Qot_GetSubInfo_pb2 import Request req = Request() req.c2s.isReqAllConn = is_all_conn return pack_pb_req(req, ProtoId.Qot_GetSubInfo, conn_id) @classmethod def unpack_subscription_query_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None raw_sub_info = rsp_pb.s2c result = {} result['total_used'] = raw_sub_info.totalUsedQuota result['remain'] = raw_sub_info.remainQuota result['conn_sub_list'] = [] for conn_sub_info in raw_sub_info.connSubInfoList: conn_sub_info_tmp = {} conn_sub_info_tmp['used'] = conn_sub_info.usedQuota conn_sub_info_tmp['is_own_conn'] = conn_sub_info.isOwnConnData conn_sub_info_tmp['sub_list'] = [] for sub_info in conn_sub_info.subInfoList: sub_info_tmp = {} if sub_info.subType not in QUOTE.REV_SUBTYPE_MAP: logger.error("error subtype:{}".format(sub_info.subType)) continue sub_info_tmp['subtype'] = QUOTE.REV_SUBTYPE_MAP[sub_info.subType] sub_info_tmp['code_list'] = [] for stock in sub_info.securityList: sub_info_tmp['code_list'].append( merge_qot_mkt_stock_str(int(stock.market), stock.code),) conn_sub_info_tmp['sub_list'].append(sub_info_tmp) result['conn_sub_list'].append(conn_sub_info_tmp) return RET_OK, "", result @classmethod def pack_push_or_unpush_req(cls, code_list, subtype_list, is_push, conn_id, is_first_push): stock_tuple_list = [] for code in code_list: ret_code, content = split_stock_str(code) if ret_code != RET_OK: return ret_code, content, None market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) from futu.common.pb.Qot_RegQotPush_pb2 import Request req = Request() for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.code = stock_code stock_inst.market = market_code for subtype in subtype_list: req.c2s.subTypeList.append(SUBTYPE_MAP[subtype]) req.c2s.isRegOrUnReg = is_push req.c2s.isFirstPush = True if is_first_push else False return pack_pb_req(req, ProtoId.Qot_RegQotPush, conn_id) @classmethod def pack_push_req(cls, code_list, subtype_list, conn_id, is_first_push): return SubscriptionQuery.pack_push_or_unpush_req(code_list, subtype_list, True, conn_id, is_first_push) @classmethod def pack_unpush_req(cls, code_list, subtype_list, conn_id, is_first_push=False): return SubscriptionQuery.pack_push_or_unpush_req(code_list, subtype_list, False, conn_id, is_first_push) def parse_pb_BasicQot(pb): item = None if pb.updateTime is not None and len(pb.updateTime) != 0: item = { 'code': merge_qot_mkt_stock_str(int(pb.security.market), pb.security.code), 'data_date': pb.updateTime.split()[0], 'data_time': pb.updateTime.split()[1], 'last_price': pb.curPrice, 'open_price': pb.openPrice, 'high_price': pb.highPrice, 'low_price': pb.lowPrice, 'prev_close_price': pb.lastClosePrice, 'volume': int(pb.volume), 'turnover': pb.turnover, 'turnover_rate': pb.turnoverRate, 'amplitude': pb.amplitude, 'suspension': pb.isSuspended, 'listing_date': pb.listTime, 'price_spread': pb.priceSpread, 'dark_status': QUOTE.REV_DARK_STATUS_MAP[pb.darkStatus] if pb.HasField( 'darkStatus') else DarkStatus.NONE, 'sec_status': SecurityStatus.to_string2(pb.secStatus) if pb.HasField( 'secStatus') else SecurityStatus.NONE, } if pb.HasField('optionExData'): set_item_from_pb(item, pb.optionExData, pb_field_map_OptionBasicQotExData) else: set_item_none(item, pb_field_map_OptionBasicQotExData) if pb.HasField('preMarket'): set_item_from_pb(item, pb.preMarket, pb_field_map_PreAfterMarketData_pre) else: set_item_none(item, pb_field_map_PreAfterMarketData_pre) if pb.HasField('afterMarket'): set_item_from_pb(item, pb.afterMarket, pb_field_map_PreAfterMarketData_after) else: set_item_none(item, pb_field_map_PreAfterMarketData_after) return item class StockQuoteQuery: """ Query Conversion for getting stock quote data. """ def __init__(self): pass @classmethod def pack_req(cls, stock_list, conn_id): stock_tuple_list = [] failure_tuple_list = [] for stock_str in stock_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: msg = content error_str = ERROR_STR_PREFIX + msg failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetBasicQot_pb2 import Request req = Request() for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetBasicQot, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] raw_quote_list = rsp_pb.s2c.basicQotList quote_list = list() for record in raw_quote_list: item = parse_pb_BasicQot(record) if item: quote_list.append(item) return RET_OK, "", quote_list class TickerQuery: """Stick ticker data query class""" def __init__(self): pass @classmethod def pack_req(cls, code, num, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None if isinstance(num, int) is False: error_str = ERROR_STR_PREFIX + "num is %s of type %s, and the type shoud be %s" \ % (num, str(type(num)), str(int)) return RET_ERROR, error_str, None if num < 0: error_str = ERROR_STR_PREFIX + "num is %s, which is less than 0" % num return RET_ERROR, error_str, None market_code, stock_code = content from futu.common.pb.Qot_GetTicker_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code req.c2s.maxRetNum = num return pack_pb_req(req, ProtoId.Qot_GetTicker, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) raw_ticker_list = rsp_pb.s2c.tickerList ticker_list = [{ "code": stock_code, "time": record.time, "price": record.price, "volume": record.volume, "turnover": record.turnover, "ticker_direction": str(QUOTE.REV_TICKER_DIRECTION[record.dir]) if record.dir in QUOTE.REV_TICKER_DIRECTION else "", "sequence": record.sequence, "recv_timestamp":record.recvTime, "type": QUOTE.REV_TICKER_TYPE_MAP[record.type] if record.type in QUOTE.REV_TICKER_TYPE_MAP else TickerType.UNKNOWN, "push_data_type":QUOTE.REV_PUSH_DATA_TYPE_MAP[record.pushDataType] if record.pushDataType in QUOTE.REV_PUSH_DATA_TYPE_MAP else PushDataType.NONE, } for record in raw_ticker_list] return RET_OK, "", ticker_list class CurKlineQuery: """Stock Kline data query class""" def __init__(self): pass @classmethod def pack_req(cls, code, num, ktype, autype, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content if ktype not in KTYPE_MAP: error_str = ERROR_STR_PREFIX + "ktype is %s, which is not valid. (%s)" \ % (ktype, ", ".join([x for x in KTYPE_MAP])) return RET_ERROR, error_str, None if autype not in AUTYPE_MAP: error_str = ERROR_STR_PREFIX + "autype is %s, which is not valid. (%s)" \ % (autype, ", ".join([str(x) for x in AUTYPE_MAP])) return RET_ERROR, error_str, None if isinstance(num, int) is False: error_str = ERROR_STR_PREFIX + "num is %s of type %s, which type should be %s" \ % (num, str(type(num)), str(int)) return RET_ERROR, error_str, None if num < 0: error_str = ERROR_STR_PREFIX + "num is %s, which is less than 0" % num return RET_ERROR, error_str, None from futu.common.pb.Qot_GetKL_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code req.c2s.rehabType = AUTYPE_MAP[autype] req.c2s.reqNum = num req.c2s.klType = KTYPE_MAP[ktype] return pack_pb_req(req, ProtoId.Qot_GetKL, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) raw_kline_list = rsp_pb.s2c.klList kline_list = [{ "code": stock_code, "time_key": record.time, "open": record.openPrice, "high": record.highPrice, "low": record.lowPrice, "close": record.closePrice, "volume": record.volume, "turnover": record.turnover, "pe_ratio": record.pe, "turnover_rate": record.turnoverRate, "last_close": record.lastClosePrice, } for record in raw_kline_list] return RET_OK, "", kline_list class CurKlinePush: """Stock Kline data push class""" def __init__(self): pass @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] if rsp_pb.s2c.rehabType != AUTYPE_MAP[AuType.QFQ]: return RET_ERROR, "kline push only support AuType.QFQ", None kl_type = QUOTE.REV_KTYPE_MAP[rsp_pb.s2c.klType] if rsp_pb.s2c.klType in QUOTE.REV_KTYPE_MAP else None if not kl_type: return RET_ERROR, "kline push error kltype", None stock_code = merge_qot_mkt_stock_str(rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) raw_kline_list = rsp_pb.s2c.klList kline_list = [{ "k_type": kl_type, "code": stock_code, "time_key": record.time, "open": record.openPrice, "high": record.highPrice, "low": record.lowPrice, "close": record.closePrice, "volume": record.volume, "turnover": record.turnover, "pe_ratio": record.pe, "turnover_rate": record.turnoverRate, "last_close": record.lastClosePrice, } for record in raw_kline_list] return RET_OK, "", kline_list class OrderBookQuery: """ Query Conversion for getting stock order book data. """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content from futu.common.pb.Qot_GetOrderBook_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code req.c2s.num = 10 return pack_pb_req(req, ProtoId.Qot_GetOrderBook, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] raw_order_book_ask = rsp_pb.s2c.orderBookAskList raw_order_book_bid = rsp_pb.s2c.orderBookBidList order_book = {} order_book['code'] = merge_qot_mkt_stock_str( rsp_pb.s2c.security.market, rsp_pb.s2c.security.code) order_book['svr_recv_time_bid'] = rsp_pb.s2c.svrRecvTimeBid order_book['svr_recv_time_ask'] = rsp_pb.s2c.svrRecvTimeAsk order_book['Bid'] = [] order_book['Ask'] = [] for record in raw_order_book_bid: order_book['Bid'].append((record.price, record.volume, record.orederCount)) for record in raw_order_book_ask: order_book['Ask'].append((record.price, record.volume, record.orederCount)) return RET_OK, "", order_book class SuspensionQuery: """ Query SuspensionQuery. """ def __init__(self): pass @classmethod def pack_req(cls, code_list, start, end, conn_id): list_req_stock = [] for stock_str in code_list: ret, content = split_stock_str(stock_str) if ret == RET_ERROR: return RET_ERROR, content, None else: list_req_stock.append(content) from futu.common.pb.Qot_GetSuspend_pb2 import Request req = Request() if start: req.c2s.beginTime = start if end: req.c2s.endTime = end for market, code in list_req_stock: stock_inst = req.c2s.securityList.add() stock_inst.market = market stock_inst.code = code return pack_pb_req(req, ProtoId.Qot_GetSuspend, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret_susp_list = [] for record in rsp_pb.s2c.SecuritySuspendList: suspend_info_tmp = {} code = merge_qot_mkt_stock_str( record.security.market, record.security.code) for suspend_info in record.suspendList: suspend_info_tmp['code'] = code suspend_info_tmp['suspension_dates'] = suspend_info.time ret_susp_list.append(suspend_info_tmp) return RET_OK, "", ret_susp_list class GlobalStateQuery: """ Query process "FTNN.exe" global state : market state & logined state """ def __init__(self): pass @classmethod def pack_req(cls, user_id, conn_id): from futu.common.pb.GetGlobalState_pb2 import Request req = Request() req.c2s.userID = user_id return pack_pb_req(req, ProtoId.GetGlobalState, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None state = rsp_pb.s2c program_status_type = ProgramStatusType.NONE program_status_desc = "" if state.HasField('programStatus'): program_status_type = ProgramStatusType.to_string2( state.programStatus.type) if state.programStatus.HasField("strExtDesc"): program_status_desc = state.programStatus.strExtDesc state_dict = { 'market_sz': QUOTE.REV_MARKET_STATE_MAP[state.marketSZ] if state.marketSZ in QUOTE.REV_MARKET_STATE_MAP else MarketState.NONE, 'market_us': QUOTE.REV_MARKET_STATE_MAP[state.marketUS] if state.marketUS in QUOTE.REV_MARKET_STATE_MAP else MarketState.NONE, 'market_sh': QUOTE.REV_MARKET_STATE_MAP[state.marketSH] if state.marketSH in QUOTE.REV_MARKET_STATE_MAP else MarketState.NONE, 'market_hk': QUOTE.REV_MARKET_STATE_MAP[state.marketHK] if state.marketHK in QUOTE.REV_MARKET_STATE_MAP else MarketState.NONE, 'market_hkfuture': QUOTE.REV_MARKET_STATE_MAP[state.marketHKFuture] if state.marketHKFuture in QUOTE.REV_MARKET_STATE_MAP else MarketState.NONE, 'server_ver': str(state.serverVer), 'trd_logined': state.trdLogined, 'timestamp': str(state.time), 'qot_logined': state.qotLogined, 'local_timestamp': state.localTime if state.HasField('localTime') else time.time(), 'program_status_type': program_status_type, 'program_status_desc': program_status_desc } return RET_OK, "", state_dict class KeepAlive: def __init__(self): pass @classmethod def pack_req(cls, conn_id): from futu.common.pb.KeepAlive_pb2 import Request req = Request() req.c2s.time = int(time.time()) return pack_pb_req(req, ProtoId.KeepAlive, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, '', rsp_pb.s2c.time class SysNotifyPush: """ SysNotifyPush """ def __init__(self): pass @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, pb_type = rsp_pb.s2c.type sub_type = None data = None notify_type = SysNoitfy.REV_SYS_EVENT_TYPE_MAP[ pb_type] if pb_type in SysNoitfy.REV_SYS_EVENT_TYPE_MAP else SysNotifyType.NONE if notify_type == SysNotifyType.GTW_EVENT: if rsp_pb.s2c.HasField('event'): pb_event = rsp_pb.s2c.event.eventType sub_type = SysNoitfy.REV_GTW_EVENT_MAP[ pb_event] if pb_event in SysNoitfy.REV_GTW_EVENT_MAP else GtwEventType.NONE data = rsp_pb.s2c.event.desc elif notify_type == SysNotifyType.PROGRAM_STATUS: if rsp_pb.s2c.HasField('programStatus'): ret, status_type = ProgramStatusType.to_string( rsp_pb.s2c.programStatus.programStatus.type) if not ret: status_type = ProgramStatusType.NONE if rsp_pb.s2c.programStatus.programStatus.HasField('strExtDesc'): status_desc = rsp_pb.s2c.programStatus.programStatus.strExtDesc else: status_desc = '' sub_type = status_type data = status_desc elif notify_type == SysNotifyType.CONN_STATUS: if rsp_pb.s2c.HasField('connectStatus'): data = {'qot_logined': rsp_pb.s2c.connectStatus.qotLogined, 'trd_logined': rsp_pb.s2c.connectStatus.trdLogined} elif notify_type == SysNotifyType.QOT_RIGHT: if rsp_pb.s2c.HasField('qotRight'): data = {'hk_qot_right': QotRight.to_string2(rsp_pb.s2c.qotRight.hkQotRight), 'us_qot_right': QotRight.to_string2(rsp_pb.s2c.qotRight.usQotRight), 'cn_qot_right': QotRight.to_string2(rsp_pb.s2c.qotRight.cnQotRight)} elif notify_type == SysNotifyType.API_LEVEL: if rsp_pb.s2c.HasField('apiLevel'): data = {'api_level': rsp_pb.s2c.apiLevel.apiLevel} if data is None: logger.warning( "SysNotifyPush data is None: notify_type={}".format(notify_type)) return RET_OK, (notify_type, sub_type, data) class MultiPointsHisKLine: """ Query MultiPointsHisKLine """ def __init__(self): pass @classmethod def pack_req(cls, code_list, dates, fields, ktype, autype, max_req, no_data_mode, conn_id): list_req_stock = [] for code in code_list: ret, content = split_stock_str(code) if ret == RET_ERROR: return RET_ERROR, content, None else: list_req_stock.append(content) for x in dates: ret, msg = check_date_str_format(x) if ret != RET_OK: return ret, msg, None if ktype not in KTYPE_MAP: error_str = ERROR_STR_PREFIX + "ktype is %s, which is not valid. (%s)" \ % (ktype, ", ".join([x for x in KTYPE_MAP])) return RET_ERROR, error_str, None if autype not in AUTYPE_MAP: error_str = ERROR_STR_PREFIX + "autype is %s, which is not valid. (%s)" \ % (autype, ", ".join([str(x) for x in AUTYPE_MAP])) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetHistoryKLPoints_pb2 import Request req = Request() req.c2s.needKLFieldsFlag = KL_FIELD.kl_fields_to_flag_val(fields) req.c2s.rehabType = AUTYPE_MAP[autype] req.c2s.klType = KTYPE_MAP[ktype] req.c2s.noDataMode = no_data_mode req.c2s.maxReqSecurityNum = max_req for market_code, code in list_req_stock: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = code for date_ in dates: req.c2s.timeList.append(date_) return pack_pb_req(req, ProtoId.Qot_GetHistoryKLPoints, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None has_next = rsp_pb.s2c.hasNext if rsp_pb.s2c.HasField( 'hasNext') else False list_ret = [] dict_data = {} raw_kline_points = rsp_pb.s2c.klPointList for raw_kline in raw_kline_points: code = merge_qot_mkt_stock_str(raw_kline.security.market, raw_kline.security.code) for raw_kl in raw_kline.klList: dict_data['code'] = code dict_data['time_point'] = raw_kl.reqTime dict_data['data_status'] = QUOTE.REV_KLDATA_STATUS_MAP[raw_kl.status] if raw_kl.status in QUOTE.REV_KLDATA_STATUS_MAP else KLDataStatus.NONE dict_data['time_key'] = raw_kl.kl.time dict_data['open'] = raw_kl.kl.openPrice if raw_kl.kl.HasField( 'openPrice') else 0 dict_data['high'] = raw_kl.kl.highPrice if raw_kl.kl.HasField( 'highPrice') else 0 dict_data['low'] = raw_kl.kl.lowPrice if raw_kl.kl.HasField( 'lowPrice') else 0 dict_data[ 'close'] = raw_kl.kl.closePrice if raw_kl.kl.HasField( 'closePrice') else 0 dict_data['volume'] = raw_kl.kl.volume if raw_kl.kl.HasField( 'volume') else 0 dict_data[ 'turnover'] = raw_kl.kl.turnover if raw_kl.kl.HasField( 'turnover') else 0 dict_data['pe_ratio'] = raw_kl.kl.pe if raw_kl.kl.HasField( 'pe') else 0 dict_data[ 'turnover_rate'] = raw_kl.kl.turnoverRate if raw_kl.kl.HasField( 'turnoverRate') else 0 dict_data[ 'change_rate'] = raw_kl.kl.changeRate if raw_kl.kl.HasField( 'changeRate') else 0 dict_data[ 'last_close'] = raw_kl.kl.lastClosePrice if raw_kl.kl.HasField( 'lastClosePrice') else 0 list_ret.append(dict_data.copy()) return RET_OK, "", (list_ret, has_next) class StockReferenceList: def __init__(self): pass @classmethod def pack_req(cls, code, ref_type, conn_id): from futu.common.pb.Qot_GetReference_pb2 import Request ret, content = split_stock_str(code) if ret != RET_OK: return ret, content, None req = Request() req.c2s.security.market = content[0] req.c2s.security.code = content[1] req.c2s.referenceType = STOCK_REFERENCE_TYPE_MAP[ref_type] return pack_pb_req(req, ProtoId.Qot_GetReference, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None if not rsp_pb.HasField('s2c'): return RET_OK, '', None data_list = [] for info in rsp_pb.s2c.staticInfoList: data = {} data['code'] = merge_qot_mkt_stock_str( info.basic.security.market, info.basic.security.code) # item['stock_id'] = info.basic.id data['lot_size'] = info.basic.lotSize data['stock_type'] = QUOTE.REV_SEC_TYPE_MAP[info.basic.secType] if info.basic.secType in QUOTE.REV_SEC_TYPE_MAP else SecurityType.NONE data['stock_name'] = info.basic.name data['list_time'] = info.basic.listTime if info.HasField('warrantExData'): data['wrt_valid'] = True data['wrt_type'] = WrtType.to_string2(info.warrantExData.type) data['wrt_code'] = merge_qot_mkt_stock_str(info.warrantExData.owner.market, info.warrantExData.owner.code) else: data['wrt_valid'] = False data_list.append(data) return RET_OK, '', data_list class OwnerPlateQuery: """ Query Conversion for getting owner plate information. """ def __init__(self): pass @classmethod def pack_req(cls, code_list, conn_id): stock_tuple_list = [] failure_tuple_list = [] for stock_str in code_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: error_str = content failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None from futu.common.pb.Qot_GetOwnerPlate_pb2 import Request req = Request() for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetOwnerPlate, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] raw_quote_list = rsp_pb.s2c.ownerPlateList data_list = [] for record in raw_quote_list: plate_info_list = record.plateInfoList for plate_info in plate_info_list: quote_list = { 'code': merge_qot_mkt_stock_str(record.security.market, record.security.code), 'plate_code': merge_qot_mkt_stock_str(plate_info.plate.market, plate_info.plate.code), 'plate_name': str(plate_info.name), 'plate_type': PLATE_TYPE_ID_TO_NAME[plate_info.plateType] } data_list.append(quote_list) return RET_OK, "", data_list class HoldingChangeList: """ Query Conversion for getting holding change list. """ def __init__(self): pass @classmethod def pack_req(cls, code, holder_type, conn_id, start_date, end_date=None): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content if start_date is None: msg = "The start date is none." return RET_ERROR, msg, None else: ret, msg = normalize_date_format(start_date) if ret != RET_OK: return ret, msg, None start_date = msg if end_date is None: today = datetime.today() end_date = today.strftime("%Y-%m-%d") else: ret, msg = normalize_date_format(end_date) if ret != RET_OK: return ret, msg, None end_date = msg from futu.common.pb.Qot_GetHoldingChangeList_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code req.c2s.holderCategory = holder_type req.c2s.beginTime = start_date if end_date: req.c2s.endTime = end_date return pack_pb_req(req, ProtoId.Qot_GetHoldingChangeList, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] raw_quote_list = rsp_pb.s2c.holdingChangeList data_list = [] for record in raw_quote_list: quote_list = { 'holder_name': record.holderName, 'holding_qty': record.holdingQty, 'holding_ratio': record.holdingRatio, 'change_qty': record.changeQty, 'change_ratio': record.changeRatio, 'time': record.time, } data_list.append(quote_list) return RET_OK, "", data_list class OptionChain: """ Query Conversion for getting option chain information. """ def __init__(self): pass @classmethod def pack_req(cls, code, index_option_type, conn_id, start_date, end_date=None, option_type=OptionType.ALL, option_cond_type=OptionCondType.ALL): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content if start_date is None: msg = "The start date is none." return RET_ERROR, msg, None else: ret, msg = normalize_date_format(start_date) if ret != RET_OK: return ret, msg, None start_date = msg if end_date is None: today = datetime.today() end_date = today.strftime("%Y-%m-%d") else: ret, msg = normalize_date_format(end_date) if ret != RET_OK: return ret, msg, None end_date = msg option_cond_type = OPTION_COND_TYPE_CLASS_MAP[option_cond_type] option_type = OPTION_TYPE_CLASS_MAP[option_type] r, index_option_type = IndexOptionType.to_number(index_option_type) if r is False: index_option_type = None from futu.common.pb.Qot_GetOptionChain_pb2 import Request req = Request() req.c2s.owner.market = market_code req.c2s.owner.code = stock_code if index_option_type is not None: req.c2s.indexOptionType = index_option_type req.c2s.beginTime = start_date req.c2s.endTime = end_date if option_type is not None: req.c2s.type = option_type if option_cond_type is not None: req.c2s.condition = option_cond_type return pack_pb_req(req, ProtoId.Qot_GetOptionChain, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, [] raw_quote_list = rsp_pb.s2c.optionChain data_list = [] for OptionItem in raw_quote_list: for record_all in OptionItem.option: record_list = [] if record_all.HasField('call'): record_list.append(record_all.call) if record_all.HasField('put'): record_list.append(record_all.put) for record in record_list: quote_list = { 'code': merge_qot_mkt_stock_str(int(record.basic.security.market), record.basic.security.code), "stock_id": record.basic.id, "name": record.basic.name, "lot_size": record.basic.lotSize, "stock_type": QUOTE.REV_SEC_TYPE_MAP[record.basic.secType] if record.basic.secType in QUOTE.REV_SEC_TYPE_MAP else SecurityType.NONE, "option_type": QUOTE.REV_OPTION_TYPE_CLASS_MAP[record.optionExData.type] if record.HasField('optionExData') else "", "stock_owner": merge_qot_mkt_stock_str(int(record.optionExData.owner.market), record.optionExData.owner.code) if record.HasField('optionExData') else "", "strike_time": record.optionExData.strikeTime, "strike_price": record.optionExData.strikePrice if record.HasField('optionExData') else NoneDataType, "suspension": record.optionExData.suspend if record.HasField('optionExData') else NoneDataType, "index_option_type": IndexOptionType.to_string2(record.optionExData.indexOptionType) if record.HasField('optionExData') else NoneDataType, } data_list.append(quote_list) return RET_OK, "", data_list class OrderDetail: """ Query Conversion for getting order detail information. """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content from futu.common.pb.Qot_GetOrderDetail_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetOrderDetail, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None code = merge_qot_mkt_stock_str( int(rsp_pb.s2c.security.market), rsp_pb.s2c.security.code) ask = [0, []] bid = [0, []] svr_recv_time_bid = rsp_pb.s2c.svrRecvTimeBid svr_recv_time_ask = rsp_pb.s2c.svrRecvTimeAsk ask[0] = rsp_pb.s2c.orderDetailAsk.orderCount for vol in rsp_pb.s2c.orderDetailAsk.orderVol: ask[1].append(vol) bid[0] = rsp_pb.s2c.orderDetailBid.orderCount for vol in rsp_pb.s2c.orderDetailBid.orderVol: bid[1].append(vol) data = { 'code': code, 'Ask': ask, 'Bid': bid, 'svr_recv_time_ask': svr_recv_time_ask, 'svr_recv_time_bid': svr_recv_time_bid } return RET_OK, "", data class QuoteWarrant: """ 拉取涡轮 """ def __init__(self): pass @classmethod def pack_req(cls, req, conn_id): from futu.quote.quote_get_warrant import Request as WarrantRequest if (req is None) or (not isinstance(req, WarrantRequest)): req = WarrantRequest() ret, context = req.fill_request_pb() if ret == RET_OK: return pack_pb_req(context, ProtoId.Qot_GetWarrantData, conn_id) else: return ret, context, None @classmethod def unpack_rsp(cls, rsp_pb): from futu.quote.quote_get_warrant import Response as WarrantResponse return WarrantResponse.unpack_response_pb(rsp_pb) class HistoryKLQuota: """ 拉取限额 """ def __init__(self): pass @classmethod def pack_req(cls, get_detail, conn_id): from futu.common.pb.Qot_RequestHistoryKLQuota_pb2 import Request req = Request() req.c2s.bGetDetail = get_detail return pack_pb_req(req, ProtoId.Qot_RequestHistoryKLQuota, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None used_quota = rsp_pb.s2c.usedQuota remain_quota = rsp_pb.s2c.remainQuota detail_list = [] details = rsp_pb.s2c.detailList for item in details: code = merge_qot_mkt_stock_str( int(item.security.market), item.security.code) request_time = str(item.requestTime) detail_list.append({"code": code, "request_time": request_time}) data = { "used_quota": used_quota, "remain_quota": remain_quota, "detail_list": detail_list } return RET_OK, "", data class RequestRehab: """ 获取除权信息 """ def __init__(self): pass @classmethod def pack_req(cls, stock, conn_id): ret_code, content = split_stock_str(stock) if ret_code != RET_OK: msg = content error_str = ERROR_STR_PREFIX + msg return RET_ERROR, error_str, None market, code = content if market not in QUOTE.REV_MKT_MAP: error_str = ERROR_STR_PREFIX + "market is %s, which is not valid. (%s)" \ % (market, ",".join([x for x in MKT_MAP])) return RET_ERROR, error_str, None from futu.common.pb.Qot_RequestRehab_pb2 import Request req = Request() req.c2s.security.market = market req.c2s.security.code = code return pack_pb_req(req, ProtoId.Qot_RequestRehab, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None class KLRehabFlag(object): SPLIT = 1 JOIN = 2 BONUS = 4 TRANSFER = 8 ALLOT = 16 ADD = 32 DIVIDED = 64 SP_DIVIDED = 128 rehab_list = list() for rehab in rsp_pb.s2c.rehabList: stock_rehab_tmp = {} stock_rehab_tmp['ex_div_date'] = rehab.time.split()[0] # 时间字符串 stock_rehab_tmp['forward_adj_factorA'] = rehab.fwdFactorA stock_rehab_tmp['forward_adj_factorB'] = rehab.fwdFactorB stock_rehab_tmp['backward_adj_factorA'] = rehab.bwdFactorA stock_rehab_tmp['backward_adj_factorB'] = rehab.bwdFactorB act_flag = rehab.companyActFlag if act_flag == 0: continue if act_flag & KLRehabFlag.SP_DIVIDED: stock_rehab_tmp['special_dividend'] = rehab.spDividend if act_flag & KLRehabFlag.DIVIDED: stock_rehab_tmp['per_cash_div'] = rehab.dividend if act_flag & KLRehabFlag.ADD: stock_rehab_tmp['stk_spo_ratio'] = rehab.addBase / rehab.addErt stock_rehab_tmp['stk_spo_price'] = rehab.addPrice if act_flag & KLRehabFlag.ALLOT: stock_rehab_tmp['allotment_ratio'] = rehab.allotBase / \ rehab.allotErt stock_rehab_tmp['allotment_price'] = rehab.allotPrice if act_flag & KLRehabFlag.TRANSFER: stock_rehab_tmp['per_share_trans_ratio'] = rehab.transferBase / \ rehab.transferErt if act_flag & KLRehabFlag.BONUS: stock_rehab_tmp['per_share_div_ratio'] = rehab.bonusBase / \ rehab.bonusErt if act_flag & KLRehabFlag.JOIN: stock_rehab_tmp['join_ratio'] = rehab.joinBase / rehab.joinErt if act_flag & KLRehabFlag.SPLIT: stock_rehab_tmp['split_ratio'] = rehab.splitBase / \ rehab.splitErt rehab_list.append(stock_rehab_tmp) return RET_OK, "", rehab_list """-------------------------------------------------------------""" class GetUserInfo: """ 拉取用户信息 """ def __init__(self): pass @classmethod def pack_req(cls, info_field, conn_id): from futu.common.pb.GetUserInfo_pb2 import Request req = Request() if info_field is None: req.c2s.flag = 0 else: req.c2s.flag = UserInfoField.fields_to_flag_val(info_field) return pack_pb_req(req, ProtoId.GetUserInfo, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None nick_name = rsp_pb.s2c.nickName if rsp_pb.s2c.HasField( 'nickName') else "N/A" avatar_url = rsp_pb.s2c.avatarUrl if rsp_pb.s2c.HasField( 'avatarUrl') else "N/A" api_level = rsp_pb.s2c.apiLevel if rsp_pb.s2c.HasField( 'apiLevel') else "N/A" hk_qot_right = rsp_pb.s2c.hkQotRight if rsp_pb.s2c.HasField( 'hkQotRight') else "N/A" us_qot_right = rsp_pb.s2c.usQotRight if rsp_pb.s2c.HasField( 'usQotRight') else "N/A" cn_qot_right = rsp_pb.s2c.cnQotRight if rsp_pb.s2c.HasField( 'cnQotRight') else "N/A" is_need_agree_disclaimer = rsp_pb.s2c.isNeedAgreeDisclaimer if rsp_pb.s2c.HasField( 'isNeedAgreeDisclaimer') else "N/A" user_id = rsp_pb.s2c.userID if rsp_pb.s2c.HasField('userID') else "N/A" update_type = rsp_pb.s2c.updateType if rsp_pb.s2c.HasField( 'updateType') else "N/A" web_key = rsp_pb.s2c.webKey if rsp_pb.s2c.HasField('webKey') else "N/A" data = { "nick_name": nick_name, "avatar_url": avatar_url, "api_level": api_level, "hk_qot_right": QotRight.to_string2(hk_qot_right), "us_qot_right": QotRight.to_string2(us_qot_right), "cn_qot_right": QotRight.to_string2(cn_qot_right), "is_need_agree_disclaimer": is_need_agree_disclaimer, "user_id": user_id, "update_type": UpdateType.to_string2(update_type), "web_key": web_key } return RET_OK, "", data class GetCapitalDistributionQuery: """ Query GetCapitalDistribution. 个股资金分布 """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): """check stock_code 股票""" ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content # 开始组包 from futu.common.pb.Qot_GetCapitalDistribution_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetCapitalDistribution, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret = dict() # 流入资金额度,大单 type=double ret["capital_in_big"] = rsp_pb.s2c.capitalInBig # 流入资金额度,中单 type=double ret["capital_in_mid"] = rsp_pb.s2c.capitalInMid # 流入资金额度,小单 type=double ret["capital_in_small"] = rsp_pb.s2c.capitalInSmall # 流出资金额度,大单 type=double ret["capital_out_big"] = rsp_pb.s2c.capitalOutBig # 流出资金额度,中单 type=double ret["capital_out_mid"] = rsp_pb.s2c.capitalOutMid # 流出资金额度,小单 type=double ret["capital_out_small"] = rsp_pb.s2c.capitalOutSmall # 更新时间字符串 type=string ret["update_time"] = rsp_pb.s2c.updateTime return RET_OK, "", ret class GetCapitalFlowQuery: """ Query GetCapitalFlow. 个股资金流入流出 """ def __init__(self): pass @classmethod def pack_req(cls, code, conn_id): """check stock_code 股票""" ret, content = split_stock_str(code) if ret == RET_ERROR: error_str = content return RET_ERROR, error_str, None market_code, stock_code = content # 开始组包 from futu.common.pb.Qot_GetCapitalFlow_pb2 import Request req = Request() req.c2s.security.market = market_code req.c2s.security.code = stock_code return pack_pb_req(req, ProtoId.Qot_GetCapitalFlow, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret_list = list() # 资金流向 type = Qot_GetCapitalFlow.CapitalFlowItem flow_item_list = rsp_pb.s2c.flowItemList # 数据最后有效时间字符串 type = string last_valid_time = rsp_pb.s2c.lastValidTime for item in flow_item_list: data = dict() ret_list.append(data) # 净流入的资金额度 type = double data["in_flow"] = item.inFlow # 开始时间字符串,以分钟为单位 type = string data["capital_flow_item_time"] = item.time data["last_valid_time"] = last_valid_time return RET_OK, "", ret_list class GetDelayStatisticsQuery: """ Query GetDelayStatistics. """ def __init__(self): pass @classmethod def pack_req(cls, type_list, qot_push_stage, segment_list, conn_id): """check type_list 统计数据类型,DelayStatisticsType""" """check qot_push_stage 行情推送统计的区间,行情推送统计时有效,QotPushStage""" """check segment_list 统计分段,默认100ms以下以2ms分段,100ms以上以500,1000,2000,-1分段,-1表示无穷大。""" # 开始组包 from futu.common.pb.GetDelayStatistics_pb2 import Request req = Request() for t in type_list: r, v = DelayStatisticsType.to_number(t) if r: req.c2s.typeList.append(v) r, v = QotPushStage.to_number(qot_push_stage) if r: req.c2s.qotPushStage = v for t in segment_list: req.c2s.segmentList.append(t) return pack_pb_req(req, ProtoId.GetDelayStatistics, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret_dic = dict() # 行情推送延迟统计 type = GetDelayStatistics.DelayStatistics qot_push_statistics_list = rsp_pb.s2c.qotPushStatisticsList # 请求延迟统计 type = GetDelayStatistics.ReqReplyStatisticsItem req_reply_statistics_list = rsp_pb.s2c.reqReplyStatisticsList # 下单延迟统计 type = GetDelayStatistics.PlaceOrderStatisticsItem place_order_statistics_list = rsp_pb.s2c.placeOrderStatisticsList # 请求延迟统计 列表类型 ret_list_req_reply_statistics_list = list() ret_dic["req_reply_statistics_list"] = ret_list_req_reply_statistics_list # 下单延迟统计 列表类型 ret_list_place_order_statistics_list = list() ret_dic["place_order_statistics_list"] = ret_list_place_order_statistics_list # 行情推送延迟统计 总表 列表类型 qot_push_all_statistics_list = list() ret_dic["qot_push_all_statistics_list"] = qot_push_all_statistics_list for item in qot_push_statistics_list: # 平均延迟和总包数加入总表 info = dict() qot_push_all_statistics_list.append(info) # 行情推送类型,QotPushType type = int32 qot_push_type = item.qotPushType info["qot_push_type"] = qot_push_type # 统计信息 type = GetDelayStatistics.DelayStatisticsItem item_list = item.itemList # 平均延迟 type = float delay_avg = item.delayAvg info["delay_avg"] = delay_avg # 总包数 type = int32 count = item.count info["count"] = count # 区段列表 ls = list() info["list"] = ls for sub_item in item_list: data = dict() ls.append(data) # 范围左闭右开,[begin,end)耗时范围起点,毫秒单位 type = int32 data["begin"] = sub_item.begin # 耗时范围结束,毫秒单位 type = int32 data["end"] = sub_item.end # 个数 type = int32 data["count"] = sub_item.count # 占比, % type = float data["proportion"] = sub_item.proportion # 累计占比, % type = float data["cumulative_ratio"] = sub_item.cumulativeRatio for item in req_reply_statistics_list: data = dict() ret_list_req_reply_statistics_list.append(data) # 协议ID type = int32 data["proto_id"] = item.protoID # 请求个数 type = int32 data["count"] = item.count # 平均总耗时,毫秒单位 type = float data["total_cost_avg"] = item.totalCostAvg # 平均OpenD耗时,毫秒单位 type = float data["open_d_cost_avg"] = item.openDCostAvg # 平均网络耗时,非当时实际请求网络耗时,毫秒单位 type = float data["net_delay_avg"] = item.netDelayAvg # 是否本地直接回包,没有向服务器请求数据 type = bool data["is_local_reply"] = item.isLocalReply for item in place_order_statistics_list: data = dict() ret_list_place_order_statistics_list.append(data) # 订单ID type = string data["order_id"] = item.orderID # 总耗时,毫秒单位 type = float data["total_cost"] = item.totalCost # OpenD耗时,毫秒单位 type = float data["open_d_cost"] = item.openDCost # 网络耗时,非当时实际请求网络耗时,毫秒单位 type = float data["net_delay"] = item.netDelay # 订单回包后到接收到订单下到交易所的耗时,毫秒单位 type = float data["update_cost"] = item.updateCost return RET_OK, "", ret_dic class Verification: """ 拉验证码 """ def __init__(self): pass @classmethod def pack_req(cls, verification_type, verification_op, code, conn_id): from futu.common.pb.Verification_pb2 import Request req = Request() ret, data = VerificationType.to_number(verification_type) if ret: req.c2s.type = data else: return RET_ERROR, data, None ret, data = VerificationOp.to_number(verification_op) if ret: req.c2s.op = data else: return RET_ERROR, data, None if code is not None and len(code) != 0: req.c2s.code = code return pack_pb_req(req, ProtoId.Verification, conn_id) @classmethod def unpack_rsp(cls, rsp_pb): return rsp_pb.retType, rsp_pb.retMsg, None """ =============================================================================== =============================================================================== """ class ModifyUserSecurityQuery: """ Query ModifyUserSecurity. """ def __init__(self): pass @classmethod def pack_req(cls, group_name, op, code_list, conn_id): """check group_name 分组名,有同名的返回首个""" """check op ModifyUserSecurityOp,操作类型""" """check code_list 新增或删除该分组下的股票""" stock_tuple_list = [] failure_tuple_list = [] for stock_str in code_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: error_str = content failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None # 开始组包 from futu.common.pb.Qot_ModifyUserSecurity_pb2 import Request req = Request() req.c2s.groupName = group_name req.c2s.op = op for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = stock_code return pack_pb_req(req, ProtoId.Qot_ModifyUserSecurity, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, "", None class GetUserSecurityQuery: """ Query GetUserSecurity. """ def __init__(self): pass @classmethod def pack_req(cls, group_name, conn_id): """check group_name 分组名,有同名的返回首个""" # 开始组包 from futu.common.pb.Qot_GetUserSecurity_pb2 import Request req = Request() req.c2s.groupName = group_name return pack_pb_req(req, ProtoId.Qot_GetUserSecurity, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None # 自选股分组下的股票列表 type = Qot_Common.SecurityStaticInfo static_info_list = rsp_pb.s2c.staticInfoList # 基本股票静态信息 type = SecurityStaticBasic basic_info_list = [{ "code": merge_qot_mkt_stock_str(record.basic.security.market, record.basic.security.code), "stock_id": record.basic.id, "name": record.basic.name, "lot_size": record.basic.lotSize, "stock_type": QUOTE.REV_SEC_TYPE_MAP[record.basic.secType] if record.basic.secType in QUOTE.REV_SEC_TYPE_MAP else SecurityType.NONE, "stock_child_type": WrtType.to_string2(record.warrantExData.type), "stock_owner": merge_qot_mkt_stock_str( record.warrantExData.owner.market, record.warrantExData.owner.code) if record.HasField('warrantExData') else ( merge_qot_mkt_stock_str( record.optionExData.owner.market, record.optionExData.owner.code) if record.HasField('optionExData') else ""), "listing_date": "N/A" if record.HasField('optionExData') else record.basic.listTime, "option_type": QUOTE.REV_OPTION_TYPE_CLASS_MAP[record.optionExData.type] if record.HasField('optionExData') else "", "strike_time": record.optionExData.strikeTime, "strike_price": record.optionExData.strikePrice if record.HasField( 'optionExData') else NoneDataType, "suspension": record.optionExData.suspend if record.HasField('optionExData') else NoneDataType, "delisting": record.basic.delisting if record.basic.HasField('delisting') else NoneDataType } for record in static_info_list] return RET_OK, "", basic_info_list class StockFilterQuery: """ Query StockFilterQuery. """ def __init__(self): pass @classmethod def pack_req(cls, market, filter_list, plate_code, begin, num, conn_id): """check group_name 分组名,有同名的返回首个""" # 开始组包 from futu.common.pb.Qot_StockFilter_pb2 import Request req = Request() req.c2s.begin = begin req.c2s.num = num """拆解market""" req.c2s.market = MKT_MAP[market] """拆解plate_code""" if plate_code is not None: ret, content = split_stock_str(plate_code) if ret != RET_OK: msg = str(content) error_str = ERROR_STR_PREFIX + msg return RET_ERROR, error_str, None market, code = content req.c2s.plate.code = code req.c2s.plate.market = market ret = RET_OK error_str = "" if filter_list is not None: for filter_item in filter_list: if isinstance(filter_item, SimpleFilter): filter_req = req.c2s.baseFilterList.add() ret, error_str = filter_item.fill_request_pb(filter_req) elif isinstance(filter_item, AccumulateFilter): filter_req = req.c2s.accumulateFilterList.add() ret, error_str = filter_item.fill_request_pb(filter_req) elif isinstance(filter_item, FinancialFilter): filter_req = req.c2s.financialFilterList.add() ret, error_str = filter_item.fill_request_pb(filter_req) else : ret = RET_ERROR error_str = ERROR_STR_PREFIX + "the item in filter_list is wrong" if (ret == RET_ERROR): return RET_ERROR, error_str, None return pack_pb_req(req, ProtoId.Qot_StockFilter, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None # 是否最后一页了,false:非最后一页,还有窝轮记录未返回; true:已是最后一页 type = bool last_page = rsp_pb.s2c.lastPage # 该条件请求所有数据的个数 type = int32 all_count = rsp_pb.s2c.allCount # type = Qot_StockFilter.StockData data_list = rsp_pb.s2c.dataList ret_list = list() for item in data_list: data = FilterStockData(item) ret_list.append(data) return RET_OK, "", (last_page, all_count, ret_list) class GetCodeChangeQuery: """ Query GetCodeChange. """ def __init__(self): pass @classmethod def pack_req(cls, code_list, time_filter_list, type_list, conn_id): stock_tuple_list = [] failure_tuple_list = [] for stock_str in code_list: ret_code, content = split_stock_str(stock_str) if ret_code != RET_OK: error_str = content failure_tuple_list.append((ret_code, error_str)) continue market_code, stock_code = content stock_tuple_list.append((market_code, stock_code)) if len(failure_tuple_list) > 0: error_str = '\n'.join([x[1] for x in failure_tuple_list]) return RET_ERROR, error_str, None # 开始组包 from futu.common.pb.Qot_GetCodeChange_pb2 import Request req = Request() req.c2s.placeHolder = 0 for market_code, stock_code in stock_tuple_list: stock_inst = req.c2s.securityList.add() stock_inst.market = market_code stock_inst.code = stock_code for type in type_list: r, n = CodeChangeType.to_number(type) req.c2s.typeList.append(n) for time_filter in time_filter_list: r, n = TimeFilterType.to_number(time_filter.type) time_filter_inst = req.c2s.timeFilterList.add() time_filter_inst.type = n time_filter_inst.beginTime = time_filter.begin_time time_filter_inst.endTime = time_filter.end_time return pack_pb_req(req, ProtoId.Qot_GetCodeChange, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret_list = list() # 股票代码更换信息,目前仅有港股数据 type = Qot_GetCodeChange.CodeChangeInfo code_change_list = rsp_pb.s2c.codeChangeList for item in code_change_list: data = {} # CodeChangeType,代码变化或者新增临时代码的事件类型 type = int32 data["code_change_info_type"] = CodeChangeType.to_string2( item.type) # 主代码,在创业板转主板中表示主板 type = code data["code"] = merge_qot_mkt_stock_str( item.security.market, item.security.code) # 关联代码,在创业板转主板中表示创业板,在剩余事件中表示临时代码 type = code data["related_code"] = merge_qot_mkt_stock_str( item.relatedSecurity.market, item.relatedSecurity.code) # 公布时间 type = string data["public_time"] = item.publicTime # 生效时间 type = string data["effective_time"] = item.effectiveTime # 结束时间,在创业板转主板事件不存在该字段,在剩余事件表示临时代码交易结束时间 type = string data["end_time"] = item.endTime ret_list.append(data) return RET_OK, "", ret_list class GetIpoListQuery: """ Query GetIpoListQuery. """ def __init__(self): pass @classmethod def pack_req(cls, conn_id, market): # 开始组包 from futu.common.pb.Qot_GetIpoList_pb2 import Request req = Request() try: req.c2s.market = MKT_MAP[market] except KeyError: return RET_ERROR, 'Invalid value: market', None return pack_pb_req(req, ProtoId.Qot_GetIpoList, conn_id) @classmethod def unpack(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None ret_list = [] for pb_item in rsp_pb.s2c.ipoList: data = {} set_item_from_pb(data, pb_item.basic, pb_field_map_BasicIpoData) if pb_item.HasField('cnExData'): set_item_from_pb(data, pb_item.cnExData, pb_field_map_CNIpoExData) else: set_item_none(data, pb_field_map_CNIpoExData) if pb_item.HasField('hkExData'): set_item_from_pb(data, pb_item.hkExData, pb_field_map_HKIpoExData) else: set_item_none(data, pb_field_map_HKIpoExData) if pb_item.HasField('usExData'): set_item_from_pb(data, pb_item.usExData, pb_field_map_USIpoExData) else: set_item_none(data, pb_field_map_USIpoExData) ret_list.append(data) return RET_OK, "", ret_list
37.506272
173
0.599342
79516fd272fa3cd6e2c9752e718118c14e6e66d9
1,466
py
Python
contrib/devtools/fix-copyright-headers.py
ocminer/kreds-core
94d550c68c0829a190c6ad676e08075bfcfa8ac0
[ "MIT" ]
null
null
null
contrib/devtools/fix-copyright-headers.py
ocminer/kreds-core
94d550c68c0829a190c6ad676e08075bfcfa8ac0
[ "MIT" ]
null
null
null
contrib/devtools/fix-copyright-headers.py
ocminer/kreds-core
94d550c68c0829a190c6ad676e08075bfcfa8ac0
[ "MIT" ]
null
null
null
#!/usr/bin/env python ''' Run this script inside of src/ and it will look for all the files that were changed this year that still have the last year in the copyright headers, and it will fix the headers on that file using a perl regex one liner. For example: if it finds something like this and we're in 2014 // Copyright (c) 2009-2013 The Kreds developers it will change it to // Copyright (c) 2009-2014 The Kreds developers It will do this for all the files in the folder and its children. Author: @gubatron ''' import os import time year = time.gmtime()[0] last_year = year - 1 command = "perl -pi -e 's/%s The Kreds/%s The Kreds/' %s" listFilesCommand = "find . | grep %s" extensions = [".cpp",".h"] def getLastGitModifiedDate(filePath): gitGetLastCommitDateCommand = "git log " + filePath +" | grep Date | head -n 1" p = os.popen(gitGetLastCommitDateCommand) result = "" for l in p: result = l break result = result.replace("\n","") return result n=1 for extension in extensions: foundFiles = os.popen(listFilesCommand % extension) for filePath in foundFiles: filePath = filePath[1:-1] if filePath.endswith(extension): filePath = os.getcwd() + filePath modifiedTime = getLastGitModifiedDate(filePath) if len(modifiedTime) > 0 and str(year) in modifiedTime: print n,"Last Git Modified: ", modifiedTime, " - ", filePath os.popen(command % (last_year,year,filePath)) n = n + 1
27.148148
81
0.691678
7951702049d771ceac98ebdd58ac3a3f56f4cfc8
18,899
py
Python
tools/odrive/tests/encoder_test.py
takijo0116/ODrive
4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2
[ "MIT" ]
1
2021-02-19T09:44:02.000Z
2021-02-19T09:44:02.000Z
tools/odrive/tests/encoder_test.py
takijo0116/ODrive
4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2
[ "MIT" ]
null
null
null
tools/odrive/tests/encoder_test.py
takijo0116/ODrive
4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2
[ "MIT" ]
null
null
null
import test_runner import time from math import pi import os from fibre.utils import Logger from odrive.enums import * from test_runner import * class TestEncoderBase(): """ Base class for encoder tests. TODO: incremental encoder doesn't use this yet. All encoder tests expect the encoder to run at a constant velocity. This can be achieved by generating an encoder signal with a Teensy. During 5 seconds, several variables are recorded and then compared against the expected waveform. This is either a straight line, a sawtooth function or a constant. """ def run_generic_encoder_test(self, encoder, true_cpr, true_rps, noise=1): encoder.config.cpr = true_cpr true_cps = true_cpr * true_rps encoder.set_linear_count(0) # prevent numerical errors data = record_log(lambda: [ encoder.shadow_count, encoder.count_in_cpr, encoder.phase, encoder.pos_estimate_counts, encoder.pos_cpr_counts, encoder.vel_estimate_counts, ], duration=5.0) short_period = (abs(1 / true_rps) < 5.0) reverse = (true_rps < 0) # encoder.shadow_count slope, offset, fitted_curve = fit_line(data[:,(0,1)]) test_assert_eq(slope, true_cps, accuracy=0.005) test_curve_fit(data[:,(0,1)], fitted_curve, max_mean_err = true_cpr * 0.02, inlier_range = true_cpr * 0.02, max_outliers = len(data[:,0]) * 0.02) # encoder.count_in_cpr slope, offset, fitted_curve = fit_sawtooth(data[:,(0,2)], true_cpr if reverse else 0, 0 if reverse else true_cpr) test_assert_eq(slope, true_cps, accuracy=0.005) test_curve_fit(data[:,(0,2)], fitted_curve, max_mean_err = true_cpr * 0.02, inlier_range = true_cpr * 0.02, max_outliers = len(data[:,0]) * 0.02 * noise) # encoder.pos_estimate slope, offset, fitted_curve = fit_line(data[:,(0,4)]) test_assert_eq(slope, true_cps, accuracy=0.005) test_curve_fit(data[:,(0,4)], fitted_curve, max_mean_err = true_cpr * 0.02, inlier_range = true_cpr * 0.02, max_outliers = len(data[:,0]) * 0.02) # encoder.pos_cpr slope, offset, fitted_curve = fit_sawtooth(data[:,(0,5)], true_cpr if reverse else 0, 0 if reverse else true_cpr) test_assert_eq(slope, true_cps, accuracy=0.005) test_curve_fit(data[:,(0,5)], fitted_curve, max_mean_err = true_cpr * 0.05, inlier_range = true_cpr * 0.05, max_outliers = len(data[:,0]) * 0.02) # encoder.vel_estimate slope, offset, fitted_curve = fit_line(data[:,(0,6)]) test_assert_eq(slope, 0.0, range = true_cpr * abs(true_rps) * 0.01) test_assert_eq(offset, true_cpr * true_rps, accuracy = 0.03) test_curve_fit(data[:,(0,6)], fitted_curve, max_mean_err = true_cpr * 0.05, inlier_range = true_cpr * 0.05 * noise, max_outliers = len(data[:,0]) * 0.05) teensy_incremental_encoder_emulation_code = """ void setup() { pinMode({enc_a}, OUTPUT); pinMode({enc_b}, OUTPUT); } int cpr = 8192; int rpm = 30; // the loop routine runs over and over again forever: void loop() { int microseconds_per_count = (1000000 * 60 / cpr / rpm); for (;;) { digitalWrite({enc_a}, HIGH); delayMicroseconds(microseconds_per_count); digitalWrite({enc_b}, HIGH); delayMicroseconds(microseconds_per_count); digitalWrite({enc_a}, LOW); delayMicroseconds(microseconds_per_count); digitalWrite({enc_b}, LOW); delayMicroseconds(microseconds_per_count); } } """ class TestIncrementalEncoder(TestEncoderBase): def get_test_cases(self, testrig: TestRig): for odrive in testrig.get_components(ODriveComponent): for encoder in odrive.encoders: # Find the Teensy that is connected to the encoder pins and the corresponding Teensy GPIOs gpio_conns = [ testrig.get_directly_connected_components(encoder.a), testrig.get_directly_connected_components(encoder.b), ] valid_combinations = [ (encoder, combination[0].parent,) + tuple(combination) + (None,) for combination in itertools.product(*gpio_conns) if ((len(set(c.parent for c in combination)) == 1) and isinstance(combination[0].parent, TeensyComponent)) ] yield AnyTestCase(*valid_combinations) def run_test(self, enc: ODriveEncoderComponent, teensy: TeensyComponent, teensy_gpio_a: TeensyGpio, teensy_gpio_b: TeensyGpio, logger: Logger): true_cps = 8192*0.5 # counts per second generated by the virtual encoder code = teensy_incremental_encoder_emulation_code.replace("{enc_a}", str(teensy_gpio_a.num)).replace("{enc_b}", str(teensy_gpio_b.num)) teensy.compile_and_program(code) if enc.handle.config.mode != ENCODER_MODE_INCREMENTAL: enc.handle.config.mode = ENCODER_MODE_INCREMENTAL enc.parent.save_config_and_reboot() else: time.sleep(1.0) # wait for PLLs to stabilize enc.handle.config.bandwidth = 1000 logger.debug("testing with 8192 CPR...") self.run_generic_encoder_test(enc.handle, 8192, true_cps / 8192) logger.debug("testing with 65536 CPR...") self.run_generic_encoder_test(enc.handle, 65536, true_cps / 65536) enc.handle.config.cpr = 8192 teensy_sin_cos_encoder_emulation_code = """ void setup() { analogWriteResolution(10); int freq = 150000000/1024; // ~146.5kHz PWM frequency analogWriteFrequency({enc_sin}, freq); analogWriteFrequency({enc_cos}, freq); } float rps = 1.0f; float pos = 0; void loop() { pos += 0.001f * rps; if (pos > 1.0f) pos -= 1.0f; analogWrite({enc_sin}, (int)(512.0f + 512.0f * sin(2.0f * M_PI * pos))); analogWrite({enc_cos}, (int)(512.0f + 512.0f * cos(2.0f * M_PI * pos))); delay(1); } """ class TestSinCosEncoder(TestEncoderBase): def get_test_cases(self, testrig: TestRig): for odrive in testrig.get_components(ODriveComponent): gpio_conns = [ testrig.get_directly_connected_components(odrive.gpio3), testrig.get_directly_connected_components(odrive.gpio4), ] valid_combinations = [ (odrive.encoders[0], combination[0].parent,) + tuple(combination) + (None,) for combination in itertools.product(*gpio_conns) if ((len(set(c.parent for c in combination)) == 1) and isinstance(combination[0].parent, TeensyComponent)) ] yield AnyTestCase(*valid_combinations) def run_test(self, enc: ODriveEncoderComponent, teensy: TeensyComponent, teensy_gpio_sin: TeensyGpio, teensy_gpio_cos: TeensyGpio, logger: Logger): code = teensy_sin_cos_encoder_emulation_code.replace("{enc_sin}", str(teensy_gpio_sin.num)).replace("{enc_cos}", str(teensy_gpio_cos.num)) teensy.compile_and_program(code) if enc.handle.config.mode != ENCODER_MODE_SINCOS: enc.parent.disable_mappings() enc.parent.handle.config.gpio3_mode = GPIO_MODE_ANALOG_IN enc.parent.handle.config.gpio4_mode = GPIO_MODE_ANALOG_IN enc.handle.config.mode = ENCODER_MODE_SINCOS enc.handle.config.bandwidth = 100 enc.parent.save_config_and_reboot() else: time.sleep(1.0) # wait for PLLs to stabilize self.run_generic_encoder_test(enc.handle, 6283, 1.0, 2.0) teensy_hall_effect_encoder_emulation_code = """ void setup() { pinMode({hall_a}, OUTPUT); pinMode({hall_b}, OUTPUT); pinMode({hall_c}, OUTPUT); digitalWrite({hall_a}, HIGH); } int cpr = 90; // 15 pole-pairs. Value suggested in hoverboard.md float rps = 1.0f; int us_per_count = (1000000.0f / cpr / rps); void loop() { digitalWrite({hall_b}, HIGH); delayMicroseconds(us_per_count); digitalWrite({hall_a}, LOW); delayMicroseconds(us_per_count); digitalWrite({hall_c}, HIGH); delayMicroseconds(us_per_count); digitalWrite({hall_b}, LOW); delayMicroseconds(us_per_count); digitalWrite({hall_a}, HIGH); delayMicroseconds(us_per_count); digitalWrite({hall_c}, LOW); delayMicroseconds(us_per_count); } """ class TestHallEffectEncoder(TestEncoderBase): def get_test_cases(self, testrig: TestRig): for odrive in testrig.get_components(ODriveComponent): for encoder in odrive.encoders: # Find the Teensy that is connected to the encoder pins and the corresponding Teensy GPIOs gpio_conns = [ testrig.get_directly_connected_components(encoder.a), testrig.get_directly_connected_components(encoder.b), testrig.get_directly_connected_components(encoder.z), ] valid_combinations = [ (encoder, combination[0].parent,) + tuple(combination) + (None,) for combination in itertools.product(*gpio_conns) if ((len(set(c.parent for c in combination)) == 1) and isinstance(combination[0].parent, TeensyComponent)) ] yield AnyTestCase(*valid_combinations) def run_test(self, enc: ODriveEncoderComponent, teensy: TeensyComponent, teensy_gpio_a: TeensyGpio, teensy_gpio_b: TeensyGpio, teensy_gpio_c: TeensyGpio, logger: Logger): true_cpr = 90 true_rps = 1.0 code = teensy_hall_effect_encoder_emulation_code.replace("{hall_a}", str(teensy_gpio_a.num)).replace("{hall_b}", str(teensy_gpio_b.num)).replace("{hall_c}", str(teensy_gpio_c.num)) teensy.compile_and_program(code) if enc.handle.config.mode != ENCODER_MODE_HALL: enc.handle.config.mode = ENCODER_MODE_HALL enc.handle.config.hall_polarity_calibrated = True if enc.parent.yaml['board-version'].startswith('v3.'): if enc.num: enc.parent.handle.config.gpio9_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio10_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio11_mode = GPIO_MODE_DIGITAL else: enc.parent.handle.config.gpio12_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio13_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio14_mode = GPIO_MODE_DIGITAL elif enc.parent.yaml['board-version'].startswith('v4.'): enc.parent.handle.config.gpio0_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio5_mode = GPIO_MODE_DIGITAL enc.parent.handle.config.gpio6_mode = GPIO_MODE_DIGITAL enc.parent.save_config_and_reboot() else: time.sleep(1.0) # wait for PLLs to stabilize enc.handle.config.bandwidth = 100 self.run_generic_encoder_test(enc.handle, true_cpr, true_rps) enc.parent.erase_config_and_reboot() # This encoder emulation mimics the specification given in the following datasheets: # # With {mode} == ENCODER_MODE_SPI_ABS_CUI: # AMT23xx: https://www.cuidevices.com/product/resource/amt23.pdf # # With {mode} == ENCODER_MODE_SPI_ABS_AMS: # AS5047P: https://ams.com/documents/20143/36005/AS5047P_DS000324_2-00.pdf/a7d44138-51f1-2f6e-c8b6-2577b369ace8 # AS5048A/AS5048B: https://ams.com/documents/20143/36005/AS5048_DS000298_4-00.pdf/910aef1f-6cd3-cbda-9d09-41f152104832 # => Only the read command on address 0x3fff is currently implemented. teensy_spi_encoder_emulation_code = """ #define ENCODER_MODE_SPI_ABS_CUI 0x100 #define ENCODER_MODE_SPI_ABS_AMS 0x101 #define ENCODER_MODE_SPI_ABS_AEAT 0x102 static float rps = 1.0f; static uint32_t cpr = 16384; static uint32_t us_per_revolution = (uint32_t)(1000000.0f / rps); static uint16_t spi_txd = 0; // first output word: NOP static uint32_t zerotime = 0; void setup() { pinMode({ncs}, INPUT_PULLUP); } uint16_t get_pos_now() { uint32_t time = micros(); return ((uint64_t)((time - zerotime) % us_per_revolution)) * cpr / us_per_revolution; } #if {mode} == ENCODER_MODE_SPI_ABS_AMS uint8_t ams_parity(uint16_t v) { v ^= v >> 8; v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return v & 1; } uint16_t handle_command(uint16_t cmd) { const uint16_t ERROR_RESPONSE = 0xc000; // error flag and parity bit set if (ams_parity(cmd)) { return ERROR_RESPONSE; } if (!(cmd & 14)) { // write not supported return ERROR_RESPONSE; } uint16_t addr = cmd & 0x3fff; uint16_t data; switch (addr) { case 0x3fff: data = get_pos_now(); break; default: return ERROR_RESPONSE; } return data | (ams_parity(data) << 15); } #endif #if {mode} == ENCODER_MODE_SPI_ABS_CUI uint8_t cui_parity(uint16_t v) { v ^= v >> 8; v ^= v >> 4; v ^= v >> 2; return ~v & 3; } uint16_t handle_command(uint16_t cmd) { (void) cmd; // input not used on CUI // Test the cui_parity function itself with the example given in the datasheet if ((0x21AB | (cui_parity(0x21AB) << 14)) != 0x61AB) { return 0x0000; } uint16_t data = get_pos_now(); return data | (cui_parity(data) << 14); } #endif void loop() { while (digitalReadFast({reset})) { zerotime = micros(); } if (!digitalReadFast({ncs})) { static uint16_t spi_rxd = 0; pinMode({miso}, OUTPUT); for (;;) { while (!digitalReadFast({sck})) if (digitalReadFast({ncs})) goto cs_deasserted; // Rising edge: Push output bit bool output_bit = spi_txd & 0x8000; digitalWriteFast({miso}, output_bit); spi_txd <<= 1; while (digitalReadFast({sck})) if (digitalReadFast({ncs})) goto cs_deasserted; // Falling edge: Sample input bit (only in AMS mode) #if {mode} == ENCODER_MODE_SPI_ABS_AMS bool input_bit = digitalReadFast({mosi}); spi_rxd <<= 1; if (input_bit) { spi_rxd |= 1; } else { spi_rxd &= ~1; } #endif } cs_deasserted: // chip deselected: Process command pinMode({miso}, INPUT); spi_txd = handle_command(spi_rxd); } } """ class TestSpiEncoder(TestEncoderBase): def __init__(self, mode: int): self.mode = mode def get_test_cases(self, testrig: TestRig): for encoder in testrig.get_components(ODriveEncoderComponent): odrive = encoder.parent odrive_ncs_gpio = odrive.gpio7 # this GPIO choice is completely arbitrary for teensy in testrig.get_components(TeensyComponent): gpio_conns = [ testrig.net_by_component.get(odrive.sck, set()).intersection(set(teensy.gpios)), testrig.net_by_component.get(odrive.miso, set()).intersection(set(teensy.gpios)), testrig.net_by_component.get(odrive.mosi, set()).intersection(set(teensy.gpios)), testrig.net_by_component.get(odrive_ncs_gpio, set()).intersection(set(teensy.gpios)), teensy.gpios ] alternatives = [] for gpio1, gpio2, gpio3, gpio4, gpio5 in itertools.product(*gpio_conns): for local_reset_gpio, tf in testrig.get_connected_components(gpio5, LinuxGpioComponent): alternatives.append((encoder, 7, teensy, gpio1, gpio2, gpio3, gpio4, gpio5, local_reset_gpio, tf)) yield AnyTestCase(*alternatives) def run_test(self, enc: ODriveEncoderComponent, odrive_ncs_gpio: int, teensy: TeensyComponent, teensy_gpio_sck: TeensyGpio, teensy_gpio_miso: TeensyGpio, teensy_gpio_mosi: TeensyGpio, teensy_gpio_ncs: TeensyGpio, teensy_gpio_reset: TeensyGpio, reset_gpio: LinuxGpioComponent, logger: Logger): true_cpr = 16384 true_rps = 1.0 reset_gpio.config(output=True) # hold encoder and disable its SPI reset_gpio.write(True) code = (teensy_spi_encoder_emulation_code .replace("{sck}", str(teensy_gpio_sck.num)) .replace("{miso}", str(teensy_gpio_miso.num)) .replace("{mosi}", str(teensy_gpio_mosi.num)) .replace("{ncs}", str(teensy_gpio_ncs.num)) .replace("{reset}", str(teensy_gpio_reset.num)) .replace("{mode}", str(self.mode))) teensy.compile_and_program(code) logger.debug(f'Configuring absolute encoder in mode 0x{self.mode:x}...') enc.handle.config.mode = self.mode setattr(enc.parent.handle.config, 'gpio' + str(odrive_ncs_gpio) + '_mode', GPIO_MODE_ANALOG_IN) enc.handle.config.abs_spi_cs_gpio_pin = odrive_ncs_gpio enc.handle.config.cpr = true_cpr # Also put the other encoder into SPI mode to make it more interesting other_enc = enc.parent.encoders[1 - enc.num] other_enc.handle.config.mode = self.mode other_enc.handle.config.abs_spi_cs_gpio_pin = odrive_ncs_gpio other_enc.handle.config.cpr = true_cpr enc.parent.save_config_and_reboot() time.sleep(1.0) logger.debug('Testing absolute readings and SPI errors...') # Encoder is still disabled - expect recurring error enc.handle.error = 0 time.sleep(0.002) # This fails from time to time because the pull-up on the ODrive only manages # to pull MISO to 1.8V, leaving it in the undefined range. test_assert_eq(enc.handle.error, ENCODER_ERROR_ABS_SPI_COM_FAIL) # Enable encoder and expect error to go away reset_gpio.write(False) release_time = time.monotonic() enc.handle.error = 0 time.sleep(0.002) test_assert_eq(enc.handle.error, 0) # Check absolute position after 1.5s time.sleep(1.5) true_delta_t = time.monotonic() - release_time test_assert_eq(enc.handle.pos_abs, (true_delta_t * true_rps * true_cpr) % true_cpr, range = true_cpr*0.002) test_assert_eq(enc.handle.error, 0) reset_gpio.write(True) time.sleep(0.002) test_assert_eq(enc.handle.error, ENCODER_ERROR_ABS_SPI_COM_FAIL) reset_gpio.write(False) release_time = time.monotonic() enc.handle.error = 0 time.sleep(0.002) test_assert_eq(enc.handle.error, 0) # Check absolute position after 1.5s time.sleep(1.5) true_delta_t = time.monotonic() - release_time test_assert_eq(enc.handle.pos_abs, (true_delta_t * true_rps * true_cpr) % true_cpr, range = true_cpr*0.002) self.run_generic_encoder_test(enc.handle, true_cpr, true_rps) enc.handle.config.cpr = 8192 tests = [ TestIncrementalEncoder(), TestSinCosEncoder(), TestHallEffectEncoder(), TestSpiEncoder(ENCODER_MODE_SPI_ABS_AMS), TestSpiEncoder(ENCODER_MODE_SPI_ABS_CUI), ] if __name__ == '__main__': test_runner.run(tests)
36.344231
296
0.65776
79517070b58c3bc3e51b78c9c47951963503bd7c
2,649
py
Python
matcher/Model/Phrase_Matcher_Predictor.py
INK-USC/expl-refinement
815a7892a8d4c42fb429856746212a44f67d2547
[ "MIT" ]
7
2021-09-29T08:14:30.000Z
2022-03-27T13:12:37.000Z
matcher/Model/Phrase_Matcher_Predictor.py
INK-USC/expl-refinement
815a7892a8d4c42fb429856746212a44f67d2547
[ "MIT" ]
null
null
null
matcher/Model/Phrase_Matcher_Predictor.py
INK-USC/expl-refinement
815a7892a8d4c42fb429856746212a44f67d2547
[ "MIT" ]
null
null
null
from Model.Phrase_Matcher import * import torch, time, numpy as np class Phrase_Matcher_Predictor: def __init__(self, batch_size): self.batch_size = batch_size def predict(self, model_, data, train_mode): all_scores = [] model_.eval() for i in range(int(np.ceil(len(data)/self.batch_size))): batch = data[(i*self.batch_size):((i+1)*self.batch_size)] scores = model_(batch, train_mode) all_scores += [[r.tolist() for r in rr] for rr in scores] return all_scores def load_model(self, gpu_id, module='find'): if module == 'find': # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_find_91.model" # best without fine-tuning BERT # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_find_86.model" # best of all model_path = "/home/huihan/newest/Expl-Reg/matcher/checkpoint/clean_find.model" # untrained baseline # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_find_baseline_train2.model" # best trained baseline saved = torch.load(model_path) self.args = saved['args'] self.args['gpu'] = gpu_id self.args['cuda_device'] = torch.device("cuda:"+str(gpu_id)) self.model_ = Phrase_Matcher(self.args) self.model_.load_state_dict(saved['state_dict']) elif module == 'fill': # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_fill_62.model" # best without fine-tuning BERT model_path = "/home/xiaohuang/qa-nle/checkpoint/train_fill_69.model" # previous best of all # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_fill_baseline.model" # untrained baseline # model_path = "/home/xiaohuang/qa-nle/checkpoint/train_fill_baseline_train2.model" # best trained baseline, best of all saved = torch.load(model_path) self.args = saved['args'] self.args['gpu'] = gpu_id self.args['cuda_device'] = torch.device("cuda:"+str(gpu_id)) self.model_ = Phrase_Matcher(self.args) self.model_.load_state_dict(saved['state_dict']) def run(self, data): assert self.model_ , "must call load_model first" all_scores = self.predict(self.model_, data, self.args['train_mode']) # returned scores are flattened once, need reforming all_scores_, i = [], 0 for d in data: num_query_spans = len(d[1]) all_scores_.append(all_scores[i:(i+num_query_spans)]) i += num_query_spans return all_scores_
48.163636
132
0.629294
79517169bfcfbf587a4aa12dcce68d91a78e0c0f
2,440
py
Python
nemo/collections/common/tokenizers/youtokentome_tokenizer.py
vadam5/NeMo
3c5db09539293c3c19a6bb7437011f91261119af
[ "Apache-2.0" ]
2
2021-09-21T07:36:20.000Z
2022-02-05T15:29:04.000Z
nemo/collections/common/tokenizers/youtokentome_tokenizer.py
vadam5/NeMo
3c5db09539293c3c19a6bb7437011f91261119af
[ "Apache-2.0" ]
null
null
null
nemo/collections/common/tokenizers/youtokentome_tokenizer.py
vadam5/NeMo
3c5db09539293c3c19a6bb7437011f91261119af
[ "Apache-2.0" ]
12
2021-06-20T08:56:10.000Z
2022-03-16T19:07:10.000Z
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path import youtokentome as yttm from nemo.collections.common.tokenizers import TokenizerSpec __all__ = ['YouTokenToMeTokenizer'] class YouTokenToMeTokenizer(TokenizerSpec): def __init__(self, model_path, bpe_dropout=0.0, legacy=False): model_path = Path(model_path).expanduser() self.tokenizer = yttm.BPE(model=str(model_path)) self.vocab_size = len(self.tokenizer.vocab()) self.special_tokens = self.tokens_to_ids(["<PAD>", "<UNK>", "<BOS>", "<EOS>"]) self.bpe_dropout = bpe_dropout self.legacy = legacy def text_to_tokens(self, text): return self.tokenizer.encode(text, output_type=yttm.OutputType.SUBWORD, dropout_prob=self.bpe_dropout) def tokens_to_text(self, tokens): return self.ids_to_text(self.tokens_to_ids(tokens)) def text_to_ids(self, text): return self.tokenizer.encode(text, output_type=yttm.OutputType.ID, dropout_prob=self.bpe_dropout) def ids_to_text(self, ids): ids_ = [id_ for id_ in ids if id_ not in self.special_tokens] return self.tokenizer.decode([ids_])[0] def tokens_to_ids(self, tokens): return [self.tokenizer.subword_to_id(token) for token in tokens] def ids_to_tokens(self, ids): if self.legacy: ids_ = [id_ for id_ in ids if id_ not in self.special_tokens] else: ids_ = ids return [self.tokenizer.id_to_subword(id_) for id_ in ids_] @property def pad_id(self): return self.tokenizer.subword_to_id("<PAD>") @property def bos_id(self): return self.tokenizer.subword_to_id("<BOS>") @property def eos_id(self): return self.tokenizer.subword_to_id("<EOS>") @property def unk_id(self): return self.tokenizer.subword_to_id("<UNK>")
34.366197
110
0.697951
795171fb287ac14974ae3430e056b7e8fb0e6c86
1,838
py
Python
days/37-39-csv-data-analsys/unisex_names/research.py
Oniwa/100daysofcode-with-python-course
12a53b2fc4e7047d664216a86def62ebfc29e03b
[ "MIT" ]
null
null
null
days/37-39-csv-data-analsys/unisex_names/research.py
Oniwa/100daysofcode-with-python-course
12a53b2fc4e7047d664216a86def62ebfc29e03b
[ "MIT" ]
null
null
null
days/37-39-csv-data-analsys/unisex_names/research.py
Oniwa/100daysofcode-with-python-course
12a53b2fc4e7047d664216a86def62ebfc29e03b
[ "MIT" ]
1
2019-10-07T09:30:10.000Z
2019-10-07T09:30:10.000Z
import os import csv import collections from typing import List data = [] Record = collections.namedtuple('Record', 'uid,name,total,' 'male_share,female_share,gap') def init(): base_folder = os.path.dirname(__file__) filename = os.path.join(base_folder, 'data', 'unisex_names_table.csv') with open(filename, 'r', encoding='utf-8') as fin: reader = csv.DictReader(fin) data.clear() for row in reader: record = parse_row(row) data.append(record) def parse_row(row): row[''] = int(row['']) row['total'] = float(row['total']) row['male_share'] = float(row['male_share']) row['female_share'] = float(row['female_share']) row['gap'] = float(row['gap']) record = Record(row[''], row['name'], row['total'], row['male_share'], row['female_share'], row['gap']) return record def most_male_name() -> List[Record]: return sorted(data, key=lambda r: -r.male_share) def most_female_name() -> List[Record]: return sorted(data, key=lambda r: -r.female_share) def most_unisex_name() -> List[Record]: return sorted(data, key=lambda r: r.gap) if __name__ == '__main__': print('Unisex Names') init() print('The 5 most male unisex names') names = most_male_name() for idx, d in enumerate(names[:5]): print(f'{idx+1} {d.name} with {d.male_share} % Male') print('The 5 most female unisex names') names = most_female_name() for idx, d in enumerate(names[:5]): print(f'{idx+1} {d.name} with {d.female_share} % Female') print('The 5 most unisex names') names = most_unisex_name() for idx, d in enumerate(names[:5]): print(f'{idx+1} {d.name} with {d.gap} % difference between male ' f'and female usage')
28.276923
74
0.60555
7951747709b54a988f7438dd783c2eabdb37d89d
11,753
py
Python
bin/physiboss.py
marcorusc/project_repo_ecm_simul
167cce668631be12f88e9f4936b4c39e71963e39
[ "BSD-3-Clause" ]
1
2020-05-08T14:09:15.000Z
2020-05-08T14:09:15.000Z
bin/physiboss.py
marcorusc/project_repo_ecm_simul
167cce668631be12f88e9f4936b4c39e71963e39
[ "BSD-3-Clause" ]
1
2020-09-08T10:58:54.000Z
2020-09-08T10:58:54.000Z
bin/physiboss.py
marcorusc/project_repo_ecm_simul
167cce668631be12f88e9f4936b4c39e71963e39
[ "BSD-3-Clause" ]
1
2020-07-23T08:26:18.000Z
2020-07-23T08:26:18.000Z
# PhysiBoSS Tab import os from ipywidgets import Layout, Label, Text, Checkbox, Button, HBox, VBox, Box, \ FloatText, BoundedIntText, BoundedFloatText, HTMLMath, Dropdown, interactive, Output from collections import deque, Counter import xml.etree.ElementTree as ET import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection import matplotlib.colors as mplc import numpy as np import glob import platform import numpy as np import csv import itertools import copy import scipy # from debug import debug_view class PhysiBoSSTab(object): def __init__(self): # tab_height = '520px' # tab_layout = Layout(width='900px', # border='2px solid black', # height=tab_height, overflow_y='scroll') self.output_dir = '.' constWidth = '180px' # self.fig = plt.figure(figsize=(6, 6)) # self.fig = plt.figure(figsize=(7, 7)) config_file = "data/PhysiCell_settings.xml" self.cell_lines = {} self.cell_lines_by_name = {} self.cell_lines_array = ["All"] if os.path.isfile(config_file): try: tree = ET.parse(config_file) except: print("Cannot parse",config_file, "- check it's XML syntax.") return root = tree.getroot() uep = root.find('.//cell_definitions') # find unique entry point (uep) for child in uep.findall('cell_definition'): self.cell_lines[int(child.attrib["ID"])] = child.attrib["name"] self.cell_lines_by_name[child.attrib["name"]] = int(child.attrib["ID"]) self.cell_lines_array.append(child.attrib["name"]) # print(child.attrib['name']) else: print("config.xml does not exist") max_frames = 0 self.svg_plot = interactive(self.create_area_chart, frame=(0, max_frames), percentage=(0.0, 10.0), total=False, cell_line=self.cell_lines_array, continuous_update=False) plot_size = '500px' # small: controls the size of the tab height, not the plot (rf. figsize for that) plot_size = '700px' # medium plot_size = '750px' # medium self.svg_plot.layout.width = '1000px' self.svg_plot.layout.height = '700px' self.use_defaults = True self.axes_min = 0.0 self.axes_max = 2000 # hmm, this can change (TODO?) self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', layout=Layout(width='160px'), # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) items_auto = [Label('select slider: drag or left/right arrows'), self.max_frames, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='70%') row1 = Box(children=items_auto, layout=box_layout) self.tab = VBox([row1, self.svg_plot]) self.count_dict = {} self.file_dict = {} def update(self, rdir=''): # with debug_view: # print("SVG: update rdir=", rdir) if rdir: self.output_dir = rdir all_files = sorted(glob.glob(os.path.join(self.output_dir, 'snapshot*.svg'))) if len(all_files) > 0: last_file = all_files[-1] self.max_frames.value = int(last_file[-12:-4]) # assumes naming scheme: "snapshot%08d.svg" # self.create_dict(self.max_frames.value, self.output_dir) # self.state_counter(self.max_frames.value) # with debug_view: # print("SVG: added %s files" % len(all_files)) def update_max_frames(self,_b): self.svg_plot.children[0].max = self.max_frames.value #------------------------- def plot_states(self, frame): # global current_idx, axes_max global current_frame current_frame = frame fname = "snapshot%08d.svg" % frame full_fname = os.path.join(self.output_dir, fname) if not os.path.isfile(full_fname): print("Once output files are generated, click the slider.") return tree = ET.parse(full_fname) root = tree.getroot() numChildren = 0 for child in root: if self.use_defaults and ('width' in child.attrib.keys()): self.axes_max = float(child.attrib['width']) if child.text and "Current time" in child.text: svals = child.text.split() title_str = svals[2] + "d, " + svals[4] + "h, " + svals[7] + "m" title_str += " (" + str(num_cells) + " agents)" self.fig = plt.figure(figsize=(15, 15)) plt.xlim(self.axes_min, self.axes_max) plt.ylim(self.axes_min, self.axes_max) plt.title(title_str) def create_dict(self, number_of_files, folder, cells_indexes): "create a dictionary with the states file in the folder 'output', half of the dict is used to calculate the percentage of the node, the other half is for the states" # if not os.path.isfile("%sstates_00000000.csv" % folder): # return self.file_dict = {} if number_of_files > 0: for i in range (0, number_of_files): nodes_dict = {} states_dict = {} with open('%s//states_%08u.csv' %(folder,i), newline='') as csvfile: states_reader = csv.reader(csvfile, delimiter=',') for row in states_reader: if row[0] != 'ID' and (cells_indexes is None or int(row[0]) in cells_indexes): states_dict[row[0]] = row[1] nodes_dict[row[0]] = row[1].replace("--", "").split() self.file_dict["node_step{0}".format(i)] = nodes_dict self.file_dict["state_step{0}".format(i)] = states_dict # print(self.file_dict) # return file_dict def state_counter(self, number_of_files, percentage): "create a dict with the states of the network, it can be used to print states pie chart" self.count_dict = {} temp_dict = {} max_cell = 0 if number_of_files > 0: for i in range (0, number_of_files): state_list = [] for key in self.file_dict["state_step{0}".format(i)]: state_list.append(self.file_dict["state_step{0}".format(i)][key]) state_counts = Counter(state_list) max_cell = max_cell + sum(state_counts.values()) #fix_count_dict = {} #for key, group in itertools.groupby(state_counts, lambda k: 'others' if (state_counts[k]<(0.01* (len(self.file_dict["state_step%s" %(i)])))) else k): #fix_count_dict[key] = sum([state_counts[k] for k in list(group)]) temp_dict["state_count{0}".format(i)] = state_counts self.count_dict = self.filter_states(max_cell, temp_dict, percentage) # return self.count_dict def create_area_chart(self, frame=None, total=False, percentage=(0.0, 100.0), cell_line="All"): "plot an area chart with the evolution of the network states during the simulation" cells_indexes = None if cell_line != "All": cells_indexes = set() for i in range(0, frame): fname = "output%08d_cells_physicell.mat" % i full_fname = os.path.join(self.output_dir, fname) if not os.path.isfile(full_fname): print("Once output files are generated, click the slider.") # No: output00000000_microenvironment0.mat return info_dict = {} scipy.io.loadmat(full_fname, info_dict) M = info_dict['cells'][[0,5], :].astype(int) cell_line_index = self.cell_lines_by_name[cell_line] indexes = np.where(M[1, :] == cell_line_index) cells_indexes = cells_indexes.union(set(M[0, indexes][0])) cells_indexes = list(cells_indexes) if len(cells_indexes) == 0: print("There are no %s cells." % cell_line) return self.create_dict(frame, self.output_dir, cells_indexes) self.state_counter(frame, percentage) state_list = [] all_state = [] a = [] for k in self.count_dict: state_list.append(list(self.count_dict[k].keys())) for l in state_list: for state in l: all_state.append(state) all_state = list(dict.fromkeys(all_state)) for state_count in self.count_dict: b = [] for states in all_state: try: b.append(self.count_dict[state_count][states]) except: b.append(0) a.append(b) a = np.array(a) #print(a) a = np.transpose(a) if not total: percent = a / a.sum(axis=0).astype(float) * 100 else: percent = a x = np.arange(len(self.count_dict)) self.fig = plt.figure(figsize=(10,5), dpi=200) ax = self.fig.add_subplot(111) ax.stackplot(x, percent, labels=all_state) ax.legend(labels=all_state, loc='upper center', bbox_to_anchor=(0.5, -0.05),shadow=True, ncol=2) # ax.legend(labels=all_state, bbox_to_anchor=(1.05, 1), loc='lower center', borderaxespad=0.) ax.set_title('100 % stacked area chart') if not total: ax.set_ylabel('Percent (%)') else: ax.set_ylabel("Total") ax.margins(0, 0) # Set margins to avoid "whitespace" # plt.show() def filter_states(self, max_cell, all_counts, percentage): """max_cell = 0 all_counts = {} for i in range (0, number_of_files): state_list = [] for key in file_dict["state_step{0}".format(i)]: state_list.append(file_dict["state_step{0}".format(i)][key]) state_counts = Counter(state_list) max_cell = max_cell + sum(state_counts.values()) all_counts[i] = state_counts""" copy_all_counts = copy.deepcopy(all_counts) state_list = [] all_state = [] for k in all_counts: state_list.append(list(all_counts[k].keys())) for l in state_list: for state in l: all_state.append(state) all_state = list(dict.fromkeys(all_state)) banned_list = [] for state in all_state: a = 0 for i in all_counts.keys(): try: a = a + all_counts[i][state] except: a = a + 0 if (a < (percentage/100) * max_cell): banned_list.append(state) for i in all_counts.keys(): del all_counts[i][state] for i in all_counts.keys(): b = 0 for state in banned_list: try: b = b + copy_all_counts[i][state] except: b = b + 0 all_counts[i]["others"] = b return all_counts
37.07571
177
0.547605
79517539e83152f9244e4ab5502fe2f3261da193
8,010
py
Python
openspeech/datasets/aishell/lit_data_module.py
techthiyanes/openspeech
71d28bae1232420da1d6f357f52ff1a607dc983f
[ "Apache-2.0", "MIT" ]
207
2021-07-22T02:04:47.000Z
2022-03-31T07:24:12.000Z
openspeech/datasets/aishell/lit_data_module.py
tqslj2/openspeech
10307587f08615224df5a868fb5249c68c70b12d
[ "Apache-2.0", "MIT" ]
81
2021-07-21T16:52:22.000Z
2022-03-31T14:56:54.000Z
openspeech/datasets/aishell/lit_data_module.py
tqslj2/openspeech
10307587f08615224df5a868fb5249c68c70b12d
[ "Apache-2.0", "MIT" ]
43
2021-07-21T16:33:27.000Z
2022-03-23T09:43:49.000Z
# MIT License # # Copyright (c) 2021 Soohwan Kim and Sangchun Ha and Soyoung Cho # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import tarfile import wget import pytorch_lightning as pl import logging from omegaconf import DictConfig from typing import Optional, Tuple from openspeech.data.audio.dataset import SpeechToTextDataset from openspeech.datasets import register_data_module from openspeech.data.sampler import RandomSampler, SmartBatchingSampler from openspeech.data.audio.data_loader import AudioDataLoader from openspeech.tokenizers.tokenizer import Tokenizer from openspeech.datasets.aishell.preprocess import ( generate_character_labels, generate_character_script, ) @register_data_module('aishell') class LightningAIShellDataModule(pl.LightningDataModule): r""" Lightning data module for AIShell-1. The corpus includes training set, development set and test sets. Training set contains 120,098 utterances from 340 speakers; development set contains 14,326 utterance from the 40 speakers; Test set contains 7,176 utterances from 20 speakers. For each speaker, around 360 utterances (about 26 minutes of speech) are released. Args: configs (DictConfig): configuration set. """ AISHELL_TRAIN_NUM = 120098 AISHELL_VALID_NUM = 14326 AISHELL_TEST_NUM = 7176 def __init__(self, configs: DictConfig): super(LightningAIShellDataModule, self).__init__() self.configs = configs self.dataset = dict() self.logger = logging.getLogger(__name__) def _download_dataset(self) -> None: r""" Download aishell dataset. """ url = "https://www.openslr.org/resources/33/data_aishell.tgz" if not os.path.exists(self.configs.dataset.dataset_path): os.mkdir(self.configs.dataset.dataset_path) wget.download(url, f"{self.configs.dataset.dataset_path}/data_aishell.tgz") self.logger.info(f"Un-tarring archive {self.configs.dataset.dataset_path}/data_aishell.tgz") tar = tarfile.open(f"{self.configs.dataset.dataset_path}/data_aishell.tgz", mode="r:gz") tar.extractall(self.configs.dataset.dataset_path) tar.close() os.remove(f"{self.configs.dataset.dataset_path}/data_aishell.tgz") self.configs.dataset.dataset_path = os.path.join(self.configs.dataset.dataset_path, "data_aishell") def _generate_manifest_files(self, manifest_file_path: str) -> None: generate_character_labels( dataset_path=self.configs.dataset.dataset_path, vocab_path=self.configs.tokenizer.vocab_path, ) generate_character_script( dataset_path=self.configs.dataset.dataset_path, manifest_file_path=manifest_file_path, vocab_path=self.configs.tokenizer.vocab_path, ) def _parse_manifest_file(self, manifest_file_path: str) -> Tuple[list, list]: """ Parsing manifest file """ audio_paths = list() transcripts = list() with open(manifest_file_path) as f: for idx, line in enumerate(f.readlines()): audio_path, _, transcript = line.split('\t') transcript = transcript.replace('\n', '') audio_paths.append(audio_path) transcripts.append(transcript) return audio_paths, transcripts def prepare_data(self): r""" Prepare AI-Shell manifest file. If there is not exist manifest file, generate manifest file. Returns: tokenizer (Tokenizer): tokenizer is in charge of preparing the inputs for a model. """ if self.configs.dataset.dataset_download: self._download_dataset() if not os.path.exists(self.configs.dataset.manifest_file_path): self.logger.info("Manifest file is not exists !!\n" "Generate manifest files..") if not os.path.exists(self.configs.dataset.dataset_path): raise ValueError("Dataset path is not valid.") self._generate_manifest_files(self.configs.dataset.manifest_file_path) def setup(self, stage: Optional[str] = None, tokenizer: Tokenizer = None): r""" Split `train` and `valid` dataset for training. Args: stage (str): stage of training. `train` or `valid` tokenizer (Tokenizer): tokenizer is in charge of preparing the inputs for a model. Returns: None """ valid_end_idx = self.AISHELL_TRAIN_NUM + self.AISHELL_VALID_NUM audio_paths, transcripts = self._parse_manifest_file(self.configs.dataset.manifest_file_path) audio_paths = { "train": audio_paths[:self.AISHELL_TRAIN_NUM], "valid": audio_paths[self.AISHELL_TRAIN_NUM:valid_end_idx], "test": audio_paths[valid_end_idx:], } transcripts = { "train": transcripts[:self.AISHELL_TRAIN_NUM], "valid": transcripts[self.AISHELL_TRAIN_NUM:valid_end_idx], "test": transcripts[valid_end_idx:], } for stage in audio_paths.keys(): self.dataset[stage] = SpeechToTextDataset( configs=self.configs, dataset_path=self.configs.dataset.dataset_path, audio_paths=audio_paths[stage], transcripts=transcripts[stage], sos_id=tokenizer.sos_id, eos_id=tokenizer.eos_id, apply_spec_augment=self.configs.audio.apply_spec_augment if stage == 'train' else False, del_silence=self.configs.audio.del_silence if stage == 'train' else False, ) def train_dataloader(self) -> AudioDataLoader: sampler = SmartBatchingSampler if self.configs.trainer.sampler == 'smart' else RandomSampler train_sampler = sampler(data_source=self.dataset['train'], batch_size=self.configs.trainer.batch_size) return AudioDataLoader( dataset=self.dataset['train'], num_workers=self.configs.trainer.num_workers, batch_sampler=train_sampler, ) def val_dataloader(self) -> AudioDataLoader: sampler = SmartBatchingSampler if self.configs.trainer.sampler == 'smart' else RandomSampler valid_sampler = sampler(self.dataset['valid'], batch_size=self.configs.trainer.batch_size) return AudioDataLoader( dataset=self.dataset['valid'], num_workers=self.configs.trainer.num_workers, batch_sampler=valid_sampler, ) def test_dataloader(self) -> AudioDataLoader: sampler = SmartBatchingSampler if self.configs.trainer.sampler == 'smart' else RandomSampler test_sampler = sampler(self.dataset['test'], batch_size=self.configs.trainer.batch_size) return AudioDataLoader( dataset=self.dataset['test'], num_workers=self.configs.trainer.num_workers, batch_sampler=test_sampler, )
43.297297
113
0.688514
795175bcb76caf23f932532a6af34c1a1f41900f
988
py
Python
kubernetes/test/test_v1_local_volume_source.py
sgwilliams-ebsco/python
35e6406536c96d4769ff7e2a02bf0fdcb902a509
[ "Apache-2.0" ]
1
2021-06-10T23:44:11.000Z
2021-06-10T23:44:11.000Z
kubernetes/test/test_v1_local_volume_source.py
sgwilliams-ebsco/python
35e6406536c96d4769ff7e2a02bf0fdcb902a509
[ "Apache-2.0" ]
null
null
null
kubernetes/test/test_v1_local_volume_source.py
sgwilliams-ebsco/python
35e6406536c96d4769ff7e2a02bf0fdcb902a509
[ "Apache-2.0" ]
1
2018-11-06T16:33:43.000Z
2018-11-06T16:33:43.000Z
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_local_volume_source import V1LocalVolumeSource class TestV1LocalVolumeSource(unittest.TestCase): """ V1LocalVolumeSource unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1LocalVolumeSource(self): """ Test V1LocalVolumeSource """ # FIXME: construct object with mandatory attributes with example values #model = kubernetes.client.models.v1_local_volume_source.V1LocalVolumeSource() pass if __name__ == '__main__': unittest.main()
21.955556
105
0.716599
795175cd50a9f44b9a70794a8565088798251296
1,111
py
Python
tests/unit/crt/auth/test_crt_sigv4.py
karim7262/botocore
070204a0afb94c23dcfe040f4933c74ab1d8e089
[ "Apache-2.0" ]
1,063
2015-01-13T13:35:09.000Z
2022-03-31T09:29:32.000Z
tests/unit/crt/auth/test_crt_sigv4.py
karim7262/botocore
070204a0afb94c23dcfe040f4933c74ab1d8e089
[ "Apache-2.0" ]
2,064
2015-01-03T15:53:33.000Z
2022-03-31T23:12:08.000Z
tests/unit/crt/auth/test_crt_sigv4.py
karim7262/botocore
070204a0afb94c23dcfe040f4933c74ab1d8e089
[ "Apache-2.0" ]
1,065
2015-01-16T15:58:42.000Z
2022-03-31T22:18:56.000Z
import pytest from tests import requires_crt, FreezeTime from tests.unit.auth.test_sigv4 import ( DATE, SERVICE, REGION, SignatureTestCase, assert_equal, create_request_from_raw_request, generate_test_cases, ) import botocore def _test_crt_signature_version_4(test_case): test_case = SignatureTestCase(test_case) request = create_request_from_raw_request(test_case.raw_request) # Use CRT logging to diagnose interim steps (canonical request, etc) # import awscrt.io # awscrt.io.init_logging(awscrt.io.LogLevel.Trace, 'stdout') auth = botocore.crt.auth.CrtSigV4Auth(test_case.credentials, SERVICE, REGION) auth.add_auth(request) actual_auth_header = request.headers["Authorization"] assert_equal( actual_auth_header, test_case.authorization_header, test_case.raw_request, "authheader", ) @requires_crt() @pytest.mark.parametrize("test_case", generate_test_cases()) @FreezeTime(module=botocore.auth.datetime, date=DATE) def test_signature_version_4(test_case): _test_crt_signature_version_4(test_case)
27.775
81
0.753375
795176046bae2ca7457990e3a7eb41c09cf08f67
695
py
Python
src/sw/allotmentclub/alembic/versions/re_28_save_message_tag_instead_of__3b50f99a2e2f.py
sweh/sw.allotmentclub.backend
77344045e29c2b173d635e9e20a0ca556161888e
[ "ZPL-2.1" ]
1
2019-11-12T08:13:18.000Z
2019-11-12T08:13:18.000Z
src/sw/allotmentclub/alembic/versions/re_28_save_message_tag_instead_of__3b50f99a2e2f.py
sweh/sw.allotmentclub.backend
77344045e29c2b173d635e9e20a0ca556161888e
[ "ZPL-2.1" ]
26
2020-05-16T12:08:25.000Z
2022-03-12T00:53:57.000Z
src/sw/allotmentclub/alembic/versions/re_28_save_message_tag_instead_of__3b50f99a2e2f.py
sweh/sw.allotmentclub.backend
77344045e29c2b173d635e9e20a0ca556161888e
[ "ZPL-2.1" ]
null
null
null
"""re #28: Save message tag instead of Message-ID. Revision ID: 3b50f99a2e2f Revises: ff1bb01af7fa Create Date: 2016-11-23 09:24:49.794794 """ # revision identifiers, used by Alembic. from alembic import op import sqlalchemy as sa revision = '3b50f99a2e2f' down_revision = 'ff1bb01af7fa' def upgrade(): op.add_column('sentmessageinfo', sa.Column('tag', sa.String(length=100), nullable=True)) op.drop_column('sentmessageinfo', 'msg_id') def downgrade(): op.add_column('sentmessageinfo', sa.Column('msg_id', sa.VARCHAR(length=100), autoincrement=False, nullable=True)) op.drop_column('sentmessageinfo', 'tag')
25.740741
73
0.670504
7951774ff6b664ddc033bfdbdceea20f513cb14b
1,374
py
Python
kolibri/core/content/test/test_paths.py
MBKayro/kolibri
0a38a5fb665503cf8f848b2f65938e73bfaa5989
[ "MIT" ]
545
2016-01-19T19:26:55.000Z
2022-03-20T00:13:04.000Z
kolibri/core/content/test/test_paths.py
MBKayro/kolibri
0a38a5fb665503cf8f848b2f65938e73bfaa5989
[ "MIT" ]
8,329
2016-01-19T19:32:02.000Z
2022-03-31T21:23:12.000Z
kolibri/core/content/test/test_paths.py
MBKayro/kolibri
0a38a5fb665503cf8f848b2f65938e73bfaa5989
[ "MIT" ]
493
2016-01-19T19:26:48.000Z
2022-03-28T14:35:05.000Z
import hashlib from django.test import TestCase from kolibri.core.content.models import LocalFile from kolibri.core.content.utils.paths import get_zip_content_config from kolibri.utils.tests.helpers import override_option class LocalFilePathsTest(TestCase): def test_file_url_reversal(self): from kolibri.utils.conf import OPTIONS path_prefix = OPTIONS["Deployment"]["URL_PATH_PREFIX"] if path_prefix != "/": path_prefix = "/" + path_prefix self.hash = hashlib.md5("DUMMYDATA".encode()).hexdigest() file = LocalFile(id=self.hash, extension="otherextension", available=True) filename = file.get_filename() self.assertEqual( file.get_storage_url(), "{}content/storage/{}/{}/{}".format( path_prefix, filename[0], filename[1], filename ), ) @override_option("Deployment", "URL_PATH_PREFIX", "prefix_test/") class PrefixedLocalFilesPathsTest(LocalFilePathsTest): pass class ZipContentConfigTest(TestCase): @override_option("Deployment", "ZIP_CONTENT_ORIGIN", "https://kolibri.example.com") def test_zip_content_origin_set(self): zip_content_origin, zip_content_port = get_zip_content_config() self.assertEqual("https://kolibri.example.com", zip_content_origin) self.assertEqual(zip_content_port, "")
33.512195
87
0.697962
795177bf4a31eb1817f9268e97fee12c4ad8541a
1,324
py
Python
attachdb/exceptions.py
LinuxJedi/pyattachsql
f47a0ee11a5f0c018bfe9dfac09d4781994c6da4
[ "Apache-2.0" ]
null
null
null
attachdb/exceptions.py
LinuxJedi/pyattachsql
f47a0ee11a5f0c018bfe9dfac09d4781994c6da4
[ "Apache-2.0" ]
null
null
null
attachdb/exceptions.py
LinuxJedi/pyattachsql
f47a0ee11a5f0c018bfe9dfac09d4781994c6da4
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import attachsql def process_exception(exception): if isinstance(exception, attachsql.ClientError): raise ProgrammingError(exception) elif isinstance (exception, attachsql.ServerError): raise OperationalError(exception) else: raise exception class Warning(StandardError): pass class Error(StandardError): pass class InterfaceError(Error): pass class DatabaseError(Error): pass class DataError(DatabaseError): pass class OperationalError(DatabaseError): pass class IntegrityError(DatabaseError): pass class InternalError(DatabaseError): pass class ProgrammingError(DatabaseError): pass class NotSupportedError(DatabaseError): pass
24.518519
75
0.753021
7951791ac259a4dbfd2f56436216bb73887cae87
15,228
py
Python
wagtail/admin/tests/tests.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
1
2021-02-17T11:39:51.000Z
2021-02-17T11:39:51.000Z
wagtail/admin/tests/tests.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
13
2015-05-08T12:27:10.000Z
2020-01-23T14:45:57.000Z
wagtail/admin/tests/tests.py
brownaa/wagtail
c97bc56c6822eb1b6589d5c33e07f71acfc48845
[ "BSD-3-Clause" ]
2
2020-09-03T20:12:32.000Z
2021-03-29T08:29:23.000Z
# -*- coding: utf-8 -*- import json import unittest from django import VERSION as DJANGO_VERSION from django.conf import settings from django.contrib.auth.models import Group, Permission from django.core import mail from django.core.management import call_command from django.test import TestCase, override_settings from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ from taggit.models import Tag from wagtail.admin.auth import user_has_any_page_permission from wagtail.admin.mail import send_mail from wagtail.admin.menu import MenuItem from wagtail.core.models import Page from wagtail.tests.testapp.models import RestaurantTag from wagtail.tests.utils import WagtailTestUtils class TestHome(TestCase, WagtailTestUtils): def setUp(self): # Login self.login() def test_simple(self): response = self.client.get(reverse('wagtailadmin_home')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Welcome to the Test Site Wagtail CMS") def test_admin_menu(self): response = self.client.get(reverse('wagtailadmin_home')) self.assertEqual(response.status_code, 200) # check that media attached to menu items is correctly pulled in if DJANGO_VERSION >= (3, 1): self.assertContains( response, '<script src="/static/testapp/js/kittens.js"></script>', html=True ) else: self.assertContains( response, '<script type="text/javascript" src="/static/testapp/js/kittens.js"></script>', html=True ) # check that custom menu items (including classname / attrs parameters) are pulled in self.assertContains( response, '<a href="http://www.tomroyal.com/teaandkittens/" class="icon icon-kitten" data-fluffy="yes">Kittens!</a>', html=True ) # Check that the explorer menu item is here, with the right start page. self.assertContains( response, 'data-explorer-start-page="1"' ) # check that is_shown is respected on menu items response = self.client.get(reverse('wagtailadmin_home') + '?hide-kittens=true') self.assertNotContains( response, '<a href="http://www.tomroyal.com/teaandkittens/" class="icon icon-kitten" data-fluffy="yes">Kittens!</a>' ) def test_never_cache_header(self): # This tests that wagtailadmins global cache settings have been applied correctly response = self.client.get(reverse('wagtailadmin_home')) self.assertIn('no-cache', response['Cache-Control']) self.assertIn('no-store', response['Cache-Control']) self.assertIn('max-age=0', response['Cache-Control']) self.assertIn('must-revalidate', response['Cache-Control']) @unittest.skipIf(settings.AUTH_USER_MODEL == 'emailuser.EmailUser', "Only applicable to CustomUser") def test_nonascii_email(self): # Test that non-ASCII email addresses don't break the admin; previously these would # cause a failure when generating Gravatar URLs self.create_superuser(username='snowman', email='☃@thenorthpole.com', password='password') # Login self.assertTrue(self.client.login(username='snowman', password='password')) response = self.client.get(reverse('wagtailadmin_home')) self.assertEqual(response.status_code, 200) class TestEditorHooks(TestCase, WagtailTestUtils): def setUp(self): self.homepage = Page.objects.get(id=2) self.login() def test_editor_css_hooks_on_add(self): response = self.client.get(reverse('wagtailadmin_pages:add', args=('tests', 'simplepage', self.homepage.id))) self.assertEqual(response.status_code, 200) self.assertContains(response, '<link rel="stylesheet" href="/path/to/my/custom.css">') def test_editor_js_hooks_on_add(self): response = self.client.get(reverse('wagtailadmin_pages:add', args=('tests', 'simplepage', self.homepage.id))) self.assertEqual(response.status_code, 200) self.assertContains(response, '<script src="/path/to/my/custom.js"></script>') def test_editor_css_hooks_on_edit(self): response = self.client.get(reverse('wagtailadmin_pages:edit', args=(self.homepage.id, ))) self.assertEqual(response.status_code, 200) self.assertContains(response, '<link rel="stylesheet" href="/path/to/my/custom.css">') def test_editor_js_hooks_on_edit(self): response = self.client.get(reverse('wagtailadmin_pages:edit', args=(self.homepage.id, ))) self.assertEqual(response.status_code, 200) self.assertContains(response, '<script src="/path/to/my/custom.js"></script>') class TestSendMail(TestCase): def test_send_email(self): send_mail("Test subject", "Test content", ["nobody@email.com"], "test@email.com") # Check that the email was sent self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test subject") self.assertEqual(mail.outbox[0].body, "Test content") self.assertEqual(mail.outbox[0].to, ["nobody@email.com"]) self.assertEqual(mail.outbox[0].from_email, "test@email.com") @override_settings(WAGTAILADMIN_NOTIFICATION_FROM_EMAIL='anothertest@email.com') def test_send_fallback_to_wagtailadmin_notification_from_email_setting(self): send_mail("Test subject", "Test content", ["nobody@email.com"]) # Check that the email was sent self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test subject") self.assertEqual(mail.outbox[0].body, "Test content") self.assertEqual(mail.outbox[0].to, ["nobody@email.com"]) self.assertEqual(mail.outbox[0].from_email, "anothertest@email.com") @override_settings(DEFAULT_FROM_EMAIL='yetanothertest@email.com') def test_send_fallback_to_default_from_email_setting(self): send_mail("Test subject", "Test content", ["nobody@email.com"]) # Check that the email was sent self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test subject") self.assertEqual(mail.outbox[0].body, "Test content") self.assertEqual(mail.outbox[0].to, ["nobody@email.com"]) self.assertEqual(mail.outbox[0].from_email, "yetanothertest@email.com") def test_send_default_from_email(self): send_mail("Test subject", "Test content", ["nobody@email.com"]) # Check that the email was sent self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test subject") self.assertEqual(mail.outbox[0].body, "Test content") self.assertEqual(mail.outbox[0].to, ["nobody@email.com"]) self.assertEqual(mail.outbox[0].from_email, "webmaster@localhost") def test_send_html_email(self): """Test that the kwarg 'html_message' works as expected on send_mail by creating 'alternatives' on the EmailMessage object""" send_mail("Test HTML subject", "TEXT content", ["has.html@email.com"], html_message="<h2>Test HTML content</h2>") send_mail("Test TEXT subject", "TEXT content", ["mr.plain.text@email.com"]) # Check that the emails were sent self.assertEqual(len(mail.outbox), 2) # check that the first email is the HTML email email_message = mail.outbox[0] self.assertEqual(email_message.subject, "Test HTML subject") self.assertEqual(email_message.alternatives, [('<h2>Test HTML content</h2>', 'text/html')]) self.assertEqual(email_message.body, "TEXT content") # note: plain text will alwasy be added to body, even with alternatives self.assertEqual(email_message.to, ["has.html@email.com"]) # confirm that without html_message kwarg we do not get 'alternatives' email_message = mail.outbox[1] self.assertEqual(email_message.subject, "Test TEXT subject") self.assertEqual(email_message.alternatives, []) self.assertEqual(email_message.body, "TEXT content") self.assertEqual(email_message.to, ["mr.plain.text@email.com"]) class TestTagsAutocomplete(TestCase, WagtailTestUtils): def setUp(self): self.login() Tag.objects.create(name="Test", slug="test") RestaurantTag.objects.create(name="Italian", slug="italian") RestaurantTag.objects.create(name="Indian", slug="indian") def test_tags_autocomplete(self): response = self.client.get(reverse('wagtailadmin_tag_autocomplete'), { 'term': 'test' }) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, ['Test']) def test_tags_autocomplete_partial_match(self): response = self.client.get(reverse('wagtailadmin_tag_autocomplete'), { 'term': 'te' }) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, ['Test']) def test_tags_autocomplete_different_term(self): response = self.client.get(reverse('wagtailadmin_tag_autocomplete'), { 'term': 'hello' }) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, []) def test_tags_autocomplete_no_term(self): response = self.client.get(reverse('wagtailadmin_tag_autocomplete')) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, []) def test_tags_autocomplete_custom_model(self): response = self.client.get( reverse('wagtailadmin_tag_model_autocomplete', args=('tests', 'restauranttag')), {'term': 'ital'} ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, ['Italian']) # should not return results from the standard Tag model response = self.client.get( reverse('wagtailadmin_tag_model_autocomplete', args=('tests', 'restauranttag')), {'term': 'test'} ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') data = json.loads(response.content.decode('utf-8')) self.assertEqual(data, []) class TestMenuItem(TestCase, WagtailTestUtils): def setUp(self): self.login() response = self.client.get(reverse('wagtailadmin_home')) self.request = response.wsgi_request def test_menuitem_reverse_lazy_url_pass(self): menuitem = MenuItem(_('Test'), reverse_lazy('wagtailadmin_home')) self.assertEqual(menuitem.is_active(self.request), True) class TestUserPassesTestPermissionDecorator(TestCase, WagtailTestUtils): """ Test for custom user_passes_test permission decorators. testapp_bob_only_zone is a view configured to only grant access to users with a first_name of Bob """ def test_user_passes_test(self): # create and log in as a user called Bob self.create_superuser(first_name='Bob', last_name='Mortimer', username='test', password='password') self.login(username='test', password='password') response = self.client.get(reverse('testapp_bob_only_zone')) self.assertEqual(response.status_code, 200) def test_user_fails_test(self): # create and log in as a user not called Bob self.create_superuser(first_name='Vic', last_name='Reeves', username='test', password='password') self.login(username='test', password='password') response = self.client.get(reverse('testapp_bob_only_zone')) self.assertRedirects(response, reverse('wagtailadmin_home')) def test_user_fails_test_ajax(self): # create and log in as a user not called Bob self.create_superuser(first_name='Vic', last_name='Reeves', username='test', password='password') self.login(username='test', password='password') response = self.client.get(reverse('testapp_bob_only_zone'), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 403) class TestUserHasAnyPagePermission(TestCase, WagtailTestUtils): def test_superuser(self): user = self.create_superuser( username='superuser', email='admin@example.com', password='p') self.assertTrue(user_has_any_page_permission(user)) def test_inactive_superuser(self): user = self.create_superuser( username='superuser', email='admin@example.com', password='p') user.is_active = False self.assertFalse(user_has_any_page_permission(user)) def test_editor(self): user = self.create_user( username='editor', email='ed@example.com', password='p') editors = Group.objects.get(name='Editors') user.groups.add(editors) self.assertTrue(user_has_any_page_permission(user)) def test_moderator(self): user = self.create_user( username='moderator', email='mod@example.com', password='p') editors = Group.objects.get(name='Moderators') user.groups.add(editors) self.assertTrue(user_has_any_page_permission(user)) def test_no_permissions(self): user = self.create_user( username='pleb', email='pleb@example.com', password='p') user.user_permissions.add( Permission.objects.get(content_type__app_label='wagtailadmin', codename='access_admin') ) self.assertFalse(user_has_any_page_permission(user)) class Test404(TestCase, WagtailTestUtils): def test_admin_404_template_used(self): self.login() response = self.client.get('/admin/sdfgdsfgdsfgsdf') self.assertEqual(response.status_code, 404) self.assertTemplateUsed(response, 'wagtailadmin/404.html') def test_not_logged_in_redirect(self): response = self.client.get('/admin/sdfgdsfgdsfgsdf') # Check that the user was redirected to the login page and that next was set correctly self.assertRedirects(response, reverse('wagtailadmin_login') + '?next=/admin/sdfgdsfgdsfgsdf') class TestRemoveStaleContentTypes(TestCase): def test_remove_stale_content_types_preserves_access_admin_permission(self): call_command('remove_stale_contenttypes', interactive=False) self.assertTrue( Permission.objects.filter(content_type__app_label='wagtailadmin', codename='access_admin').exists() )
43.13881
133
0.68177
79517a201cdd37dd5567b9e24d323c63d54f8492
1,107
py
Python
2020/hackceler8/match-3-package/other-challenge-src/inv/main.py
BearerPipelineTest/google-ctf
a0cab9cb6663ab908b9186d5428aa9674253c5c3
[ "Apache-2.0" ]
2,757
2018-04-28T21:41:36.000Z
2022-03-29T06:33:36.000Z
2020/hackceler8/match-3-package/other-challenge-src/inv/main.py
BearerPipelineTest/google-ctf
a0cab9cb6663ab908b9186d5428aa9674253c5c3
[ "Apache-2.0" ]
20
2019-07-23T15:29:32.000Z
2022-01-21T12:53:04.000Z
2020/hackceler8/match-3-package/other-challenge-src/inv/main.py
BearerPipelineTest/google-ctf
a0cab9cb6663ab908b9186d5428aa9674253c5c3
[ "Apache-2.0" ]
449
2018-05-09T05:54:05.000Z
2022-03-30T14:54:18.000Z
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np a = [ # NO DATA ] f = np.array([[ 0.012339 , -0.02620502, -0.03098542, 0.07781701, -0.0270996 ], [ 0.00468379, 0.00022547, 0.06944456, -0.0484358 , -0.02109563], [-0.00247619, 0.0222133 , -0.02510456, 0.02109282, -0.01257638], [-0.02556051, 0.00968766, -0.01059733, -0.03079028, 0.0493632 ], [ 0.01152323, -0.00291923, 0.00064684, -0.01818232, 0.01265076]]) if np.allclose(np.dot(f,a),np.eye(len(f)),atol=1e-05):print(''.join(map(chr,(i for s in a for i in s))))
41
104
0.68112
79517a3821a651b88d3fdc0db30a99f75d522932
4,673
py
Python
tests/cli/__init__.py
M3t0r/tpl
32ee0bb1fc629446a6451f20053c64ce8a860a61
[ "MIT" ]
11
2018-07-17T12:30:57.000Z
2021-07-31T00:46:06.000Z
tests/cli/__init__.py
M3t0r/tpl
32ee0bb1fc629446a6451f20053c64ce8a860a61
[ "MIT" ]
16
2018-10-08T21:50:16.000Z
2021-07-29T12:20:57.000Z
tests/cli/__init__.py
M3t0r/tpl
32ee0bb1fc629446a6451f20053c64ce8a860a61
[ "MIT" ]
4
2018-10-09T15:20:35.000Z
2020-04-16T13:50:48.000Z
import os from pathlib import Path from subprocess import run, PIPE, CompletedProcess from collections import defaultdict import json import pytest import yaml EXECUTION_TIMEOUT = 2 # seconds class CLI: """Helper class to ease testing of CLI commands""" def __init__(self, executable_list, tmpdir, print_debug_output=True): self._executable = executable_list self.tmpdir = tmpdir self._tmpfile_auto_increment = defaultdict(int) # print stdout/err and exit code so that in case of errors we can see # what happened self._print_debug_output = print_debug_output def __call__(self, *args, stdin="", env={}, encoding="UTF-8") -> CompletedProcess: # patch PATH into env if not already set env.setdefault("PATH", os.environ["PATH"]) result = run( ["tpl", *[str(arg) for arg in args]], timeout=EXECUTION_TIMEOUT, stdout=PIPE, stderr=PIPE, input=str(stdin).encode(encoding), env=env, cwd=str(self.tmpdir) ) # Python 3.5 doesn't support the `encoding` argument to `run()`, # so we have to manually decode the byte strings result.stdout = result.stdout.decode(encoding) result.stderr = result.stderr.decode(encoding) if self._print_debug_output: self.print_debug_info_for_call(result) return result def _print_stream_output(self, call_result: CompletedProcess, stream_name: str): stream = getattr(call_result, stream_name.lower()) name = stream_name.upper() print(name + ":", end="") if len(stream) == 0: print(" (stream is empty)") elif stream == "\n": print(" (stream is empty, containts only one newline)") elif stream[-1] != "\n": print(" (does not end in newline)") else: print() print("-" * 24) print(stream, end="") # if it doesn't end in a newline add one so the seperation doesn't start # directly after the output if len(stream) > 0 and stream[-1] != "\n": print() print("=" * 24) def print_debug_info_for_call(self, call_result: CompletedProcess): print("Command:", call_result.args) print("Return code:", call_result.returncode) self._print_stream_output(call_result, "stdout") self._print_stream_output(call_result, "stderr") print("Folder hierarchy:") print(self.folder_tree()) def folder_tree(self, path=None): if path is None: path = self.tmpdir path = Path(str(path)) return "./\n" + "\n".join(self._folder_structure_recursive(path)) def _folder_structure_recursive(self, path: Path): for item in path.iterdir(): yield "|-- " + item.name if item.is_dir(): for line in self._folder_structure_recursive(item): yield "| " + line def _normalize_filename(self, name): allowed_chars = ( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "01234567890" "-_." ) return "".join([c for c in str(name) if c in allowed_chars][:32]) def unique_file(self, name="") -> Path: """Generate a unique filename that can be used in the tmpdir""" normalized = self._normalize_filename(name) index = str(self._tmpfile_auto_increment[normalized]) self._tmpfile_auto_increment[normalized] += 1 filename = normalized + "-" + index if len(normalized) == 0: filename = index return Path(str(self.tmpdir), filename) def path_for_content(self, file_content, encoding="UTF-8", name="") -> Path: if name == "": name = file_content # use the first few characters to form a name file_path = self.unique_file(name) with file_path.open("wb") as file: file.write(str(file_content).encode(encoding)) return file_path def path_for_json(self, content: dict, encoding="UTF-8", name="") -> Path: if name == "": name = "json-data" return self.path_for_content(json.dumps(content), encoding, name) def path_for_yaml(self, content: dict, encoding="UTF-8", name="") -> Path: if name == "": name = "yaml-data" return self.path_for_content( yaml.dump(content, default_flow_style=False), encoding, name ) @pytest.fixture def cli(tmpdir): yield CLI("tpl", tmpdir)
32.678322
86
0.594907
79517b2bde9d2fbaa81036bf1e2405d4fbdd0918
1,897
py
Python
tests/unit/boundary/plugin_get_test.py
jdgwartney/boundary-api-cli
f17bc252e3958656514042360c9f96fd50ab496c
[ "Apache-2.0" ]
null
null
null
tests/unit/boundary/plugin_get_test.py
jdgwartney/boundary-api-cli
f17bc252e3958656514042360c9f96fd50ab496c
[ "Apache-2.0" ]
null
null
null
tests/unit/boundary/plugin_get_test.py
jdgwartney/boundary-api-cli
f17bc252e3958656514042360c9f96fd50ab496c
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # # Copyright 2015 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json from unittest import TestCase from boundary import PluginGet from cli_runner import CLIRunner from cli_test import CLITest class PluginGetTest(TestCase): def setUp(self): self.cli = PluginGet() def test_cli_description(self): CLITest.check_description(self, self.cli) def test_cli_help(self): CLITest.check_cli_help(self, self.cli) def test_get_plugin(self): runner = CLIRunner(PluginGet()) plugin_name = 'httpcheck' get = runner.get_output(['-n', plugin_name]) plugin_get = json.loads(get) plugin = plugin_get['result'] self.assertTrue('download' in plugin) self.assertTrue('repoUrl' in plugin) self.assertEqual(plugin_name, plugin['name']) self.assertTrue('description' in plugin) self.assertTrue('paramSchema' in plugin) self.assertTrue('paramArray' in plugin) self.assertTrue('postExtract' in plugin) self.assertTrue('command' in plugin) self.assertTrue('ignore' in plugin) self.assertTrue('icon' in plugin) self.assertTrue('dashboards' in plugin) self.assertTrue('version' in plugin) self.assertTrue('metrics' in plugin) self.assertTrue('metricDefinitions' in plugin)
31.616667
74
0.69689
79517c494edd1e5493b9f7dad9211145151d28e4
2,018
py
Python
Python3/1226.py
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
Python3/1226.py
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
Python3/1226.py
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 48 ms submission from threading import Lock class DiningPhilosophers: forks = [Lock() for _ in range(5)] even = Lock() # call the functions directly to execute, for example, eat() def wantsToEat(self, philosopher: int, pickLeftFork: 'Callable[[], None]', pickRightFork: 'Callable[[], None]', eat: 'Callable[[], None]', putLeftFork: 'Callable[[], None]', putRightFork: 'Callable[[], None]') -> None: i = philosopher if i % 2 == 0: self.even.acquire() right_fork = i left_fork = (i+1) % 5 self.forks[right_fork].acquire() self.forks[left_fork].acquire() pickRightFork() pickLeftFork() eat() putLeftFork() putRightFork() self.forks[right_fork].release() self.forks[left_fork].release() if i % 2 == 0: self.even.release() __________________________________________________________________________________________________ sample 52 ms submission import threading class DiningPhilosophers: def __init__(self): self.lock = threading.Lock() # call the functions directly to execute, for example, eat() def wantsToEat(self, philosopher: int, pickLeftFork: 'Callable[[], None]', pickRightFork: 'Callable[[], None]', eat: 'Callable[[], None]', putLeftFork: 'Callable[[], None]', putRightFork: 'Callable[[], None]') -> None: with self.lock: pickLeftFork() pickRightFork() eat() putLeftFork() putRightFork() __________________________________________________________________________________________________
32.548387
98
0.573835
79517d3d62c6bcc246afabd6176d71f9ae6aabba
6,898
py
Python
Src/Tests/test_property.py
Enerccio/ironpython26-fixed
e302db14f05396a378adb438565a829e66acbf94
[ "MS-PL" ]
1
2020-02-11T06:02:40.000Z
2020-02-11T06:02:40.000Z
Src/Languages/IronPython/Tests/test_property.py
rudimk/dlr-dotnet
71d11769f99d6ff1516ddbaed091a359eb46c670
[ "MS-PL" ]
null
null
null
Src/Languages/IronPython/Tests/test_property.py
rudimk/dlr-dotnet
71d11769f99d6ff1516ddbaed091a359eb46c670
[ "MS-PL" ]
1
2018-11-21T04:10:23.000Z
2018-11-21T04:10:23.000Z
##################################################################################### # # Copyright (c) Microsoft Corporation. All rights reserved. # # This source code is subject to terms and conditions of the Microsoft Public License. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Microsoft Public License, please send an email to # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Microsoft Public License. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### from iptest.assert_util import * array_list_options = [] if is_cli or is_silverlight: array_list_options.append(System.Collections.Generic.List[int]) if not is_silverlight: array_list_options.append(System.Collections.ArrayList) for ArrayList in array_list_options: l = ArrayList() index = l.Add(22) Assert(l[0] == 22) l[0] = 33 Assert(l[0] == 33) import sys Assert('<stdin>' in str(sys.stdin)) #Assert('<stdout>' in str(sys.stdout)) #Assert('<stderr>' in str(sys.stderr)) # getting a property from a class should return the property, # getting it from an instance should do the descriptor check def test_sanity(): class foo(object): def myset(self, value): pass def myget(self): return "hello" prop = property(fget=myget,fset=myset) AreEqual(type(foo.prop), property) a = foo() AreEqual(a.prop, 'hello') @skip("win32") def test_builtinclrtype_set(): # setting an instance property on a built-in type should # throw that you can't set on built-in types for ArrayList in array_list_options: def setCount(): ArrayList.Count = 23 AssertError(AttributeError, setCount) # System.String.Empty is a read-only static field AssertError(AttributeError, setattr, System.String, "Empty", "foo") # a class w/ a metaclass that has a property # defined should hit the descriptor when getting # it on the class. def test_metaclass(): class MyType(type): def myget(self): return 'hello' aaa = property(fget=myget) class foo(object): __metaclass__ = MyType AreEqual(foo.aaa, 'hello') def test_reflected_property(): # ReflectedProperty tests for ArrayList in array_list_options: alist = ArrayList() AreEqual(ArrayList.Count.__set__(None, 5), None) AssertError(TypeError, ArrayList.Count, alist, 5) AreEqual(alist.Count, 0) AreEqual(str(ArrayList.__dict__['Count']), '<property# Count on %s>' % ArrayList.__name__) def tryDelReflectedProp(): del ArrayList.Count AssertError(AttributeError, tryDelReflectedProp) @skip("win32") def test_reflected_extension_property_ops(): ''' Test to hit IronPython.RunTime.Operations.ReflectedExtensionPropertyOps ''' t_list = [ (complex.__dict__['real'], 'complex', 'float', 'real'), (complex.__dict__['imag'], 'complex', 'float', 'imag'), ] for stuff, typename, returnType, propName in t_list: expected = "Get: " + propName + "(self: " + typename + ") -> " + returnType + newline Assert(stuff.__doc__.startswith(expected), stuff.__doc__) def test_class_doc(): AreEqual(object.__dict__['__class__'].__doc__, "the object's class") def test_prop_doc_only(): # define a property w/ only the doc x = property(None, None, doc = 'Holliday') AreEqual(x.fget, None) AreEqual(x.fset, None) AreEqual(x.fdel, None) AreEqual(x.__doc__, 'Holliday') def test_member_lookup_oldclass(): class OldC: xprop = property(lambda self: self._xprop) def __init__(self): self._xprop = 42 self.xmember = 42 c = OldC() c.__dict__['xprop'] = 43 c.__dict__['xmember'] = 43 AreEqual(c.xprop, 43) AreEqual(c.xmember, 43) c.xprop = 41 c.xmember = 41 AreEqual(c.xprop, 41) AreEqual(c.xmember, 41) AreEqual(c.__dict__['xprop'], 41) AreEqual(c.__dict__['xmember'], 41) def test_member_lookup_newclass(): class NewC(object): def xprop_setter(self, xprop): self._xprop = xprop xprop = property(lambda self: self._xprop, xprop_setter) def __init__(self): self._xprop = 42 self.xmember = 42 c = NewC() c.__dict__['xprop'] = 43 c.__dict__['xmember'] = 43 AreEqual(c.xprop, 42) AreEqual(c.xmember, 43) c.xprop = 41 c.xmember = 41 AreEqual(c.xprop, 41) AreEqual(c.xmember, 41) AreEqual(c.__dict__['xprop'], 43) AreEqual(c.__dict__['xmember'], 41) def test_inheritance(): class MyProperty(property): def __init__(self, *args): property.__init__(self, *args) x = MyProperty(1,2,3) AreEqual(x.fget, 1) AreEqual(x.fset, 2) AreEqual(x.fdel, 3) class MyProperty(property): def __init__(self, *args): property.__init__(self, *args) def __get__(self, *args): return 42 def __set__(self, inst, value): inst.foo = value def __delete__(self, *args): inst.bar = 'baz' class MyClass(object): x = MyProperty() inst = MyClass() AreEqual(inst.x, 42) inst.x = 'abc' AreEqual(inst.foo, 'abc') del inst.x AreEqual(inst.bar, 'baz') def test_property_mutation(): class x(object): pass prop = property() x.foo = prop inst = x() for i in xrange(42): prop.__init__(lambda self: i) AreEqual(inst.foo, i) def test_property_doc(): def getter(self): """getter doc""" AreEqual(property(getter).__doc__, "getter doc") AreEqual(property(None).__doc__, None) AreEqual(property(None, getter, getter).__doc__, None) Assert(type(property.__doc__) is str) def assignerror(): property.__doc__ = None AssertErrorWithMessage(TypeError, "can't set attributes of built-in/extension type 'property'", assignerror) def test_class_assign(): """assigning to a property through the class should replace the property in the class dictionary""" class x(object): def set(self, value): AssertUnreachable() prop = property(lambda x:42, set) x.prop = 42 AreEqual(x.__dict__['prop'], 42) def test_assign(): x = property() for attr in ['__doc__', 'fdel', 'fget', 'fset']: AssertErrorWithMessage(TypeError, "readonly attribute", lambda : setattr(x, attr, 'abc')) run_test(__name__)
28.270492
112
0.610322
79517e6b988c8afd19a4717ea4353b138163ab68
10,074
py
Python
FakeNewsAnalysis/FakeNewsAnalysis/validate.py
Feupos/DataScience
d246ab70554095456afb14ddef990accb3f9d2ac
[ "MIT" ]
null
null
null
FakeNewsAnalysis/FakeNewsAnalysis/validate.py
Feupos/DataScience
d246ab70554095456afb14ddef990accb3f9d2ac
[ "MIT" ]
null
null
null
FakeNewsAnalysis/FakeNewsAnalysis/validate.py
Feupos/DataScience
d246ab70554095456afb14ddef990accb3f9d2ac
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt from matplotlib import colors from matplotlib.ticker import PercentFormatter import matplotlib.dates as md import sklearn from sklearn import svm from sklearn.naive_bayes import GaussianNB, ComplementNB, MultinomialNB from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier from textblob import TextBlob, Word, Blobber import nltk import textstat from lexicalrichness import LexicalRichness import pandas as pd pd.options.mode.chained_assignment = None import numpy as np import random from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator import seaborn as sns sns.set() from itertools import groupby import time from datetime import datetime import sys import csv import ctypes csv.field_size_limit(int(ctypes.c_ulong(-1).value // 2)) from statistics import mean from tqdm import tqdm import itertools def plot_features(body_features, title_features): # ['type', 'WC', 'TTR', 'NN', 'quote'] timestamp = datetime.now().strftime("%Y%m%d%H%M%S") save_dir = 'FakeNewsAnalysis/Results/' plt.figure() sns.boxplot(y = 'type', x = 'NN', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'NN') plt.figure() sns.boxplot(y = 'type', x = 'TTR', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'TTR') plt.figure() sns.boxplot(y = 'type', x = 'WC', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'WC') plt.figure() sns.boxplot(y = 'type', x = 'quote', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'quote') plt.figure() sns.boxplot(y = 'type', x = 'per_stop', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'per_stop') plt.figure() sns.boxplot(y = 'type', x = 'NN', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'NN') plt.figure() sns.boxplot(y = 'type', x = 'avg_wlen', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'avg_wlen') plt.figure() sns.boxplot(y = 'type', x = 'FK', data = body_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'body' + 'FK') plt.figure() sns.boxplot(y = 'type', x = 'NN', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'NN') plt.figure() sns.boxplot(y = 'type', x = 'TTR', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'TTR') plt.figure() sns.boxplot(y = 'type', x = 'WC', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'WC') plt.figure() sns.boxplot(y = 'type', x = 'quote', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'quote') plt.figure() sns.boxplot(y = 'type', x = 'per_stop', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'per_stop') plt.figure() sns.boxplot(y = 'type', x = 'NN', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'NN') plt.figure() sns.boxplot(y = 'type', x = 'avg_wlen', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'avg_wlen') plt.figure() sns.boxplot(y = 'type', x = 'FK', data = title_features, whis="range", palette="vlag") plt.tight_layout() plt.savefig(save_dir + timestamp + 'title' + 'FK') plt.show() if __name__ == "__main__": group_a_type = 'fake' group_b_type = 'reliable' title_features = pd.read_pickle('FakeNewsAnalysis/Data/title_features.pkl') #print(title_features.groupby(['type']).agg(['count'])) body_features = pd.read_pickle('FakeNewsAnalysis/Data/body_features.pkl') title_features_fake = title_features[title_features.type.isin([group_a_type])] title_features_reliable = title_features[title_features.type.isin([group_b_type])] title_features_fake = title_features_fake[:750]#:min(title_features_fake.type.count(),title_features_reliable.type.count())] title_features_reliable = title_features_reliable[:750]#:min(title_features_fake.type.count(),title_features_reliable.type.count())] title_features = title_features_fake.append(title_features_reliable) title_features = title_features.sample(frac=1).reset_index(drop=True) body_features_fake = body_features[body_features.type.isin([group_a_type])] body_features_reliable = body_features[body_features.type.isin([group_b_type])] body_features_fake = body_features_fake[:750]#:min(body_features_fake.type.count(),body_features_reliable.type.count())] body_features_reliable = body_features_reliable[:750]#:min(body_features_fake.type.count(),body_features_reliable.type.count())] body_features = body_features_fake.append(body_features_reliable) body_features = body_features.sample(frac=1).reset_index(drop=True) plot_features(body_features, title_features) #'per_stop','WC','TTR','NN','avg_wlen','quote','FK','polarity','NNP' ignore_features = ['polarity', 'NNP']#'per_stop','avg_wlen','FK','polarity','NNP'] full_body_features = body_features#.drop(columns=ignore_features) full_title_features = title_features#.drop(columns=ignore_features) print('number of ' + group_a_type + ': ' + str(title_features[title_features.type.isin([group_a_type])].type.count()) + ' - number of '+ group_b_type + ': ' + str(title_features[title_features.type.isin([group_b_type])].type.count())) print('baseline: ' + str(title_features[title_features.type.isin([group_a_type])].type.count()/title_features.type.count())) #features = ['type','per_stop','WC','TTR','NN','avg_wlen','quote','FK','polarity','NNP','str_neg','str_pos','JJR','JJS','RBR','RBS'] features = ['type','per_stop','WC','TTR','NN','avg_wlen','quote','FK','NNP','str_neg','str_pos','JJR','JJS','RBR','RBS'] scores = [] folds = int(title_features[title_features.type.isin([group_a_type])].type.count()/15) cv = sklearn.model_selection.KFold(n_splits=folds, shuffle=True) body_features = full_body_features[features]#[['type', 'NN', 'TTR', 'WC', 'quote']] #features = ['per_stop','WC','TTR','NN','avg_wlen','quote','FK','polarity','NNP','str_neg','str_pos','JJR','JJS','RBR','RBS'] #print(body_features) with tqdm(total=folds) as pbar: for train_index, test_index in cv.split(body_features): X = body_features.iloc[train_index].drop(columns=['type']) y = body_features.iloc[train_index].type #clf = svm.SVC(gamma='auto',kernel ='linear') #clf = GaussianNB() #clf = MultinomialNB() clf = RandomForestClassifier(n_estimators=32, max_depth=10)#, min_samples_split = 0.4, min_samples_leaf = 0.05, random_state=42) #clf = GradientBoostingClassifier() clf.fit(X, y) scores.append(clf.score(body_features.iloc[test_index].drop(columns=['type']), body_features.iloc[test_index].type)) pbar.update(1) #print(scores) print('body feature prediction score: ' + str(mean(scores))) scores = [] #folds = 5 cv = sklearn.model_selection.KFold(n_splits=folds, shuffle=True) title_features = full_title_features[features]#[['type', 'per_stop', 'NN', 'avg_wlen', 'FK']] #print(title_features) with tqdm(total=folds) as pbar: for train_index, test_index in cv.split(title_features): X = title_features.iloc[train_index].drop(columns=['type']) y = title_features.iloc[train_index].type #clf = svm.SVC(gamma='auto',kernel ='linear') #clf = GaussianNB() #clf = MultinomialNB() clf = RandomForestClassifier(n_estimators=32, max_depth=10)#, min_samples_split = 0.4, min_samples_leaf = 0.05, random_state=42) #clf = GradientBoostingClassifier() clf.fit(X, y) scores.append(clf.score(title_features.iloc[test_index].drop(columns=['type']), title_features.iloc[test_index].type)) pbar.update(1) #print(scores) print('title feature prediction score: ' + str(mean(scores))) scores = [] #folds = 5 cv = sklearn.model_selection.KFold(n_splits=folds, shuffle=True) joint_features = title_features.drop(columns=['type']).add_suffix('_title').join(body_features) #print(joint_features) with tqdm(total=folds) as pbar: for train_index, test_index in cv.split(joint_features): X = joint_features.iloc[train_index].drop(columns=['type']) y = joint_features.iloc[train_index].type #clf = svm.SVC(gamma='auto',kernel ='linear') #clf = GaussianNB() #clf = MultinomialNB() clf = RandomForestClassifier(n_estimators=32, max_depth=10)#, min_samples_split = 0.4, min_samples_leaf = 0.05, random_state=42) #clf = GradientBoostingClassifier() clf.fit(X, y) scores.append(clf.score(joint_features.iloc[test_index].drop(columns=['type']), joint_features.iloc[test_index].type)) pbar.update(1) #print(scores) print('joint feature prediction score: ' + str(mean(scores))) # avaliar performance com as mesmas features ## testar com o mesmo datase!!!!! # especular motivos para diferenca # adicionar features do LIWC
47.744076
238
0.678876
79517e8190f46311328fd11e72b79f34afc5f79d
873
py
Python
virtual/lib/python3.6/site-packages/django/contrib/gis/db/backends/spatialite/features.py
Ruterana/clone_instagram
a068587ef1d1a93ec8d1c08086bf11c0fb274b83
[ "MIT" ]
33
2018-10-07T21:50:44.000Z
2022-02-16T18:16:56.000Z
virtual/lib/python3.6/site-packages/django/contrib/gis/db/backends/spatialite/features.py
Ruterana/clone_instagram
a068587ef1d1a93ec8d1c08086bf11c0fb274b83
[ "MIT" ]
27
2017-04-01T15:06:36.000Z
2021-02-08T20:19:58.000Z
virtual/lib/python3.6/site-packages/django/contrib/gis/db/backends/spatialite/features.py
ngishjonathan/gallery
dd67f28887316d6277927c667f6641d26317b0b8
[ "MIT" ]
11
2019-02-26T14:30:28.000Z
2021-12-31T05:04:08.000Z
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.sqlite3.features import \ DatabaseFeatures as SQLiteDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, SQLiteDatabaseFeatures): supports_3d_storage = True # SpatiaLite can only count vertices in LineStrings supports_num_points_poly = False @cached_property def supports_initspatialmetadata_in_one_transaction(self): # SpatiaLite 4.1+ support initializing all metadata in one transaction # which can result in a significant performance improvement when # creating the database. return self.connection.ops.spatial_version >= (4, 1, 0) @cached_property def supports_area_geodetic(self): return bool(self.connection.ops.lwgeom_version())
39.681818
78
0.775487
79517f286dc5819c1142c7a98bb5b6d33ed3f946
669
py
Python
ex106.py
raphael-abrantes/exercises-python
71f1e7cba2f56173c256d43e4fe33a43722b4484
[ "MIT" ]
null
null
null
ex106.py
raphael-abrantes/exercises-python
71f1e7cba2f56173c256d43e4fe33a43722b4484
[ "MIT" ]
null
null
null
ex106.py
raphael-abrantes/exercises-python
71f1e7cba2f56173c256d43e4fe33a43722b4484
[ "MIT" ]
null
null
null
import sys, os caminho = os.path.dirname(__file__) sys.path.append(caminho[:caminho.find('exs')]) from time import sleep def printlin(txt): print(f'~'*int(len(txt) + 4),flush=False) print(f' {txt} ',flush=False) print(f'~'*int(len(txt) + 4), flush=False) def pyhelp(): while True: printlin('SISTEMA DE AJUDA PyHELP') pesquisa = str(input('Função ou Biblioteca > ')).strip().lower() if pesquisa.upper() == 'END': break printlin(f'Acessando o Manual de "{pesquisa}"') sleep(1) print(f'{help(pesquisa)}') sleep(2) printlin(f'ATÉ LOGO') #PROGRAMA pyhelp()
26.76
73
0.575486
79517f3fd889d0933c355c5467801ee2ad5a840d
4,987
py
Python
netboxers/models/dns_zonefile.py
okoeroo/netbox-tools
fab502ad038fc0395e5d54435a2ba90189d8a6cf
[ "MIT" ]
5
2020-08-31T22:56:07.000Z
2021-08-09T18:41:39.000Z
netboxers/models/dns_zonefile.py
okoeroo/netbox-tools
fab502ad038fc0395e5d54435a2ba90189d8a6cf
[ "MIT" ]
null
null
null
netboxers/models/dns_zonefile.py
okoeroo/netbox-tools
fab502ad038fc0395e5d54435a2ba90189d8a6cf
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 class DNS_Resource_Record: def __init__(self, **kwargs): self.rr_name = None self.rr_type = None self.rr_class = 'IN' self.rr_ttl = 86400 self.rr_data = None for key, value in kwargs.items(): # Generic if key == 'rr_name': self.rr_name = value.lower() elif key == 'rr_type': self.rr_type = value.upper() elif key == 'rr_class': self.rr_class = value.upper() elif key == 'rr_ttl': self.rr_ttl = value elif key == 'rr_data': self.rr_data = value.lower() # SOA elif key == 'soa_mname': self.soa_mname = self.dns_canonicalize(value).lower() elif key == 'soa_rname': # Funky e-mail: foo\.bar.example.org self.soa_rname = self.dns_canonicalize(value).lower() elif key == 'soa_serial': self.soa_serial = value elif key == 'soa_refresh': self.soa_refresh = value elif key == 'soa_retry': self.soa_retry = value elif key == 'soa_expire': self.soa_expire = value elif key == 'soa_minimum_ttl': self.soa_minimum_ttl = value # MX elif key == 'mx_priority': self.mx_priority = value elif key == 'mx_value': self.mx_data = self.dns_canonicalize(value).lower() # Post processing if self.rr_type == 'SOA': self.rr_name = self.dns_canonicalize(self.rr_name) self.rr_data = " ".join([ self.soa_mname, self.soa_rname, str(self.soa_serial), str(self.soa_refresh), str(self.soa_retry), str(self.soa_expire), str(self.soa_minimum_ttl)]) elif self.rr_type == 'MX': self.rr_data = " ".join([ self.mx_priority, self.mx_data]) elif self.rr_type == 'NS': self.rr_data = self.dns_canonicalize(self.rr_data) elif self.rr_type == 'CNAME': self.rr_name = self.normalize_name(self.rr_name) self.rr_data = self.normalize_name(self.rr_data) self.rr_data = self.dns_canonicalize(self.rr_data) elif self.rr_type == 'A': self.rr_name = self.normalize_name(self.rr_name) self.rr_data = str(self.rr_data) elif self.rr_type == 'PTR': self.rr_name = self.dns_canonicalize(self.rr_name) self.rr_data = self.normalize_name(self.rr_data) self.rr_data = self.dns_canonicalize(self.rr_data) # Sanity checks if self.rr_name is None: raise InputError("DNS_Resource_Record(__init__)", "No rr_name provided") elif self.rr_type is None: raise InputError("DNS_Resource_Record(__init__)", "No rr_type provided") elif self.rr_class is None: raise InputError("DNS_Resource_Record(__init__)", "No rr_class provided") elif self.rr_ttl is None: raise InputError("DNS_Resource_Record(__init__)", "No rr_ttl provided") elif self.rr_data is None: raise InputError("DNS_Resource_Record(__init__)", "No rr_data provided") def dns_canonicalize(self, s): if s == '@': return s if not s.endswith('.'): return s + '.' else: return s def normalize_name(self, name): return name.lower().replace(" ", "_").replace("-", "_").replace("\"", "").replace("\'", "") def __str__(self): res = [] res.append(self.rr_name) res.append(str(self.rr_ttl)) res.append(self.rr_class) res.append(self.rr_type) res.append(self.rr_data) return " ".join(res) class DNS_Zonefile: def __init__(self): self.resource_records = [] def add_rr(self, rr): self.resource_records.append(rr) def get_str(self): res = [] for rr in self.resource_records: res.append(str(rr)) return "\n".join(res) def __str__(self): return self.get_str() """ @ 86400 IN SOA ns hostmaster.koeroo.local 7 86400 7200 3600000 1800 $TTL 86400 @ IN SOA ns.icann.org. noc.dns.icann.org. ( 2020080302 ;Serial 7200 ;Refresh 3600 ;Retry 1209600 ;Expire 3600 ;Minimum TTL ) """
34.157534
85
0.497895
79517f4493b23d37ee1eb7a8698a99bc3587e5d6
16,229
py
Python
nutils/util.py
soraros/nutils
91119b12bdebf12a85eecb6a2247be2415f60e6f
[ "MIT" ]
1
2019-11-17T23:16:13.000Z
2019-11-17T23:16:13.000Z
nutils/util.py
GabrielJie/nutils
cb47070fc8aaf1caeb38c1d90d19ef3c107f114a
[ "MIT" ]
1
2020-12-23T22:38:16.000Z
2020-12-23T22:38:16.000Z
nutils/util.py
GabrielJie/nutils
cb47070fc8aaf1caeb38c1d90d19ef3c107f114a
[ "MIT" ]
null
null
null
# Copyright (c) 2014 Evalf # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ The util module provides a collection of general purpose methods. """ from . import numeric import sys, os, numpy, collections.abc, inspect, functools, operator, numbers, pathlib, ctypes, io, contextlib supports_outdirfd = os.open in os.supports_dir_fd and os.listdir in os.supports_fd sum = functools.partial(functools.reduce, operator.add) product = functools.partial(functools.reduce, operator.mul) def cumsum(seq): offset = 0 for i in seq: yield offset offset += i def gather(items): gathered = [] d = {} for key, value in items: try: values = d[key] except KeyError: d[key] = values = [] gathered.append((key, values)) values.append(value) return gathered def pairwise(items, *, periodic=False): items = iter(items) try: first = a = next(items) except StopIteration: return for b in items: yield a, b a = b if periodic: yield a, first def allequal(seq1, seq2): seq1 = iter(seq1) seq2 = iter(seq2) for item1, item2 in zip(seq1, seq2): if item1 != item2: return False if list(seq1) or list(seq2): return False return True class NanVec(numpy.ndarray): 'nan-initialized vector' def __new__(cls, length): vec = numpy.empty(length, dtype=float).view(cls) vec[:] = numpy.nan return vec @property def where(self): return ~numpy.isnan(self.view(numpy.ndarray)) def __iand__(self, other): if self.dtype != float: return self.view(numpy.ndarray).__iand__(other) where = self.where if numpy.isscalar(other): self[where] = other else: assert numeric.isarray(other) and other.shape == self.shape self[where] = other[where] return self def __and__(self, other): if self.dtype != float: return self.view(numpy.ndarray).__and__(other) return self.copy().__iand__(other) def __ior__(self, other): if self.dtype != float: return self.view(numpy.ndarray).__ior__(other) wherenot = ~self.where self[wherenot] = other if numpy.isscalar(other) else other[wherenot] return self def __or__(self, other): if self.dtype != float: return self.view(numpy.ndarray).__or__(other) return self.copy().__ior__(other) def __invert__(self): if self.dtype != float: return self.view(numpy.ndarray).__invert__() nanvec = NanVec(len(self)) nanvec[numpy.isnan(self)] = 0 return nanvec def regularize(bbox, spacing, xy=numpy.empty((0,2))): xy = numpy.asarray(xy) index0 = numeric.floor(bbox[:,0] / (2*spacing)) * 2 - 1 shape = numeric.ceil(bbox[:,1] / (2*spacing)) * 2 + 2 - index0 index = numeric.round(xy / spacing) - index0 keep = numpy.logical_and(numpy.greater_equal(index, 0), numpy.less(index, shape)).all(axis=1) mask = numpy.zeros(shape, dtype=bool) for i, ind in enumerate(index): if keep[i]: if not mask[tuple(ind)]: mask[tuple(ind)] = True else: keep[i] = False coursex = mask[0:-2:2] | mask[1:-1:2] | mask[2::2] coarsexy = coursex[:,0:-2:2] | coursex[:,1:-1:2] | coursex[:,2::2] vacant, = (~coarsexy).ravel().nonzero() newindex = numpy.array(numpy.unravel_index(vacant, coarsexy.shape)).T * 2 + index0 + 1 return numpy.concatenate([newindex * spacing, xy[keep]], axis=0) def tri_merge(tri, x, mergetol=0): '''Create connected triangulation by connecting (near) identical points. Based on a set of coordinates ``x``, create a modified copy of ``tri`` with any occurrence of ``j`` replaced by ``i`` if ``x[i]`` equals ``x[j]`` within specified tolerance. The result is a triangulation that remains valid for any associated data vector that follows the same equality relations. Example: >>> x = [0,0], [1,0], [0,1], [1,0], [1,1] # note: x[1] == x[3]) >>> tri = [0,1,2], [2,3,4] >>> tri_merge(tri, x) array([[0, 1, 2], [2, 1, 4]]) .. requires:: scipy Args ---- x : :class:`float` array Vertex coordinates. tri : :class:`int` array Triangulation. mergetol : :class:`float` (optional, default 0) Distance within which two points are considered equal. If mergetol == 0 then points are considered equal if and only if their coordinates are identical. If mergetol > 0 (required scipy) then points are considered equal if they are within euclidian distance < mergetol. If mergetol < 0 then tri is returned unchanged. Returns ------- merged_tri : :class:`int` array ''' tri = numpy.asarray(tri) x = numpy.asarray(x) assert tri.dtype == int assert x.ndim == tri.ndim == 2 assert tri.shape[1] == x.shape[1] + 1 if mergetol < 0: return tri if mergetol == 0: order = numpy.lexsort(x.T) keep = numpy.concatenate([[True], numpy.diff(x[order], axis=0).any(axis=1)]) renumber = numpy.empty(len(x), dtype=int) renumber[order] = order[keep][keep.cumsum()-1] else: import scipy.spatial renumber = numpy.arange(len(x)) for i, j in sorted(scipy.spatial.cKDTree(x).query_pairs(mergetol)): assert i < j renumber[j] = renumber[i] return renumber[tri] class tri_interpolator: '''Interpolate function values defined in triangulation vertices. Convenience object that implements 2D interpolation on top of matplotlib's triangulation routines. Unlike matplotlib's own ``LinearTriInterpolator``, the ``tri_interpolator`` allows for interpolation of multi-dimensional arrays, as well as repeated interpolations of different vertex values. The arguments are identical to :func:`tri_merge`. After instantiation of the interpolator object, interpolation coordinates are specified via the object's getitem operator. The resulting callable performs the interpolation: >>> trix = [0,0], [1,0], [0,1], [1,1] # vertex coordinates >>> triu = 0, 0, 10, 0 # vertex values >>> interpolate = tri_interpolator([[0,1,2],[1,3,2]], trix) >>> x = [.1,.1], [.1,.9], [.9,.9] # interpolation coordinates >>> u = interpolate[x](triu) # interpolated values .. requires:: matplotlib ''' def __init__(self, tri, x, mergetol=0): x = numpy.asarray(x) assert x.ndim == 2 if x.shape[1] != 2: raise NotImplementedError('only 2D interpolation is supported for now') import matplotlib.tri self.mpltri = matplotlib.tri.Triangulation(x[:,0], x[:,1], tri_merge(tri, x, mergetol)) def __getitem__(self, x): x = numpy.asarray(x) assert x.shape[-1] == 2 itri = self.mpltri.get_trifinder()(x[...,0].ravel(), x[...,1].ravel()) inside = itri != -1 itri = itri[inside] plane_coords = numpy.concatenate([x.reshape(-1, 2)[inside], numpy.ones([len(itri), 1])], axis=1) def interpolate(vtri): vtri = numpy.asarray(vtri) assert vtri.shape[0] == len(self.mpltri.x) vx = numpy.empty(x.shape[:-1] + vtri.shape[1:]) vx[...] = numpy.nan for vx_items, vtri_items in zip(vx.reshape(len(inside), -1).T, vtri.reshape(len(vtri), -1).T): plane_coeffs = self.mpltri.calculate_plane_coefficients(vtri_items) vx_items[inside] = numeric.contract(plane_coords, plane_coeffs[itri], axis=1) return vx return interpolate class linear_regressor: def add(self, x, y, weight=.5): y = numpy.asarray(y) new = numpy.outer([1, x], [x] + list(y.flat)) (x_, *y_), (xx_, *xy_) = self.avg = (1-weight) * getattr(self, 'avg', new) + weight * new return numpy.dot([[-x_,1], [xx_,-x_]], [y_,xy_]).reshape((2,)+y.shape) / (xx_-x_**2 or numpy.nan) def obj2str(obj): '''compact, lossy string representation of arbitrary object''' return '['+','.join(obj2str(item) for item in obj)+']' if isinstance(obj, collections.abc.Iterable) \ else str(obj).strip('0').rstrip('.') or '0' if isinstance(obj, numbers.Real) \ else str(obj) class single_or_multiple: """ Method wrapper, converts first positional argument to tuple: tuples/lists are passed on as tuples, other objects are turned into tuple singleton. Return values should match the length of the argument list, and are unpacked if the original argument was not a tuple/list. >>> class Test: ... @single_or_multiple ... def square(self, args): ... return [v**2 for v in args] ... >>> T = Test() >>> T.square(2) 4 >>> T.square([2,3]) (4, 9) Args ---- f: :any:`callable` Method that expects a tuple as first positional argument, and that returns a list/tuple of the same length. Returns ------- : Wrapped method. """ def __init__(self, f): functools.update_wrapper(self, f) def __get__(self, instance, owner): return single_or_multiple(self.__wrapped__.__get__(instance, owner)) def __call__(self, *args, **kwargs): if not args: raise TypeError('{} requires at least 1 positional argument'.format(self.__wrapped__.__name__)) ismultiple = isinstance(args[0], (list,tuple,map)) retvals = tuple(self.__wrapped__(tuple(args[0]) if ismultiple else args[:1], *args[1:], **kwargs)) if not ismultiple: retvals, = retvals return retvals class positional_only: '''Change all positional-or-keyword arguments to positional-only. Python introduces syntax to define positional-only parameters in version 3.8, but the same effect can be achieved in older versions by using a wrapper with a var-positional argument. The :func:`positional_only` decorator uses this technique to treat all positional-or-keyword arguments as positional-only. In order to avoid name clashes between the positional-only arguments and variable keyword arguments, the wrapper additionally introduces the convention that the last argument receives the variable keyword argument dictionary in case is has a default value of ... (ellipsis). Example: >>> @positional_only ... def f(x, *, y): ... pass >>> inspect.signature(f) <Signature (x, /, *, y)> >>> @positional_only ... def f(x, *args, y, kwargs=...): ... pass >>> inspect.signature(f) <Signature (x, /, *args, y, **kwargs)> Args ---- f : :any:`callable` Function to be wrapped. ''' def __init__(self, f): signature = inspect.signature(f) parameters = list(signature.parameters.values()) keywords = [] varkw = None for i, param in enumerate(parameters): if param.kind is param.VAR_KEYWORD: raise Exception('positional_only decorated function must use ellipses to mark a variable keyword argument') if i == len(parameters)-1 and param.default is ...: parameters[i] = param.replace(kind=inspect.Parameter.VAR_KEYWORD, default=inspect.Parameter.empty) varkw = param.name elif param.kind is param.POSITIONAL_OR_KEYWORD: parameters[i] = param.replace(kind=param.POSITIONAL_ONLY) elif param.kind is param.KEYWORD_ONLY: keywords.append(param.name) self.__keywords = tuple(keywords) self.__varkw = varkw self.__signature__ = signature.replace(parameters=parameters) functools.update_wrapper(self, f) def __get__(self, instance, owner): return positional_only(self.__wrapped__.__get__(instance, owner)) def __call__(self, *args, **kwargs): wrappedkwargs = {name: kwargs.pop(name) for name in self.__keywords if name in kwargs} if self.__varkw: wrappedkwargs[self.__varkw] = kwargs elif kwargs: raise TypeError('{}() got an unexpected keyword argument {!r}'.format(self.__wrapped__.__name__, *kwargs)) return self.__wrapped__(*args, **wrappedkwargs) def loadlib(**libname): ''' Find and load a dynamic library using :any:`ctypes.CDLL`. For each (supported) platform the name of the library should be specified as a keyword argument, including the extension, where the keywords should match the possible values of :any:`sys.platform`. Example ------- To load the Intel MKL runtime library, write:: loadlib(linux='libmkl_rt.so', darwin='libmkl_rt.dylib', win32='mkl_rt.dll') ''' try: return ctypes.CDLL(libname[sys.platform]) except (OSError, KeyError): pass def readtext(path): '''Read file and return contents Args ---- path: :class:`os.PathLike`, :class:`str` or :class:`io.TextIOBase` Path-like or file-like object pointing to the data to be read. Returns ------- : File data as :class:`str`. ''' if isinstance(path, pathlib.Path): with path.open() as f: return f.read() if isinstance(path, str): with open(path) as f: return f.read() if isinstance(path, io.TextIOBase): return path.read() raise TypeError('readtext requires a path-like or file-like argument') def binaryfile(path): '''Open file for binary reading Args ---- path: :class:`os.PathLike`, :class:`str` or :class:`io.BufferedIOBase` Path-like or file-like object pointing to the data to be read. Returns ------- : Context that returns a :class:`io.BufferedReader` upon entry. ''' if isinstance(path, pathlib.Path): return path.open('rb') if isinstance(path, str): return open(path, 'rb') if isinstance(path, io.BufferedIOBase): return contextlib.nullcontext(path) if hasattr(contextlib, 'nullcontext') \ else contextlib.contextmanager(iter)([path]) # Python <= 3.6 raise TypeError('binaryfile requires a path-like or file-like argument') class settable: '''Context-switchable data container. A mutable container for a general Python object, which can be changed by entering the ``sets`` context. The current value can be accessed via the ``value`` attribute. >>> myprop = settable(2) >>> myprop.value 2 >>> with myprop.sets(3): ... myprop.value 3 >>> myprop.value 2 ''' __slots__ = 'value' def __init__(self, value=None): self.value = value @contextlib.contextmanager def sets(self, value): oldvalue = self.value self.value = value try: yield finally: self.value = oldvalue def index(sequence, item): '''Index of first occurrence. Generalization of `tuple.index`. ''' if isinstance(sequence, (list, tuple)): return sequence.index(item) for i, v in enumerate(sequence): if v == item: return i raise ValueError('index(sequence, item): item not in sequence') def unique(items, key=None): '''Deduplicate items in sequence. Return a tuple `(unique, indices)` such that `items[i] == unique[indices[i]]` and `unique` does not contain duplicate items. An optional `key` is applied to all items before testing for equality. ''' seen = {} unique = [] indices = [] for item in items: k = item if key is None else key(item) try: index = seen[k] except KeyError: index = seen[k] = len(unique) unique.append(item) indices.append(index) return unique, indices try: cached_property = functools.cached_property except AttributeError: # python < 3.8 def cached_property(func): # minimal backport @functools.wraps(func) def wrapped(self): try: val = self.__dict__[func.__name__] except KeyError: self.__dict__[func.__name__] = val = func(self) return val return property(wrapped) # vim:sw=2:sts=2:et
31.45155
115
0.670466
79517f77cf4ff40f3a04a2f6e3cbdc38ac7594c9
9,481
py
Python
tests/scrapers/test_reel.py
code1dot/instascrape
aa0a7e556341ab12be9ab4587c6c57ddf432675f
[ "MIT" ]
445
2020-10-05T19:33:31.000Z
2022-03-28T20:06:15.000Z
tests/scrapers/test_reel.py
code1dot/instascrape
aa0a7e556341ab12be9ab4587c6c57ddf432675f
[ "MIT" ]
92
2020-10-05T15:15:08.000Z
2022-03-31T03:18:58.000Z
tests/scrapers/test_reel.py
code1dot/instascrape
aa0a7e556341ab12be9ab4587c6c57ddf432675f
[ "MIT" ]
116
2020-10-05T17:06:20.000Z
2022-03-20T15:39:46.000Z
import csv import datetime import json import re import os import pytest from bs4 import BeautifulSoup import requests from instascrape import Reel class TestReel: @pytest.fixture def url(self): return "https://www.instagram.com/reel/CIrJSrFFHM_/" @pytest.fixture def get_request(self, url): return requests.get(url, headers={"User-Agent": "user-agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36 Edg/87.0.664.57"}) @pytest.fixture def page_instance(self, url): random_google_reel = Reel(url) random_google_reel.scrape() return random_google_reel def test_from_html(self, get_request, page_instance): reel_html = get_request.text reel_obj = Reel(reel_html) reel_obj.scrape() assert reel_obj.likes == page_instance.likes def test_from_soup(self, get_request, page_instance): reel_html = get_request.text reel_soup = BeautifulSoup(reel_html, features='lxml') reel_obj = Reel(reel_soup) reel_obj.scrape() assert reel_obj.likes == page_instance.likes def test_to_dict(self, page_instance): assert isinstance(page_instance.to_dict(), dict) def test_embed(self, page_instance): html_embed = page_instance.embed() embed_copied_from_instagram = '<blockquote class="instagram-media" data-instgrm-captioned data-instgrm-permalink="https://www.instagram.com/reel/CIrJSrFFHM_/?utm_source=ig_embed&amp;utm_campaign=loading" data-instgrm-version="13" style=" background:#FFF; border:0; border-radius:3px; box-shadow:0 0 1px 0 rgba(0,0,0,0.5),0 1px 10px 0 rgba(0,0,0,0.15); margin: 1px; max-width:540px; min-width:326px; padding:0; width:99.375%; width:-webkit-calc(100% - 2px); width:calc(100% - 2px);"><div style="padding:16px;"> <a href="https://www.instagram.com/reel/CIrJSrFFHM_/?utm_source=ig_embed&amp;utm_campaign=loading" style=" background:#FFFFFF; line-height:0; padding:0 0; text-align:center; text-decoration:none; width:100%;" target="_blank"> <div style=" display: flex; flex-direction: row; align-items: center;"> <div style="background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 40px; margin-right: 14px; width: 40px;"></div> <div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center;"> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 100px;"></div> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 60px;"></div></div></div><div style="padding: 19% 0;"></div> <div style="display:block; height:50px; margin:0 auto 12px; width:50px;"><svg width="50px" height="50px" viewBox="0 0 60 60" version="1.1" xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink"><g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g transform="translate(-511.000000, -20.000000)" fill="#000000"><g><path d="M556.869,30.41 C554.814,30.41 553.148,32.076 553.148,34.131 C553.148,36.186 554.814,37.852 556.869,37.852 C558.924,37.852 560.59,36.186 560.59,34.131 C560.59,32.076 558.924,30.41 556.869,30.41 M541,60.657 C535.114,60.657 530.342,55.887 530.342,50 C530.342,44.114 535.114,39.342 541,39.342 C546.887,39.342 551.658,44.114 551.658,50 C551.658,55.887 546.887,60.657 541,60.657 M541,33.886 C532.1,33.886 524.886,41.1 524.886,50 C524.886,58.899 532.1,66.113 541,66.113 C549.9,66.113 557.115,58.899 557.115,50 C557.115,41.1 549.9,33.886 541,33.886 M565.378,62.101 C565.244,65.022 564.756,66.606 564.346,67.663 C563.803,69.06 563.154,70.057 562.106,71.106 C561.058,72.155 560.06,72.803 558.662,73.347 C557.607,73.757 556.021,74.244 553.102,74.378 C549.944,74.521 548.997,74.552 541,74.552 C533.003,74.552 532.056,74.521 528.898,74.378 C525.979,74.244 524.393,73.757 523.338,73.347 C521.94,72.803 520.942,72.155 519.894,71.106 C518.846,70.057 518.197,69.06 517.654,67.663 C517.244,66.606 516.755,65.022 516.623,62.101 C516.479,58.943 516.448,57.996 516.448,50 C516.448,42.003 516.479,41.056 516.623,37.899 C516.755,34.978 517.244,33.391 517.654,32.338 C518.197,30.938 518.846,29.942 519.894,28.894 C520.942,27.846 521.94,27.196 523.338,26.654 C524.393,26.244 525.979,25.756 528.898,25.623 C532.057,25.479 533.004,25.448 541,25.448 C548.997,25.448 549.943,25.479 553.102,25.623 C556.021,25.756 557.607,26.244 558.662,26.654 C560.06,27.196 561.058,27.846 562.106,28.894 C563.154,29.942 563.803,30.938 564.346,32.338 C564.756,33.391 565.244,34.978 565.378,37.899 C565.522,41.056 565.552,42.003 565.552,50 C565.552,57.996 565.522,58.943 565.378,62.101 M570.82,37.631 C570.674,34.438 570.167,32.258 569.425,30.349 C568.659,28.377 567.633,26.702 565.965,25.035 C564.297,23.368 562.623,22.342 560.652,21.575 C558.743,20.834 556.562,20.326 553.369,20.18 C550.169,20.033 549.148,20 541,20 C532.853,20 531.831,20.033 528.631,20.18 C525.438,20.326 523.257,20.834 521.349,21.575 C519.376,22.342 517.703,23.368 516.035,25.035 C514.368,26.702 513.342,28.377 512.574,30.349 C511.834,32.258 511.326,34.438 511.181,37.631 C511.035,40.831 511,41.851 511,50 C511,58.147 511.035,59.17 511.181,62.369 C511.326,65.562 511.834,67.743 512.574,69.651 C513.342,71.625 514.368,73.296 516.035,74.965 C517.703,76.634 519.376,77.658 521.349,78.425 C523.257,79.167 525.438,79.673 528.631,79.82 C531.831,79.965 532.853,80.001 541,80.001 C549.148,80.001 550.169,79.965 553.369,79.82 C556.562,79.673 558.743,79.167 560.652,78.425 C562.623,77.658 564.297,76.634 565.965,74.965 C567.633,73.296 568.659,71.625 569.425,69.651 C570.167,67.743 570.674,65.562 570.82,62.369 C570.966,59.17 571,58.147 571,50 C571,41.851 570.966,40.831 570.82,37.631"></path></g></g></g></svg></div><div style="padding-top: 8px;"> <div style=" color:#3897f0; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:550; line-height:18px;"> View this post on Instagram</div></div><div style="padding: 12.5% 0;"></div> <div style="display: flex; flex-direction: row; margin-bottom: 14px; align-items: center;"><div> <div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(0px) translateY(7px);"></div> <div style="background-color: #F4F4F4; height: 12.5px; transform: rotate(-45deg) translateX(3px) translateY(1px); width: 12.5px; flex-grow: 0; margin-right: 14px; margin-left: 2px;"></div> <div style="background-color: #F4F4F4; border-radius: 50%; height: 12.5px; width: 12.5px; transform: translateX(9px) translateY(-18px);"></div></div><div style="margin-left: 8px;"> <div style=" background-color: #F4F4F4; border-radius: 50%; flex-grow: 0; height: 20px; width: 20px;"></div> <div style=" width: 0; height: 0; border-top: 2px solid transparent; border-left: 6px solid #f4f4f4; border-bottom: 2px solid transparent; transform: translateX(16px) translateY(-4px) rotate(30deg)"></div></div><div style="margin-left: auto;"> <div style=" width: 0px; border-top: 8px solid #F4F4F4; border-right: 8px solid transparent; transform: translateY(16px);"></div> <div style=" background-color: #F4F4F4; flex-grow: 0; height: 12px; width: 16px; transform: translateY(-4px);"></div> <div style=" width: 0; height: 0; border-top: 8px solid #F4F4F4; border-left: 8px solid transparent; transform: translateY(-4px) translateX(8px);"></div></div></div> <div style="display: flex; flex-direction: column; flex-grow: 1; justify-content: center; margin-bottom: 24px;"> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; margin-bottom: 6px; width: 224px;"></div> <div style=" background-color: #F4F4F4; border-radius: 4px; flex-grow: 0; height: 14px; width: 144px;"></div></div></a><p style=" color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; line-height:17px; margin-bottom:0; margin-top:8px; overflow:hidden; padding:8px 0 7px; text-align:center; text-overflow:ellipsis; white-space:nowrap;"><a href="https://www.instagram.com/reel/CIrJSrFFHM_/?utm_source=ig_embed&amp;utm_campaign=loading" style=" color:#c9c8cd; font-family:Arial,sans-serif; font-size:14px; font-style:normal; font-weight:normal; line-height:17px; text-decoration:none;" target="_blank">A post shared by Google (@google)</a></p></div></blockquote> <script async src="//www.instagram.com/embed.js"></script>' assert html_embed == embed_copied_from_instagram @pytest.mark.file_io def test_to_json(self, page_instance, tmpdir): file = tmpdir.join("data.json") page_instance.to_json(fp=str(file)) with open(str(file), "r") as injson: json_dict = json.load(injson) assert page_instance['shortcode'] == json_dict['shortcode'] @pytest.mark.file_io def test_to_csv(self, page_instance, tmpdir): # write to CSV file = tmpdir.join("data.csv") page_instance.to_csv(fp=str(file)) # reread the csv with open(str(file), mode="r") as infile: reader = csv.reader(infile) csv_dict = {row[0]: row[1] for row in reader} assert page_instance['shortcode'] == csv_dict['shortcode'] @pytest.mark.file_io def test_download_photo(self, page_instance, tmpdir): # donwload photo file = tmpdir.join("image.jpg") page_instance.download(fp=str(file)) assert os.path.exists(file)
120.012658
6,999
0.703618
7951802bea7927d1a926b21c11f1c9a679a6c1da
735
py
Python
test/statements/import7.py
abjugard/MagicPython
2802ded681e0ab1a1057821c1da287147d639505
[ "MIT" ]
1,482
2015-10-16T21:59:32.000Z
2022-03-30T11:44:40.000Z
test/statements/import7.py
abjugard/MagicPython
2802ded681e0ab1a1057821c1da287147d639505
[ "MIT" ]
226
2015-10-15T15:53:44.000Z
2022-03-25T03:08:27.000Z
test/statements/import7.py
abjugard/MagicPython
2802ded681e0ab1a1057821c1da287147d639505
[ "MIT" ]
129
2015-10-20T02:41:49.000Z
2022-03-22T01:44:36.000Z
from .importing import * from importing import * from : keyword.control.import.python, source.python : source.python . : punctuation.separator.period.python, source.python importing : source.python : source.python import : keyword.control.import.python, source.python : source.python * : keyword.operator.arithmetic.python, source.python from : keyword.control.import.python, source.python : source.python importing : source.python : source.python import : keyword.control.import.python, source.python : source.python * : keyword.operator.arithmetic.python, source.python
35
66
0.617687
795181d419550e9da97e49798e8ae7fdf6b03834
12,556
py
Python
flanker/mime/message/scanner.py
meta-x/flanker
1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad
[ "Apache-2.0" ]
null
null
null
flanker/mime/message/scanner.py
meta-x/flanker
1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad
[ "Apache-2.0" ]
null
null
null
flanker/mime/message/scanner.py
meta-x/flanker
1e37baa1db2ecee238ac3de1e36a2948e0a6d3ad
[ "Apache-2.0" ]
1
2020-12-18T08:33:56.000Z
2020-12-18T08:33:56.000Z
import regex as re from collections import deque from cStringIO import StringIO from flanker.mime.message.headers import parsing, is_empty, ContentType from flanker.mime.message.part import MimePart, Stream from flanker.mime.message.errors import DecodingError from logging import getLogger log = getLogger(__name__) def scan(string): """Scanner that uses 1 pass to scan the entire message and build a message tree""" if not isinstance(string, str): raise DecodingError("Scanner works with byte strings only") tokens = tokenize(string) if not tokens: tokens = [default_content_type()] try: return traverse( Start(), TokensIterator(tokens, string)) except DecodingError: raise except Exception: raise DecodingError( "Mailformed MIME message") def traverse(pointer, iterator, parent=None): """Recursive-descendant parser""" iterator.check() token = iterator.next() # this means that this part does not have any # content type set, so set it to RFC default (text/plain) # it even can have no headers if token.is_end() or token.is_boundary(): return make_part( content_type=default_content_type(), start=pointer, end=token, iterator=iterator, parent=parent) # this part tells us that it is singlepart # so we should ignore all other content-type headers # until the boundary or the end of message if token.is_singlepart(): while True: iterator.check() end = iterator.next() if not end.is_content_type(): break return make_part( content_type=token, start=pointer, end=end, iterator=iterator, parent=parent) # good old multipart message # here goes the real recursion # we scan part by part until the end elif token.is_multipart(): content_type = token # well, multipart message should provide # some boundary, how could we parse it otherwise? boundary = content_type.get_boundary() if not boundary: raise DecodingError( "Multipart message without boundary") parts = deque() token = iterator.next() # we are expecting first boundary for multipart message # something is broken otherwize if not token.is_boundary() or token != boundary: raise DecodingError( "Multipart message without starting boundary") while True: token = iterator.current() if token.is_end(): break if token == boundary and token.is_final(): iterator.next() break parts.append( traverse(token, iterator, content_type)) return make_part( content_type=content_type, start=pointer, end=token, iterator=iterator, parts=parts, parent=parent) # this is a weird mime part, actually # it can contain multiple headers # separated by newlines, so we grab them here elif token.is_delivery_status(): if parent and parent.is_multipart(): while True: iterator.check() end = iterator.next() if not end.is_content_type(): break else: raise DecodingError( "Mailformed delivery status message") return make_part( content_type=token, start=pointer, end=end, iterator=iterator, parent=parent) # this is a message container that holds # a message inside, delimited from parent # headers by newline elif token.is_message_container(): enclosed = traverse(pointer, iterator, token) return make_part( content_type=token, start=pointer, end=iterator.current(), iterator=iterator, enclosed=enclosed, parent=parent) # this part contains headers separated by newlines, # grab these headers and enclose them in one part elif token.is_headers_container(): enclosed = grab_headers(pointer, iterator, token) return make_part( content_type=token, start=pointer, end=iterator.current(), iterator=iterator, enclosed=enclosed, parent=parent) def grab_headers(pointer, iterator, parent): """This function collects all tokens till the boundary or the end of the message. Used to scan parts of the message that contain random headers, e.g. text/rfc822-headers""" content_type = None while True: iterator.check() end = iterator.next() # remember the first content-type we have met when grabbing # the headers until the boundary or message end if not content_type and end.is_content_type(): content_type = end if not end.is_content_type(): break return make_part( content_type=content_type or ContentType("text", "plain"), start=pointer, end=end, iterator=iterator, parent=parent) def default_content_type(): return ContentType("text", "plain", {'charset': 'ascii'}) def make_part(content_type, start, end, iterator, parts=[], enclosed=None, parent=None): # here we detect where the message really starts # the exact position in the string, at the end of the # starting boundary and after the begining of the end boundary if start.is_boundary(): start = start.end + 1 else: start = start.start # if this is the message ending, end of part # the position of the last symbol of the message if end.is_end(): end = len(iterator.string) - 1 # for multipart boundaries # consider the final boundary as the ending one elif content_type.is_multipart(): end = end.end # otherwize, end is position of the the symbol before # the boundary start else: end = end.start - 1 # our tokenizer detected the begining of the message container # that is separated from the enclosed message by newlines # here we find where the enclosed message begings by searching for the # first newline if parent and (parent.is_message_container() or parent.is_headers_container()): start = locate_first_newline(iterator.stream, start) # ok, finally, create the MimePart. # note that it does not parse anything, just remembers # the position in the string return MimePart( container=Stream( content_type=content_type, start=start, end=end, stream=iterator.stream, string=iterator.string), parts=parts, enclosed=enclosed, is_root=(parent==None)) def locate_first_newline(stream, start): """We need to locate the first newline""" stream.seek(start) for line in stream: if is_empty(line): return stream.tell() class TokensIterator(object): def __init__(self, tokens, string): self.position = -1 self.tokens = tokens self.string = string self.stream = StringIO(string) self.opcount = 0 def next(self): self.position += 1 if self.position >= len(self.tokens): return END return self.tokens[self.position] def current(self): if self.position >= len(self.tokens): return END return self.tokens[self.position] def back(self): self.position -= 1 def check(self): """ This function is used to protect our lovely scanner from the deadloops, we count the number of operations performed and will raise an exception if things go wrong (too much ops) """ self.opcount += 1 if self.opcount > MAX_OPS: raise DecodingError( "Too many parts: {}, max is {}".format( self.opcount, MAX_OPS)) class Boundary(object): def __init__(self, value, start, end, final=None): self.value = value self.start = start self.end = end self.final = final def is_final(self): return self.final def __str__(self): return "Boundary({}, final={})".format( self.value, self.final) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if isinstance(other, Boundary): return self.value == other.value and self.final == other.final else: return self.value == str(other) def is_content_type(self): return False def is_boundary(self): return True def is_end(self): return False class End(object): def is_end(self): return True @property def start(self): return -1 @property def end(self): return -1 def is_boundary(self): return False def is_content_type(self): return False class Start(object): def is_end(self): return False @property def start(self): return 0 @property def end(self): return 0 def is_boundary(self): return False pattern = re.compile( r"""(?P<ctype> ^content-type: # field value, consists of printable # US-ASCII chars, space and tab [\x21-\x7e\ \t]+ # optional field folded part # newline followed by one or more spaces # and field value symbols (can not be empty) (?:(?:\r\n|\n)[ \t]+[\x20-\x7e \t]+)* ) | (?P<boundary> # this may be a boundary and may be not # we just pre-scan it for future consideration ^--.* )""", re.IGNORECASE | re.MULTILINE | re.VERBOSE) CTYPE = 'ctype' BOUNDARY = 'boundary' END = End() MAX_OPS = 500 def tokenize(string): """ This function scans the entire message with a simple regex to find all Content-Types and boundaries. """ tokens = deque() for m in pattern.finditer(string): if m.group(CTYPE): name, token = parsing.parse_header(m.group(CTYPE)) else: token = Boundary( m.group(BOUNDARY).strip("\t\r\n"), grab_newline(m.start(), string, -1), grab_newline(m.end(), string, 1)) tokens.append(token) return setup_boundaries(tokens) def grab_newline(position, string, direction): """Boundary can be preceeded by \r\n or \n and can end with \r\n or \n this function scans the line to locate these cases. """ while 0 < position < len(string): if string[position] == '\n': if direction < 0: if position - 1 > 0 and string[position-1] == '\r': return position - 1 return position position += direction return position def setup_boundaries(tokens): """ We need to reliably determine whether given line is a boundary or just pretends to be one. We get all the multipart content-types that declare the boundaries and check each boundary against them to verify. Additional complexity is that boundary can consist of dashes only """ boundaries = [t.get_boundary() for t in tokens \ if t.is_content_type() and t.get_boundary()] def strip_endings(value): if value.endswith("--"): return value[:-2] else: return value def setup(token): if token.is_content_type(): return True elif token.is_boundary(): value = token.value[2:] if value in boundaries: token.value = value token.final = False return True if strip_endings(value) in boundaries: token.value = strip_endings(value) token.final = True return True # false boundary return False else: raise DecodingError("Unknown token") return token.is_content_type() or \ (token.is_boundary() and token in boundaries) return [t for t in tokens if setup(t)]
28.343115
83
0.591908
795181d6f4f89b0559e4e0362fb5bd539ca49836
238
py
Python
relayer/utils/__init__.py
wizeline/relayer
72b579b65d351ee2a006b06b6e72ef3fb3e69758
[ "MIT" ]
3
2016-11-13T03:16:26.000Z
2018-12-11T23:46:16.000Z
relayer/utils/__init__.py
wizeline/relayer
72b579b65d351ee2a006b06b6e72ef3fb3e69758
[ "MIT" ]
27
2016-06-21T18:05:25.000Z
2021-12-13T19:55:25.000Z
relayer/utils/__init__.py
wizeline/relayer
72b579b65d351ee2a006b06b6e72ef3fb3e69758
[ "MIT" ]
1
2016-06-28T16:09:09.000Z
2016-06-28T16:09:09.000Z
from datetime import datetime def get_elapsed_time_in_milliseconds(start_time: datetime, end_time: datetime) -> float: elapsed_time = end_time - start_time return elapsed_time.microseconds / 1000.0 + elapsed_time.seconds * 1000
34
88
0.789916
7951828c6641d38543a87a95b532cc9d97665d83
308
py
Python
run.py
Katze2/Flask-template
99925f6bfbaf92ace9b0fd7c792b989ed90a7e00
[ "MIT" ]
null
null
null
run.py
Katze2/Flask-template
99925f6bfbaf92ace9b0fd7c792b989ed90a7e00
[ "MIT" ]
null
null
null
run.py
Katze2/Flask-template
99925f6bfbaf92ace9b0fd7c792b989ed90a7e00
[ "MIT" ]
null
null
null
# -*- encoding: utf-8 -*- """ Python Aplication Template Licence: GPLv3 """ import os from app import app #---------------------------------------- # launch #---------------------------------------- if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
17.111111
41
0.470779
795182c2b6a869d7e8209dbe0877adafa25987cd
3,828
py
Python
OBlog/blueprint/comments/main.py
OhYee/OBlog
a9d7e4fda5651cf9c5afd4c128c4df4442794e97
[ "BSD-3-Clause" ]
23
2018-02-23T12:56:43.000Z
2021-12-20T13:21:47.000Z
OBlog/blueprint/comments/main.py
OhYee/OBlog
a9d7e4fda5651cf9c5afd4c128c4df4442794e97
[ "BSD-3-Clause" ]
17
2018-02-23T12:52:39.000Z
2018-12-04T05:50:58.000Z
OBlog/blueprint/comments/main.py
OhYee/OBlog
a9d7e4fda5651cf9c5afd4c128c4df4442794e97
[ "BSD-3-Clause" ]
2
2018-06-16T20:52:23.000Z
2021-04-08T15:29:44.000Z
from OBlog import database as db from .sendEmail import Email from ..posts.main import getPostForShow from OBlog.markdown import render_markdown import re import time from ..admin.main import getSiteConfigDict def getCommentsOfUrlForShow(url): res = db.query_db( 'select id,html,username,time,sendemail,ad from comments where url="{}" and show="true"', url) return res def getCommentsOfID(_id): return db.query_db('select * from comments where id="{}"', _id, one=True) def getAllComments(): return db.query_db('select * from comments;') def getLastID(): res = db.raw_query_db('select count(id) from comments') return res[0][0] def contain_zh(word): ''' description: 检测是否存在中文 input: 文本 output: bool - True:存在中文;False:不存在中文 ''' return len(re.findall(u'[\u4e00-\u9fa5]+', word)) != 0 def mail(postUrl, raw, emailaddress): ''' description: 给该评论@的所有用户以及站长发信 input: text - postUrl 评论的页面链接 text - raw 评论内容 output: ''' config = getSiteConfigDict() if config['smtp']['value'] != '1': # 未开启smtp return rooturl = config['rooturl']['value'] post = getPostForShow(postUrl[5:]) if len(postUrl) > 5 else None title = post['title'] if post else '评论区' url = rooturl + postUrl mailList = re.findall(r'@([0-9]+)#', raw) for _id in mailList: d = getCommentsOfID(_id) if d and d["sendemail"] == 'true' and d["show"] == 'true': Email( d['email'], "评论通知", '''您好:<br> 有人在评论中@您,点击链接查看评论内容<br> <a href='{url}'>{title}</a><br> 若无法点击链接,可以将网址({url})复制到地址栏<br> <br> From:{sitename}评论自动通知系统<br> 该邮件无需回复,如有问题请联系{email} '''.format( url=url, title=title, sitename=config["sitename"]['value'], email=config["email"]['value'] )) Email(config["email"]['value'], "评论通知", emailaddress + "评论了文章<a href='" + url + "'>" + title + "</a>(" + url + ")<br>内容如下<br>" + raw) def addComment(postRequest): if not re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[A-Za-z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', postRequest['email']): return [1, ''] if not contain_zh(postRequest['raw']): return [2, ''] postRequest['id'] = str(getLastID() + 1) postRequest['html'] = render_markdown(postRequest['raw'], allow_html=False) postRequest['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) postRequest['username'] = postRequest['email'][0:2] + \ '******' + postRequest['email'][-2:] postRequest['show'] = 'true' postRequest['ad'] = 'false' keyList = ['id', 'raw', 'html', 'time', 'username', 'email', 'sendemail', 'show', 'ad', 'url', 'ip'] postRequest = dict( (key, postRequest[key] if key in postRequest else "")for key in keyList) db.insert_db("comments", postRequest) try: mail(postRequest['url'], postRequest['raw'], postRequest['email']) except Exception as e: print(e.args) return [0, postRequest] def updateComment(postRequest): cid = postRequest['id'] keyList = ['sendemail', 'show', 'ad'] postRequest = dict( (key, postRequest[key] if key in postRequest else "")for key in keyList) db.update_db("comments", postRequest, {'id': cid}) return 0 def updateCommentUrl(postRequest): db.update_db("comments", {'url': postRequest['url']}, { 'url': postRequest['oldurl']}) return 0
30.624
109
0.540752
7951834c2b6d4ca26cd8612c8eb878d770f5a895
1,623
py
Python
src/google/appengine/datastore/datastore_pb.py
myelin/appengine-python-standard
2a99acd114f7cdd66fbad9bfd185384eef847c84
[ "Apache-2.0" ]
null
null
null
src/google/appengine/datastore/datastore_pb.py
myelin/appengine-python-standard
2a99acd114f7cdd66fbad9bfd185384eef847c84
[ "Apache-2.0" ]
null
null
null
src/google/appengine/datastore/datastore_pb.py
myelin/appengine-python-standard
2a99acd114f7cdd66fbad9bfd185384eef847c84
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # # Copyright 2007 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """The Python datastore protocol buffer definition (old name).""" from __future__ import absolute_import from google.appengine.api.api_base_pb2 import Integer64Proto from google.appengine.api.api_base_pb2 import StringProto from google.appengine.api.api_base_pb2 import VoidProto from google.appengine.datastore import datastore_v3_bytes_pb2 as datastore_v3_pb2 from google.appengine.datastore.datastore_v3_bytes_pb2 import * from google.appengine.datastore.action_pb2 import Action from google.appengine.datastore.entity_bytes_pb2 import CompositeIndex from google.appengine.datastore.entity_bytes_pb2 import EntityProto from google.appengine.datastore.entity_bytes_pb2 import Index from google.appengine.datastore.entity_bytes_pb2 import Path from google.appengine.datastore.entity_bytes_pb2 import Property from google.appengine.datastore.entity_bytes_pb2 import PropertyValue from google.appengine.datastore.entity_bytes_pb2 import Reference from google.appengine.datastore.snapshot_pb2 import Snapshot
33.122449
81
0.825015
7951842acc6741c52b2669400f7082171c68d377
31,921
py
Python
sdk/python/arvados/commands/arv_copy.py
chlige/arvados
e4a68851e521c0e3152f9790683d8cdb1b3923df
[ "ECL-2.0", "Apache-2.0" ]
222
2015-01-02T17:24:54.000Z
2019-11-27T06:31:51.000Z
sdk/python/arvados/commands/arv_copy.py
chlige/arvados
e4a68851e521c0e3152f9790683d8cdb1b3923df
[ "ECL-2.0", "Apache-2.0" ]
62
2015-03-12T20:22:06.000Z
2019-12-04T18:35:35.000Z
sdk/python/arvados/commands/arv_copy.py
chlige/arvados
e4a68851e521c0e3152f9790683d8cdb1b3923df
[ "ECL-2.0", "Apache-2.0" ]
75
2015-01-22T21:20:50.000Z
2019-12-03T08:52:23.000Z
# Copyright (C) The Arvados Authors. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # arv-copy [--recursive] [--no-recursive] object-uuid # # Copies an object from Arvados instance src to instance dst. # # By default, arv-copy recursively copies any dependent objects # necessary to make the object functional in the new instance # (e.g. for a workflow, arv-copy copies the workflow, # input collections, and docker images). If # --no-recursive is given, arv-copy copies only the single record # identified by object-uuid. # # The user must have files $HOME/.config/arvados/{src}.conf and # $HOME/.config/arvados/{dst}.conf with valid login credentials for # instances src and dst. If either of these files is not found, # arv-copy will issue an error. from __future__ import division from future import standard_library from future.utils import listvalues standard_library.install_aliases() from past.builtins import basestring from builtins import object import argparse import contextlib import getpass import os import re import shutil import sys import logging import tempfile import urllib.parse import io import arvados import arvados.config import arvados.keep import arvados.util import arvados.commands._util as arv_cmd import arvados.commands.keepdocker import ruamel.yaml as yaml from arvados.api import OrderedJsonModel from arvados._version import __version__ COMMIT_HASH_RE = re.compile(r'^[0-9a-f]{1,40}$') logger = logging.getLogger('arvados.arv-copy') # local_repo_dir records which git repositories from the Arvados source # instance have been checked out locally during this run, and to which # directories. # e.g. if repository 'twp' from src_arv has been cloned into # /tmp/gitfHkV9lu44A then local_repo_dir['twp'] = '/tmp/gitfHkV9lu44A' # local_repo_dir = {} # List of collections that have been copied in this session, and their # destination collection UUIDs. collections_copied = {} # Set of (repository, script_version) two-tuples of commits copied in git. scripts_copied = set() # The owner_uuid of the object being copied src_owner_uuid = None def main(): copy_opts = argparse.ArgumentParser(add_help=False) copy_opts.add_argument( '--version', action='version', version="%s %s" % (sys.argv[0], __version__), help='Print version and exit.') copy_opts.add_argument( '-v', '--verbose', dest='verbose', action='store_true', help='Verbose output.') copy_opts.add_argument( '--progress', dest='progress', action='store_true', help='Report progress on copying collections. (default)') copy_opts.add_argument( '--no-progress', dest='progress', action='store_false', help='Do not report progress on copying collections.') copy_opts.add_argument( '-f', '--force', dest='force', action='store_true', help='Perform copy even if the object appears to exist at the remote destination.') copy_opts.add_argument( '--src', dest='source_arvados', help='The cluster id of the source Arvados instance. May be either a pathname to a config file, or (for example) "foo" as shorthand for $HOME/.config/arvados/foo.conf. If not provided, will be inferred from the UUID of the object being copied.') copy_opts.add_argument( '--dst', dest='destination_arvados', help='The name of the destination Arvados instance (required). May be either a pathname to a config file, or (for example) "foo" as shorthand for $HOME/.config/arvados/foo.conf. If not provided, will use ARVADOS_API_HOST from environment.') copy_opts.add_argument( '--recursive', dest='recursive', action='store_true', help='Recursively copy any dependencies for this object, and subprojects. (default)') copy_opts.add_argument( '--no-recursive', dest='recursive', action='store_false', help='Do not copy any dependencies or subprojects.') copy_opts.add_argument( '--project-uuid', dest='project_uuid', help='The UUID of the project at the destination to which the collection or workflow should be copied.') copy_opts.add_argument( '--storage-classes', dest='storage_classes', help='Comma separated list of storage classes to be used when saving data to the destinaton Arvados instance.') copy_opts.add_argument( 'object_uuid', help='The UUID of the object to be copied.') copy_opts.set_defaults(progress=True) copy_opts.set_defaults(recursive=True) parser = argparse.ArgumentParser( description='Copy a workflow, collection or project from one Arvados instance to another. On success, the uuid of the copied object is printed to stdout.', parents=[copy_opts, arv_cmd.retry_opt]) args = parser.parse_args() if args.storage_classes: args.storage_classes = [x for x in args.storage_classes.strip().replace(' ', '').split(',') if x] if args.verbose: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) if not args.source_arvados: args.source_arvados = args.object_uuid[:5] # Create API clients for the source and destination instances src_arv = api_for_instance(args.source_arvados) dst_arv = api_for_instance(args.destination_arvados) if not args.project_uuid: args.project_uuid = dst_arv.users().current().execute(num_retries=args.retries)["uuid"] # Identify the kind of object we have been given, and begin copying. t = uuid_type(src_arv, args.object_uuid) if t == 'Collection': set_src_owner_uuid(src_arv.collections(), args.object_uuid, args) result = copy_collection(args.object_uuid, src_arv, dst_arv, args) elif t == 'Workflow': set_src_owner_uuid(src_arv.workflows(), args.object_uuid, args) result = copy_workflow(args.object_uuid, src_arv, dst_arv, args) elif t == 'Group': set_src_owner_uuid(src_arv.groups(), args.object_uuid, args) result = copy_project(args.object_uuid, src_arv, dst_arv, args.project_uuid, args) else: abort("cannot copy object {} of type {}".format(args.object_uuid, t)) # Clean up any outstanding temp git repositories. for d in listvalues(local_repo_dir): shutil.rmtree(d, ignore_errors=True) # If no exception was thrown and the response does not have an # error_token field, presume success if 'error_token' in result or 'uuid' not in result: logger.error("API server returned an error result: {}".format(result)) exit(1) print(result['uuid']) if result.get('partial_error'): logger.warning("Warning: created copy with uuid {} but failed to copy some items: {}".format(result['uuid'], result['partial_error'])) exit(1) logger.info("Success: created copy with uuid {}".format(result['uuid'])) exit(0) def set_src_owner_uuid(resource, uuid, args): global src_owner_uuid c = resource.get(uuid=uuid).execute(num_retries=args.retries) src_owner_uuid = c.get("owner_uuid") # api_for_instance(instance_name) # # Creates an API client for the Arvados instance identified by # instance_name. # # If instance_name contains a slash, it is presumed to be a path # (either local or absolute) to a file with Arvados configuration # settings. # # Otherwise, it is presumed to be the name of a file in # $HOME/.config/arvados/instance_name.conf # def api_for_instance(instance_name): if not instance_name: # Use environment return arvados.api('v1', model=OrderedJsonModel()) if '/' in instance_name: config_file = instance_name else: config_file = os.path.join(os.environ['HOME'], '.config', 'arvados', "{}.conf".format(instance_name)) try: cfg = arvados.config.load(config_file) except (IOError, OSError) as e: abort(("Could not open config file {}: {}\n" + "You must make sure that your configuration tokens\n" + "for Arvados instance {} are in {} and that this\n" + "file is readable.").format( config_file, e, instance_name, config_file)) if 'ARVADOS_API_HOST' in cfg and 'ARVADOS_API_TOKEN' in cfg: api_is_insecure = ( cfg.get('ARVADOS_API_HOST_INSECURE', '').lower() in set( ['1', 't', 'true', 'y', 'yes'])) client = arvados.api('v1', host=cfg['ARVADOS_API_HOST'], token=cfg['ARVADOS_API_TOKEN'], insecure=api_is_insecure, model=OrderedJsonModel()) else: abort('need ARVADOS_API_HOST and ARVADOS_API_TOKEN for {}'.format(instance_name)) return client # Check if git is available def check_git_availability(): try: arvados.util.run_command(['git', '--help']) except Exception: abort('git command is not available. Please ensure git is installed.') def filter_iter(arg): """Iterate a filter string-or-list. Pass in a filter field that can either be a string or list. This will iterate elements as if the field had been written as a list. """ if isinstance(arg, basestring): return iter((arg,)) else: return iter(arg) def migrate_repository_filter(repo_filter, src_repository, dst_repository): """Update a single repository filter in-place for the destination. If the filter checks that the repository is src_repository, it is updated to check that the repository is dst_repository. If it does anything else, this function raises ValueError. """ if src_repository is None: raise ValueError("component does not specify a source repository") elif dst_repository is None: raise ValueError("no destination repository specified to update repository filter") elif repo_filter[1:] == ['=', src_repository]: repo_filter[2] = dst_repository elif repo_filter[1:] == ['in', [src_repository]]: repo_filter[2] = [dst_repository] else: raise ValueError("repository filter is not a simple source match") def migrate_script_version_filter(version_filter): """Update a single script_version filter in-place for the destination. Currently this function checks that all the filter operands are Git commit hashes. If they're not, it raises ValueError to indicate that the filter is not portable. It could be extended to make other transformations in the future. """ if not all(COMMIT_HASH_RE.match(v) for v in filter_iter(version_filter[2])): raise ValueError("script_version filter is not limited to commit hashes") def attr_filtered(filter_, *attr_names): """Return True if filter_ applies to any of attr_names, else False.""" return any((name == 'any') or (name in attr_names) for name in filter_iter(filter_[0])) @contextlib.contextmanager def exception_handler(handler, *exc_types): """If any exc_types are raised in the block, call handler on the exception.""" try: yield except exc_types as error: handler(error) # copy_workflow(wf_uuid, src, dst, args) # # Copies a workflow identified by wf_uuid from src to dst. # # If args.recursive is True, also copy any collections # referenced in the workflow definition yaml. # # The owner_uuid of the new workflow is set to any given # project_uuid or the user who copied the template. # # Returns the copied workflow object. # def copy_workflow(wf_uuid, src, dst, args): # fetch the workflow from the source instance wf = src.workflows().get(uuid=wf_uuid).execute(num_retries=args.retries) if not wf["definition"]: logger.warning("Workflow object {} has an empty or null definition, it won't do anything.".format(wf_uuid)) # copy collections and docker images if args.recursive and wf["definition"]: wf_def = yaml.safe_load(wf["definition"]) if wf_def is not None: locations = [] docker_images = {} graph = wf_def.get('$graph', None) if graph is not None: workflow_collections(graph, locations, docker_images) else: workflow_collections(wf_def, locations, docker_images) if locations: copy_collections(locations, src, dst, args) for image in docker_images: copy_docker_image(image, docker_images[image], src, dst, args) # copy the workflow itself del wf['uuid'] wf['owner_uuid'] = args.project_uuid existing = dst.workflows().list(filters=[["owner_uuid", "=", args.project_uuid], ["name", "=", wf["name"]]]).execute() if len(existing["items"]) == 0: return dst.workflows().create(body=wf).execute(num_retries=args.retries) else: return dst.workflows().update(uuid=existing["items"][0]["uuid"], body=wf).execute(num_retries=args.retries) def workflow_collections(obj, locations, docker_images): if isinstance(obj, dict): loc = obj.get('location', None) if loc is not None: if loc.startswith("keep:"): locations.append(loc[5:]) docker_image = obj.get('dockerImageId', None) or obj.get('dockerPull', None) or obj.get('acrContainerImage', None) if docker_image is not None: ds = docker_image.split(":", 1) tag = ds[1] if len(ds)==2 else 'latest' docker_images[ds[0]] = tag for x in obj: workflow_collections(obj[x], locations, docker_images) elif isinstance(obj, list): for x in obj: workflow_collections(x, locations, docker_images) # copy_collections(obj, src, dst, args) # # Recursively copies all collections referenced by 'obj' from src # to dst. obj may be a dict or a list, in which case we run # copy_collections on every value it contains. If it is a string, # search it for any substring that matches a collection hash or uuid # (this will find hidden references to collections like # "input0": "$(file 3229739b505d2b878b62aed09895a55a+142/HWI-ST1027_129_D0THKACXX.1_1.fastq)") # # Returns a copy of obj with any old collection uuids replaced by # the new ones. # def copy_collections(obj, src, dst, args): def copy_collection_fn(collection_match): """Helper function for regex substitution: copies a single collection, identified by the collection_match MatchObject, to the destination. Returns the destination collection uuid (or the portable data hash if that's what src_id is). """ src_id = collection_match.group(0) if src_id not in collections_copied: dst_col = copy_collection(src_id, src, dst, args) if src_id in [dst_col['uuid'], dst_col['portable_data_hash']]: collections_copied[src_id] = src_id else: collections_copied[src_id] = dst_col['uuid'] return collections_copied[src_id] if isinstance(obj, basestring): # Copy any collections identified in this string to dst, replacing # them with the dst uuids as necessary. obj = arvados.util.portable_data_hash_pattern.sub(copy_collection_fn, obj) obj = arvados.util.collection_uuid_pattern.sub(copy_collection_fn, obj) return obj elif isinstance(obj, dict): return type(obj)((v, copy_collections(obj[v], src, dst, args)) for v in obj) elif isinstance(obj, list): return type(obj)(copy_collections(v, src, dst, args) for v in obj) return obj def total_collection_size(manifest_text): """Return the total number of bytes in this collection (excluding duplicate blocks).""" total_bytes = 0 locators_seen = {} for line in manifest_text.splitlines(): words = line.split() for word in words[1:]: try: loc = arvados.KeepLocator(word) except ValueError: continue # this word isn't a locator, skip it if loc.md5sum not in locators_seen: locators_seen[loc.md5sum] = True total_bytes += loc.size return total_bytes def create_collection_from(c, src, dst, args): """Create a new collection record on dst, and copy Docker metadata if available.""" collection_uuid = c['uuid'] body = {} for d in ('description', 'manifest_text', 'name', 'portable_data_hash', 'properties'): body[d] = c[d] if not body["name"]: body['name'] = "copied from " + collection_uuid if args.storage_classes: body['storage_classes_desired'] = args.storage_classes body['owner_uuid'] = args.project_uuid dst_collection = dst.collections().create(body=body, ensure_unique_name=True).execute(num_retries=args.retries) # Create docker_image_repo+tag and docker_image_hash links # at the destination. for link_class in ("docker_image_repo+tag", "docker_image_hash"): docker_links = src.links().list(filters=[["head_uuid", "=", collection_uuid], ["link_class", "=", link_class]]).execute(num_retries=args.retries)['items'] for src_link in docker_links: body = {key: src_link[key] for key in ['link_class', 'name', 'properties']} body['head_uuid'] = dst_collection['uuid'] body['owner_uuid'] = args.project_uuid lk = dst.links().create(body=body).execute(num_retries=args.retries) logger.debug('created dst link {}'.format(lk)) return dst_collection # copy_collection(obj_uuid, src, dst, args) # # Copies the collection identified by obj_uuid from src to dst. # Returns the collection object created at dst. # # If args.progress is True, produce a human-friendly progress # report. # # If a collection with the desired portable_data_hash already # exists at dst, and args.force is False, copy_collection returns # the existing collection without copying any blocks. Otherwise # (if no collection exists or if args.force is True) # copy_collection copies all of the collection data blocks from src # to dst. # # For this application, it is critical to preserve the # collection's manifest hash, which is not guaranteed with the # arvados.CollectionReader and arvados.CollectionWriter classes. # Copying each block in the collection manually, followed by # the manifest block, ensures that the collection's manifest # hash will not change. # def copy_collection(obj_uuid, src, dst, args): if arvados.util.keep_locator_pattern.match(obj_uuid): # If the obj_uuid is a portable data hash, it might not be # uniquely identified with a particular collection. As a # result, it is ambiguous as to what name to use for the copy. # Apply some heuristics to pick which collection to get the # name from. srccol = src.collections().list( filters=[['portable_data_hash', '=', obj_uuid]], order="created_at asc" ).execute(num_retries=args.retries) items = srccol.get("items") if not items: logger.warning("Could not find collection with portable data hash %s", obj_uuid) return c = None if len(items) == 1: # There's only one collection with the PDH, so use that. c = items[0] if not c: # See if there is a collection that's in the same project # as the root item (usually a workflow) being copied. for i in items: if i.get("owner_uuid") == src_owner_uuid and i.get("name"): c = i break if not c: # Didn't find any collections located in the same project, so # pick the oldest collection that has a name assigned to it. for i in items: if i.get("name"): c = i break if not c: # None of the collections have names (?!), so just pick the # first one. c = items[0] # list() doesn't return manifest text (and we don't want it to, # because we don't need the same maninfest text sent to us 50 # times) so go and retrieve the collection object directly # which will include the manifest text. c = src.collections().get(uuid=c["uuid"]).execute(num_retries=args.retries) else: # Assume this is an actual collection uuid, so fetch it directly. c = src.collections().get(uuid=obj_uuid).execute(num_retries=args.retries) # If a collection with this hash already exists at the # destination, and 'force' is not true, just return that # collection. if not args.force: if 'portable_data_hash' in c: colhash = c['portable_data_hash'] else: colhash = c['uuid'] dstcol = dst.collections().list( filters=[['portable_data_hash', '=', colhash]] ).execute(num_retries=args.retries) if dstcol['items_available'] > 0: for d in dstcol['items']: if ((args.project_uuid == d['owner_uuid']) and (c.get('name') == d['name']) and (c['portable_data_hash'] == d['portable_data_hash'])): return d c['manifest_text'] = dst.collections().get( uuid=dstcol['items'][0]['uuid'] ).execute(num_retries=args.retries)['manifest_text'] return create_collection_from(c, src, dst, args) # Fetch the collection's manifest. manifest = c['manifest_text'] logger.debug("Copying collection %s with manifest: <%s>", obj_uuid, manifest) # Copy each block from src_keep to dst_keep. # Use the newly signed locators returned from dst_keep to build # a new manifest as we go. src_keep = arvados.keep.KeepClient(api_client=src, num_retries=args.retries) dst_keep = arvados.keep.KeepClient(api_client=dst, num_retries=args.retries) dst_manifest = io.StringIO() dst_locators = {} bytes_written = 0 bytes_expected = total_collection_size(manifest) if args.progress: progress_writer = ProgressWriter(human_progress) else: progress_writer = None for line in manifest.splitlines(): words = line.split() dst_manifest.write(words[0]) for word in words[1:]: try: loc = arvados.KeepLocator(word) except ValueError: # If 'word' can't be parsed as a locator, # presume it's a filename. dst_manifest.write(' ') dst_manifest.write(word) continue blockhash = loc.md5sum # copy this block if we haven't seen it before # (otherwise, just reuse the existing dst_locator) if blockhash not in dst_locators: logger.debug("Copying block %s (%s bytes)", blockhash, loc.size) if progress_writer: progress_writer.report(obj_uuid, bytes_written, bytes_expected) data = src_keep.get(word) dst_locator = dst_keep.put(data, classes=(args.storage_classes or [])) dst_locators[blockhash] = dst_locator bytes_written += loc.size dst_manifest.write(' ') dst_manifest.write(dst_locators[blockhash]) dst_manifest.write("\n") if progress_writer: progress_writer.report(obj_uuid, bytes_written, bytes_expected) progress_writer.finish() # Copy the manifest and save the collection. logger.debug('saving %s with manifest: <%s>', obj_uuid, dst_manifest.getvalue()) c['manifest_text'] = dst_manifest.getvalue() return create_collection_from(c, src, dst, args) def select_git_url(api, repo_name, retries, allow_insecure_http, allow_insecure_http_opt): r = api.repositories().list( filters=[['name', '=', repo_name]]).execute(num_retries=retries) if r['items_available'] != 1: raise Exception('cannot identify repo {}; {} repos found' .format(repo_name, r['items_available'])) https_url = [c for c in r['items'][0]["clone_urls"] if c.startswith("https:")] http_url = [c for c in r['items'][0]["clone_urls"] if c.startswith("http:")] other_url = [c for c in r['items'][0]["clone_urls"] if not c.startswith("http")] priority = https_url + other_url + http_url git_config = [] git_url = None for url in priority: if url.startswith("http"): u = urllib.parse.urlsplit(url) baseurl = urllib.parse.urlunsplit((u.scheme, u.netloc, "", "", "")) git_config = ["-c", "credential.%s/.username=none" % baseurl, "-c", "credential.%s/.helper=!cred(){ cat >/dev/null; if [ \"$1\" = get ]; then echo password=$ARVADOS_API_TOKEN; fi; };cred" % baseurl] else: git_config = [] try: logger.debug("trying %s", url) arvados.util.run_command(["git"] + git_config + ["ls-remote", url], env={"HOME": os.environ["HOME"], "ARVADOS_API_TOKEN": api.api_token, "GIT_ASKPASS": "/bin/false"}) except arvados.errors.CommandFailedError: pass else: git_url = url break if not git_url: raise Exception('Cannot access git repository, tried {}' .format(priority)) if git_url.startswith("http:"): if allow_insecure_http: logger.warning("Using insecure git url %s but will allow this because %s", git_url, allow_insecure_http_opt) else: raise Exception("Refusing to use insecure git url %s, use %s if you really want this." % (git_url, allow_insecure_http_opt)) return (git_url, git_config) def copy_docker_image(docker_image, docker_image_tag, src, dst, args): """Copy the docker image identified by docker_image and docker_image_tag from src to dst. Create appropriate docker_image_repo+tag and docker_image_hash links at dst. """ logger.debug('copying docker image {}:{}'.format(docker_image, docker_image_tag)) # Find the link identifying this docker image. docker_image_list = arvados.commands.keepdocker.list_images_in_arv( src, args.retries, docker_image, docker_image_tag) if docker_image_list: image_uuid, image_info = docker_image_list[0] logger.debug('copying collection {} {}'.format(image_uuid, image_info)) # Copy the collection it refers to. dst_image_col = copy_collection(image_uuid, src, dst, args) elif arvados.util.keep_locator_pattern.match(docker_image): dst_image_col = copy_collection(docker_image, src, dst, args) else: logger.warning('Could not find docker image {}:{}'.format(docker_image, docker_image_tag)) def copy_project(obj_uuid, src, dst, owner_uuid, args): src_project_record = src.groups().get(uuid=obj_uuid).execute(num_retries=args.retries) # Create/update the destination project existing = dst.groups().list(filters=[["owner_uuid", "=", owner_uuid], ["name", "=", src_project_record["name"]]]).execute(num_retries=args.retries) if len(existing["items"]) == 0: project_record = dst.groups().create(body={"group": {"group_class": "project", "owner_uuid": owner_uuid, "name": src_project_record["name"]}}).execute(num_retries=args.retries) else: project_record = existing["items"][0] dst.groups().update(uuid=project_record["uuid"], body={"group": { "description": src_project_record["description"]}}).execute(num_retries=args.retries) args.project_uuid = project_record["uuid"] logger.debug('Copying %s to %s', obj_uuid, project_record["uuid"]) partial_error = "" # Copy collections try: copy_collections([col["uuid"] for col in arvados.util.list_all(src.collections().list, filters=[["owner_uuid", "=", obj_uuid]])], src, dst, args) except Exception as e: partial_error += "\n" + str(e) # Copy workflows for w in arvados.util.list_all(src.workflows().list, filters=[["owner_uuid", "=", obj_uuid]]): try: copy_workflow(w["uuid"], src, dst, args) except Exception as e: partial_error += "\n" + "Error while copying %s: %s" % (w["uuid"], e) if args.recursive: for g in arvados.util.list_all(src.groups().list, filters=[["owner_uuid", "=", obj_uuid]]): try: copy_project(g["uuid"], src, dst, project_record["uuid"], args) except Exception as e: partial_error += "\n" + "Error while copying %s: %s" % (g["uuid"], e) project_record["partial_error"] = partial_error return project_record # git_rev_parse(rev, repo) # # Returns the 40-character commit hash corresponding to 'rev' in # git repository 'repo' (which must be the path of a local git # repository) # def git_rev_parse(rev, repo): gitout, giterr = arvados.util.run_command( ['git', 'rev-parse', rev], cwd=repo) return gitout.strip() # uuid_type(api, object_uuid) # # Returns the name of the class that object_uuid belongs to, based on # the second field of the uuid. This function consults the api's # schema to identify the object class. # # It returns a string such as 'Collection', 'Workflow', etc. # # Special case: if handed a Keep locator hash, return 'Collection'. # def uuid_type(api, object_uuid): if re.match(arvados.util.keep_locator_pattern, object_uuid): return 'Collection' p = object_uuid.split('-') if len(p) == 3: type_prefix = p[1] for k in api._schema.schemas: obj_class = api._schema.schemas[k].get('uuidPrefix', None) if type_prefix == obj_class: return k return None def abort(msg, code=1): logger.info("arv-copy: %s", msg) exit(code) # Code for reporting on the progress of a collection upload. # Stolen from arvados.commands.put.ArvPutCollectionWriter # TODO(twp): figure out how to refactor into a shared library # (may involve refactoring some arvados.commands.arv_copy.copy_collection # code) def machine_progress(obj_uuid, bytes_written, bytes_expected): return "{} {}: {} {} written {} total\n".format( sys.argv[0], os.getpid(), obj_uuid, bytes_written, -1 if (bytes_expected is None) else bytes_expected) def human_progress(obj_uuid, bytes_written, bytes_expected): if bytes_expected: return "\r{}: {}M / {}M {:.1%} ".format( obj_uuid, bytes_written >> 20, bytes_expected >> 20, float(bytes_written) / bytes_expected) else: return "\r{}: {} ".format(obj_uuid, bytes_written) class ProgressWriter(object): _progress_func = None outfile = sys.stderr def __init__(self, progress_func): self._progress_func = progress_func def report(self, obj_uuid, bytes_written, bytes_expected): if self._progress_func is not None: self.outfile.write( self._progress_func(obj_uuid, bytes_written, bytes_expected)) def finish(self): self.outfile.write("\n") if __name__ == '__main__': main()
39.90125
254
0.645469
7951865d0cf816b04130813a230bcec383e16f3b
1,184
py
Python
myprojectenv/lib/python3.5/site-packages/ansible/vars/unsafe_proxy.py
lancerenteria/doFlask
2d4e242469b108c6c8316ee18a540307497bfb53
[ "MIT" ]
null
null
null
myprojectenv/lib/python3.5/site-packages/ansible/vars/unsafe_proxy.py
lancerenteria/doFlask
2d4e242469b108c6c8316ee18a540307497bfb53
[ "MIT" ]
null
null
null
myprojectenv/lib/python3.5/site-packages/ansible/vars/unsafe_proxy.py
lancerenteria/doFlask
2d4e242469b108c6c8316ee18a540307497bfb53
[ "MIT" ]
null
null
null
# (c) 2017, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type # This is backwards compat. unsafe_proxy was moved to avoid circular imports. from ansible.utils.unsafe_proxy import * try: from __main__ import display except: from ansible.utils.display import Display display = Display() display.deprecated('ansible.vars.unsafe_proxy is deprecated. Use ansible.utils.unsafe_proxy instead.', version='2.8')
37
118
0.767736
795187263cbf9133359f8e12be58fbdd9b907af4
2,399
py
Python
Scripts/pilconvert.py
Zendom88/web-api
4340ccc3a4c433676aec33f3e0b6254979504a70
[ "MIT" ]
null
null
null
Scripts/pilconvert.py
Zendom88/web-api
4340ccc3a4c433676aec33f3e0b6254979504a70
[ "MIT" ]
null
null
null
Scripts/pilconvert.py
Zendom88/web-api
4340ccc3a4c433676aec33f3e0b6254979504a70
[ "MIT" ]
null
null
null
#!c:\gfapps\d'sdoc~1\duong\code\web-api\scripts\python.exe # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-30 fl Optimize output (PNG, JPEG) # 0.4 97-01-18 fl Made optimize an option (PNG, JPEG) # 0.5 98-12-30 fl Fixed -f option (from Anthony Baxter) # from __future__ import print_function import getopt import string import sys from PIL import Image def usage(): print("PIL Convert 0.5/1998-12-30 -- convert image files") print("Usage: pilconvert [option] infile outfile") print() print("Options:") print() print(" -c <format> convert to format (default is given by extension)") print() print(" -g convert to greyscale") print(" -p convert to palette image (using standard palette)") print(" -r convert to rgb") print() print(" -o optimize output (trade speed for size)") print(" -q <value> set compression quality (0-100, JPEG only)") print() print(" -f list supported file formats") sys.exit(1) if len(sys.argv) == 1: usage() try: opt, argv = getopt.getopt(sys.argv[1:], "c:dfgopq:r") except getopt.error as v: print(v) sys.exit(1) output_format = None convert = None options = {} for o, a in opt: if o == "-f": Image.init() id = sorted(Image.ID) print("Supported formats (* indicates output format):") for i in id: if i in Image.SAVE: print(i+"*", end=' ') else: print(i, end=' ') sys.exit(1) elif o == "-c": output_format = a if o == "-g": convert = "L" elif o == "-p": convert = "P" elif o == "-r": convert = "RGB" elif o == "-o": options["optimize"] = 1 elif o == "-q": options["quality"] = string.atoi(a) if len(argv) != 2: usage() try: im = Image.open(argv[0]) if convert and im.mode != convert: im.draft(convert, im.size) im = im.convert(convert) if output_format: im.save(argv[1], output_format, **options) else: im.save(argv[1], **options) except: print("cannot convert image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
23.99
77
0.554398
795187ad88d4041c428424fc7095c76671940c55
3,714
py
Python
src/ghostricon/vpn.py
ziirish/ghostricon
db1ca0deb191d72da3ac953385020f5bc77e8b6e
[ "MIT" ]
null
null
null
src/ghostricon/vpn.py
ziirish/ghostricon
db1ca0deb191d72da3ac953385020f5bc77e8b6e
[ "MIT" ]
1
2021-10-20T19:57:34.000Z
2021-10-21T20:55:24.000Z
src/ghostricon/vpn.py
ziirish/ghostricon
db1ca0deb191d72da3ac953385020f5bc77e8b6e
[ "MIT" ]
null
null
null
import os import re import typing import logging import subprocess from shlex import quote from ghostricon.commands import server_types from ghostricon.config import reload_config class Vpn: logger = logging.getLogger("VPNTOOL") reg = re.compile(r"^\|\s*\d+\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|$") def __init__(self, user: str): self.user = user self.load_config() self.connected() def load_config(self): self.config = reload_config(self.user)["Global"] def _run(self, args: typing.List[str]) -> str: self.logger.debug("running as " + f"{subprocess.check_output(['/usr/bin/whoami'])}") self.logger.debug(f"substitute as {self.user}") env = os.environ env["USER"] = self.user cmd = ["/usr/bin/cyberghostvpn"] cmd += args # cmd = [quote(x) for x in cmd] self.logger.debug(f"COMMAND: {cmd}") try: ret = subprocess.check_output(cmd, env=env).decode("utf-8").rstrip() self.logger.debug(f"RET: {ret}") return ret except subprocess.CalledProcessError: self.logger.exception("Command Failed!") def list(self, kind: str = None, *args) -> typing.List[str]: fargs = ["--country-code"] kind = kind.lower() if kind else None if kind and kind in server_types: fargs.insert(0, server_types[kind]) fargs += args ret = self._run(fargs) servers = [] for line in ret.splitlines(): match = self.reg.match(line) if match: servers.append((match.group(1), match.group(2))) return servers def status(self) -> bool: ret = self._run(["--status"]) return ret != "No VPN connections found." def disconnect(self): if not self.connected(): return False self._run(["--stop"]) return self.connected() def connect(self, kind: str = None, country: str = None, platform: str = None, force: bool = False) -> bool: def _select_from_default(kind_, country_=None): servers = self.list(kind_) default_country_name = country_ or self.config.get("default_country") for name, code in servers: if name == default_country_name: return code if self.connected(): if force: self.disconnect() else: return True self.load_config() default_server_type = self.config.get("default_type").lower() args = ["--connect"] if not kind or kind not in server_types: kind = default_server_type if kind not in server_types: kind = "traffic" args.append(server_types[kind]) if kind == "streaming": if not platform and default_server_type == kind: platform = self.config.get("default_country") args.append(platform) if not country: country = _select_from_default(kind, platform) elif not country: country = _select_from_default(kind) if country: args += ["--country-code", country] self._run(args) return self.connected() def connected(self) -> bool: self._connected = self.status() self.logger.debug(f"CONNECTED: {self._connected}") return self._connected def changed(self) -> bool: if self.status() != self._connected: self._connected = not self._connected return True return False
32.295652
81
0.556004
795189018e06e3b47116d7eefa4b2690b467f0d1
3,148
py
Python
jj/mock/_history/_history_request.py
nikitanovosibirsk/jj
ea75c932e476c0dc3f282141877a7199ee4a81a9
[ "Apache-2.0" ]
4
2020-09-08T08:14:21.000Z
2022-01-27T19:22:53.000Z
jj/mock/_history/_history_request.py
nikitanovosibirsk/jj
ea75c932e476c0dc3f282141877a7199ee4a81a9
[ "Apache-2.0" ]
19
2018-02-13T05:51:25.000Z
2022-03-27T22:48:11.000Z
jj/mock/_history/_history_request.py
nikitanovosibirsk/jj
ea75c932e476c0dc3f282141877a7199ee4a81a9
[ "Apache-2.0" ]
3
2017-11-17T13:25:23.000Z
2022-02-03T12:57:00.000Z
from typing import Any, Dict, List, Tuple from aiohttp.web_exceptions import HTTPRequestEntityTooLarge from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy from packed import packable from ...requests import Request __all__ = ("HistoryRequest",) @packable("jj.mock.HistoryRequest") class HistoryRequest: def __init__(self, *, method: str, path: str, segments: Dict[str, str], params: "MultiDictProxy[str]", headers: "CIMultiDictProxy[str]", body: bytes) -> None: self._method = method self._path = path self._segments = segments self._params = params self._headers = headers self._body = body @property def method(self) -> str: return self._method @property def path(self) -> str: return self._path @property def segments(self) -> Dict[str, str]: return self._segments @property def params(self) -> "MultiDictProxy[str]": return self._params @property def headers(self) -> "CIMultiDictProxy[str]": return self._headers @property def body(self) -> bytes: return self._body @staticmethod async def from_request(request: Request) -> "HistoryRequest": try: body = await request.read() except HTTPRequestEntityTooLarge: body = b"<binary>" await request.release() return HistoryRequest( method=request.method, path=request.path, segments=request.segments, params=request.params, headers=request.headers, body=body, ) def __packed__(self) -> Dict[str, Any]: params = [[key, val] for key, val in self._params.items()] headers = [[key, val] for key, val in self._headers.items()] return { "method": self._method, "path": self._path, "segments": self._segments, "params": params, "headers": headers, "body": self.body, } @classmethod def __unpacked__(cls, *, method: str, path: str, segments: Dict[str, str], params: List[Tuple[str, str]], headers: List[Tuple[str, str]], body: bytes, **kwargs: Any) -> "HistoryRequest": real_params = MultiDictProxy(MultiDict(params)) real_headers = CIMultiDictProxy(CIMultiDict(headers)) return HistoryRequest( method=method, path=path, segments=segments, params=real_params, headers=real_headers, body=body, ) def __repr__(self) -> str: return (f"HistoryRequest(" f"method={self._method!r}, " f"path={self._path!r}, " f"params={self._params!r}, " f"headers={self._headers!r}, " f"body={self._body!r}" f")")
28.880734
78
0.537484
7951897a65aae559cea6ec19cc9b2b2cb5516ba8
954
py
Python
test/test_lastname.py
200312/python_training
623cfd967d999849aac5d3130823fba8638bc289
[ "Apache-2.0" ]
null
null
null
test/test_lastname.py
200312/python_training
623cfd967d999849aac5d3130823fba8638bc289
[ "Apache-2.0" ]
null
null
null
test/test_lastname.py
200312/python_training
623cfd967d999849aac5d3130823fba8638bc289
[ "Apache-2.0" ]
null
null
null
import re from model.contact import Contact def test_lastname_on_home_page(app, check_ui): contact_from_home_page = app.contact.get_contact_list()[0] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.lastname == merge_lastname_like_on_home_page(contact_from_edit_page) if check_ui: assert sorted(contact_from_home_page.lastname, key=Contact.id_or_max) == sorted(merge_lastname_like_on_home_page(contact_from_edit_page), key=Contact.id_or_max) def test_lastname_on_contact_view_page(app): contact_from_view_page = app.contact.get_contact_from_view_page(0) contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_view_page.lastname == contact_from_edit_page.lastname def clear(s): return re.sub("[ -]", "", s) def merge_lastname_like_on_home_page(contact): return "\n".join(map(lambda x: clear(x), [contact.lastname]))
43.363636
168
0.800839
7951897dd6c9c5ac7f0c52e19439b1b89eed3b0e
282
py
Python
dtamg_py/build_datapackages.py
transparencia-mg/dtamg-py
6007d33a1f33f01f504f82a52ed298cc9f466f61
[ "MIT" ]
null
null
null
dtamg_py/build_datapackages.py
transparencia-mg/dtamg-py
6007d33a1f33f01f504f82a52ed298cc9f466f61
[ "MIT" ]
15
2021-12-20T15:25:23.000Z
2022-03-07T21:55:57.000Z
dtamg_py/build_datapackages.py
transparencia-mg/dtamg-py
6007d33a1f33f01f504f82a52ed298cc9f466f61
[ "MIT" ]
null
null
null
import click from dtamg_py.utils import build_datapackages @click.command(name='build-datapackages') def build_datapackages_cli(): """ Função responsável pela construção dos conjuntos derivados de todo conjunto AGE7. Constroi pasta build_datasets. """ build_datapackages()
28.2
114
0.797872
79518a6bdf57bc397abb8af7a181eb64d76c5cc2
3,292
py
Python
metrics/eval.py
AndresPMD/semantic_adaptive_margin
1e8bf2f1836498c48df030cb0a967b72b52e8460
[ "Apache-2.0" ]
12
2021-12-09T14:59:48.000Z
2021-12-20T08:34:26.000Z
metrics/eval.py
AndresPMD/semantic_adaptive_margin
1e8bf2f1836498c48df030cb0a967b72b52e8460
[ "Apache-2.0" ]
null
null
null
metrics/eval.py
AndresPMD/semantic_adaptive_margin
1e8bf2f1836498c48df030cb0a967b72b52e8460
[ "Apache-2.0" ]
null
null
null
import argparse import json import os import numpy as np import pandas as pd from metric import Metric if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--dataset_path', type=str, default='/data2fast/users/amafla/Precomp_features/data/', help='ground truth data path') parser.add_argument('--metric_path', type=str, default='./out', help='the path that has metrics and model output') parser.add_argument('--dataset', type=str, default='coco', help='which dataset to use, options are: coco, f30k') parser.add_argument('--split', type=str, default='test', help='Choose to evaluate on coco 1k test set or 5k test set. (test | testall)') parser.add_argument('--metric_name', type=str, default='spice', help='which image captioning metric to use, options are: cider, spice') parser.add_argument('--recall_type', type=str, default='recall', help='Options are recall and vse_recall') parser.add_argument('--score', default=['hard', 'soft', 'softer'], nargs="+", help='which scoring method to use, options are: hard, soft, softer') parser.add_argument('--model_name', type=str, default='CVSE_cider', help='which model to use, options are: VSEPP, SCAN, VSRN, CVSE') parser.add_argument('--threshold', type=int, default=1, help='Threshold of number of relevant samples to compute metrics, options are: 1,2,3') parser.add_argument('--recall_thresholds', default=[1, 5, 10, 20, 30], nargs="+", help='K values in Recall_at_K') parser.add_argument('--include_anns', action='store_true', help='Include human annotations to define relevant items') args = parser.parse_args() if args.metric_name == 'spice': metric = pd.read_csv(os.path.join(args.metric_path, args.dataset + '_' + args.metric_name + '.csv'), sep=',', header=None) metric = metric.to_numpy() if args.dataset == 'coco': metric = metric[:, :5000] if args.dataset == 'f30k': metric = metric[:, :1000] elif args.metric_name == 'cider': metric = np.load(os.path.join(args.metric_path, args.dataset + '_cider.npy')) if args.split == 'testall' and args.dataset == 'coco': metric = metric[:, :5000] elif args.split == 'test' and args.dataset == 'coco': metric = metric[:, :1000] filename = os.path.join(args.metric_path, 'sims_' + args.model_name + '_' + args.dataset + '_precomp.json') sims = json.load(open(filename, 'r')) if len(sims) == 1000 and args.dataset == 'coco' and args.split == 'testall': raise ValueError('You cant have coco 1k and testall option together') if len(sims) == 5000 and args.dataset == 'coco' and args.split == 'test': raise ValueError('You cant have coco 5k and test option together') M = Metric(metric, sims, recall_type=args.recall_type, score=args.score, metric_name=args.metric_name, recall_thresholds=args.recall_thresholds, threshold=args.threshold, dataset=args.dataset, include_anns=args.include_anns, model_name=args.model_name) print("\n ... LOADING DATA ...\n") scores = M.compute_metrics()
49.134328
140
0.6452
79518a6e3958d051c586fdc1109c5fe813fd5f11
154
py
Python
SquareRoot.py
kpp46/Task-3
12ba7c8558c8a60717e9053194f2419d5b3e04af
[ "MIT" ]
null
null
null
SquareRoot.py
kpp46/Task-3
12ba7c8558c8a60717e9053194f2419d5b3e04af
[ "MIT" ]
null
null
null
SquareRoot.py
kpp46/Task-3
12ba7c8558c8a60717e9053194f2419d5b3e04af
[ "MIT" ]
null
null
null
import math class SquareRoot: a = 0 result = 0 def __init__(self, a): self.a = a self.result = math.sqrt(self.a)
14
40
0.512987
79518a990ea03bb7ff644f55dd6db3661e4888b4
3,820
py
Python
tests/components/zha/test_device_action.py
pcaston/core
e74d946cef7a9d4e232ae9e0ba150d18018cfe33
[ "Apache-2.0" ]
1
2021-07-08T20:09:55.000Z
2021-07-08T20:09:55.000Z
tests/components/zha/test_device_action.py
pcaston/core
e74d946cef7a9d4e232ae9e0ba150d18018cfe33
[ "Apache-2.0" ]
47
2021-02-21T23:43:07.000Z
2022-03-31T06:07:10.000Z
tests/components/zha/test_device_action.py
OpenPeerPower/core
f673dfac9f2d0c48fa30af37b0a99df9dd6640ee
[ "Apache-2.0" ]
null
null
null
"""The test for zha device automation actions.""" from unittest.mock import patch import pytest import zigpy.profiles.zha import zigpy.zcl.clusters.general as general import zigpy.zcl.clusters.security as security import zigpy.zcl.foundation as zcl_f import openpeerpower.components.automation as automation from openpeerpower.components.device_automation import ( _async_get_device_automations as async_get_device_automations, ) from openpeerpower.components.zha import DOMAIN from openpeerpower.helpers import device_registry as dr from openpeerpower.setup import async_setup_component from tests.common import async_mock_service, mock_coro from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401 SHORT_PRESS = "remote_button_short_press" COMMAND = "command" COMMAND_SINGLE = "single" @pytest.fixture async def device_ias(opp, zigpy_device_mock, zha_device_joined_restored): """IAS device fixture.""" clusters = [general.Basic, security.IasZone, security.IasWd] zigpy_device = zigpy_device_mock( { 1: { "in_clusters": [c.cluster_id for c in clusters], "out_clusters": [general.OnOff.cluster_id], "device_type": zigpy.profiles.zha.DeviceType.ON_OFF_SWITCH, } }, ) zha_device = await zha_device_joined_restored(zigpy_device) zha_device.update_available(True) await opp.async_block_till_done() return zigpy_device, zha_device async def test_get_actions(opp, device_ias): """Test we get the expected actions from a zha device.""" ieee_address = str(device_ias[0].ieee) ha_device_registry = dr.async_get(opp) reg_device = ha_device_registry.async_get_device({(DOMAIN, ieee_address)}) actions = await async_get_device_automations(opp, "action", reg_device.id) expected_actions = [ {"domain": DOMAIN, "type": "squawk", "device_id": reg_device.id}, {"domain": DOMAIN, "type": "warn", "device_id": reg_device.id}, ] assert actions == expected_actions async def test_action(opp, device_ias): """Test for executing a zha device action.""" zigpy_device, zha_device = device_ias zigpy_device.device_automation_triggers = { (SHORT_PRESS, SHORT_PRESS): {COMMAND: COMMAND_SINGLE} } ieee_address = str(zha_device.ieee) ha_device_registry = dr.async_get(opp) reg_device = ha_device_registry.async_get_device({(DOMAIN, ieee_address)}) with patch( "zigpy.zcl.Cluster.request", return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), ): assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "device_id": reg_device.id, "domain": "zha", "platform": "device", "type": SHORT_PRESS, "subtype": SHORT_PRESS, }, "action": { "domain": DOMAIN, "device_id": reg_device.id, "type": "warn", }, } ] }, ) await opp.async_block_till_done() calls = async_mock_service(opp, DOMAIN, "warning_device_warn") channel = zha_device.channels.pools[0].client_channels["1:0x0006"] channel.zha_send_event(COMMAND_SINGLE, []) await opp.async_block_till_done() assert len(calls) == 1 assert calls[0].domain == DOMAIN assert calls[0].service == "warning_device_warn" assert calls[0].data["ieee"] == ieee_address
32.931034
85
0.627749
79518ac2498493132e29d8bbe14a9001e90e8981
42,594
py
Python
python/tvm/testing.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
1
2021-08-05T17:25:14.000Z
2021-08-05T17:25:14.000Z
python/tvm/testing.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
1
2019-08-16T20:37:41.000Z
2019-08-16T20:38:15.000Z
python/tvm/testing.py
wjj19950828/tvm
9c63f4fc318652f6fff68342da2d11b26592a3e0
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unnecessary-comprehension """ TVM testing utilities Testing Markers *************** We use pytest markers to specify the requirements of test functions. Currently there is a single distinction that matters for our testing environment: does the test require a gpu. For tests that require just a gpu or just a cpu, we have the decorator :py:func:`requires_gpu` that enables the test when a gpu is available. To avoid running tests that don't require a gpu on gpu nodes, this decorator also sets the pytest marker `gpu` so we can use select the gpu subset of tests (using `pytest -m gpu`). Unfortunately, many tests are written like this: .. python:: def test_something(): for target in all_targets(): do_something() The test uses both gpu and cpu targets, so the test needs to be run on both cpu and gpu nodes. But we still want to only run the cpu targets on the cpu testing node. The solution is to mark these tests with the gpu marker so they will be run on the gpu nodes. But we also modify all_targets (renamed to enabled_targets) so that it only returns gpu targets on gpu nodes and cpu targets on cpu nodes (using an environment variable). Instead of using the all_targets function, future tests that would like to test against a variety of targets should use the :py:func:`tvm.testing.parametrize_targets` functionality. This allows us greater control over which targets are run on which testing nodes. If in the future we want to add a new type of testing node (for example fpgas), we need to add a new marker in `tests/python/pytest.ini` and a new function in this module. Then targets using this node should be added to the `TVM_TEST_TARGETS` environment variable in the CI. """ import collections import copy import functools import logging import os import sys import time import pickle import pytest import _pytest import numpy as np import tvm import tvm.arith import tvm.tir import tvm.te import tvm._ffi from tvm.contrib import nvcc from tvm.error import TVMError def assert_allclose(actual, desired, rtol=1e-7, atol=1e-7): """Version of np.testing.assert_allclose with `atol` and `rtol` fields set in reasonable defaults. Arguments `actual` and `desired` are not interchangeable, since the function compares the `abs(actual-desired)` with `atol+rtol*abs(desired)`. Since we often allow `desired` to be close to zero, we generally want non-zero `atol`. """ actual = np.asanyarray(actual) desired = np.asanyarray(desired) np.testing.assert_allclose(actual.shape, desired.shape) np.testing.assert_allclose(actual, desired, rtol=rtol, atol=atol, verbose=True) def check_numerical_grads( function, input_values, grad_values, function_value=None, delta=1e-3, atol=1e-2, rtol=0.1 ): """A helper function that checks that numerical gradients of a function are equal to gradients computed in some different way (analytical gradients). Numerical gradients are computed using finite difference approximation. To reduce the number of function evaluations, the number of points used is gradually increased if the error value is too high (up to 5 points). Parameters ---------- function A function that takes inputs either as positional or as keyword arguments (either `function(*input_values)` or `function(**input_values)` should be correct) and returns a scalar result. Should accept numpy ndarrays. input_values : Dict[str, numpy.ndarray] or List[numpy.ndarray] A list of values or a dict assigning values to variables. Represents the point at which gradients should be computed. grad_values : Dict[str, numpy.ndarray] or List[numpy.ndarray] Gradients computed using a different method. function_value : float, optional Should be equal to `function(**input_values)`. delta : float, optional A small number used for numerical computation of partial derivatives. The default 1e-3 is a good choice for float32. atol : float, optional Absolute tolerance. Gets multiplied by `sqrt(n)` where n is the size of a gradient. rtol : float, optional Relative tolerance. """ # If input_values is a list then function accepts positional arguments # In this case transform it to a function taking kwargs of the form {"0": ..., "1": ...} if not isinstance(input_values, dict): input_len = len(input_values) input_values = {str(idx): val for idx, val in enumerate(input_values)} def _function(_input_len=input_len, _orig_function=function, **kwargs): return _orig_function(*(kwargs[str(i)] for i in range(input_len))) function = _function grad_values = {str(idx): val for idx, val in enumerate(grad_values)} if function_value is None: function_value = function(**input_values) # a helper to modify j-th element of val by a_delta def modify(val, j, a_delta): val = val.copy() val.reshape(-1)[j] = val.reshape(-1)[j] + a_delta return val # numerically compute a partial derivative with respect to j-th element of the var `name` def derivative(x_name, j, a_delta): modified_values = { n: modify(val, j, a_delta) if n == x_name else val for n, val in input_values.items() } return (function(**modified_values) - function_value) / a_delta def compare_derivative(j, n_der, grad): der = grad.reshape(-1)[j] return np.abs(n_der - der) < atol + rtol * np.abs(n_der) for x_name, grad in grad_values.items(): if grad.shape != input_values[x_name].shape: raise AssertionError( "Gradient wrt '{}' has unexpected shape {}, expected {} ".format( x_name, grad.shape, input_values[x_name].shape ) ) ngrad = np.zeros_like(grad) wrong_positions = [] # compute partial derivatives for each position in this variable for j in range(np.prod(grad.shape)): # forward difference approximation nder = derivative(x_name, j, delta) # if the derivative is not equal to the analytical one, try to use more # precise and expensive methods if not compare_derivative(j, nder, grad): # central difference approximation nder = (derivative(x_name, j, -delta) + nder) / 2 if not compare_derivative(j, nder, grad): # central difference approximation using h = delta/2 cnder2 = ( derivative(x_name, j, delta / 2) + derivative(x_name, j, -delta / 2) ) / 2 # five-point derivative nder = (4 * cnder2 - nder) / 3 # if the derivatives still don't match, add this position to the # list of wrong positions if not compare_derivative(j, nder, grad): wrong_positions.append(np.unravel_index(j, grad.shape)) ngrad.reshape(-1)[j] = nder wrong_percentage = int(100 * len(wrong_positions) / np.prod(grad.shape)) dist = np.sqrt(np.sum((ngrad - grad) ** 2)) grad_norm = np.sqrt(np.sum(ngrad ** 2)) if not (np.isfinite(dist) and np.isfinite(grad_norm)): raise ValueError( "NaN or infinity detected during numerical gradient checking wrt '{}'\n" "analytical grad = {}\n numerical grad = {}\n".format(x_name, grad, ngrad) ) # we multiply atol by this number to make it more universal for different sizes sqrt_n = np.sqrt(float(np.prod(grad.shape))) if dist > atol * sqrt_n + rtol * grad_norm: raise AssertionError( "Analytical and numerical grads wrt '{}' differ too much\n" "analytical grad = {}\n numerical grad = {}\n" "{}% of elements differ, first 10 of wrong positions: {}\n" "distance > atol*sqrt(n) + rtol*grad_norm\n" "distance {} > {}*{} + {}*{}".format( x_name, grad, ngrad, wrong_percentage, wrong_positions[:10], dist, atol, sqrt_n, rtol, grad_norm, ) ) max_diff = np.max(np.abs(ngrad - grad)) avg_diff = np.mean(np.abs(ngrad - grad)) logging.info( "Numerical grad test wrt '%s' of shape %s passes, " "dist = %f, max_diff = %f, avg_diff = %f", x_name, grad.shape, dist, max_diff, avg_diff, ) def assert_prim_expr_equal(lhs, rhs): """Assert lhs and rhs equals to each iother. Parameters ---------- lhs : tvm.tir.PrimExpr The left operand. rhs : tvm.tir.PrimExpr The left operand. """ ana = tvm.arith.Analyzer() res = ana.simplify(lhs - rhs) equal = isinstance(res, tvm.tir.IntImm) and res.value == 0 if not equal: raise ValueError("{} and {} are not equal".format(lhs, rhs)) def check_bool_expr_is_true(bool_expr, vranges, cond=None): """Check that bool_expr holds given the condition cond for every value of free variables from vranges. for example, 2x > 4y solves to x > 2y given x in (0, 10) and y in (0, 10) here bool_expr is x > 2y, vranges is {x: (0, 10), y: (0, 10)}, cond is 2x > 4y We creates iterations to check, for x in range(10): for y in range(10): assert !(2x > 4y) || (x > 2y) Parameters ---------- bool_expr : tvm.ir.PrimExpr Boolean expression to check vranges: Dict[tvm.tir.expr.Var, tvm.ir.Range] Free variables and their ranges cond: tvm.ir.PrimExpr extra conditions needs to be satisfied. """ if cond is not None: bool_expr = tvm.te.any(tvm.tir.Not(cond), bool_expr) def _run_expr(expr, vranges): """Evaluate expr for every value of free variables given by vranges and return the tensor of results. """ def _compute_body(*us): vmap = {v: u + r.min for (v, r), u in zip(vranges.items(), us)} return tvm.tir.stmt_functor.substitute(expr, vmap) A = tvm.te.compute([r.extent.value for v, r in vranges.items()], _compute_body) args = [tvm.nd.empty(A.shape, A.dtype)] sch = tvm.te.create_schedule(A.op) mod = tvm.build(sch, [A]) mod(*args) return args[0].numpy() res = _run_expr(bool_expr, vranges) if not np.all(res): indices = list(np.argwhere(res == 0)[0]) counterex = [(str(v), i + r.min) for (v, r), i in zip(vranges.items(), indices)] counterex = sorted(counterex, key=lambda x: x[0]) counterex = ", ".join([v + " = " + str(i) for v, i in counterex]) ana = tvm.arith.Analyzer() raise AssertionError( "Expression {}\nis not true on {}\n" "Counterexample: {}".format(ana.simplify(bool_expr), vranges, counterex) ) def check_int_constraints_trans_consistency(constraints_trans, vranges=None): """Check IntConstraintsTransform is a bijective transformation. Parameters ---------- constraints_trans : arith.IntConstraintsTransform Integer constraints transformation vranges: Dict[tvm.tir.Var, tvm.ir.Range] Free variables and their ranges """ if vranges is None: vranges = {} def _check_forward(constraints1, constraints2, varmap, backvarmap): ana = tvm.arith.Analyzer() all_vranges = vranges.copy() all_vranges.update({v: r for v, r in constraints1.ranges.items()}) # Check that the transformation is injective cond_on_vars = tvm.tir.const(1, "bool") for v in constraints1.variables: if v in varmap: # variable mapping is consistent v_back = ana.simplify(tvm.tir.stmt_functor.substitute(varmap[v], backvarmap)) cond_on_vars = tvm.te.all(cond_on_vars, v == v_back) # Also we have to check that the new relations are true when old relations are true cond_subst = tvm.tir.stmt_functor.substitute( tvm.te.all(tvm.tir.const(1, "bool"), *constraints2.relations), backvarmap ) # We have to include relations from vranges too for v in constraints2.variables: if v in constraints2.ranges: r = constraints2.ranges[v] range_cond = tvm.te.all(v >= r.min, v < r.min + r.extent) range_cond = tvm.tir.stmt_functor.substitute(range_cond, backvarmap) cond_subst = tvm.te.all(cond_subst, range_cond) cond_subst = ana.simplify(cond_subst) check_bool_expr_is_true( tvm.te.all(cond_subst, cond_on_vars), all_vranges, cond=tvm.te.all(tvm.tir.const(1, "bool"), *constraints1.relations), ) _check_forward( constraints_trans.src, constraints_trans.dst, constraints_trans.src_to_dst, constraints_trans.dst_to_src, ) _check_forward( constraints_trans.dst, constraints_trans.src, constraints_trans.dst_to_src, constraints_trans.src_to_dst, ) def _get_targets(target_str=None): if target_str is None: target_str = os.environ.get("TVM_TEST_TARGETS", "") if len(target_str) == 0: target_str = DEFAULT_TEST_TARGETS target_names = set(t.strip() for t in target_str.split(";") if t.strip()) targets = [] for target in target_names: target_kind = target.split()[0] is_enabled = tvm.runtime.enabled(target_kind) is_runnable = is_enabled and tvm.device(target_kind).exist targets.append( { "target": target, "target_kind": target_kind, "is_enabled": is_enabled, "is_runnable": is_runnable, } ) if all(not t["is_runnable"] for t in targets): if tvm.runtime.enabled("llvm"): logging.warning( "None of the following targets are supported by this build of TVM: %s." " Try setting TVM_TEST_TARGETS to a supported target. Defaulting to llvm.", target_str, ) return _get_targets("llvm") raise TVMError( "None of the following targets are supported by this build of TVM: %s." " Try setting TVM_TEST_TARGETS to a supported target." " Cannot default to llvm, as it is not enabled." % target_str ) return targets DEFAULT_TEST_TARGETS = ( "llvm;cuda;opencl;metal;rocm;vulkan -from_device=0;nvptx;" "llvm -device=arm_cpu;opencl -device=mali,aocl_sw_emu" ) def device_enabled(target): """Check if a target should be used when testing. It is recommended that you use :py:func:`tvm.testing.parametrize_targets` instead of manually checking if a target is enabled. This allows the user to control which devices they are testing against. In tests, this should be used to check if a device should be used when said device is an optional part of the test. Parameters ---------- target : str Target string to check against Returns ------- bool Whether or not the device associated with this target is enabled. Example ------- >>> @tvm.testing.uses_gpu >>> def test_mytest(): >>> for target in ["cuda", "llvm"]: >>> if device_enabled(target): >>> test_body... Here, `test_body` will only be reached by with `target="cuda"` on gpu test nodes and `target="llvm"` on cpu test nodes. """ assert isinstance(target, str), "device_enabled requires a target as a string" # only check if device name is found, sometime there are extra flags target_kind = target.split(" ")[0] return any(target_kind == t["target_kind"] for t in _get_targets() if t["is_runnable"]) def enabled_targets(): """Get all enabled targets with associated devices. In most cases, you should use :py:func:`tvm.testing.parametrize_targets` instead of this function. In this context, enabled means that TVM was built with support for this target, the target name appears in the TVM_TEST_TARGETS environment variable, and a suitable device for running this target exists. If TVM_TEST_TARGETS is not set, it defaults to variable DEFAULT_TEST_TARGETS in this module. If you use this function in a test, you **must** decorate the test with :py:func:`tvm.testing.uses_gpu` (otherwise it will never be run on the gpu). Returns ------- targets: list A list of pairs of all enabled devices and the associated context """ return [(t["target"], tvm.device(t["target"])) for t in _get_targets() if t["is_runnable"]] def _compose(args, decs): """Helper to apply multiple markers""" if len(args) > 0: f = args[0] for d in reversed(decs): f = d(f) return f return decs def uses_gpu(*args): """Mark to differentiate tests that use the GPU in some capacity. These tests will be run on CPU-only test nodes and on test nodes with GPUs. To mark a test that must have a GPU present to run, use :py:func:`tvm.testing.requires_gpu`. Parameters ---------- f : function Function to mark """ _uses_gpu = [pytest.mark.gpu] return _compose(args, _uses_gpu) def requires_gpu(*args): """Mark a test as requiring a GPU to run. Tests with this mark will not be run unless a gpu is present. Parameters ---------- f : function Function to mark """ _requires_gpu = [ pytest.mark.skipif( not tvm.cuda().exist and not tvm.rocm().exist and not tvm.opencl().exist and not tvm.metal().exist and not tvm.vulkan().exist, reason="No GPU present", ), *uses_gpu(), ] return _compose(args, _requires_gpu) def requires_cuda(*args): """Mark a test as requiring the CUDA runtime. This also marks the test as requiring a cuda gpu. Parameters ---------- f : function Function to mark """ _requires_cuda = [ pytest.mark.cuda, pytest.mark.skipif(not device_enabled("cuda"), reason="CUDA support not enabled"), *requires_gpu(), ] return _compose(args, _requires_cuda) def requires_nvptx(*args): """Mark a test as requiring the NVPTX compilation on the CUDA runtime This also marks the test as requiring a cuda gpu, and requiring LLVM support. Parameters ---------- f : function Function to mark """ _requires_nvptx = [ pytest.mark.skipif(not device_enabled("nvptx"), reason="NVPTX support not enabled"), *requires_llvm(), *requires_gpu(), ] return _compose(args, _requires_nvptx) def requires_cudagraph(*args): """Mark a test as requiring the CUDA Graph Feature This also marks the test as requiring cuda Parameters ---------- f : function Function to mark """ _requires_cudagraph = [ pytest.mark.skipif( not nvcc.have_cudagraph(), reason="CUDA Graph is not supported in this environment" ), *requires_cuda(), ] return _compose(args, _requires_cudagraph) def requires_opencl(*args): """Mark a test as requiring the OpenCL runtime. This also marks the test as requiring a gpu. Parameters ---------- f : function Function to mark """ _requires_opencl = [ pytest.mark.opencl, pytest.mark.skipif(not device_enabled("opencl"), reason="OpenCL support not enabled"), *requires_gpu(), ] return _compose(args, _requires_opencl) def requires_rocm(*args): """Mark a test as requiring the rocm runtime. This also marks the test as requiring a gpu. Parameters ---------- f : function Function to mark """ _requires_rocm = [ pytest.mark.rocm, pytest.mark.skipif(not device_enabled("rocm"), reason="rocm support not enabled"), *requires_gpu(), ] return _compose(args, _requires_rocm) def requires_metal(*args): """Mark a test as requiring the metal runtime. This also marks the test as requiring a gpu. Parameters ---------- f : function Function to mark """ _requires_metal = [ pytest.mark.metal, pytest.mark.skipif(not device_enabled("metal"), reason="metal support not enabled"), *requires_gpu(), ] return _compose(args, _requires_metal) def requires_vulkan(*args): """Mark a test as requiring the vulkan runtime. This also marks the test as requiring a gpu. Parameters ---------- f : function Function to mark """ _requires_vulkan = [ pytest.mark.vulkan, pytest.mark.skipif(not device_enabled("vulkan"), reason="vulkan support not enabled"), *requires_gpu(), ] return _compose(args, _requires_vulkan) def requires_tensorcore(*args): """Mark a test as requiring a tensorcore to run. Tests with this mark will not be run unless a tensorcore is present. Parameters ---------- f : function Function to mark """ _requires_tensorcore = [ pytest.mark.tensorcore, pytest.mark.skipif( not tvm.cuda().exist or not nvcc.have_tensorcore(tvm.cuda(0).compute_version), reason="No tensorcore present", ), *requires_gpu(), ] return _compose(args, _requires_tensorcore) def requires_llvm(*args): """Mark a test as requiring llvm to run. Parameters ---------- f : function Function to mark """ _requires_llvm = [ pytest.mark.llvm, pytest.mark.skipif(not device_enabled("llvm"), reason="LLVM support not enabled"), ] return _compose(args, _requires_llvm) def requires_micro(*args): """Mark a test as requiring microTVM to run. Parameters ---------- f : function Function to mark """ _requires_micro = [ pytest.mark.skipif( tvm.support.libinfo().get("USE_MICRO", "OFF") != "ON", reason="MicroTVM support not enabled. Set USE_MICRO=ON in config.cmake to enable.", ) ] return _compose(args, _requires_micro) def requires_rpc(*args): """Mark a test as requiring rpc to run. Parameters ---------- f : function Function to mark """ _requires_rpc = [ pytest.mark.skipif( tvm.support.libinfo().get("USE_RPC", "OFF") != "ON", reason="RPC support not enabled. Set USE_RPC=ON in config.cmake to enable.", ) ] return _compose(args, _requires_rpc) def _target_to_requirement(target): # mapping from target to decorator if target.startswith("cuda"): return requires_cuda() if target.startswith("rocm"): return requires_rocm() if target.startswith("vulkan"): return requires_vulkan() if target.startswith("nvptx"): return requires_nvptx() if target.startswith("metal"): return requires_metal() if target.startswith("opencl"): return requires_opencl() if target.startswith("llvm"): return requires_llvm() return [] def _pytest_target_params(targets, excluded_targets=None, xfail_targets=None): # Include unrunnable targets here. They get skipped by the # pytest.mark.skipif in _target_to_requirement(), showing up as # skipped tests instead of being hidden entirely. if targets is None: if excluded_targets is None: excluded_targets = set() if xfail_targets is None: xfail_targets = set() target_marks = [] for t in _get_targets(): # Excluded targets aren't included in the params at all. if t["target_kind"] not in excluded_targets: # Known failing targets are included, but are marked # as expected to fail. extra_marks = [] if t["target_kind"] in xfail_targets: extra_marks.append( pytest.mark.xfail( reason='Known failing test for target "{}"'.format(t["target_kind"]) ) ) target_marks.append((t["target"], extra_marks)) else: target_marks = [(target, []) for target in targets] return [ pytest.param(target, marks=_target_to_requirement(target) + extra_marks) for target, extra_marks in target_marks ] def _auto_parametrize_target(metafunc): """Automatically applies parametrize_targets Used if a test function uses the "target" fixture, but isn't already marked with @tvm.testing.parametrize_targets. Intended for use in the pytest_generate_tests() handler of a conftest.py file. """ if "target" in metafunc.fixturenames: parametrized_args = [ arg.strip() for mark in metafunc.definition.iter_markers("parametrize") for arg in mark.args[0].split(",") ] if "target" not in parametrized_args: # Check if the function is marked with either excluded or # known failing targets. excluded_targets = getattr(metafunc.function, "tvm_excluded_targets", []) xfail_targets = getattr(metafunc.function, "tvm_known_failing_targets", []) metafunc.parametrize( "target", _pytest_target_params(None, excluded_targets, xfail_targets), scope="session", ) def parametrize_targets(*args): """Parametrize a test over a specific set of targets. Use this decorator when you want your test to be run over a specific set of targets and devices. It is intended for use where a test is applicable only to a specific target, and is inapplicable to any others (e.g. verifying target-specific assembly code matches known assembly code). In most circumstances, :py:func:`tvm.testing.exclude_targets` or :py:func:`tvm.testing.known_failing_targets` should be used instead. If used as a decorator without arguments, the test will be parametrized over all targets in :py:func:`tvm.testing.enabled_targets`. This behavior is automatically enabled for any target that accepts arguments of ``target`` or ``dev``, so the explicit use of the bare decorator is no longer needed, and is maintained for backwards compatibility. Parameters ---------- f : function Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:, where `xxxxxxxxx` is any name. targets : list[str], optional Set of targets to run against. If not supplied, :py:func:`tvm.testing.enabled_targets` will be used. Example ------- >>> @tvm.testing.parametrize_targets("llvm", "cuda") >>> def test_mytest(target, dev): >>> ... # do something """ def wrap(targets): def func(f): return pytest.mark.parametrize( "target", _pytest_target_params(targets), scope="session" )(f) return func if len(args) == 1 and callable(args[0]): return wrap(None)(args[0]) return wrap(args) def exclude_targets(*args): """Exclude a test from running on a particular target. Use this decorator when you want your test to be run over a variety of targets and devices (including cpu and gpu devices), but want to exclude some particular target or targets. For example, a test may wish to be run against all targets in tvm.testing.enabled_targets(), except for a particular target that does not support the capabilities. Applies pytest.mark.skipif to the targets given. Parameters ---------- f : function Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:, where `xxxxxxxxx` is any name. targets : list[str] Set of targets to exclude. Example ------- >>> @tvm.testing.exclude_targets("cuda") >>> def test_mytest(target, dev): >>> ... # do something Or >>> @tvm.testing.exclude_targets("llvm", "cuda") >>> def test_mytest(target, dev): >>> ... # do something """ def wraps(func): func.tvm_excluded_targets = args return func return wraps def known_failing_targets(*args): """Skip a test that is known to fail on a particular target. Use this decorator when you want your test to be run over a variety of targets and devices (including cpu and gpu devices), but know that it fails for some targets. For example, a newly implemented runtime may not support all features being tested, and should be excluded. Applies pytest.mark.xfail to the targets given. Parameters ---------- f : function Function to parametrize. Must be of the form `def test_xxxxxxxxx(target, dev)`:, where `xxxxxxxxx` is any name. targets : list[str] Set of targets to skip. Example ------- >>> @tvm.testing.known_failing_targets("cuda") >>> def test_mytest(target, dev): >>> ... # do something Or >>> @tvm.testing.known_failing_targets("llvm", "cuda") >>> def test_mytest(target, dev): >>> ... # do something """ def wraps(func): func.tvm_known_failing_targets = args return func return wraps def parameter(*values, ids=None): """Convenience function to define pytest parametrized fixtures. Declaring a variable using ``tvm.testing.parameter`` will define a parametrized pytest fixture that can be used by test functions. This is intended for cases that have no setup cost, such as strings, integers, tuples, etc. For cases that have a significant setup cost, please use :py:func:`tvm.testing.fixture` instead. If a test function accepts multiple parameters defined using ``tvm.testing.parameter``, then the test will be run using every combination of those parameters. The parameter definition applies to all tests in a module. If a specific test should have different values for the parameter, that test should be marked with ``@pytest.mark.parametrize``. Parameters ---------- values A list of parameter values. A unit test that accepts this parameter as an argument will be run once for each parameter given. ids : List[str], optional A list of names for the parameters. If None, pytest will generate a name from the value. These generated names may not be readable/useful for composite types such as tuples. Returns ------- function A function output from pytest.fixture. Example ------- >>> size = tvm.testing.parameter(1, 10, 100) >>> def test_using_size(size): >>> ... # Test code here Or >>> shape = tvm.testing.parameter((5,10), (512,1024), ids=['small','large']) >>> def test_using_size(shape): >>> ... # Test code here """ # Optional cls parameter in case a parameter is defined inside a # class scope. @pytest.fixture(params=values, ids=ids) def as_fixture(*_cls, request): return request.param return as_fixture _parametrize_group = 0 def parameters(*value_sets): """Convenience function to define pytest parametrized fixtures. Declaring a variable using tvm.testing.parameters will define a parametrized pytest fixture that can be used by test functions. Like :py:func:`tvm.testing.parameter`, this is intended for cases that have no setup cost, such as strings, integers, tuples, etc. For cases that have a significant setup cost, please use :py:func:`tvm.testing.fixture` instead. Unlike :py:func:`tvm.testing.parameter`, if a test function accepts multiple parameters defined using a single call to ``tvm.testing.parameters``, then the test will only be run once for each set of parameters, not for all combinations of parameters. These parameter definitions apply to all tests in a module. If a specific test should have different values for some parameters, that test should be marked with ``@pytest.mark.parametrize``. Parameters ---------- values : List[tuple] A list of parameter value sets. Each set of values represents a single combination of values to be tested. A unit test that accepts parameters defined will be run once for every set of parameters in the list. Returns ------- List[function] Function outputs from pytest.fixture. These should be unpacked into individual named parameters. Example ------- >>> size, dtype = tvm.testing.parameters( (16,'float32'), (512,'float16') ) >>> def test_feature_x(size, dtype): >>> # Test code here >>> assert( (size,dtype) in [(16,'float32'), (512,'float16')]) """ global _parametrize_group parametrize_group = _parametrize_group _parametrize_group += 1 outputs = [] for param_values in zip(*value_sets): # Optional cls parameter in case a parameter is defined inside a # class scope. def fixture_func(*_cls, request): return request.param fixture_func.parametrize_group = parametrize_group fixture_func.parametrize_values = param_values outputs.append(pytest.fixture(fixture_func)) return outputs def _parametrize_correlated_parameters(metafunc): parametrize_needed = collections.defaultdict(list) for name, fixturedefs in metafunc.definition._fixtureinfo.name2fixturedefs.items(): fixturedef = fixturedefs[-1] if hasattr(fixturedef.func, "parametrize_group") and hasattr( fixturedef.func, "parametrize_values" ): group = fixturedef.func.parametrize_group values = fixturedef.func.parametrize_values parametrize_needed[group].append((name, values)) for parametrize_group in parametrize_needed.values(): if len(parametrize_group) == 1: name, values = parametrize_group[0] metafunc.parametrize(name, values, indirect=True) else: names = ",".join(name for name, values in parametrize_group) value_sets = zip(*[values for name, values in parametrize_group]) metafunc.parametrize(names, value_sets, indirect=True) def fixture(func=None, *, cache_return_value=False): """Convenience function to define pytest fixtures. This should be used as a decorator to mark functions that set up state before a function. The return value of that fixture function is then accessible by test functions as that accept it as a parameter. Fixture functions can accept parameters defined with :py:func:`tvm.testing.parameter`. By default, the setup will be performed once for each unit test that uses a fixture, to ensure that unit tests are independent. If the setup is expensive to perform, then the cache_return_value=True argument can be passed to cache the setup. The fixture function will be run only once (or once per parameter, if used with tvm.testing.parameter), and the same return value will be passed to all tests that use it. If the environment variable TVM_TEST_DISABLE_CACHE is set to a non-zero value, it will disable this feature and no caching will be performed. Example ------- >>> @tvm.testing.fixture >>> def cheap_setup(): >>> return 5 # Setup code here. >>> >>> def test_feature_x(target, dev, cheap_setup) >>> assert(cheap_setup == 5) # Run test here Or >>> size = tvm.testing.parameter(1, 10, 100) >>> >>> @tvm.testing.fixture >>> def cheap_setup(size): >>> return 5*size # Setup code here, based on size. >>> >>> def test_feature_x(cheap_setup): >>> assert(cheap_setup in [5, 50, 500]) Or >>> @tvm.testing.fixture(cache_return_value=True) >>> def expensive_setup(): >>> time.sleep(10) # Setup code here >>> return 5 >>> >>> def test_feature_x(target, dev, expensive_setup): >>> assert(expensive_setup == 5) """ force_disable_cache = bool(int(os.environ.get("TVM_TEST_DISABLE_CACHE", "0"))) cache_return_value = cache_return_value and not force_disable_cache # Deliberately at function scope, so that caching can track how # many times the fixture has been used. If used, the cache gets # cleared after the fixture is no longer needed. scope = "function" def wraps(func): if cache_return_value: func = _fixture_cache(func) func = pytest.fixture(func, scope=scope) return func if func is None: return wraps return wraps(func) def _fixture_cache(func): cache = {} # Can't use += on a bound method's property. Therefore, this is a # list rather than a variable so that it can be accessed from the # pytest_collection_modifyitems(). num_uses_remaining = [0] # Using functools.lru_cache would require the function arguments # to be hashable, which wouldn't allow caching fixtures that # depend on numpy arrays. For example, a fixture that takes a # numpy array as input, then calculates uses a slow method to # compute a known correct output for that input. Therefore, # including a fallback for serializable types. def get_cache_key(*args, **kwargs): try: hash((args, kwargs)) return (args, kwargs) except TypeError as e: pass try: return pickle.dumps((args, kwargs)) except TypeError as e: raise TypeError( "TVM caching of fixtures requires arguments to the fixture " "to be either hashable or serializable" ) from e @functools.wraps(func) def wrapper(*args, **kwargs): try: cache_key = get_cache_key(*args, **kwargs) try: cached_value = cache[cache_key] except KeyError: cached_value = cache[cache_key] = func(*args, **kwargs) try: yield copy.deepcopy(cached_value) except TypeError as e: rfc_url = ( "https://github.com/apache/tvm-rfcs/blob/main/rfcs/" "0007-parametrized-unit-tests.md#unresolved-questions" ) message = ( "TVM caching of fixtures can only be used on serializable data types, not {}.\n" "Please see {} for details/discussion." ).format(type(cached_value), rfc_url) raise TypeError(message) from e finally: # Clear the cache once all tests that use a particular fixture # have completed. num_uses_remaining[0] -= 1 if not num_uses_remaining[0]: cache.clear() # Set in the pytest_collection_modifyitems() wrapper.num_uses_remaining = num_uses_remaining return wrapper def _count_num_fixture_uses(items): # Helper function, counts the number of tests that use each cached # fixture. Should be called from pytest_collection_modifyitems(). for item in items: is_skipped = item.get_closest_marker("skip") or any( mark.args[0] for mark in item.iter_markers("skipif") ) if is_skipped: continue for fixturedefs in item._fixtureinfo.name2fixturedefs.values(): # Only increment the active fixturedef, in a name has been overridden. fixturedef = fixturedefs[-1] if hasattr(fixturedef.func, "num_uses_remaining"): fixturedef.func.num_uses_remaining[0] += 1 def _remove_global_fixture_definitions(items): # Helper function, removes fixture definitions from the global # variables of the modules they were defined in. This is intended # to improve readability of error messages by giving a NameError # if a test function accesses a pytest fixture but doesn't include # it as an argument. Should be called from # pytest_collection_modifyitems(). modules = set(item.module for item in items) for module in modules: for name in dir(module): obj = getattr(module, name) if hasattr(obj, "_pytestfixturefunction") and isinstance( obj._pytestfixturefunction, _pytest.fixtures.FixtureFunctionMarker ): delattr(module, name) def identity_after(x, sleep): """Testing function to return identity after sleep Parameters ---------- x : int The input value. sleep : float The amount of time to sleep Returns ------- x : object The original value """ if sleep: time.sleep(sleep) return x def terminate_self(): """Testing function to terminate the process.""" sys.exit(-1) tvm._ffi._init_api("testing", __name__)
32.993029
100
0.63462
79518b20c38cdf26e5a5219aedf012419c1fff47
671
py
Python
NVIDIA/benchmarks/transformer/implementations/pytorch/data_preparation/fairseq/data/__init__.py
chuanli11/training_results_v0.6
eade2d815e125e1d9af8439fc5d0bd8721777fa3
[ "Apache-2.0" ]
null
null
null
NVIDIA/benchmarks/transformer/implementations/pytorch/data_preparation/fairseq/data/__init__.py
chuanli11/training_results_v0.6
eade2d815e125e1d9af8439fc5d0bd8721777fa3
[ "Apache-2.0" ]
null
null
null
NVIDIA/benchmarks/transformer/implementations/pytorch/data_preparation/fairseq/data/__init__.py
chuanli11/training_results_v0.6
eade2d815e125e1d9af8439fc5d0bd8721777fa3
[ "Apache-2.0" ]
1
2020-02-11T23:24:05.000Z
2020-02-11T23:24:05.000Z
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .dictionary import Dictionary from .fairseq_dataset import FairseqDataset from .indexed_dataset import IndexedDataset, IndexedInMemoryDataset, IndexedRawTextDataset # noqa: F401 from .language_pair_dataset import LanguagePairDataset from .monolingual_dataset import MonolingualDataset from .token_block_dataset import TokenBlockDataset from .data_utils import EpochBatchIterator
44.733333
104
0.831595
79518cf794d0b3f4046bd49d330ed5cbced1aec1
2,449
py
Python
workflows/cp-leaveout/py/tests/test_run_chained.py
andrew-weisman/Supervisor
9110f85c85dcc2593de68db96dbd0f433a476507
[ "MIT" ]
10
2017-03-14T14:36:19.000Z
2021-01-21T00:39:36.000Z
workflows/cp-leaveout/py/tests/test_run_chained.py
andrew-weisman/Supervisor
9110f85c85dcc2593de68db96dbd0f433a476507
[ "MIT" ]
58
2017-03-03T21:07:53.000Z
2021-07-19T18:51:03.000Z
workflows/cp-leaveout/py/tests/test_run_chained.py
andrew-weisman/Supervisor
9110f85c85dcc2593de68db96dbd0f433a476507
[ "MIT" ]
21
2017-03-08T16:07:47.000Z
2020-11-24T04:23:00.000Z
# Run with python -m unittest tests.test_run_chained from parent directory import unittest import os import run_chained class RunChainedTests(unittest.TestCase): def test_root_nodes(self): root_node = '1' first_stage = 1 n_nodes = 4 root_nodes = run_chained.compute_parent_nodes(root_node, first_stage, n_nodes) self.assertEqual(['1'], root_nodes) first_stage = 3 n_nodes = 4 root_nodes = run_chained.compute_parent_nodes(root_node, first_stage, n_nodes) self.assertEqual(16, len(root_nodes)) for a in range(1, 5): for b in range(1, 5): self.assertTrue('1.{}.{}'.format(a, b) in root_nodes) def read_lines(self, fname): with open(fname) as f_in: lines = f_in.readlines() return [x.strip() for x in lines] def test_upfs(self): if os.path.exists('./tests/test_out/test_upf_s1_upf.txt'): os.remove('./tests/test_out/test_upf_s1_upf.txt') args = {'upf_directory' : './tests/test_out', 'first_stage' : 1, 'stages' : 1} cfg = run_chained.Config(args) root_nodes = run_chained.compute_parent_nodes(1, 1, 4) run_chained.generate_upfs('test_upf', cfg, root_nodes, 4) vals = self.read_lines('./tests/test_out/test_upf_s1_upf.txt') self.assertEqual(['1.1', '1.2', '1.3', '1.4'], vals) if os.path.exists('./tests/test_out/test_upf_s2_upf.txt'): os.remove('./tests/test_out/test_upf_s2_upf.txt') os.remove('./tests/test_out/test_upf_s3_upf.txt') args = {'upf_directory' : './tests/test_out', 'first_stage' : 2, 'stages' : 2} cfg = run_chained.Config(args) root_nodes = run_chained.compute_parent_nodes(1, 2, 4) upfs, runs_per_stage = run_chained.generate_upfs('test_upf', cfg, root_nodes, 4) vals = self.read_lines(upfs[0]) self.assertEqual(16, len(vals)) self.assertEqual(16, runs_per_stage[0]) for a in range(1, 5): for b in range(1, 5): self.assertTrue('1.{}.{}'.format(a, b) in vals) vals = self.read_lines(upfs[1]) self.assertEqual(64, len(vals)) self.assertEqual(64, runs_per_stage[1]) for a in range(1, 5): for b in range(1, 5): for c in range(1, 5): self.assertTrue('1.{}.{}.{}'.format(a, b, c) in vals)
37.106061
88
0.599837
79518d9033de721a481eecda4a3cb563fc64f378
14,603
py
Python
FileTools.py
hiroog/FileListLib
1e543adc810c61a7a18749cb7117d6ca1ea22597
[ "MIT" ]
null
null
null
FileTools.py
hiroog/FileListLib
1e543adc810c61a7a18749cb7117d6ca1ea22597
[ "MIT" ]
null
null
null
FileTools.py
hiroog/FileListLib
1e543adc810c61a7a18749cb7117d6ca1ea22597
[ "MIT" ]
null
null
null
# 2018/01/14 Hiroyuki Ogasawara # vim:ts=4 sw=4 et: import os, stat import sys import re import time import shutil sys.path.append( os.path.dirname( sys.argv[0] ) ) import FileListLib class LogOutput: def __init__( self ): self.Verbose= False self.LogFile= None def open_log( self, file_name ): self.LogFile= open( file_name, 'w' ) def p( self, *args ): print( *args ) if self.LogFile: for arg in args: self.LogFile.write( str(arg) ) self.LogFile.write( ' ' ) self.LogFile.write( '\n' ) def v( self, *args ): if self.Verbose: self.p( *args ) def wb( self, arg ): sys.stdout.flush() sys.stdout.buffer.write( arg ) if self.LogFile: self.LogFile.flush() self.LogFile.buffer.write( arg ) Log= LogOutput() #------------------------------------------------------------------------------ class UTF8Tools2: def __init__( self ): pass def convert( self, file_name, output_name, en_src, en_dest ): with open( file_name, 'r', encoding=en_src ) as fi: with open( output_name, 'w', encoding=en_dest ) as fo: fo.write( fi.read() ) def isUTF8( self, file_name ): try: with open( file_name, 'r', encoding='utf-8', errors='strict' ) as fi: fi.read() except UnicodeError: return False return True def isSJIS( self, file_name ): try: with open( file_name, 'r', encoding='cp932', errors='strict' ) as fi: fi.read() except UnicodeError: return False return True #------------------------------------------------------------------------------ class FileTools: def __init__( self ): pass def f_copy_target( self, file_list, options ): base_dir= options['base'] target= options['target'] force_copy= options['force'] verbose= options['verbose'] Log.p( 'copy %s to %s' % (base_dir,target) ) start= time.perf_counter() total_count= len(file_list) copy_index= 0 file_count= 0 base_offset= len(base_dir) progress_step= 1.0/10 progress= progress_step for file_name in file_list: skip= False path= file_name[base_offset:] if path[0] == '/': path= path[1:] dest_file= os.path.join( target, path ) dir= os.path.dirname( dest_file ) if not os.path.exists( dir ): os.makedirs( dir ) elif not force_copy: if os.path.exists( dest_file ): src_time= os.path.getmtime( file_name ) dest_time= os.path.getmtime( dest_file ) if src_time <= dest_time: skip= True if not skip: if verbose: Log.v( file_name + ' --> ' + dest_file ) shutil.copy( file_name, dest_file ) file_stat= os.stat( dest_file ) os.chmod( dest_file, file_stat.st_mode | stat.S_IWRITE ) file_count+= 1 copy_index+= 1 if copy_index / total_count > progress: sec= time.perf_counter() - start Log.p( " %d%% %.2f sec" % (progress * 100,sec) ) progress+= progress_step Log.p( 'copy %d files' % file_count ) return file_list def f_grep( self, file_list, options ): pattern= options['pattern'] verbose= options['verbose'] grep_pat= re.compile( pattern.encode( encoding='utf-8' ) ) grep_list= [] for file_name in file_list: with open( file_name, 'rb' ) as fi: line_num= 0 added_flag= False for line in fi: line_num+= 1 pat= grep_pat.search( line ) if pat is not None: if not added_flag: grep_list.append( file_name ) added_flag= True if verbose: Log.v( '[%s] %d' % (file_name, line_num) ) Log.wb( line ) Log.wb( b'\r\n' ) else: Log.p( file_name ) break return grep_list def f_noutf8( self, file_list, options ): u8tools= UTF8Tools2() c_cp932= 0 c_utf8= 0 c_unknown= 0 grep_list= [] for file_name in file_list: if u8tools.isUTF8( file_name ): c_utf8+= 1 elif u8tools.isSJIS( file_name ): c_cp932+= 1 grep_list.append( file_name ) else: c_unknown+= 1 grep_list.append( file_name ) Log.p( '# utf8', c_utf8 ) Log.p( '# cp932', c_cp932 ) Log.p( '# erros', c_unknown ) return grep_list def f_cvutf8( self, file_list, options ): u8tools= UTF8Tools2() for file_name in file_list: if u8tools.isSJIS( file_name ): src_temp= file_name + '.cp932.src' if not os.path.exists( src_temp ): os.rename( file_name, src_temp ) output_name= file_name Log.v( src_temp, '-->', output_name ) u8tools.convert( src_temp, output_name, 'cp932', 'utf-8' ) return file_list def f_size_command( self, file_list, options ): total= 0 for file_name in file_list: total+= os.path.getsize( file_name ) #Log.p( 'size= %d byte' % total ) mark= "GMK" unit= 1024*1024*1024 index= 0 while unit >= 1024: if total >= unit: Log.p( 'size= %.2f %c (%d byte)' % (total/unit,mark[index],total) ) break index+= 1 unit>>= 10 return file_list def f_file_list( self, file_list, options ): for file_name in file_list: Log.p( file_name ) return file_list def f_save_list( self, file_list, options ): save_file= options['save'] with open( save_file, 'w', encoding='utf-8' ) as fo: for file_name in file_list: fo.write( '%s\n' % file_name ) fo.write( '# %d\n' % len(file_list) ) Log.p( 'save: %d %s' % (len(file_list), save_file) ) return file_list def f_load_list( self, file_list, options ): load_file= options['load'] load_list= [] with open( load_file, 'r', encoding='utf-8' ) as fi: for line in fi: name= line.strip() if name == '' or name[0] == '#': continue load_list.append( name ) Log.p( 'load: %d %s' % (len(load_list), load_file) ) file_list.extend( load_list ) return file_list def f_difftree( self, file_list, options ): diffroot= options['diffroot'] diff_list= [] for file_name in file_list: target_path= os.path.join( diffroot, file_name ) if not os.path.exists( target_path ): diff_list.append( file_name ) Log.v( target_path ) return diff_list def f_pathmatch( self, file_list, options ): match_pat= re.compile( options['pathmatch'] ) diff_list= [] for file_name in file_list: pat= match_pat.search( file_name ) if pat is not None: diff_list.append( file_name ) return diff_list def f_pathstrip( self, file_list, options ): match_pat= re.compile( options['pathstrip'] ) diff_list= [] for file_name in file_list: pat= match_pat.search( file_name ) if pat is not None: diff_list.append( pat.group(1) ) return diff_list def f_ignore( self, file_list, options ): ignore_file= options['ignore'] fll= FileListLib.FileListLib( ignore_file ) file_list= fll.find_file( options['base'] ) return file_list def f_findtree( self, file_list, options ): ignore_file= options['ignore'] fll= FileListLib.FileListLib() file_list= fll.find_file_preload( options['base'], ignore_file ) return file_list def f_dir( self, file_list, options ): sfile= set() for file_name in file_list: root,name= os.path.split( file_name ) sfile.add( root ) return list( sfile ) def f_unique( self, file_list, options ): sfile= set() for file_name in file_list: sfile.add( file_name ) return list( sfile ) def f_setwritable( self, file_list, options ): sfile= set() for file_name in file_list: file_stat= os.stat( file_name ) os.chmod( file_name, file_stat.st_mode | stat.S_IWRITE ) return file_list def f_clear( self, file_list, options ): return [] #------------------------------------------------------------------------------ def usage(): print( 'FileTools.py v1.35 2020/10/11 Hiroyuki Ogasawara' ) print( 'usage: FileTools.py [<options|commands>] [<base_dir>]' ) print( 'command:' ) print( ' -i,--ignore <ignore_file>' ) print( ' -ig' ) print( ' --findtree <ignore_file>' ) print( ' --copy <target_folder>' ) print( ' -l,--list' ) print( ' --size' ) print( ' --grep <pattern>' ) print( ' --load <file_name>' ) print( ' --save <file_name>' ) print( ' --difftree <diff_root>' ) print( ' --pathmatch <pattern>' ) print( ' --pathstrip <pattern>' ) print( ' --dir' ) print( ' --unique' ) print( ' --noutf8' ) print( ' --cvutf8' ) print( ' --setwritable' ) print( ' --clear' ) print( 'option:' ) print( ' --force force overwrite' ) print( ' --clog <file_name> output console log' ) print( ' -v,--verbose' ) print( 'ex. FileTools.py -i .flignore src --copy dest' ) sys.exit( 1 ) def getArg( ai, argv, options, opt_name ): if ai+1 < len(argv): ai+= 1 options[opt_name]= argv[ai] return ai def main( argv ): options= { 'base' : '.', 'force' : False, 'target': None, 'verbose': False, 'ignore': '.flignore', } action_list= [] acount= len(argv) ai= 1 while ai < acount: arg= argv[ai] if arg[0] == '-': if arg == '--debug': FileListLib.Log.DebugOutput= True elif arg == '-i' or arg == '--ignore': if ai+1 < acount: ai+= 1 options['ignore']= argv[ai] action_list.append( 'f_ignore' ) elif arg == '--findtree': if ai+1 < acount: ai+= 1 options['ignore']= argv[ai] action_list.append( 'f_findtree' ) elif arg == '--copy': if ai+1 < acount: ai+= 1 options['target']= argv[ai] action_list.append( 'f_copy_target' ) elif arg == '--grep': if ai+1 < acount: ai+= 1 options['pattern']= argv[ai] action_list.append( 'f_grep' ) elif arg == '--save': if ai+1 < acount: ai+= 1 options['save']= argv[ai] action_list.append( 'f_save_list' ) elif arg == '--load': if ai+1 < acount: ai+= 1 options['load']= argv[ai] action_list.append( 'f_load_list' ) elif arg == '--difftree': if ai+1 < acount: ai+= 1 options['diffroot']= argv[ai] action_list.append( 'f_difftree' ) elif arg == '--pathmatch': if ai+1 < acount: ai+= 1 options['pathmatch']= argv[ai] action_list.append( 'f_pathmatch' ) elif arg == '--pathstrip': if ai+1 < acount: ai+= 1 options['pathstrip']= argv[ai] action_list.append( 'f_pathstrip' ) elif arg == '-ig': action_list.append( 'f_ignore' ) elif arg == '--size': action_list.append( 'f_size_command' ) elif arg == '--dir': action_list.append( 'f_dir' ) elif arg == '--unique': action_list.append( 'f_unique' ) elif arg == '--clear': action_list.append( 'f_clear' ) elif arg == '-l' or arg == '--list': action_list.append( 'f_file_list' ) elif arg == '--noutf8': action_list.append( 'f_noutf8' ) elif arg == '--cvutf8': action_list.append( 'f_cvutf8' ) elif arg == '--setwritable': action_list.append( 'f_setwritable' ) elif arg == '--force': options['force']= True elif arg == '-v' or arg == '--verbose': options['verbose']= True elif arg == '--clog': if ai+1 < acount: ai+= 1 Log.open_log( argv[ai] ) else: usage() else: options['base']= arg ai+= 1 Log.Verbose= options['verbose'] if action_list != []: start= time.perf_counter() file_list= [] ftool= FileTools() for action in action_list: Log.p( '#begin [%s] in %d files' % (action, len(file_list)) ) try: func= getattr( ftool, action ) except AttributeError: usage() break file_list= func( file_list, options ) Log.p( '#end [%s] out %d files' % (action, len(file_list)) ) else: usage() Log.v( '#total: %.2f sec' % (time.perf_counter() - start) ) return 0 if __name__ == '__main__': sys.exit( main( sys.argv ) )
33.340183
84
0.4786
79518db987d1bb7d782c89ffc52794f1860ea986
29,680
py
Python
kinova_station/hardware_station.py
kwesiRutledge/kinova_drake
889594fcec4457737bc191a4006c2bba69b944c6
[ "MIT" ]
null
null
null
kinova_station/hardware_station.py
kwesiRutledge/kinova_drake
889594fcec4457737bc191a4006c2bba69b944c6
[ "MIT" ]
null
null
null
kinova_station/hardware_station.py
kwesiRutledge/kinova_drake
889594fcec4457737bc191a4006c2bba69b944c6
[ "MIT" ]
null
null
null
from pydrake.all import * import time import sys import threading from kinova_station.common import (EndEffectorTarget, GripperTarget, EndEffectorWrenchCalculator) from kortex_api.TCPTransport import TCPTransport from kortex_api.RouterClient import RouterClient, RouterClientSendOptions from kortex_api.SessionManager import SessionManager from kortex_api.autogen.client_stubs.DeviceConfigClientRpc import DeviceConfigClient from kortex_api.autogen.client_stubs.DeviceManagerClientRpc import DeviceManagerClient from kortex_api.autogen.client_stubs.VisionConfigClientRpc import VisionConfigClient from kortex_api.autogen.client_stubs.BaseClientRpc import BaseClient from kortex_api.autogen.client_stubs.BaseCyclicClientRpc import BaseCyclicClient from kortex_api.autogen.messages import DeviceConfig_pb2, Session_pb2, Base_pb2, VisionConfig_pb2 import gi gi.require_version('Gst', '1.0') from gi.repository import Gst import cv2 import matplotlib.pyplot as plt # DEBUG class KinovaStationHardwareInterface(LeafSystem): """ A system block for controlling a 6 or 7 DoF Kinova Gen3 robot, modeled after Drake's ManipulationStationHardwareInterface, but with the kinova instead of a kuka arm. ------------------------------------ | | | | | | | | --> measured_arm_position | | --> measured_arm_velocity ee_target ---------------> | KinovaStationHardwareInterface | --> measured_arm_torque ee_target_type ----------> | | | | | | --> measured_ee_pose | | --> measured_ee_twist | | --> measured_ee_wrench gripper_target ----------> | | gripper_target_type -----> | | | | --> measured_gripper_position | | --> measured_gripper_velocity | | | | --> camera_rgb_image | | --> camera_depth_image | | --> camera_transform | | | | ----------------------------------- The input ee_target can be a desired end-effector pose, twist or wrench, as specified by ee_target_type. Similarly, the gripper_target can be a desired gripper position or velocity, as specified by gripper_target_type. """ def __init__(self): LeafSystem.__init__(self) self.set_name("kinova_hardware_interface") # Identify the Number of Joints self.num_joints = self.FindNumberOfRobotJoints() # Declare input ports self.ee_target_port = self.DeclareVectorInputPort( "ee_target", BasicVector(6)) self.ee_target_type_port = self.DeclareAbstractInputPort( "ee_target_type", AbstractValue.Make(EndEffectorTarget.kPose)) self.gripper_target_port = self.DeclareVectorInputPort( "gripper_target", BasicVector(1)) self.gripper_target_type_port = self.DeclareAbstractInputPort( "gripper_target_type", AbstractValue.Make(GripperTarget.kPosition)) # Declare output ports self.DeclareVectorOutputPort( "measured_arm_position", BasicVector(self.num_joints), self.CalcArmPosition) self.DeclareVectorOutputPort( "measured_arm_velocity", BasicVector(self.num_joints), self.CalcArmVelocity) self.DeclareVectorOutputPort( "measured_arm_torque", BasicVector(self.num_joints), self.CalcArmTorque) self.DeclareVectorOutputPort( "measured_ee_pose", BasicVector(6), self.CalcEndEffectorPose, {self.time_ticket()}) self.DeclareVectorOutputPort( "measured_ee_twist", BasicVector(6), self.CalcEndEffectorTwist, {self.time_ticket()}) self.DeclareVectorOutputPort( "measured_ee_wrench", BasicVector(6), self.CalcEndEffectorWrench) self.DeclareVectorOutputPort( "measured_gripper_position", BasicVector(1), self.CalcGripperPosition, {self.time_ticket()}) self.DeclareVectorOutputPort( "measured_gripper_velocity", BasicVector(1), self.CalcGripperVelocity, {self.time_ticket()}) sample_rgb_image = Image[PixelType.kRgba8U](width=480, height=270) sample_depth_image = Image[PixelType.kDepth16U](width=480, height=270) self.DeclareAbstractOutputPort( "camera_rgb_image", lambda: AbstractValue.Make(sample_rgb_image), self.CaptureRgbImage, {self.time_ticket()}) self.DeclareAbstractOutputPort( "camera_depth_image", lambda: AbstractValue.Make(sample_depth_image), self.CaptureDepthImage, {self.time_ticket()}) self.DeclareAbstractOutputPort( "camera_transform", lambda: AbstractValue.Make(RigidTransform()), # TODO: use CameraPosePublisher? self.CalcCameraTransform, {self.time_ticket()}) # Create a dummy continuous state so that the simulator # knows not to just jump to the last possible timestep self.DeclareContinuousState(1) # Each call to self.base_cyclic.RefreshFeedback() takes about 0.025s, so we'll # try to minimize redudant calls to the base as much as possible by storing # feedback from the base at each timestep. self.last_feedback_time = -np.inf self.feedback = None # Store end-effector pose (for computing camera pose) self.ee_pose = np.zeros(6) def __enter__(self): """ Start an API instance and connect to the hardware. This is called at the beginning of a 'with' statement'. """ print("Opening Hardware Connection") TCP_PORT = 10000 # UDP port is 10001 # Set up API self.transport = TCPTransport() self.router = RouterClient(self.transport, RouterClient.basicErrorCallback) self.transport.connect('192.168.1.10', TCP_PORT) # Create session session_info = Session_pb2.CreateSessionInfo() session_info.username = "admin" session_info.password = "admin" session_info.session_inactivity_timeout = 60000 # (milliseconds) session_info.connection_inactivity_timeout = 2000 # (milliseconds) self.session_manager = SessionManager(self.router) self.session_manager.CreateSession(session_info) # Create required services device_config = DeviceConfigClient(self.router) self.base = BaseClient(self.router) self.base_cyclic = BaseCyclicClient(self.router) if self.base.GetArmState().active_state != Base_pb2.ARMSTATE_SERVOING_READY: print("") print("ERROR: arm not in ready state.") print(self.base.GetArmState()) print("Make sure there is nothing else currently sending commands (e.g. joystick, web interface), ") print("and clear any faults before trying again.") sys.exit(0) # Set up depth image pipeline. We use raw Gstramer for the depth image, since # OpenCV only supports 8bit images and we want 16bit depth images for full resolution. Gst.init(None) depth_command = 'rtspsrc location=rtsp://192.168.1.10/depth latency=30 ! rtpgstdepay ! videoconvert ! appsink' depth_video_pipe = Gst.parse_launch(depth_command) depth_video_pipe.set_state(Gst.State.PLAYING) self.depth_video_sink = depth_video_pipe.get_by_name('appsink0') self.depth_video_sink.set_property('sync', False) self.depth_video_sink.set_property('max-buffers', 2) self.depth_video_sink.set_property('drop', True) # Set up the color image pipeline using OpenCV color_command = 'rtspsrc location=rtsp://192.168.1.10/color latency=30 ! rtph264depay ! avdec_h264 ! videoconvert ! appsink drop=true max-buffers=2' self.color_stream = cv2.VideoCapture(color_command) if (self.color_stream.isOpened()== False): print("ERROR: Error opening video stream for Gen3 Camera.") # While it might be nice to immediately stop when this is the case, # we allow the user to potentially control the joints of the robot with no visual image. # sys.exit(0) # DEBUG: set color and depth image sizes #device_manager = DeviceManagerClient(self.router) #vision_config = VisionConfigClient(self.router) #all_devices_info = device_manager.ReadAllDevices() # #vision_handles = [ hd for hd in all_devices_info.device_handle if hd.device_type == DeviceConfig_pb2.VISION ] #if len(vision_handles) == 0: # raise RuntimeError("There is no vision device registered in the devices info") #elif len(vision_handles) > 1: # raise RuntimeError("There is more than one vision device registered in the devices info") # #vision_device_id = vision_handles[0].device_identifier #profile_id = VisionConfig_pb2.IntrinsicProfileIdentifier() #profile_id.sensor = VisionConfig_pb2.SENSOR_COLOR #profile_id.resolution = VisionConfig_pb2.RESOLUTION_640x480 # #intrinsics = vision_config.GetIntrinsicParametersProfile(profile_id, vision_device_id) #vision_config.SetIntrinsicParameters(intrinsics, vision_device_id) print("Hardware Connection Open.\n") return self def __exit__(self, exc_type, exc_value, traceback): """ Disconnect from the API instance and close everything down. This is called at the end of a 'with' statement. """ print("\nClosing Hardware Connection...") if self.session_manager is not None: router_options = RouterClientSendOptions() router_options.timeout_ms = 1000 self.session_manager.CloseSession() self.transport.disconnect() print("Hardware Connection Closed.") def check_for_end_or_abort(self, e): """ Return a closure checking for END or ABORT notifications Arguments: e -- event to signal when the action is completed (will be set when an END or ABORT occurs) """ def check(notification, e = e): print("EVENT : " + \ Base_pb2.ActionEvent.Name(notification.action_event)) if notification.action_event == Base_pb2.ACTION_END \ or notification.action_event == Base_pb2.ACTION_ABORT: e.set() return check def GetFeedback(self, current_time): """ Sets self.feedback with the latest data from the controller. We also indicate the time at which this feedback was set, in an effor to reduce redudnant calls to self.base_cyclic.RefreshFeedback(), which take about 25ms each. """ self.feedback = self.base_cyclic.RefreshFeedback() self.last_feedback_time = current_time def go_home(self, name="Home"): """ Move the arm to the home position. Different positions can be specified using the 'name' parameter ('Home', 'Retract', 'Packaging', or 'Zero'). """ # Make sure the arm is in Single Level Servoing mode base_servo_mode = Base_pb2.ServoingModeInformation() base_servo_mode.servoing_mode = Base_pb2.SINGLE_LEVEL_SERVOING self.base.SetServoingMode(base_servo_mode) # Move arm to ready position print("Moving the arm to the home position") action_type = Base_pb2.RequestedActionType() action_type.action_type = Base_pb2.REACH_JOINT_ANGLES action_list = self.base.ReadAllActions(action_type) action_handle = None for action in action_list.action_list: if action.name == name: action_handle = action.handle if action_handle == None: print("Invalid home position name: %s" % name) print("Must be one of ['Home','Retract','Packaging','Zero']") print("Exiting.") sys.exit(0) e = threading.Event() notification_handle = self.base.OnNotificationActionTopic( self.check_for_end_or_abort(e), Base_pb2.NotificationOptions() ) self.base.ExecuteActionFromReference(action_handle) # Leave time to action to complete TIMEOUT_DURATION = 20 # seconds finished = e.wait(TIMEOUT_DURATION) self.base.Unsubscribe(notification_handle) if finished: print("Home position reached") else: print("Timeout while moving to home position") return finished def send_gripper_command(self, mode, command): """ Send a position or a velocity command to the gripper """ assert (mode == Base_pb2.GRIPPER_POSITION) or (mode == Base_pb2.GRIPPER_SPEED) gripper_command = Base_pb2.GripperCommand() gripper_command.mode = mode finger = gripper_command.gripper.finger.add() finger.finger_identifier = 1 finger.value = command self.base.SendGripperCommand(gripper_command) def send_gripper_position_command(self, position): """ Convienience method for sending a position command (real number in [0,1]) to the gripper. """ self.send_gripper_command( mode = Base_pb2.GRIPPER_POSITION, command = position) def send_gripper_velocity_command(self, velocity): """ Convienience method for sending a velocity command to the gripper. """ self.send_gripper_command( mode = Base_pb2.GRIPPER_SPEED, command = velocity) def send_pose_command(self, pose): """ Convienience method for sending a target end-effector pose to the robot. WARNING: unlike the twist and wrench commands, this command stops everything and just moves the end-effector to the desired pose. """ action = Base_pb2.Action() action.name = "End-effector pose command" action.application_data = "" cartesian_pose = action.reach_pose.target_pose cartesian_pose.theta_x = np.degrees(pose[0]) cartesian_pose.theta_y = np.degrees(pose[1]) cartesian_pose.theta_z = np.degrees(pose[2]) cartesian_pose.x = pose[3] cartesian_pose.y = pose[4] cartesian_pose.z = pose[5] e = threading.Event() notification_handle = self.base.OnNotificationActionTopic( self.check_for_end_or_abort(e), Base_pb2.NotificationOptions() ) self.base.ExecuteAction(action) TIMEOUT_DURATION = 20 # seconds finished = e.wait(TIMEOUT_DURATION) self.base.Unsubscribe(notification_handle) def send_twist_command(self, cmd_twist): """ Convienience method for sending an end-effector twist command to the robot. """ command = Base_pb2.TwistCommand() command.reference_frame = Base_pb2.CARTESIAN_REFERENCE_FRAME_BASE command.duration = 0 twist = command.twist twist.angular_x = np.degrees(cmd_twist[0]) twist.angular_y = np.degrees(cmd_twist[1]) twist.angular_z = np.degrees(cmd_twist[2]) twist.linear_x = cmd_twist[3] twist.linear_y = cmd_twist[4] twist.linear_z = cmd_twist[5] # Note: this API call takes about 25ms self.base.SendTwistCommand(command) def send_wrench_command(self, cmd_wrench): """ Convienience method for sending an end-effector wrench command to the robot. WARNING: this method is experimental. Force control should probably be done with full torque-control over a 1kHz control loop (UDP) in C++. """ command = Base_pb2.WrenchCommand() command.reference_frame = Base_pb2.CARTESIAN_REFERENCE_FRAME_BASE command.duration = 0 wrench = command.wrench wrench.torque_x = cmd_wrench[0] wrench.torque_y = cmd_wrench[1] wrench.torque_z = cmd_wrench[2] wrench.force_x = cmd_wrench[3] wrench.force_y = cmd_wrench[4] wrench.force_z = cmd_wrench[5] self.base.SendWrenchCommand(command) def CalcArmPosition(self, context, output): """ Compute the current joint angles and send as output. """ # Get feedback from the base, but only if we haven't already this timestep t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) q = np.zeros(self.num_joints) for i in range(self.num_joints): q[i] = np.radians(self.feedback.actuators[i].position) # Kortex provides joint angles # in degrees for some reason output.SetFromVector(q) def CalcArmVelocity(self, context, output): """ Compute the current joint velocities and send as output. """ t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) qd = np.zeros(self.num_joints) for i in range(self.num_joints): qd[i] = np.radians(self.feedback.actuators[i].velocity) # Kortex provides joint angles # in degrees for some reason output.SetFromVector(qd) def CalcArmTorque(self, context, output): """ Compute the current joint torques and send as output. """ t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) tau = np.zeros(self.num_joints) for i in range(self.num_joints): tau[i] = np.radians(self.feedback.actuators[i].torque) # in Nm output.SetFromVector(tau) def CalcEndEffectorPose(self, context, output): """ Compute the current end-effector pose and send as output. """ t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) ee_pose = np.zeros(6) ee_pose[0] = np.radians(self.feedback.base.tool_pose_theta_x) ee_pose[1] = np.radians(self.feedback.base.tool_pose_theta_y) ee_pose[2] = np.radians(self.feedback.base.tool_pose_theta_z) ee_pose[3] = self.feedback.base.tool_pose_x ee_pose[4] = self.feedback.base.tool_pose_y ee_pose[5] = self.feedback.base.tool_pose_z # Store the end-effector pose so we can use it to compute the camera pose self.ee_pose = ee_pose output.SetFromVector(ee_pose) def CalcEndEffectorTwist(self, context, output): """ Compute the current end-effector twist and send as output """ t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) ee_twist = np.zeros(6) ee_twist[0] = np.radians(self.feedback.base.tool_twist_angular_x) ee_twist[1] = np.radians(self.feedback.base.tool_twist_angular_y) ee_twist[2] = np.radians(self.feedback.base.tool_twist_angular_z) ee_twist[3] = self.feedback.base.tool_twist_linear_x ee_twist[4] = self.feedback.base.tool_twist_linear_y ee_twist[5] = self.feedback.base.tool_twist_linear_z output.SetFromVector(ee_twist) def CalcEndEffectorWrench(self, context, output): """ Compute the current end-effector wrench and send as output """ t = context.get_time() if (self.last_feedback_time != t): self.GetFeedback(t) ee_wrench = np.zeros(6) ee_wrench[0] = self.feedback.base.tool_external_wrench_torque_x ee_wrench[1] = self.feedback.base.tool_external_wrench_torque_y ee_wrench[2] = self.feedback.base.tool_external_wrench_torque_z ee_wrench[3] = self.feedback.base.tool_external_wrench_force_x ee_wrench[4] = self.feedback.base.tool_external_wrench_force_y ee_wrench[5] = self.feedback.base.tool_external_wrench_force_z output.SetFromVector(ee_wrench) def CalcGripperPosition(self, context, output): """ Compute the current gripper position and send as output Note that this method is fairly slow: sending and recieving the MeasuredGripperMovement takes about 25ms. """ # Position is 0 full open, 1 fully closed gripper_request = Base_pb2.GripperRequest() gripper_request.mode = Base_pb2.GRIPPER_POSITION gripper_measure = self.base.GetMeasuredGripperMovement(gripper_request) output.SetFromVector([gripper_measure.finger[0].value]) def CalcGripperVelocity(self, context, output): """ Compute the current gripper velocity and send as output. Note that this method is fairly slow: sending and recieving the MeasuredGripperMovement takes about 25ms. """ # TODO: this just gives us a speed, but not a direction! gripper_request = Base_pb2.GripperRequest() gripper_request.mode = Base_pb2.GRIPPER_SPEED gripper_measure = self.base.GetMeasuredGripperMovement(gripper_request) output.SetFromVector([gripper_measure.finger[0].value]) def CaptureRgbImage(self, context, output): """ Capture and send as output a color image from the camera. """ # Read data vida OpenCV ret, frame = self.color_stream.read() if not ret: raise RuntimeError("Unable to pull color image") # Resize to match resolution of the depth image, and add an alpha channel frame = cv2.resize(frame, (480, 270)) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) # Transform to match depth image (roughly) #tx = 0 #ty = 0 #M = np.array([[1, 0, tx], # transformation matrix # [0, 1, ty]]) #rows, cols, _ = frame.shape #frame = cv2.warpAffine(frame, M, (rows,cols)) #with open('color_image_saved.npy', 'wb') as f: # np.save(f, frame) color_image = output.get_mutable_value() # 270 x 480 x 4 color_image.mutable_data[:,:,:] = frame def CaptureDepthImage(self, context, output): """ Capture and send as output a depth image from the camera. """ # Get raw byte stream from the camera timeout = 2.0 # max seconds to wait for an image sample = self.depth_video_sink.emit('try-pull-sample', timeout) if sample is None: raise RuntimeError("Unable to pull depth image: %s second timeout exceeded" % timeout) # Convert to a 16bit image (consistent with OpenCV, for example) buf = sample.get_buffer() caps = sample.get_caps() frame = np.ndarray( ( caps.get_structure(0).get_value('height'), caps.get_structure(0).get_value('width'), 1 ), buffer=buf.extract_dup(0, buf.get_size()), dtype=np.uint16) #with open('depth_image_saved.npy', 'wb') as f: # np.save(f, frame) # Convert to a Drake DepthImage depth_image = output.get_mutable_value() depth_image.mutable_data[:,:,:] = frame def CalcCameraTransform(self, context, output): """ Compute and send as output the current pose of the camera in the world. """ ee_rpy = self.ee_pose[:3] ee_xyz = self.ee_pose[3:] # pose of end-effector in the world frame X_WE = RigidTransform( RotationMatrix(RollPitchYaw(ee_rpy)), ee_xyz) # pose of camera in the end-effector frame # TODO: get precise transform data from the datasheet X_EC = RigidTransform( RotationMatrix(RollPitchYaw([0,0,np.pi])), # This seems strange... [0.03,0.065,-0.14]) # Compute pose of camera in the world frame X_WC = X_WE.multiply(X_EC) output.set_value(X_WC) def DoCalcTimeDerivatives(self, context, continuous_state): """ This method gets called every timestep. Its nominal purpose is to update the (dummy) continuous variable for the simulator, but here we'll use it to parse inputs and send the corresponding commands to the robot. """ print("time is: %s" % context.get_time()) # Get data from input ports ee_target_type = self.ee_target_type_port.Eval(context) ee_target = self.ee_target_port.Eval(context) gripper_target_type = self.gripper_target_type_port.Eval(context) gripper_target = self.gripper_target_port.Eval(context) # Send commands to the base consistent with these targets if gripper_target_type == GripperTarget.kPosition: self.send_gripper_position_command(gripper_target[0]) elif gripper_target_type == GripperTarget.kVelocity: self.send_gripper_velocity_command(gripper_target[0]) else: raise RuntimeError("Invalid gripper target type %s" % gripper_target_type) if ee_target_type == EndEffectorTarget.kPose: # WARNING: unlike the twist and wrench commands, this command # stops everything and just moves the end-effector to the # desired pose. self.send_pose_command(ee_target) elif ee_target_type == EndEffectorTarget.kTwist: self.send_twist_command(ee_target) elif ee_target_type == EndEffectorTarget.kWrench: # WARNING: this method is experimental. Full torque control via a 1kHz # UDP connection and C code is probably preferable for force control. self.send_wrench_command(ee_target) else: raise RuntimeError("Invalid end-effector target type %s" % ee_target_type) def FindNumberOfRobotJoints(self): ''' This function creates all required objects and connections to use the arm's services. It is easier to use the DeviceConnection utility class to create the router and then create the services you need (as done in the other examples). However, if you want to create all objects yourself, this function tells you how to do it. ''' # Constants PORT = 10000 username0 = "admin" pw0 = "admin" ip0 = '192.168.1.10' # Setup API error_callback = lambda kException: print("_________ callback error _________ {}".format(kException)) transport = TCPTransport() router = RouterClient(transport, error_callback) transport.connect(ip0, PORT) # Create session session_info = Session_pb2.CreateSessionInfo() session_info.username = username0 session_info.password = pw0 session_info.session_inactivity_timeout = 60000 # (milliseconds) session_info.connection_inactivity_timeout = 2000 # (milliseconds) # print("Creating session for communication") session_manager = SessionManager(router) session_manager.CreateSession(session_info) # print("Session created") # Create required services base = BaseClient(router) # print(base.GetArmState()) gmja_out = base.GetMeasuredJointAngles() num_joints = len(gmja_out.joint_angles) print("There are " + str(num_joints) + " joints on this robot!") # Close API session session_manager.CloseSession() # Disconnect from the transport object transport.disconnect() return num_joints
40.546448
156
0.60374
79518e6dc5a2222308241998a17ac7285249b9d6
24
py
Python
sklearn_extra/_version.py
ineveLoppiliF/scikit-learn-extra
0cee1e6da0f14290c7652ba967669f946773bc78
[ "BSD-3-Clause" ]
null
null
null
sklearn_extra/_version.py
ineveLoppiliF/scikit-learn-extra
0cee1e6da0f14290c7652ba967669f946773bc78
[ "BSD-3-Clause" ]
null
null
null
sklearn_extra/_version.py
ineveLoppiliF/scikit-learn-extra
0cee1e6da0f14290c7652ba967669f946773bc78
[ "BSD-3-Clause" ]
null
null
null
__version__ = "0.1.0b2"
12
23
0.666667
79518f1609f6098dd1f2e2111b4633405f5f70e1
23,187
py
Python
test/test_handler.py
Jazun713/sensu-plugin-py-pagerduty
88f2d53aa07c88c05d9a50b5c99cda5225ac1fec
[ "MIT" ]
null
null
null
test/test_handler.py
Jazun713/sensu-plugin-py-pagerduty
88f2d53aa07c88c05d9a50b5c99cda5225ac1fec
[ "MIT" ]
1
2018-08-07T20:46:41.000Z
2019-01-10T23:25:14.000Z
test/test_handler.py
Jazun713/sensu-plugin-py-pagerduty
88f2d53aa07c88c05d9a50b5c99cda5225ac1fec
[ "MIT" ]
null
null
null
import mock import unittest import json, logging import mock from pagerduty.handler import PagerdutyHandler def event_no_teams(): event = {'client': { "name": "test_client", "address": "127.0.0.1", "keepalive": { "handler": "sensu_deregister", "thresholds": { "critical": 604800, "warning": 300 } }, "metrics": { "cpu": { "crit": 100, "warning": 90 }, "disk": { "crit": 5, "warning": 8 }, "memory": { "crit": 100, "warning": 90 } }, "pools": {}, "services": { "octopus-deploy": { "service": "OctopusDeploy Tentacle" } }, "subscriptions": [ "win-svc-metrics", "octopus-deploy-service", "host-checks", "host-metrics", "client:test_client" ], "version": "1.2.0", "timestamp": 1529508402 }, 'check': { "thresholds": { "warning": 300, "critical": 604800 }, "handler": "sensu_pagerduty", "name": "keepalive", "severity": "error", "links": [{"href": "https://sensu.io", "text": "RunBook"}], "output": "No keepalive sent from client for 1337 seconds (>=300)", "status": 1, "type": "standard", "history": ["1", "1", "1"], }} event.update({ "occurrences": 3, "action": "create", }) return event def settings_teams(): settings = {'pagerduty': {'api_key': 'default_key', 'svc_email': 'test@example.com', 'team_1': {'api_key': 'team_1_key'}, 'dynamic_description_prefix_key': 'name'}} return settings def settings_no_teams(): settings = {'pagerduty': {'api_key': 'default_key', 'svc_email': 'test@example.com', 'dynamic_description_prefix_key': 'name'}} return settings @mock.patch("pypd.EventV2.create") @mock.patch("pagerduty.handler.PagerdutyHandler.grab_event") @mock.patch("pagerduty.handler.PagerdutyHandler.grab_settings") @mock.patch("sys.stdin") class TestPagerdutyHandler(unittest.TestCase): """Test handle if handler config (settings) and event['client'] has pager_team""" def test_handle_pager_team_client_and_settings(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_teams() event = event_no_teams() event['client']['pager_team'] = 'team_1' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'team_1_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if handler config (settings) and event['check'] has pager_team''' def test_handle_pager_team_check_and_settings(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_teams() event = event_no_teams() event['check']['pager_team'] = 'team_1' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'team_1_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if handler config (settings) has pager_team but event does not''' def test_handle_pager_team_settings_not_event(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_teams() event = event_no_teams() stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if event['check'] has pager_team but handler config (settings) does not''' def test_handle_pager_team_check_not_settings(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['pager_team'] = 'team_1' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if neither handler config (settings) or event has pager_team''' def test_handle_pager_team_no_event_no_settings(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if severity is not info, warning, critical, or error''' def test_handle_severity_assert_fail(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['severity'] = 'thingy' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if event['check']['severity'] is info''' def test_handle_severity_info(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['severity'] = 'info' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'info', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if event['check']['severity'] is warning''' def test_handle_severity_warning(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['severity'] = 'warning' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'warning', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if event['check']['severity'] is critical''' def test_handle_severity_critical(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['severity'] = 'critical' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'critical', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if event['check']['severity'] is error''' def test_handle_severity_error(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['severity'] = 'error' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client for 1337 seconds (>=300)', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) '''Test handle if output is a dictionary''' def test_handle_output_dict_with_PD_context(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)', 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse minions ' 'name to attempt restart. Restart not attempted' } event['check']['pagerduty_contexts'] = ['This is a pd context', 'This is another pd context'] stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': { 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse ' 'minions name to attempt restart. Restart not attempted', 'Contexts': ['This is a pd context', 'This is another pd context'], 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) def test_handle_output_dict_with_no_PD_context(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)', 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse minions ' 'name to attempt restart. Restart not attempted' } stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': { 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse ' 'minions name to attempt restart. Restart not attempted', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) def test_handle_output_no_status_no_PD_context(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "RunBook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': 'No keepalive sent from client for 1337 seconds (>=300)' }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) def test_handle_links_as_string(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)', 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse minions ' 'name to attempt restart. Restart not attempted' } event['check']['pagerduty_contexts'] = ['This is a pd context', 'This is another pd context'] event['check']['links'] = 'https://sensu.io' stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': { 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse ' 'minions name to attempt restart. Restart not attempted', 'Contexts': ['This is a pd context', 'This is another pd context'], 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) def test_handle_links_as_list(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)', 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse minions ' 'name to attempt restart. Restart not attempted' } event['check']['pagerduty_contexts'] = ['This is a pd context', 'This is another pd context'] event['check']['links'] = ['https://sensu.io', 'https://example.com'] stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io"}, {"href": "https://example.com"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': { 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse ' 'minions name to attempt restart. Restart not attempted', 'Contexts': ['This is a pd context', 'This is another pd context'], 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) def test_handle_links_as_dict(self, mock_stdin, mock_grab_settings, mock_grab_event, mock_event_create): settings = settings_no_teams() event = event_no_teams() event['check']['output'] = { 'Summary': 'No keepalive sent from client', 'Details': 'No keepalive sent from client for 1337 seconds (>=300)', 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse minions ' 'name to attempt restart. Restart not attempted' } event['check']['pagerduty_contexts'] = ['This is a pd context', 'This is another pd context'] event['check']['links'] = [{'href': 'https://sensu.io', 'text': 'Runbook'}] stdin = mock_stdin.read.return_value = json.dumps(event) mock_event = mock_grab_event.return_value = event mock_settings = mock_grab_settings.return_value = settings handler = PagerdutyHandler() payload = {} payload = { 'routing_key': 'default_key', 'event_action': 'trigger', 'dedup_key': 'keepalive/test_client', 'images': None, 'links': [{"href": "https://sensu.io", "text": "Runbook"}], 'payload': { 'summary': '( test_client ) No keepalive sent from client', 'severity': 'error', 'source': 'test_client', 'class': None, 'group': None, 'component': None, 'custom_details': { 'Status': 'Unable to authenticate with Salt to attempt restart. Restart not attempted Unable parse ' 'minions name to attempt restart. Restart not attempted', 'Contexts': ['This is a pd context', 'This is another pd context'], 'Details': 'No keepalive sent from client for 1337 seconds (>=300)' } }} logging.debug("Event called with pypd.EventV2.create(data=" + json.dumps(payload)) mock_event_create.assert_called_with(data=payload) if __name__ == '__main__': unittest.main()
38.073892
112
0.684133
79519052792e9726ce416153ee43ebef4e74e4e0
6,801
py
Python
elasticsearch/komand_elasticsearch/util/helpers.py
killstrelok/insightconnect-plugins
911358925f4233ab273dbd8172e8b7b9188ebc01
[ "MIT" ]
1
2020-03-18T09:14:55.000Z
2020-03-18T09:14:55.000Z
elasticsearch/komand_elasticsearch/util/helpers.py
killstrelok/insightconnect-plugins
911358925f4233ab273dbd8172e8b7b9188ebc01
[ "MIT" ]
1
2021-02-23T23:57:37.000Z
2021-02-23T23:57:37.000Z
elasticsearch/komand_elasticsearch/util/helpers.py
killstrelok/insightconnect-plugins
911358925f4233ab273dbd8172e8b7b9188ebc01
[ "MIT" ]
null
null
null
import requests from urllib.parse import quote from requests.auth import HTTPBasicAuth def test_auth(log, host, username=None, password=None): if not host.endswith('/'): host += '/' headers = {'Accept': 'application/json'} try: if not username: resp = requests.get(host, headers=headers) else: resp = requests.get(host, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), host)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % host) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % host) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % host) raise Exception("Call failed: unknown error") def put_index(log, host, index, type_, id_, document, username=None, password=None, params=None): if not host.endswith('/'): host += '/' url = host + index + '/' + type_ + '/' + id_ + '?' if params: d = [k + '=' + quote(v) for k, v in params.items()] url += '&'.join(d) headers = {'Content-Type': 'application/json'} try: if not username: resp = requests.put(url, json=document, headers=headers) else: resp = requests.put(url, json=document, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), url)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % url) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % url) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % url) raise Exception("Call failed: unknown error") def post_index(log, host, index, type_, document, username=None, password=None, params=None): if not host.endswith('/'): host += '/' url = host + index + '/' + type_ + '?' if params: d = [k + '=' + quote(v) for k, v in params.items()] url += '&'.join(d) headers = {'Content-Type': 'application/json'} try: if not username: resp = requests.post(url, json=document, headers=headers) else: resp = requests.post(url, json=document, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), url)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % url) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % url) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % url) raise Exception("Call failed: unknown error") def post_update(log, host, index, type_, id_, script, username=None, password=None, params=None): if not host.endswith('/'): host += '/' url = host + index + '/' + type_ + '/' + id_ + '/' + '_update' + '?' if params: d = [k + '=' + quote(v) for k, v in params.items()] url += '&'.join(d) headers = {'Content-Type': 'application/json'} try: if not username: resp = requests.post(url, json=script, headers=headers) else: resp = requests.post(url, json=script, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), url)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % url) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % url) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % url) raise Exception("Call failed: unknown error") def get_search(log, host, index, type_, query=None, username=None, password=None, params=None): if not host.endswith('/'): host += '/' url = host + index + '/' + type_ + '/' + '_search?' if params: d = [k + '=' + quote(v) for k, v in params.items()] url += '&'.join(d) headers = {'Content-Type': 'application/json'} if not query: query = {} query['version'] = True try: if not username: resp = requests.get(url, json=query, headers=headers) else: resp = requests.get(url, json=query, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), url)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % url) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % url) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % url) raise Exception("Call failed: unknown error") def get_health(log, host, username=None, password=None): if not host.endswith('/'): host += '/' url = host + '_cluster/health' headers = {'Content-Type': 'application/json'} try: if not username: resp = requests.get(url, headers=headers) else: resp = requests.get(url, auth=HTTPBasicAuth(username, password), headers=headers) if resp.status_code >= 200 and resp.status_code <= 399: return resp.json() except requests.exceptions.HTTPError: log.error('Requests: HTTPError: status code %s for %s' % (str(resp.status_code), url)) except requests.exceptions.Timeout: log.error('Requests: Timeout for %s' % url) except requests.exceptions.TooManyRedirects: log.error('Requests: TooManyRedirects for %s' % url) except requests.exceptions.ConnectionError: log.error('Requests: ConnectionError for %s' % url) raise Exception("Call failed: unknown error")
40.005882
109
0.631084
7951906008449ff707e25155b96b8a059086f7df
6,940
py
Python
src/tf_train_mt_combined.py
gycggd/leaf-classification
b37dd4a6a262562c454038218c1472329e54128b
[ "MIT" ]
null
null
null
src/tf_train_mt_combined.py
gycggd/leaf-classification
b37dd4a6a262562c454038218c1472329e54128b
[ "MIT" ]
null
null
null
src/tf_train_mt_combined.py
gycggd/leaf-classification
b37dd4a6a262562c454038218c1472329e54128b
[ "MIT" ]
null
null
null
import tensorflow as tf import numpy as np import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='', help='input data path') parser.add_argument('--model_dir', type=str, default='', help='output model path') FLAGS, _ = parser.parse_known_args() train_data_path = os.path.join(FLAGS.data_dir, "train_data_1.tfrecords") val_data_path = os.path.join(FLAGS.data_dir, "val_data_1.tfrecords") def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): """max_pool_2x2 downsamples a feature map by 2X.""" return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def weight_variable(shape, name=None): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) def bias_variable(shape, name=None): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=name) image = tf.placeholder(tf.float32, (None, 96, 96, 1)) numerical = tf.placeholder(tf.float32, (None, 192)) label = tf.placeholder(tf.float32, (None, 99)) keep_prob = tf.placeholder(tf.float32) W_conv1 = weight_variable([5, 5, 1, 8], name='W_conv1') b_conv1 = bias_variable([8], name='b_conv1') h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1) print(W_conv1.name) h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 8, 32], name='W_conv2') b_conv2 = bias_variable([32], name='b_conv2') h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) h_pool2_flat = tf.reshape(h_pool2, [-1, 24 * 24 * 32]) concated = tf.concat([h_pool2_flat, numerical], axis=1) W_fc1 = weight_variable([24 * 24 * 32 + 192, 100], name='W_fc1') b_fc1 = bias_variable([100], name='b_fc1') h_fc1 = tf.nn.relu(tf.matmul(concated, W_fc1) + b_fc1) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([100, 99], name='W_fc2') b_fc2 = bias_variable([99], name='b_fc2') y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=label, logits=y_conv)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(label, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: def decode(serialized_example): feature_dic = {'image': tf.FixedLenFeature([], tf.string), 'num': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.string)} features = tf.parse_single_example(serialized_example, features=feature_dic) return features['image'], features['num'], features['label'] class DataReader: def __init__(self, data_path): self.dataset = tf.data.TFRecordDataset([data_path]).map(decode) self.iterator = self.dataset.make_one_shot_iterator() self.iter_image, self.iter_num, self.iter_label = self.iterator.get_next() self.cnt = 0 def get_all(self): all_image, all_num, all_label = [], [], [] try: while True: bytes_image, bytes_num, bytes_label = sess.run((self.iter_image, self.iter_num, self.iter_label)) image, num, label = np.fromstring(bytes_image, dtype=np.bool), \ np.fromstring(bytes_num, dtype=np.float64), \ np.fromstring(bytes_label, dtype=np.bool) # print(image.shape, num.shape, label.shape) image = np.reshape(image, (1, 96, 96, 1)) all_image.append(image) all_num.append(num) all_label.append(label) self.cnt += 1 except tf.errors.OutOfRangeError: pass all_image, all_num, all_label = np.concatenate(all_image), np.array( all_num), np.array(all_label) # print(all_image.shape, all_num.shape, all_label.shape) return all_image, all_num, all_label def get_batch(self): batch_image, batch_num, batch_label = [], [], [] try: while True: bytes_image, bytes_num, bytes_label = sess.run((self.iter_image, self.iter_num, self.iter_label)) image, num, label = np.fromstring(bytes_image, dtype=np.bool), \ np.fromstring(bytes_num, dtype=np.float64), \ np.fromstring(bytes_label, dtype=np.bool) # print(image.shape, num.shape, label.shape) image = np.reshape(image, (1, 96, 96, 1)) batch_image.append(image) batch_num.append(num) batch_label.append(label) self.cnt += 1 if self.cnt % 32 == 0 or self.cnt % 891 == 0: break except tf.errors.OutOfRangeError: pass batch_image, batch_num, batch_label = np.concatenate(batch_image), np.array( batch_num), np.array(batch_label) # print(batch_image.shape, batch_num.shape, batch_label.shape) return batch_image, batch_num, batch_label sess.run(tf.global_variables_initializer()) train_data_reader = DataReader(data_path=train_data_path) val_data_reader = DataReader(data_path=val_data_path) val_image, val_num, val_label = val_data_reader.get_all() for i in range(28 * 200): batch_image, batch_num, batch_label = train_data_reader.get_batch() if i % 28 == 0: train_accuracy = accuracy.eval(feed_dict={ image: batch_image, numerical: batch_num, label: batch_label, keep_prob: 1.0}) train_loss = cross_entropy.eval(feed_dict={ image: batch_image, numerical: batch_num, label: batch_label, keep_prob: 1.0}) print('Epoch %d, training accuracy %g, training loss %g' % (i // 32, train_accuracy, train_loss)) val_accuracy = accuracy.eval(feed_dict={ image: val_image, numerical: val_num, label: val_label, keep_prob: 1.0}) val_loss = cross_entropy.eval(feed_dict={ image: val_image, numerical: val_num, label: val_label, keep_prob: 1.0}) print('Validation accuracy %g, validation loss %g' % (val_accuracy, val_loss)) train_step.run(feed_dict={image: batch_image, numerical: batch_num, label: batch_label, keep_prob: 0.5})
43.924051
117
0.619741
7951909d3410875b34c440e6c03aa0ee4cfdf6f3
10,919
py
Python
O365/utils/token.py
urshala/python-o365
8d6969d39ca56c0c81de66119f5bdb1a4bbf2da3
[ "Apache-2.0" ]
null
null
null
O365/utils/token.py
urshala/python-o365
8d6969d39ca56c0c81de66119f5bdb1a4bbf2da3
[ "Apache-2.0" ]
null
null
null
O365/utils/token.py
urshala/python-o365
8d6969d39ca56c0c81de66119f5bdb1a4bbf2da3
[ "Apache-2.0" ]
null
null
null
import logging import json import datetime as dt from pathlib import Path from abc import ABC, abstractmethod log = logging.getLogger(__name__) EXPIRES_ON_THRESHOLD = 1 * 60 # 1 minute class Token(dict): """ A dict subclass with extra methods to resemble a token """ @property def is_long_lived(self): """ Checks whether this token has a refresh token :return bool: True if has a refresh_token """ return 'refresh_token' in self @property def is_expired(self): """ Checks whether this token is expired :return bool: True if the token is expired, False otherwise """ return dt.datetime.now() > self.expiration_datetime @property def expiration_datetime(self): """ Returns the expiration datetime :return datetime: The datetime this token expires """ access_expires_at = self.access_expiration_datetime expires_on = access_expires_at - dt.timedelta(seconds=EXPIRES_ON_THRESHOLD) if self.is_long_lived: expires_on = expires_on + dt.timedelta(days=90) return expires_on @property def access_expiration_datetime(self): """ Returns the token's access expiration datetime :return datetime: The datetime the token's access expires """ expires_at = self.get('expires_at') if expires_at: return dt.datetime.fromtimestamp(expires_at) else: # consider the token expired, add 10 second buffer to current dt return dt.datetime.now() - dt.timedelta(seconds=10) @property def is_access_expired(self): """ Returns whether or not the token's access is expired. :return bool: True if the token's access is expired, False otherwise """ return dt.datetime.now() > self.access_expiration_datetime class BaseTokenBackend(ABC): """ A base token storage class """ serializer = json # The default serializer is json token_constructor = Token # the default token constructor def __init__(self): self._token = None @property def token(self): """ The stored Token dict """ return self._token @token.setter def token(self, value): """ Setter to convert any token dict into Token instance """ if value and not isinstance(value, Token): value = Token(value) self._token = value @abstractmethod def load_token(self): """ Abstract method that will retrieve the oauth token """ raise NotImplementedError def get_token(self): """ Loads the token, stores it in the token property and returns it""" self.token = self.load_token() # store the token in the 'token' property return self.token @abstractmethod def save_token(self): """ Abstract method that will save the oauth token """ raise NotImplementedError def delete_token(self): """ Optional Abstract method to delete the token """ raise NotImplementedError def check_token(self): """ Optional Abstract method to check for the token existence """ raise NotImplementedError def should_refresh_token(self, con=None): """ This method is intended to be implemented for environments where multiple Connection instances are running on paralel. This method should check if it's time to refresh the token or not. The chosen backend can store a flag somewhere to answer this question. This can avoid race conditions between different instances trying to refresh the token at once, when only one should make the refresh. > This is an example of how to achieve this: > 1) Along with the token store a Flag > 2) The first to see the Flag as True must transacionally update it > to False. This method then returns True and therefore the > connection will refresh the token. > 3) The save_token method should be rewrited to also update the flag > back to True always. > 4) Meanwhile between steps 2 and 3, any other token backend checking > for this method should get the flag with a False value. > This method should then wait and check again the flag. > This can be implemented as a call with an incremental backoff > factor to avoid too many calls to the database. > At a given point in time, the flag will return True. > Then this method should load the token and finally return False > signaling there is no need to refresh the token. If this returns True, then the Connection will refresh the token. If this returns False, then the Connection will NOT refresh the token. If this returns None, then this method already executed the refresh and therefore the Connection does not have to. By default this always returns True There is an example of this in the examples folder. :param Connection con: the connection that calls this method. This is passed because maybe the locking mechanism needs to refresh the token within the lock applied in this method. :rtype: bool or None :return: True if the Connection can refresh the token False if the Connection should not refresh the token None if the token was refreshed and therefore the Connection should do nothing. """ return True class FileSystemTokenBackend(BaseTokenBackend): """ A token backend based on files on the filesystem """ def __init__(self, token_path=None, token_filename=None): """ Init Backend :param str or Path token_path: the path where to store the token :param str token_filename: the name of the token file """ super().__init__() if not isinstance(token_path, Path): token_path = Path(token_path) if token_path else Path() if token_path.is_file(): self.token_path = token_path else: token_filename = token_filename or 'o365_token.txt' self.token_path = token_path / token_filename def __repr__(self): return str(self.token_path) def load_token(self): """ Retrieves the token from the File System :return dict or None: The token if exists, None otherwise """ token = None if self.token_path.exists(): with self.token_path.open('r') as token_file: token = self.token_constructor(self.serializer.load(token_file)) return token def save_token(self): """ Saves the token dict in the specified file :return bool: Success / Failure """ if self.token is None: raise ValueError('You have to set the "token" first.') try: if not self.token_path.parent.exists(): self.token_path.parent.mkdir(parents=True) except Exception as e: log.error('Token could not be saved: {}'.format(str(e))) return False with self.token_path.open('w') as token_file: # 'indent = True' will make the file human readable self.serializer.dump(self.token, token_file, indent=True) return True def delete_token(self): """ Deletes the token file :return bool: Success / Failure """ if self.token_path.exists(): self.token_path.unlink() return True return False def check_token(self): """ Cheks if the token exists in the filesystem :return bool: True if exists, False otherwise """ return self.token_path.exists() class FirestoreBackend(BaseTokenBackend): """ A Google Firestore database backend to store tokens """ def __init__(self, client, collection, doc_id, field_name='token'): """ Init Backend :param firestore.Client client: the firestore Client instance :param str collection: the firestore collection where to store tokens (can be a field_path) :param str doc_id: # the key of the token document. Must be unique per-case. :param str field_name: the name of the field that stores the token in the document """ super().__init__() self.client = client self.collection = collection self.doc_id = doc_id self.doc_ref = client.collections(collection).document(doc_id) self.field_name = field_name def __repr__(self): return 'Collection: {}. Doc Id: {}'.format(self.collection, self.doc_id) def load_token(self): """ Retrieves the token from the store :return dict or None: The token if exists, None otherwise """ token = None try: doc = self.doc_ref.get() except Exception as e: log.error('Token (collection: {}, doc_id: {}) ' 'could not be retrieved from the backend: {}' .format(self.collection, self.doc_id, str(e))) doc = None if doc and doc.exists: token_str = doc.get(self.field_name) if token_str: token = self.token_constructor(self.serializer.loads(token_str)) return token def save_token(self): """ Saves the token dict in the store :return bool: Success / Failure """ if self.token is None: raise ValueError('You have to set the "token" first.') try: # set token will overwrite previous data self.doc_ref.set({ self.field_name: self.serializer.dumps(self.token) }) except Exception as e: log.error('Token could not be saved: {}'.format(str(e))) return False return True def delete_token(self): """ Deletes the token from the store :return bool: Success / Failure """ try: self.doc_ref.delete() except Exception as e: log.error('Could not delete the token (key: {}): {}'.format(self.doc_id, str(e))) return False return True def check_token(self): """ Checks if the token exists :return bool: True if it exists on the store """ try: doc = self.doc_ref.get() except Exception as e: log.error('Token (collection: {}, doc_id: {}) ' 'could not be retrieved from the backend: {}' .format(self.collection, self.doc_id, str(e))) doc = None return doc and doc.exists
34.884984
99
0.614434
7951911e862334f2e3d4d61beb828dcdbb48113c
13,107
py
Python
repo2docker/buildpacks/base.py
ryanlovett/repo2docker
e871f350765f10ac6adf8ddc548bb3244ea011ed
[ "BSD-3-Clause" ]
null
null
null
repo2docker/buildpacks/base.py
ryanlovett/repo2docker
e871f350765f10ac6adf8ddc548bb3244ea011ed
[ "BSD-3-Clause" ]
null
null
null
repo2docker/buildpacks/base.py
ryanlovett/repo2docker
e871f350765f10ac6adf8ddc548bb3244ea011ed
[ "BSD-3-Clause" ]
null
null
null
import textwrap import jinja2 import tarfile import io import os import re import logging import docker TEMPLATE = r""" FROM buildpack-deps:bionic # avoid prompts from apt ENV DEBIAN_FRONTEND=noninteractive # Set up locales properly RUN apt-get update && \ apt-get install --yes --no-install-recommends locales && \ apt-get purge && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && \ locale-gen ENV LC_ALL en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US.UTF-8 # Use bash as default shell, rather than sh ENV SHELL /bin/bash # Set up user ARG NB_USER ARG NB_UID ENV USER ${NB_USER} ENV HOME /home/${NB_USER} RUN adduser --disabled-password \ --gecos "Default user" \ --uid ${NB_UID} \ ${NB_USER} WORKDIR ${HOME} RUN apt-get update && \ apt-get install --yes --no-install-recommends \ {% for package in base_packages -%} {{ package }} \ {% endfor -%} && apt-get purge && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* {% if packages -%} RUN apt-get update && \ apt-get install --yes \ {% for package in packages -%} {{ package }} \ {% endfor -%} && apt-get purge && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* {% endif -%} EXPOSE 8888 {% if env -%} # Almost all environment variables {% for item in env -%} ENV {{item[0]}} {{item[1]}} {% endfor -%} {% endif -%} {% if path -%} # Special case PATH ENV PATH {{ ':'.join(path) }}:${PATH} {% endif -%} {% if build_script_files -%} # If scripts required during build are present, copy them {% for src, dst in build_script_files.items() %} COPY {{ src }} {{ dst }} {% endfor -%} {% endif -%} {% for sd in build_script_directives -%} {{sd}} {% endfor %} # Copy and chown stuff. This doubles the size of the repo, because # you can't actually copy as USER, only as root! Thanks, Docker! USER root COPY src/ ${HOME} RUN chown -R ${NB_USER}:${NB_USER} ${HOME} # Run assemble scripts! These will actually build the specification # in the repository into the image. {% for sd in assemble_script_directives -%} {{ sd }} {% endfor %} # Container image Labels! # Put these at the end, since we don't want to rebuild everything # when these change! Did I mention I hate Dockerfile cache semantics? {% for k, v in labels.items() -%} LABEL {{k}}={{v}} {%- endfor %} # We always want containers to run as non-root USER ${NB_USER} # Make sure that postBuild scripts are marked executable before executing them {% if post_build_scripts -%} {% for s in post_build_scripts -%} RUN chmod +x {{ s }} RUN ./{{ s }} {% endfor %} {% endif -%} # Specify the default command to run CMD ["jupyter", "notebook", "--ip", "0.0.0.0"] {% if appendix -%} # Appendix: {{ appendix }} {% endif %} """ class BuildPack: """ A composable BuildPack. Specifically used for creating Dockerfiles for use with repo2docker only. Things that are kept constant: - base image - some environment variables (such as locale) - user creation & ownership of home directory - working directory Everything that is configurable is additive & deduplicative, and there are *some* general guarantees of ordering. """ def __init__(self): self.log = logging.getLogger('repo2docker') self.appendix = '' def get_packages(self): """ List of packages that are installed in this BuildPack. Versions are not specified, and ordering is not guaranteed. These are usually installed as apt packages. """ return set() def get_base_packages(self): """ Base set of apt packages that are installed for all images. These contain useful images that are commonly used by a lot of images, where it would be useful to share a base docker image layer that contains them. These would be installed with a --no-install-recommends option. """ return { # Utils! "less", # FIXME: Use npm from nodesource! # Everything seems to depend on npm these days, unfortunately. "npm", "unzip", } def get_env(self): """ Ordered list of environment variables to be set for this image. Ordered so that environment variables can use other environment variables in their values. Expects tuples, with the first item being the environment variable name and the second item being the value. """ return [] def get_path(self): """ Ordered list of file system paths to look for executables in. Just sets the PATH environment variable. Separated out since it is very commonly set by various buildpacks. """ # Allow local user installs into ~/.local, which is where the # XDG desktop standard suggests these should be # See https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html return ['$HOME/.local/bin'] def get_labels(self): """ Docker labels to set on the built image. """ return {} def get_build_script_files(self): """ Dict of files to be copied to the container image for use in building. This is copied before the `build_scripts` & `assemble_scripts` are run, so can be executed from either of them. It's a dictionary where the key is the source file path in the host system, and the value is the destination file path inside the container image. """ return {} def get_build_scripts(self): """ Ordered list of shell script snippets to build the base image. A list of tuples, where the first item is a username & the second is a single logical line of a bash script that should be RUN as that user. These are run before the source of the repository is copied into the container image, and hence can not reference stuff from the repository. When the build scripts are done, the container image should be in a state where it is generically re-useable for building various other repositories with similar environments. You can use environment variable substitutions in both the username and the execution script. """ return [] def get_assemble_scripts(self): """ Ordered list of shell script snippets to build the repo into the image. A list of tuples, where the first item is a username & the second is a single logical line of a bash script that should be RUN as that user. These are run after the source of the repository is copied into the container image (into the current directory). These should be the scripts that actually build the repository into the container image. If this needs to be dynamically determined (based on the presence or absence of certain files, for example), you can create any method and decorate it with `traitlets.default('assemble_scripts)` and the return value of this method is used as the value of assemble_scripts. You can expect that the script is running in the current directory of the repository being built when doing dynamic detection. You can use environment variable substitutions in both the username and the execution script. """ return [] def get_post_build_scripts(self): """ An ordered list of executable scripts to execute after build. Is run as a non-root user, and must be executable. Used for doing things that are currently not supported by other means! The scripts should be as deterministic as possible - running it twice should not produce different results! """ return [] def binder_path(self, path): """Locate a file""" if os.path.exists('binder'): return os.path.join('binder', path) else: return path def detect(self): return True def render(self): """ Render BuildPack into Dockerfile """ t = jinja2.Template(TEMPLATE) build_script_directives = [] last_user = 'root' for user, script in self.get_build_scripts(): if last_user != user: build_script_directives.append("USER {}".format(user)) last_user = user build_script_directives.append("RUN {}".format( textwrap.dedent(script.strip('\n')) )) assemble_script_directives = [] last_user = 'root' for user, script in self.get_assemble_scripts(): if last_user != user: assemble_script_directives.append("USER {}".format(user)) last_user = user assemble_script_directives.append("RUN {}".format( textwrap.dedent(script.strip('\n')) )) return t.render( packages=sorted(self.get_packages()), path=self.get_path(), env=self.get_env(), labels=self.get_labels(), build_script_directives=build_script_directives, assemble_script_directives=assemble_script_directives, build_script_files=self.get_build_script_files(), base_packages=sorted(self.get_base_packages()), post_build_scripts=self.get_post_build_scripts(), appendix=self.appendix, ) def build(self, image_spec, memory_limit, build_args): tarf = io.BytesIO() tar = tarfile.open(fileobj=tarf, mode='w') dockerfile_tarinfo = tarfile.TarInfo("Dockerfile") dockerfile = self.render().encode('utf-8') dockerfile_tarinfo.size = len(dockerfile) tar.addfile( dockerfile_tarinfo, io.BytesIO(dockerfile) ) def _filter_tar(tar): # We need to unset these for build_script_files we copy into tar # Otherwise they seem to vary each time, preventing effective use # of the cache! # https://github.com/docker/docker-py/pull/1582 is related tar.uname = '' tar.gname = '' tar.uid = 1000 tar.gid = 1000 return tar for src in sorted(self.get_build_script_files()): src_parts = src.split('/') src_path = os.path.join(os.path.dirname(__file__), *src_parts) tar.add(src_path, src, filter=_filter_tar) tar.add('.', 'src/', filter=_filter_tar) tar.close() tarf.seek(0) limits = { # Always disable memory swap for building, since mostly # nothing good can come of that. 'memswap': -1 } if memory_limit: limits['memory'] = memory_limit client = docker.APIClient(version='auto', **docker.utils.kwargs_from_env()) for line in client.build( fileobj=tarf, tag=image_spec, custom_context=True, buildargs=build_args, decode=True, forcerm=True, rm=True, container_limits=limits ): yield line class BaseImage(BuildPack): def get_env(self): return [ ("APP_BASE", "/srv") ] def detect(self): return True def get_assemble_scripts(self): assemble_scripts = [] try: with open(self.binder_path('apt.txt')) as f: extra_apt_packages = [] for l in f: package = l.partition('#')[0].strip() if not package: continue # Validate that this is, indeed, just a list of packages # We're doing shell injection around here, gotta be careful. # FIXME: Add support for specifying version numbers if not re.match(r"^[a-z0-9.+-]+", package): raise ValueError("Found invalid package name {} in " "apt.txt".format(package)) extra_apt_packages.append(package) assemble_scripts.append(( 'root', r""" apt-get update && \ apt-get install --yes --no-install-recommends {} && \ apt-get purge && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* """.format(' '.join(extra_apt_packages)) )) except FileNotFoundError: pass return assemble_scripts def get_post_build_scripts(self): post_build = self.binder_path('postBuild') if os.path.exists(post_build): return [post_build] return []
30.410673
90
0.596246
795194f38e566cda3e3b91ed0ee504ef8cde2dca
3,168
py
Python
pymks/tests/test_structure_analysis.py
wd15/pymks-clean
97a4145c56626f6a1dea5c3a67dbaf83d3372446
[ "MIT" ]
null
null
null
pymks/tests/test_structure_analysis.py
wd15/pymks-clean
97a4145c56626f6a1dea5c3a67dbaf83d3372446
[ "MIT" ]
null
null
null
pymks/tests/test_structure_analysis.py
wd15/pymks-clean
97a4145c56626f6a1dea5c3a67dbaf83d3372446
[ "MIT" ]
null
null
null
import numpy as np def test_n_componets_from_reducer(): from pymks import MKSStructureAnalysis from pymks import DiscreteIndicatorBasis from sklearn.manifold import LocallyLinearEmbedding reducer = LocallyLinearEmbedding(n_components=7) dbasis = DiscreteIndicatorBasis(n_states=3, domain=[0, 2]) model = MKSStructureAnalysis(dimension_reducer=reducer, basis=dbasis) assert model.n_components == 7 def test_n_components_with_reducer(): from pymks import MKSStructureAnalysis from pymks import DiscreteIndicatorBasis from sklearn.manifold import Isomap reducer = Isomap(n_components=7) dbasis = DiscreteIndicatorBasis(n_states=3, domain=[0, 2]) model = MKSStructureAnalysis(dimension_reducer=reducer, basis=dbasis, n_components=9) assert model.n_components == 9 def test_n_components_change(): from pymks import MKSStructureAnalysis from pymks import DiscreteIndicatorBasis dbasis = DiscreteIndicatorBasis(n_states=2) model = MKSStructureAnalysis(basis=dbasis) model.n_components = 27 assert model.n_components == 27 def test_default_n_components(): from pymks import MKSStructureAnalysis from pymks import DiscreteIndicatorBasis dbasis = DiscreteIndicatorBasis(n_states=2) model = MKSStructureAnalysis(basis=dbasis) assert model.n_components == 5 def test_default_dimension_reducer(): from sklearn.decomposition import RandomizedPCA from pymks import MKSStructureAnalysis from pymks import PrimitiveBasis model = MKSStructureAnalysis(basis=PrimitiveBasis()) assert isinstance(model.dimension_reducer, RandomizedPCA) def test_default_correlations(): from pymks import PrimitiveBasis from pymks import MKSStructureAnalysis prim_basis = PrimitiveBasis(6) model_prim = MKSStructureAnalysis(basis=prim_basis) assert model_prim.correlations == [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5)] def test_set_correlations(): from pymks import PrimitiveBasis from pymks import MKSStructureAnalysis test_correlations = [(0, 0), (0, 2), (0, 4)] prim_basis = PrimitiveBasis(6) model_prim = MKSStructureAnalysis(basis=prim_basis, correlations=test_correlations) assert model_prim.correlations == test_correlations def test_reshape_X(): from pymks import MKSStructureAnalysis from pymks import PrimitiveBasis anaylzer = MKSStructureAnalysis(basis=PrimitiveBasis()) X = np.arange(18).reshape(2, 3, 3) X_test = np.concatenate((np.arange(-4, 5)[None], np.arange(-4, 5)[None])) assert np.allclose(anaylzer._reduce_shape(X), X_test) def test_set_components(): from pymks import MKSStructureAnalysis from pymks import PrimitiveBasis p_basis = PrimitiveBasis(2) model = MKSStructureAnalysis(basis=p_basis) X = np.random.randint(2, size=(50, 10, 10)) model.fit(X) components = model.components_ model.components_ = components * 2 assert np.allclose(model.components_, components * 2) if __name__ == '__main__': test_set_correlations()
34.813187
77
0.726641
7951951eb0c2b19e4dee5a738ed7c192afc813cf
1,876
py
Python
tests/test_noise_dropout.py
marco-willi/HiDDeN-tensorflow
f657b41ee145452f6b187b99f8c26fa4af2fba79
[ "MIT" ]
null
null
null
tests/test_noise_dropout.py
marco-willi/HiDDeN-tensorflow
f657b41ee145452f6b187b99f8c26fa4af2fba79
[ "MIT" ]
null
null
null
tests/test_noise_dropout.py
marco-willi/HiDDeN-tensorflow
f657b41ee145452f6b187b99f8c26fa4af2fba79
[ "MIT" ]
null
null
null
import tensorflow as tf import numpy as np from noise import dropout class DropOutTest(tf.test.TestCase): def setUp(self): self.layer = dropout.Dropout() def testEqualityAcrossChannels(self): """ Test that samples across channels are identical """ # Test simple binary case input_image = tf.ones((1, 12, 12, 3)) background_image = tf.zeros((1, 12, 12, 3)) res = self.layer((input_image, background_image)) channels = tf.split(res, res.shape[-1], axis=-1) with self.cached_session(use_gpu=False): self.assertAllEqual(channels[0], channels[1]) self.assertAllEqual(channels[1], channels[2]) def testMutabilityOnDifferentCalls(self): """ Confirm that different invocations of the layer lead to different samplings """ input_image = tf.ones((1, 1000, 1000, 1)) background_image = tf.zeros((1, 1000, 1000, 1)) res1 = self.layer((input_image, background_image), 0.5) res2 = self.layer((input_image, background_image), 0.5) with self.cached_session(use_gpu=False): self.assertNotAllEqual(res1, res2) def testMultipleSamplingProportions(self): with self.cached_session(use_gpu=False): input_image = tf.ones((1, 1000, 1000, 1)) background_image = tf.zeros((1, 1000, 1000, 1)) keep_probs = [0, 0.1, 0.5, 0.9, 1.0] for keep_prob in keep_probs: res = self.layer((input_image, background_image), keep_prob) total_shape = np.prod(res.shape) actual = tf.reduce_sum(res) / total_shape actual = actual.numpy() expected = 1.0 * keep_prob self.assertAlmostEqual(actual, expected, places=2) if __name__ == '__main__': tf.test.main(argv=None)
33.5
76
0.61194
795195e52893a6d95f30cc5b9a8722293f88ad6e
906
py
Python
ros/src/twist_controller/pid.py
TeamDoernbach/SDCNanodegreeCapstone
10bdc59dc1b8f56136bf3f6f4ab64c97082420bb
[ "MIT" ]
4
2019-01-04T07:32:33.000Z
2019-08-08T17:25:11.000Z
ros/src/twist_controller/pid.py
TeamDoernbach/SDCNanodegreeCapstone
10bdc59dc1b8f56136bf3f6f4ab64c97082420bb
[ "MIT" ]
19
2019-01-04T13:42:56.000Z
2019-01-21T20:10:41.000Z
ros/src/twist_controller/pid.py
TeamDoernbach/SDCNanodegreeCapstone
10bdc59dc1b8f56136bf3f6f4ab64c97082420bb
[ "MIT" ]
4
2019-01-08T21:54:54.000Z
2019-12-14T04:47:55.000Z
import rospy MIN_NUM = float('-inf') MAX_NUM = float('inf') class PID(object): def __init__(self, kp, ki, kd, mn=MIN_NUM, mx=MAX_NUM): self.kp = kp self.ki = ki self.kd = kd self.min = mn self.max = mx self.int_val = self.last_error = 0. def reset(self): self.int_val = 0.0 def step(self, error, sample_time): integral = self.int_val + error * sample_time; derivative = (error - self.last_error) / sample_time; val = self.kp * error + self.ki * integral + self.kd * derivative; if val > self.max: val = self.max elif val < self.min: val = self.min else: self.int_val = integral self.last_error = error #rospy.logwarn("Throttle: {0}"".format(val)) #rospy.logwarn("Velocity error: {0}"".format(error)) return val
23.230769
74
0.548565
79519655d0a6ae3137e97e0a4164ff503642be9f
4,226
py
Python
pyod/test/test_so_gaal.py
g0lemXIV/pyod
eb3a920d4b72e69f0529d4fde83c9b76ce5e163b
[ "BSD-2-Clause" ]
5,126
2018-11-09T06:05:38.000Z
2022-03-31T14:25:14.000Z
pyod/test/test_so_gaal.py
durgeshsamariya/pyod
dfafc57f74dc3d49d0166f21ab2ddb97e3d1d898
[ "BSD-2-Clause" ]
325
2018-11-14T20:02:39.000Z
2022-03-30T22:49:38.000Z
pyod/test/test_so_gaal.py
durgeshsamariya/pyod
dfafc57f74dc3d49d0166f21ab2ddb97e3d1d898
[ "BSD-2-Clause" ]
1,049
2018-11-09T06:12:12.000Z
2022-03-31T06:21:28.000Z
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function import os import sys import unittest # noinspection PyProtectedMember from numpy.testing import assert_allclose from numpy.testing import assert_array_less from numpy.testing import assert_equal from numpy.testing import assert_raises from sklearn.metrics import roc_auc_score from sklearn.base import clone # temporary solution for relative imports in case pyod is not installed # if pyod is installed, no need to use the following line sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from pyod.models.so_gaal import SO_GAAL from pyod.utils.data import generate_data from pyod.utils.data import evaluate_print class TestSO_GAAL(unittest.TestCase): """ Notes: GAN may yield unstable results, so the test is design for running models only, without any performance check. """ def setUp(self): self.n_train = 1000 self.n_test = 200 self.n_features = 2 self.contamination = 0.1 # GAN may yield unstable results; turning performance check off # self.roc_floor = 0.8 self.X_train, self.y_train, self.X_test, self.y_test = generate_data( n_train=self.n_train, n_test=self.n_test, n_features=self.n_features, contamination=self.contamination, random_state=42) self.clf = SO_GAAL(contamination=self.contamination) self.clf.fit(self.X_train) def test_parameters(self): assert (hasattr(self.clf, 'decision_scores_') and self.clf.decision_scores_ is not None) assert (hasattr(self.clf, 'labels_') and self.clf.labels_ is not None) assert (hasattr(self.clf, 'threshold_') and self.clf.threshold_ is not None) assert (hasattr(self.clf, '_mu') and self.clf._mu is not None) assert (hasattr(self.clf, '_sigma') and self.clf._sigma is not None) assert (hasattr(self.clf, 'discriminator') and self.clf.discriminator is not None) def test_train_scores(self): assert_equal(len(self.clf.decision_scores_), self.X_train.shape[0]) def test_prediction_scores(self): pred_scores = self.clf.decision_function(self.X_test) # check score shapes assert_equal(pred_scores.shape[0], self.X_test.shape[0]) # check performance # assert (roc_auc_score(self.y_test, pred_scores) >= self.roc_floor) def test_prediction_labels(self): pred_labels = self.clf.predict(self.X_test) assert_equal(pred_labels.shape, self.y_test.shape) def test_prediction_proba(self): pred_proba = self.clf.predict_proba(self.X_test) assert (pred_proba.min() >= 0) assert (pred_proba.max() <= 1) def test_prediction_proba_linear(self): pred_proba = self.clf.predict_proba(self.X_test, method='linear') assert (pred_proba.min() >= 0) assert (pred_proba.max() <= 1) def test_prediction_proba_unify(self): pred_proba = self.clf.predict_proba(self.X_test, method='unify') assert (pred_proba.min() >= 0) assert (pred_proba.max() <= 1) def test_prediction_proba_parameter(self): with assert_raises(ValueError): self.clf.predict_proba(self.X_test, method='something') def test_fit_predict(self): pred_labels = self.clf.fit_predict(self.X_train) assert_equal(pred_labels.shape, self.y_train.shape) def test_fit_predict_score(self): self.clf.fit_predict_score(self.X_test, self.y_test) self.clf.fit_predict_score(self.X_test, self.y_test, scoring='roc_auc_score') self.clf.fit_predict_score(self.X_test, self.y_test, scoring='prc_n_score') with assert_raises(NotImplementedError): self.clf.fit_predict_score(self.X_test, self.y_test, scoring='something') def test_model_clone(self): clone_clf = clone(self.clf) def tearDown(self): pass if __name__ == '__main__': unittest.main()
35.216667
79
0.666588
79519721e261f6c0ab7fd1c0814c29e61c8fb891
2,014
py
Python
forms/role_form.py
qwc-services/sogis-agdi
f278612c42f648da07448905f2b8021b279e66bc
[ "MIT" ]
null
null
null
forms/role_form.py
qwc-services/sogis-agdi
f278612c42f648da07448905f2b8021b279e66bc
[ "MIT" ]
null
null
null
forms/role_form.py
qwc-services/sogis-agdi
f278612c42f648da07448905f2b8021b279e66bc
[ "MIT" ]
null
null
null
from flask_wtf import FlaskForm from wtforms import FieldList, FormField, HiddenField, SelectField, \ StringField, SubmitField, TextAreaField, ValidationError from wtforms.validators import DataRequired, Optional class GroupForm(FlaskForm): """Subform for groups""" group_id = HiddenField('Gruppen-ID', validators=[DataRequired()]) group_name = HiddenField('Gruppe', validators=[Optional()]) class UserForm(FlaskForm): """Subform for users""" user_id = HiddenField('Benutzer-ID', validators=[DataRequired()]) user_name = HiddenField('Benutzer', validators=[Optional()]) class RoleForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) description = TextAreaField('Beschreibung', validators=[DataRequired()]) groups = FieldList(FormField(GroupForm)) group = SelectField( 'Zugeordnete Gruppen', coerce=int, validators=[Optional()] ) users = FieldList(FormField(UserForm)) user = SelectField( 'Zugeordnete Benutzer', coerce=int, validators=[Optional()] ) submit = SubmitField('Speichern') def __init__(self, config_models, **kwargs): """Constructor :param ConfigModels config_models: Helper for ORM models """ self.config_models = config_models self.Role = self.config_models.model('role') # store any provided role object self.obj = kwargs.get('obj') super(RoleForm, self).__init__(**kwargs) def validate_name(self, field): """Validate uniqueness of name""" # check if role name exists session = self.config_models.session() query = session.query(self.Role).filter_by(name=field.data) if self.obj: # ignore current role query = query.filter(self.Role.id != self.obj.id) role = query.first() session.close() if role is not None: raise ValidationError( 'Eine Rolle mit diesem Namen ist bereits vorhanden' )
33.016393
76
0.658888
795197bbd9ff3061195bb50ee5c4315a41d868ea
2,346
py
Python
tests/test_Vitodens222W.py
sskrlj/PyViCare
3a54b8e73e5b72cf04a28b2827ccb01e12fa8810
[ "Apache-2.0" ]
null
null
null
tests/test_Vitodens222W.py
sskrlj/PyViCare
3a54b8e73e5b72cf04a28b2827ccb01e12fa8810
[ "Apache-2.0" ]
null
null
null
tests/test_Vitodens222W.py
sskrlj/PyViCare
3a54b8e73e5b72cf04a28b2827ccb01e12fa8810
[ "Apache-2.0" ]
null
null
null
import unittest from PyViCare.PyViCareGazBoiler import GazBoiler from PyViCare.PyViCareUtils import PyViCareNotSupportedFeatureError from tests.ViCareServiceMock import ViCareServiceMock class Vitodens222W(unittest.TestCase): def setUp(self): self.service = ViCareServiceMock('response/Vitodens222W.json') self.device = GazBoiler(self.service) def test_getBurnerActive(self): self.assertEqual(self.device.getBurnerActive(), False) def test_getBurnerStarts(self): self.assertEqual(self.device.burners[0].getStarts(), 79167) def test_getBurnerHours(self): self.assertEqual(self.device.burners[0].getHours(), 25123.2) def test_getBurnerModulation(self): self.assertEqual(self.device.burners[0].getModulation(), 0) def test_getPrograms(self): expected_programs = ['active', 'comfort', 'eco', 'external', 'holiday', 'normal', 'reduced', 'standby'] self.assertListEqual( self.device.circuits[0].getPrograms(), expected_programs) def test_getModes(self): expected_modes = ['standby', 'dhw', 'dhwAndHeating', 'forcedReduced', 'forcedNormal'] self.assertListEqual( self.device.circuits[0].getModes(), expected_modes) def test_getPowerConsumptionDays(self): self.assertRaises(PyViCareNotSupportedFeatureError, self.device.getPowerConsumptionDays) def test_getFrostProtectionActive(self): self.assertEqual( self.device.circuits[0].getFrostProtectionActive(), False) def test_getDomesticHotWaterCirculationPumpActive(self): self.assertEqual( self.device.getDomesticHotWaterCirculationPumpActive(), False) def test_getDomesticHotWaterOutletTemperature(self): self.assertEqual( self.device.getDomesticHotWaterOutletTemperature(), 44.8) def test_getDomesticHotWaterCirculationScheduleModes(self): self.assertEqual( self.device.getDomesticHotWaterCirculationScheduleModes(), ['on']) def test_getOutsideTemperature(self): self.assertEqual( self.device.getOutsideTemperature(), 16.3) def test_getBoilerTemperature(self): self.assertEqual( self.device.getBoilerTemperature(), 73)
36.65625
83
0.693947
795197c577e8827839bf583bc48326a708b90443
915
py
Python
users/migrations/0001_initial.py
tanmayag8958/upes-fipi-jigyasa
e05e41e7624175ae64216a54cc546bbb74b2df61
[ "MIT" ]
8
2019-03-08T10:28:38.000Z
2019-10-17T00:04:44.000Z
users/migrations/0001_initial.py
tanmayag8958/upes-fipi-jigyasa
e05e41e7624175ae64216a54cc546bbb74b2df61
[ "MIT" ]
124
2020-02-11T23:51:09.000Z
2022-01-13T01:06:09.000Z
users/migrations/0001_initial.py
tanmayag8958/upes-fipi-jigyasa
e05e41e7624175ae64216a54cc546bbb74b2df61
[ "MIT" ]
3
2019-03-07T18:44:55.000Z
2019-03-08T10:36:50.000Z
# Generated by Django 2.1.7 on 2019-03-04 21:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='User_details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('team_count', models.IntegerField()), ('date_registered', models.DateTimeField(default=django.utils.timezone.now)), ('trans_id', models.TextField()), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
31.551724
121
0.64153
795197dfa3f5f6dcc66385ec31391f6581b14dc2
728
py
Python
firmware/eppenwolf/host/test/test_.py
0xDBFB7/covidinator
e9c103e5e62bc128169400998df5f5cd13bd8949
[ "MIT" ]
null
null
null
firmware/eppenwolf/host/test/test_.py
0xDBFB7/covidinator
e9c103e5e62bc128169400998df5f5cd13bd8949
[ "MIT" ]
null
null
null
firmware/eppenwolf/host/test/test_.py
0xDBFB7/covidinator
e9c103e5e62bc128169400998df5f5cd13bd8949
[ "MIT" ]
null
null
null
import sys sys.path.append('/home/arthurdent/covidinator/firmware/eppendoofus/host/') import device_comms from device_comms import * import pytest from functions import * link = device_comms.connect() def test_loopback(): send_size = 0 float_ = 563.5 send_size = add_float(link, send_size, float_) link.send(send_size, packet_id=10) wait_for_response(link) pos = 0 val, pos = rx_float(link, pos) clear_buffers(link) assert val == pytest.approx(float_) assert link.idByte == 10 def test_VCO_driver(): set_VCO(link, 3, 2, 1, 0); # def test_turbidimeter(): print(sample_turbidity(link)) def test_relative_move(): move_relative(link, 0,10) move_relative(link, 1,10)
19.675676
74
0.703297
795198b6c0286b3d0b39a0ad5cf25ad2dfb8ae9b
1,218
py
Python
demo_stock/A_1day/D04_download_pb_lf.py
jiangtiantu/kquant_data
9bd47ba23c23110757186897e37ea36234bdce2c
[ "BSD-2-Clause" ]
23
2017-08-05T04:35:47.000Z
2020-12-16T09:40:08.000Z
demo_stock/A_1day/D04_download_pb_lf.py
jiangtiantu/kquant_data
9bd47ba23c23110757186897e37ea36234bdce2c
[ "BSD-2-Clause" ]
2
2017-08-05T04:57:10.000Z
2018-04-14T14:52:39.000Z
demo_stock/A_1day/D04_download_pb_lf.py
wukan1986/kquant_data
9bd47ba23c23110757186897e37ea36234bdce2c
[ "BSD-2-Clause" ]
21
2017-08-01T09:56:30.000Z
2021-07-10T01:19:39.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 下载财报一类的信息 """ import os import pandas as pd from WindPy import w from kquant_data.xio.csv import write_data_dataframe, read_data_dataframe from kquant_data.api import all_instruments from kquant_data.wind_resume.wsd import download_daily_at from kquant_data.config import __CONFIG_H5_STK_FACTOR_DIR__, __CONFIG_H5_STK_DIR__ if __name__ == '__main__': w.start() path = os.path.join(__CONFIG_H5_STK_DIR__, '1day', 'Symbol.csv') Symbols = all_instruments(path) wind_codes = list(Symbols['wind_code']) # 下载多天数据,以另一数据做为标准来下载 # 比如交易数据是10月8号,那就得取10月7号,然后再平移到8号,如果7号没有数据那就得9月30号 path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, 'roe.csv') date_index = read_data_dataframe(path) field = 'pb_lf' df = None for i in range(len(date_index)): print(date_index.index[i]) date_str = date_index.index[i].strftime('%Y-%m-%d') df_new = download_daily_at(w, wind_codes, field, date_str, "Days=Alldays") if df is None: df = df_new else: df = pd.concat([df, df_new]) path = os.path.join(__CONFIG_H5_STK_FACTOR_DIR__, '%s.csv' % field) write_data_dataframe(path, df)
29.707317
82
0.698686
795198d3c78443fdf26464ac308d9cb9b169b7ba
1,836
py
Python
djmodels/db/backends/mysql/client.py
iMerica/dj-models
fbe4a55ac362f9355a2298f58aa0deb0b6082e19
[ "BSD-3-Clause" ]
5
2019-02-15T16:47:50.000Z
2021-12-26T18:52:23.000Z
djmodels/db/backends/mysql/client.py
iMerica/dj-models
fbe4a55ac362f9355a2298f58aa0deb0b6082e19
[ "BSD-3-Clause" ]
null
null
null
djmodels/db/backends/mysql/client.py
iMerica/dj-models
fbe4a55ac362f9355a2298f58aa0deb0b6082e19
[ "BSD-3-Clause" ]
2
2021-08-09T02:29:09.000Z
2021-08-20T03:30:11.000Z
import subprocess from djmodels.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = 'mysql' @classmethod def settings_to_cmd_args(cls, settings_dict): args = [cls.executable_name] db = settings_dict['OPTIONS'].get('db', settings_dict['NAME']) user = settings_dict['OPTIONS'].get('user', settings_dict['USER']) passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD']) host = settings_dict['OPTIONS'].get('host', settings_dict['HOST']) port = settings_dict['OPTIONS'].get('port', settings_dict['PORT']) server_ca = settings_dict['OPTIONS'].get('ssl', {}).get('ca') client_cert = settings_dict['OPTIONS'].get('ssl', {}).get('cert') client_key = settings_dict['OPTIONS'].get('ssl', {}).get('key') defaults_file = settings_dict['OPTIONS'].get('read_default_file') # Seems to be no good way to set sql_mode with CLI. if defaults_file: args += ["--defaults-file=%s" % defaults_file] if user: args += ["--user=%s" % user] if passwd: args += ["--password=%s" % passwd] if host: if '/' in host: args += ["--socket=%s" % host] else: args += ["--host=%s" % host] if port: args += ["--port=%s" % port] if server_ca: args += ["--ssl-ca=%s" % server_ca] if client_cert: args += ["--ssl-cert=%s" % client_cert] if client_key: args += ["--ssl-key=%s" % client_key] if db: args += [db] return args def runshell(self): args = DatabaseClient.settings_to_cmd_args(self.connection.settings_dict) subprocess.check_call(args)
37.469388
82
0.566993
79519b5a9eda35b7f070eda0fdb8119cce8e9fad
3,591
py
Python
tests/unit/publisher/test_neo4j_preprocessor.py
Gusto/amundsendatabuilder-1
d24cba9d51795f908c8325d847e020b3c949f34a
[ "Apache-2.0" ]
1
2020-08-20T16:22:07.000Z
2020-08-20T16:22:07.000Z
tests/unit/publisher/test_neo4j_preprocessor.py
Gusto/amundsendatabuilder-1
d24cba9d51795f908c8325d847e020b3c949f34a
[ "Apache-2.0" ]
2
2020-07-20T16:03:49.000Z
2020-08-14T16:14:10.000Z
tests/unit/publisher/test_neo4j_preprocessor.py
Gusto/amundsendatabuilder-1
d24cba9d51795f908c8325d847e020b3c949f34a
[ "Apache-2.0" ]
null
null
null
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import textwrap import unittest import uuid from databuilder.publisher.neo4j_preprocessor import NoopRelationPreprocessor, DeleteRelationPreprocessor class TestNeo4jPreprocessor(unittest.TestCase): def testNoopRelationPreprocessor(self): # type () -> None preprocessor = NoopRelationPreprocessor() self.assertTrue(not preprocessor.is_perform_preprocess()) def testDeleteRelationPreprocessor(self): # noqa: W293 preprocessor = DeleteRelationPreprocessor() self.assertTrue(preprocessor.is_perform_preprocess()) preprocessor.filter(start_label='foo_label', end_label='bar_label', start_key='foo_key', end_key='bar_key', relation='foo_relation', reverse_relation='bar_relation') self.assertTrue(preprocessor.filter(start_label=str(uuid.uuid4()), end_label=str(uuid.uuid4()), start_key=str(uuid.uuid4()), end_key=str(uuid.uuid4()), relation=str(uuid.uuid4()), reverse_relation=str(uuid.uuid4()))) actual = preprocessor.preprocess_cypher(start_label='foo_label', end_label='bar_label', start_key='foo_key', end_key='bar_key', relation='foo_relation', reverse_relation='bar_relation') expected = (textwrap.dedent(""" MATCH (n1:foo_label {key: $start_key })-[r]-(n2:bar_label {key: $end_key }) WITH r LIMIT 2 DELETE r RETURN count(*) as count; """), {'start_key': 'foo_key', 'end_key': 'bar_key'}) self.assertEqual(expected, actual) def testDeleteRelationPreprocessorFilter(self): preprocessor = DeleteRelationPreprocessor(label_tuples=[('foo', 'bar')]) self.assertTrue(preprocessor.filter(start_label='foo', end_label='bar', start_key=str(uuid.uuid4()), end_key=str(uuid.uuid4()), relation=str(uuid.uuid4()), reverse_relation=str(uuid.uuid4()))) self.assertTrue(preprocessor.filter(start_label='bar', end_label='foo', start_key=str(uuid.uuid4()), end_key=str(uuid.uuid4()), relation=str(uuid.uuid4()), reverse_relation=str(uuid.uuid4()))) self.assertFalse(preprocessor.filter(start_label='foz', end_label='baz', start_key=str(uuid.uuid4()), end_key=str(uuid.uuid4()), relation=str(uuid.uuid4()), reverse_relation=str(uuid.uuid4()))) if __name__ == '__main__': unittest.main()
43.792683
105
0.470899
79519b88f8ca7bcdf899b5787ef61c573ba6cadd
2,719
py
Python
chainer_chemistry/links/update/schnet_update.py
k-ishiguro/chainer-chemistry
aec33496def16e76bdfbefa508ba01ab9f79a592
[ "MIT" ]
1
2019-06-19T00:05:59.000Z
2019-06-19T00:05:59.000Z
chainer_chemistry/links/update/schnet_update.py
k-ishiguro/chainer-chemistry
aec33496def16e76bdfbefa508ba01ab9f79a592
[ "MIT" ]
null
null
null
chainer_chemistry/links/update/schnet_update.py
k-ishiguro/chainer-chemistry
aec33496def16e76bdfbefa508ba01ab9f79a592
[ "MIT" ]
1
2020-10-12T07:23:44.000Z
2020-10-12T07:23:44.000Z
""" Chainer implementation of CFConv. SchNet: A continuous-filter convolutional neural network for modeling quantum interactions Kristof et al. See: https://arxiv.org/abs/1706.08566 """ import chainer from chainer import functions from chainer import links from chainer_chemistry.links.connection.graph_linear import GraphLinear class CFConv(chainer.Chain): def __init__(self, num_rbf=300, radius_resolution=0.1, gamma=10.0, hidden_dim=64): super(CFConv, self).__init__() with self.init_scope(): self.dense1 = links.Linear(num_rbf, hidden_dim) self.dense2 = links.Linear(hidden_dim) self.hidden_dim = hidden_dim self.num_rbf = num_rbf self.radius_resolution = radius_resolution self.gamma = gamma def __call__(self, h, dist): """ Args: h (numpy.ndarray): axis 0 represents minibatch index, axis 1 represents atom_index and axis2 represents feature dimension. dist (numpy.ndarray): axis 0 represents minibatch index, axis 1 and 2 represent distance between atoms. """ mb, atom, ch = h.shape if ch != self.hidden_dim: raise ValueError('h.shape[2] {} and hidden_dim {} must be same!' .format(ch, self.hidden_dim)) embedlist = self.xp.arange( self.num_rbf).astype('f') * self.radius_resolution dist = functions.reshape(dist, (mb, atom, atom, 1)) dist = functions.broadcast_to(dist, (mb, atom, atom, self.num_rbf)) dist = functions.exp(- self.gamma * (dist - embedlist) ** 2) dist = functions.reshape(dist, (-1, self.num_rbf)) dist = self.dense1(dist) dist = functions.softplus(dist) dist = self.dense2(dist) dist = functions.softplus(dist) dist = functions.reshape(dist, (mb, atom, atom, self.hidden_dim)) h = functions.reshape(h, (mb, atom, 1, self.hidden_dim)) h = functions.broadcast_to(h, (mb, atom, atom, self.hidden_dim)) h = functions.sum(h * dist, axis=1) return h class SchNetUpdate(chainer.Chain): def __init__(self, hidden_dim=64): super(SchNetUpdate, self).__init__() with self.init_scope(): self.linear = chainer.ChainList( *[GraphLinear(hidden_dim) for _ in range(3)]) self.cfconv = CFConv(hidden_dim=hidden_dim) self.hidden_dim = hidden_dim def __call__(self, x, dist): v = self.linear[0](x) v = self.cfconv(v, dist) v = self.linear[1](v) v = functions.softplus(v) v = self.linear[2](v) return x + v
35.776316
76
0.612357
79519b905b9daad63c8348993c0ebddefd88df38
3,840
py
Python
script popolamento DB/env/lib/python3.7/site-packages/setuptools/command/install_lib.py
2dadsgn/Smart-vase-webapp-flask-
0714d960ec21c77be069dd07b1bc8407f33e0b72
[ "Apache-2.0" ]
null
null
null
script popolamento DB/env/lib/python3.7/site-packages/setuptools/command/install_lib.py
2dadsgn/Smart-vase-webapp-flask-
0714d960ec21c77be069dd07b1bc8407f33e0b72
[ "Apache-2.0" ]
null
null
null
script popolamento DB/env/lib/python3.7/site-packages/setuptools/command/install_lib.py
2dadsgn/Smart-vase-webapp-flask-
0714d960ec21c77be069dd07b1bc8407f33e0b72
[ "Apache-2.0" ]
null
null
null
import distutils.command.install_lib as orig import imp import os from itertools import product, starmap class install_lib(orig.install_lib): """Don't add compiled flags to filenames of non-Python files""" def run(self): self.build() outfiles = self.install() if outfiles is not None: # always compile, in case we have any extension stubs to deal with self.byte_compile(outfiles) def get_exclusions(self): """ Return a collections.Sized collections.Container of paths to be excluded for single_version_externally_managed installations. """ all_packages = ( pkg for ns_pkg in self._get_SVEM_NSPs() for pkg in self._all_packages(ns_pkg) ) excl_specs = product(all_packages, self._gen_exclusion_paths()) return set(starmap(self._exclude_pkg_path, excl_specs)) def _exclude_pkg_path(self, pkg, exclusion_path): """ Given a package name and exclusion path within that package, compute the full exclusion path. """ parts = pkg.split('.') + [exclusion_path] return os.path.join(self.install_dir, *parts) @staticmethod def _all_packages(pkg_name): """ >>> list(install_lib._all_packages('foo.bar.baz')) ['foo.bar.baz', 'foo.bar', 'foo'] """ while pkg_name: yield pkg_name pkg_name, sep, child = pkg_name.rpartition('.') def _get_SVEM_NSPs(self): """ Get namespace packages (list) but only for single_version_externally_managed installations and empty otherwise. """ # TODO: is it necessary to short-circuit here? i.e. what's the cost # if get_finalized_command is called even when namespace_packages is # False? if not self.distribution.namespace_packages: return [] install_cmd = self.get_finalized_command('install') svem = install_cmd.single_version_externally_managed return self.distribution.namespace_packages if svem else [] @staticmethod def _gen_exclusion_paths(): """ Generate file paths to be excluded for namespace packages (bytecode cache files). """ # always exclude the package module itself yield '__init__.py' yield '__init__.pyc' yield '__init__.pyo' if not hasattr(imp, 'get_tag'): return base = os.path.join('__pycache__', '__init__.' + imp.get_tag()) yield base + '.pyc' yield base + '.pyo' yield base + '.opt-1.pyc' yield base + '.opt-2.pyc' def copy_tree( self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1 ): assert preserve_mode and preserve_times and not preserve_symlinks exclude = self.get_exclusions() if not exclude: return orig.install_lib.copy_tree(self, infile, outfile) # Exclude namespace package __init__.py* files from the output from setuptools.archive_util import unpack_directory from distutils import log outfiles = [] def pf(src, dst): if dst in exclude: log.warn("Skipping installation of %s (namespace package)", dst) return False log.info("copying %s -> %s", src, os.path.dirname(dst)) outfiles.append(dst) return dst unpack_directory(infile, outfile, pf) return outfiles def get_outputs(self): outputs = orig.install_lib.get_outputs(self) exclude = self.get_exclusions() if exclude: return [f for f in outputs if f not in exclude] return outputs
31.47541
78
0.611719
79519c66e27cf9955710d533d1ac316a00aa83ad
5,587
py
Python
grr/server/grr_response_server/gui/api_e2e_tests/vfs_test.py
billstackpole/grr
203a0a99990a2d4004aed84a5cd822cbda2b418c
[ "Apache-2.0" ]
1
2019-03-28T07:09:41.000Z
2019-03-28T07:09:41.000Z
grr/server/grr_response_server/gui/api_e2e_tests/vfs_test.py
gingogo/grr
203a0a99990a2d4004aed84a5cd822cbda2b418c
[ "Apache-2.0" ]
null
null
null
grr/server/grr_response_server/gui/api_e2e_tests/vfs_test.py
gingogo/grr
203a0a99990a2d4004aed84a5cd822cbda2b418c
[ "Apache-2.0" ]
1
2018-08-30T14:50:24.000Z
2018-08-30T14:50:24.000Z
#!/usr/bin/env python # -*- mode: python; encoding: utf-8 -*- """Tests for API client and VFS-related API calls.""" import io import threading import time import zipfile from grr_response_core.lib import flags from grr_response_core.lib import rdfvalue from grr_response_proto.api import vfs_pb2 from grr_response_server import aff4 from grr_response_server.gui import api_e2e_test_lib from grr.test_lib import fixture_test_lib from grr.test_lib import flow_test_lib from grr.test_lib import test_lib class ApiClientLibVfsTest(api_e2e_test_lib.ApiE2ETest): """Tests VFS operations part of GRR Python API client library.""" def setUp(self): super(ApiClientLibVfsTest, self).setUp() self.client_urn = self.SetupClient(0) fixture_test_lib.ClientFixture(self.client_urn, self.token) def testGetFileFromRef(self): file_ref = self.api.Client( client_id=self.client_urn.Basename()).File("fs/os/c/Downloads/a.txt") self.assertEqual(file_ref.path, "fs/os/c/Downloads/a.txt") file_obj = file_ref.Get() self.assertEqual(file_obj.path, "fs/os/c/Downloads/a.txt") self.assertFalse(file_obj.is_directory) self.assertEqual(file_obj.data.name, "a.txt") def testGetFileForDirectory(self): file_obj = self.api.Client( client_id=self.client_urn.Basename()).File("fs/os/c/Downloads").Get() self.assertEqual(file_obj.path, "fs/os/c/Downloads") self.assertTrue(file_obj.is_directory) def testListFiles(self): files_iter = self.api.Client(client_id=self.client_urn.Basename()).File( "fs/os/c/Downloads").ListFiles() files_list = list(files_iter) self.assertEqual( sorted(f.data.name for f in files_list), sorted( [u"a.txt", u"b.txt", u"c.txt", u"d.txt", u"sub1", u"中国新闻网新闻中.txt"])) def testGetBlob(self): out = io.BytesIO() self.api.Client(client_id=self.client_urn.Basename()).File( "fs/tsk/c/bin/rbash").GetBlob().WriteToStream(out) self.assertEqual(out.getvalue(), "Hello world") def testGetBlobUnicode(self): aff4.FACTORY.Copy("aff4:/C.1000000000000000/fs/tsk/c/bin/bash", "aff4:/C.1000000000000000/fs/tsk/c/bin/中国新闻网新闻中") out = io.BytesIO() self.api.Client(client_id=self.client_urn.Basename()).File( u"fs/tsk/c/bin/中国新闻网新闻中").GetBlob().WriteToStream(out) self.assertEqual(out.getvalue(), "Hello world") def testGetFilesArchive(self): zip_stream = io.BytesIO() self.api.Client(client_id=self.client_urn.Basename()).File( "fs/tsk/c/bin").GetFilesArchive().WriteToStream(zip_stream) zip_fd = zipfile.ZipFile(zip_stream) namelist = zip_fd.namelist() self.assertEqual( sorted(namelist), sorted([ "vfs_C_1000000000000000_fs_tsk_c_bin/fs/tsk/c/bin/rbash", "vfs_C_1000000000000000_fs_tsk_c_bin/fs/tsk/c/bin/bash" ])) def testGetVersionTimes(self): vtimes = self.api.Client(client_id=self.client_urn.Basename()).File( "fs/os/c/Downloads/a.txt").GetVersionTimes() self.assertEqual(len(vtimes), 1) def testRefresh(self): operation = self.api.Client(client_id=self.client_urn.Basename()).File( "fs/os/c/Downloads").Refresh() self.assertTrue(operation.operation_id) self.assertEqual(operation.GetState(), operation.STATE_RUNNING) def testRefreshWaitUntilDone(self): f = self.api.Client( client_id=self.client_urn.Basename()).File("fs/os/c/Downloads") operation = f.Refresh() self.assertEqual(operation.GetState(), operation.STATE_RUNNING) def ProcessOperation(): time.sleep(1) # We assume that the operation id is the URN of a flow. flow_test_lib.TestFlowHelper( rdfvalue.RDFURN(operation.operation_id), client_id=self.client_urn, token=self.token) threading.Thread(target=ProcessOperation).start() result_f = operation.WaitUntilDone().target_file self.assertEqual(f.path, result_f.path) self.assertEqual(operation.GetState(), operation.STATE_FINISHED) def testCollect(self): operation = self.api.Client(client_id=self.client_urn.Basename()).File( "fs/os/c/Downloads/a.txt").Collect() self.assertTrue(operation.operation_id) self.assertEqual(operation.GetState(), operation.STATE_RUNNING) def testCollectWaitUntilDone(self): f = self.api.Client( client_id=self.client_urn.Basename()).File("fs/os/c/Downloads/a.txt") operation = f.Collect() self.assertEqual(operation.GetState(), operation.STATE_RUNNING) def ProcessOperation(): time.sleep(1) # We assume that the operation id is the URN of a flow. flow_test_lib.TestFlowHelper( rdfvalue.RDFURN(operation.operation_id), client_id=self.client_urn, token=self.token) threading.Thread(target=ProcessOperation).start() result_f = operation.WaitUntilDone().target_file self.assertEqual(f.path, result_f.path) self.assertEqual(operation.GetState(), operation.STATE_FINISHED) def testGetTimeline(self): timeline = self.api.Client( client_id=self.client_urn.Basename()).File("fs").GetTimeline() self.assertTrue(timeline) for item in timeline: self.assertTrue(isinstance(item, vfs_pb2.ApiVfsTimelineItem)) def testGetTimelineAsCsv(self): out = io.BytesIO() self.api.Client(client_id=self.client_urn.Basename()).File( "fs").GetTimelineAsCsv().WriteToStream(out) self.assertTrue(out.getvalue()) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
34.701863
80
0.706819
79519dde580e0176bb0528f8be03a339b8c543a1
193,564
py
Python
tests/unit/test_jlink.py
RisinT96/pylink
a2bdb648bde08dceebbffcf3233d876b307eedf6
[ "Apache-2.0" ]
null
null
null
tests/unit/test_jlink.py
RisinT96/pylink
a2bdb648bde08dceebbffcf3233d876b307eedf6
[ "Apache-2.0" ]
null
null
null
tests/unit/test_jlink.py
RisinT96/pylink
a2bdb648bde08dceebbffcf3233d876b307eedf6
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pylink.enums as enums from pylink.errors import JLinkException, JLinkDataException import pylink.jlink as jlink import pylink.protocols.swd as swd import pylink.structs as structs import pylink.unlockers.unlock_kinetis as unlock_kinetis import pylink.util as util import mock try: import StringIO except ImportError: import io as StringIO import ctypes import itertools import unittest class TestJLink(unittest.TestCase): """Tests the ``jlink`` submodule.""" def setUp(self): """Called before each test. Performs setup. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ assertRaisesRegexp = getattr(self, 'assertRaisesRegexp', None) self.assertRaisesRegexp = getattr(self, 'assertRaisesRegex', assertRaisesRegexp) self.lib = mock.Mock() self.dll = mock.Mock() self.lib.dll.return_value = self.dll self.jlink = jlink.JLink(self.lib) def tearDown(self): """Called after each test. Performs teardown. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ del self.jlink @mock.patch('pylink.jlink.library') def test_jlink_initialize_no_lib(self, mock_lib): """TEsts initializing a ``JLink`` without a provided library. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ jlink.JLink() def test_jlink_initialize_invalid_dll(self): """Tests initializing a ``JLink`` with an invalid DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.lib.dll.return_value = None with self.assertRaises(TypeError): jlink.JLink(self.lib) def test_jlink_initialize_provided_dll(self): """Tests initializing a ``JLink`` with a provided valid DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ jlink.JLink(self.lib) def test_jlink_open_required_not_open(self): """Tests calling a method when ``open_required()`` is specified. This test checks that if we call a method that has specified that ``open_required()`` is needed, and we're not open, that a ``JLinkException`` is raised. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsOpen.return_value = False my_jlink = jlink.JLink(self.lib) with self.assertRaisesRegexp(JLinkException, 'DLL is not open'): my_jlink.update_firmware() def test_jlink_open_required_no_emu(self): """Tests calling a method when ``open_required()`` is specified. This test checks that if we call a method that has specified that ``open_required()`` is needed, and we're open, but no emulator is connected, that a ``JLinkException`` is raised. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsOpen.return_value = True self.dll.JLINKARM_EMU_IsConnected.return_value = False my_jlink = jlink.JLink(self.lib) with self.assertRaisesRegexp(JLinkException, 'connection has been lost'): my_jlink.update_firmware() def test_jlink_open_required_is_opened(self): """Tests calling a method when ``open_required()`` is specified. This test checks that if we call a method that has specified that ``open_required()`` is needed, and we're open and have a connected emulator, that we succeed. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ firmware = 0xdeadbeef self.dll.JLINKARM_IsOpen.return_value = True self.dll.JLINKARM_EMU_IsConnected.return_value = True self.dll.JLINKARM_UpdateFirmwareIfNewer.return_value = firmware my_jlink = jlink.JLink(self.lib) my_jlink.update_firmware() def test_jlink_connection_required_not_connected(self): """Tests calling a method when ``connection_required()`` is specified. This test checks that if we call a method that has specified that ``connection_required()`` is needed, and we're not connected, that an error is raised. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsOpen.return_value = True self.dll.JLINKARM_EMU_IsConnected.return_value = True self.dll.JLINKARM_IsConnected.return_value = False my_link = jlink.JLink(self.lib) with self.assertRaisesRegexp(JLinkException, 'Target is not connected'): my_link.cpu_capability(1) def test_jlink_connection_required_is_connected(self): """Tests calling a method when ``connection_required()`` is specified. We should succeed if connected. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsOpen.return_value = True self.dll.JLINKARM_EMU_IsConnected.return_value = True self.dll.JLINKARM_IsConnected.return_value = True my_link = jlink.JLink(self.lib) my_link.cpu_capability(1) def test_jlink_minimum_required(self): """Tests that the minimum required decorator handles versions correctly. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49801 with self.assertRaisesRegexp(JLinkException, 'Version'): self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 49800 with self.assertRaisesRegexp(JLinkException, 'Version'): self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 39804 with self.assertRaisesRegexp(JLinkException, 'Version'): self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 50000 self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 61009 self.jlink.erase_licenses() def test_jlink_interface_required_wrong_interface(self): """Tests calling a method when ``interface_required()`` is specified. If a given method requires we have a specific target interface, and we do not, and it has specified ``interface_required()``, it should generate an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ my_jlink = jlink.JLink(self.lib) self.assertEqual(enums.JLinkInterfaces.JTAG, my_jlink.tif) with self.assertRaisesRegexp(JLinkException, 'Unsupported for current interface.'): my_jlink.swd_read8(0) def test_jlink_interface_required_correct_interface(self): """Tests calling a method when ``interface_required()`` is specified. If a given method requires we have a specific target interface, and we do, and it has specified ``interface_required()``, we should succeed. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ my_jlink = jlink.JLink(self.lib) self.assertEqual(enums.JLinkInterfaces.JTAG, my_jlink.tif) my_jlink._tif = enums.JLinkInterfaces.SWD self.dll.JLINK_SWD_GetU8.return_value = 0 my_jlink.swd_read8(0) def test_jlink_opened(self): """Tests the J-Link ``opened()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # DLL has not been succesfully opened. No J-Link connection. self.dll.JLINKARM_IsOpen.return_value = 0 self.assertFalse(self.jlink.opened()) # DLL has been opened successfully. self.dll.JLINKARM_IsOpen.return_value = 1 self.assertTrue(self.jlink.opened()) def test_jlink_connected(self): """Tests the J-Link ``connected()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # Connection to J-Link established. self.dll.JLINKARM_EMU_IsConnected.return_value = 1 self.assertTrue(self.jlink.connected()) # Connection to J-Link is not established. self.dll.JLINKARM_EMU_IsConnected.return_value = 0 self.assertFalse(self.jlink.connected()) def test_jlink_target_connected(self): """Tests the J-Link ``target_connected()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # If not connected self.dll.JLINKARM_IsConnected.return_value = 0 self.assertFalse(self.jlink.target_connected()) # If connected self.dll.JLINKARM_IsConnected.return_value = 1 self.assertTrue(self.jlink.target_connected()) def test_jlink_log_handler(self): """Tests the J-Link ``log_handler`` setter/getter. As long as the DLL is not open, we can set a log handler, which is made into a ``ctypes`` function. Once one is set, it is used for all DLL logging. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def foo(): return None original_log_handler = self.jlink.log_handler self.dll.JLINKARM_IsOpen.return_value = 1 self.jlink.log_handler = foo log_handler = self.jlink.log_handler self.assertEqual(original_log_handler, log_handler) self.dll.JLINKARM_IsOpen.return_value = 0 self.jlink.log_handler = foo log_handler = self.jlink.log_handler self.assertTrue(log_handler) self.assertNotEqual(original_log_handler, log_handler) def test_jlink_detailed_log_handler(self): """Tests the J-Link ``detailed_log_handler`` setter/getter. As long as the DLL is not open, we can set a detailed log handler, which is made into a ``ctypes`` function. Once one is set, it is used for all DLL detailed logging. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def foo(): return None original_log_handler = self.jlink.detailed_log_handler self.dll.JLINKARM_IsOpen.return_value = 1 self.jlink.detailed_log_handler = foo log_handler = self.jlink.detailed_log_handler self.assertEqual(original_log_handler, log_handler) self.dll.JLINKARM_IsOpen.return_value = 0 self.jlink.detailed_log_handler = foo log_handler = self.jlink.detailed_log_handler self.assertTrue(log_handler) self.assertNotEqual(original_log_handler, log_handler) def test_jlink_error_handler(self): """Tests the J-Link ``error_handler`` setter/getter. As long as the DLL is not open, we can set an error handler which is made into a ``ctypes`` funciton. Once one is set, it is used for all DLL error logging. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def foo(): return None original_error_handler = self.jlink.error_handler self.dll.JLINKARM_IsOpen.return_value = 1 self.jlink.error_handler = foo error_handler = self.jlink.error_handler self.assertEqual(original_error_handler, error_handler) self.dll.JLINKARM_IsOpen.return_value = 0 self.jlink.error_handler = foo error_handler = self.jlink.error_handler self.assertTrue(error_handler) self.assertNotEqual(original_error_handler, error_handler) def test_jlink_warning_handler(self): """Tests the J-Link ``warning_handler`` setter/getter. As long as the DLL is not open, we can set an warning handler which is made into a ``ctypes`` funciton. Once one is set, it is used for all DLL warning logging. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def foo(): return None original_warning_handler = self.jlink.warning_handler self.dll.JLINKARM_IsOpen.return_value = 1 self.jlink.warning_handler = foo warning_handler = self.jlink.warning_handler self.assertEqual(original_warning_handler, warning_handler) self.dll.JLINKARM_IsOpen.return_value = 0 self.jlink.warning_handler = foo warning_handler = self.jlink.warning_handler self.assertTrue(warning_handler) self.assertNotEqual(original_warning_handler, warning_handler) def test_jlink_num_connected_emulators(self): """Tests the J-Link ``num_connected_emulators()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_GetNumDevices.return_value = 1 self.assertEqual(1, self.jlink.num_connected_emulators()) self.dll.JLINKARM_EMU_GetNumDevices.return_value = 0 self.assertEqual(0, self.jlink.num_connected_emulators()) def test_jlink_connected_emulators(self): """Tests the J-Link ``connected_emulators()`` method. This method returns a list of ``structs.JLinkConnectInfo`` structures provided that is succeeds, otherwise raises a ``JLinkException``. The returned list may be empty. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # >= 0, total number of emulators which have been found self.dll.JLINKARM_EMU_GetList.return_value = 0 connected_emulators = self.jlink.connected_emulators() self.assertTrue(isinstance(connected_emulators, list)) self.assertEqual(0, len(connected_emulators)) # < 0, Error self.dll.JLINKARM_EMU_GetList.return_value = -1 with self.assertRaises(JLinkException): connected_emulators = self.jlink.connected_emulators() # < 0, Error self.dll.JLINKARM_EMU_GetList = mock.Mock() self.dll.JLINKARM_EMU_GetList.side_effect = [1, -1] with self.assertRaises(JLinkException): connected_emulators = self.jlink.connected_emulators() # >= 0, total number of emulators which have been found self.dll.JLINKARM_EMU_GetList = mock.Mock() self.dll.JLINKARM_EMU_GetList.return_value = 1 connected_emulators = self.jlink.connected_emulators() self.assertTrue(isinstance(connected_emulators, list)) self.assertEqual(1, len(connected_emulators)) self.assertTrue(isinstance(connected_emulators[0], structs.JLinkConnectInfo)) def test_jlink_num_supported_devices(self): """Tests the J-Link ``num_supported_devices()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_DEVICE_GetInfo.return_value = 0 self.assertEqual(self.jlink.num_supported_devices(), 0) self.dll.JLINKARM_DEVICE_GetInfo.return_value = 1 self.assertEqual(self.jlink.num_supported_devices(), 1) def test_jlink_supported_device(self): """Tests the J-Link ``supported_device()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_DEVICE_GetInfo.return_value = 1 with self.assertRaisesRegexp(ValueError, 'Invalid index.'): dev = self.jlink.supported_device('dog') with self.assertRaisesRegexp(ValueError, 'Invalid index.'): dev = self.jlink.supported_device(-1) with self.assertRaisesRegexp(ValueError, 'Invalid index.'): dev = self.jlink.supported_device(1) dev = self.jlink.supported_device(0) self.assertTrue(isinstance(dev, structs.JLinkDeviceInfo)) def test_jlink_open_unspecified(self): """Tests the J-Link ``open()`` method with an unspecified method. When opening a connection to an emulator, we need to specify by which method we are connecting to the emulator. If neither USB or Ethernet or specified, then we should raise an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(AttributeError): self.jlink.open() def test_jlink_open_unspecified_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) with an unspecified method. When opening a connection to an emulator, we need to specify by which method we are connecting to the emulator. If neither USB or Ethernet or specified, then we should raise an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(AttributeError): with jlink.JLink(self.lib) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. def test_jlink_open_ethernet_failed(self): """Tests the J-Link ``open()`` method over Ethernet failing. If we fail to select a J-Link over ethernet, it should raise an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SelectIP.return_value = 1 with self.assertRaises(JLinkException): self.jlink.open(ip_addr='127.0.0.1:80') self.dll.JLINKARM_SelectIP.assert_called_once() def test_jlink_open_ethernet_failed_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) over Ethernet failing. If we fail to select a J-Link over ethernet, it should raise an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SelectIP.return_value = 1 with self.assertRaises(JLinkException): with jlink.JLink(self.lib, ip_addr='127.0.0.1:80') as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.dll.JLINKARM_SelectIP.assert_called_once() @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_ethernet(self): """Tests the J-Link ``open()`` method over Ethernet succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLNKARM_SelectIP.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 self.dll.JLINKARM_GetSN.return_value = 123456789 self.jlink.open(ip_addr='127.0.0.1:80') self.dll.JLINKARM_SelectIP.assert_called_once() @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_ethernet_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) over Ethernet succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLNKARM_SelectIP.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 self.dll.JLINKARM_GetSN.return_value = 123456789 with jlink.JLink(self.lib, ip_addr='127.0.0.1:80') as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.dll.JLINKARM_SelectIP.assert_called_once() @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_ethernet_and_serial_number(self): """Tests the J-Link ``open()`` method over Ethernet succeeding with identification done by serial number. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_OpenEx.return_value = 0 self.jlink.open(serial_no=123456789, ip_addr='127.0.0.1:80') self.assertEqual(0, self.dll.JLINKARM_EMU_SelectIP.call_count) self.assertEqual(1, self.dll.JLINKARM_EMU_SelectIPBySN.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_ethernet_and_serial_number_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) over Ethernet succeeding with identification done by serial number. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_OpenEx.return_value = 0 with jlink.JLink(self.lib, serial_no=123456789, ip_addr='127.0.0.1:80') as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.assertEqual(0, self.dll.JLINKARM_EMU_SelectIP.call_count) self.assertEqual(1, self.dll.JLINKARM_EMU_SelectIPBySN.call_count) def test_jlink_open_tunnel(self): """Tests the J-Link ``open_tunnel()`` method over tunnel succeeding with default port value. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLNKARM_SelectIP.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 self.dll.JLINKARM_GetSN.return_value = 123456789 self.jlink.open_tunnel(serial_no=123456789) self.dll.JLINKARM_SelectIP.assert_called_once_with('tunnel:123456789'.encode(), 19020) def test_jlink_open_tunnel_context_manager(self): """Tests the J-Link ``open_tunnel()`` method (using context manager) over tunnel succeeding with default port value. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLNKARM_SelectIP.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 self.dll.JLINKARM_GetSN.return_value = 123456789 with jlink.JLink(self.lib, serial_no=123456789, open_tunnel=True) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.dll.JLINKARM_SelectIP.assert_called_once_with('tunnel:123456789'.encode(), 19020) def test_jlink_open_serial_number_failed(self): """Tests the J-Link ``open()`` method over USB by serial number, but failing. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = -1 with self.assertRaises(JLinkException): self.jlink.open(serial_no=123456789) self.assertEqual(0, self.dll.JLINKARM_OpenEx.call_count) def test_jlink_open_serial_number_failed_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) over USB by serial number, but failing. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = -1 with self.assertRaises(JLinkException): with jlink.JLink(self.lib, serial_no=123456789) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.assertEqual(0, self.dll.JLINKARM_OpenEx.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_serial_number(self): """Tests the J-Link ``open()`` method over USB by serial number and succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 self.jlink.open(serial_no=123456789) self.assertEqual(1, self.dll.JLINKARM_OpenEx.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_serial_number_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) over USB by serial number and succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 with jlink.JLink(self.lib, serial_no=123456789) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.assertEqual(1, self.dll.JLINKARM_OpenEx.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_serial_number_context_manager_manual(self): """Tests the J-Link ``open()`` method in context manager over USB by serial number and succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 with jlink.JLink(self.lib, open_tunnel=None) as jl: # Requires manual open as open_tunnel=None. self.dll.JLINKARM_OpenEx.assert_not_called() jl.open(serial_no=123456789) self.dll.JLINKARM_OpenEx.assert_called() self.assertEqual(1, self.dll.JLINKARM_OpenEx.call_count) self.assertEqual(1, self.dll.JLINKARM_Close.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_dll_failed(self): """Tests the J-Link ``open()`` method failing to open the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 buf = ctypes.create_string_buffer(b'Error!', 32) self.dll.JLINKARM_OpenEx.return_value = ctypes.addressof(buf) with self.assertRaisesRegexp(JLinkException, 'Error!'): self.jlink.open(serial_no=123456789) self.assertEqual(1, self.dll.JLINKARM_OpenEx.call_count) @mock.patch('pylink.jlock.JLock', new=mock.Mock()) def test_jlink_open_dll_failed_context_manager(self): """Tests the J-Link ``open()`` method (using context manager) failing to open the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 buf = ctypes.create_string_buffer(b'Error!', 32) self.dll.JLINKARM_OpenEx.return_value = ctypes.addressof(buf) with self.assertRaisesRegexp(JLinkException, 'Error!'): with jlink.JLink(self.lib, serial_no=123456789) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.assertEqual(1, self.dll.JLINKARM_OpenEx.call_count) @mock.patch('pylink.jlock.JLock') def test_jlink_open_lock_failed(self, mock_jlock): """Tests the J-Link ``open()`` method failing if the lockfile is held. Args: self (TestJLink): the ``TestJLink`` instance mock_jlock (Mock): the mocked lock instance Returns: ``None`` """ mock_lock = mock.Mock() mock_jlock.return_value = mock_lock mock_lock.acquire.return_value = False self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 with self.assertRaisesRegexp(JLinkException, 'J-Link is already open.'): self.jlink.open(serial_no=123456789) self.dll.JLINKARM_OpenEx.assert_not_called() @mock.patch('pylink.jlock.JLock') def test_jlink_open_lock_failed_context_manager(self, mock_jlock): """Tests the J-Link ``open()`` method (using context manager) failing if the lockfile is held. Args: self (TestJLink): the ``TestJLink`` instance mock_jlock (Mock): the mocked lock instance Returns: ``None`` """ mock_lock = mock.Mock() mock_jlock.return_value = mock_lock mock_lock.acquire.return_value = False self.dll.JLINKARM_EMU_SelectByUSBSN.return_value = 0 self.dll.JLINKARM_OpenEx.return_value = 0 with self.assertRaisesRegexp(JLinkException, 'J-Link is already open.'): with jlink.JLink(self.lib, serial_no=123456789) as jl: self.assertTrue(jl.opened()) # Opened in CM. self.dll.JLINKARM_Close.assert_called() # Closed on exit. self.dll.JLINKARM_OpenEx.assert_not_called() def test_jlink_close(self): """Tests the J-Link ``close()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # close() does nothing if there has been no open() call first. self.jlink.close() self.assertEqual(0, self.dll.JLINKARM_Close.call_count) # close() decrements the refcount if open() has been called multiple times. self.jlink._open_refcount = 5 self.jlink.close() self.assertEqual(0, self.dll.JLINKARM_Close.call_count) self.assertEqual(4, self.jlink._open_refcount) # close() calls the DLL close method when refcount is exhausted. self.jlink._open_refcount = 1 self.jlink.close() self.assertEqual(1, self.dll.JLINKARM_Close.call_count) self.assertEqual(0, self.jlink._open_refcount) def test_jlink_close_context_manager(self): """Tests the J-Link ``close()`` method using context manager. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_OpenEx.return_value = 0 with jlink.JLink(self.lib, ip_addr='127.0.0.1:80') as jl: self.assertTrue(jl.opened()) self.dll.JLINKARM_Close.assert_not_called() # .close() is first called when exiting the context manager # Depending on the system - GC operation, it can also already be # called from __del__ when the object is garbage collected. self.assertIn(self.dll.JLINKARM_Close.call_count, (1, 2)) def test_jlink_test(self): """Tests the J-Link self test. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Test.return_value = 0 self.assertTrue(self.jlink.test()) self.dll.JLINKARM_Test.return_value = 1 self.assertFalse(self.jlink.test()) def test_jlink_invalidate_firmware(self): """Tests invaliding the J-Link firmware. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ mocked = mock.Mock() self.jlink.exec_command = mocked self.jlink.invalidate_firmware() self.assertEqual(1, self.jlink.exec_command.call_count) self.jlink.exec_command.assert_called_with('InvalidateFW') def test_jlink_update_firmware(self): """Tests the J-Link ``update_firmware()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ firmware = 0xdeadbeef self.dll.JLINKARM_UpdateFirmwareIfNewer.return_value = firmware self.assertEqual(firmware, self.jlink.update_firmware()) def test_jlink_sync_firmware_outdated(self): """Tests syncing the J-Link firmware when it is outdated. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.firmware_newer = mock.Mock() self.jlink.firmware_newer.return_value = False self.jlink.firmware_outdated = mock.Mock() self.jlink.firmware_outdated.side_effect = [True, False, True, True] self.jlink.invalidate_firmware = mock.Mock() self.jlink.update_firmware = mock.Mock() self.jlink.update_firmware.side_effect = [JLinkException(''), None] self.jlink.open = mock.Mock() self.jlink.open.return_value = None self.dll.JLINKARM_GetSN.return_value = 0xdeadbeef self.assertEqual(None, self.jlink.sync_firmware()) self.assertEqual(0, self.jlink.invalidate_firmware.call_count) self.assertEqual(1, self.jlink.update_firmware.call_count) self.assertEqual(1, self.dll.JLINKARM_GetSN.call_count) self.jlink.open.assert_called_with(serial_no=0xdeadbeef) # Firmware still outdated after syncing. with self.assertRaises(JLinkException): self.jlink.sync_firmware() def test_jlink_sync_firmware_newer(self): """Tests syncing the J-Link firmware when it is newer than the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.firmware_newer = mock.Mock() self.jlink.firmware_newer.side_effect = [True, False, True, True] self.jlink.firmware_outdated = mock.Mock() self.jlink.firmware_outdated.return_value = False self.jlink.invalidate_firmware = mock.Mock() self.jlink.update_firmware = mock.Mock() self.jlink.update_firmware.side_effect = [JLinkException(''), None] self.jlink.open = mock.Mock() self.jlink.open.return_value = None self.dll.JLINKARM_GetSN.return_value = 0xdeadbeef self.assertEqual(None, self.jlink.sync_firmware()) self.assertEqual(1, self.jlink.invalidate_firmware.call_count) self.assertEqual(1, self.jlink.update_firmware.call_count) self.assertEqual(1, self.dll.JLINKARM_GetSN.call_count) self.jlink.open.assert_called_with(serial_no=0xdeadbeef) # Firmware still newer after syncing. with self.assertRaises(JLinkException): self.jlink.sync_firmware() def test_jlink_sync_firmware_in_sync(self): """Tests syncing the J-Link firmware when it is in sync. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.firmware_newer = mock.Mock() self.jlink.firmware_newer.return_value = False self.jlink.firmware_outdated = mock.Mock() self.jlink.firmware_outdated.return_value = False self.jlink.invalidate_firmware = mock.Mock() self.jlink.update_firmware = mock.Mock() self.dll.JLINKARM_GetSN.return_value = 0xdeadbeef self.assertEqual(None, self.jlink.sync_firmware()) self.assertEqual(0, self.jlink.invalidate_firmware.call_count) self.assertEqual(0, self.jlink.update_firmware.call_count) self.assertEqual(1, self.dll.JLINKARM_GetSN.call_count) def test_jlink_exec_command_error_string(self): """Tests the J-Link ``exec_command()`` when an error string is returned. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def foo(cmd, err_buf, err_buf_len): for (index, ch) in enumerate(b'Error!'): err_buf[index] = ch return 0 self.dll.JLINKARM_ExecCommand = foo with self.assertRaisesRegexp(JLinkException, 'Error!'): self.jlink.exec_command('SupplyPower = 1') def test_jlink_exec_command_error_code(self): """Tests the J-Link ``exec_command()`` when an error code is returned. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.jlink.exec_command('SupplyPowerf = 1') def test_jlink_exec_command_success(self): """Tests the J-Link ``exec_command()`` succeeding. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.assertEqual(0, self.jlink.exec_command('SupplyPower = 1')) self.dll.JLINKARM_ExecCommand.return_value = 1 self.assertEqual(1, self.jlink.exec_command('SupplyPower = 1')) self.dll.JLINKARM_ExecCommand.return_value = -1 self.assertEqual(-1, self.jlink.exec_command('SupplyPower = 1')) def test_jlink_enable_dialog_boxes(self): """Tests enabling the dialog boxes shown by the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 50200 self.jlink.exec_command = mock.Mock() self.jlink.enable_dialog_boxes() self.jlink.exec_command.assert_called_with('SetBatchMode = 0') def test_jlink_disable_dialog_boxes(self): """Tests disabling the dialog boxes shown by the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 50200 self.jlink.exec_command = mock.Mock() self.jlink.disable_dialog_boxes() self.jlink.exec_command.assert_any_call('SilentUpdateFW') self.jlink.exec_command.assert_any_call('SuppressInfoUpdateFW') self.jlink.exec_command.assert_any_call('SetBatchMode = 1') def test_jlink_jtag_configure(self): """Tests the J-Link ``jtag_configure()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaisesRegexp(ValueError, 'IR'): self.jlink.jtag_configure('sdafas', 0) with self.assertRaisesRegexp(ValueError, 'Data bits'): self.jlink.jtag_configure(0, 'asfadsf') self.assertEqual(None, self.jlink.jtag_configure(0, 0)) self.assertEqual(1, self.dll.JLINKARM_ConfigJTAG.call_count) self.assertEqual(None, self.jlink.jtag_configure()) self.assertEqual(2, self.dll.JLINKARM_ConfigJTAG.call_count) def test_jlink_coresight_configure_swd(self): """Tests Coresight Configure over SWD. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.assertEqual(enums.JLinkInterfaces.SWD, self.jlink.tif) self.dll.JLINKARM_GetDLLVersion.return_value = 49805 self.dll.JLINKARM_CORESIGHT_Configure.return_value = -1 with self.assertRaises(JLinkException): self.jlink.coresight_configure() self.dll.JLINKARM_CORESIGHT_Configure.return_value = 0 self.jlink.coresight_configure() self.dll.JLINKARM_CORESIGHT_Configure.assert_called_with('') def test_jlink_coresight_configure_jtag(self): """Tests Coresight Configure over JTAG. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.JTAG self.assertEqual(enums.JLinkInterfaces.JTAG, self.jlink.tif) self.dll.JLINKARM_GetDLLVersion.return_value = 49805 self.dll.JLINKARM_CORESIGHT_Configure.return_value = 0 self.jlink.coresight_configure(perform_tif_init=False) self.dll.JLINKARM_CORESIGHT_Configure.return_value = -1 with self.assertRaises(JLinkException): self.jlink.coresight_configure() self.dll.JLINKARM_CORESIGHT_Configure.return_value = 0 self.jlink.coresight_configure(dr_post=2, ir_post=3, perform_tif_init=False) arg = self.dll.JLINKARM_CORESIGHT_Configure.call_args[0][0] self.assertTrue(len(arg) > 0) self.assertTrue(b'PerformTIFInit=0' in arg) self.assertTrue(b'DRPost=2' in arg) self.assertTrue(b'IRPost=3' in arg) @mock.patch('time.sleep') def test_jlink_connect_failed(self, mock_sleep): """Tests J-Link ``connect()`` failing due to hardware issue. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = -1 self.dll.JLINKARM_IsHalted.return_value = 0 with self.assertRaises(JLinkException): self.jlink.connect('device') self.assertEqual(1, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(1, self.dll.JLINKARM_Connect.call_count) self.assertEqual(0, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_auto(self, mock_sleep): """Tests J-Link ``connect()`` with ``auto`` speed. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 self.jlink.num_supported_devices = mock.Mock() self.jlink.num_supported_devices.return_value = 1 self.jlink.supported_device = mock.Mock() self.jlink.supported_device.return_value = mock.Mock() self.jlink.supported_device.return_value.name = 'device' self.assertEqual(None, self.jlink.connect('device', speed='auto')) self.assertEqual(1, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(1, self.dll.JLINKARM_Connect.call_count) self.assertEqual(1, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_adaptive(self, mock_sleep): """Tests J-Link ``connect()`` with ``adaptive`` speed. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 self.jlink.num_supported_devices = mock.Mock() self.jlink.num_supported_devices.return_value = 1 self.jlink.supported_device = mock.Mock() self.jlink.supported_device.return_value = mock.Mock() self.jlink.supported_device.return_value.name = 'device' self.assertEqual(None, self.jlink.connect('device', speed='adaptive')) self.assertEqual(1, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(1, self.dll.JLINKARM_Connect.call_count) self.assertEqual(1, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_speed_invalid(self, mock_sleep): """Tests J-Link ``connect()`` fails if speed is invalid. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 with self.assertRaises(TypeError): self.jlink.connect('device', speed=-1) self.assertEqual(1, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(0, self.dll.JLINKARM_Connect.call_count) self.assertEqual(0, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_speed(self, mock_sleep): """Tests J-Link ``connect()`` with a numerical speed. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 self.jlink.num_supported_devices = mock.Mock() self.jlink.num_supported_devices.return_value = 1 self.jlink.supported_device = mock.Mock() self.jlink.supported_device.return_value = mock.Mock() self.jlink.supported_device.return_value.name = 'device' self.jlink.connect('device', speed=10) self.assertEqual(1, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(1, self.dll.JLINKARM_Connect.call_count) self.assertEqual(1, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_verbose(self, mock_sleep): """Tests J-Link ``connect()`` with verbose logging. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 self.jlink.num_supported_devices = mock.Mock() self.jlink.num_supported_devices.return_value = 1 self.jlink.supported_device = mock.Mock() self.jlink.supported_device.return_value = mock.Mock() self.jlink.supported_device.return_value.name = 'device' self.jlink.connect('device', speed=10, verbose=True) self.assertEqual(2, self.dll.JLINKARM_ExecCommand.call_count) self.assertEqual(1, self.dll.JLINKARM_Connect.call_count) self.assertEqual(1, self.dll.JLINKARM_IsHalted.call_count) @mock.patch('time.sleep') def test_jlink_connect_supported_device_not_found(self, mock_sleep): """Tests J-Link ``connect()`` when the supported device is not found. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked sleep function Returns: ``None`` """ self.dll.JLINKARM_ExecCommand.return_value = 0 self.dll.JLINKARM_Connect.return_value = 0 self.dll.JLINKARM_IsHalted.return_value = 0 self.jlink.num_supported_devices = mock.Mock() self.jlink.num_supported_devices.return_value = 0 with self.assertRaisesRegexp(JLinkException, 'Unsupported device'): self.jlink.connect('device') def test_jlink_error(self): """Tests the J-Link ``error`` property. Should be ``None`` on no error, otherwise a non-zero integer value. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_HasError.return_value = 0 self.assertEqual(None, self.jlink.error) self.dll.JLINKARM_HasError.return_value = 1 self.assertEqual(1, self.jlink.error) def test_jlink_clear_error(self): """Tests clearing the J-Link error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_HasError.return_value = 0 self.assertEqual(None, self.jlink.clear_error()) self.dll.JLINKARM_ClrError.assert_called_once() def test_jlink_compile_date(self): """Tests the J-Link ``compile_date`` property. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ date = '2016-09-09' buf = ctypes.create_string_buffer(date.encode(), 32) self.dll.JLINKARM_GetCompileDateTime.return_value = ctypes.addressof(buf) self.assertEqual(date, self.jlink.compile_date) def test_jlink_version(self): """Tests the J-Link ``version`` property. The return value when querying the DLL for its version is a 32-bit DLL version number interpreted as Mmmrr where M is the major number, mm is the minor number, and rr is the revision number. Input: 25402 Output: 2.54b Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 25402 self.assertEqual('2.54b', self.jlink.version) self.dll.JLINKARM_GetDLLVersion.return_value = 60000 self.assertEqual('6.00', self.jlink.version) self.dll.JLINKARM_GetDLLVersion.return_value = 60002 self.assertEqual('6.00b', self.jlink.version) self.dll.JLINKARM_GetDLLVersion.return_value = 49805 self.assertEqual('4.98e', self.jlink.version) def test_jlink_compatible_firmware_version(self): """Tests that getting a compatible firmware version from the DLL. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ firmware = 'J-Trace Cortex-M Rev.3 compiled Mar 30 2015 13:52:25' def set_firmware_string(buf, buf_size): ctypes.memmove(buf, firmware.encode(), len(firmware)) self.dll.JLINKARM_GetFirmwareString = set_firmware_string self.dll.JLINKARM_GetEmbeddedFWString.return_value = -1 with self.assertRaises(JLinkException): self.jlink.compatible_firmware_version self.dll.JLINKARM_GetEmbeddedFWString.return_value = 0 self.dll.JLINKARM_GetEmbeddedFWString.assert_called() self.assertEqual('', self.jlink.compatible_firmware_version) def test_jlink_firmware_outdated(self): """Tests checking if the J-Link firmware is outdated. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ old = 'J-Trace Cortex-M Rev.3 compiled Mar 30 2015 13:52:25' new = 'J-Trace Cortex-M Rev.3 compiled Jun 30 2016 16:58:07' def set_embedded_fw_string(identifier, buf, buf_size): ctypes.memmove(buf, old.encode(), len(old)) return 0 def set_firmware_string(buf, buf_size): ctypes.memmove(buf, new.encode(), len(new)) return 0 self.dll.JLINKARM_GetFirmwareString = set_firmware_string self.dll.JLINKARM_GetEmbeddedFWString = set_embedded_fw_string self.assertFalse(self.jlink.firmware_outdated()) new, old = old, new self.assertTrue(self.jlink.firmware_outdated()) def test_jlink_firmware_newer(self): """Tests checking if the J-Link firmware is newer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ old = 'J-Trace Cortex-M Rev.3 compiled Mar 30 2015 13:52:25' new = 'J-Trace Cortex-M Rev.3 compiled Jun 30 2016 16:58:07' def set_embedded_fw_string(identifier, buf, buf_size): ctypes.memmove(buf, old.encode(), len(old)) return 0 def set_firmware_string(buf, buf_size): ctypes.memmove(buf, new.encode(), len(new)) return 0 self.dll.JLINKARM_GetFirmwareString = set_firmware_string self.dll.JLINKARM_GetEmbeddedFWString = set_embedded_fw_string self.assertTrue(self.jlink.firmware_newer()) new, old = old, new self.assertFalse(self.jlink.firmware_newer()) def test_jlink_hardware_info_invalid(self): """Tests the J-Link ``hardware_info`` property when it fails to read info. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetHWInfo.return_value = -1 with self.assertRaises(JLinkException): self.jlink.hardware_info def test_jlink_hardware_info_valid(self): """Tests the J-Link ``hardware_info`` property when info is read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetHWInfo.return_value = 0 result = self.jlink.hardware_info self.assertTrue(all(map(lambda x: x == 0, result))) def test_jlink_hardware_status_invalid(self): """Tests the J-Link ``hardware_status`` property on failure to read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetHWStatus.return_value = 1 with self.assertRaises(JLinkException): self.jlink.hardware_status def test_jlink_hardware_status_valid(self): """Tests the J-Link ``hardware_status`` property on successful read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetHWStatus.return_value = 0 stat = self.jlink.hardware_status self.assertTrue(isinstance(stat, structs.JLinkHardwareStatus)) def test_jlink_hardware_version(self): """Tests the J-Link ``hardware_version`` property. Input: 20330 Output: 2.03 Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetHardwareVersion.return_value = 20330 self.assertEqual('2.03', self.jlink.hardware_version) def test_jlink_firmware_version(self): """Tests the J-Link ``firmware_version`` property. Example Firmware Strings: ``Firmware: J-Link compiled Nov 17 2005 16:12:19`` ``Firmware: J-Link compiled Nov 09 2005 19:32:24 -- Update --`` ``Firmware: J-Link compiled Nov 17 2005 16:12:19 ARM Rev.5`` Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ firmware_strings = [ 'Firmware: J-Link compiled Nov 17 2005 16:12:19', 'Firmware: J-Link compiled Nov 09 2005 19:32:24 -- Update --', 'Firmware: J-Link compiled Nov 17 2005 16:12:19 ARM Rev.5' ] def get_firmware_string(buf, buf_size): firmware_string = firmware_strings.pop(0) ctypes.memmove(buf, firmware_string.encode(), len(firmware_string)) self.dll.JLINKARM_GetFirmwareString = get_firmware_string while len(firmware_strings) > 0: firmware_string = firmware_strings[0] self.assertEqual(firmware_string, self.jlink.firmware_version) def test_jlink_capabilities(self): """Tests the J-Link ``capabilities`` property. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetEmuCaps.return_value = 0 self.assertEqual(0, self.jlink.capabilities) self.assertEqual(1, self.dll.JLINKARM_GetEmuCaps.call_count) def test_jlink_extended_capabilities(self): """Tests the J-Link ``extended_capabilities`` property. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ result = self.jlink.extended_capabilities self.assertTrue(all(map(lambda x: x == 0, result))) self.assertEqual(1, self.dll.JLINKARM_GetEmuCapsEx.call_count) def test_jlink_has_extended_capability(self): """Tests the J-Link ``extended_capability()`` method for checking if an emulator has a capability. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_HasCapEx.return_value = 0 self.assertFalse(self.jlink.extended_capability(0)) self.assertEqual(1, self.dll.JLINKARM_EMU_HasCapEx.call_count) self.dll.JLINKARM_EMU_HasCapEx.return_value = 1 self.assertTrue(self.jlink.extended_capability(0)) self.assertEqual(2, self.dll.JLINKARM_EMU_HasCapEx.call_count) def test_jlink_features_no_features(self): """Tests the J-Link ``features`` property returns an empty list. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ result = self.jlink.features self.assertTrue(isinstance(result, list)) self.assertEqual(0, len(result)) def test_jlink_features_has_features(self): """Tests the J-Link ``features`` property returns a feature list. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ feature_string = 'RDI, JFlash, FlashDL' def func(b): ctypes.memmove(b, feature_string.encode(), len(feature_string)) self.dll.JLINKARM_GetFeatureString = func result = self.jlink.features self.assertTrue(isinstance(result, list)) self.assertEqual(3, len(result)) self.assertEqual('RDI', result[0]) self.assertEqual('JFlash', result[1]) self.assertEqual('FlashDL', result[2]) def test_jlink_product_name_empty(self): """Tests the J-Link ``product_name`` property on empty name. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.assertEqual('', self.jlink.product_name) def test_jlink_serial_number(self): """Tests the J-Link ``serial_number`` property returns a serial number. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ serial = 0xdeadbeef self.dll.JLINKARM_GetSN.return_value = serial self.assertEqual(serial, self.jlink.serial_number) def test_jlink_oem_failed(self): """Tests the J-Link ``oem`` property raises an exception on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetOEMString.return_value = 1 with self.assertRaises(JLinkException): self.jlink.oem self.dll.JLINKARM_GetOEMString.return_value = -1 with self.assertRaises(JLinkException): self.jlink.oem def test_jlink_no_oem(self): """Tests the J-Link ``oem`` property when there is no OEM. SEGGER branded devices have no OEM, so we should get back an empty string (`None`) in this instance. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetOEMString.return_value = 0 self.assertEqual(None, self.jlink.oem) def test_jlink_has_oem(self): """Tests the J-Link ``oem`` property when there is an OEM. Possible OEMs are: MIDAS, SAM-ICE, DIGI-LINK, Freescale, IAR, and NXP. Args: self (TestJLink): the ``TestJLink`` instanace Returns: ``None`` """ oems = ['MIDAS', 'SAM-ICE', 'DIGI-LINK', 'Freescale', 'IAR', 'NXP'] def func(buf): oem = oems.pop(0) ctypes.memmove(buf, oem.encode(), len(oem)) return 0 self.dll.JLINKARM_GetOEMString = func while len(oems) > 0: oem = oems[0] self.assertEqual(oem, self.jlink.oem) def test_jlink_index(self): """Tests the J-Link ``index`` property. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetSelDevice.return_value = 2 self.assertEqual(2, self.jlink.index) def test_jlink_speed_getter(self): """Tests getting the speed of the J-Link emulator connection. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetSpeed.return_value = 1 self.assertEqual(1, self.jlink.speed) self.assertEqual(1, self.dll.JLINKARM_GetSpeed.call_count) def test_jlink_set_speed_too_fast(self): """Tests that an error is raised when specifying a too fast speed. When setting the speed of a JTAG communication, there is a maximum value that can be given. This checks that an error is raised if the value passed is too large. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaisesRegexp(ValueError, 'exceeds max speed'): self.jlink.set_speed(jlink.JLink.MAX_JTAG_SPEED + 1) self.assertEqual(0, self.dll.JLINKARM_SetSpeed.call_count) def test_jlink_set_speed_too_slow(self): """Tests that an error is raised when specifying a too slow speed. When setting the speed of a JTAG communication, there is a minimum value that can be given. This checks that an error is raised if the value passed is too small. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaisesRegexp(ValueError, 'is too slow'): self.jlink.set_speed(jlink.JLink.MIN_JTAG_SPEED - 1) self.assertEqual(0, self.dll.JLINKARM_SetSpeed.call_count) def test_jlink_set_speed_non_number(self): """Tests that an error is raised when specifying a non-numeric speed. If we give a speed, the speed must be a natural number. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(TypeError): self.jlink.set_speed(-1) with self.assertRaises(TypeError): self.jlink.set_speed('dog') self.assertEqual(0, self.dll.JLINKARM_SetSpeed.call_count) def test_jlink_set_speed_auto(self): """Tests setting an automatic speed. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_speed(auto=True) self.dll.JLINKARM_SetSpeed.assert_called_once_with(0) def test_jlink_set_speed_adaptive(self): """Tests setting an adaptive speed. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_speed(adaptive=True) self.dll.JLINKARM_SetSpeed.assert_called_once_with(jlink.JLink.ADAPTIVE_JTAG_SPEED) def test_jlink_set_speed_speed(self): """Tests setting a valid numeric speed. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_speed(12) self.dll.JLINKARM_SetSpeed.assert_called_once_with(12) def test_jlink_set_max_speed(self): """Tests the J-Link ``set_max_speed()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.assertEqual(None, self.jlink.set_max_speed()) self.assertEqual(1, self.dll.JLINKARM_SetMaxSpeed.call_count) def test_jlink_speed_info(self): """Tests the J-Link ``speed_info`` property. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ info = self.jlink.speed_info self.assertTrue(isinstance(info, structs.JLinkSpeedInfo)) def test_jlink_builtin_licenses_fail_to_read(self): """Tests the J-Link ``licenses`` property generates an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_GetAvailableLicense.return_value = -1 with self.assertRaises(JLinkException): self.jlink.licenses def test_jlink_builtin_licenses_empty(self): """Tests that the J-Link ``buitlin_licenses`` property returns an empty string. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_GetAvailableLicense.return_value = 0 self.assertEqual('', self.jlink.licenses) def test_jlink_custom_licenses_fail_to_read(self): """Tests the J-Link fail to read the custom licenses. Two possible fail conditions: - JLink error. - Unsupported on current SDK. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49800 with self.assertRaisesRegexp(JLinkException, 'Version 4.98b required'): self.jlink.custom_licenses self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_GetLicenses.return_value = -1 with self.assertRaises(JLinkException): self.jlink.custom_licenses def test_jlink_custom_licenses_empty(self): """Tests that the J-Link when there are no custom licenses. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_GetLicenses.return_value = 0 self.assertEqual('', self.jlink.custom_licenses) def test_jlink_add_license_failure(self): """Tests add license failing due to the possible error states. Error states are: - Unsupported SDK. - Unspecified (error code -1). - Failed to read / write license area (error code -2). - Not enough space to store license (error code -3). Args: self (TestJLink): the ``TestJLink`` instnace Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49800 with self.assertRaisesRegexp(JLinkException, 'Version 4.98b required'): self.jlink.add_license('license') self.dll.JLINKARM_GetDLLVersion.return_value = 49801 with self.assertRaisesRegexp(JLinkException, 'Version 4.98b required'): self.jlink.add_license('license') self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_AddLicense.return_value = -1 with self.assertRaisesRegexp(JLinkException, 'Unspecified error'): self.jlink.add_license('license') self.dll.JLINK_EMU_AddLicense.return_value = -2 with self.assertRaisesRegexp(JLinkException, 'read/write'): self.jlink.add_license('license') self.dll.JLINK_EMU_AddLicense.return_value = -3 with self.assertRaisesRegexp(JLinkException, 'space'): self.jlink.add_license('license') def test_jlink_add_license(self): """Tests adding a license and succeeding. The second time a same license is added to a device, the J-Link returns to indicate that the license already exists. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_AddLicense.return_value = 0 self.assertTrue(self.jlink.add_license('license')) self.dll.JLINK_EMU_AddLicense.return_value = 1 self.assertFalse(self.jlink.add_license('license')) def test_jlink_erase_licenses_failed(self): """Tests when erasing licenses fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49800 with self.assertRaisesRegexp(JLinkException, 'Version 4.98b required'): self.jlink.erase_licenses() self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_EraseLicenses.return_value = -1 self.assertFalse(self.jlink.erase_licenses()) def test_jlink_erase_license_success(self): """Tests when erasing licenses succeeds. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetDLLVersion.return_value = 49802 self.dll.JLINK_EMU_EraseLicenses.return_value = 0 self.assertTrue(self.jlink.erase_licenses()) def test_jlink_tif(self): """Tests the J-Link ``tif`` getter. When a J-Link is created, this should be JTAG. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.assertEqual(enums.JLinkInterfaces.JTAG, self.jlink.tif) def test_jlink_supported_tifs(self): """Tests the J-Link ``supported_tifs`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.assertEqual(0, self.jlink.supported_tifs()) def test_jlink_set_tif_unsupported(self): """Tests that an exception is raised when setting an unsupported TIF. If the target interface is not supported by the J-Link, trying to set it will raise an exception. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.supported_tifs = mock.Mock() self.jlink.supported_tifs.return_value = 0 with self.assertRaises(JLinkException): self.jlink.set_tif(enums.JLinkInterfaces.SPI) def test_jlink_set_tif_failed(self): """Tests for failing to set the TIF. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.supported_tifs = mock.Mock() self.jlink.supported_tifs.return_value = (1 << enums.JLinkInterfaces.JTAG) self.dll.JLINKARM_TIF_Select.return_value = 1 self.assertFalse(self.jlink.set_tif(enums.JLinkInterfaces.JTAG)) def test_jlink_set_tif_success(self): """Tests for successfully setting a TIF. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.supported_tifs = mock.Mock() self.jlink.supported_tifs.return_value = (1 << enums.JLinkInterfaces.JTAG) self.dll.JLINKARM_TIF_Select.return_value = 0 self.assertTrue(self.jlink.set_tif(enums.JLinkInterfaces.JTAG)) def test_jlink_gpio_properties_failure(self): """Tests for failing to get the emulator's GPIO descriptors. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_EMU_GPIO_GetProps.return_value = -1 with self.assertRaises(JLinkException): self.jlink.gpio_properties() self.assertEqual(1, self.dll.JLINK_EMU_GPIO_GetProps.call_count) self.dll.JLINK_EMU_GPIO_GetProps = mock.Mock() self.dll.JLINK_EMU_GPIO_GetProps.side_effect = [1, -1] with self.assertRaises(JLinkException): self.jlink.gpio_properties() self.assertEqual(2, self.dll.JLINK_EMU_GPIO_GetProps.call_count) def test_jlink_gpio_properties_success(self): """Tests for succeeding in getting the emulator's GPIO descriptors. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_EMU_GPIO_GetProps.side_effect = [1, 1] props = self.jlink.gpio_properties() self.assertEqual(2, self.dll.JLINK_EMU_GPIO_GetProps.call_count) self.assertTrue(isinstance(props, list)) self.assertEqual(1, len(props)) self.assertTrue(all(map(lambda x: isinstance(x, structs.JLinkGPIODescriptor), props))) def test_jlink_gpio_get_failure(self): """Tests when getting GPIO pin states returns an error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_EMU_GPIO_GetState.return_value = -1 with self.assertRaises(JLinkException): self.jlink.gpio_get() with self.assertRaises(JLinkException): self.jlink.gpio_get([1, 2, 3]) def test_jlink_gpio_get_success(self): """Tests getting the GPIO pin states successfully. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_EMU_GPIO_GetState.return_value = 0 res = self.jlink.gpio_get([]) self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) def test_jlink_gpio_set_length_mismatch(self): """Tests failure to set GPIO pin states due to length mismatch. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.gpio_set([], [0]) with self.assertRaises(ValueError): self.jlink.gpio_set([0], []) with self.assertRaises(ValueError): self.jlink.gpio_set([2, 3, 4], [0, 1]) def test_jlink_gpio_set_failure(self): """Tests failure to set the GPIO pin states. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ pins = [2, 3] statuses = [1, 0] self.dll.JLINK_EMU_GPIO_SetState.return_value = -1 with self.assertRaises(JLinkException): self.jlink.gpio_set(pins, statuses) def test_jlink_gpio_set_success(self): """Tests succussfully setting the GPIO pin states. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_EMU_GPIO_SetState.return_value = 0 pins = [2, 3] statuses = [1, 0] res = self.jlink.gpio_set(pins, statuses) self.assertTrue(isinstance(res, list)) self.assertEqual(2, len(res)) def test_jlink_comm_supported(self): """Tests the J-Link ``comm_supported()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_COM_IsSupported.return_value = 0 self.assertFalse(self.jlink.comm_supported()) self.dll.JLINKARM_EMU_COM_IsSupported.return_value = 1 self.assertTrue(self.jlink.comm_supported()) @mock.patch('pylink.unlockers.unlock') def test_jlink_unlock_kinetis(self, mock_unlock): """Tests calling unlock on a connected Kinetis device. Args: self (TestJLink): the ``TestJLink`` instance mock_unlock (Mock): mocked unlock call Returns: ``None`` """ device = mock.Mock() device.manufacturer = 'Freescale' mock_unlock.side_effect = [True, False] self.jlink._device = device self.assertEqual(True, self.jlink.unlock()) mock_unlock.assert_called_with(self.jlink, device.manufacturer) with self.assertRaisesRegexp(JLinkException, 'Failed to unlock device'): self.jlink.unlock() def test_jlink_cpu_capability(self): """Tests the J-Link ``cpu_capability()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EMU_HasCPUCap.return_value = 0 self.assertFalse(self.jlink.cpu_capability(0)) self.dll.JLINKARM_EMU_HasCPUCap.return_value = 1 self.assertTrue(self.jlink.cpu_capability(0)) def test_jlink_set_trace_source(self): """Tests the J-Link ``set_trace_source()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ source = 0xdeadbeef self.jlink.set_trace_source(source) self.dll.JLINKARM_SelectTraceSource.assert_called_with(source) def test_jlink_set_etb_trace(self): """Tests setting ETB as the trace source. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_etb_trace() self.dll.JLINKARM_SelectTraceSource.assert_called_with(0) def test_jlink_set_etm_trace(self): """Tests setting ETM as the trace source. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_etm_trace() self.dll.JLINKARM_SelectTraceSource.assert_called_with(1) def test_jlink_power_on(self): """Tests the J-Link ``power_on()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.exec_command = mock.Mock() self.jlink.power_on() self.jlink.exec_command.assert_called_once_with('SupplyPower = 1') self.jlink.exec_command = mock.Mock() self.jlink.power_on(default=True) self.jlink.exec_command.assert_called_once_with('SupplyPowerDefault = 1') def test_jlink_power_off(self): """Tests the J-Link ``power_off()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.exec_command = mock.Mock() self.jlink.power_off() self.jlink.exec_command.assert_called_once_with('SupplyPower = 0') self.jlink.exec_command = mock.Mock() self.jlink.power_off(default=True) self.jlink.exec_command.assert_called_once_with('SupplyPowerDefault = 0') def test_jlink_set_reset_strategy(self): """Tests the J-Link ``set_reset_strategy()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ strategy = 1 self.dll.JLINKARM_SetResetType.return_value = 0 self.assertEqual(0, self.jlink.set_reset_strategy(strategy)) self.dll.JLINKARM_SetResetType.assert_called_once_with(strategy) def test_jlink_set_reset_pin(self): """Tests the J-Link ``set_reset_pin_*`` methods. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_reset_pin_high() self.dll.JLINKARM_SetRESET.assert_called_once() self.jlink.set_reset_pin_low() self.dll.JLINKARM_ClrRESET.assert_called_once() def test_jlink_set_tck_pin(self): """Tests the J-Link ``set_tck_pin_*`` methods. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SetTCK.return_value = 0 self.jlink.set_tck_pin_high() self.dll.JLINKARM_SetTCK.assert_called_once() self.dll.JLINKARM_SetTCK.return_value = -1 with self.assertRaisesRegexp(JLinkException, 'Feature not supported'): self.jlink.set_tck_pin_high() self.dll.JLINKARM_ClrTCK.return_value = 0 self.jlink.set_tck_pin_low() self.dll.JLINKARM_ClrTCK.assert_called_once() self.dll.JLINKARM_ClrTCK.return_value = -1 with self.assertRaisesRegexp(JLinkException, 'Feature not supported'): self.jlink.set_tck_pin_low() def test_jlink_set_tdi_pin(self): """Tests the J-Link ``set_tdi_pin_*`` methods. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_tdi_pin_high() self.dll.JLINKARM_SetTDI.assert_called_once() self.jlink.set_tdi_pin_low() self.dll.JLINKARM_ClrTDI.assert_called_once() def test_jlink_set_tms_pin(self): """Tests the J-Link ``set_tms_pin_*`` methods. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_tms_pin_high() self.dll.JLINKARM_SetTMS.assert_called_once() self.jlink.set_tms_pin_low() self.dll.JLINKARM_ClrTMS.assert_called_once() def test_jlink_set_trst_pin(self): """Tests the J-Link ``set_trst_pin_*`` methods. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.set_trst_pin_high() self.dll.JLINKARM_SetTRST.assert_called_once() self.jlink.set_trst_pin_low() self.dll.JLINKARM_ClrTRST.assert_called_once() def test_jlink_erase_failed_to_halt(self): """Tests the J-Link ``erase()`` method when device fails to halt. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.halted = mock.Mock() self.jlink.halted.side_effect = JLinkException(-1) self.jlink.halt = mock.Mock() self.dll.JLINK_EraseChip.return_value = 0 self.assertEqual(0, self.jlink.erase()) self.assertEqual(1, self.dll.JLINK_EraseChip.call_count) self.assertEqual(0, self.jlink.halt.call_count) def test_jlinK_erase_failed(self): """Tests the J-Link ``erase()`` method when it fails to erase. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.halted = mock.Mock() self.jlink.halted.side_effect = JLinkException(-1) self.jlink.halt = mock.Mock() self.dll.JLINK_EraseChip.return_value = -1 with self.assertRaises(JLinkException): self.jlink.erase() self.assertEqual(1, self.dll.JLINK_EraseChip.call_count) self.assertEqual(0, self.jlink.halt.call_count) def test_jlink_erase_success(self): """Tests a successful erase of the target. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.halted = mock.Mock() self.jlink.halted.return_value = False self.jlink.halt = mock.Mock() self.dll.JLINK_EraseChip.return_value = 1 self.assertEqual(1, self.jlink.erase()) self.assertEqual(1, self.dll.JLINK_EraseChip.call_count) self.assertEqual(1, self.jlink.halt.call_count) def test_jlink_flash_invalid_flags(self): """Tests trying to flash with invalid flags that an error is raised. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(JLinkException): self.jlink.flash([0], 0, flags=-1) with self.assertRaises(JLinkException): self.jlink.flash([0], 0, flags=1) def test_jlink_flash_fail_to_flash(self): """Tests when the flash fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EndDownload.return_value = -1 self.jlink.power_on = mock.Mock() self.jlink.erase = mock.Mock() self.jlink.memory_write = mock.Mock() self.jlink.halted = mock.Mock() self.jlink.halted.return_value = True with self.assertRaises(JLinkException): self.jlink.flash([0], 0) def test_jlink_flash_success(self): """Tests a successful flash. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_EndDownload.return_value = 0 self.jlink.power_on = mock.Mock() self.jlink.erase = mock.Mock() self.jlink.memory_write = mock.Mock() self.jlink.halt = mock.Mock() self.jlink.halted = mock.Mock() self.jlink.halted.return_value = True # With a progress callback. self.assertEqual(0, self.jlink.flash([0], 0, util.noop)) self.dll.JLINK_SetFlashProgProgressCallback.assert_called_once() arg = self.dll.JLINK_SetFlashProgProgressCallback.call_args[0][0] self.assertTrue(callable(arg)) # Without a progress callback self.assertEqual(0, self.jlink.flash([0], 0)) self.dll.JLINK_SetFlashProgProgressCallback.assert_called_with(0) # Halted exception self.jlink.halted.side_effect = JLinkException(-1) self.assertEqual(0, self.jlink.flash([0], 0)) self.jlink.halted.side_effect = None # Not halted self.jlink.halted.return_value = False self.assertEqual(0, self.jlink.flash([0], 0)) self.jlink.halt.assert_called_once() # Halted self.jlink.halted.return_value = True self.assertEqual(0, self.jlink.flash([0], 0)) self.jlink.halt.assert_called_once() # Without power by default self.jlink.power_on = mock.Mock() self.assertEqual(0, self.jlink.flash([0], 0)) self.jlink.power_on.assert_not_called() # With power self.jlink.power_on = mock.Mock() self.assertEqual(0, self.jlink.flash([0], 0, power_on=True)) self.jlink.power_on.assert_called_once() # Without power, explicit self.jlink.power_on = mock.Mock() self.assertEqual(0, self.jlink.flash([0], 0, power_on=False)) self.jlink.power_on.assert_not_called() def test_jlink_flash_file_fail_to_flash(self): """Tests when the flash fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_DownloadFile.return_value = -1 self.jlink.halted = mock.Mock() self.jlink.halted.return_value = True self.jlink.power_on = mock.Mock() self.jlink.erase = mock.Mock() with self.assertRaises(JLinkException): self.jlink.flash_file('path', 0) def test_jlink_flash_file_success(self): """Tests a successful flash. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_DownloadFile.return_value = 0 self.jlink.halted = mock.Mock() self.jlink.halted.return_value = True self.jlink.halt = mock.Mock() self.jlink.power_on = mock.Mock() self.jlink.erase = mock.Mock() # With a progress callback. self.assertEqual(0, self.jlink.flash_file('path', 0, util.noop)) self.dll.JLINK_SetFlashProgProgressCallback.assert_called_once() arg = self.dll.JLINK_SetFlashProgProgressCallback.call_args[0][0] self.assertTrue(callable(arg)) # Without a progress callback self.assertEqual(0, self.jlink.flash_file('path', 0)) self.dll.JLINK_SetFlashProgProgressCallback.assert_called_with(0) # Halted exception self.jlink.halted.side_effect = JLinkException(-1) self.assertEqual(0, self.jlink.flash_file('path', 0)) self.jlink.halted.side_effect = None # Not halted self.jlink.halted.return_value = False self.assertEqual(0, self.jlink.flash_file('path', 0)) self.jlink.halt.assert_called_once() # Halted self.jlink.halted.return_value = True self.assertEqual(0, self.jlink.flash_file('path', 0)) self.jlink.halt.assert_called_once() # With power self.jlink.power_on = mock.Mock() self.assertEqual(0, self.jlink.flash_file('path', 0, power_on=True)) self.jlink.power_on.assert_called_once() # Without power self.jlink.power_on = mock.Mock() self.assertEqual(0, self.jlink.flash_file('path', 0, power_on=False)) self.jlink.power_on.assert_not_called() def test_jlink_reset_fail(self): """Tests J-Link ``reset()`` when it fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Reset.return_value = -1 with self.assertRaises(JLinkException): self.jlink.reset() self.dll.JLINKARM_SetResetDelay.assert_called_once() def test_jlink_reset_halt(self): """Tests J-Link ``reset()`` success with halt. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Reset.return_value = 0 self.assertEqual(0, self.jlink.reset()) self.dll.JLINKARM_Reset.assert_called_once() self.dll.JLINKARM_Go.assert_not_called() self.dll.JLINKARM_SetResetDelay.assert_called_once() def test_jlink_reset_no_halt(self): """Tests J-Link ``reset()`` without halt. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Reset.return_value = 0 self.assertEqual(0, self.jlink.reset(halt=False)) self.dll.JLINKARM_Reset.assert_called_once() self.dll.JLINKARM_Go.assert_called_once() self.dll.JLINKARM_SetResetDelay.assert_called_once() def test_jlink_reset_tap(self): """Tests resetting the TAP controller. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.reset_tap() self.dll.JLINKARM_ResetTRST.assert_called_once() def test_jlink_restart_invalid_instructions(self): """Tests J-Link ``restart()`` with an invalid number of ops to simulate. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.restart(-1) with self.assertRaises(ValueError): self.jlink.restart('dog') def test_jlink_restart_not_halted(self): """Tests J-Link ``restart()`` when the target is not halted. If the target is not halted, ``restart()`` is a no-op. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.halted = mock.Mock() self.jlink.halted.return_value = False self.assertEqual(False, self.jlink.restart()) def test_jlink_restarted(self): """Tests J-Link ``restart()`` successfully restarting the target. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.halted = mock.Mock() self.jlink.halted.return_value = True self.assertEqual(True, self.jlink.restart()) self.dll.JLINKARM_GoEx.called_once_with(0, 0) self.dll.JLINKARM_GoEx = mock.Mock() self.assertEqual(True, self.jlink.restart(10, skip_breakpoints=True)) self.dll.JLINKARM_GoEx.called_once_with(10, enums.JLinkFlags.GO_OVERSTEP_BP) @mock.patch('time.sleep') def test_jlink_halt_failure(self, mock_sleep): """Tests J-Link ``halt()`` failure. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked ``time.sleep()`` call Returns: ``None`` """ self.dll.JLINKARM_Halt.return_value = 1 self.assertEqual(False, self.jlink.halt()) self.dll.JLINKARM_Halt.return_value = -1 self.assertEqual(False, self.jlink.halt()) self.assertEqual(0, mock_sleep.call_count) @mock.patch('time.sleep') def test_jlink_halt_success(self, mock_sleep): """Tests J-Link ``halt()`` success. Args: self (TestJLink): the ``TestJLink`` instance mock_sleep (Mock): mocked ``time.sleep()`` call Returns: ``None`` """ self.dll.JLINKARM_Halt.return_value = 0 self.assertEqual(True, self.jlink.halt()) self.assertEqual(1, mock_sleep.call_count) def test_jlink_halted_on_error(self): """Tests when querying if the target is halted fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsHalted.return_value = -1 with self.assertRaises(JLinkException): self.jlink.halted() def test_jlink_halted_on_success(self): """Tests when querying if the target is halted succeeds. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_IsHalted.return_value = 1 self.assertEqual(True, self.jlink.halted()) self.dll.JLINKARM_IsHalted.return_value = 255 self.assertEqual(True, self.jlink.halted()) self.dll.JLINKARM_IsHalted.return_value = 0 self.assertEqual(False, self.jlink.halted()) def test_jlink_core_id(self): """Tests the J-Link ``core_id()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ core_id = 1337 self.dll.JLINKARM_GetId.return_value = core_id self.assertEqual(core_id, self.jlink.core_id()) def test_jlink_core_cpu(self): """Tests the J-Link ``core_cpu()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ core_cpu = 234881279 self.dll.JLINKARM_CORE_GetFound.return_value = core_cpu self.assertEqual(core_cpu, self.jlink.core_cpu()) def test_jlink_core_name(self): """Tests retrieving the CPU core's name. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ core_cpu = 234881279 core_name = b'Cortex-M4' self.dll.JLINKARM_CORE_GetFound.return_value = core_cpu def write_core_name(cpu, buf, buf_size): for (index, ch) in enumerate(core_name): buf[index] = ch self.assertEqual(cpu, core_cpu) self.dll.JLINKARM_Core2CoreName.side_effect = write_core_name self.assertEqual(core_name.decode(), self.jlink.core_name()) self.dll.JLINKARM_CORE_GetFound.assert_called_once() self.dll.JLINKARM_Core2CoreName.assert_called_once() def test_jlink_ir_len(self): """Tests the J-Link ``ir_len()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ ir_len = 2 self.dll.JLINKARM_GetIRLen.return_value = ir_len self.assertEqual(ir_len, self.jlink.ir_len()) def test_jlink_scan_len(self): """Tests the J-Link ``scan_len()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ scan_len = 2 self.dll.JLINKARM_GetScanLen.return_value = scan_len self.assertEqual(scan_len, self.jlink.scan_len()) def test_jlink_scan_chain_len(self): """Tests getting the scan chain length of the J-Link. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ scan_chain = 1 self.dll.JLINKARM_MeasureSCLen.return_value = -1 with self.assertRaises(JLinkException): self.jlink.scan_chain_len(scan_chain) self.dll.JLINKARM_MeasureSCLen.return_value = 0 self.assertEqual(0, self.jlink.scan_chain_len(scan_chain)) def test_jlink_device_family(self): """Tests the J-Link ``device_family()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ family = enums.JLinkDeviceFamily.CORTEX_M1 self.dll.JLINKARM_GetDeviceFamily.return_value = family self.assertEqual(family, self.jlink.device_family()) family = enums.JLinkDeviceFamily.CORTEX_M3 self.dll.JLINKARM_GetDeviceFamily.return_value = family self.assertEqual(family, self.jlink.device_family()) def test_jlink_register_list(self): """Tests the J-Link ``register_list()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetRegisterList.return_value = 0 res = self.jlink.register_list() self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) def test_jlink_register_name(self): """Tests the J-Link ``register_name()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ register_name = 'Name' buf = ctypes.create_string_buffer(register_name.encode(), len(register_name)) self.dll.JLINKARM_GetRegisterName.return_value = ctypes.addressof(buf) self.assertEqual(register_name, self.jlink.register_name(0)) def test_jlink_cpu_speed_error(self): """Tests the J-Link ``cpu_speed()`` method on error. Args: self (TestJlink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_MeasureCPUSpeedEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.cpu_speed() def test_jlink_cpu_speed_success(self): """Tests the J-Link ``cpu_speed()`` method on success. There are three cases: - When silent option is passed. - When silent option is not passed. - When CPU speed is not supported. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ # Unsupported self.dll.JLINKARM_MeasureCPUSpeedEx.return_value = 0 self.assertEqual(0, self.jlink.cpu_speed()) # Silent option not passed self.dll.JLINKARM_MeasureCPUSpeedEx.return_value = 1 self.assertEqual(1, self.jlink.cpu_speed()) self.dll.JLINKARM_MeasureCPUSpeedEx.assert_called_with(-1, 1, 0) # Silent option passed self.dll.JLINKARM_MeasureCPUSpeedEx.return_value = 1 self.assertEqual(1, self.jlink.cpu_speed(silent=True)) self.dll.JLINKARM_MeasureCPUSpeedEx.assert_called_with(-1, 1, 1) def test_jlink_cpu_halt_reasons_failure(self): """Tests failing to get the CPU halt reasons. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetMOEs.return_value = -1 with self.assertRaises(JLinkException): self.jlink.cpu_halt_reasons() def test_jlink_cpu_halt_reasons_success(self): """Tests successfully getting the CPU halt reasons. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetMOEs.return_value = 0 halt_reasons = self.jlink.cpu_halt_reasons() self.assertTrue(isinstance(halt_reasons, list)) self.assertEqual(0, len(halt_reasons)) self.dll.JLINKARM_GetMOEs.return_value = 1 halt_reasons = self.jlink.cpu_halt_reasons() self.assertTrue(isinstance(halt_reasons, list)) self.assertEqual(1, len(halt_reasons)) self.assertTrue(isinstance(halt_reasons[0], structs.JLinkMOEInfo)) def test_jlink_jtag_create_clock(self): """Tests creating a JTAG clock on TCK. Should return the status of the TDO pin: either 0 or 1. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Clock.return_value = 0 self.assertEqual(0, self.jlink.jtag_create_clock()) self.dll.JLINKARM_Clock.return_value = 1 self.assertEqual(1, self.jlink.jtag_create_clock()) def test_jlink_jtag_send_invalid_bits(self): """Tests passing an invalid number of bits to ``jtag_send()``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ tms = 0 tdi = 0 num_bits = 0 with self.assertRaises(ValueError): self.jlink.jtag_send(tms, tdi, num_bits) num_bits = -1 with self.assertRaises(ValueError): self.jlink.jtag_send(tms, tdi, num_bits) num_bits = 33 with self.assertRaises(ValueError): self.jlink.jtag_send(tms, tdi, num_bits) def test_jlink_jtag_send_success(self): """Tests successfully sending data via JTAG. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ tms = 0 tdi = 0 num_bits = 1 self.assertEqual(None, self.jlink.jtag_send(tms, tdi, num_bits)) def test_jlink_jtag_flush(self): """Tests successfully flushing the JTAG buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.jtag_flush() self.dll.JLINKARM_WriteBits.assert_called_once() def test_jlink_swd_read8(self): """Tests the J-Link ``swd_read8()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD val = 10 self.dll.JLINK_SWD_GetU8.return_value = val self.assertEqual(val, self.jlink.swd_read8(0)) def test_jlink_swd_read16(self): """Tests the J-Link ``swd_read16()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD val = 10 self.dll.JLINK_SWD_GetU16.return_value = val self.assertEqual(val, self.jlink.swd_read16(0)) def test_jlink_swd_read32(self): """Tests the J-Link ``swd_read32()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD val = 10 self.dll.JLINK_SWD_GetU32.return_value = val self.assertEqual(val, self.jlink.swd_read32(0)) def test_jlink_swd_write_fail(self): """Tests the J-Link ``swd_write()`` method on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.dll.JLINK_SWD_StoreRaw.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swd_write(0, 0, 32) def test_jlink_swd_write_success(self): """Tests the J-Link ``swd_write()`` method on success. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD bitpos = 1 self.dll.JLINK_SWD_StoreRaw.return_value = bitpos self.assertEqual(bitpos, self.jlink.swd_write(8, 8, 8)) self.dll.JLINK_SWD_StoreRaw.assert_called_once() def test_jlink_swd_write8(self): """Tests the J-Link ``swd_write8()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.jlink.swd_write = mock.Mock() self.jlink.swd_write8(0, 0) self.jlink.swd_write.assert_called_once_with(0, 0, 8) def test_jlink_swd_write16(self): """Tests the J-Link ``swd_write16()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.jlink.swd_write = mock.Mock() self.jlink.swd_write16(0, 0) self.jlink.swd_write.assert_called_once_with(0, 0, 16) def test_jlink_swd_write32(self): """Tests the J-Link ``swd_write32()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.jlink.swd_write = mock.Mock() self.jlink.swd_write32(0, 0) self.jlink.swd_write.assert_called_once_with(0, 0, 32) def test_jlink_swd_sync(self): """Tests the J-Link ``swd_sync()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink._tif = enums.JLinkInterfaces.SWD self.assertEqual(None, self.jlink.swd_sync()) self.dll.JLINK_SWD_SyncBits.assert_called_once() self.assertEqual(None, self.jlink.swd_sync(pad=True)) self.dll.JLINK_SWD_SyncBytes.assert_called_once() def test_jlink_flash_write_access_width(self): """Tests calling the flash write methods with variable access width. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0xdeadbeef self.jlink.flash_write = mock.Mock() self.jlink.flash_write8(addr, [0xFF]) self.jlink.flash_write.assert_called_with(addr, [0xFF], 8) self.jlink.flash_write16(addr, [0xFFFF]) self.jlink.flash_write.assert_called_with(addr, [0xFFFF], 16) self.jlink.flash_write32(addr, [0xFFFFFFFF]) self.jlink.flash_write.assert_called_with(addr, [0xFFFFFFFF], 32) def test_jlink_code_memory_read_invalid(self): """Tests failing to read code memory. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadCodeMem.return_value = -1 with self.assertRaises(JLinkException): self.jlink.code_memory_read(0, 1) def test_jlink_code_memory_read_success(self): """Tests successfully reading code memory. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadCodeMem.return_value = 0 res = self.jlink.code_memory_read(0, 1) self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) self.dll.JLINKARM_ReadCodeMem.return_value = 1 res = self.jlink.code_memory_read(0, 1) self.assertTrue(isinstance(res, list)) self.assertEqual(1, len(res)) self.assertTrue(isinstance(res[0], int)) def test_jlink_num_memory_zones(self): """Tests the J-Link ``num_memory_zones()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_GetMemZones.return_value = -1 with self.assertRaises(JLinkException): self.jlink.num_memory_zones() self.dll.JLINK_GetMemZones.return_value = 2 self.assertEqual(2, self.jlink.num_memory_zones()) def test_jlink_memory_zones_empty(self): """Tests the J-Link ``memory_zones()`` method with no zones. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.num_memory_zones = mock.Mock() self.jlink.num_memory_zones.return_value = 0 res = self.jlink.memory_zones() self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) self.assertEqual(0, self.dll.JLINK_GetMemZones.call_count) def test_jlink_memory_zones_failure(self): """Tests the J-Link ``memory_zones()`` method on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.num_memory_zones = mock.Mock() self.jlink.num_memory_zones.return_value = 1 self.dll.JLINK_GetMemZones.return_value = -1 with self.assertRaises(JLinkException): self.jlink.memory_zones() def test_jlink_memory_zones_success(self): """Tests the J-Link ``memory_zones()`` on success. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.num_memory_zones = mock.Mock() self.jlink.num_memory_zones.return_value = 1 self.dll.JLINK_GetMemZones.return_value = 0 res = self.jlink.memory_zones() self.assertTrue(isinstance(res, list)) self.assertEqual(1, len(res)) self.assertTrue(all(map(lambda x: isinstance(x, structs.JLinkMemoryZone), res))) self.assertEqual(1, self.dll.JLINK_GetMemZones.call_count) def test_jlink_memory_read_failure(self): """Tests a memory read that fails to read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadMemEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.memory_read(0, 1) def test_jlink_memory_read_invalid_access(self): """Tests the memory read fails when given an invalid access width. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.memory_read(0, 0, nbits=42) with self.assertRaises(ValueError): self.jlink.memory_read(0, 0, nbits=13) with self.assertRaises(ValueError): self.jlink.memory_read(0, 0, nbits=-1) def test_jlink_memory_read_zoned(self): """Tests a memory read of a zoned memory region. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadMemZonedEx.return_value = 0 res = self.jlink.memory_read(0, 1, 'zone') self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) self.dll.JLINKARM_ReadMemZonedEx.assert_called_once() self.dll.JLINKARM_ReadMemEx.assert_not_called() def test_jlink_memory_read_unzoned(self): """Tests a memory read of an unzoned region. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadMemEx.return_value = 0 res = self.jlink.memory_read(0, 1) self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) self.dll.JLINKARM_ReadMemEx.assert_called_once() self.dll.JLINKARM_ReadMemZonedEx.assert_not_called() def test_jlink_memory_read_access(self): """Tests the different memory read access bits. There are three types of ways to access memory: by byte, by halfword, and by word. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_units = 4 accesses = [1, 2, 4] def write_to_memory(addr, buf_size, buf, access): self.assertEqual(num_units * access, buf_size) # Write a byte first buf[0] = 0xFF # Write a halfword next buf[1] = 0xFF00 # Write a word next buf[2] = 0xFFFF0000 # Write a long word next buf[3] = 0xFFFFFFFF00000000 self.assertEqual(accesses.pop(0), access) return num_units self.dll.JLINKARM_ReadMemEx.side_effect = write_to_memory self.dll.JLINKARM_ReadMemEx.return_value = num_units res = self.jlink.memory_read(0, num_units, nbits=8) self.assertEqual(num_units, len(res)) self.assertEqual(0xFF, res[0]) self.assertEqual(0x00, res[1]) self.assertEqual(0x00, res[2]) self.assertEqual(0x00, res[3]) res = self.jlink.memory_read(0, num_units, nbits=16) self.assertEqual(num_units, len(res)) self.assertEqual(0xFF, res[0]) self.assertEqual(0xFF00, res[1]) self.assertEqual(0x00, res[2]) self.assertEqual(0x00, res[3]) res = self.jlink.memory_read(0, num_units, nbits=32) self.assertEqual(num_units, len(res)) self.assertEqual(0xFF, res[0]) self.assertEqual(0xFF00, res[1]) self.assertEqual(0xFFFF0000, res[2]) self.assertEqual(0x00, res[3]) def test_jlink_memory_read_byte_halfword_word(self): """Tests the memory read functions for bytes, halfwords and words. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.memory_read = mock.Mock() self.jlink.memory_read8(0, 0) self.jlink.memory_read.assert_called_with(0, 0, nbits=8, zone=None) self.jlink.memory_read16(0, 0) self.jlink.memory_read.assert_called_with(0, 0, zone=None, nbits=16) self.jlink.memory_read32(0, 0) self.jlink.memory_read.assert_called_with(0, 0, zone=None, nbits=32) def test_jlink_memory_read_longword(self): """Tests the memory read function for a longword. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadMemU64.return_value = -1 with self.assertRaises(JLinkException): self.jlink.memory_read64(0, 0) self.dll.JLINKARM_ReadMemU64.return_value = 0 res = self.jlink.memory_read64(0, 0) self.assertTrue(isinstance(res, list)) self.assertEqual(0, len(res)) def test_jlink_memory_write_invalid_access(self): """Tests the memory write fails when given an invalid access width. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.memory_write(0, [0], nbits=42) with self.assertRaises(ValueError): self.jlink.memory_write(0, [0], nbits=13) with self.assertRaises(ValueError): self.jlink.memory_write(0, [0], nbits=-1) def test_jlink_memory_write_failure(self): """Tests a memory write that fails to write. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteMemEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.memory_write(0, [0]) def test_jlink_memory_write_zoned(self): """Tests a memory write to a zoned memory region. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteMemZonedEx.return_value = 0 self.assertEqual(0, self.jlink.memory_write(0, [0], 'zone')) self.dll.JLINKARM_WriteMemZonedEx.assert_called_once() self.dll.JLINKARM_WriteMemEx.assert_not_called() def test_jlink_memory_write_unzoned(self): """Tests a memory write to an unzoned memory region. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteMemEx.return_value = 0 self.assertEqual(0, self.jlink.memory_write(0, [0])) self.dll.JLINKARM_WriteMemEx.assert_called_once() self.dll.JLINKARM_WriteMemZonedEx.assert_not_called() def test_jlink_memory_write_access_width(self): """Tests the access width specified memory writes. There are three types of memory accesses: bytes, half words, and full word access. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_units = 4 accesses = [1, 2, 4] def read_from_memory(addr, buf_size, buf, access): self.assertEqual(num_units * access, buf_size) self.assertEqual(accesses.pop(0), access) if access == 1: self.assertEqual(0xFF, buf[0]) self.assertEqual(0x00, buf[1]) self.assertEqual(0x00, buf[2]) self.assertEqual(0x00, buf[3]) elif access == 2: self.assertEqual(0xFF, buf[0]) self.assertEqual(0xFF00, buf[1]) self.assertEqual(0x00, buf[2]) self.assertEqual(0x00, buf[3]) elif access == 4: self.assertEqual(0xFF, buf[0]) self.assertEqual(0xFF00, buf[1]) self.assertEqual(0xFFFF0000, buf[2]) self.assertEqual(0x00, buf[3]) return num_units self.dll.JLINKARM_WriteMemEx.side_effect = read_from_memory self.dll.JLINKARM_WriteMemEx.return_value = num_units data = [0xFF, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000] self.assertEqual(num_units, self.jlink.memory_write8(0, data)) self.assertEqual(num_units, self.jlink.memory_write16(0, data)) self.assertEqual(num_units, self.jlink.memory_write32(0, data)) self.assertEqual(0, len(accesses)) def test_jlink_memory_write_no_access_width(self): """Tests memory write with an unspecified access width and intger size. When a memory write occurs, the data must either be written into an array of 8-bit unsigned integers, 16-bit unsigned integers, or 32-bit unsigned intgers. Since a list of any sized integers can be passed in, we hvae to ensure we properly pack it into 8-bit unsigned integers. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ data = [1 << 8, 1 << 16, 1 << 32] self.dll.JLINKARM_WriteMemEx.return_value = 0 self.jlink.memory_write(0, data) _, num_bytes, data, width = self.dll.JLINKARM_WriteMemEx.call_args[0] self.assertEqual(0, width) self.assertEqual(10, num_bytes) self.assertEqual(10, len(data)) # 1 << 8 self.assertEqual(1, data[0]) self.assertEqual(0, data[1]) # 1 << 16 self.assertEqual(1, data[2]) self.assertEqual(0, data[3]) self.assertEqual(0, data[4]) # 1 << 32 self.assertEqual(1, data[5]) self.assertEqual(0, data[6]) self.assertEqual(0, data[7]) self.assertEqual(0, data[8]) self.assertEqual(0, data[9]) def test_jlink_memory_write_long_word(self): """Tests the ``memory_write64()`` method. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ long_word = 0xFFFFFFFF00000000 self.jlink.memory_write32 = mock.Mock() self.jlink.memory_write64(0, [long_word]) first, last = self.jlink.memory_write32.call_args[0][1] self.assertEqual(last, 0xFFFFFFFF) self.assertEqual(first, 0x00000000) def test_jlink_register_read_single(self): """Tests reading a single register at a time. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadReg.return_value = 0xFF self.assertEqual(0xFF, self.jlink.register_read(0)) def test_jlink_register_read_single_from_name(self): """Tests reading a single register at a time. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetRegisterList.return_value = 1 self.dll.JLINKARM_GetRegisterName.return_value = 'R0'.encode() self.dll.JLINKARM_ReadReg.return_value = 0xFF self.assertEqual(0xFF, self.jlink.register_read('R0')) def test_jlink_register_read_multiple_failure(self): """Tests failing to read multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadRegs.return_value = -1 with self.assertRaises(JLinkException): self.jlink.register_read_multiple([2, 3, 4]) def test_jlink_register_read_multiple_success(self): """Tests successfully reading multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadRegs.return_value = 0 res = self.jlink.register_read_multiple(list(range(10))) self.assertTrue(isinstance(res, list)) self.assertEqual(10, len(res)) self.assertTrue(all(x == 0 for x in res)) def test_jlink_register_read_multiple_from_name_failure(self): """Tests successfully reading multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def register_list(buf, _): num_items = 3 for i in range(num_items): buf[i] = i return num_items self.dll.JLINKARM_ReadRegs.return_value = 0 self.dll.JLINKARM_GetRegisterList.side_effect = register_list self.dll.JLINKARM_GetRegisterName.side_effect = lambda idx: 'R{}'.format(idx + 10).encode() with self.assertRaises(JLinkException) as exception: self.jlink.register_read_multiple(['R{}'.format(idx) for idx in range(3)]) assert str(exception.exception) == 'No register found matching name: R0. (available registers: R10, R11, R12)' def test_jlink_register_read_multiple_from_name_success(self): """Tests successfully reading multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def register_list(buf, num_items): for i in range(num_items): buf[i] = i return num_items self.dll.JLINKARM_ReadRegs.return_value = 0 self.dll.JLINKARM_GetRegisterList.side_effect = register_list self.dll.JLINKARM_GetRegisterName.side_effect = lambda idx: 'R{}'.format(idx).encode() res = self.jlink.register_read_multiple(['R{}'.format(idx) for idx in range(10)]) self.assertTrue(isinstance(res, list)) self.assertEqual(10, len(res)) self.assertTrue(all(x == 0 for x in res)) def test_jlink_register_write_single_failure(self): """Tests failing to write to a single register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteReg.return_value = -1 with self.assertRaises(JLinkException): self.jlink.register_write(0, 0xFF) def test_jlink_register_write_single_success(self): """Tests successfully writing to a single register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteReg.return_value = 0 self.assertEqual(0xFF, self.jlink.register_write(0, 0xFF)) def test_jlink_register_write_single_from_name_success(self): """Tests successfully writing to a single register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteReg.return_value = 0 self.dll.JLINKARM_GetRegisterList.return_value = 1 self.dll.JLINKARM_GetRegisterName.return_value = 'R0'.encode() self.assertEqual(0xFF, self.jlink.register_write('R0', 0xFF)) def test_jlink_register_write_multiple_failure(self): """Tests failing to write to multiple registers at once. There are two conditions to failure: - The number of values aren't equal to the number of registers; or - The J-Link fails to write to the registers. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaisesRegexp(ValueError, 'equal number'): self.jlink.register_write_multiple([2, 3], [1]) with self.assertRaisesRegexp(ValueError, 'equal number'): self.jlink.register_write_multiple([2, 3], [1, 4, 5]) self.dll.JLINKARM_WriteRegs.return_value = -1 with self.assertRaises(JLinkException): self.jlink.register_write_multiple([2, 3, 4], [2, 3, 4]) def test_jlink_register_write_multiple_success(self): """Tests succussfully writing to multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteRegs.return_value = 0 res = self.jlink.register_write_multiple([0, 1], [0xFF, 0xFF]) self.assertEqual(None, res) indices, values, _, count = self.dll.JLINKARM_WriteRegs.call_args[0] self.assertEqual(2, count) self.assertEqual(list(indices), [0, 1]) self.assertEqual(list(values), [0xFF] * count) def test_jlink_register_write_multiple_from_name_success(self): """Tests succussfully writing to multiple registers at once. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def register_list(buf, num_items): for i in range(num_items): buf[i] = i return num_items self.dll.JLINKARM_WriteRegs.return_value = 0 self.dll.JLINKARM_GetRegisterList.side_effect = register_list self.dll.JLINKARM_GetRegisterName.side_effect = lambda idx: 'R{}'.format(idx).encode() res = self.jlink.register_write_multiple(['R0', 'R1'], [0xFF, 0xFF]) self.assertEqual(None, res) indices, values, _, count = self.dll.JLINKARM_WriteRegs.call_args[0] self.assertEqual(2, count) self.assertEqual(list(indices), [0, 1]) self.assertEqual(list(values), [0xFF] * count) def test_jlink_ice_register_read_success(self): """Tests successfully reading from an ICE register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ReadICEReg.return_value = 0x123456789 self.assertEqual(0x123456789, self.jlink.ice_register_read(0x08)) def test_jlink_ice_register_write_success(self): """Tests successfully writing to an ARM ICE register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.assertEqual(None, self.jlink.ice_register_write(0x08, 0x123456789, True)) self.dll.JLINKARM_WriteICEReg.assert_called_with(0x08, 0x123456789, 1) self.assertEqual(None, self.jlink.ice_register_write(0x08, 0x123456789, False)) self.dll.JLINKARM_WriteICEReg.assert_called_with(0x08, 0x123456789, 0) def test_jlink_etm_supported_arm_7_9_supported(self): """Tests when ETM is supported on an ARM 7/9 core. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ETM_IsPresent.return_value = 1 self.assertTrue(self.jlink.etm_supported()) self.dll.JLINKARM_ETM_IsPresent.assert_called_once() self.dll.JLINKARM_GetDebugInfo.assert_not_called() def test_jlink_etm_supported_cortex_m_supported(self): """Tests when ETM is supported on a Cortex-M core. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ETM_IsPresent.return_value = 0 self.dll.JLINKARM_GetDebugInfo.return_value = 0 self.assertTrue(self.jlink.etm_supported()) self.dll.JLINKARM_ETM_IsPresent.assert_called_once() self.dll.JLINKARM_GetDebugInfo.assert_called_once() def test_jlink_etm_supported_not_supported(self): """Tests when ETM is not supported on a Cortex-M core. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_ETM_IsPresent.return_value = 0 self.dll.JLINKARM_GetDebugInfo.return_value = 1 self.assertFalse(self.jlink.etm_supported()) self.dll.JLINKARM_ETM_IsPresent.assert_called_once() self.dll.JLINKARM_GetDebugInfo.assert_called_once() def test_jlink_etm_register_read(self): """Tests reading an ETM register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ index = 0xdeadbeef self.jlink.etm_register_read(index) self.dll.JLINKARM_ETM_ReadReg.assert_called_once_with(index) def test_jlink_etm_register_write(self): """Tests writing to an ETM register. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ index = 0xdeadbeef value = 0x1337 self.jlink.etm_register_write(index, value) self.dll.JLINKARM_ETM_WriteReg.assert_called_once_with(index, value, 0) def test_jlink_coresight_read_failure(self): """Tests the ``coresight_read()`` method on failure to read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CORESIGHT_ReadAPDPReg.return_value = -1 with self.assertRaises(JLinkException): self.jlink.coresight_read([0], [0xFF]) def test_jlink_coresight_read_success(self): """Tests the ``coresight_read()`` method on successful read. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CORESIGHT_ReadAPDPReg.return_value = 0 self.assertEqual(0, self.jlink.coresight_read(0, True)) self.assertEqual(0, self.jlink.coresight_read(0, False)) def test_jlink_coresight_write_failure(self): """Tests the ``coresight_write()`` method on failure to write. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CORESIGHT_WriteAPDPReg.return_value = -1 with self.assertRaises(JLinkException): self.jlink.coresight_write(0, 0) def test_jlink_coresight_write_success(self): """Tests the ``coresight_write()`` method on successful write. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CORESIGHT_WriteAPDPReg.return_value = 0 self.assertEqual(0, self.jlink.coresight_write(0, 0, True)) self.dll.JLINKARM_CORESIGHT_WriteAPDPReg.assert_called_with(0, 1, 0) self.assertEqual(0, self.jlink.coresight_write(0, 0, False)) self.dll.JLINKARM_CORESIGHT_WriteAPDPReg.assert_called_with(0, 0, 0) def test_jlink_reset_pulls_reset(self): """Tests setting / unsetting the RESET pin. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.enable_reset_pulls_reset() self.dll.JLINKARM_ResetPullsRESET.assert_called_with(1) self.jlink.disable_reset_pulls_reset() self.dll.JLINKARM_ResetPullsRESET.assert_called_with(0) def test_jlink_reset_pulls_trst(self): """Tests setting / unsetting the TRST pin. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.enable_reset_pulls_trst() self.dll.JLINKARM_ResetPullsTRST.assert_called_with(1) self.jlink.disable_reset_pulls_trst() self.dll.JLINKARM_ResetPullsTRST.assert_called_with(0) def test_jlink_reset_inits_registers(self): """Tests setting registers to initialize or not on reset. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.enable_reset_inits_registers() self.dll.JLINKARM_SetInitRegsOnReset.assert_called_with(1) self.jlink.disable_reset_inits_registers() self.dll.JLINKARM_SetInitRegsOnReset.assert_called_with(0) def test_jlink_set_little_endian(self): """Tests setting the endianess of the target to little endian. Args: self (TestJlink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SetEndian.return_value = 1 self.assertTrue(self.jlink.set_little_endian()) self.dll.JLINKARM_SetEndian.assert_called_with(0) self.dll.JLINKARM_SetEndian.return_value = 0 self.assertFalse(self.jlink.set_little_endian()) self.dll.JLINKARM_SetEndian.assert_called_with(0) def test_jlink_set_big_endian(self): """Tests setting the endianess of the target to big endian. Args: self (TestJlink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SetEndian.return_value = 0 self.assertTrue(self.jlink.set_big_endian()) self.dll.JLINKARM_SetEndian.assert_called_with(1) self.dll.JLINKARM_SetEndian.return_value = 1 self.assertFalse(self.jlink.set_big_endian()) self.dll.JLINKARM_SetEndian.assert_called_with(1) def test_jlink_set_vector_catch(self): """Tests setting a vector catch. A vector catch is used to have the CPU halt when certain events occur. There are two conditions when setting a vector catch: either it succeeds or it fails with a ``JLinkException``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_WriteVectorCatch.return_value = -1 with self.assertRaises(JLinkException): self.jlink.set_vector_catch(0xFF) self.dll.JLINKARM_WriteVectorCatch.return_value = 0 self.assertEqual(None, self.jlink.set_vector_catch(0xFF)) def test_jlink_step(self): """Tests stepping the target CPU. There are two possible ways to step: a normal step or a step in THUMB mode. A step can also fail with a ``JLinkException``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_Step.return_value = -1 with self.assertRaises(JLinkException): self.jlink.step() self.dll.JLINKARM_Step.return_value = 0 self.assertEqual(None, self.jlink.step()) self.dll.JLINKARM_StepComposite.return_value = -1 with self.assertRaises(JLinkException): self.jlink.step(thumb=True) self.dll.JLINKARM_Step.return_value = -1 self.dll.JLINKARM_StepComposite.return_value = 0 self.assertEqual(None, self.jlink.step(thumb=True)) def test_jlink_enable_software_breakpoints(self): """Tests enabling the software breakpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.enable_soft_breakpoints() self.dll.JLINKARM_EnableSoftBPs.assert_called_with(1) def test_jlink_disable_software_breakpoints(self): """Tests disabling the software breakpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.disable_soft_breakpoints() self.dll.JLINKARM_EnableSoftBPs.assert_called_with(0) def test_jlink_num_active_breakpoints(self): """Tests querying the number of active breakpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_active_breakpoints = 20 self.dll.JLINKARM_GetNumBPs.return_value = num_active_breakpoints self.assertEqual(num_active_breakpoints, self.jlink.num_active_breakpoints()) def test_jlink_num_available_breakpoints(self): """Tests querying the number of available breakpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ breakpoint_types = dict(( (enums.JLinkBreakpoint.ARM, 1), (enums.JLinkBreakpoint.THUMB, 2), (enums.JLinkBreakpoint.SW_RAM, 3), (enums.JLinkBreakpoint.SW_FLASH, 4), (enums.JLinkBreakpoint.HW, 5) )) num_breakpoints = sum(breakpoint_types.values()) def get_num_bp_units(flags): if flags == enums.JLinkBreakpoint.ANY: return num_breakpoints count = 0 for (mask, value) in breakpoint_types.items(): if flags & mask: count = count + value return count self.dll.JLINKARM_GetNumBPUnits = get_num_bp_units self.assertEqual(num_breakpoints, self.jlink.num_available_breakpoints()) count = breakpoint_types[enums.JLinkBreakpoint.ARM] self.assertEqual(count, self.jlink.num_available_breakpoints(arm=True)) flags = [enums.JLinkBreakpoint.THUMB, enums.JLinkBreakpoint.SW_RAM] count = sum(breakpoint_types[f] for f in flags) self.assertEqual(count, self.jlink.num_available_breakpoints(thumb=True, ram=True)) def test_jlink_breakpoint_info(self): """Tests querying for the breakpoint information. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetBPInfoEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.breakpoint_info(0x1) self.dll.JLINKARM_GetBPInfoEx.return_value = 0 with self.assertRaises(ValueError): self.jlink.breakpoint_info() bp = self.jlink.breakpoint_info(0x1) self.assertTrue(isinstance(bp, structs.JLinkBreakpointInfo)) def test_jlink_breakpoint_find(self): """Tests searching for a breakpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_FindBP.return_value = 0 self.assertEqual(0, self.jlink.breakpoint_find(0x1337)) self.dll.JLINKARM_FindBP.return_value = 1 self.assertEqual(1, self.jlink.breakpoint_find(0x1337)) def test_jlink_breakpoint_set(self): """Tests setting a breakpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0x1337 self.dll.JLINKARM_SetBPEx.return_value = 0 with self.assertRaises(JLinkException): self.jlink.breakpoint_set(addr) self.dll.JLINKARM_SetBPEx.return_value = 1 self.assertEqual(1, self.jlink.breakpoint_set(addr)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.ANY) self.dll.JLINKARM_SetBPEx.return_value = 2 self.assertEqual(2, self.jlink.breakpoint_set(addr, arm=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.ARM | enums.JLinkBreakpoint.ANY) self.dll.JLINKARM_SetBPEx.return_value = 3 self.assertEqual(3, self.jlink.breakpoint_set(addr, thumb=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.THUMB | enums.JLinkBreakpoint.ANY) def test_jlink_software_breakpoint_set(self): """Tests setting a software breakpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0x1337 self.dll.JLINKARM_SetBPEx.return_value = 0 with self.assertRaises(JLinkException): self.jlink.software_breakpoint_set(addr) self.dll.JLINKARM_SetBPEx.return_value = 1 self.assertEqual(1, self.jlink.software_breakpoint_set(addr)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW) self.assertEqual(1, self.jlink.software_breakpoint_set(addr, arm=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW | enums.JLinkBreakpoint.ARM) self.assertEqual(1, self.jlink.software_breakpoint_set(addr, thumb=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW | enums.JLinkBreakpoint.THUMB) self.assertEqual(1, self.jlink.software_breakpoint_set(addr, arm=True, flash=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW_FLASH | enums.JLinkBreakpoint.ARM) self.assertEqual(1, self.jlink.software_breakpoint_set(addr, arm=True, ram=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW_RAM | enums.JLinkBreakpoint.ARM) self.assertEqual(1, self.jlink.software_breakpoint_set(addr, thumb=True, ram=True, flash=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.SW | enums.JLinkBreakpoint.THUMB) def test_jlink_hardware_breakpoint_set(self): """Tests setting a hardware breakpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0x1337 self.dll.JLINKARM_SetBPEx.return_value = 0 with self.assertRaises(JLinkException): self.jlink.hardware_breakpoint_set(addr) self.dll.JLINKARM_SetBPEx.return_value = 1 self.assertEqual(1, self.jlink.hardware_breakpoint_set(addr)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.HW) self.assertEqual(1, self.jlink.hardware_breakpoint_set(addr, arm=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.HW | enums.JLinkBreakpoint.ARM) self.assertEqual(1, self.jlink.hardware_breakpoint_set(addr, thumb=True)) self.dll.JLINKARM_SetBPEx.assert_called_with(addr, enums.JLinkBreakpoint.HW | enums.JLinkBreakpoint.THUMB) def test_jlink_breakpoint_clear(self): """Tests clearing breakpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ handle = 0x1 self.jlink.breakpoint_clear(handle) self.dll.JLINKARM_ClrBPEx.assert_called_with(handle) self.jlink.breakpoint_clear_all() self.dll.JLINKARM_ClrBPEx.assert_called_with(0xFFFFFFFF) def test_jlink_num_active_watchpoints(self): """Tests getting the number of active watchpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetNumWPs.return_value = 0 self.assertEqual(0, self.jlink.num_active_watchpoints()) self.dll.JLINKARM_GetNumWPs.assert_called_once() def test_jlink_num_available_watchpoints(self): """Tests getting the number of available watchpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_GetNumWPUnits.return_value = 0 self.assertEqual(0, self.jlink.num_available_watchpoints()) self.dll.JLINKARM_GetNumWPUnits.assert_called_once() def test_jlink_watchpoint_info_failure(self): """Tests that errors are generated when watchpoint info fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ handle = 0x1 self.dll.JLINKARM_GetWPInfoEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.watchpoint_info(handle) self.dll.JLINKARM_GetWPInfoEx.return_value = 0 with self.assertRaises(ValueError): self.jlink.watchpoint_info() self.dll.JLINKARM_GetWPInfoEx.side_effect = [1, -1] with self.assertRaises(JLinkException): self.jlink.watchpoint_info(1) def test_jlink_watchpoint_info_success(self): """Tests successfully getting information about a watchpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ handle = 0x1 self.dll.JLINKARM_GetWPInfoEx.return_value = 1 wp = self.jlink.watchpoint_info(handle=1) self.assertEqual(None, wp) self.dll.JLINKARM_GetWPInfoEx.return_value = 1 wp = self.jlink.watchpoint_info(index=0x0) self.assertTrue(isinstance(wp, structs.JLinkWatchpointInfo)) def test_jlink_watchpoint_set_invalid_access(self): """Tests setting a watchpoint failing due to bad access size. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0xdeadbeef with self.assertRaises(ValueError): self.jlink.watchpoint_set(addr, access_size=3) with self.assertRaises(ValueError): self.jlink.watchpoint_set(addr, access_size=19) def test_jlink_watchpoint_set_failure(self): """Tests setting a watchpoint failing due to an event error. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ addr = 0xdeadbeef self.dll.JLINKARM_SetDataEvent.return_value = -1 with self.assertRaises(JLinkDataException): self.jlink.watchpoint_set(addr) wp = self.dll.JLINKARM_SetDataEvent.call_args[0][0].contents self.assertTrue(isinstance(wp, structs.JLinkDataEvent)) self.assertTrue((3 < 1) | (1 << 4), wp.AccessMask) def test_jlink_watchpoint_set_success(self): """Tests successfully setting a watchpoint. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ kwargs = { 'addr': 0xA0000000, 'addr_mask': 0x00000000, 'data': 0x0, 'data_mask': 0xFFFFFFFF, 'access_size': 32, 'read': True, 'write': True, 'privileged': False } self.dll.JLINKARM_SetDataEvent.return_value = 0 self.assertEqual(0, self.jlink.watchpoint_set(**kwargs)) wp = self.dll.JLINKARM_SetDataEvent.call_args[0][0].contents self.assertTrue(isinstance(wp, structs.JLinkDataEvent)) # We should have a data watchpoint on address 0xA0000000, matching any # data access, any access (R/W), 32-bit access size. self.assertEqual(1 << 0, wp.Type) self.assertEqual(ctypes.sizeof(wp), wp.SizeOfStruct) self.assertEqual(0xA0000000, wp.Addr) self.assertEqual(0x00000000, wp.AddrMask) self.assertEqual(0x0, wp.Data) self.assertEqual(0xFFFFFFFF, wp.DataMask) self.assertEqual(2 << 1, wp.Access) self.assertEqual((1 << 0) | (1 << 4), wp.AccessMask) kwargs = { 'addr': 0xA0000000, 'addr_mask': 0x0000000F, 'data': 0x11223340, 'data_mask': 0x0000000F, 'access_size': 16, 'read': False, 'write': True, 'privileged': False } self.dll.JLINKARM_SetDataEvent.return_value = 1 self.assertEqual(0, self.jlink.watchpoint_set(**kwargs)) wp = self.dll.JLINKARM_SetDataEvent.call_args[0][0].contents self.assertTrue(isinstance(wp, structs.JLinkDataEvent)) # We should have a data watchpoint on address 0xA0000000 - 0xA000000F, # matching data 0x11223340 - 0x1122334F, write accesses only, 16-bit # access size. self.assertEqual(1 << 0, wp.Type) self.assertEqual(ctypes.sizeof(wp), wp.SizeOfStruct) self.assertEqual(0xA0000000, wp.Addr) self.assertEqual(0x0000000F, wp.AddrMask) self.assertEqual(0x11223340, wp.Data) self.assertEqual(0x0000000F, wp.DataMask) self.assertEqual((1 << 1) | (1 << 0), wp.Access) self.assertEqual(1 << 4, wp.AccessMask) kwargs = { 'addr': 0xA0000000, 'addr_mask': 0x00000000, 'data': 0x11223340, 'data_mask': 0x00000000, 'access_size': 8, 'read': True, 'write': False, 'privileged': True } self.dll.JLINKARM_SetDataEvent.return_value = 1 self.assertEqual(0, self.jlink.watchpoint_set(**kwargs)) wp = self.dll.JLINKARM_SetDataEvent.call_args[0][0].contents self.assertTrue(isinstance(wp, structs.JLinkDataEvent)) # We should have a data watchpoint on address 0xA0000000, matching data # 0x11223340, read access only, 8-bit access size, and privileged. self.assertEqual(1 << 0, wp.Type) self.assertEqual(ctypes.sizeof(wp), wp.SizeOfStruct) self.assertEqual(0xA0000000, wp.Addr) self.assertEqual(0x0, wp.AddrMask) self.assertEqual(0x11223340, wp.Data) self.assertEqual(0x0, wp.DataMask) self.assertEqual((0 << 0) | (0 << 1) | (1 << 4), wp.Access) self.assertEqual(0, wp.AccessMask) def test_jlink_watchpoint_clear(self): """Tests clearing watchpoints. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ handle = 0x1 self.jlink.watchpoint_clear(handle) self.dll.JLINKARM_ClrDataEvent.assert_called_with(handle) self.jlink.watchpoint_clear_all() self.dll.JLINKARM_ClrDataEvent.assert_called_with(0xFFFFFFFF) def test_jlink_disassemble_instruction_invalid_address(self): """Tests passing an invalid instruction to ``disassemble_instruction()`` Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(TypeError): self.jlink.disassemble_instruction('0xdeadbeef') def test_jlink_disassemble_instruction_failed(self): """Tests failing to disassemble an instruction. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ address = 0xdeadbeef self.dll.JLINKARM_DisassembleInst.return_value = -1 with self.assertRaises(JLinkException): self.jlink.disassemble_instruction(address) def test_jlink_disassemble_instruction_success(self): """Tests succeeding to disassemble an instruction. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ address = 0xdeadbeef self.dll.JLINKARM_DisassembleInst.return_value = 0 self.assertEqual('', self.jlink.disassemble_instruction(address)) def test_jlink_strace_configure_invalid_width(self): """Tests specifying in invalid width to the STRACE configure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.strace_configure('4') with self.assertRaises(ValueError): self.jlink.strace_configure(32) def test_jlink_strace_configure_failed(self): """Tests failing to configure the port width. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Config.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_configure(4) def test_jlink_strace_configure_success(self): """Tests successfully configuring the STRACE port width. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Config.return_value = 0 self.assertEqual(None, self.jlink.strace_configure(4)) self.dll.JLINK_STRACE_Config.assert_called_with(b'PortWidth=4') def test_jlink_strace_start_failed(self): """Tests failing to start STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Start.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_start() def test_jlink_strace_start_success(self): """Tests successfully starting STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Start.return_value = 0 self.assertEqual(None, self.jlink.strace_start()) def test_jlink_strace_stop_failed(self): """Tests failing to stop STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Stop.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_stop() def test_jlink_strace_stop_success(self): """Tests successfully stopping STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Stop.return_value = 0 self.assertEqual(None, self.jlink.strace_stop()) def test_jlink_strace_read_invalid_instruction_count(self): """Tests passing an invalid number of instructions to read over STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.strace_read(-1) with self.assertRaises(ValueError): self.jlink.strace_read(0x10001) def test_jlink_strace_read_failed(self): """Tests when an STRACE read fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_instructions = 0x10000 self.dll.JLINK_STRACE_Read.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_read(num_instructions) def test_jlink_strace_read_success(self): """Tests successfully reading from STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_instructions = 0x10000 self.dll.JLINK_STRACE_Read.return_value = 0 self.assertEqual([], self.jlink.strace_read(num_instructions)) self.dll.JLINK_STRACE_Read.assert_called_once() def test_jlink_strace_trace_events(self): """Tests setting the trace events for the STRACE. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ methods = [ self.jlink.strace_code_fetch_event, self.jlink.strace_data_load_event, self.jlink.strace_data_store_event ] events = [0, 2, 3] kwargs = { 'operation': 3, 'address': 0x4000194, 'address_range': 0x10 } for (event, method) in zip(events, methods): self.dll.JLINK_STRACE_Control.return_value = -1 self.dll.JLINK_STRACE_Control.side_effect = None with self.assertRaises(JLinkException): method(**kwargs) def trace_event(command, pointer): obj = ctypes.cast(pointer, ctypes.POINTER(structs.JLinkStraceEventInfo)).contents self.assertEqual(0, command) self.assertEqual(event, obj.Type) self.assertEqual(kwargs.get('operation'), obj.Op) self.assertEqual(kwargs.get('address'), obj.Addr) self.assertEqual(kwargs.get('address_range'), obj.AddrRangeSize) return 0 self.dll.JLINK_STRACE_Control.return_value = 0 self.dll.JLINK_STRACE_Control.side_effect = trace_event self.assertEqual(0, method(**kwargs)) return None def test_jlink_strace_trace_data_access_event(self): """Tests STRACE for tracing a data access event. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ op, addr, data, addr_range = 3, 0x4000194, 0x1337, 0x10 self.dll.JLINK_STRACE_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_data_access_event(op, addr, data) self.dll.JLINK_STRACE_Control.return_value = 0 self.jlink.strace_data_access_event(op, addr, data, address_range=addr_range) def test_jlink_strace_clear_failed(self): """Tests failing to clear the STRACE trace events. This test verifies both the singular trace event clear and the multiple trace event clear. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Control.return_value = -1 handle = 0xdeadbeef with self.assertRaises(JLinkException): self.jlink.strace_clear(handle) args, _ = self.dll.JLINK_STRACE_Control.call_args self.assertTrue(1 in args) with self.assertRaises(JLinkException): self.jlink.strace_clear_all() self.dll.JLINK_STRACE_Control.assert_called_with(2, 0) def test_jlink_strace_clear_success(self): """Tests failing succeeding in clearing the STRACE trace events. This test verifies both the singular trace event clear and the multiple trace event clear. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_STRACE_Control.return_value = 0 handle = 0xdeadbeef self.assertEqual(None, self.jlink.strace_clear(handle)) args, _ = self.dll.JLINK_STRACE_Control.call_args self.assertTrue(1 in args) self.assertEqual(None, self.jlink.strace_clear_all()) self.dll.JLINK_STRACE_Control.assert_called_with(2, 0) def test_jlink_strace_set_buffer_size_failed(self): """Tests failing to set the STRACE buffer size. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ size = 256 self.dll.JLINK_STRACE_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.strace_set_buffer_size(size) def test_jlink_strace_set_buffer_size_success(self): """Tests successfully setting the STRACE buffer size. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ size = 256 self.dll.JLINK_STRACE_Control.return_value = 0 self.jlink.strace_set_buffer_size(size) args, _ = self.dll.JLINK_STRACE_Control.call_args self.assertTrue(3 in args) def test_jlink_trace_start_failed(self): """Tests failing to start the trace. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_start() def test_jlink_trace_start_success(self): """Tests succeeding in starting the trace. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(None, self.jlink.trace_start()) self.dll.JLINKARM_TRACE_Control.assert_called_once_with(0, 0) def test_jlink_trace_stop_failed(self): """Tests failing to stop tracing. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_stop() def test_jlink_trace_stop_success(self): """Tests succeeding in stopping tracing. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(None, self.jlink.trace_stop()) self.dll.JLINKARM_TRACE_Control.assert_called_once_with(1, 0) def test_jlink_trace_flush_failed(self): """Tests failing to flush the trace buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_flush() def test_jlink_trace_flush_success(self): """Tests successfully flushing the trace buffer successfully. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(None, self.jlink.trace_flush()) self.dll.JLINKARM_TRACE_Control.assert_called_once_with(2, 0) def test_jlink_trace_sample_count(self): """Tests getting the sample count from the TRACE API. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ capacity = 256 self.dll.JLINKARM_TRACE_Control.return_value = 1 self.jlink.trace_max_buffer_capacity = lambda: capacity with self.assertRaises(JLinkException): self.jlink.trace_sample_count() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(capacity, self.jlink.trace_sample_count()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x10 in args) def test_jlink_trace_buffer_capacity(self): """Tests getting the current capacity of the TRACE buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_buffer_capacity() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(0, self.jlink.trace_buffer_capacity()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x11 in args) def test_jlink_trace_set_buffer_capacity(self): """Tests setting the buffer capacity. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ capacity = 256 self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_set_buffer_capacity(capacity) def set_buffer_capacity(command, pointer): c_uint = ctypes.cast(pointer, ctypes.POINTER(ctypes.c_uint32)).contents self.assertEqual(0x12, command) self.assertEqual(capacity, c_uint.value) return 0 self.dll.JLINKARM_TRACE_Control = set_buffer_capacity self.assertEqual(None, self.jlink.trace_set_buffer_capacity(capacity)) def test_jlink_trace_min_buffer_capacity(self): """Tests querying the TRACE buffer's minimum capacity. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_min_buffer_capacity() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(0, self.jlink.trace_min_buffer_capacity()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x13 in args) def test_jlink_trace_max_buffer_capacity(self): """Tests querying the TRACE buffer's maximum capacity. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_max_buffer_capacity() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(0, self.jlink.trace_max_buffer_capacity()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x14 in args) def test_jlink_trace_set_format(self): """Tests setting the format of the TRACE buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ fmt = 0xdeadbeef self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_set_format(fmt) self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(None, self.jlink.trace_set_format(fmt)) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x20 in args) def test_jlink_trace_format(self): """Tests querying the current format of the TRACE buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_format() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(0, self.jlink.trace_format()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x21 in args) def test_jlink_trace_region_count(self): """Tessts querying the number of TRACE regions. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_region_count() self.dll.JLINKARM_TRACE_Control.return_value = 0 self.assertEqual(0, self.jlink.trace_region_count()) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x30 in args) def test_jlink_trace_region(self): """Tests querying the J-Link for a TRACE region. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ region_index = 0xdeadbeef self.dll.JLINKARM_TRACE_Control.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_region(region_index) self.dll.JLINKARM_TRACE_Control.return_value = 0 region = self.jlink.trace_region(region_index) self.assertEqual(ctypes.sizeof(region), region.SizeOfStruct) self.assertEqual(region_index, region.RegionIndex) args, _ = self.dll.JLINKARM_TRACE_Control.call_args self.assertTrue(0x32 in args) def test_jlink_trace_read_failed(self): """Tests failing to read from the TRACE buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ offset = 0 num_items = 13 self.dll.JLINKARM_TRACE_Read.return_value = 1 with self.assertRaises(JLinkException): self.jlink.trace_read(offset, num_items) def test_jlink_trace_read_success(self): """Tests successfully reading from the TRACE buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ offset = 0 num_items = 0 self.dll.JLINKARM_TRACE_Read.return_value = 0 self.assertEqual([], self.jlink.trace_read(offset, num_items)) def test_jlink_swo_start(self): """Tests starting to collect SWO data. On error, an exception is generated, otherwise the result is ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_start() self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(False, self.jlink.swo_enabled()) self.assertEqual(None, self.jlink.swo_start()) self.assertEqual(True, self.jlink.swo_enabled()) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(0, arg) self.assertEqual(True, self.jlink.swo_enabled()) self.assertEqual(None, self.jlink.swo_start()) self.assertEqual(True, self.jlink.swo_enabled()) def test_jlink_swo_enable(self): """Tests enabling SWO output on the target device. SWO output can also be enabled by calling ``.swo_enable()``, which on error should raise an exception, otherwise return ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_EnableTarget.return_value = -1 self.jlink.swo_stop = mock.Mock() with self.assertRaises(JLinkException): self.jlink.swo_enable(0) self.dll.JLINKARM_SWO_EnableTarget.return_value = 0 self.assertEqual(None, self.jlink.swo_enable(0)) self.assertEqual(True, self.jlink.swo_enabled()) self.dll.JLINKARM_SWO_EnableTarget.assert_called_with(0, 9600, 0, 0x01) self.assertEqual(None, self.jlink.swo_enable(0)) self.assertEqual(True, self.jlink.swo_enabled()) def test_jlink_swo_disable(self): """Tests disabling the stimulus ports. On error, this should raise an exception, otherwise return ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_DisableTarget.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_disable(0) self.dll.JLINKARM_SWO_DisableTarget.return_value = 0 self.assertEqual(None, self.jlink.swo_disable(0)) self.dll.JLINKARM_SWO_DisableTarget.assert_called_with(0) def test_jlink_swo_stop(self): """Tests disabling SWO output. On error, this should raise an exception, otherwise return ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_stop() self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(None, self.jlink.swo_stop()) self.dll.JLINKARM_SWO_Control.assert_called_with(1, 0) def test_jlink_swo_flush(self): """Tests flushing the SWO buffer. On error, this should raise an exception, otherwise return ``None``. Flushing without a byte count should flush all data in the buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_flush(1) self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(None, self.jlink.swo_flush(1)) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(2, arg) val = self.dll.JLINKARM_SWO_Control.call_args[0][1] self.assertEqual(1, val._obj.value) num_bytes = 1337 self.jlink.swo_num_bytes = mock.Mock() self.jlink.swo_num_bytes.return_value = num_bytes self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(None, self.jlink.swo_flush()) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(2, arg) val = self.dll.JLINKARM_SWO_Control.call_args[0][1] self.assertEqual(1337, val._obj.value) def test_jlink_swo_speed_info(self): """Tests getting the device speed info. On error, this should raise an exception, otherwise return the speed information. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_speed_info() self.dll.JLINKARM_SWO_Control.return_value = 0 info = self.jlink.swo_speed_info() self.assertTrue(isinstance(info, structs.JLinkSWOSpeedInfo)) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(3, arg) def test_jlink_swo_num_bytes_in_buffer(self): """Tests getting the number of bytes in the SWO buffer. On error, this should raise an exception, otherwise return the number of bytes in the SWO buffer. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_num_bytes() self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(0, self.jlink.swo_num_bytes()) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(10, arg) def test_jlink_swo_set_host_buffer_size(self): """Tests setting the host buffer size. On error, this should raise an exception, otherwise return ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_set_host_buffer_size(0) self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(None, self.jlink.swo_set_host_buffer_size(0)) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(20, arg) def test_jlink_swo_set_emu_buffer_size(self): """Tests setting the emulator's buffer size. On error, this should raise an exception, otherwise return ``None``. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_set_emu_buffer_size(0) self.dll.JLINKARM_SWO_Control.return_value = 0 self.assertEqual(None, self.jlink.swo_set_emu_buffer_size(0)) arg = self.dll.JLINKARM_SWO_Control.call_args[0][0] self.assertEqual(21, arg) def test_jlink_swo_get_supported_speeds(self): """Tests getting the J-Link's and target's supported speeds. On error this should raise an exception, otherwise return a list of the supported speeds. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_SWO_GetCompatibleSpeeds.return_value = -1 with self.assertRaises(JLinkException): self.jlink.swo_supported_speeds(0) self.dll.JLINKARM_SWO_GetCompatibleSpeeds.return_value = 0 supported_speeds = self.jlink.swo_supported_speeds(0) self.assertTrue(isinstance(supported_speeds, list)) self.assertEqual(0, sum(supported_speeds)) def test_jlink_swo_read(self): """Tests reading data from the SWO buffer. Reading can flush in addition to just reading the bytes. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.jlink.swo_flush = mock.Mock() num_bytes = 10 # Read without flushing res = self.jlink.swo_read(0, num_bytes) self.assertTrue(isinstance(res, list)) self.assertEqual(num_bytes, len(res)) self.jlink.swo_flush.assert_not_called() # Read with flushing res = self.jlink.swo_read(0, num_bytes, True) self.assertTrue(isinstance(res, list)) self.assertEqual(num_bytes, len(res)) self.jlink.swo_flush.assert_called_once_with(num_bytes) def test_jlink_swo_read_stimulus_invalid(self): """Tests for an invalid port when reading data from a stimulus port. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ with self.assertRaises(ValueError): self.jlink.swo_read_stimulus(-1, 0) with self.assertRaises(ValueError): self.jlink.swo_read_stimulus(32, 0) def test_jlink_swo_read_stimulus(self): """Tests reading data from the stimulus port successfully. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_bytes = 10 self.dll.JLINKARM_SWO_ReadStimulus.return_value = num_bytes res = self.jlink.swo_read_stimulus(0, num_bytes) self.assertTrue(isinstance(res, list)) self.assertEqual(num_bytes, len(res)) def test_rtt_start_calls_rtt_control_with_START_command(self): """Tests that rtt_start calls RTTERMINAL_Control with start command. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_start() actual_cmd, config_ptr = self.dll.JLINK_RTTERMINAL_Control.call_args[0] self.assertEqual(enums.JLinkRTTCommand.START, actual_cmd) self.assertIsNone(config_ptr) self.jlink.rtt_start(0xDEADBEEF) actual_cmd, config_ptr = self.dll.JLINK_RTTERMINAL_Control.call_args[0] self.assertEqual(enums.JLinkRTTCommand.START, actual_cmd) self.assertTrue(config_ptr) config = ctypes.cast(config_ptr, ctypes.POINTER(structs.JLinkRTTerminalStart)).contents self.assertEqual(0xDEADBEEF, config.ConfigBlockAddress) def test_rtt_stop_calls_rtt_control_with_STOP_command(self): """Tests that rtt_stop calls RTTERMINAL_Control with stop command. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_stop() actual = self.dll.JLINK_RTTERMINAL_Control.call_args[0] self.assertEqual(enums.JLinkRTTCommand.STOP, actual[0]) self.assertIsNone(actual[1]) def test_rtt_get_buf_descriptor_calls_control_with_struct(self): """Tests that the ``rtt_get_buf_descriptor`` populates struct. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def _rtt_control(command, buf_ptr): buf = ctypes.cast(buf_ptr, ctypes.POINTER(structs.JLinkRTTerminalBufDesc)).contents buf.acName = str.encode('Terminal 0') buf.SizeOfBuffer = 0x1337 buf.Flags = 0x3 return 0 self.dll.JLINK_RTTERMINAL_Control.side_effect = _rtt_control buffer_index = 0x7 up = True desc = self.jlink.rtt_get_buf_descriptor(buffer_index, up) self.dll.JLINK_RTTERMINAL_Control.assert_called_with(enums.JLinkRTTCommand.GETDESC, mock.ANY) self.assertEqual(buffer_index, desc.BufferIndex) self.assertTrue(desc.up) self.assertEqual('Terminal 0', desc.name) self.assertEqual(0x1337, desc.SizeOfBuffer) self.assertEqual(0x3, desc.Flags) def test_rtt_get_num_up_buffers_calls_control_with_cmd_and_dir(self): """Tests that rtt_get_num_up_buffers calls RTTERMINAL_Control. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_get_num_up_buffers() actual = self.dll.JLINK_RTTERMINAL_Control.call_args[0] self.assertEqual(enums.JLinkRTTCommand.GETNUMBUF, actual[0]) self.assertEqual(enums.JLinkRTTDirection.UP, actual[1]._obj.value) def test_rtt_get_num_up_buffers_returns_result_from_control(self): """Tests that rtt_get_num_up_buffers returns RTTERMINAL_Control. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 2345 self.dll.JLINK_RTTERMINAL_Control.return_value = expected actual = self.jlink.rtt_get_num_up_buffers() self.assertEqual(actual, expected) def test_rtt_get_num_down_buffers_calls_control_with_cmd_and_dir(self): """Tests that rtt_get_num_down_buffers calls RTTERMINAL_Control. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_get_num_down_buffers() actual = self.dll.JLINK_RTTERMINAL_Control.call_args[0] self.assertEqual(enums.JLinkRTTCommand.GETNUMBUF, actual[0]) self.assertEqual(enums.JLinkRTTDirection.DOWN, actual[1]._obj.value) def test_rtt_get_num_down_buffers_returns_result_from_control(self): """Tests that rtt_get_num_down_buffers returns RTTERMINAL_Control. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 2345 self.dll.JLINK_RTTERMINAL_Control.return_value = expected actual = self.jlink.rtt_get_num_down_buffers() self.assertEqual(actual, expected) def test_rtt_get_status_returns_result_from_control(self): """Tests that ``rtt_get_status`` returns a valid RTT terminal status. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ def _rtt_control(command, stat_ptr): stat = ctypes.cast(stat_ptr, ctypes.POINTER(structs.JLinkRTTerminalStatus)).contents stat.NumBytesTransferred = 0x1234 stat.NumBytesRead = 0x4321 stat.IsRunning = 1 stat.NumUpBuffers = 3 stat.NumDownBuffers = 3 return 0 self.dll.JLINK_RTTERMINAL_Control.side_effect = _rtt_control stat = self.jlink.rtt_get_status() self.dll.JLINK_RTTERMINAL_Control.assert_called_with(enums.JLinkRTTCommand.GETSTAT, mock.ANY) self.assertEqual(0x1234, stat.NumBytesTransferred) self.assertEqual(0x4321, stat.NumBytesRead) self.assertTrue(stat.IsRunning) self.assertEqual(3, stat.NumUpBuffers) self.assertEqual(3, stat.NumDownBuffers) def test_rtt_control_forwards_command_to_RTTERMINAL_Control(self): """Tests that rtt_control forwards the command to RTT. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 1234 self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_control(expected, None) actual = self.dll.JLINK_RTTERMINAL_Control.call_args[0][0] self.assertEqual(actual, expected) def test_rtt_control_forwards_none_config_to_RTTERMINAL_Control(self): """Tests that a None config value is forwarded to RTTERMINAL_Control. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_control(0, None) self.assertIsNone(self.dll.JLINK_RTTERMINAL_Control.call_args[0][1]) def test_rtt_control_wraps_config_in_byref_before_calling_Control(self): """Tests that non-None configs get wrapped in ctypes.byref. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 1234 config = ctypes.c_int(expected) self.dll.JLINK_RTTERMINAL_Control.return_value = 0 self.jlink.rtt_control(0, config) actual = self.dll.JLINK_RTTERMINAL_Control.call_args[0][1] self.assertIs(type(actual), type(ctypes.byref(ctypes.c_int()))) self.assertEqual(actual._obj.value, expected) def test_rtt_control_raises_error_if_RTTERMINAL_Control_fails(self): """Tests that a JLinkException is raised if RTTERMINAL_Control fails. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Control.return_value = -1 with self.assertRaises(JLinkException): self.jlink.rtt_control(0, None) def test_rtt_read_forwards_buffer_index_to_RTTERMINAL_Read(self): """Tests that rtt_read calls RTTERMINAL_Read with the supplied index. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 3 self.dll.JLINK_RTTERMINAL_Read.return_value = 0 self.jlink.rtt_read(expected, 0) self.assertEqual(self.dll.JLINK_RTTERMINAL_Read.call_args[0][0], expected) def test_rtt_read_returns_partial_payload_when_underfilled(self): """Tests that rtt_read returns fewer bytes than requested when not full. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ num_bytes = 16 actual_bytes = 5 self.dll.JLINK_RTTERMINAL_Read.return_value = actual_bytes res = self.jlink.rtt_read(0, num_bytes) self.assertEqual(len(res), actual_bytes) def test_rtt_read_returns_list_sized_from_RTTERMINAL_Read(self): """Tests that rtt_read returns however many bytes were read from RTT. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 123 self.dll.JLINK_RTTERMINAL_Read.return_value = expected res = self.jlink.rtt_read(0, expected) self.assertEqual(len(res), expected) def test_rtt_read_raises_exception_if_RTTERMINAL_Read_fails(self): """Tests that rtt_read raises a JLinkException on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Read.return_value = -1 with self.assertRaises(JLinkException): self.jlink.rtt_read(0, 0) def test_rtt_write_forwards_buffer_index_to_RTTERMINAL_Write(self): """Tests that rtt_write calls RTTERMINAL_Write with the supplied index. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 89 self.dll.JLINK_RTTERMINAL_Write.return_value = 0 self.jlink.rtt_write(expected, []) self.assertEqual(self.dll.JLINK_RTTERMINAL_Write.call_args[0][0], expected) def test_rtt_write_converts_byte_list_to_ctype_array(self): """Tests that rtt_write converts the provided byte list to ctype. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = b'\x00\x01\x02\x03' self.dll.JLINK_RTTERMINAL_Write.return_value = 0 self.jlink.rtt_write(0, expected) actual = bytearray(self.dll.JLINK_RTTERMINAL_Write.call_args[0][1]) self.assertEqual(actual, expected) def test_rtt_write_returns_result_from_RTTERMINAL_Write(self): """Tests that rtt_write returns whatever value RTTERMINAL_Write returns. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 1234 self.dll.JLINK_RTTERMINAL_Write.return_value = expected actual = self.jlink.rtt_write(0, b'') self.assertEqual(actual, expected) def test_rtt_write_raises_exception_if_RTTERMINAL_Write_fails(self): """Tests that rtt_write raises a JLinkException on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINK_RTTERMINAL_Write.return_value = -1 with self.assertRaises(JLinkException): self.jlink.rtt_write(0, []) def test_cp15_present_returns_true(self): """Tests that cp15_present returns ``True`` when CP15_IsPresent returns a value different from 0 and ``False`` when CP15_IsPresent returns a value equal to 0. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CP15_IsPresent.return_value = 0 assert self.jlink.cp15_present() is False self.dll.JLINKARM_CP15_IsPresent.return_value = 1 assert self.jlink.cp15_present() is True def test_cp15_register_read_returns_result_from_JLINKARM_CP15_ReadEx(self): """Tests that cp15_register_read returns whatever value CP15_ReadEx returns. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ expected = 1234 def read_data(cr_n, cr_m, op_1, op_2, value): value.contents.value = expected return self.dll.JLINKARM_CP15_ReadEx.return_value self.dll.JLINKARM_CP15_ReadEx.return_value = 0 self.dll.JLINKARM_CP15_ReadEx.side_effect = read_data actual = self.jlink.cp15_register_read(0, 0, 0, 0) assert actual == expected def test_cp15_register_read_raises_exception_if_CP15_ReadEx_fails(self): """Tests that cp15_register_read raises a JLinkException on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CP15_ReadEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.cp15_register_read(0, 0, 0, 0) def test_cp15_register_write_success(self): """Tests that cp15_register_write uses provided parameters. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ args = [1, 2, 3, 4, 5] self.dll.JLINKARM_CP15_WriteEx.return_value = 0 actual = self.jlink.cp15_register_write(*args) assert self.dll.JLINKARM_CP15_WriteEx.called_once_with(*args) def test_cp15_register_write_raises_exception_if_CP15_WriteEx_fails(self): """Tests that cp15_register_write raises a JLinkException on failure. Args: self (TestJLink): the ``TestJLink`` instance Returns: ``None`` """ self.dll.JLINKARM_CP15_WriteEx.return_value = -1 with self.assertRaises(JLinkException): self.jlink.cp15_register_write(0, 0, 0, 0, 0) if __name__ == '__main__': unittest.main()
31.341321
118
0.627622
79519e4b3e9ea379eabeb30c1b611cf1c2936f4e
800
py
Python
dbf_to_csv.py
tothebeat/fatal-car-crashes
7112103b9ee49eabacba3f5e6d0496ea3c78132a
[ "MIT" ]
8
2015-12-17T22:45:29.000Z
2017-06-04T19:40:30.000Z
dbf_to_csv.py
lovingawareness/fatal-car-crashes
7112103b9ee49eabacba3f5e6d0496ea3c78132a
[ "MIT" ]
1
2015-10-17T02:08:38.000Z
2015-10-17T02:08:38.000Z
dbf_to_csv.py
lovingawareness/fatal-car-crashes
7112103b9ee49eabacba3f5e6d0496ea3c78132a
[ "MIT" ]
2
2015-12-24T04:33:07.000Z
2016-05-20T02:19:08.000Z
import csv import sys from dbfpy import dbf def dbf_to_csv(dbf_path, csv_path): with open(dbf_path, 'rb') as dbf_file: database = dbf.Dbf(dbf_file, readOnly=True) with open(csv_path, 'wb') as csv_file: dict_writer = csv.DictWriter(csv_file, fieldnames=sorted(database[0].asDict().keys())) dict_writer.writeheader() for record_number, record in enumerate(database): dict_writer.writerow(record.asDict()) print 'Converted {n} rows of DBF file {f}'.format(n=record_number, f=dbf_path) if __name__ == "__main__": if len(sys.argv) < 3: print "Here's how you run me:" print "{0} path/to/somedata.dbf path/to/output.csv".format(__file__) sys.exit(1) dbf_to_csv(sys.argv[1], sys.argv[2])
34.782609
98
0.64
79519e53b040b134ae0f1f78df17181381dc8db2
2,036
py
Python
cup_test/cup_service_heartbeat_test.py
lotapp/CUP
c3b3d4cdc2627a0fecbfecc6adaaa6670ac73a1c
[ "Apache-2.0" ]
900
2017-02-15T05:14:03.000Z
2022-03-22T08:07:39.000Z
cup_test/cup_service_heartbeat_test.py
horsedongmin/CUP
94398c7d94b2574db565c3e8d6dcfe2f3722f007
[ "Apache-2.0" ]
30
2017-02-24T05:16:15.000Z
2021-08-04T02:03:12.000Z
cup_test/cup_service_heartbeat_test.py
horsedongmin/CUP
94398c7d94b2574db565c3e8d6dcfe2f3722f007
[ "Apache-2.0" ]
185
2017-02-15T02:23:09.000Z
2022-02-24T08:47:43.000Z
#!/usr/bin/env python # -*- coding: utf-8 -* # Copyright: [CUP] - See LICENSE for details. # Authors: Guannan Ma (@mythmgn), """ :description: unittest for cup.services.heartbeat """ import os import sys import time _NOW_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' sys.path.insert(0, _NOW_PATH + '../') import cup from cup import net from cup import unittest from cup import log from cup.services import heartbeat class TestMyCase(unittest.CUTCase): """ test class for cup """ def __init__(self): super(self.__class__, self).__init__( b_logstd=False ) log.info('Start to run ' + str(__file__)) self._hb = heartbeat.HeartbeatService( judge_lost_in_sec=5, keep_lost=True ) self._tmpfile = _NOW_PATH + '_tmp_file' def setup(self): """ setup """ @classmethod def _check(cls, key, devices, should_in=False): in_it = False for device in devices: if device.get_name() == key: in_it = True if should_in: assert in_it, 'key:%s should in devices' % key else: assert not in_it, 'key:%s should not in devices' % key def _lost_heartbeat(self): hostname = net.get_local_hostname() self._hb.refresh(hostname, heartbeat.Device(hostname)) lost_devices = self._hb.get_lost() self._check(hostname, lost_devices, should_in=False) time.sleep(6) lost_devices = self._hb.get_lost() self._check(hostname, lost_devices, should_in=True) self._hb.cleanup_oldlost(self._tmpfile) def test_run(self): """ @author: maguannan """ self._lost_heartbeat() def teardown(self): """ teardown """ cup.log.info('End running ' + str(__file__)) os.unlink(self._tmpfile) if __name__ == '__main__': cup.unittest.CCaseExecutor().runcase(TestMyCase()) # vi:set tw=0 ts=4 sw=4 nowrap fdm=indent
25.135802
66
0.604126
79519f6349c538376a9cc6a5685cd9b6655046a2
348
py
Python
haystack/nodes/retriever/__init__.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
1
2022-03-06T02:13:15.000Z
2022-03-06T02:13:15.000Z
haystack/nodes/retriever/__init__.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
null
null
null
haystack/nodes/retriever/__init__.py
ArzelaAscoIi/haystack
be8f50c9e3de4e264b3f345f5f4b9c9ec518ed08
[ "Apache-2.0" ]
1
2022-03-23T18:17:02.000Z
2022-03-23T18:17:02.000Z
from haystack.nodes.retriever.base import BaseRetriever from haystack.nodes.retriever.dense import DensePassageRetriever, EmbeddingRetriever, TableTextRetriever from haystack.nodes.retriever.sparse import ElasticsearchRetriever, ElasticsearchFilterOnlyRetriever, TfidfRetriever from haystack.nodes.retriever.text2sparql import Text2SparqlRetriever
69.6
116
0.896552
79519f6cf8aebd49b44f19c0ca4ee4fbaa3c95c8
66,873
py
Python
src/transformers/models/mobilebert/modeling_mobilebert.py
Knarik1/transformers
c2a7d7280250addae38a49c31a57ddd897be2065
[ "Apache-2.0" ]
2
2021-09-16T01:24:38.000Z
2021-09-29T18:45:34.000Z
src/transformers/models/mobilebert/modeling_mobilebert.py
Knarik1/transformers
c2a7d7280250addae38a49c31a57ddd897be2065
[ "Apache-2.0" ]
5
2021-10-05T21:43:16.000Z
2021-12-15T15:20:32.000Z
src/transformers/models/mobilebert/modeling_mobilebert.py
Knarik1/transformers
c2a7d7280250addae38a49c31a57ddd897be2065
[ "Apache-2.0" ]
2
2021-08-15T14:42:10.000Z
2021-09-25T15:40:49.000Z
# MIT License # # Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import math import os import warnings from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACT2FN from ...file_utils import ( ModelOutput, add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from ...modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPooling, MaskedLMOutput, MultipleChoiceModelOutput, NextSentencePredictorOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer from ...utils import logging from .configuration_mobilebert import MobileBertConfig logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "google/mobilebert-uncased" _CONFIG_FOR_DOC = "MobileBertConfig" _TOKENIZER_FOR_DOC = "MobileBertTokenizer" MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = ["google/mobilebert-uncased"] def load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.replace("ffn_layer", "ffn") name = name.replace("FakeLayerNorm", "LayerNorm") name = name.replace("extra_output_weights", "dense/kernel") name = name.replace("bert", "mobilebert") name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info(f"Skipping {'/'.join(name)}") continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "output_weights": pointer = getattr(pointer, "weight") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info(f"Skipping {'/'.join(name)}") continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) return model class NoNorm(nn.Module): def __init__(self, feat_size, eps=None): super().__init__() self.bias = nn.Parameter(torch.zeros(feat_size)) self.weight = nn.Parameter(torch.ones(feat_size)) def forward(self, input_tensor): return input_tensor * self.weight + self.bias NORM2FN = {"layer_norm": nn.LayerNorm, "no_norm": NoNorm} class MobileBertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() self.trigram_input = config.trigram_input self.embedding_size = config.embedding_size self.hidden_size = config.hidden_size self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) embed_dim_multiplier = 3 if self.trigram_input else 1 embedded_input_size = self.embedding_size * embed_dim_multiplier self.embedding_transformation = nn.Linear(embedded_input_size, config.hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size) self.dropout = nn.Dropout(config.hidden_dropout_prob) # position_ids (1, len position emb) is contiguous in memory and exported when serialized self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: input_shape = inputs_embeds.size()[:-1] seq_length = input_shape[1] if position_ids is None: position_ids = self.position_ids[:, :seq_length] if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) if inputs_embeds is None: inputs_embeds = self.word_embeddings(input_ids) if self.trigram_input: # From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited # Devices (https://arxiv.org/abs/2004.02984) # # The embedding table in BERT models accounts for a substantial proportion of model size. To compress # the embedding layer, we reduce the embedding dimension to 128 in MobileBERT. # Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512 # dimensional output. inputs_embeds = torch.cat( [ nn.functional.pad(inputs_embeds[:, 1:], [0, 0, 0, 1, 0, 0], value=0), inputs_embeds, nn.functional.pad(inputs_embeds[:, :-1], [0, 0, 1, 0, 0, 0], value=0), ], dim=2, ) if self.trigram_input or self.embedding_size != self.hidden_size: inputs_embeds = self.embedding_transformation(inputs_embeds) # Add positional embeddings and token type embeddings, then layer # normalize and perform dropout. position_embeddings = self.position_embeddings(position_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = inputs_embeds + position_embeddings + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings class MobileBertSelfAttention(nn.Module): def __init__(self, config): super().__init__() self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.query = nn.Linear(config.true_hidden_size, self.all_head_size) self.key = nn.Linear(config.true_hidden_size, self.all_head_size) self.value = nn.Linear( config.true_hidden_size if config.use_bottleneck_attention else config.hidden_size, self.all_head_size ) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, query_tensor, key_tensor, value_tensor, attention_mask=None, head_mask=None, output_attentions=None, ): mixed_query_layer = self.query(query_tensor) mixed_key_layer = self.key(key_tensor) mixed_value_layer = self.value(value_tensor) query_layer = self.transpose_for_scores(mixed_query_layer) key_layer = self.transpose_for_scores(mixed_key_layer) value_layer = self.transpose_for_scores(mixed_value_layer) # Take the dot product between "query" and "key" to get the raw attention scores. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in BertModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) # Mask heads if we want to if head_mask is not None: attention_probs = attention_probs * head_mask context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) return outputs class MobileBertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.use_bottleneck = config.use_bottleneck self.dense = nn.Linear(config.true_hidden_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps) if not self.use_bottleneck: self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, residual_tensor): layer_outputs = self.dense(hidden_states) if not self.use_bottleneck: layer_outputs = self.dropout(layer_outputs) layer_outputs = self.LayerNorm(layer_outputs + residual_tensor) return layer_outputs class MobileBertAttention(nn.Module): def __init__(self, config): super().__init__() self.self = MobileBertSelfAttention(config) self.output = MobileBertSelfOutput(config) self.pruned_heads = set() def prune_heads(self, heads): if len(heads) == 0: return heads, index = find_pruneable_heads_and_indices( heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads ) # Prune linear layers self.self.query = prune_linear_layer(self.self.query, index) self.self.key = prune_linear_layer(self.self.key, index) self.self.value = prune_linear_layer(self.self.value, index) self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) # Update hyper params and store pruned heads self.self.num_attention_heads = self.self.num_attention_heads - len(heads) self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads self.pruned_heads = self.pruned_heads.union(heads) def forward( self, query_tensor, key_tensor, value_tensor, layer_input, attention_mask=None, head_mask=None, output_attentions=None, ): self_outputs = self.self( query_tensor, key_tensor, value_tensor, attention_mask, head_mask, output_attentions, ) # Run a linear projection of `hidden_size` then add a residual # with `layer_input`. attention_output = self.output(self_outputs[0], layer_input) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class MobileBertIntermediate(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states class OutputBottleneck(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.true_hidden_size, config.hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states, residual_tensor): layer_outputs = self.dense(hidden_states) layer_outputs = self.dropout(layer_outputs) layer_outputs = self.LayerNorm(layer_outputs + residual_tensor) return layer_outputs class MobileBertOutput(nn.Module): def __init__(self, config): super().__init__() self.use_bottleneck = config.use_bottleneck self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size) if not self.use_bottleneck: self.dropout = nn.Dropout(config.hidden_dropout_prob) else: self.bottleneck = OutputBottleneck(config) def forward(self, intermediate_states, residual_tensor_1, residual_tensor_2): layer_output = self.dense(intermediate_states) if not self.use_bottleneck: layer_output = self.dropout(layer_output) layer_output = self.LayerNorm(layer_output + residual_tensor_1) else: layer_output = self.LayerNorm(layer_output + residual_tensor_1) layer_output = self.bottleneck(layer_output, residual_tensor_2) return layer_output class BottleneckLayer(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intra_bottleneck_size) self.LayerNorm = NORM2FN[config.normalization_type](config.intra_bottleneck_size, eps=config.layer_norm_eps) def forward(self, hidden_states): layer_input = self.dense(hidden_states) layer_input = self.LayerNorm(layer_input) return layer_input class Bottleneck(nn.Module): def __init__(self, config): super().__init__() self.key_query_shared_bottleneck = config.key_query_shared_bottleneck self.use_bottleneck_attention = config.use_bottleneck_attention self.input = BottleneckLayer(config) if self.key_query_shared_bottleneck: self.attention = BottleneckLayer(config) def forward(self, hidden_states): # This method can return three different tuples of values. These different values make use of bottlenecks, # which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory # usage. These linear layer have weights that are learned during training. # # If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the # key, query, value, and "layer input" to be used by the attention layer. # This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor # in the attention self output, after the attention scores have been computed. # # If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return # four values, three of which have been passed through a bottleneck: the query and key, passed through the same # bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck. # # Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck, # and the residual layer will be this value passed through a bottleneck. bottlenecked_hidden_states = self.input(hidden_states) if self.use_bottleneck_attention: return (bottlenecked_hidden_states,) * 4 elif self.key_query_shared_bottleneck: shared_attention_input = self.attention(hidden_states) return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states) else: return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states) class FFNOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states, residual_tensor): layer_outputs = self.dense(hidden_states) layer_outputs = self.LayerNorm(layer_outputs + residual_tensor) return layer_outputs class FFNLayer(nn.Module): def __init__(self, config): super().__init__() self.intermediate = MobileBertIntermediate(config) self.output = FFNOutput(config) def forward(self, hidden_states): intermediate_output = self.intermediate(hidden_states) layer_outputs = self.output(intermediate_output, hidden_states) return layer_outputs class MobileBertLayer(nn.Module): def __init__(self, config): super().__init__() self.use_bottleneck = config.use_bottleneck self.num_feedforward_networks = config.num_feedforward_networks self.attention = MobileBertAttention(config) self.intermediate = MobileBertIntermediate(config) self.output = MobileBertOutput(config) if self.use_bottleneck: self.bottleneck = Bottleneck(config) if config.num_feedforward_networks > 1: self.ffn = nn.ModuleList([FFNLayer(config) for _ in range(config.num_feedforward_networks - 1)]) def forward( self, hidden_states, attention_mask=None, head_mask=None, output_attentions=None, ): if self.use_bottleneck: query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states) else: query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4 self_attention_outputs = self.attention( query_tensor, key_tensor, value_tensor, layer_input, attention_mask, head_mask, output_attentions=output_attentions, ) attention_output = self_attention_outputs[0] s = (attention_output,) outputs = self_attention_outputs[1:] # add self attentions if we output attention weights if self.num_feedforward_networks != 1: for i, ffn_module in enumerate(self.ffn): attention_output = ffn_module(attention_output) s += (attention_output,) intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output, hidden_states) outputs = ( (layer_output,) + outputs + ( torch.tensor(1000), query_tensor, key_tensor, value_tensor, layer_input, attention_output, intermediate_output, ) + s ) return outputs class MobileBertEncoder(nn.Module): def __init__(self, config): super().__init__() self.layer = nn.ModuleList([MobileBertLayer(config) for _ in range(config.num_hidden_layers)]) def forward( self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_attentions = () if output_attentions else None for i, layer_module in enumerate(self.layer): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) layer_outputs = layer_module( hidden_states, attention_mask, head_mask[i], output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_attentions = all_attentions + (layer_outputs[1],) # Add last layer if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions ) class MobileBertPooler(nn.Module): def __init__(self, config): super().__init__() self.do_activate = config.classifier_activation if self.do_activate: self.dense = nn.Linear(config.hidden_size, config.hidden_size) def forward(self, hidden_states): # We "pool" the model by simply taking the hidden state corresponding # to the first token. first_token_tensor = hidden_states[:, 0] if not self.do_activate: return first_token_tensor else: pooled_output = self.dense(first_token_tensor) pooled_output = torch.tanh(pooled_output) return pooled_output class MobileBertPredictionHeadTransform(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.hidden_act self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states): hidden_states = self.dense(hidden_states) hidden_states = self.transform_act_fn(hidden_states) hidden_states = self.LayerNorm(hidden_states) return hidden_states class MobileBertLMPredictionHead(nn.Module): def __init__(self, config): super().__init__() self.transform = MobileBertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.dense = nn.Linear(config.vocab_size, config.hidden_size - config.embedding_size, bias=False) self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = hidden_states.matmul(torch.cat([self.decoder.weight.t(), self.dense.weight], dim=0)) hidden_states += self.decoder.bias return hidden_states class MobileBertOnlyMLMHead(nn.Module): def __init__(self, config): super().__init__() self.predictions = MobileBertLMPredictionHead(config) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores class MobileBertPreTrainingHeads(nn.Module): def __init__(self, config): super().__init__() self.predictions = MobileBertLMPredictionHead(config) self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, sequence_output, pooled_output): prediction_scores = self.predictions(sequence_output) seq_relationship_score = self.seq_relationship(pooled_output) return prediction_scores, seq_relationship_score class MobileBertPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = MobileBertConfig pretrained_model_archive_map = MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST load_tf_weights = load_tf_weights_in_mobilebert base_model_prefix = "mobilebert" _keys_to_ignore_on_load_missing = [r"position_ids"] def _init_weights(self, module): """Initialize the weights""" if isinstance(module, nn.Linear): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, (nn.LayerNorm, NoNorm)): module.bias.data.zero_() module.weight.data.fill_(1.0) @dataclass class MobileBertForPreTrainingOutput(ModelOutput): """ Output type of :class:`~transformers.MobileBertForPreTraining`. Args: loss (`optional`, returned when ``labels`` is provided, ``torch.FloatTensor`` of shape :obj:`(1,)`): Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss. prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). seq_relationship_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`): Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax). hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``): Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape :obj:`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``): Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None prediction_logits: torch.FloatTensor = None seq_relationship_logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None MOBILEBERT_START_DOCSTRING = r""" This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__ subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config (:class:`~transformers.MobileBertConfig`): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights. """ MOBILEBERT_INPUTS_DOCSTRING = r""" Args: input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using :class:`~transformers.BertTokenizer`. See :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for details. `What are input IDs? <../glossary.html#input-ids>`__ attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. `What are attention masks? <../glossary.html#attention-mask>`__ token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`): Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0, 1]``: - 0 corresponds to a `sentence A` token, - 1 corresponds to a `sentence B` token. `What are token type IDs? <../glossary.html#token-type-ids>`_ position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0, config.max_position_embeddings - 1]``. `What are position IDs? <../glossary.html#position-ids>`_ head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`): Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`): Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert :obj:`input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (:obj:`bool`, `optional`): Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned tensors for more detail. output_hidden_states (:obj:`bool`, `optional`): Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for more detail. return_dict (:obj:`bool`, `optional`): Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple. """ @add_start_docstrings( "The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.", MOBILEBERT_START_DOCSTRING, ) class MobileBertModel(MobileBertPreTrainedModel): """ https://arxiv.org/pdf/2004.02984.pdf """ def __init__(self, config, add_pooling_layer=True): super().__init__(config) self.config = config self.embeddings = MobileBertEmbeddings(config) self.encoder = MobileBertEncoder(config) self.pooler = MobileBertPooler(config) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value def _prune_heads(self, heads_to_prune): """ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base class PreTrainedModel """ for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(heads) @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_hidden_states=None, output_attentions=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_shape = input_ids.size() elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) if token_type_ids is None: token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask( attention_mask, input_shape, self.device ) # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds ) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] pooled_output = self.pooler(sequence_output) if self.pooler is not None else None if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPooling( last_hidden_state=sequence_output, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) @add_start_docstrings( """ MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next sentence prediction (classification)` head. """, MOBILEBERT_START_DOCSTRING, ) class MobileBertForPreTraining(MobileBertPreTrainedModel): def __init__(self, config): super().__init__(config) self.mobilebert = MobileBertModel(config) self.cls = MobileBertPreTrainingHeads(config) # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddigs): self.cls.predictions.decoder = new_embeddigs def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding: # resize dense output embedings at first self.cls.predictions.dense = self._get_resized_lm_head( self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True ) return super().resize_token_embeddings(new_num_tokens=new_num_tokens) @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=MobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, next_sentence_label=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (``torch.LongTensor`` of shape ``(batch_size, sequence_length)``, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see :obj:`input_ids` docstring) Indices should be in ``[0, 1]``: - 0 indicates sequence B is a continuation of sequence A, - 1 indicates sequence B is a random sequence. Returns: Examples:: >>> from transformers import MobileBertTokenizer, MobileBertForPreTraining >>> import torch >>> tokenizer = MobileBertTokenizer.from_pretrained("google/mobilebert-uncased") >>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased") >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1 >>> outputs = model(input_ids) >>> prediction_logits = outputs.prediction_logits >>> seq_relationship_logits = outputs.seq_relationship_logits """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output, pooled_output = outputs[:2] prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output) total_loss = None if labels is not None and next_sentence_label is not None: loss_fct = CrossEntropyLoss() masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1)) total_loss = masked_lm_loss + next_sentence_loss if not return_dict: output = (prediction_scores, seq_relationship_score) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return MobileBertForPreTrainingOutput( loss=total_loss, prediction_logits=prediction_scores, seq_relationship_logits=seq_relationship_score, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings("""MobileBert Model with a `language modeling` head on top. """, MOBILEBERT_START_DOCSTRING) class MobileBertForMaskedLM(MobileBertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.mobilebert = MobileBertModel(config, add_pooling_layer=False) self.cls = MobileBertOnlyMLMHead(config) self.config = config # Initialize weights and apply final processing self.post_init() def get_output_embeddings(self): return self.cls.predictions.decoder def set_output_embeddings(self, new_embeddigs): self.cls.predictions.decoder = new_embeddigs def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding: # resize dense output embedings at first self.cls.predictions.dense = self._get_resized_lm_head( self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True ) return super().resize_token_embeddings(new_num_tokens=new_num_tokens) @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]`` """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] prediction_scores = self.cls(sequence_output) masked_lm_loss = None if labels is not None: loss_fct = CrossEntropyLoss() # -100 index = padding token masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (prediction_scores,) + outputs[2:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return MaskedLMOutput( loss=masked_lm_loss, logits=prediction_scores, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) class MobileBertOnlyNSPHead(nn.Module): def __init__(self, config): super().__init__() self.seq_relationship = nn.Linear(config.hidden_size, 2) def forward(self, pooled_output): seq_relationship_score = self.seq_relationship(pooled_output) return seq_relationship_score @add_start_docstrings( """MobileBert Model with a `next sentence prediction (classification)` head on top. """, MOBILEBERT_START_DOCSTRING, ) class MobileBertForNextSentencePrediction(MobileBertPreTrainedModel): def __init__(self, config): super().__init__(config) self.mobilebert = MobileBertModel(config) self.cls = MobileBertOnlyNSPHead(config) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring) Indices should be in ``[0, 1]``. - 0 indicates sequence B is a continuation of sequence A, - 1 indicates sequence B is a random sequence. Returns: Examples:: >>> from transformers import MobileBertTokenizer, MobileBertForNextSentencePrediction >>> import torch >>> tokenizer = MobileBertTokenizer.from_pretrained('google/mobilebert-uncased') >>> model = MobileBertForNextSentencePrediction.from_pretrained('google/mobilebert-uncased') >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced." >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light." >>> encoding = tokenizer(prompt, next_sentence, return_tensors='pt') >>> outputs = model(**encoding, labels=torch.LongTensor([1])) >>> loss = outputs.loss >>> logits = outputs.logits """ if "next_sentence_label" in kwargs: warnings.warn( "The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.", FutureWarning, ) labels = kwargs.pop("next_sentence_label") return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] seq_relationship_score = self.cls(pooled_output) next_sentence_loss = None if labels is not None: loss_fct = CrossEntropyLoss() next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), labels.view(-1)) if not return_dict: output = (seq_relationship_score,) + outputs[2:] return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output return NextSentencePredictorOutput( loss=next_sentence_loss, logits=seq_relationship_score, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. """, MOBILEBERT_START_DOCSTRING, ) # Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing class MobileBertForSequenceClassification(MobileBertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.config = config self.mobilebert = MobileBertModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ..., config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss), If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(logits.squeeze(), labels.squeeze()) else: loss = loss_fct(logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(logits, labels) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). """, MOBILEBERT_START_DOCSTRING, ) # Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering with Bert->MobileBert all-casing class MobileBertForQuestionAnswering(MobileBertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.mobilebert = MobileBertModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, start_positions=None, end_positions=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for position (index) of the end of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the sequence are not taken into account for computing the loss. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[2:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a softmax) e.g. for RocStories/SWAG tasks. """, MOBILEBERT_START_DOCSTRING, ) # Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice with Bert->MobileBert all-casing class MobileBertForMultipleChoice(MobileBertPreTrainedModel): def __init__(self, config): super().__init__(config) self.mobilebert = MobileBertModel(config) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, 1) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward( MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length") ) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`): Labels for computing the multiple choice classification loss. Indices should be in ``[0, ..., num_choices-1]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See :obj:`input_ids` above) """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None inputs_embeds = ( inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) if inputs_embeds is not None else None ) outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) reshaped_logits = logits.view(-1, num_choices) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(reshaped_logits, labels) if not return_dict: output = (reshaped_logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return MultipleChoiceModelOutput( loss=loss, logits=reshaped_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @add_start_docstrings( """ MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. """, MOBILEBERT_START_DOCSTRING, ) # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing class MobileBertForTokenClassification(MobileBertPreTrainedModel): _keys_to_ignore_on_load_unexpected = [r"pooler"] def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.mobilebert = MobileBertModel(config, add_pooling_layer=False) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) @add_code_sample_docstrings( processor_class=_TOKENIZER_FOR_DOC, checkpoint=_CHECKPOINT_FOR_DOC, output_type=TokenClassifierOutput, config_class=_CONFIG_FOR_DOC, ) def forward( self, input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels - 1]``. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mobilebert( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() # Only keep active parts of the loss if attention_mask is not None: active_loss = attention_mask.view(-1) == 1 active_logits = logits.view(-1, self.num_labels) active_labels = torch.where( active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels) ) loss = loss_fct(active_logits, active_labels) else: loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
41.717405
168
0.669403
7951a051f0b33966f23ab3701a9570ab0c5e4b15
29,833
py
Python
vvs_app/master_window.py
Sheriff99yt/Vision_Visual_Scripting
a930c805ff91379baf5cbb08d08b7f383eab2f95
[ "MIT" ]
5
2021-12-17T06:52:11.000Z
2021-12-20T19:52:57.000Z
vvs_app/master_window.py
Sheriff99yt/Vision_Visual_Scripting
a930c805ff91379baf5cbb08d08b7f383eab2f95
[ "MIT" ]
null
null
null
vvs_app/master_window.py
Sheriff99yt/Vision_Visual_Scripting
a930c805ff91379baf5cbb08d08b7f383eab2f95
[ "MIT" ]
null
null
null
import os import subprocess import sys from qtpy.QtGui import * from qtpy.QtWidgets import * from qtpy.QtCore import * from nodeeditor.node_editor_widget import NodeEditorWidget from nodeeditor.utils import loadStylesheets from nodeeditor.node_editor_window import NodeEditorWindow from vvs_app.editor_settings_wnd import SettingsWidget from vvs_app.master_editor_wnd import MasterEditorWnd from vvs_app.master_designer_wnd import MasterDesignerWnd from vvs_app.editor_node_list import NodeList from vvs_app.editor_files_wdg import FilesWDG from vvs_app.editor_user_nodes_list import UserNodesList from vvs_app.editor_properties_list import PropertiesList from vvs_app.global_switches import * from nodeeditor.utils import dumpException # from vvs_app.nodes_configuration import FUNCTIONS # Enabling edge validators from nodeeditor.node_edge import Edge from nodeeditor.node_edge_validators import ( edge_cannot_connect_two_outputs_or_two_inputs, edge_cannot_connect_input_and_output_of_same_node ) # Edge.registerEdgeValidator(edge_validator_debug) from vvs_app.master_node import MasterNode from vvs_app.nodes.nodes_configuration import register_Node Edge.registerEdgeValidator(edge_cannot_connect_two_outputs_or_two_inputs) Edge.registerEdgeValidator(edge_cannot_connect_input_and_output_of_same_node) # images for the dark skin DEBUG = False class MasterWindow(NodeEditorWindow): def initUI(self): # self.qss_theme = "qss/nodeeditor-light.qss" self.settingsWidget = None self.qss_theme = self.global_switches.themes[self.global_switches.switches_Dict["Appearance"]["Theme"][0]] # ["Theme"][0] self.stylesheet_filename = os.path.join(os.path.dirname(__file__), self.qss_theme) loadStylesheets( os.path.join(os.path.dirname(__file__), self.qss_theme), self.stylesheet_filename) self.global_switches.update_font_size(self.global_switches.switches_Dict["Appearance"]["Font Size"]) self.empty_icon = QIcon(".") if DEBUG: print("Registered nodes:") self.stackedDisplay = QStackedWidget() self.graphs_parent_wdg = QMdiArea() self.CreateLibraryWnd() # Create Node Designer Window self.node_designer = MasterDesignerWnd(self) self.stackedDisplay.addWidget(self.graphs_parent_wdg) self.stackedDisplay.addWidget(self.node_designer) self.graphs_parent_wdg.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.graphs_parent_wdg.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.graphs_parent_wdg.setTabsClosable(True) self.graphs_parent_wdg.setTabsMovable(True) self.graphs_parent_wdg.subWindowActivated.connect(self.active_graph_switched) self.setCentralWidget(self.stackedDisplay) self.windowMapper = QSignalMapper(self) self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow) # Create Welcome Screen and allow user to set the project Directory self.create_welcome_screen() # Create Nodes List self.create_functions_dock() # Create Files Dock self.create_files_dock() # Create Details List Window self.create_properties_dock() # Create Variable List self.create_user_nodes_dock() self.createActions() self.create_menus() self.createStatusBar() self.update_menus() self.readSettings() self.CreateToolBar() self.setWindowTitle("Vision Visual Scripting") self.update_libraries_wnd() self.library_menu.setEnabled(False) self.node_designer_menu.setEnabled(False) self.set_actions_shortcuts() def create_welcome_screen(self): Elayout = QVBoxLayout() Elayout.setAlignment(Qt.AlignCenter) Elayout.setSpacing(20) self.empty_screen = QWidget() self.empty_screen.setLayout(Elayout) user_text = QLabel("Select Your Project Directory...") user_text.setFont(QFont("Roboto", 14)) w_image = QPixmap("icons/Dark/VVS_White2.png" if self.global_switches.switches_Dict["Appearance"]['Theme'][0] == 'Dark' else "icons/light/VVS_White2.png") welcome_image = QLabel() welcome_image.setPixmap(w_image) self.brows_btn = QPushButton("Brows..") Elayout.addWidget(welcome_image) Elayout.addItem(QSpacerItem(120, 120)) Elayout.addWidget(user_text) Elayout.addWidget(self.brows_btn) self.stackedDisplay.addWidget(self.empty_screen) self.switch_display(Welcome=True) def CreateOfflineDir(self): self.Offline_Dir = f"C:/Users/{os.getlogin()}/AppData/Roaming/VVS/Offline Library" if os.path.exists(self.Offline_Dir): pass else: self.Offline_Dir = os.makedirs(os.getenv('AppData') + "/VVS/Offline Library") self.library_offline_list.setRootIndex(self.Model.index(self.Offline_Dir)) def CreateLibraryWnd(self): self.librariesDock = QDockWidget("Libraries") self.library_subwnd = QTabWidget() self.librariesDock.setWidget(self.library_subwnd) self.librariesDock.setFeatures(self.librariesDock.DockWidgetMovable) self.addDockWidget(Qt.RightDockWidgetArea, self.librariesDock) offline_Vlayout = QVBoxLayout() offline_Vlayout.setContentsMargins(0, 0, 0, 0) self.Model = QFileSystemModel() self.Model.setRootPath("") self.library_offline_list = QTreeView() self.library_offline_list.setSelectionMode(QAbstractItemView.ExtendedSelection) self.library_offline_list.setModel(self.Model) self.library_offline_list.setSortingEnabled(True) self.library_offline_list.setColumnWidth(0, 130) self.library_offline_list.sortByColumn(0, Qt.AscendingOrder) self.library_offline_list.hideColumn(1) self.library_offline_list.hideColumn(2) self.library_offline_list.setStyleSheet("color: white") self.library_offline_list.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) offline_Vlayout.addWidget(self.library_offline_list) self.library_online_list = QListWidget() topVlayout = QVBoxLayout() search_bar_layout = QHBoxLayout() self.search_line_edit = QLineEdit() self.search_btn = QPushButton() search_bar_layout.addWidget(self.search_line_edit) search_bar_layout.addWidget(self.search_btn) self.search_btn.setMaximumSize(30, 30) self.search_btn.setIcon(QIcon("icons/Light/search.png")) self.search_line_edit.setMinimumHeight(30) topVlayout.addLayout(search_bar_layout) topVlayout.addWidget(self.library_online_list) online_widget = QWidget() online_widget.setLayout(topVlayout) offline_widget = QWidget() offline_widget.setLayout(offline_Vlayout) self.library_subwnd.addTab(offline_widget, " Offline ") self.library_subwnd.addTab(online_widget, " Online ") self.CreateOfflineDir() self.library_offline_list.clicked.connect(self.ViewSelectedFiles) def ViewSelectedFiles(self): all_files = [] selected_files = self.library_offline_list.selectedIndexes() for file_name in selected_files: file_path = QFileSystemModel().filePath(file_name) if file_path.endswith(".json"): if not all_files.__contains__(file_path): all_files.append(file_path) # print(all_files) self.on_file_open(all_files) def active_graph_switched(self): self.update_menus() if self.currentNodeEditor(): self.VEStackedWdg.setCurrentWidget(self.currentNodeEditor().scene.user_nodes_wdg) def switch_display(self, Welcome=False, Editor=False, Designer=False, Library=False): # Use the Argument To Force Activate the Specified Window if Editor: self.stackedDisplay.setCurrentIndex(0) self.library_btn.setChecked(False) self.node_editor_btn.setChecked(True) self.node_designer_btn.setChecked(False) return if Library: self.stackedDisplay.setCurrentIndex(0) self.library_btn.setChecked(True) self.node_editor_btn.setChecked(False) self.node_designer_btn.setChecked(False) return elif Designer: self.stackedDisplay.setCurrentIndex(1) self.library_btn.setChecked(False) self.node_editor_btn.setChecked(False) self.node_designer_btn.setChecked(True) self.node_editor_menu.setEnabled(False) self.library_menu.setEnabled(False) self.toolbar_library.setChecked(False) self.librariesDock.setVisible(self.toolbar_library.isChecked()) return elif Welcome: self.stackedDisplay.setCurrentIndex(2) return def CreateToolBar(self): # Create Tools self.tools_bar self.tools_bar = QToolBar("Tools", self) self.tools_bar.setIconSize(QSize(20, 20)) self.tools_bar.setFloatable(False) # Add self.tools_bar To Main Window self.addToolBar(self.tools_bar) # Add and connect self.settingsBtn self.settingsBtn = QAction(QIcon(self.global_switches.get_icon("settings.png")), "&Open Settings Window", self) self.settingsBtn.setIconText("settings.png") self.settingsBtn.setCheckable(True) self.settingsBtn.triggered.connect(self.onSettingsOpen) self.settingsBtn.setShortcut(QKeySequence(self.global_switches.switches_Dict["Key Mapping"]["Settings Window"])) self.tools_bar.addAction(self.settingsBtn) self.actions_list["Settings Window"] = self.settingsBtn # Add Separator self.tools_bar.addSeparator() # Add and connect self.node_editor_btn self.node_editor_btn = QAction(QIcon(self.global_switches.get_icon("edit.png")), "&Node Editor", self) self.node_editor_btn.setIconText("edit.png") self.node_editor_btn.setCheckable(True) self.node_editor_btn.triggered.connect(self.activate_editor_mode) self.tools_bar.addAction(self.node_editor_btn) self.actions_list["Node Editor Window"] = self.node_editor_btn # Add and connect self.node_designer_btn self.node_designer_btn = QAction(QIcon(self.global_switches.get_icon("node design.png")), "&Node Designer", self) self.node_designer_btn.setIconText("node design.png") self.node_designer_btn.setEnabled(False) self.node_designer_btn.setCheckable(True) self.node_designer_btn.triggered.connect(self.activate_designer_mode) self.tools_bar.addAction(self.node_designer_btn) self.actions_list["Node Designer Window"] = self.node_designer_btn # Add and connect self.library_btn self.library_btn = QAction(QIcon(self.global_switches.get_icon("library.png")), "&Library", self) self.library_btn.setIconText("library.png") self.library_btn.setCheckable(True) self.library_btn.triggered.connect(self.activate_library_mode) self.library_btn.setShortcut(QKeySequence("`")) self.tools_bar.addAction(self.library_btn) self.actions_list["Library Window"] = self.library_btn # Add Separator self.tools_bar.addSeparator() # # Add Separator # self.tools_bar.addSeparator() def onSettingsOpen(self): if self.settingsWidget: if self.settingsWidget.isHidden(): self.settingsWidget.show() self.settingsBtn.setChecked(True) else: self.settingsWidget.hide() else: self.settingsWidget = SettingsWidget(masterRef=self) self.global_switches.update_font_size(self.global_switches.switches_Dict["Appearance"]["Font Size"]) self.settingsWidget.show() self.settingsBtn.setChecked(True) self.settingsWidget.setWindowTitle("Settings") self.settingsWidget.setGeometry(300, 150, 1200, 800) def closeEvent(self, event): self.graphs_parent_wdg.closeAllSubWindows() if self.graphs_parent_wdg.currentSubWindow(): event.ignore() else: self.writeSettings() event.accept() # hacky fix for PyQt 5.14.x import sys sys.exit(0) def createActions(self): super().createActions() self.actClose = QAction("Cl&ose", self, statusTip="Close the active window", triggered=self.graphs_parent_wdg.closeActiveSubWindow) self.actCloseAll = QAction("Close &All", self, statusTip="Close all the windows", triggered=self.graphs_parent_wdg.closeAllSubWindows) self.actTile = QAction("&Tile", self, statusTip="Tile the windows", triggered=self.graphs_parent_wdg.tileSubWindows) self.actCascade = QAction("&Cascade", self, statusTip="Cascade the windows", triggered=self.graphs_parent_wdg.cascadeSubWindows) self.actNext = QAction("Ne&xt", self, shortcut=QKeySequence.NextChild, statusTip="Move the focus to the next window", triggered=self.graphs_parent_wdg.activateNextSubWindow) self.actPrevious = QAction("Pre&vious", self, shortcut=QKeySequence.PreviousChild, statusTip="Move the focus to the previous window", triggered=self.graphs_parent_wdg.activatePreviousSubWindow) self.actSeparator = QAction(self) self.actSeparator.setSeparator(True) self.actAbout = QAction("&About", self, statusTip="Show the application's About box", triggered=self.about) self.actDoc = QAction("&Documentation", self, triggered=self.open_doc) self.actions_list = {"New Graph": self.actNew, "Open": self.actOpen, "Set Project Location": self.actSetProjectDir, "Save": self.actSave, "Save As": self.actSaveAs, "Exit": self.actExit, "Undo": self.actUndo, "Redo": self.actRedo, "Cut": self.actCut, "Copy": self.actCopy, "Paste": self.actPaste, "Delete": self.actDelete, "Select All": self.actSelectAll, } def set_actions_shortcuts(self): shortcuts = self.global_switches.switches_Dict["Key Mapping"] for act in self.actions_list: if shortcuts.__contains__(act): self.actions_list[act].setShortcut(shortcuts[act]) def open_doc(self): subprocess.Popen('hh.exe "VVS-Help.chm"') def currentNodeEditor(self): """ we're returning NodeEditorWidget here... """ activeSubWindow = self.graphs_parent_wdg.activeSubWindow() if activeSubWindow: return activeSubWindow.widget() else: return None def on_new_graph_tab(self): # Overrides Node Editor Window > actNew action try: subwnd = self.new_graph_tab() all_names = [] for item in self.graphs_parent_wdg.subWindowList(): all_names.append(item.widget().windowTitle()) self.files_widget.new_graph_name(subwnd, all_names) except Exception as e: dumpException(e) def on_file_open(self, all_files=False): if all_files == False: file_names, filter = QFileDialog.getOpenFileNames(self, 'Open graph from file', self.files_widget.Project_Directory, self.getFileDialogFilter()) else: file_names = all_files try: for file_name in file_names: if file_name: if self.findMdiChild(file_name): subwnd = self.findMdiChild(file_name) self.graphs_parent_wdg.setActiveSubWindow(subwnd) else: # We need to create new subWindow and open the file subwnd = self.new_graph_tab() node_editor = subwnd.widget() if node_editor.fileLoad(file_name): self.statusBar().showMessage("File %s loaded" % file_name, 5000) node_editor.setWindowTitle(os.path.splitext(os.path.basename(file_name))[0]) else: node_editor.close() except Exception as e: dumpException(e) def create_menus(self): super().create_menus() self.node_editor_menu = self.menuBar().addMenu("&Node Editor") self.library_menu = self.menuBar().addMenu("&Library") self.node_designer_menu = self.menuBar().addMenu("&Node Designer") self.update_window_menu() self.helpMenu = self.menuBar().addMenu("&Help") self.helpMenu.addAction(self.actDoc) self.helpMenu.addAction(self.actAbout) self.editMenu.aboutToShow.connect(self.update_edit_menu) def update_menus(self): # print("update Menus") active = self.currentNodeEditor() hasMdiChild = (active is not None) # Update File Menu self.actSave.setEnabled(hasMdiChild) self.actSaveAs.setEnabled(hasMdiChild) # Update Node Editor Menu self.actSelectAll.setEnabled(hasMdiChild) self.actClose.setEnabled(hasMdiChild) self.actCloseAll.setEnabled(hasMdiChild) self.actTile.setEnabled(hasMdiChild) self.actCascade.setEnabled(hasMdiChild) self.actNext.setEnabled(hasMdiChild) self.actPrevious.setEnabled(hasMdiChild) self.actSeparator.setVisible(hasMdiChild) # Update Edit Menu self.update_edit_menu() def update_edit_menu(self): try: # print("update Edit Menu") active = self.currentNodeEditor() hasMdiChild = (active is not None) self.actPaste.setEnabled(hasMdiChild) self.actCut.setEnabled(hasMdiChild and active.hasSelectedItems()) self.actSelectAll.setEnabled(hasMdiChild) self.actCopy.setEnabled(hasMdiChild and active.hasSelectedItems()) self.actDelete.setEnabled(hasMdiChild and active.hasSelectedItems()) self.actUndo.setEnabled(hasMdiChild and active.canUndo()) self.actRedo.setEnabled(hasMdiChild and active.canRedo()) except Exception as e: dumpException(e) def update_window_menu(self): self.toolbar_library = self.library_menu.addAction("Libraries Window") self.toolbar_library.setCheckable(True) self.toolbar_library.triggered.connect(self.update_libraries_wnd) self.toolbar_library.setChecked(False) self.toolbar_properties = self.node_editor_menu.addAction("Properties Window") self.toolbar_properties.setCheckable(True) self.toolbar_properties.triggered.connect(self.update_properties_wnd) self.toolbar_properties.setChecked(True) self.toolbar_files = self.node_editor_menu.addAction("Project Files Window") self.toolbar_files.setCheckable(True) self.toolbar_files.triggered.connect(self.update_files_wnd) self.toolbar_files.setChecked(True) self.toolbar_events_vars = self.node_editor_menu.addAction("Variables & Events Window") self.toolbar_events_vars.setCheckable(True) self.toolbar_events_vars.triggered.connect(self.update_events_vars_wnd) self.toolbar_events_vars.setChecked(True) self.toolbar_functions = self.node_editor_menu.addAction("Functions Window") self.toolbar_functions.setCheckable(True) self.toolbar_functions.triggered.connect(self.update_functions_wnd) self.toolbar_functions.setChecked(True) self.node_editor_menu.addSeparator() self.node_editor_menu.addAction(self.actClose) self.node_editor_menu.addAction(self.actCloseAll) self.node_editor_menu.addSeparator() self.node_editor_menu.addAction(self.actTile) # self.windowMenu.addAction(self.actCascade) self.node_editor_menu.addSeparator() self.node_editor_menu.addAction(self.actNext) self.node_editor_menu.addAction(self.actPrevious) self.node_editor_menu.addAction(self.actSeparator) windows = self.graphs_parent_wdg.subWindowList() self.actSeparator.setVisible(len(windows) != 0) for i, window in enumerate(windows): child = window.widget() text = "%d %s" % (i + 1, child.getUserFriendlyFilename()) if i < 9: text = '&' + text action = self.node_editor_menu.addAction(text) action.setCheckable(True) action.setChecked(child is self.currentNodeEditor()) action.triggered.connect(self.windowMapper.map) self.windowMapper.setMapping(action, window) def update_functions_wnd(self): self.toolbar_functions.setChecked(self.toolbar_functions.isChecked()) self.functionsDock.setVisible(self.toolbar_functions.isChecked()) def update_events_vars_wnd(self): self.toolbar_events_vars.setChecked(self.toolbar_events_vars.isChecked()) self.varsEventsDock.setVisible(self.toolbar_events_vars.isChecked()) def update_properties_wnd(self): self.toolbar_properties.setChecked(self.toolbar_properties.isChecked()) self.proprietiesDock.setVisible(self.toolbar_properties.isChecked()) def update_libraries_wnd(self): self.toolbar_library.setChecked(self.toolbar_library.isChecked()) self.librariesDock.setVisible(self.toolbar_library.isChecked()) def update_files_wnd(self): self.toolbar_files.setChecked(self.toolbar_files.isChecked()) self.filesDock.setVisible(self.toolbar_files.isChecked()) def activate_editor_mode(self): if self.graphs_parent_wdg.subWindowList(): self.switch_display(Editor=True) else: self.switch_display(Welcome=True) self.node_editor_menu.setEnabled(True) self.library_menu.setEnabled(False) self.toolbar_library.setChecked(False) self.librariesDock.setVisible(self.toolbar_library.isChecked()) self.toolbar_functions.setChecked(True) self.functionsDock.setVisible(self.toolbar_functions.isChecked()) self.toolbar_files.setChecked(True) self.filesDock.setVisible(self.toolbar_files.isChecked()) self.toolbar_properties.setChecked(True) self.proprietiesDock.setVisible(self.toolbar_properties.isChecked()) def activate_designer_mode(self): self.switch_display(Designer=True) def activate_library_mode(self): if self.graphs_parent_wdg.subWindowList(): self.switch_display(Library=True) else: self.switch_display(Welcome=True) # Handel buttons State self.node_editor_menu.setEnabled(False) self.library_menu.setEnabled(True) self.toolbar_library.setChecked(True) self.librariesDock.setVisible(self.toolbar_library.isChecked()) self.toolbar_files.setChecked(False) self.filesDock.setVisible(self.toolbar_files.isChecked()) def create_functions_dock(self): self.functionsDock = QDockWidget("Functions") self.nodesListWidget = NodeList() self.functionsDock.setWidget(self.nodesListWidget) self.functionsDock.setFeatures(self.functionsDock.DockWidgetMovable) self.addDockWidget(Qt.LeftDockWidgetArea, self.functionsDock) def create_files_dock(self): self.brows_btn.clicked.connect(self.files_widget.set_project_folder) # self.files_widget.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.filesDock = QDockWidget("Project Files") self.filesDock.setWidget(self.files_widget) self.filesDock.setFeatures(self.filesDock.DockWidgetMovable) self.addDockWidget(Qt.RightDockWidgetArea, self.filesDock) def create_properties_dock(self): self.proprietiesWdg = PropertiesList(master_ref=self) self.proprietiesDock = QDockWidget("Properties") self.proprietiesDock.setWidget(self.proprietiesWdg) self.proprietiesDock.setFeatures(self.proprietiesDock.DockWidgetMovable) self.addDockWidget(Qt.RightDockWidgetArea, self.proprietiesDock) def create_user_nodes_dock(self): self.varsEventsDock = QDockWidget("Variables & Events") self.VEStackedWdg = QStackedWidget() self.VEStackedWdg.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.varsEventsDock.setWidget(self.VEStackedWdg) self.varsEventsDock.setFeatures(self.varsEventsDock.DockWidgetMovable) self.addDockWidget(Qt.LeftDockWidgetArea, self.varsEventsDock) def delete_user_nodes_wgd(self, ref): self.VEStackedWdg.removeWidget(ref) def createStatusBar(self): self.statusBar().showMessage("Ready") def before_window_close(self): self.proprietiesWdg.clear() def on_before_save_file(self): self.proprietiesWdg.clear() def new_graph_tab(self): # This Check Prevents The Parent graph from opening in Cascade view-mode if not self.graphs_parent_wdg.subWindowList(): self.switch_display(Editor=True) node_editor = MasterEditorWnd(masterRef=self) VEL = UserNodesList(scene=node_editor.scene, propertiesWdg=self.proprietiesWdg) self.VEStackedWdg.addWidget(VEL) self.VEStackedWdg.setCurrentWidget(VEL) node_editor.scene.user_nodes_wdg = VEL # node_editor.scene.masterRef = self # node_editor.scene.history.masterRef = self subwnd = QMdiSubWindow() subwnd.setAttribute(Qt.WA_DeleteOnClose, True) subwnd.setWidget(node_editor) self.graphs_parent_wdg.addSubWindow(subwnd) subwnd.setWindowIcon(self.empty_icon) node_editor.scene.addItemSelectedListener(self.update_edit_menu) node_editor.scene.addItemsDeselectedListener(self.update_edit_menu) node_editor.scene.history.addHistoryModifiedListener(self.update_edit_menu) node_editor.addCloseEventListener(self.on_sub_wnd_close) self.graphs_parent_wdg.setViewMode(QMdiArea.TabbedView) subwnd.show() return subwnd def on_sub_wnd_close(self, widget, event): existing = self.findMdiChild(widget.filename) self.graphs_parent_wdg.setActiveSubWindow(existing) if self.ask_save(): event.accept() self.delete_user_nodes_wgd(widget.scene.user_nodes_wdg) if (len(self.graphs_parent_wdg.subWindowList())-1) == 0: self.switch_display(Welcome=True) else: self.switch_display(Editor=True) self.before_window_close() else: event.ignore() def findMdiChild(self, filename): for window in self.graphs_parent_wdg.subWindowList(): if window.widget().filename == filename: return window return None def setActiveSubWindow(self, window): if window: self.graphs_parent_wdg.setActiveSubWindow(window) def get_QWidget_content(self, widget): if [QKeySequenceEdit].__contains__(type(widget)): return widget.keySequence().toString() elif [QSpinBox, QDoubleSpinBox].__contains__(type(widget)): return widget.value() elif [QLineEdit, QLabel].__contains__(type(widget)): return widget.text() elif [QTextEdit].__contains__(type(widget)): return widget.toPlainText() elif [QRadioButton, QCheckBox].__contains__(type(widget)): return widget.isChecked() elif [QComboBox].__contains__(type(widget)): current = widget.currentText() widget.removeItem(widget.currentIndex()) content_list = [current] for index in range(widget.__len__()): content_list.append(widget.itemText(index)) widget.clear() widget.addItems(content_list) return content_list else: print(widget, "Widget Not Supported") return None def set_QWidget_content(self, widget, new_value): if [QKeySequenceEdit].__contains__(type(widget)): widget.setKeySequence(new_value) elif [QSpinBox, QDoubleSpinBox].__contains__(type(widget)): widget.setValue(new_value) elif [QLineEdit, QLabel, QTextEdit].__contains__(type(widget)): widget.setText(new_value) elif [QRadioButton, QCheckBox].__contains__(type(widget)): widget.setChecked(new_value) elif [QComboBox].__contains__(type(widget)): widget.addItems(new_value) else: print(widget, "Widget Not Supported") def about(self): QMessageBox.about(self, "About Calculator NodeEditor Example", "The <b>Calculator NodeEditor</b> example demonstrates how to write multiple " "document interface applications using PyQt5 and NodeEditor. For more information visit: " "<a href='https://www.blenderfreak.com/'>www.BlenderFreak.com</a>")
38.693904
201
0.676968
7951a12f7373608912f8d4afccdf0d7bde911d74
359
py
Python
flaskbb/__init__.py
rehee/try_discuz
063c2c89c25054c88b3ac785a3ed135c7abc9be5
[ "BSD-3-Clause" ]
8
2015-08-08T00:19:34.000Z
2019-08-28T16:20:19.000Z
flaskbb/__init__.py
rehee/try_discuz
063c2c89c25054c88b3ac785a3ed135c7abc9be5
[ "BSD-3-Clause" ]
45
2021-03-22T07:15:27.000Z
2021-12-23T21:07:10.000Z
flaskbb/__init__.py
rehee/try_discuz
063c2c89c25054c88b3ac785a3ed135c7abc9be5
[ "BSD-3-Clause" ]
6
2021-03-26T18:30:56.000Z
2022-03-27T10:58:53.000Z
# -*- coding: utf-8 -*- """ flaskbb ~~~~~~~ FlaskBB is a forum software written in python using the microframework Flask. :copyright: (c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ __version__ = "2.0.2" import logging logger = logging.getLogger(__name__) from flaskbb.app import create_app # noqa
18.894737
59
0.660167
7951a1b8aeea89ad1d6c9b0b5398f5975b099b0b
1,721
py
Python
data/migrations/0002_create_schools.py
mdavoodi/konkourse-python
50f2904e7bbb31f00c4dd66fb55cd644ea3c4eee
[ "MIT" ]
4
2015-06-23T22:17:50.000Z
2019-01-17T21:32:02.000Z
data/migrations/0002_create_schools.py
mdavoodi/konkourse-python
50f2904e7bbb31f00c4dd66fb55cd644ea3c4eee
[ "MIT" ]
null
null
null
data/migrations/0002_create_schools.py
mdavoodi/konkourse-python
50f2904e7bbb31f00c4dd66fb55cd644ea3c4eee
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.conf import settings from django.core.files import File import os # class Migration(DataMigration): def forwards(self, orm): Page = orm['page.Page'] virginia_tech = Page(title='Virginia Tech') virginia_tech.save() image = open(settings.DEFAULT_PATH + '/static/img/logos/vt-logo.jpg') virginia_tech.image.save(os.path.basename(image.name), File(image)) jmu = Page(title='James Madison University') jmu.save() image = open(settings.DEFAULT_PATH + '/static/img/logos/jmu-logo.jpg') jmu.image.save(os.path.basename(image.name), File(image)) uva = Page(title='University of Virginia') uva.save() image = open(settings.DEFAULT_PATH + '/static/img/logos/uva-logo.jpg') uva.image.save(os.path.basename(image.name), File(image)) konkourse = Page(title='Konkourse') konkourse.save() image = open(settings.DEFAULT_PATH + '/static/img/logos/konkourse.png') konkourse.image.save(os.path.basename(image.name), File(image)) models = { u'page.page': { 'Meta': {'object_name': 'Page'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': "'1000'"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': "'30'"}) } } complete_apps = ['page', 'data'] symmetrical = True
35.854167
95
0.620569
7951a2ca63e1a3c9253c8e7ab1a16087db1e792f
578
py
Python
tests/test_paint.py
yngtodd/paint
ee39d58ad430e473b4d8f88107a6d7658f9e34f8
[ "MIT" ]
null
null
null
tests/test_paint.py
yngtodd/paint
ee39d58ad430e473b4d8f88107a6d7658f9e34f8
[ "MIT" ]
null
null
null
tests/test_paint.py
yngtodd/paint
ee39d58ad430e473b4d8f88107a6d7658f9e34f8
[ "MIT" ]
null
null
null
#!/usr/bin/env python """Tests for `paint` package.""" # pylint: disable=redefined-outer-name import pytest @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string del response
23.12
78
0.704152
7951a2fd617903a24f35c213ccb78d7ca750e441
1,465
py
Python
migrations/versions/63c5fe144a13_adding_user_controls.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
migrations/versions/63c5fe144a13_adding_user_controls.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
migrations/versions/63c5fe144a13_adding_user_controls.py
ukblumf/randomise-it
0610721eba649dfa205b0d3c4b3e24d67aa1d781
[ "MIT" ]
null
null
null
"""Adding User Controls Revision ID: 63c5fe144a13 Revises: 840486fe2851 Create Date: 2020-09-08 16:49:49.286078 """ # revision identifiers, used by Alembic. revision = '63c5fe144a13' down_revision = '840486fe2851' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('users', schema=None) as batch_op: batch_op.add_column(sa.Column('login_ban', sa.Boolean(), nullable=True)) batch_op.add_column(sa.Column('login_ban_description', sa.String(length=512), nullable=True)) batch_op.add_column(sa.Column('login_ban_until', sa.DateTime(), nullable=True)) batch_op.add_column(sa.Column('share_ban', sa.Boolean(), nullable=True)) batch_op.add_column(sa.Column('share_ban_description', sa.String(length=512), nullable=True)) batch_op.add_column(sa.Column('share_ban_until', sa.DateTime(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table('users', schema=None) as batch_op: batch_op.drop_column('share_ban_until') batch_op.drop_column('share_ban_description') batch_op.drop_column('share_ban') batch_op.drop_column('login_ban_until') batch_op.drop_column('login_ban_description') batch_op.drop_column('login_ban') # ### end Alembic commands ###
35.731707
101
0.70785
7951a3726c0518bd81550799563609dff773cac5
16,566
py
Python
training/training_code/bert/create_pretraining_data.py
yil532/MAX-Text-Sentiment-Classifier
6f40c4f5def7d0a0ddd96cfc3e382d4c936b7ac6
[ "Apache-2.0" ]
null
null
null
training/training_code/bert/create_pretraining_data.py
yil532/MAX-Text-Sentiment-Classifier
6f40c4f5def7d0a0ddd96cfc3e382d4c936b7ac6
[ "Apache-2.0" ]
null
null
null
training/training_code/bert/create_pretraining_data.py
yil532/MAX-Text-Sentiment-Classifier
6f40c4f5def7d0a0ddd96cfc3e382d4c936b7ac6
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create masked LM/next sentence masked_lm TF examples for BERT.""" import collections import random import tensorflow as tf import tokenization flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_string("input_file", None, "Input raw text file (or comma-separated list of files).") flags.DEFINE_string( "output_file", None, "Output TF example file (or comma-separated list of files).") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_bool( "do_lower_case", True, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_integer("max_seq_length", 128, "Maximum sequence length.") flags.DEFINE_integer("max_predictions_per_seq", 20, "Maximum number of masked LM predictions per sequence.") flags.DEFINE_integer("random_seed", 12345, "Random seed for data generation.") flags.DEFINE_integer( "dupe_factor", 10, "Number of times to duplicate the input data (with different masks).") flags.DEFINE_float("masked_lm_prob", 0.15, "Masked LM probability.") flags.DEFINE_float( "short_seq_prob", 0.1, "Probability of creating sequences which are shorter than the " "maximum length.") class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, is_random_next): self.tokens = tokens self.segment_ids = segment_ids self.is_random_next = is_random_next self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "tokens: %s\n" % (" ".join( [tokenization.printable_text(x) for x in self.tokens])) s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) s += "is_random_next: %s\n" % self.is_random_next s += "masked_lm_positions: %s\n" % (" ".join( [str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % (" ".join( [tokenization.printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.python_io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= max_seq_length while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = tokenizer.convert_tokens_to_ids(instance.masked_lm_labels) masked_lm_weights = [1.0] * len(masked_lm_ids) while len(masked_lm_positions) < max_predictions_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(0) masked_lm_weights.append(0.0) next_sentence_label = 1 if instance.is_random_next else 0 features = collections.OrderedDict() features["input_ids"] = create_int_feature(input_ids) features["input_mask"] = create_int_feature(input_mask) features["segment_ids"] = create_int_feature(segment_ids) features["masked_lm_positions"] = create_int_feature(masked_lm_positions) features["masked_lm_ids"] = create_int_feature(masked_lm_ids) features["masked_lm_weights"] = create_float_feature(masked_lm_weights) features["next_sentence_labels"] = create_int_feature([next_sentence_label]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) writers[writer_index].write(tf_example.SerializeToString()) writer_index = (writer_index + 1) % len(writers) total_written += 1 if inst_index < 20: tf.logging.info("*** Example ***") tf.logging.info("tokens: %s" % " ".join( [tokenization.printable_text(x) for x in instance.tokens])) for feature_name in features.keys(): feature = features[feature_name] values = [] if feature.int64_list.value: values = feature.int64_list.value elif feature.float_list.value: values = feature.float_list.value tf.logging.info( "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.logging.info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) return feature def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): """Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) One sentence per line. These should ideally be actual sentences, not # entire paragraphs or arbitrary spans of text. (Because we use the # sentence boundaries for the "next sentence prediction" task). # (2) Blank lines between documents. Document boundaries are needed so # that the "next sentence prediction" task doesn't span between documents. for input_file in input_files: with tf.gfile.GFile(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break line = line.strip() # Empty lines are used as document delimiters if not line: all_documents.append([]) tokens = tokenizer.tokenize(line) if tokens: all_documents[-1].append(tokens) # Remove empty documents all_documents = [x for x in all_documents if x] rng.shuffle(all_documents) vocab_words = list(tokenizer.vocab.keys()) instances = [] for _ in range(dupe_factor): for document_index in range(len(all_documents)): instances.extend( create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng)) rng.shuffle(instances) return instances def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter # sequences to minimize the mismatch between pre-training and fine-tuning. # The `target_seq_length` is just a rough target however, whereas # `max_seq_length` is a hard limit. target_seq_length = max_num_tokens if rng.random() < short_seq_prob: target_seq_length = rng.randint(2, max_num_tokens) # We DON'T just concatenate all of the tokens from a document into a long # sequence and choose an arbitrary split point because this would make the # next sentence prediction task too easy. Instead, we split the input into # segments "A" and "B" based on the actual "sentences" provided by the user # input. instances = [] current_chunk = [] current_length = 0 i = 0 while i < len(document): segment = document[i] current_chunk.append(segment) current_length += len(segment) if i == len(document) - 1 or current_length >= target_seq_length: if current_chunk: # `a_end` is how many segments from `current_chunk` go into the `A` # (first) sentence. a_end = 1 if len(current_chunk) >= 2: a_end = rng.randint(1, len(current_chunk) - 1) tokens_a = [] for j in range(a_end): tokens_a.extend(current_chunk[j]) tokens_b = [] # Random next is_random_next = False if len(current_chunk) == 1 or rng.random() < 0.5: is_random_next = True target_b_length = target_seq_length - len(tokens_a) # This should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the document # we're processing. for _ in range(10): random_document_index = rng.randint(0, len(all_documents) - 1) if random_document_index != document_index: break random_document = all_documents[random_document_index] random_start = rng.randint(0, len(random_document) - 1) for j in range(random_start, len(random_document)): tokens_b.extend(random_document[j]) if len(tokens_b) >= target_b_length: break # We didn't actually use these segments so we "put them back" so # they don't go to waste. num_unused_segments = len(current_chunk) - a_end i -= num_unused_segments # Actual next else: is_random_next = False for j in range(a_end, len(current_chunk)): tokens_b.extend(current_chunk[j]) truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) assert len(tokens_a) >= 1 assert len(tokens_b) >= 1 tokens = [] segment_ids = [] tokens.append("[CLS]") segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append("[SEP]") segment_ids.append(0) for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append("[SEP]") segment_ids.append(1) (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng) instance = TrainingInstance( tokens=tokens, segment_ids=segment_ids, is_random_next=is_random_next, masked_lm_positions=masked_lm_positions, masked_lm_labels=masked_lm_labels) instances.append(instance) current_chunk = [] current_length = 0 i += 1 return instances MaskedLmInstance = collections.namedtuple("MaskedLmInstance", ["index", "label"]) def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[SEP]": continue cand_indexes.append(i) rng.shuffle(cand_indexes) output_tokens = list(tokens) num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) masked_lms = [] covered_indexes = set() for index in cand_indexes: if len(masked_lms) >= num_to_predict: break if index in covered_indexes: continue covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if rng.random() < 0.8: masked_token = "[MASK]" else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] output_tokens[index] = masked_token masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop() def main(_): tf.logging.set_verbosity(tf.logging.INFO) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.gfile.Glob(input_pattern)) tf.logging.info("*** Reading from input files ***") for input_file in input_files: tf.logging.info(" %s", input_file) rng = random.Random(FLAGS.random_seed) instances = create_training_instances( input_files, tokenizer, FLAGS.max_seq_length, FLAGS.dupe_factor, FLAGS.short_seq_prob, FLAGS.masked_lm_prob, FLAGS.max_predictions_per_seq, rng) output_files = FLAGS.output_file.split(",") tf.logging.info("*** Writing to output files ***") for output_file in output_files: tf.logging.info(" %s", output_file) write_instance_to_example_files(instances, tokenizer, FLAGS.max_seq_length, FLAGS.max_predictions_per_seq, output_files) if __name__ == "__main__": flags.mark_flag_as_required("input_file") flags.mark_flag_as_required("output_file") flags.mark_flag_as_required("vocab_file") tf.app.run()
37.735763
86
0.62091
7951a3a63ef8b1e1c3cab3782b242a9784ccd584
5,632
py
Python
src/modelSuite/atanProfile.py
mirofedurco/PyAstronomy
b0e5806a18bde647654e6c9de323327803722864
[ "MIT" ]
98
2015-01-01T12:46:05.000Z
2022-02-13T14:17:36.000Z
src/modelSuite/atanProfile.py
mirofedurco/PyAstronomy
b0e5806a18bde647654e6c9de323327803722864
[ "MIT" ]
46
2015-02-10T19:53:38.000Z
2022-01-11T17:26:05.000Z
src/modelSuite/atanProfile.py
mirofedurco/PyAstronomy
b0e5806a18bde647654e6c9de323327803722864
[ "MIT" ]
38
2015-01-08T17:00:34.000Z
2022-03-04T05:15:22.000Z
from __future__ import print_function, division from PyAstronomy import funcFit as fuf import numpy as np class AtanProfile(fuf.OneDFit): """ A profile based on the arc tangent function. This class implements the following profile: .. math:: f(x) = \\frac{A}{2\\arctan(\\sigma)} \\times \\left(\\arctan\\left(\\frac{x-\mu}{scale} + \sigma\\right) + \\arctan\\left(-\\frac{x-\mu}{scale} + \sigma\\right)\\right) + \mu \\times x + off which can provide a relatively flat top and steep edges. *Fit parameters* - `A` - The amplitude. In this case, the height (not the area under) the profile reached for :math:`x=0`. Note that for :math:`\mu \\not = 0` the highest point may be elsewhere, which is neglected here. - `scale` - A scale parameter affecting the width of the profile. Note, however, that also :math:`\sigma` affects the width. - `mu` - The center of the profile. - `off` - An offset - `lin` - A gradient in the offset. The width of the profile may be approximated by the inflection points, which are given by .. math:: \\frac{\\partial^2 f(x)}{\partial x^2} = 0 \\rightarrow x_{1,2} = \mu \\pm\\frac{scale}{3}\\left(-3+3\sigma^2+6\\sqrt{\sigma^4+\sigma^2+1}\\right)^{1/2} """ def __init__(self): fuf.OneDFit.__init__(self, ["scale", "sig", "mu", "A", "off", "lin"]) def evaluate(self, x): """ Calculates and returns model according to the current parameter values. Parameters ---------- x : Array The positions at which to evaluate the model. """ # Shift by mu x = x - self["mu"] # The heart of the profile y = np.arctan(x/self["scale"] + self["sig"]) + np.arctan(-x/self["scale"] + self["sig"]) # Make the highest point (actually most extreme point) # equal to A y *= (self["A"] / (2.*np.arctan(self["sig"]))) # Add offset and gradient y += self["off"] y += self["lin"] * (x + self["mu"]) return y def inflectionPoints(self): """ Calculate the inflection points. The inflection points of the profile depend on both :math:`\sigma` and :math:`\mu`. Returns ------- Inflection points : tuple Locations of the inflection points. Smaller one first. """ d = abs(self["scale"])/3.0 * \ np.sqrt(-3. + 3.*self["sig"]**2 + 6.*np.sqrt(self["sig"]**4 + self["sig"]**2 + 1.0)) return self["mu"]-d, self["mu"]+d class AtanProfileDamped(fuf.OneDFit): """ A profile based on the arc tangent function. This class implements the following profile: .. math:: d(x) = f(x) \\times H(|x-\mu| - |ifp-\mu|) \\times \\exp\\left(\\frac{|x-\mu| - |ifp-\mu|}{\\tau}\\right) + \mu \\times x + off Here :math:`f(x)` is the profile described in :py:class:`AtanProfile`, H denotes the Heaviside function, and ifp is the location of the inflection point. The parameter :math:`\\tau` can be used to provide an additional drop at the edges of the profile. *Fit parameters* - `A` - The amplitude. In this case, the height (not the area under) the profile reached for :math:`x=0`. Note that for :math:`\mu \\not = 0` the highest point may be elsewhere, which is neglected here. - `scale` - A scale parameter affecting the width of the profile. Note, however, that also :math:`\sigma` affects the width. - `tau` - This parameter controls an additional drop at the edges of the profile. - `mu` - The center of the profile. - `off` - An offset - `lin` - A gradient in the offset. The width of the profile may be approximated by the inflection points, which are given by .. math:: \\frac{\\partial^2 f(x)}{\partial x^2} = 0 \\rightarrow x_{1,2} = \mu \\pm\\frac{scale}{3}\\left(-3+3\sigma^2+6\\sqrt{\sigma^4+\sigma^2+1}\\right)^{1/2} """ def __init__(self): fuf.OneDFit.__init__(self, ["scale", "sig", "mu", "A", "off", "lin", "tau"]) def evaluate(self, x): """ Calculates and returns model according to the current parameter values. Parameters ---------- x : Array The positions at which to evaluate the model. """ # Shift by mu x = x - self["mu"] # The heart of the profile y = np.arctan(x/self["scale"] + self["sig"]) + np.arctan(-x/self["scale"] + self["sig"]) # Make the highest point (actually most extreme point) # equal to A y *= (self["A"] / (2.*np.arctan(self["sig"]))) # Produce additional drop difp = abs(self.inflectionPoints()[0] - self["mu"]) indi = np.where(np.abs(x) > difp)[0] y[indi] *= np.exp(-np.abs(np.abs(x[indi])-difp)**2/self["tau"]) # Add offset and gradient y += self["off"] y += self["lin"] * (x + self["mu"]) return y def inflectionPoints(self): """ Calculate the inflection points. The inflection points of the profile depend on both :math:`\sigma` and :math:`\mu`. Returns ------- Inflection points : tuple Locations of the inflection points. Smaller one first. """ d = abs(self["scale"])/3.0 * \ np.sqrt(-3. + 3.*self["sig"]**2 + 6.*np.sqrt(self["sig"]**4 + self["sig"]**2 + 1.0)) return self["mu"]-d, self["mu"]+d
33.927711
112
0.558416
7951a478888d514f45639c78e64ccc8c6d0df8e7
1,033
py
Python
shortener/schema.py
Shivansh2407/octr.ix
c5d46de1c26344f32aa0c6514471a85c795a70dd
[ "MIT" ]
null
null
null
shortener/schema.py
Shivansh2407/octr.ix
c5d46de1c26344f32aa0c6514471a85c795a70dd
[ "MIT" ]
5
2020-11-28T13:38:22.000Z
2022-02-10T02:34:12.000Z
shortener/schema.py
Shivansh2407/octr.ix
c5d46de1c26344f32aa0c6514471a85c795a70dd
[ "MIT" ]
null
null
null
import graphene from graphene_django import DjangoObjectType from django.db.models import Q from .models import URL class URLType(DjangoObjectType): class Meta: model = URL class Query(graphene.ObjectType): urls = graphene.List(URLType, url=graphene.String(), first=graphene.Int(), skip=graphene.Int()) def resolve_urls(self, info, url=None, first=None, skip=None, **kwargs): queryset = URL.objects.all() if url: _filter = Q(full_url__icontains=url) queryset = queryset.filter(_filter) if first: queryset = queryset[:first] if skip: queryset = queryset[skip:] return queryset class CreateURL(graphene.Mutation): url = graphene.Field(URLType) class Arguments: full_url = graphene.String() def mutate(self, info, full_url): url = URL(full_url=full_url) url.save() return CreateURL(url=url) class Mutation(graphene.ObjectType): create_url = CreateURL.Field()
21.978723
99
0.64666
7951a4d138b7f909d0b12efdf23a67ce826f1e7d
11,963
py
Python
bosch_arm/bosch_arm_control/nodes/plotter4.py
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
3
2017-02-02T13:27:45.000Z
2018-06-17T11:52:13.000Z
bosch_arm/bosch_arm_control/nodes/plotter4.py
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
bosch_arm/bosch_arm_control/nodes/plotter4.py
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- import roslib; roslib.load_manifest('bosch_arm_control') import rospy from sensor_msgs.msg import JointState from bma180.msg import bma180meas from bosch_arm_control.msg import Diagnostic import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.Qwt5 import * #import numpy import socket import thread import threading import time import loggerUi #from PyQt4.Qwt5.anynumpy import * class DynamicPlot(QwtPlot): def __init__(self, *args): QwtPlot.__init__(self, *args) self.time = [] self.curves = {} self.tid = 0 self.active = False self.timestep = 20 #50 Hz self.updateCurves = None def start(self): if self.active == False: self.tid = self.startTimer(self.timestep) self.active = True def stop(self): if self.active == True: self.killTimer(self.tid) self.active = False def setUpdateCallback(self, callback): #Function to call to update plot data before replotting self.updateCurves = callback def timerEvent(self, e): lock.acquire() curve1.setData(time,m1values) curve2.setData(time,m2values) curve3.setData(time,m3values) curve4.setData(time,m4values) curve5.setData(time,m1command) curve6.setData(time,m2command) curve7.setData(time,m3command) curve8.setData(time,m4command) #curve9.setData(time,v1) #curve10.setData(time,v2) #curve11.setData(time,v3) #curve12.setData(time,v4) curve9.setData(time,m1error) curve10.setData(time,m2error) curve11.setData(time,m3error) curve12.setData(time,m4error) curve13.setData(time,t1) curve14.setData(time,t2) curve15.setData(time,t3) curve16.setData(time,t4) curve17.setData(time2,accX1) curve18.setData(time2,accY1) curve19.setData(time2,accZ1) curve20.setData(time2,accX2) curve21.setData(time2,accY2) curve22.setData(time2,accZ2) lock.release() self.replot() def diag_listener(msg): da = msg.data.split(',') data = [float(i) for i in da] valout = data[0] #valout = int(data) #print valout #print msg.data pf = 0.5 vf = 0.08 tf = 100/0.184 ef = 10 lock.acquire() m1values.append(data[0]*pf) m1values.pop(0) m2values.append(data[1]*pf) m2values.pop(0) m3values.append(data[2]*pf) m3values.pop(0) m4values.append(data[3]*pf) m4values.pop(0) m1command.append(data[4]*pf) m1command.pop(0) m2command.append(data[5]*pf) m2command.pop(0) m3command.append(data[6]*pf) m3command.pop(0) m4command.append(data[7]*pf) m4command.pop(0) m1error.append(ef*(data[0]-data[4])) m1error.pop(0) m2error.append(ef*(data[1]-data[5])) m2error.pop(0) m3error.append(ef*(data[2]-data[6])) m3error.pop(0) m4error.append(ef*(data[3]-data[7])) m4error.pop(0) v1.append(data[8]*vf) v1.pop(0) v2.append(data[9]*vf) v2.pop(0) v3.append(data[10]*vf) v3.pop(0) v4.append(data[11]*vf) v4.pop(0) t1.append(data[12]*tf) t1.pop(0) t2.append(data[13]*tf) t2.pop(0) t3.append(data[14]*tf) t3.pop(0) t4.append(data[15]*tf) t4.pop(0) lock.release() #print data def acc_listener(data): af = 100 lock.acquire() if data.iChipSelect==0: accX1.append(data.fAcclX*af) accX1.pop(0) accY1.append(data.fAcclY*af) accY1.pop(0) accZ1.append(data.fAcclZ*af) accZ1.pop(0) else: accX2.append(data.fAcclX*af) accX2.pop(0) accY2.append(data.fAcclY*af) accY2.pop(0) accZ2.append(data.fAcclZ*af) accZ2.pop(0) lock.release() def listen(): rospy.init_node('listener', anonymous=True) rospy.Subscriber("/diagnostics", Diagnostic, diag_listener) rospy.Subscriber("/bma180", bma180meas, acc_listener) def toggle(): if ui.m1.isChecked():curve1.setPen(QPen(Qt.red)) else: curve1.setPen(QPen(Qt.NoPen)) if ui.m2.isChecked():curve2.setPen(QPen(Qt.green)) else: curve2.setPen(QPen(Qt.NoPen)) if ui.m3.isChecked():curve3.setPen(QPen(Qt.blue)) else: curve3.setPen(QPen(Qt.NoPen)) if ui.m4.isChecked():curve4.setPen(QPen(Qt.gray)) else: curve4.setPen(QPen(Qt.NoPen)) if ui.m1c.isChecked():curve5.setPen(QPen(Qt.black)) else: curve5.setPen(QPen(Qt.NoPen)) if ui.m2c.isChecked():curve6.setPen(QPen(Qt.black)) else: curve6.setPen(QPen(Qt.NoPen)) if ui.m3c.isChecked():curve7.setPen(QPen(Qt.black)) else: curve7.setPen(QPen(Qt.NoPen)) if ui.m4c.isChecked():curve8.setPen(QPen(Qt.black)) else: curve8.setPen(QPen(Qt.NoPen)) if ui.v1.isChecked():curve9.setPen(QPen(Qt.darkRed)) else: curve9.setPen(QPen(Qt.NoPen)) if ui.v2.isChecked():curve10.setPen(QPen(Qt.darkGreen)) else: curve10.setPen(QPen(Qt.NoPen)) if ui.v3.isChecked():curve11.setPen(QPen(Qt.darkBlue)) else: curve11.setPen(QPen(Qt.NoPen)) if ui.v4.isChecked():curve12.setPen(QPen(Qt.cyan)) else: curve12.setPen(QPen(Qt.NoPen)) if ui.t1.isChecked():curve13.setPen(QPen(Qt.magenta)) else: curve13.setPen(QPen(Qt.NoPen)) if ui.t2.isChecked():curve14.setPen(QPen(Qt.yellow)) else: curve14.setPen(QPen(Qt.NoPen)) if ui.t3.isChecked():curve15.setPen(QPen(Qt.darkCyan)) else: curve15.setPen(QPen(Qt.NoPen)) if ui.t4.isChecked():curve16.setPen(QPen(Qt.darkMagenta)) else: curve16.setPen(QPen(Qt.NoPen)) if ui.accX1.isChecked():curve17.setPen(QPen(Qt.red)) else: curve17.setPen(QPen(Qt.NoPen)) if ui.accY1.isChecked():curve18.setPen(QPen(Qt.green)) else: curve18.setPen(QPen(Qt.NoPen)) if ui.accZ1.isChecked():curve19.setPen(QPen(Qt.blue)) else: curve19.setPen(QPen(Qt.NoPen)) if ui.accX2.isChecked():curve20.setPen(QPen(Qt.darkRed)) else: curve20.setPen(QPen(Qt.NoPen)) if ui.accY2.isChecked():curve21.setPen(QPen(Qt.darkGreen)) else: curve21.setPen(QPen(Qt.NoPen)) if ui.accZ2.isChecked():curve22.setPen(QPen(Qt.darkBlue)) else: curve22.setPen(QPen(Qt.NoPen)) def toggleplot(): if plot.active == True: plot.stop() ui.start_pause.setText("Start") else: plot.start() ui.start_pause.setText("Pause") if __name__=="__main__": length = 2000 reduction=10 lock = threading.Lock() m1values = [0 for i in range(length)] m2values = [0 for i in range(length)] m3values = [0 for i in range(length)] m4values = [0 for i in range(length)] m1command = [0 for i in range(length)] m2command = [0 for i in range(length)] m3command = [0 for i in range(length)] m4command = [0 for i in range(length)] m1error = [0 for i in range(length)] m2error = [0 for i in range(length)] m3error = [0 for i in range(length)] m4error = [0 for i in range(length)] v1 = [0 for i in range(length)] v2 = [0 for i in range(length)] v3 = [0 for i in range(length)] v4 = [0 for i in range(length)] t1 = [0 for i in range(length)] t2 = [0 for i in range(length)] t3 = [0 for i in range(length)] t4 = [0 for i in range(length)] time = [i for i in range(length)] length2= length/reduction accX1 = [0 for i in range(length2)] accY1 = [0 for i in range(length2)] accZ1 = [0 for i in range(length2)] accX2 = [0 for i in range(length2)] accY2 = [0 for i in range(length2)] accZ2 = [0 for i in range(length2)] time2 = [i for i in range(1,length,reduction)] app = QApplication(sys.argv) window = QMainWindow() ui = loggerUi.Ui_MainWindow() ui.setupUi(window) ui.qwtPlot = DynamicPlot(ui.centralwidget) plot = ui.qwtPlot plot.setObjectName("qwtPlot") ui.gridLayout.addWidget(plot, 0, 0, 1, 1) plot.setCanvasBackground(Qt.white) plot.setTitle("Datastream") plot.insertLegend(QwtLegend(), QwtPlot.BottomLegend); curve1 = QwtPlotCurve("M1 position") curve1.attach(plot) curve1.setPen(QPen(Qt.NoPen)) curve2 = QwtPlotCurve("M2 position") curve2.attach(plot) curve2.setPen(QPen(Qt.NoPen)) curve3 = QwtPlotCurve("M3 position") curve3.attach(plot) curve3.setPen(QPen(Qt.NoPen)) curve4 = QwtPlotCurve("M4 position") curve4.attach(plot) curve4.setPen(QPen(Qt.NoPen)) curve5 = QwtPlotCurve("M1 command") curve5.attach(plot) curve5.setPen(QPen(Qt.NoPen)) curve6 = QwtPlotCurve("M2 command") curve6.attach(plot) curve6.setPen(QPen(Qt.NoPen)) curve7 = QwtPlotCurve("M3 command") curve7.attach(plot) curve7.setPen(QPen(Qt.NoPen)) curve8 = QwtPlotCurve("M4 command") curve8.attach(plot) curve8.setPen(QPen(Qt.NoPen)) curve9 = QwtPlotCurve("V1") curve9.attach(plot) curve9.setPen(QPen(Qt.NoPen)) curve10 = QwtPlotCurve("V2") curve10.attach(plot) curve10.setPen(QPen(Qt.NoPen)) curve11 = QwtPlotCurve("V3") curve11.attach(plot) curve11.setPen(QPen(Qt.NoPen)) curve12 = QwtPlotCurve("V4") curve12.attach(plot) curve12.setPen(QPen(Qt.NoPen)) curve13 = QwtPlotCurve("T1") curve13.attach(plot) curve13.setPen(QPen(Qt.NoPen)) curve14 = QwtPlotCurve("T2") curve14.attach(plot) curve14.setPen(QPen(Qt.NoPen)) curve15 = QwtPlotCurve("T3") curve15.attach(plot) curve15.setPen(QPen(Qt.NoPen)) curve16 = QwtPlotCurve("T4") curve16.attach(plot) curve16.setPen(QPen(Qt.NoPen)) curve17 = QwtPlotCurve("accX1") curve17.attach(plot) curve17.setPen(QPen(Qt.NoPen)) curve18 = QwtPlotCurve("accY1") curve18.attach(plot) curve18.setPen(QPen(Qt.NoPen)) curve19 = QwtPlotCurve("accZ1") curve19.attach(plot) curve19.setPen(QPen(Qt.NoPen)) curve20 = QwtPlotCurve("accX2") curve20.attach(plot) curve20.setPen(QPen(Qt.NoPen)) curve21 = QwtPlotCurve("accY2") curve21.attach(plot) curve21.setPen(QPen(Qt.NoPen)) curve22 = QwtPlotCurve("accZ2") curve22.attach(plot) curve22.setPen(QPen(Qt.NoPen)) mY = QwtPlotMarker() mY.setLabelAlignment(Qt.AlignRight | Qt.AlignTop) mY.setLineStyle(QwtPlotMarker.HLine) mY.setYValue(0.0) mY.attach(plot) #plot.setAxisTitle(QwtPlot.xBottom, "Time (s)") #plot.setAxisTitle(QwtPlot.yLeft, "Force (g)") listen() plot.setAxisScale(QwtPlot.yLeft, -125, 125) plot.start() window.connect(ui.start_pause, SIGNAL("released()"), toggleplot) window.connect(ui.m1, SIGNAL("released()"), toggle) window.connect(ui.m2, SIGNAL("released()"), toggle) window.connect(ui.m3, SIGNAL("released()"), toggle) window.connect(ui.m4, SIGNAL("released()"), toggle) window.connect(ui.m1c, SIGNAL("released()"), toggle) window.connect(ui.m2c, SIGNAL("released()"), toggle) window.connect(ui.m3c, SIGNAL("released()"), toggle) window.connect(ui.m4c, SIGNAL("released()"), toggle) window.connect(ui.v1, SIGNAL("released()"), toggle) window.connect(ui.v2, SIGNAL("released()"), toggle) window.connect(ui.v3, SIGNAL("released()"), toggle) window.connect(ui.v4, SIGNAL("released()"), toggle) window.connect(ui.t1, SIGNAL("released()"), toggle) window.connect(ui.t2, SIGNAL("released()"), toggle) window.connect(ui.t3, SIGNAL("released()"), toggle) window.connect(ui.t4, SIGNAL("released()"), toggle) window.connect(ui.accX1, SIGNAL("released()"), toggle) window.connect(ui.accY1, SIGNAL("released()"), toggle) window.connect(ui.accZ1, SIGNAL("released()"), toggle) window.connect(ui.accX2, SIGNAL("released()"), toggle) window.connect(ui.accX2, SIGNAL("released()"), toggle) window.connect(ui.accX2, SIGNAL("released()"), toggle) window.show() sys.exit(app.exec_())
30.133501
68
0.645323
7951a5f2fd88f726385cff5ef5d8c57fff04757d
895
py
Python
servers/web/django/server/urls.py
ericharmeling/photoblocks
b5c61e4d5b459336145647c877daa5d27a8440e6
[ "MIT" ]
2
2018-06-21T13:57:09.000Z
2018-07-11T01:38:07.000Z
servers/web/django/server/urls.py
ericharmeling/photoblocks
b5c61e4d5b459336145647c877daa5d27a8440e6
[ "MIT" ]
null
null
null
servers/web/django/server/urls.py
ericharmeling/photoblocks
b5c61e4d5b459336145647c877daa5d27a8440e6
[ "MIT" ]
1
2018-11-21T21:13:03.000Z
2018-11-21T21:13:03.000Z
"""rest URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.conf.urls import url from .views import NodesView urlpatterns = [ url('admin/', admin.site.urls), url('node/', NodesView.as_view(), name='nodes'), url('node/<int:id>/', NodesView.as_view(), name='nodes') ]
31.964286
77
0.696089
7951a6488542efa0bd4c0afe383448663e93ffe9
4,382
py
Python
tests/test_scripts/output/genpython/inheritedid_ncvs.py
smartniz/linkml
5edc319c7f63378b024d89f5dd8f34b68b41cf11
[ "CC0-1.0" ]
null
null
null
tests/test_scripts/output/genpython/inheritedid_ncvs.py
smartniz/linkml
5edc319c7f63378b024d89f5dd8f34b68b41cf11
[ "CC0-1.0" ]
null
null
null
tests/test_scripts/output/genpython/inheritedid_ncvs.py
smartniz/linkml
5edc319c7f63378b024d89f5dd8f34b68b41cf11
[ "CC0-1.0" ]
null
null
null
# Auto generated from inheritedid.yaml by pythongen.py version: 0.9.0 # Generation date: 2022-02-01T06:40:25 # Schema: test_inherited_id # # id: https://example.org/inheritedid # description: Test # license: https://creativecommons.org/publicdomain/zero/1.0/ import dataclasses import sys import re from jsonasobj2 import JsonObj, as_dict from typing import Optional, List, Union, Dict, ClassVar, Any from dataclasses import dataclass from linkml_runtime.linkml_model.meta import EnumDefinition, PermissibleValue, PvFormulaOptions from linkml_runtime.utils.slot import Slot from linkml_runtime.utils.metamodelcore import empty_list, empty_dict, bnode from linkml_runtime.utils.yamlutils import YAMLRoot, extended_str, extended_float, extended_int from linkml_runtime.utils.dataclass_extensions_376 import dataclasses_init_fn_with_kwargs from linkml_runtime.utils.formatutils import camelcase, underscore, sfx from linkml_runtime.utils.enumerations import EnumDefinitionImpl from rdflib import Namespace, URIRef from linkml_runtime.utils.curienamespace import CurieNamespace from linkml_runtime.utils.metamodelcore import URI metamodel_version = "1.7.0" version = None # Overwrite dataclasses _init_fn to add **kwargs in __init__ dataclasses._init_fn = dataclasses_init_fn_with_kwargs # Namespaces LINKML = CurieNamespace('linkml', 'https://w3id.org/linkml/') XSD = CurieNamespace('xsd', 'http://www.w3.org/2001/XMLSchema#') DEFAULT_ = LINKML # Types class String(str): type_class_uri = XSD.string type_class_curie = "xsd:string" type_name = "string" type_model_uri = LINKML.String class Uri(URI): """ a complete URI """ type_class_uri = XSD.anyURI type_class_curie = "xsd:anyURI" type_name = "uri" type_model_uri = LINKML.Uri class IdentifierType(String): """ A string that is intended to uniquely identify a thing May be URI in full or compact (CURIE) form """ type_class_uri = XSD.string type_class_curie = "xsd:string" type_name = "identifier type" type_model_uri = LINKML.IdentifierType class LabelType(String): """ A string that provides a human-readable name for a thing """ type_class_uri = XSD.string type_class_curie = "xsd:string" type_name = "label type" type_model_uri = LINKML.LabelType # Class references class NamedThingId(IdentifierType): pass class AttributeId(IdentifierType): pass class BiologicalSexId(AttributeId): pass class OntologyClassId(NamedThingId): pass @dataclass class NamedThing(YAMLRoot): """ a databased entity or concept/class """ id: Union[str, NamedThingId] = None name: Optional[Union[str, LabelType]] = None def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): if self._is_empty(self.id): self.MissingRequiredField("id") if not isinstance(self.id, NamedThingId): self.id = NamedThingId(self.id) if self.name is not None and not isinstance(self.name, LabelType): self.name = LabelType(self.name) super().__post_init__(**kwargs) @dataclass class Attribute(YAMLRoot): """ A property or characteristic of an entity """ id: Union[str, AttributeId] = None def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): if self._is_empty(self.id): self.MissingRequiredField("id") if not isinstance(self.id, AttributeId): self.id = AttributeId(self.id) super().__post_init__(**kwargs) @dataclass class BiologicalSex(Attribute): id: Union[str, BiologicalSexId] = None def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): if self._is_empty(self.id): self.MissingRequiredField("id") if not isinstance(self.id, BiologicalSexId): self.id = BiologicalSexId(self.id) super().__post_init__(**kwargs) @dataclass class OntologyClass(NamedThing): """ a concept or class in an ontology, vocabulary or thesaurus """ id: Union[str, OntologyClassId] = None def __post_init__(self, *_: List[str], **kwargs: Dict[str, Any]): if self._is_empty(self.id): self.MissingRequiredField("id") if not isinstance(self.id, OntologyClassId): self.id = OntologyClassId(self.id) super().__post_init__(**kwargs) # Enumerations # Slots
27.734177
109
0.711775
7951a67a81a74d155619ca9f83823ee4165c34b0
2,835
py
Python
test/HDFSHandlerTest.py
cedricg92/event-manager
d07fafe88dca06a4d1a07e2a368122b0fb18ccfd
[ "Apache-2.0" ]
null
null
null
test/HDFSHandlerTest.py
cedricg92/event-manager
d07fafe88dca06a4d1a07e2a368122b0fb18ccfd
[ "Apache-2.0" ]
null
null
null
test/HDFSHandlerTest.py
cedricg92/event-manager
d07fafe88dca06a4d1a07e2a368122b0fb18ccfd
[ "Apache-2.0" ]
null
null
null
import os import shutil from ptest.assertion import assert_true from ptest.decorator import TestClass, BeforeMethod, Test, AfterMethod from watchdog.events import FileCreatedEvent from shirp.event import EventConf from shirp.handler import HDFSHandler HDFS_GROUP = "grp-hdfs" @TestClass(run_mode="singleline") class HDFSHandlerTest: def __init__(self, hdfs_put_handler=None, hdfs_get_handler=None, put_event_conf=None, get_event_conf=None): """ :param hdfs_put_handler: :type hdfs_put_handler: HDFSHandler :param hdfs_get_handler: :type hdfs_get_handler: HDFSHandler :param put_event_conf: :type put_event_conf: EventConf :param get_event_conf: :type get_event_conf: EventConf """ self.hdfs_put_handler = hdfs_put_handler self.hdfs_get_handler = hdfs_get_handler self.put_event_conf = put_event_conf self.get_event_conf = get_event_conf self.current_dir = os.path.dirname(os.path.realpath(__file__)) self.result = False @BeforeMethod(group=HDFS_GROUP) def before_hdfs_test(self): self.put_event_conf = EventConf(True, "test move", "hdfs", HDFSHandler.TYPE_PUT, "D:\\Users\\Cedric\\PycharmProjects\\event-manager\\rep_test\\in", ["test_????.txt"], "/user/hduser", {"hdfsUrl": "http://192.168.1.24:50070", "hdfsUser": "hduser"}) self.get_event_conf = EventConf(True, "test move", "hdfs", HDFSHandler.TYPE_GET, "/user/hduser", ["test_????.txt"], "D:\\Users\\Cedric\\PycharmProjects\\event-manager\\rep_test\\out", {"hdfsUrl": "http://192.168.1.24:50070", "hdfsUser": "hduser"}) HDFSHandler.FILE_LOG = self.current_dir + os.path.sep + "events.log" self.hdfs_put_handler = HDFSHandler(self.put_event_conf, self.put_event_conf.subtype) self.hdfs_get_handler = HDFSHandler(self.get_event_conf, self.get_event_conf.subtype) @Test(group=HDFS_GROUP) def move_test(self): shutil.copy("D:\\Users\\Cedric\\PycharmProjects\\event-manager\\rep_test\\test_2208.txt", self.put_event_conf.directory) event = FileCreatedEvent(self.put_event_conf.directory + os.path.sep + "test_2208.txt") assert_true(self.hdfs_put_handler.on_created(event)) assert_true(self.hdfs_get_handler.process("/user/hduser/test_2208.txt")) assert_true(os.path.exists(self.get_event_conf.destination + os.path.sep + "test_2208.txt")) @AfterMethod(group=HDFS_GROUP) def after_hdfs_test(self): os.remove(self.get_event_conf.destination + os.path.sep + "test_2208.txt")
46.47541
111
0.649383
7951a69dbdb6179b869fd219bad4bf214a94f1a6
21,724
py
Python
mmdet/models/backbones/pvt.py
hyperlist/mmdetection
ba4918de7fb21a96edc373584fa21a17d098a843
[ "Apache-2.0" ]
null
null
null
mmdet/models/backbones/pvt.py
hyperlist/mmdetection
ba4918de7fb21a96edc373584fa21a17d098a843
[ "Apache-2.0" ]
null
null
null
mmdet/models/backbones/pvt.py
hyperlist/mmdetection
ba4918de7fb21a96edc373584fa21a17d098a843
[ "Apache-2.0" ]
null
null
null
import math import warnings import numpy as np import paddle import paddle.nn as nn from mmcv.cnn import (Conv2d, build_activation_layer, build_norm_layer, constant_init, normal_init, trunc_normal_init) from mmcv.cnn.bricks.drop import build_dropout from mmcv.cnn.bricks.transformer import MultiheadAttention from mmcv.runner import (BaseModule, ModuleList, Sequential, _load_checkpoint, load_state_dict) from torch.nn.modules.utils import _pair as to_2tuple from ...utils import get_root_logger from ..builder import BACKBONES from ..utils import PatchEmbed, nchw_to_nlc, nlc_to_nchw, pvt_convert class MixFFN(BaseModule): """An implementation of MixFFN of PVT. The differences between MixFFN & FFN: 1. Use 1X1 Conv to replace Linear layer. 2. Introduce 3X3 Depth-wise Conv to encode positional information. Args: embed_dims (int): The feature dimension. Same as `MultiheadAttention`. feedforward_channels (int): The hidden dimension of FFNs. act_cfg (dict, optional): The activation config for FFNs. Default: dict(type='GELU'). ffn_drop (float, optional): Probability of an element to be zeroed in FFN. Default 0.0. dropout_layer (obj:`ConfigDict`): The dropout_layer used when adding the shortcut. Default: None. use_conv (bool): If True, add 3x3 DWConv between two Linear layers. Defaults: False. init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization. Default: None. """ def __init__(self, embed_dims, feedforward_channels, act_cfg=dict(type='GELU'), ffn_drop=0., dropout_layer=None, use_conv=False, init_cfg=None): super(MixFFN, self).__init__(init_cfg=init_cfg) self.embed_dims = embed_dims self.feedforward_channels = feedforward_channels self.act_cfg = act_cfg activate = build_activation_layer(act_cfg) in_channels = embed_dims fc1 = Conv2d( in_channels=in_channels, out_channels=feedforward_channels, kernel_size=1, stride=1, bias=True) if use_conv: # 3x3 depth wise conv to provide positional encode information dw_conv = Conv2d( in_channels=feedforward_channels, out_channels=feedforward_channels, kernel_size=3, stride=1, padding=(3 - 1) // 2, bias=True, groups=feedforward_channels) fc2 = Conv2d( in_channels=feedforward_channels, out_channels=in_channels, kernel_size=1, stride=1, bias=True) drop = nn.Dropout(ffn_drop) layers = [fc1, activate, drop, fc2, drop] if use_conv: layers.insert(1, dw_conv) self.layers = Sequential(*layers) self.dropout_layer = build_dropout( dropout_layer) if dropout_layer else torch.nn.Identity() def forward(self, x, hw_shape, identity=None): out = nlc_to_nchw(x, hw_shape) out = self.layers(out) out = nchw_to_nlc(out) if identity is None: identity = x return identity + self.dropout_layer(out) class SpatialReductionAttention(MultiheadAttention): """An implementation of Spatial Reduction Attention of PVT. This module is modified from MultiheadAttention which is a module from mmcv.cnn.bricks.transformer. Args: embed_dims (int): The embedding dimension. num_heads (int): Parallel attention heads. attn_drop (float): A Dropout layer on attn_output_weights. Default: 0.0. proj_drop (float): A Dropout layer after `nn.MultiheadAttention`. Default: 0.0. dropout_layer (obj:`ConfigDict`): The dropout_layer used when adding the shortcut. Default: None. batch_first (bool): Key, Query and Value are shape of (batch, n, embed_dim) or (n, batch, embed_dim). Default: False. qkv_bias (bool): enable bias for qkv if True. Default: True. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='LN'). sr_ratio (int): The ratio of spatial reduction of Spatial Reduction Attention of PVT. Default: 1. init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization. Default: None. """ def __init__(self, embed_dims, num_heads, attn_drop=0., proj_drop=0., dropout_layer=None, batch_first=True, qkv_bias=True, norm_cfg=dict(type='LN'), sr_ratio=1, init_cfg=None): super().__init__( embed_dims, num_heads, attn_drop, proj_drop, batch_first=batch_first, dropout_layer=dropout_layer, bias=qkv_bias, init_cfg=init_cfg) self.sr_ratio = sr_ratio if sr_ratio > 1: self.sr = Conv2d( in_channels=embed_dims, out_channels=embed_dims, kernel_size=sr_ratio, stride=sr_ratio) # The ret[0] of build_norm_layer is norm name. self.norm = build_norm_layer(norm_cfg, embed_dims)[1] def forward(self, x, hw_shape, identity=None): x_q = x if self.sr_ratio > 1: x_kv = nlc_to_nchw(x, hw_shape) x_kv = self.sr(x_kv) x_kv = nchw_to_nlc(x_kv) x_kv = self.norm(x_kv) else: x_kv = x if identity is None: identity = x_q out = self.attn(query=x_q, key=x_kv, value=x_kv)[0] return identity + self.dropout_layer(self.proj_drop(out)) class PVTEncoderLayer(BaseModule): """Implements one encoder layer in PVT. Args: embed_dims (int): The feature dimension. num_heads (int): Parallel attention heads. feedforward_channels (int): The hidden dimension for FFNs. drop_rate (float): Probability of an element to be zeroed. after the feed forward layer. Default: 0.0. attn_drop_rate (float): The drop out rate for attention layer. Default: 0.0. drop_path_rate (float): stochastic depth rate. Default: 0.0. qkv_bias (bool): enable bias for qkv if True. Default: True. act_cfg (dict): The activation config for FFNs. Default: dict(type='GELU'). norm_cfg (dict): Config dict for normalization layer. Default: dict(type='LN'). sr_ratio (int): The ratio of spatial reduction of Spatial Reduction Attention of PVT. Default: 1. use_conv_ffn (bool): If True, use Convolutional FFN to replace FFN. Default: False. init_cfg (dict, optional): Initialization config dict. Default: None. """ def __init__(self, embed_dims, num_heads, feedforward_channels, drop_rate=0., attn_drop_rate=0., drop_path_rate=0., qkv_bias=True, act_cfg=dict(type='GELU'), norm_cfg=dict(type='LN'), sr_ratio=1, use_conv_ffn=False, init_cfg=None): super(PVTEncoderLayer, self).__init__(init_cfg=init_cfg) # The ret[0] of build_norm_layer is norm name. self.norm1 = build_norm_layer(norm_cfg, embed_dims)[1] self.attn = SpatialReductionAttention( embed_dims=embed_dims, num_heads=num_heads, attn_drop=attn_drop_rate, proj_drop=drop_rate, dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), qkv_bias=qkv_bias, norm_cfg=norm_cfg, sr_ratio=sr_ratio) # The ret[0] of build_norm_layer is norm name. self.norm2 = build_norm_layer(norm_cfg, embed_dims)[1] self.ffn = MixFFN( embed_dims=embed_dims, feedforward_channels=feedforward_channels, ffn_drop=drop_rate, dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate), use_conv=use_conv_ffn, act_cfg=act_cfg) def forward(self, x, hw_shape): x = self.attn(self.norm1(x), hw_shape, identity=x) x = self.ffn(self.norm2(x), hw_shape, identity=x) return x class AbsolutePositionEmbedding(BaseModule): """An implementation of the absolute position embedding in PVT. Args: pos_shape (int): The shape of the absolute position embedding. pos_dim (int): The dimension of the absolute position embedding. drop_rate (float): Probability of an element to be zeroed. Default: 0.0. """ def __init__(self, pos_shape, pos_dim, drop_rate=0., init_cfg=None): super().__init__(init_cfg=init_cfg) if isinstance(pos_shape, int): pos_shape = to_2tuple(pos_shape) elif isinstance(pos_shape, tuple): if len(pos_shape) == 1: pos_shape = to_2tuple(pos_shape[0]) assert len(pos_shape) == 2, \ f'The size of image should have length 1 or 2, ' \ f'but got {len(pos_shape)}' self.pos_shape = pos_shape self.pos_dim = pos_dim self.pos_embed = paddle.create_parameter( paddle.zeros(1, pos_shape[0] * pos_shape[1], pos_dim)) self.drop = nn.Dropout(p=drop_rate) def init_weights(self): trunc_normal_init(self.pos_embed, std=0.02) def resize_pos_embed(self, pos_embed, input_shape, mode='bilinear'): """Resize pos_embed weights. Resize pos_embed using bilinear interpolate method. Args: pos_embed (torch.Tensor): Position embedding weights. input_shape (tuple): Tuple for (downsampled input image height, downsampled input image width). mode (str): Algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` | ``'trilinear'``. Default: ``'bilinear'``. Return: torch.Tensor: The resized pos_embed of shape [B, L_new, C]. """ assert pos_embed.ndim == 3, 'shape of pos_embed must be [B, L, C]' pos_h, pos_w = self.pos_shape pos_embed_weight = pos_embed[:, (-1 * pos_h * pos_w):] pos_embed_weight = pos_embed_weight.reshape( 1, pos_h, pos_w, self.pos_dim).permute(0, 3, 1, 2).contiguous() pos_embed_weight = F.interpolate( pos_embed_weight, size=input_shape, mode=mode) pos_embed_weight = torch.flatten(pos_embed_weight, 2).transpose(1, 2).contiguous() pos_embed = pos_embed_weight return pos_embed def forward(self, x, hw_shape, mode='bilinear'): pos_embed = self.resize_pos_embed(self.pos_embed, hw_shape, mode) return self.drop(x + pos_embed) @BACKBONES.register_module() class PyramidVisionTransformer(BaseModule): """Pyramid Vision Transformer (PVT) Implementation of `Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions <https://arxiv.org/pdf/2102.12122.pdf>`_. Args: pretrain_img_size (int | tuple[int]): The size of input image when pretrain. Defaults: 224. in_channels (int): Number of input channels. Default: 3. embed_dims (int): Embedding dimension. Default: 64. num_stags (int): The num of stages. Default: 4. num_layers (Sequence[int]): The layer number of each transformer encode layer. Default: [3, 4, 6, 3]. num_heads (Sequence[int]): The attention heads of each transformer encode layer. Default: [1, 2, 5, 8]. patch_sizes (Sequence[int]): The patch_size of each patch embedding. Default: [4, 2, 2, 2]. strides (Sequence[int]): The stride of each patch embedding. Default: [4, 2, 2, 2]. paddings (Sequence[int]): The padding of each patch embedding. Default: [0, 0, 0, 0]. sr_ratios (Sequence[int]): The spatial reduction rate of each transformer encode layer. Default: [8, 4, 2, 1]. out_indices (Sequence[int] | int): Output from which stages. Default: (0, 1, 2, 3). mlp_ratios (Sequence[int]): The ratio of the mlp hidden dim to the embedding dim of each transformer encode layer. Default: [8, 8, 4, 4]. qkv_bias (bool): Enable bias for qkv if True. Default: True. drop_rate (float): Probability of an element to be zeroed. Default 0.0. attn_drop_rate (float): The drop out rate for attention layer. Default 0.0. drop_path_rate (float): stochastic depth rate. Default 0.1. use_abs_pos_embed (bool): If True, add absolute position embedding to the patch embedding. Defaults: True. use_conv_ffn (bool): If True, use Convolutional FFN to replace FFN. Default: False. act_cfg (dict): The activation config for FFNs. Default: dict(type='GELU'). norm_cfg (dict): Config dict for normalization layer. Default: dict(type='LN'). pretrained (str, optional): model pretrained path. Default: None. convert_weights (bool): The flag indicates whether the pre-trained model is from the original repo. We may need to convert some keys to make it compatible. Default: True. init_cfg (dict or list[dict], optional): Initialization config dict. Default: None. """ def __init__(self, pretrain_img_size=224, in_channels=3, embed_dims=64, num_stages=4, num_layers=[3, 4, 6, 3], num_heads=[1, 2, 5, 8], patch_sizes=[4, 2, 2, 2], strides=[4, 2, 2, 2], paddings=[0, 0, 0, 0], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratios=[8, 8, 4, 4], qkv_bias=True, drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1, use_abs_pos_embed=True, norm_after_stage=False, use_conv_ffn=False, act_cfg=dict(type='GELU'), norm_cfg=dict(type='LN', eps=1e-6), pretrained=None, convert_weights=True, init_cfg=None): super().__init__(init_cfg=init_cfg) self.convert_weights = convert_weights if isinstance(pretrain_img_size, int): pretrain_img_size = to_2tuple(pretrain_img_size) elif isinstance(pretrain_img_size, tuple): if len(pretrain_img_size) == 1: pretrain_img_size = to_2tuple(pretrain_img_size[0]) assert len(pretrain_img_size) == 2, \ f'The size of image should have length 1 or 2, ' \ f'but got {len(pretrain_img_size)}' assert not (init_cfg and pretrained), \ 'init_cfg and pretrained cannot be setting at the same time' if isinstance(pretrained, str): warnings.warn('DeprecationWarning: pretrained is deprecated, ' 'please use "init_cfg" instead') self.init_cfg = dict(type='Pretrained', checkpoint=pretrained) elif pretrained is None: self.init_cfg = init_cfg else: raise TypeError('pretrained must be a str or None') self.embed_dims = embed_dims self.num_stages = num_stages self.num_layers = num_layers self.num_heads = num_heads self.patch_sizes = patch_sizes self.strides = strides self.sr_ratios = sr_ratios assert num_stages == len(num_layers) == len(num_heads) \ == len(patch_sizes) == len(strides) == len(sr_ratios) self.out_indices = out_indices assert max(out_indices) < self.num_stages self.pretrained = pretrained # transformer encoder dpr = [ x.item() for x in torch.linspace(0, drop_path_rate, sum(num_layers)) ] # stochastic num_layer decay rule cur = 0 self.layers = ModuleList() for i, num_layer in enumerate(num_layers): embed_dims_i = embed_dims * num_heads[i] patch_embed = PatchEmbed( in_channels=in_channels, embed_dims=embed_dims_i, kernel_size=patch_sizes[i], stride=strides[i], padding=paddings[i], bias=True, norm_cfg=norm_cfg) layers = ModuleList() if use_abs_pos_embed: pos_shape = pretrain_img_size // np.prod(patch_sizes[:i + 1]) pos_embed = AbsolutePositionEmbedding( pos_shape=pos_shape, pos_dim=embed_dims_i, drop_rate=drop_rate) layers.append(pos_embed) layers.extend([ PVTEncoderLayer( embed_dims=embed_dims_i, num_heads=num_heads[i], feedforward_channels=mlp_ratios[i] * embed_dims_i, drop_rate=drop_rate, attn_drop_rate=attn_drop_rate, drop_path_rate=dpr[cur + idx], qkv_bias=qkv_bias, act_cfg=act_cfg, norm_cfg=norm_cfg, sr_ratio=sr_ratios[i], use_conv_ffn=use_conv_ffn) for idx in range(num_layer) ]) in_channels = embed_dims_i # The ret[0] of build_norm_layer is norm name. if norm_after_stage: norm = build_norm_layer(norm_cfg, embed_dims_i)[1] else: norm = nn.Identity() self.layers.append(ModuleList([patch_embed, layers, norm])) cur += num_layer def init_weights(self): logger = get_root_logger() if self.init_cfg is None: logger.warn(f'No pre-trained weights for ' f'{self.__class__.__name__}, ' f'training start from scratch') for m in self.modules(): if isinstance(m, nn.Linear): trunc_normal_init(m.weight, std=.02) if m.bias is not None: constant_init(m.bias, 0) elif isinstance(m, nn.LayerNorm): constant_init(m.bias, 0) constant_init(m.weight, 1.0) elif isinstance(m, nn.Conv2D): fan_out = m.kernel_size[0] * m.kernel_size[ 1] * m.out_channels fan_out //= m.groups normal_init(m.weight, 0, math.sqrt(2.0 / fan_out)) if m.bias is not None: constant_init(m.bias, 0) elif isinstance(m, AbsolutePositionEmbedding): m.init_weights() else: assert 'checkpoint' in self.init_cfg, f'Only support ' \ f'specify `Pretrained` in ' \ f'`init_cfg` in ' \ f'{self.__class__.__name__} ' checkpoint = _load_checkpoint( self.init_cfg.checkpoint, logger=logger, map_location='cpu') logger.warn(f'Load pre-trained model for ' f'{self.__class__.__name__} from original repo') if 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] elif 'model' in checkpoint: state_dict = checkpoint['model'] else: state_dict = checkpoint if self.convert_weights: # Because pvt backbones are not supported by mmcls, # so we need to convert pre-trained weights to match this # implementation. state_dict = pvt_convert(state_dict) load_state_dict(self, state_dict, strict=False, logger=logger) def forward(self, x): outs = [] for i, layer in enumerate(self.layers): x, hw_shape = layer[0](x) for block in layer[1]: x = block(x, hw_shape) x = layer[2](x) x = nlc_to_nchw(x, hw_shape) if i in self.out_indices: outs.append(x) return outs @BACKBONES.register_module() class PyramidVisionTransformerV2(PyramidVisionTransformer): """Implementation of `PVTv2: Improved Baselines with Pyramid Vision Transformer <https://arxiv.org/pdf/2106.13797.pdf>`_.""" def __init__(self, **kwargs): super(PyramidVisionTransformerV2, self).__init__( patch_sizes=[7, 3, 3, 3], paddings=[3, 1, 1, 1], use_abs_pos_embed=False, norm_after_stage=True, use_conv_ffn=True, **kwargs)
39.142342
79
0.571718
7951a76b626800c4ae979f851e61de955fb2401c
24,491
py
Python
azure-mgmt-network/azure/mgmt/network/v2018_12_01/operations/public_ip_prefixes_operations.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
1
2021-09-07T18:36:04.000Z
2021-09-07T18:36:04.000Z
azure-mgmt-network/azure/mgmt/network/v2018_12_01/operations/public_ip_prefixes_operations.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
2
2019-10-02T23:37:38.000Z
2020-10-02T01:17:31.000Z
azure-mgmt-network/azure/mgmt/network/v2018_12_01/operations/public_ip_prefixes_operations.py
JonathanGailliez/azure-sdk-for-python
f0f051bfd27f8ea512aea6fc0c3212ee9ee0029b
[ "MIT" ]
null
null
null
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from msrest.polling import LROPoller, NoPolling from msrestazure.polling.arm_polling import ARMPolling from .. import models class PublicIPPrefixesOperations(object): """PublicIPPrefixesOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. :ivar api_version: Client API version. Constant value: "2018-12-01". """ models = models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2018-12-01" self.config = config def _delete_initial( self, resource_group_name, public_ip_prefix_name, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.delete.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.delete(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 202, 204]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response def delete( self, resource_group_name, public_ip_prefix_name, custom_headers=None, raw=False, polling=True, **operation_config): """Deletes the specified public IP prefix. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the PublicIpPrefix. :type public_ip_prefix_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns None or ClientRawResponse<None> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._delete_initial( resource_group_name=resource_group_name, public_ip_prefix_name=public_ip_prefix_name, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} def get( self, resource_group_name, public_ip_prefix_name, expand=None, custom_headers=None, raw=False, **operation_config): """Gets the specified public IP prefix in a specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param expand: Expands referenced resources. :type expand: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: PublicIPPrefix or ClientRawResponse if raw=true :rtype: ~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ # Construct URL url = self.get.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('PublicIPPrefix', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} def _create_or_update_initial( self, resource_group_name, public_ip_prefix_name, parameters, custom_headers=None, raw=False, **operation_config): # Construct URL url = self.create_or_update.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'PublicIPPrefix') # Construct and send request request = self._client.put(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200, 201]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('PublicIPPrefix', response) if response.status_code == 201: deserialized = self._deserialize('PublicIPPrefix', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def create_or_update( self, resource_group_name, public_ip_prefix_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Creates or updates a static or dynamic public IP prefix. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param parameters: Parameters supplied to the create or update public IP prefix operation. :type parameters: ~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns PublicIPPrefix or ClientRawResponse<PublicIPPrefix> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, public_ip_prefix_name=public_ip_prefix_name, parameters=parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('PublicIPPrefix', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} def _update_tags_initial( self, resource_group_name, public_ip_prefix_name, tags=None, custom_headers=None, raw=False, **operation_config): parameters = models.TagsObject(tags=tags) # Construct URL url = self.update_tags.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'publicIpPrefixName': self._serialize.url("public_ip_prefix_name", public_ip_prefix_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'TagsObject') # Construct and send request request = self._client.patch(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('PublicIPPrefix', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized def update_tags( self, resource_group_name, public_ip_prefix_name, tags=None, custom_headers=None, raw=False, polling=True, **operation_config): """Updates public IP prefix tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param public_ip_prefix_name: The name of the public IP prefix. :type public_ip_prefix_name: str :param tags: Resource tags. :type tags: dict[str, str] :param dict custom_headers: headers that will be added to the request :param bool raw: The poller return type is ClientRawResponse, the direct response alongside the deserialized response :param polling: True for ARMPolling, False for no polling, or a polling object for personal polling strategy :return: An instance of LROPoller that returns PublicIPPrefix or ClientRawResponse<PublicIPPrefix> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._update_tags_initial( resource_group_name=resource_group_name, public_ip_prefix_name=public_ip_prefix_name, tags=tags, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('PublicIPPrefix', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method) update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIpPrefixName}'} def list_all( self, custom_headers=None, raw=False, **operation_config): """Gets all the public IP prefixes in a subscription. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of PublicIPPrefix :rtype: ~azure.mgmt.network.v2018_12_01.models.PublicIPPrefixPaged[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list_all.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.PublicIPPrefixPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.PublicIPPrefixPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPPrefixes'} def list( self, resource_group_name, custom_headers=None, raw=False, **operation_config): """Gets all public IP prefixes in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: An iterator like instance of PublicIPPrefix :rtype: ~azure.mgmt.network.v2018_12_01.models.PublicIPPrefixPaged[~azure.mgmt.network.v2018_12_01.models.PublicIPPrefix] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp return response # Deserialize response deserialized = models.PublicIPPrefixPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.PublicIPPrefixPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes'}
46.827916
175
0.671757
7951a7941dd6bc9bef1b322015def6a9a9e06453
328
py
Python
app/pit/forms.py
edynox/iis
594200506b641cbac249dc6e95d229bea1edeb28
[ "MIT" ]
null
null
null
app/pit/forms.py
edynox/iis
594200506b641cbac249dc6e95d229bea1edeb28
[ "MIT" ]
null
null
null
app/pit/forms.py
edynox/iis
594200506b641cbac249dc6e95d229bea1edeb28
[ "MIT" ]
null
null
null
from django.forms import ModelForm from ..models import Pit class PitForm(ModelForm): class Meta: model = Pit fields = ['location'] def __init__(self, *args, **kwargs): super(ModelForm, self).__init__(*args, **kwargs) self.fields['location'].widget.attrs['class'] = 'form-control'
25.230769
70
0.631098
7951a7a45fd9bb5bd8c29191cc256e8623d60442
237
py
Python
modules/dbnd/src/dbnd/_core/utils/platform/windows_compatible/pwd.py
ipattarapong/dbnd
7bd65621c46c73e078eb628f994127ad4c7dbd1a
[ "Apache-2.0" ]
224
2020-01-02T10:46:37.000Z
2022-03-02T13:54:08.000Z
modules/dbnd/src/dbnd/_core/utils/platform/windows_compatible/pwd.py
ipattarapong/dbnd
7bd65621c46c73e078eb628f994127ad4c7dbd1a
[ "Apache-2.0" ]
16
2020-03-11T09:37:58.000Z
2022-01-26T10:22:08.000Z
modules/dbnd/src/dbnd/_core/utils/platform/windows_compatible/pwd.py
ipattarapong/dbnd
7bd65621c46c73e078eb628f994127ad4c7dbd1a
[ "Apache-2.0" ]
24
2020-03-24T13:53:50.000Z
2022-03-22T11:55:18.000Z
# patch windows module so python-daemon will work on windows # this is required for python-daemon<2.2 imported by airflow 1.10.1. # This issue is resolved in newer versions of python-daemon def getpwuid(*args, **kwargs): return -1
29.625
68
0.746835
7951a9a9c01a2ec528f5b03589b01025729721cb
17,899
py
Python
tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py
jdehotin/TensorFlow
a6c5f8e4e013e54fed8dfcf49fb6de365f018022
[ "Apache-2.0" ]
1
2021-06-10T23:59:44.000Z
2021-06-10T23:59:44.000Z
tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py
jdehotin/TensorFlow
a6c5f8e4e013e54fed8dfcf49fb6de365f018022
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py
jdehotin/TensorFlow
a6c5f8e4e013e54fed8dfcf49fb6de365f018022
[ "Apache-2.0" ]
1
2021-12-16T05:34:55.000Z
2021-12-16T05:34:55.000Z
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from scipy import stats import tensorflow as tf distributions = tf.contrib.distributions class QuantizedDistributionTest(tf.test.TestCase): def setUp(self): self._rng = np.random.RandomState(0) def _assert_all_finite(self, array): self.assertTrue(np.isfinite(array).all()) def test_quantization_of_uniform_with_cutoffs_having_no_effect(self): with self.test_session(): # The Quantized uniform with cutoffs == None divides the real line into: # R = ...(-1, 0](0, 1](1, 2](2, 3](3, 4]... # j = ... 0 1 2 3 4 ... # Since this uniform (below) is supported on [0, 3], # it places 1/3 of its mass in the intervals j = 1, 2, 3. # Adding a cutoff at y = 0 changes the picture to # R = ...(-inf, 0](0, 1](1, 2](2, 3](3, 4]... # j = ... 0 1 2 3 4 ... # So the QUniform still places 1/3 of its mass in the intervals # j = 1, 2, 3. # Adding a cutoff at y = 3 changes the picture to # R = ...(-1, 0](0, 1](1, 2](2, inf) # j = ... 0 1 2 3 # and the QUniform still places 1/3 of its mass in the intervals # j = 1, 2, 3. for lcut, ucut in [ (None, None), (0.0, None), (None, 3.0), (0.0, 3.0), (-10., 10.) ]: qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=lcut, upper_cutoff=ucut, a=0.0, b=3.0) # pmf # uniform had no mass below -1. self.assertAllClose(0., qdist.pmf(-1.).eval()) # uniform had no mass below 0. self.assertAllClose(0., qdist.pmf(0.).eval()) # uniform put 1/3 of its mass in each of (0, 1], (1, 2], (2, 3], # which are the intervals j = 1, 2, 3. self.assertAllClose(1 / 3, qdist.pmf(1.).eval()) self.assertAllClose(1 / 3, qdist.pmf(2.).eval()) self.assertAllClose(1 / 3, qdist.pmf(3.).eval()) # uniform had no mass in (3, 4] or (4, 5], which are j = 4, 5. self.assertAllClose(0 / 3, qdist.pmf(4.).eval()) self.assertAllClose(0 / 3, qdist.pmf(5.).eval()) # cdf self.assertAllClose(0., qdist.cdf(-1.).eval()) self.assertAllClose(0., qdist.cdf(0.).eval()) self.assertAllClose(1 / 3, qdist.cdf(1.).eval()) self.assertAllClose(2 / 3, qdist.cdf(2.).eval()) # Note fractional values allowed for cdfs of discrete distributions. # And adding 0.5 makes no difference because the quantized dist has # mass only on the integers, never in between. self.assertAllClose(2 / 3, qdist.cdf(2.5).eval()) self.assertAllClose(3 / 3, qdist.cdf(3.).eval()) self.assertAllClose(3 / 3, qdist.cdf(4.).eval()) self.assertAllClose(3 / 3, qdist.cdf(5.).eval()) def test_quantization_of_uniform_with_cutoffs_in_the_middle(self): with self.test_session(): # The uniform is supported on [-3, 3] # Consider partitions the real line in intervals # ...(-3, -2](-2, -1](-1, 0](0, 1](1, 2](2, 3] ... # Before cutoffs, the uniform puts a mass of 1/6 in each interval written # above. Because of cutoffs, the qdist considers intervals and indices # ...(-infty, -1](-1, 0](0, infty) ... # -1 0 1 qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=-1.0, upper_cutoff=1.0, a=-3.0, b=3.0) # pmf # Uniform had no mass on (-4, -3] or (-3, -2] self.assertAllClose(0., qdist.cdf(-3.).eval()) self.assertAllClose(0., qdist.cdf(-2.).eval()) # Uniform had 1/6 of its mass in each of (-3, -2], and (-2, -1], which # were collapsed into (-infty, -1], which is now the "-1" interval. self.assertAllClose(1 / 3, qdist.cdf(-1.).eval()) # The j=0 interval contained mass from (-3, 0], which is 1/2 of the # uniform's mass. self.assertAllClose(1 / 2, qdist.cdf(0.).eval()) # Adding 0.5 makes no difference because the quantized dist has mass on # the integers, not in between them. self.assertAllClose(1 / 2, qdist.cdf(0.5).eval()) # After applying the cutoff, all mass was either in the interval # (0, infty), or below. (0, infty) is the interval indexed by j=1, # so pmf(1) should equal 1. self.assertAllClose(1., qdist.cdf(1.0).eval()) # Since no mass of qdist is above 1, # pmf(10) = P[Y <= 10] = P[Y <= 1] = pmf(1). self.assertAllClose(1., qdist.cdf(10.0).eval()) def test_quantization_of_batch_of_uniforms(self): batch_shape = (5, 5) with self.test_session(): # The uniforms are supported on [0, 10]. The qdist considers the # intervals # ... (0, 1](1, 2]...(9, 10]... # with the intervals displayed above each holding 1 / 10 of the mass. # The qdist will be defined with no cutoffs, qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=None, upper_cutoff=None, a=tf.zeros( batch_shape, dtype=tf.float32), b=10 * tf.ones( batch_shape, dtype=tf.float32)) # x is random integers in {-3,...,12}. x = self._rng.randint(-3, 13, size=batch_shape).astype(np.float32) # pmf # qdist.pmf(j) = 1 / 10 for j in {1,...,10}, and 0 otherwise, expected_pmf = (1 / 10) * np.ones(batch_shape) expected_pmf[x < 1] = 0. expected_pmf[x > 10] = 0. self.assertAllClose(expected_pmf, qdist.pmf(x).eval()) # cdf # qdist.cdf(j) # = 0 for j < 1 # = j / 10, for j in {1,...,10}, # = 1, for j > 10. expected_cdf = x.copy() / 10 expected_cdf[x < 1] = 0. expected_cdf[x > 10] = 1. self.assertAllClose(expected_cdf, qdist.cdf(x).eval()) def test_sampling_from_batch_of_normals(self): batch_shape = (2,) with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=0., upper_cutoff=None, mu=tf.zeros( batch_shape, dtype=tf.float32), sigma=tf.ones( batch_shape, dtype=tf.float32)) samps = qdist.sample_n(n=5000, seed=42) samps_v = samps.eval() # With lower_cutoff = 0, the interval j=0 is (-infty, 0], which holds 1/2 # of the mass of the normals. # rtol chosen to be 2x as large as necessary to pass. self.assertAllClose([0.5, 0.5], (samps_v == 0).mean(axis=0), rtol=0.03) # The interval j=1 is (0, 1], which is from the mean to one standard # deviation out. This should contain 0.6827 / 2 of the mass. self.assertAllClose( [0.6827 / 2, 0.6827 / 2], (samps_v == 1).mean(axis=0), rtol=0.03) def test_samples_agree_with_cdf_for_samples_over_large_range(self): # Consider the cdf for distribution X, F(x). # If U ~ Uniform[0, 1], then Y := F^{-1}(U) is distributed like X since # P[Y <= y] = P[F^{-1}(U) <= y] = P[U <= F(y)] = F(y). # If F is a bijection, we also have Z = F(X) is Uniform. # # Make an exponential with large mean (= 100). This ensures we will get # quantized values over a large range. This large range allows us to # pretend that the cdf F is a bijection, and hence F(X) is uniform. # Note that F cannot be bijection since it is constant between the # integers. Hence, F(X) (see below) will not be uniform exactly. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Exponential, lam=0.01) # X ~ QuantizedExponential x = qdist.sample_n(n=10000, seed=42) # Z = F(X), should be Uniform. z = qdist.cdf(x) # Compare the CDF of Z to that of a Uniform. # dist = maximum distance between P[Z <= a] and P[U <= a]. # We ignore pvalue, since of course this distribution is not exactly, and # with so many sample points we would get a false fail. dist, _ = stats.kstest(z.eval(), "uniform") # Since the distribution take values (approximately) in [0, 100], the # cdf should have jumps (approximately) every 1/100 of the way up. # Assert that the jumps are not more than 2/100. self.assertLess(dist, 0.02) def test_samples_agree_with_pdf_for_samples_over_small_range(self): # Testing that samples and pdf agree for a small range is important because # it makes sure the bin edges are consistent. # Make an exponential with mean 5. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Exponential, lam=0.2) # Standard error should be less than 1 / (2 * sqrt(n_samples)) n_samples = 10000 std_err_bound = 1 / (2 * np.sqrt(n_samples)) samps = qdist.sample((n_samples,), seed=42).eval() # The smallest value the samples can take on is 1, which corresponds to # the interval (0, 1]. Recall we use ceiling in the sampling definition. self.assertLess(0.5, samps.min()) for x in range(1, 10): self.assertAllClose( qdist.pmf(float(x)).eval(), (samps == x).mean(), atol=std_err_bound) def test_normal_cdf_and_survival_function(self): # At integer values, the result should be the same as the standard normal. batch_shape = (3, 3) mu = self._rng.randn(*batch_shape) sigma = self._rng.rand(*batch_shape) + 1.0 with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) sp_normal = stats.norm(mu, sigma) x = self._rng.randint(-5, 5, size=batch_shape).astype(np.float64) self.assertAllClose( sp_normal.cdf(x), qdist.cdf(x).eval()) self.assertAllClose( sp_normal.sf(x), qdist.survival_function(x).eval()) def test_normal_log_cdf_and_log_survival_function(self): # At integer values, the result should be the same as the standard normal. batch_shape = (3, 3) mu = self._rng.randn(*batch_shape) sigma = self._rng.rand(*batch_shape) + 1.0 with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) sp_normal = stats.norm(mu, sigma) x = self._rng.randint(-10, 10, size=batch_shape).astype(np.float64) self.assertAllClose( sp_normal.logcdf(x), qdist.log_cdf(x).eval()) self.assertAllClose( sp_normal.logsf(x), qdist.log_survival_function(x).eval()) def test_normal_prob_with_cutoffs(self): # At integer values, the result should be the same as the standard normal. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=0., sigma=1., lower_cutoff=-2., upper_cutoff=2.) sm_normal = stats.norm(0., 1.) # These cutoffs create partitions of the real line, and indices: # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf) # -2 -1 0 1 2 # Test interval (-inf, -2], <--> index -2. self.assertAllClose( sm_normal.cdf(-2), qdist.prob(-2.).eval(), atol=0) # Test interval (-2, -1], <--> index -1. self.assertAllClose( sm_normal.cdf(-1) - sm_normal.cdf(-2), qdist.prob(-1.).eval(), atol=0) # Test interval (-1, 0], <--> index 0. self.assertAllClose( sm_normal.cdf(0) - sm_normal.cdf(-1), qdist.prob(0.).eval(), atol=0) # Test interval (1, inf), <--> index 2. self.assertAllClose( 1. - sm_normal.cdf(1), qdist.prob(2.).eval(), atol=0) def test_normal_log_prob_with_cutoffs(self): # At integer values, the result should be the same as the standard normal. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=0., sigma=1., lower_cutoff=-2., upper_cutoff=2.) sm_normal = stats.norm(0., 1.) # These cutoffs create partitions of the real line, and indices: # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf) # -2 -1 0 1 2 # Test interval (-inf, -2], <--> index -2. self.assertAllClose( np.log(sm_normal.cdf(-2)), qdist.log_prob(-2.).eval(), atol=0) # Test interval (-2, -1], <--> index -1. self.assertAllClose( np.log(sm_normal.cdf(-1) - sm_normal.cdf(-2)), qdist.log_prob(-1.).eval(), atol=0) # Test interval (-1, 0], <--> index 0. self.assertAllClose( np.log(sm_normal.cdf(0) - sm_normal.cdf(-1)), qdist.log_prob(0.).eval(), atol=0) # Test interval (1, inf), <--> index 2. self.assertAllClose( np.log(1. - sm_normal.cdf(1)), qdist.log_prob(2.).eval(), atol=0) def test_log_prob_and_grad_gives_finite_results(self): with self.test_session(): for dtype in [np.float32, np.float64]: mu = tf.Variable(0., name="mu", dtype=dtype) sigma = tf.Variable(1., name="sigma", dtype=dtype) qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = np.arange(-100, 100, 2).astype(dtype) tf.initialize_all_variables().run() proba = qdist.log_prob(x) grads = tf.gradients(proba, [mu, sigma]) self._assert_all_finite(proba.eval()) self._assert_all_finite(grads[0].eval()) self._assert_all_finite(grads[1].eval()) def test_prob_and_grad_gives_finite_results_for_common_events(self): with self.test_session(): mu = tf.Variable(0.0, name="mu") sigma = tf.Variable(1.0, name="sigma") qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = tf.ceil(4 * self._rng.rand(100).astype(np.float32) - 2) tf.initialize_all_variables().run() proba = qdist.prob(x) self._assert_all_finite(proba.eval()) grads = tf.gradients(proba, [mu, sigma]) self._assert_all_finite(grads[0].eval()) self._assert_all_finite(grads[1].eval()) def test_lower_cutoff_must_be_below_upper_cutoff_or_we_raise(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1., # not strictly less than upper_cutoff. upper_cutoff=1., mu=0., sigma=1., validate_args=True) self.assertTrue(qdist.validate_args) # Default is True. with self.assertRaisesOpError("must be strictly less"): qdist.sample().eval() def test_cutoffs_must_be_integer_valued_if_validate_args_true(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.5, upper_cutoff=10., mu=0., sigma=1., validate_args=True) self.assertTrue(qdist.validate_args) # Default is True. with self.assertRaisesOpError("has non-integer components"): qdist.sample().eval() def test_cutoffs_can_be_float_valued_if_validate_args_false(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.5, upper_cutoff=10.11, mu=0., sigma=1., validate_args=False) self.assertFalse(qdist.validate_args) # Default is True. # Should not raise qdist.sample().eval() def test_dtype_and_shape_inherited_from_base_dist(self): batch_shape = (2, 3) with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.0, upper_cutoff=10.0, mu=tf.zeros(batch_shape), sigma=tf.ones(batch_shape)) self.assertEqual(batch_shape, qdist.get_batch_shape()) self.assertAllEqual(batch_shape, qdist.batch_shape().eval()) self.assertEqual((), qdist.get_event_shape()) self.assertAllEqual((), qdist.event_shape().eval()) samps = qdist.sample_n(n=10) self.assertEqual((10,) + batch_shape, samps.get_shape()) self.assertAllEqual((10,) + batch_shape, samps.eval().shape) y = self._rng.randint(0, 5, size=batch_shape).astype(np.float32) self.assertEqual(batch_shape, qdist.prob(y).get_shape()) self.assertEqual(batch_shape, qdist.prob(y).eval().shape) if __name__ == "__main__": tf.test.main()
38.91087
80
0.605118
7951ab2d7a199c1f14743cedb1847f1b64fe00ca
1,056
py
Python
services/web/utils/errors.py
winnyboy5/Python_API_Boiler
0f153a77be6ffb56c3343c5405b2a4f52b681082
[ "MIT" ]
1
2020-12-21T15:20:05.000Z
2020-12-21T15:20:05.000Z
services/web/utils/errors.py
winnyboy5/Python_API_Boiler
0f153a77be6ffb56c3343c5405b2a4f52b681082
[ "MIT" ]
null
null
null
services/web/utils/errors.py
winnyboy5/Python_API_Boiler
0f153a77be6ffb56c3343c5405b2a4f52b681082
[ "MIT" ]
null
null
null
from flask import current_app, jsonify errors = { "InternalServerError": { "message": "Something went wrong", "status": 500 }, "SchemaValidationError": { "message": "Request is missing required fields", "status": 400 }, "EmailAlreadyExistsError": { "message": "User with given email address already exists", "status": 400 }, "UnauthorizedError": { "message": "Invalid username or password", "status": 401 }, "EmailDoesnotExistsError": { "message": "Couldn't find the user with given email address", "status": 400 }, "ExpiredTokenError": { "message": "Expired token", "status": 403 }, "BadTokenError": { "message": "Invalid token", "status": 403 } } def error_handle(e): print(current_app.config['DEBUG']) if(current_app.config['DEBUG']): raise e else: print(current_app.config['DEBUG']) raise e return jsonify(errors["InternalServerError"])
24.55814
69
0.573864
7951ab94f571d08b0be1fdc8953dfee553c65537
940
py
Python
acrylamid/views/index.py
farleykr/acrylamid
c6c0f60b594d2920f6387ba82b552093d7c5fe1b
[ "BSD-2-Clause-FreeBSD" ]
61
2015-01-15T23:23:11.000Z
2022-03-24T16:39:31.000Z
acrylamid/views/index.py
farleykr/acrylamid
c6c0f60b594d2920f6387ba82b552093d7c5fe1b
[ "BSD-2-Clause-FreeBSD" ]
28
2015-01-26T22:32:24.000Z
2022-01-13T01:11:56.000Z
acrylamid/views/index.py
farleykr/acrylamid
c6c0f60b594d2920f6387ba82b552093d7c5fe1b
[ "BSD-2-Clause-FreeBSD" ]
25
2015-01-22T19:26:29.000Z
2021-06-30T21:53:06.000Z
# -*- encoding: utf-8 -*- # # Copyright 2012 Martin Zimmermann <info@posativ.org>. All rights reserved. # License: BSD Style, 2 clauses -- see LICENSE. from acrylamid.views import View, Paginator class Index(View, Paginator): """Creates nicely paged listing of your posts. First page renders to ``route`` (defaults to */*) with a recent list of your (e.g. summarized) articles. Other pages enumerate to the variable ``pagination`` (*/page/:num/* per default). .. code-block:: python '/' : { 'view': 'index', 'template': 'main.html', 'pagination': '/page/:num/', 'items_per_page': 10 } """ export = ['prev', 'curr', 'next', 'items_per_page', 'entrylist'] template = 'main.html' def init(self, *args, **kwargs): View.init(self, *args, **kwargs) Paginator.init(self, *args, **kwargs) self.filters.append('relative')
30.322581
82
0.594681
7951abf8d29d16879cc0f408148f1092242511f7
10,661
py
Python
changastuff.py
trquinn/custom_python_packages
1d623a278832b58da28ff76ddea0ccd9a3c3ef15
[ "MIT" ]
null
null
null
changastuff.py
trquinn/custom_python_packages
1d623a278832b58da28ff76ddea0ccd9a3c3ef15
[ "MIT" ]
null
null
null
changastuff.py
trquinn/custom_python_packages
1d623a278832b58da28ff76ddea0ccd9a3c3ef15
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Contains various functions for submitting ChaNGa jobs to hyak. These are quite platform specific. Created on Wed Oct 29 13:30:56 2014 @author: ibackus """ import os import glob import re from subprocess import Popen, PIPE import pynbody import isaac import ICglobal_settings global_settings = ICglobal_settings.global_settings def PBS_script(workdir, param='snapshot.param', nodes=1, ppn=12, walltime=48, \ jobname='PBS_job', backfill=True, email=None, **kwargs): """ A not very robust function to generate PBS submission scripts for ChaNGa jobs on hyak. Some of the requirements include: mpi version of ChaNGa gcc_4.4.7-ompi_1.6.5 PBS (it's on hyak, don't worry) By default, any directory with 'lastcheckpoint' in it will be restarted! If you don't want to just restart a simulation, delete lastcheckpoint from the simulation directory! **ARGUMENTS** *Required* workdir : str Directory of the simulation *Optional* param : str Filename of the .param file (not full path) nodes : int Number of computation nodes to request ppn : int Number of cores per node walltime : float or int Walltime to request in hours jobname : str backfill : bool Boolean flag for whether to use the backfill (default is TRUE) email : str Email address for PBS to send updates to **kwargs flag pairs. CAREFUL: these must not conflict with other flags. Flag,val pairs (ie -flag val) are passed as: flag=val **RETURN** PBS_script : str A string for the PBS script. Can be saved easily to file """ # Setup filenames param_full = os.path.join(workdir, param) outfile = os.path.join(workdir, 'changa.out') fprefix = os.path.splitext(param)[0] # Get changa preset preset = global_settings['changa_presets']['mpi'] # Set up the walltime for PBS hours = int(walltime) mins = int((walltime*60)%60) secs = int((walltime*3600)%60) walltime_str = '{0:d}:{1:02d}:{2:02d}'.format(hours,mins,secs) # Write the script! # Start with the shebang script = '#!/bin/bash\n' # Some PBS flags script += '#PBS -N {0}\n\ #PBS -j oe\n\ #PBS -l nodes={1}:ppn={2},feature={2}core\n\ #PBS -l walltime={3}\n\ #PBS -V\n'.format(jobname, nodes, ppn, walltime_str) # Email stuff if email is not None: script += '#PBS -M {0}\n'.format(email) script += '#PBS -m be\n' # Choose whether to use the backfill if backfill: script += '#PBS -q bf\n' # Parse kwargs if kwargs is not None: for key, val in kwargs.iteritems(): script += '#PBS -{0} {1}\n'.format(key, val) # Runtime initialization script += 'module load gcc_4.4.7-ompi_1.6.5\n\ export MX_RCACHE=0\n\ workdir={0}\n\ cd $workdir\n\ changbin=$(which {1})\n'.format(workdir, preset[2]) # Now assume that we want to restart if there is a checkpoint script += 'if [ -e "lastcheckpoint" ]\n\ then\n\ echo "lastcheckpoint exists -- restarting simulation..."\n\ last=`cat lastcheckpoint`\n\ mpirun --mca mtl mx --mca pml cm $changbin +restart {0}.chk$last +balancer MultistepLB_notopo -wall {1} {2} >> {3} 2>&1\n'.format(fprefix,int(walltime*60), param_full, outfile) script += 'else\n\ echo "lastcheckpoint doesnt exist -- starting new simulation..."\n\ mpirun --mca mtl mx --mca pml cm $changbin -D 3 +consph +balancer MultistepLB_notopo -wall {0} {1} >& {2}\n\ fi\n'.format(int(walltime*60), param_full, outfile) return script def subber(directories, scriptname, scriptstr=None, subfile=None): """ Submits scriptname, contained in all the directories, to the submission queue using qsub. Optionally, the script can be provided as a string (or a list of strings for each simulation) in the variable scriptstr Optionally a bash script can be saved to subfile instead of submitting the scripts. This can be useful for batch submission when using a computation node. Note: the submission scripts will be made executable for all users **ARGUMENTS** directories : str, list, ndarray, tuple The directory or directories containing the submission script scriptname : str Script to submit. Should be present in all the directories scriptstr : str, list, or None Default = None (do nothing!) Either a string containing the PBS submission script (see PBS_script) or a list of such strings. These will be saved to directories/scriptname subfile : str or None (optional) If a string, filename for a bash script to be saved instead of executing the qsub commands """ # Make the directories list iterable if isinstance(directories, str): directories = [directories] # Make the submission scripts an iterable list if isinstance(scriptstr, str): scriptstr = [scriptstr] * len(directories) # Get current working directory cwd = os.getcwd() # Change directories to full paths fullpaths = [] for directory in directories: fullpaths.append(os.path.abspath(directory)) # Submission command command = 'qsub ' + scriptname if subfile is not None: bashscript = open(subfile, 'w') bashscript.write('#/bin/bash\n') # Submit all the scripts for i, fullpath in enumerate(fullpaths): os.chdir(fullpath) # If submission scripts have been provided as strings, write them out if scriptstr is not None: f = open(scriptname, 'w') f.write(scriptstr[i]) f.close() # Make them executable os.system('chmod a+x ' + scriptname) if subfile is not None: bashscript.write(command + '\n') else: # Submit the script to PBS p = Popen(command.split(), stderr=PIPE, stdout=PIPE) for line in iter(p.stdout.readline, ''): print line, p.wait() # Finalize if subfile is not None: bashscript.close() os.system('chmod a+x ' + subfile) os.chdir(cwd) def make_continue_sub(simdir='.', paramname='snapshot.param', \ newparam='continue.param', t=None, t_extra=None, oldsub='subber.sh', \ newsub='cont_subber.sh'): """ Makes a submission script for continuing a simulation from a previous output. Also makes a .param file for the continued simulation. The simulation will be continued in the same directory, with snapshot numbering scheme for outputs being the same. Parameters for the original simulation cannot be altered (except the number of steps you want to continue the simulation by). PBS runtime parameters also cannot be changed (number of nodes, walltime, etc...) Any checkpoints will be deleted. Requires a submission script be present for the original simulation NOTE: if nSteps, nSteps_extra are not set, the total number of steps to simulate is not changed. **ARGUMENTS** simdir : str The simulation directory paramname : str Filename of the .param file for the simulation newparam : str filename for the .param file for the continued simulation t : float or SimArray Total simulation time to run. If no units are specified, it is in simulation units t_extra : float or SimArray Extra simulation time to run If no units are specified, it is in simulation units OVERIDES t!!! oldsub : str Filename for the original submission script newsub : str Filename for the new submission script **RETURNS** sub_path : str Full path to the PBS submission script """ # Lazy man's way of dealing with files in another directory cwd = os.getcwd() os.chdir(simdir) # Load param file param = isaac.configparser(paramname, 'param') fprefix = param['achOutName'] # Find all the outputs. They should be of the format fprefix.000000 search_exp = '^' + fprefix + '.(?:(?<!\d)\d{6}(?!\d))$' flist = [] for fname in glob.glob(fprefix + '*'): if re.search(search_exp, fname) is not None: flist.append(fname) # Find the number of the last output (the last 6 chars should be an int) flist.sort() iStartStep = int(flist[-1][-6:]) param['iStartStep'] = iStartStep param['achInFile'] = flist[-1] dDelta = param['dDelta'] # Set the number of steps to run if t_extra is not None: # Convert to simulation units if needed if pynbody.units.has_units(t_extra): t_unit = isaac.units_from_param(param)['t_unit'] t_extra.convert_units(t_unit) # Assign output param['nSteps'] = iStartStep + int(round(t_extra/dDelta)) elif t is not None: # Convert to simulation units if needed if pynbody.units.has_units(t): t_unit = isaac.units_from_param(param)['t_unit'] t.convert_units(t_unit) # Assign output param['nSteps'] = int(round(t/dDelta)) # Save new param file isaac.configsave(param, newparam, ftype='param') # Delete old checkpoints for checkpoint in glob.glob(fprefix + '.chk*'): print 'removing ' + checkpoint os.system('rm -rf ' + checkpoint) if os.path.exists('lastcheckpoint'): print 'removing lastcheckpoint' os.remove('lastcheckpoint') # Create a submission script for the simulation continuation oldsubfile = open(oldsub, 'r') newsubfile = open(newsub, 'w') for line in oldsubfile: newsubfile.write(line.replace(paramname, newparam)) oldsubfile.close() newsubfile.close() # Make the submission script executable os.chmod(newsub, 0777) sub_path = os.path.abspath(newsub) # Change back to original working directory os.chdir(cwd) return sub_path
30.115819
180
0.611669