body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
def write(self, data):
'Send raw bytes to the instrument.\n\n :param data: bytes to be sent to the instrument\n :type data: bytes\n '
(begin, end, size) = (0, 0, len(data))
bytes_sent = 0
raw_write = super(USBTMC, self).write
while ((end == 0) or (end < size)):
(begin, end) = (end, (begin + self.RECV_CHUNK))
self._btag = ((self._btag % 255) + 1)
eom = (end >= size)
data = BulkOutMessage.build_array(self._btag, eom, data[begin:end])
bytes_sent += raw_write(data)
return size | -2,811,891,068,964,354,000 | Send raw bytes to the instrument.
:param data: bytes to be sent to the instrument
:type data: bytes | pyvisa-py/protocols/usbtmc.py | write | circuitfox/pyvisa-py | python | def write(self, data):
'Send raw bytes to the instrument.\n\n :param data: bytes to be sent to the instrument\n :type data: bytes\n '
(begin, end, size) = (0, 0, len(data))
bytes_sent = 0
raw_write = super(USBTMC, self).write
while ((end == 0) or (end < size)):
(begin, end) = (end, (begin + self.RECV_CHUNK))
self._btag = ((self._btag % 255) + 1)
eom = (end >= size)
data = BulkOutMessage.build_array(self._btag, eom, data[begin:end])
bytes_sent += raw_write(data)
return size |
def testV1ScaleIOVolumeSource(self):
'\n Test V1ScaleIOVolumeSource\n '
pass | 7,621,895,843,589,934,000 | Test V1ScaleIOVolumeSource | kubernetes/test/test_v1_scale_io_volume_source.py | testV1ScaleIOVolumeSource | MiaoRachelYu/python | python | def testV1ScaleIOVolumeSource(self):
'\n \n '
pass |
def create_tenant(self, name: str, slug: str=None) -> str:
'\n Creates a new tenant.\n\n Note this route only works when run against Prefect Server.\n\n Args:\n - name (str): the name of the tenant to create\n - slug (str, optional): the slug of the tenant to create; defaults to name\n\n Returns:\n - str: the ID of the newly created tenant, or the ID of the currently active tenant\n\n Raises:\n - ValueError: if run against Prefect Cloud\n '
if (prefect.config.backend != 'server'):
msg = 'To create a tenant with Prefect Cloud, please signup at https://cloud.prefect.io/'
raise ValueError(msg)
if (slug is None):
slug = slugify(name)
tenant_info = self.graphql({'mutation($input: create_tenant_input!)': {'create_tenant(input: $input)': {'id'}}}, variables=dict(input=dict(name=name, slug=slug)))
return tenant_info.data.create_tenant.id | 4,363,685,843,409,000,400 | Creates a new tenant.
Note this route only works when run against Prefect Server.
Args:
- name (str): the name of the tenant to create
- slug (str, optional): the slug of the tenant to create; defaults to name
Returns:
- str: the ID of the newly created tenant, or the ID of the currently active tenant
Raises:
- ValueError: if run against Prefect Cloud | src/prefect/client/client.py | create_tenant | zmac12/prefect | python | def create_tenant(self, name: str, slug: str=None) -> str:
'\n Creates a new tenant.\n\n Note this route only works when run against Prefect Server.\n\n Args:\n - name (str): the name of the tenant to create\n - slug (str, optional): the slug of the tenant to create; defaults to name\n\n Returns:\n - str: the ID of the newly created tenant, or the ID of the currently active tenant\n\n Raises:\n - ValueError: if run against Prefect Cloud\n '
if (prefect.config.backend != 'server'):
msg = 'To create a tenant with Prefect Cloud, please signup at https://cloud.prefect.io/'
raise ValueError(msg)
if (slug is None):
slug = slugify(name)
tenant_info = self.graphql({'mutation($input: create_tenant_input!)': {'create_tenant(input: $input)': {'id'}}}, variables=dict(input=dict(name=name, slug=slug)))
return tenant_info.data.create_tenant.id |
def get(self, path: str, server: str=None, headers: dict=None, params: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> dict:
"\n Convenience function for calling the Prefect API with token auth and GET request\n\n Args:\n - path (str): the path of the API url. For example, to GET\n http://prefect-server/v1/auth/login, path would be 'auth/login'.\n - server (str, optional): the server to send the GET request to;\n defaults to `self.api_server`\n - headers (dict, optional): Headers to pass with the request\n - params (dict): GET parameters\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Dictionary representation of the request made\n "
response = self._request(method='GET', path=path, params=params, server=server, headers=headers, token=token, retry_on_api_error=retry_on_api_error)
if response.text:
return response.json()
else:
return {} | -2,281,131,258,830,956,500 | Convenience function for calling the Prefect API with token auth and GET request
Args:
- path (str): the path of the API url. For example, to GET
http://prefect-server/v1/auth/login, path would be 'auth/login'.
- server (str, optional): the server to send the GET request to;
defaults to `self.api_server`
- headers (dict, optional): Headers to pass with the request
- params (dict): GET parameters
- token (str): an auth token. If not supplied, the `client.access_token` is used.
- retry_on_api_error (bool): whether the operation should be retried if the API returns
an API_ERROR code
Returns:
- dict: Dictionary representation of the request made | src/prefect/client/client.py | get | zmac12/prefect | python | def get(self, path: str, server: str=None, headers: dict=None, params: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> dict:
"\n Convenience function for calling the Prefect API with token auth and GET request\n\n Args:\n - path (str): the path of the API url. For example, to GET\n http://prefect-server/v1/auth/login, path would be 'auth/login'.\n - server (str, optional): the server to send the GET request to;\n defaults to `self.api_server`\n - headers (dict, optional): Headers to pass with the request\n - params (dict): GET parameters\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Dictionary representation of the request made\n "
response = self._request(method='GET', path=path, params=params, server=server, headers=headers, token=token, retry_on_api_error=retry_on_api_error)
if response.text:
return response.json()
else:
return {} |
def post(self, path: str, server: str=None, headers: dict=None, params: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> dict:
"\n Convenience function for calling the Prefect API with token auth and POST request\n\n Args:\n - path (str): the path of the API url. For example, to POST\n http://prefect-server/v1/auth/login, path would be 'auth/login'.\n - server (str, optional): the server to send the POST request to;\n defaults to `self.api_server`\n - headers(dict): headers to pass with the request\n - params (dict): POST parameters\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Dictionary representation of the request made\n "
response = self._request(method='POST', path=path, params=params, server=server, headers=headers, token=token, retry_on_api_error=retry_on_api_error)
if response.text:
return response.json()
else:
return {} | -5,386,446,069,364,894,000 | Convenience function for calling the Prefect API with token auth and POST request
Args:
- path (str): the path of the API url. For example, to POST
http://prefect-server/v1/auth/login, path would be 'auth/login'.
- server (str, optional): the server to send the POST request to;
defaults to `self.api_server`
- headers(dict): headers to pass with the request
- params (dict): POST parameters
- token (str): an auth token. If not supplied, the `client.access_token` is used.
- retry_on_api_error (bool): whether the operation should be retried if the API returns
an API_ERROR code
Returns:
- dict: Dictionary representation of the request made | src/prefect/client/client.py | post | zmac12/prefect | python | def post(self, path: str, server: str=None, headers: dict=None, params: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> dict:
"\n Convenience function for calling the Prefect API with token auth and POST request\n\n Args:\n - path (str): the path of the API url. For example, to POST\n http://prefect-server/v1/auth/login, path would be 'auth/login'.\n - server (str, optional): the server to send the POST request to;\n defaults to `self.api_server`\n - headers(dict): headers to pass with the request\n - params (dict): POST parameters\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Dictionary representation of the request made\n "
response = self._request(method='POST', path=path, params=params, server=server, headers=headers, token=token, retry_on_api_error=retry_on_api_error)
if response.text:
return response.json()
else:
return {} |
def graphql(self, query: Any, raise_on_error: bool=True, headers: Dict[(str, str)]=None, variables: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> GraphQLResult:
'\n Convenience function for running queries against the Prefect GraphQL API\n\n Args:\n - query (Any): A representation of a graphql query to be executed. It will be\n parsed by prefect.utilities.graphql.parse_graphql().\n - raise_on_error (bool): if True, a `ClientError` will be raised if the GraphQL\n returns any `errors`.\n - headers (dict): any additional headers that should be passed as part of the\n request\n - variables (dict): Variables to be filled into a query with the key being\n equivalent to the variables that are accepted by the query\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Data returned from the GraphQL query\n\n Raises:\n - ClientError if there are errors raised by the GraphQL mutation\n '
result = self.post(path='', server=self.api_server, headers=headers, params=dict(query=parse_graphql(query), variables=json.dumps(variables)), token=token, retry_on_api_error=retry_on_api_error)
if (raise_on_error and ('errors' in result)):
if ('UNAUTHENTICATED' in str(result['errors'])):
raise AuthorizationError(result['errors'])
elif ('Malformed Authorization header' in str(result['errors'])):
raise AuthorizationError(result['errors'])
elif (result['errors'][0].get('extensions', {}).get('code') == 'VERSION_LOCKING_ERROR'):
raise VersionLockError(result['errors'])
raise ClientError(result['errors'])
else:
return GraphQLResult(result) | 6,395,111,916,919,576,000 | Convenience function for running queries against the Prefect GraphQL API
Args:
- query (Any): A representation of a graphql query to be executed. It will be
parsed by prefect.utilities.graphql.parse_graphql().
- raise_on_error (bool): if True, a `ClientError` will be raised if the GraphQL
returns any `errors`.
- headers (dict): any additional headers that should be passed as part of the
request
- variables (dict): Variables to be filled into a query with the key being
equivalent to the variables that are accepted by the query
- token (str): an auth token. If not supplied, the `client.access_token` is used.
- retry_on_api_error (bool): whether the operation should be retried if the API returns
an API_ERROR code
Returns:
- dict: Data returned from the GraphQL query
Raises:
- ClientError if there are errors raised by the GraphQL mutation | src/prefect/client/client.py | graphql | zmac12/prefect | python | def graphql(self, query: Any, raise_on_error: bool=True, headers: Dict[(str, str)]=None, variables: Dict[(str, JSONLike)]=None, token: str=None, retry_on_api_error: bool=True) -> GraphQLResult:
'\n Convenience function for running queries against the Prefect GraphQL API\n\n Args:\n - query (Any): A representation of a graphql query to be executed. It will be\n parsed by prefect.utilities.graphql.parse_graphql().\n - raise_on_error (bool): if True, a `ClientError` will be raised if the GraphQL\n returns any `errors`.\n - headers (dict): any additional headers that should be passed as part of the\n request\n - variables (dict): Variables to be filled into a query with the key being\n equivalent to the variables that are accepted by the query\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - dict: Data returned from the GraphQL query\n\n Raises:\n - ClientError if there are errors raised by the GraphQL mutation\n '
result = self.post(path=, server=self.api_server, headers=headers, params=dict(query=parse_graphql(query), variables=json.dumps(variables)), token=token, retry_on_api_error=retry_on_api_error)
if (raise_on_error and ('errors' in result)):
if ('UNAUTHENTICATED' in str(result['errors'])):
raise AuthorizationError(result['errors'])
elif ('Malformed Authorization header' in str(result['errors'])):
raise AuthorizationError(result['errors'])
elif (result['errors'][0].get('extensions', {}).get('code') == 'VERSION_LOCKING_ERROR'):
raise VersionLockError(result['errors'])
raise ClientError(result['errors'])
else:
return GraphQLResult(result) |
def _request(self, method: str, path: str, params: Dict[(str, JSONLike)]=None, server: str=None, headers: dict=None, token: str=None, retry_on_api_error: bool=True) -> 'requests.models.Response':
'\n Runs any specified request (GET, POST, DELETE) against the server\n\n Args:\n - method (str): The type of request to be made (GET, POST, DELETE)\n - path (str): Path of the API URL\n - params (dict, optional): Parameters used for the request\n - server (str, optional): The server to make requests against, base API\n server is used if not specified\n - headers (dict, optional): Headers to pass with the request\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - requests.models.Response: The response returned from the request\n\n Raises:\n - ClientError: if the client token is not in the context (due to not being logged in)\n - ValueError: if a method is specified outside of the accepted GET, POST, DELETE\n - requests.HTTPError: if a status code is returned that is not `200` or `401`\n '
if (server is None):
server = self.api_server
assert isinstance(server, str)
if (token is None):
token = self.get_auth_token()
import requests
url = urljoin(server, path.lstrip('/')).rstrip('/')
params = (params or {})
headers = (headers or {})
if token:
headers['Authorization'] = 'Bearer {}'.format(token)
headers['X-PREFECT-CORE-VERSION'] = str(prefect.__version__)
if self._attached_headers:
headers.update(self._attached_headers)
session = requests.Session()
retry_total = (6 if (prefect.config.backend == 'cloud') else 1)
retries = requests.packages.urllib3.util.retry.Retry(total=retry_total, backoff_factor=1, status_forcelist=[500, 502, 503, 504], method_whitelist=['DELETE', 'GET', 'POST'])
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries))
response = self._send_request(session=session, method=method, url=url, params=params, headers=headers)
try:
json_resp = response.json()
except JSONDecodeError as exc:
if ((prefect.config.backend == 'cloud') and ('Authorization' not in headers)):
raise ClientError('Malformed response received from Cloud - please ensure that you have an API token properly configured.') from exc
else:
raise ClientError('Malformed response received from API.') from exc
if (('API_ERROR' in str(json_resp.get('errors'))) and retry_on_api_error):
(success, retry_count) = (False, 0)
while ((success is False) and (retry_count < 6)):
response = self._send_request(session=session, method=method, url=url, params=params, headers=headers)
if ('API_ERROR' in str(response.json().get('errors'))):
retry_count += 1
time.sleep((0.25 * (2 ** (retry_count - 1))))
else:
success = True
return response | -4,203,393,476,046,338,000 | Runs any specified request (GET, POST, DELETE) against the server
Args:
- method (str): The type of request to be made (GET, POST, DELETE)
- path (str): Path of the API URL
- params (dict, optional): Parameters used for the request
- server (str, optional): The server to make requests against, base API
server is used if not specified
- headers (dict, optional): Headers to pass with the request
- token (str): an auth token. If not supplied, the `client.access_token` is used.
- retry_on_api_error (bool): whether the operation should be retried if the API returns
an API_ERROR code
Returns:
- requests.models.Response: The response returned from the request
Raises:
- ClientError: if the client token is not in the context (due to not being logged in)
- ValueError: if a method is specified outside of the accepted GET, POST, DELETE
- requests.HTTPError: if a status code is returned that is not `200` or `401` | src/prefect/client/client.py | _request | zmac12/prefect | python | def _request(self, method: str, path: str, params: Dict[(str, JSONLike)]=None, server: str=None, headers: dict=None, token: str=None, retry_on_api_error: bool=True) -> 'requests.models.Response':
'\n Runs any specified request (GET, POST, DELETE) against the server\n\n Args:\n - method (str): The type of request to be made (GET, POST, DELETE)\n - path (str): Path of the API URL\n - params (dict, optional): Parameters used for the request\n - server (str, optional): The server to make requests against, base API\n server is used if not specified\n - headers (dict, optional): Headers to pass with the request\n - token (str): an auth token. If not supplied, the `client.access_token` is used.\n - retry_on_api_error (bool): whether the operation should be retried if the API returns\n an API_ERROR code\n\n Returns:\n - requests.models.Response: The response returned from the request\n\n Raises:\n - ClientError: if the client token is not in the context (due to not being logged in)\n - ValueError: if a method is specified outside of the accepted GET, POST, DELETE\n - requests.HTTPError: if a status code is returned that is not `200` or `401`\n '
if (server is None):
server = self.api_server
assert isinstance(server, str)
if (token is None):
token = self.get_auth_token()
import requests
url = urljoin(server, path.lstrip('/')).rstrip('/')
params = (params or {})
headers = (headers or {})
if token:
headers['Authorization'] = 'Bearer {}'.format(token)
headers['X-PREFECT-CORE-VERSION'] = str(prefect.__version__)
if self._attached_headers:
headers.update(self._attached_headers)
session = requests.Session()
retry_total = (6 if (prefect.config.backend == 'cloud') else 1)
retries = requests.packages.urllib3.util.retry.Retry(total=retry_total, backoff_factor=1, status_forcelist=[500, 502, 503, 504], method_whitelist=['DELETE', 'GET', 'POST'])
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=retries))
response = self._send_request(session=session, method=method, url=url, params=params, headers=headers)
try:
json_resp = response.json()
except JSONDecodeError as exc:
if ((prefect.config.backend == 'cloud') and ('Authorization' not in headers)):
raise ClientError('Malformed response received from Cloud - please ensure that you have an API token properly configured.') from exc
else:
raise ClientError('Malformed response received from API.') from exc
if (('API_ERROR' in str(json_resp.get('errors'))) and retry_on_api_error):
(success, retry_count) = (False, 0)
while ((success is False) and (retry_count < 6)):
response = self._send_request(session=session, method=method, url=url, params=params, headers=headers)
if ('API_ERROR' in str(response.json().get('errors'))):
retry_count += 1
time.sleep((0.25 * (2 ** (retry_count - 1))))
else:
success = True
return response |
def attach_headers(self, headers: dict) -> None:
'\n Set headers to be attached to this Client\n\n Args:\n - headers (dict): A dictionary of headers to attach to this client. These headers\n get added on to the existing dictionary of headers.\n '
self._attached_headers.update(headers) | -7,213,665,426,098,937,000 | Set headers to be attached to this Client
Args:
- headers (dict): A dictionary of headers to attach to this client. These headers
get added on to the existing dictionary of headers. | src/prefect/client/client.py | attach_headers | zmac12/prefect | python | def attach_headers(self, headers: dict) -> None:
'\n Set headers to be attached to this Client\n\n Args:\n - headers (dict): A dictionary of headers to attach to this client. These headers\n get added on to the existing dictionary of headers.\n '
self._attached_headers.update(headers) |
@property
def _local_settings_path(self) -> Path:
'\n Returns the local settings directory corresponding to the current API servers\n '
path = '{home}/client/{server}'.format(home=prefect.context.config.home_dir, server=slugify(self.api_server, regex_pattern='[^-\\.a-z0-9]+'))
return (Path(os.path.expanduser(path)) / 'settings.toml') | -4,684,211,161,303,825,000 | Returns the local settings directory corresponding to the current API servers | src/prefect/client/client.py | _local_settings_path | zmac12/prefect | python | @property
def _local_settings_path(self) -> Path:
'\n \n '
path = '{home}/client/{server}'.format(home=prefect.context.config.home_dir, server=slugify(self.api_server, regex_pattern='[^-\\.a-z0-9]+'))
return (Path(os.path.expanduser(path)) / 'settings.toml') |
def _save_local_settings(self, settings: dict) -> None:
'\n Writes settings to local storage\n '
self._local_settings_path.parent.mkdir(exist_ok=True, parents=True)
with self._local_settings_path.open('w+') as f:
toml.dump(settings, f) | 7,160,887,922,359,211,000 | Writes settings to local storage | src/prefect/client/client.py | _save_local_settings | zmac12/prefect | python | def _save_local_settings(self, settings: dict) -> None:
'\n \n '
self._local_settings_path.parent.mkdir(exist_ok=True, parents=True)
with self._local_settings_path.open('w+') as f:
toml.dump(settings, f) |
def _load_local_settings(self) -> dict:
'\n Loads settings from local storage\n '
if self._local_settings_path.exists():
with self._local_settings_path.open('r') as f:
return toml.load(f)
return {} | -4,027,457,190,338,211,000 | Loads settings from local storage | src/prefect/client/client.py | _load_local_settings | zmac12/prefect | python | def _load_local_settings(self) -> dict:
'\n \n '
if self._local_settings_path.exists():
with self._local_settings_path.open('r') as f:
return toml.load(f)
return {} |
def save_api_token(self) -> None:
'\n Saves the API token in local storage.\n '
settings = self._load_local_settings()
settings['api_token'] = self._api_token
self._save_local_settings(settings) | -1,917,627,436,893,828,400 | Saves the API token in local storage. | src/prefect/client/client.py | save_api_token | zmac12/prefect | python | def save_api_token(self) -> None:
'\n \n '
settings = self._load_local_settings()
settings['api_token'] = self._api_token
self._save_local_settings(settings) |
def get_auth_token(self) -> str:
"\n Returns an auth token:\n - if no explicit access token is stored, returns the api token\n - if there is an access token:\n - if there's a refresh token and the access token expires in the next 30 seconds,\n then we refresh the access token and store the result\n - return the access token\n\n Returns:\n - str: the access token\n "
if (not self._access_token):
return self._api_token
expiration = (self._access_token_expires_at or pendulum.now())
if (self._refresh_token and (pendulum.now().add(seconds=30) > expiration)):
self._refresh_access_token()
return self._access_token | -1,884,620,996,661,254,100 | Returns an auth token:
- if no explicit access token is stored, returns the api token
- if there is an access token:
- if there's a refresh token and the access token expires in the next 30 seconds,
then we refresh the access token and store the result
- return the access token
Returns:
- str: the access token | src/prefect/client/client.py | get_auth_token | zmac12/prefect | python | def get_auth_token(self) -> str:
"\n Returns an auth token:\n - if no explicit access token is stored, returns the api token\n - if there is an access token:\n - if there's a refresh token and the access token expires in the next 30 seconds,\n then we refresh the access token and store the result\n - return the access token\n\n Returns:\n - str: the access token\n "
if (not self._access_token):
return self._api_token
expiration = (self._access_token_expires_at or pendulum.now())
if (self._refresh_token and (pendulum.now().add(seconds=30) > expiration)):
self._refresh_access_token()
return self._access_token |
def get_available_tenants(self) -> List[Dict]:
'\n Returns a list of available tenants.\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Returns:\n - List[Dict]: a list of dictionaries containing the id, slug, and name of\n available tenants\n '
result = self.graphql({'query': {'tenant(order_by: {slug: asc})': {'id', 'slug', 'name'}}}, token=self._api_token)
return result.data.tenant | -4,935,558,625,172,033,000 | Returns a list of available tenants.
NOTE: this should only be called by users who have provided a USER-scoped API token.
Returns:
- List[Dict]: a list of dictionaries containing the id, slug, and name of
available tenants | src/prefect/client/client.py | get_available_tenants | zmac12/prefect | python | def get_available_tenants(self) -> List[Dict]:
'\n Returns a list of available tenants.\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Returns:\n - List[Dict]: a list of dictionaries containing the id, slug, and name of\n available tenants\n '
result = self.graphql({'query': {'tenant(order_by: {slug: asc})': {'id', 'slug', 'name'}}}, token=self._api_token)
return result.data.tenant |
def login_to_tenant(self, tenant_slug: str=None, tenant_id: str=None) -> bool:
"\n Log in to a specific tenant\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Args:\n - tenant_slug (str): the tenant's slug\n - tenant_id (str): the tenant's id\n\n Returns:\n - bool: True if the login was successful\n\n Raises:\n - ValueError: if at least one of `tenant_slug` or `tenant_id` isn't provided\n - ValueError: if the `tenant_id` is not a valid UUID\n - ValueError: if no matching tenants are found\n\n "
if ((tenant_slug is None) and (tenant_id is None)):
raise ValueError('At least one of `tenant_slug` or `tenant_id` must be provided.')
elif tenant_id:
try:
uuid.UUID(tenant_id)
except ValueError as exc:
raise ValueError('The `tenant_id` must be a valid UUID.') from exc
tenant = self.graphql({'query($slug: String, $id: uuid)': {'tenant(where: {slug: { _eq: $slug }, id: { _eq: $id } })': {'id'}}}, variables=dict(slug=tenant_slug, id=tenant_id), token=self._api_token)
if (not tenant.data.tenant):
raise ValueError('No matching tenants found.')
tenant_id = tenant.data.tenant[0].id
if (prefect.config.backend == 'cloud'):
payload = self.graphql({'mutation($input: switch_tenant_input!)': {'switch_tenant(input: $input)': {'access_token', 'expires_at', 'refresh_token'}}}, variables=dict(input=dict(tenant_id=tenant_id)), token=self._api_token)
self._access_token = payload.data.switch_tenant.access_token
self._access_token_expires_at = pendulum.parse(payload.data.switch_tenant.expires_at)
self._refresh_token = payload.data.switch_tenant.refresh_token
self._active_tenant_id = tenant_id
settings = self._load_local_settings()
settings['active_tenant_id'] = self._active_tenant_id
self._save_local_settings(settings)
return True | -1,303,885,025,766,660,600 | Log in to a specific tenant
NOTE: this should only be called by users who have provided a USER-scoped API token.
Args:
- tenant_slug (str): the tenant's slug
- tenant_id (str): the tenant's id
Returns:
- bool: True if the login was successful
Raises:
- ValueError: if at least one of `tenant_slug` or `tenant_id` isn't provided
- ValueError: if the `tenant_id` is not a valid UUID
- ValueError: if no matching tenants are found | src/prefect/client/client.py | login_to_tenant | zmac12/prefect | python | def login_to_tenant(self, tenant_slug: str=None, tenant_id: str=None) -> bool:
"\n Log in to a specific tenant\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Args:\n - tenant_slug (str): the tenant's slug\n - tenant_id (str): the tenant's id\n\n Returns:\n - bool: True if the login was successful\n\n Raises:\n - ValueError: if at least one of `tenant_slug` or `tenant_id` isn't provided\n - ValueError: if the `tenant_id` is not a valid UUID\n - ValueError: if no matching tenants are found\n\n "
if ((tenant_slug is None) and (tenant_id is None)):
raise ValueError('At least one of `tenant_slug` or `tenant_id` must be provided.')
elif tenant_id:
try:
uuid.UUID(tenant_id)
except ValueError as exc:
raise ValueError('The `tenant_id` must be a valid UUID.') from exc
tenant = self.graphql({'query($slug: String, $id: uuid)': {'tenant(where: {slug: { _eq: $slug }, id: { _eq: $id } })': {'id'}}}, variables=dict(slug=tenant_slug, id=tenant_id), token=self._api_token)
if (not tenant.data.tenant):
raise ValueError('No matching tenants found.')
tenant_id = tenant.data.tenant[0].id
if (prefect.config.backend == 'cloud'):
payload = self.graphql({'mutation($input: switch_tenant_input!)': {'switch_tenant(input: $input)': {'access_token', 'expires_at', 'refresh_token'}}}, variables=dict(input=dict(tenant_id=tenant_id)), token=self._api_token)
self._access_token = payload.data.switch_tenant.access_token
self._access_token_expires_at = pendulum.parse(payload.data.switch_tenant.expires_at)
self._refresh_token = payload.data.switch_tenant.refresh_token
self._active_tenant_id = tenant_id
settings = self._load_local_settings()
settings['active_tenant_id'] = self._active_tenant_id
self._save_local_settings(settings)
return True |
def _refresh_access_token(self) -> bool:
"\n Refresh the client's JWT access token.\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Returns:\n - bool: True if the refresh succeeds\n "
payload = self.graphql({'mutation($input: refresh_token_input!)': {'refresh_token(input: $input)': {'access_token', 'expires_at', 'refresh_token'}}}, variables=dict(input=dict(access_token=self._access_token)), token=self._refresh_token)
self._access_token = payload.data.refresh_token.access_token
self._access_token_expires_at = pendulum.parse(payload.data.refresh_token.expires_at)
self._refresh_token = payload.data.refresh_token.refresh_token
return True | 674,399,932,671,175,400 | Refresh the client's JWT access token.
NOTE: this should only be called by users who have provided a USER-scoped API token.
Returns:
- bool: True if the refresh succeeds | src/prefect/client/client.py | _refresh_access_token | zmac12/prefect | python | def _refresh_access_token(self) -> bool:
"\n Refresh the client's JWT access token.\n\n NOTE: this should only be called by users who have provided a USER-scoped API token.\n\n Returns:\n - bool: True if the refresh succeeds\n "
payload = self.graphql({'mutation($input: refresh_token_input!)': {'refresh_token(input: $input)': {'access_token', 'expires_at', 'refresh_token'}}}, variables=dict(input=dict(access_token=self._access_token)), token=self._refresh_token)
self._access_token = payload.data.refresh_token.access_token
self._access_token_expires_at = pendulum.parse(payload.data.refresh_token.expires_at)
self._refresh_token = payload.data.refresh_token.refresh_token
return True |
def register(self, flow: 'Flow', project_name: str=None, build: bool=True, set_schedule_active: bool=True, version_group_id: str=None, compressed: bool=True, no_url: bool=False) -> str:
"\n Push a new flow to Prefect Cloud\n\n Args:\n - flow (Flow): a flow to register\n - project_name (str, optional): the project that should contain this flow.\n - build (bool, optional): if `True`, the flow's environment is built\n prior to serialization; defaults to `True`\n - set_schedule_active (bool, optional): if `False`, will set the schedule to\n inactive in the database to prevent auto-scheduling runs (if the Flow has a\n schedule). Defaults to `True`. This can be changed later.\n - version_group_id (str, optional): the UUID version group ID to use for versioning\n this Flow in Cloud; if not provided, the version group ID associated with this\n Flow's project and name will be used.\n - compressed (bool, optional): if `True`, the serialized flow will be; defaults to\n `True` compressed\n - no_url (bool, optional): if `True`, the stdout from this function will not\n contain the URL link to the newly-registered flow in the Cloud UI\n\n Returns:\n - str: the ID of the newly-registered flow\n\n Raises:\n - ClientError: if the register failed\n "
required_parameters = {p for p in flow.parameters() if p.required}
if ((flow.schedule is not None) and required_parameters):
required_names = {p.name for p in required_parameters}
if (not all([(required_names <= set(c.parameter_defaults.keys())) for c in flow.schedule.clocks])):
raise ClientError('Flows with required parameters can not be scheduled automatically.')
if (any((e.key for e in flow.edges)) and (flow.result is None)):
warnings.warn('No result handler was specified on your Flow. Cloud features such as input caching and resuming task runs from failure may not work properly.', stacklevel=2)
if compressed:
create_mutation = {'mutation($input: create_flow_from_compressed_string_input!)': {'create_flow_from_compressed_string(input: $input)': {'id'}}}
else:
create_mutation = {'mutation($input: create_flow_input!)': {'create_flow(input: $input)': {'id'}}}
project = None
if (project_name is None):
raise TypeError("'project_name' is a required field when registering a flow.")
query_project = {'query': {with_args('project', {'where': {'name': {'_eq': project_name}}}): {'id': True}}}
project = self.graphql(query_project).data.project
if (not project):
raise ValueError("Project {} not found. Run `prefect create project '{}'` to create it.".format(project_name, project_name))
serialized_flow = flow.serialize(build=build)
if isinstance(flow.storage, prefect.environments.storage.Docker):
flow.environment.metadata['image'] = flow.storage.name
serialized_flow = flow.serialize(build=False)
if (not flow.environment.metadata.get('image')):
version = prefect.__version__.split('+')[0]
flow.environment.metadata['image'] = f'prefecthq/prefect:all_extras-{version}'
serialized_flow = flow.serialize(build=False)
try:
prefect.serialization.flow.FlowSchema().load(serialized_flow)
except Exception as exc:
raise ValueError('Flow could not be deserialized successfully. Error was: {}'.format(repr(exc))) from exc
if compressed:
serialized_flow = compress(serialized_flow)
res = self.graphql(create_mutation, variables=dict(input=dict(project_id=(project[0].id if project else None), serialized_flow=serialized_flow, set_schedule_active=set_schedule_active, version_group_id=version_group_id)), retry_on_api_error=False)
flow_id = (res.data.create_flow_from_compressed_string.id if compressed else res.data.create_flow.id)
if (not no_url):
flow_url = self.get_cloud_url('flow', flow_id)
prefix = '└── '
print('Flow URL: {}'.format(flow_url))
msg = f''' {prefix}ID: {flow_id}
{prefix}Project: {project_name}
{prefix}Labels: {list(flow.environment.labels)}'''
print(msg)
return flow_id | -6,778,166,901,766,833,000 | Push a new flow to Prefect Cloud
Args:
- flow (Flow): a flow to register
- project_name (str, optional): the project that should contain this flow.
- build (bool, optional): if `True`, the flow's environment is built
prior to serialization; defaults to `True`
- set_schedule_active (bool, optional): if `False`, will set the schedule to
inactive in the database to prevent auto-scheduling runs (if the Flow has a
schedule). Defaults to `True`. This can be changed later.
- version_group_id (str, optional): the UUID version group ID to use for versioning
this Flow in Cloud; if not provided, the version group ID associated with this
Flow's project and name will be used.
- compressed (bool, optional): if `True`, the serialized flow will be; defaults to
`True` compressed
- no_url (bool, optional): if `True`, the stdout from this function will not
contain the URL link to the newly-registered flow in the Cloud UI
Returns:
- str: the ID of the newly-registered flow
Raises:
- ClientError: if the register failed | src/prefect/client/client.py | register | zmac12/prefect | python | def register(self, flow: 'Flow', project_name: str=None, build: bool=True, set_schedule_active: bool=True, version_group_id: str=None, compressed: bool=True, no_url: bool=False) -> str:
"\n Push a new flow to Prefect Cloud\n\n Args:\n - flow (Flow): a flow to register\n - project_name (str, optional): the project that should contain this flow.\n - build (bool, optional): if `True`, the flow's environment is built\n prior to serialization; defaults to `True`\n - set_schedule_active (bool, optional): if `False`, will set the schedule to\n inactive in the database to prevent auto-scheduling runs (if the Flow has a\n schedule). Defaults to `True`. This can be changed later.\n - version_group_id (str, optional): the UUID version group ID to use for versioning\n this Flow in Cloud; if not provided, the version group ID associated with this\n Flow's project and name will be used.\n - compressed (bool, optional): if `True`, the serialized flow will be; defaults to\n `True` compressed\n - no_url (bool, optional): if `True`, the stdout from this function will not\n contain the URL link to the newly-registered flow in the Cloud UI\n\n Returns:\n - str: the ID of the newly-registered flow\n\n Raises:\n - ClientError: if the register failed\n "
required_parameters = {p for p in flow.parameters() if p.required}
if ((flow.schedule is not None) and required_parameters):
required_names = {p.name for p in required_parameters}
if (not all([(required_names <= set(c.parameter_defaults.keys())) for c in flow.schedule.clocks])):
raise ClientError('Flows with required parameters can not be scheduled automatically.')
if (any((e.key for e in flow.edges)) and (flow.result is None)):
warnings.warn('No result handler was specified on your Flow. Cloud features such as input caching and resuming task runs from failure may not work properly.', stacklevel=2)
if compressed:
create_mutation = {'mutation($input: create_flow_from_compressed_string_input!)': {'create_flow_from_compressed_string(input: $input)': {'id'}}}
else:
create_mutation = {'mutation($input: create_flow_input!)': {'create_flow(input: $input)': {'id'}}}
project = None
if (project_name is None):
raise TypeError("'project_name' is a required field when registering a flow.")
query_project = {'query': {with_args('project', {'where': {'name': {'_eq': project_name}}}): {'id': True}}}
project = self.graphql(query_project).data.project
if (not project):
raise ValueError("Project {} not found. Run `prefect create project '{}'` to create it.".format(project_name, project_name))
serialized_flow = flow.serialize(build=build)
if isinstance(flow.storage, prefect.environments.storage.Docker):
flow.environment.metadata['image'] = flow.storage.name
serialized_flow = flow.serialize(build=False)
if (not flow.environment.metadata.get('image')):
version = prefect.__version__.split('+')[0]
flow.environment.metadata['image'] = f'prefecthq/prefect:all_extras-{version}'
serialized_flow = flow.serialize(build=False)
try:
prefect.serialization.flow.FlowSchema().load(serialized_flow)
except Exception as exc:
raise ValueError('Flow could not be deserialized successfully. Error was: {}'.format(repr(exc))) from exc
if compressed:
serialized_flow = compress(serialized_flow)
res = self.graphql(create_mutation, variables=dict(input=dict(project_id=(project[0].id if project else None), serialized_flow=serialized_flow, set_schedule_active=set_schedule_active, version_group_id=version_group_id)), retry_on_api_error=False)
flow_id = (res.data.create_flow_from_compressed_string.id if compressed else res.data.create_flow.id)
if (not no_url):
flow_url = self.get_cloud_url('flow', flow_id)
prefix = '└── '
print('Flow URL: {}'.format(flow_url))
msg = f' {prefix}ID: {flow_id}
{prefix}Project: {project_name}
{prefix}Labels: {list(flow.environment.labels)}'
print(msg)
return flow_id |
def get_cloud_url(self, subdirectory: str, id: str, as_user: bool=True) -> str:
'\n Convenience method for creating Prefect Cloud URLs for a given subdirectory.\n\n Args:\n - subdirectory (str): the subdirectory to use (e.g., `"flow-run"`)\n - id (str): the ID of the page\n - as_user (bool, optional): whether this query is being made from a USER scoped token;\n defaults to `True`. Only used internally for queries made from RUNNERs\n\n Returns:\n - str: the URL corresponding to the appropriate base URL, tenant slug, subdirectory\n and ID\n\n Example:\n\n ```python\n from prefect import Client\n\n client = Client()\n client.get_cloud_url("flow-run", "424242-ca-94611-111-55")\n # returns "https://cloud.prefect.io/my-tenant-slug/flow-run/424242-ca-94611-111-55"\n ```\n '
if (prefect.config.backend == 'cloud'):
tenant_slug = self.get_default_tenant_slug(as_user=as_user)
else:
tenant_slug = ''
base_url = (re.sub('api-', '', prefect.config.cloud.api) if re.search('api-', prefect.config.cloud.api) else re.sub('api', 'cloud', prefect.config.cloud.api))
full_url = prefect.config.cloud.api
if tenant_slug:
full_url = '/'.join([base_url.rstrip('/'), tenant_slug, subdirectory, id])
elif (prefect.config.backend == 'server'):
full_url = '/'.join([prefect.config.server.ui.endpoint, subdirectory, id])
return full_url | -3,544,279,537,556,646,000 | Convenience method for creating Prefect Cloud URLs for a given subdirectory.
Args:
- subdirectory (str): the subdirectory to use (e.g., `"flow-run"`)
- id (str): the ID of the page
- as_user (bool, optional): whether this query is being made from a USER scoped token;
defaults to `True`. Only used internally for queries made from RUNNERs
Returns:
- str: the URL corresponding to the appropriate base URL, tenant slug, subdirectory
and ID
Example:
```python
from prefect import Client
client = Client()
client.get_cloud_url("flow-run", "424242-ca-94611-111-55")
# returns "https://cloud.prefect.io/my-tenant-slug/flow-run/424242-ca-94611-111-55"
``` | src/prefect/client/client.py | get_cloud_url | zmac12/prefect | python | def get_cloud_url(self, subdirectory: str, id: str, as_user: bool=True) -> str:
'\n Convenience method for creating Prefect Cloud URLs for a given subdirectory.\n\n Args:\n - subdirectory (str): the subdirectory to use (e.g., `"flow-run"`)\n - id (str): the ID of the page\n - as_user (bool, optional): whether this query is being made from a USER scoped token;\n defaults to `True`. Only used internally for queries made from RUNNERs\n\n Returns:\n - str: the URL corresponding to the appropriate base URL, tenant slug, subdirectory\n and ID\n\n Example:\n\n ```python\n from prefect import Client\n\n client = Client()\n client.get_cloud_url("flow-run", "424242-ca-94611-111-55")\n # returns "https://cloud.prefect.io/my-tenant-slug/flow-run/424242-ca-94611-111-55"\n ```\n '
if (prefect.config.backend == 'cloud'):
tenant_slug = self.get_default_tenant_slug(as_user=as_user)
else:
tenant_slug =
base_url = (re.sub('api-', , prefect.config.cloud.api) if re.search('api-', prefect.config.cloud.api) else re.sub('api', 'cloud', prefect.config.cloud.api))
full_url = prefect.config.cloud.api
if tenant_slug:
full_url = '/'.join([base_url.rstrip('/'), tenant_slug, subdirectory, id])
elif (prefect.config.backend == 'server'):
full_url = '/'.join([prefect.config.server.ui.endpoint, subdirectory, id])
return full_url |
def get_default_tenant_slug(self, as_user: bool=True) -> str:
'\n Get the default tenant slug for the currently authenticated user\n\n Args:\n - as_user (bool, optional): whether this query is being made from a USER scoped token;\n defaults to `True`. Only used internally for queries made from RUNNERs\n\n Returns:\n - str: the slug of the current default tenant for this user\n '
if as_user:
query = {'query': {'user': {'default_membership': {'tenant': 'slug'}}}}
else:
query = {'query': {'tenant': {'slug'}}}
res = self.graphql(query)
if as_user:
user = res.get('data').user[0]
slug = user.default_membership.tenant.slug
else:
slug = res.get('data').tenant[0].slug
return slug | -8,470,113,905,930,942,000 | Get the default tenant slug for the currently authenticated user
Args:
- as_user (bool, optional): whether this query is being made from a USER scoped token;
defaults to `True`. Only used internally for queries made from RUNNERs
Returns:
- str: the slug of the current default tenant for this user | src/prefect/client/client.py | get_default_tenant_slug | zmac12/prefect | python | def get_default_tenant_slug(self, as_user: bool=True) -> str:
'\n Get the default tenant slug for the currently authenticated user\n\n Args:\n - as_user (bool, optional): whether this query is being made from a USER scoped token;\n defaults to `True`. Only used internally for queries made from RUNNERs\n\n Returns:\n - str: the slug of the current default tenant for this user\n '
if as_user:
query = {'query': {'user': {'default_membership': {'tenant': 'slug'}}}}
else:
query = {'query': {'tenant': {'slug'}}}
res = self.graphql(query)
if as_user:
user = res.get('data').user[0]
slug = user.default_membership.tenant.slug
else:
slug = res.get('data').tenant[0].slug
return slug |
def create_project(self, project_name: str, project_description: str=None) -> str:
'\n Create a new Project\n\n Args:\n - project_name (str): the project that should contain this flow\n - project_description (str, optional): the project description\n\n Returns:\n - str: the ID of the newly-created project\n\n Raises:\n - ClientError: if the project creation failed\n '
project_mutation = {'mutation($input: create_project_input!)': {'create_project(input: $input)': {'id'}}}
res = self.graphql(project_mutation, variables=dict(input=dict(name=project_name, description=project_description, tenant_id=self._active_tenant_id)))
return res.data.create_project.id | 8,238,271,992,302,800,000 | Create a new Project
Args:
- project_name (str): the project that should contain this flow
- project_description (str, optional): the project description
Returns:
- str: the ID of the newly-created project
Raises:
- ClientError: if the project creation failed | src/prefect/client/client.py | create_project | zmac12/prefect | python | def create_project(self, project_name: str, project_description: str=None) -> str:
'\n Create a new Project\n\n Args:\n - project_name (str): the project that should contain this flow\n - project_description (str, optional): the project description\n\n Returns:\n - str: the ID of the newly-created project\n\n Raises:\n - ClientError: if the project creation failed\n '
project_mutation = {'mutation($input: create_project_input!)': {'create_project(input: $input)': {'id'}}}
res = self.graphql(project_mutation, variables=dict(input=dict(name=project_name, description=project_description, tenant_id=self._active_tenant_id)))
return res.data.create_project.id |
def create_flow_run(self, flow_id: str=None, context: dict=None, parameters: dict=None, scheduled_start_time: datetime.datetime=None, idempotency_key: str=None, run_name: str=None, version_group_id: str=None) -> str:
"\n Create a new flow run for the given flow id. If `start_time` is not provided, the flow\n run will be scheduled to start immediately. If both `flow_id` and `version_group_id`\n are provided, only the `flow_id` will be used.\n\n Args:\n - flow_id (str, optional): the id of the Flow you wish to schedule\n - context (dict, optional): the run context\n - parameters (dict, optional): a dictionary of parameter values to pass to the flow run\n - scheduled_start_time (datetime, optional): the time to schedule the execution\n for; if not provided, defaults to now\n - idempotency_key (str, optional): an idempotency key; if provided, this run will\n be cached for 24 hours. Any subsequent attempts to create a run with the same\n idempotency key will return the ID of the originally created run (no new run\n will be created after the first). An error will be raised if parameters or\n context are provided and don't match the original. Each subsequent request\n will reset the TTL for 24 hours.\n - run_name (str, optional): The name assigned to this flow run\n - version_group_id (str, optional): if provided, the unique unarchived flow within\n this version group will be scheduled to run. This input can be used as a\n stable API for running flows which are regularly updated.\n\n Returns:\n - str: the ID of the newly-created flow run\n\n Raises:\n - ClientError: if the GraphQL query is bad for any reason\n "
create_mutation = {'mutation($input: create_flow_run_input!)': {'create_flow_run(input: $input)': {'id': True}}}
if ((not flow_id) and (not version_group_id)):
raise ValueError('One of flow_id or version_group_id must be provided')
if flow_id:
inputs = dict(flow_id=flow_id)
else:
inputs = dict(version_group_id=version_group_id)
if (parameters is not None):
inputs.update(parameters=parameters)
if (context is not None):
inputs.update(context=context)
if (idempotency_key is not None):
inputs.update(idempotency_key=idempotency_key)
if (scheduled_start_time is not None):
inputs.update(scheduled_start_time=scheduled_start_time.isoformat())
if (run_name is not None):
inputs.update(flow_run_name=run_name)
res = self.graphql(create_mutation, variables=dict(input=inputs))
return res.data.create_flow_run.id | 2,886,062,023,428,716,000 | Create a new flow run for the given flow id. If `start_time` is not provided, the flow
run will be scheduled to start immediately. If both `flow_id` and `version_group_id`
are provided, only the `flow_id` will be used.
Args:
- flow_id (str, optional): the id of the Flow you wish to schedule
- context (dict, optional): the run context
- parameters (dict, optional): a dictionary of parameter values to pass to the flow run
- scheduled_start_time (datetime, optional): the time to schedule the execution
for; if not provided, defaults to now
- idempotency_key (str, optional): an idempotency key; if provided, this run will
be cached for 24 hours. Any subsequent attempts to create a run with the same
idempotency key will return the ID of the originally created run (no new run
will be created after the first). An error will be raised if parameters or
context are provided and don't match the original. Each subsequent request
will reset the TTL for 24 hours.
- run_name (str, optional): The name assigned to this flow run
- version_group_id (str, optional): if provided, the unique unarchived flow within
this version group will be scheduled to run. This input can be used as a
stable API for running flows which are regularly updated.
Returns:
- str: the ID of the newly-created flow run
Raises:
- ClientError: if the GraphQL query is bad for any reason | src/prefect/client/client.py | create_flow_run | zmac12/prefect | python | def create_flow_run(self, flow_id: str=None, context: dict=None, parameters: dict=None, scheduled_start_time: datetime.datetime=None, idempotency_key: str=None, run_name: str=None, version_group_id: str=None) -> str:
"\n Create a new flow run for the given flow id. If `start_time` is not provided, the flow\n run will be scheduled to start immediately. If both `flow_id` and `version_group_id`\n are provided, only the `flow_id` will be used.\n\n Args:\n - flow_id (str, optional): the id of the Flow you wish to schedule\n - context (dict, optional): the run context\n - parameters (dict, optional): a dictionary of parameter values to pass to the flow run\n - scheduled_start_time (datetime, optional): the time to schedule the execution\n for; if not provided, defaults to now\n - idempotency_key (str, optional): an idempotency key; if provided, this run will\n be cached for 24 hours. Any subsequent attempts to create a run with the same\n idempotency key will return the ID of the originally created run (no new run\n will be created after the first). An error will be raised if parameters or\n context are provided and don't match the original. Each subsequent request\n will reset the TTL for 24 hours.\n - run_name (str, optional): The name assigned to this flow run\n - version_group_id (str, optional): if provided, the unique unarchived flow within\n this version group will be scheduled to run. This input can be used as a\n stable API for running flows which are regularly updated.\n\n Returns:\n - str: the ID of the newly-created flow run\n\n Raises:\n - ClientError: if the GraphQL query is bad for any reason\n "
create_mutation = {'mutation($input: create_flow_run_input!)': {'create_flow_run(input: $input)': {'id': True}}}
if ((not flow_id) and (not version_group_id)):
raise ValueError('One of flow_id or version_group_id must be provided')
if flow_id:
inputs = dict(flow_id=flow_id)
else:
inputs = dict(version_group_id=version_group_id)
if (parameters is not None):
inputs.update(parameters=parameters)
if (context is not None):
inputs.update(context=context)
if (idempotency_key is not None):
inputs.update(idempotency_key=idempotency_key)
if (scheduled_start_time is not None):
inputs.update(scheduled_start_time=scheduled_start_time.isoformat())
if (run_name is not None):
inputs.update(flow_run_name=run_name)
res = self.graphql(create_mutation, variables=dict(input=inputs))
return res.data.create_flow_run.id |
def get_flow_run_info(self, flow_run_id: str) -> FlowRunInfoResult:
'\n Retrieves version and current state information for the given flow run.\n\n Args:\n - flow_run_id (str): the id of the flow run to get information for\n\n Returns:\n - GraphQLResult: an object representing information about the flow run\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
query = {'query': {with_args('flow_run_by_pk', {'id': flow_run_id}): {'id': True, 'name': True, 'flow_id': True, 'parameters': True, 'context': True, 'version': True, 'scheduled_start_time': True, 'serialized_state': True, with_args('task_runs', {'where': {'map_index': {'_eq': (- 1)}}}): {'id': True, 'task': {'id': True, 'slug': True}, 'version': True, 'serialized_state': True}}}}
result = self.graphql(query).data.flow_run_by_pk
if (result is None):
raise ClientError('Flow run ID not found: "{}"'.format(flow_run_id))
result.scheduled_start_time = pendulum.parse(result.scheduled_start_time)
result.state = prefect.engine.state.State.deserialize(result.pop('serialized_state'))
task_runs = []
for tr in result.task_runs:
tr.state = prefect.engine.state.State.deserialize(tr.pop('serialized_state'))
task_info = tr.pop('task')
tr.task_id = task_info['id']
tr.task_slug = task_info['slug']
task_runs.append(TaskRunInfoResult(**tr))
result.task_runs = task_runs
result.context = (result.context.to_dict() if (result.context is not None) else None)
result.parameters = (result.parameters.to_dict() if (result.parameters is not None) else None)
return FlowRunInfoResult(**result) | -7,162,629,357,981,999,000 | Retrieves version and current state information for the given flow run.
Args:
- flow_run_id (str): the id of the flow run to get information for
Returns:
- GraphQLResult: an object representing information about the flow run
Raises:
- ClientError: if the GraphQL mutation is bad for any reason | src/prefect/client/client.py | get_flow_run_info | zmac12/prefect | python | def get_flow_run_info(self, flow_run_id: str) -> FlowRunInfoResult:
'\n Retrieves version and current state information for the given flow run.\n\n Args:\n - flow_run_id (str): the id of the flow run to get information for\n\n Returns:\n - GraphQLResult: an object representing information about the flow run\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
query = {'query': {with_args('flow_run_by_pk', {'id': flow_run_id}): {'id': True, 'name': True, 'flow_id': True, 'parameters': True, 'context': True, 'version': True, 'scheduled_start_time': True, 'serialized_state': True, with_args('task_runs', {'where': {'map_index': {'_eq': (- 1)}}}): {'id': True, 'task': {'id': True, 'slug': True}, 'version': True, 'serialized_state': True}}}}
result = self.graphql(query).data.flow_run_by_pk
if (result is None):
raise ClientError('Flow run ID not found: "{}"'.format(flow_run_id))
result.scheduled_start_time = pendulum.parse(result.scheduled_start_time)
result.state = prefect.engine.state.State.deserialize(result.pop('serialized_state'))
task_runs = []
for tr in result.task_runs:
tr.state = prefect.engine.state.State.deserialize(tr.pop('serialized_state'))
task_info = tr.pop('task')
tr.task_id = task_info['id']
tr.task_slug = task_info['slug']
task_runs.append(TaskRunInfoResult(**tr))
result.task_runs = task_runs
result.context = (result.context.to_dict() if (result.context is not None) else None)
result.parameters = (result.parameters.to_dict() if (result.parameters is not None) else None)
return FlowRunInfoResult(**result) |
def update_flow_run_heartbeat(self, flow_run_id: str) -> None:
'\n Convenience method for heartbeating a flow run.\n\n Does NOT raise an error if the update fails.\n\n Args:\n - flow_run_id (str): the flow run ID to heartbeat\n\n '
mutation = {'mutation': {with_args('update_flow_run_heartbeat', {'input': {'flow_run_id': flow_run_id}}): {'success'}}}
self.graphql(mutation, raise_on_error=True) | 6,089,364,651,048,748,000 | Convenience method for heartbeating a flow run.
Does NOT raise an error if the update fails.
Args:
- flow_run_id (str): the flow run ID to heartbeat | src/prefect/client/client.py | update_flow_run_heartbeat | zmac12/prefect | python | def update_flow_run_heartbeat(self, flow_run_id: str) -> None:
'\n Convenience method for heartbeating a flow run.\n\n Does NOT raise an error if the update fails.\n\n Args:\n - flow_run_id (str): the flow run ID to heartbeat\n\n '
mutation = {'mutation': {with_args('update_flow_run_heartbeat', {'input': {'flow_run_id': flow_run_id}}): {'success'}}}
self.graphql(mutation, raise_on_error=True) |
def update_task_run_heartbeat(self, task_run_id: str) -> None:
'\n Convenience method for heartbeating a task run.\n\n Does NOT raise an error if the update fails.\n\n Args:\n - task_run_id (str): the task run ID to heartbeat\n\n '
mutation = {'mutation': {with_args('update_task_run_heartbeat', {'input': {'task_run_id': task_run_id}}): {'success'}}}
self.graphql(mutation, raise_on_error=True) | 7,843,818,405,197,987,000 | Convenience method for heartbeating a task run.
Does NOT raise an error if the update fails.
Args:
- task_run_id (str): the task run ID to heartbeat | src/prefect/client/client.py | update_task_run_heartbeat | zmac12/prefect | python | def update_task_run_heartbeat(self, task_run_id: str) -> None:
'\n Convenience method for heartbeating a task run.\n\n Does NOT raise an error if the update fails.\n\n Args:\n - task_run_id (str): the task run ID to heartbeat\n\n '
mutation = {'mutation': {with_args('update_task_run_heartbeat', {'input': {'task_run_id': task_run_id}}): {'success'}}}
self.graphql(mutation, raise_on_error=True) |
def get_flow_run_state(self, flow_run_id: str) -> 'prefect.engine.state.State':
'\n Retrieves the current state for a flow run.\n\n Args:\n - flow_run_id (str): the id for this flow run\n\n Returns:\n - State: a Prefect State object\n '
query = {'query': {with_args('flow_run_by_pk', {'id': flow_run_id}): {'serialized_state': True}}}
flow_run = self.graphql(query).data.flow_run_by_pk
return prefect.engine.state.State.deserialize(flow_run.serialized_state) | -7,446,695,253,653,859,000 | Retrieves the current state for a flow run.
Args:
- flow_run_id (str): the id for this flow run
Returns:
- State: a Prefect State object | src/prefect/client/client.py | get_flow_run_state | zmac12/prefect | python | def get_flow_run_state(self, flow_run_id: str) -> 'prefect.engine.state.State':
'\n Retrieves the current state for a flow run.\n\n Args:\n - flow_run_id (str): the id for this flow run\n\n Returns:\n - State: a Prefect State object\n '
query = {'query': {with_args('flow_run_by_pk', {'id': flow_run_id}): {'serialized_state': True}}}
flow_run = self.graphql(query).data.flow_run_by_pk
return prefect.engine.state.State.deserialize(flow_run.serialized_state) |
def set_flow_run_state(self, flow_run_id: str, state: 'prefect.engine.state.State', version: int=None) -> 'prefect.engine.state.State':
'\n Sets new state for a flow run in the database.\n\n Args:\n - flow_run_id (str): the id of the flow run to set state for\n - state (State): the new state for this flow run\n - version (int, optional): the current version of the flow run state. This is optional\n but it can be supplied to enforce version-locking.\n\n Returns:\n - State: the state the current flow run should be considered in\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
mutation = {'mutation($input: set_flow_run_states_input!)': {'set_flow_run_states(input: $input)': {'states': {'id', 'status', 'message'}}}}
serialized_state = state.serialize()
result = self.graphql(mutation, variables=dict(input=dict(states=[dict(state=serialized_state, flow_run_id=flow_run_id, version=version)])))
state_payload = result.data.set_flow_run_states.states[0]
if (state_payload.status == 'QUEUED'):
return prefect.engine.state.Queued(message=state_payload.get('message'), start_time=pendulum.now('UTC').add(seconds=prefect.context.config.cloud.queue_interval))
return state | -6,250,182,351,231,868,000 | Sets new state for a flow run in the database.
Args:
- flow_run_id (str): the id of the flow run to set state for
- state (State): the new state for this flow run
- version (int, optional): the current version of the flow run state. This is optional
but it can be supplied to enforce version-locking.
Returns:
- State: the state the current flow run should be considered in
Raises:
- ClientError: if the GraphQL mutation is bad for any reason | src/prefect/client/client.py | set_flow_run_state | zmac12/prefect | python | def set_flow_run_state(self, flow_run_id: str, state: 'prefect.engine.state.State', version: int=None) -> 'prefect.engine.state.State':
'\n Sets new state for a flow run in the database.\n\n Args:\n - flow_run_id (str): the id of the flow run to set state for\n - state (State): the new state for this flow run\n - version (int, optional): the current version of the flow run state. This is optional\n but it can be supplied to enforce version-locking.\n\n Returns:\n - State: the state the current flow run should be considered in\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
mutation = {'mutation($input: set_flow_run_states_input!)': {'set_flow_run_states(input: $input)': {'states': {'id', 'status', 'message'}}}}
serialized_state = state.serialize()
result = self.graphql(mutation, variables=dict(input=dict(states=[dict(state=serialized_state, flow_run_id=flow_run_id, version=version)])))
state_payload = result.data.set_flow_run_states.states[0]
if (state_payload.status == 'QUEUED'):
return prefect.engine.state.Queued(message=state_payload.get('message'), start_time=pendulum.now('UTC').add(seconds=prefect.context.config.cloud.queue_interval))
return state |
def get_latest_cached_states(self, task_id: str, cache_key: Optional[str], created_after: datetime.datetime) -> List['prefect.engine.state.State']:
"\n Pulls all Cached states for the given task that were created after the provided date.\n\n Args:\n - task_id (str): the task id for this task run\n - cache_key (Optional[str]): the cache key for this Task's cache; if `None`, the\n task id alone will be used\n - created_after (datetime.datetime): the earliest date the state should have been\n created at\n\n Returns:\n - List[State]: a list of Cached states created after the given date\n "
args = {'where': {'state': {'_eq': 'Cached'}, 'state_timestamp': {'_gte': created_after.isoformat()}}, 'order_by': {'state_timestamp': EnumValue('desc')}, 'limit': 100}
if (cache_key is not None):
args['where'].update({'cache_key': {'_eq': cache_key}})
else:
args['where'].update({'task_id': {'_eq': task_id}})
query = {'query': {with_args('task_run', args): 'serialized_state'}}
result = self.graphql(query)
deserializer = prefect.engine.state.State.deserialize
valid_states = [deserializer(res.serialized_state) for res in result.data.task_run]
return valid_states | -683,146,956,107,417,100 | Pulls all Cached states for the given task that were created after the provided date.
Args:
- task_id (str): the task id for this task run
- cache_key (Optional[str]): the cache key for this Task's cache; if `None`, the
task id alone will be used
- created_after (datetime.datetime): the earliest date the state should have been
created at
Returns:
- List[State]: a list of Cached states created after the given date | src/prefect/client/client.py | get_latest_cached_states | zmac12/prefect | python | def get_latest_cached_states(self, task_id: str, cache_key: Optional[str], created_after: datetime.datetime) -> List['prefect.engine.state.State']:
"\n Pulls all Cached states for the given task that were created after the provided date.\n\n Args:\n - task_id (str): the task id for this task run\n - cache_key (Optional[str]): the cache key for this Task's cache; if `None`, the\n task id alone will be used\n - created_after (datetime.datetime): the earliest date the state should have been\n created at\n\n Returns:\n - List[State]: a list of Cached states created after the given date\n "
args = {'where': {'state': {'_eq': 'Cached'}, 'state_timestamp': {'_gte': created_after.isoformat()}}, 'order_by': {'state_timestamp': EnumValue('desc')}, 'limit': 100}
if (cache_key is not None):
args['where'].update({'cache_key': {'_eq': cache_key}})
else:
args['where'].update({'task_id': {'_eq': task_id}})
query = {'query': {with_args('task_run', args): 'serialized_state'}}
result = self.graphql(query)
deserializer = prefect.engine.state.State.deserialize
valid_states = [deserializer(res.serialized_state) for res in result.data.task_run]
return valid_states |
def get_task_run_info(self, flow_run_id: str, task_id: str, map_index: Optional[int]=None) -> TaskRunInfoResult:
'\n Retrieves version and current state information for the given task run.\n\n Args:\n - flow_run_id (str): the id of the flow run that this task run lives in\n - task_id (str): the task id for this task run\n - map_index (int, optional): the mapping index for this task run; if\n `None`, it is assumed this task is _not_ mapped\n\n Returns:\n - NamedTuple: a tuple containing `id, task_id, version, state`\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
mutation = {'mutation': {with_args('get_or_create_task_run', {'input': {'flow_run_id': flow_run_id, 'task_id': task_id, 'map_index': ((- 1) if (map_index is None) else map_index)}}): {'id': True}}}
result = self.graphql(mutation)
if (result is None):
raise ClientError('Failed to create task run.')
task_run_id = result.data.get_or_create_task_run.id
query = {'query': {with_args('task_run_by_pk', {'id': task_run_id}): {'version': True, 'serialized_state': True, 'task': {'slug': True}}}}
task_run = self.graphql(query).data.task_run_by_pk
if (task_run is None):
raise ClientError('Task run ID not found: "{}"'.format(task_run_id))
state = prefect.engine.state.State.deserialize(task_run.serialized_state)
return TaskRunInfoResult(id=task_run_id, task_id=task_id, task_slug=task_run.task.slug, version=task_run.version, state=state) | 5,572,389,203,775,407,000 | Retrieves version and current state information for the given task run.
Args:
- flow_run_id (str): the id of the flow run that this task run lives in
- task_id (str): the task id for this task run
- map_index (int, optional): the mapping index for this task run; if
`None`, it is assumed this task is _not_ mapped
Returns:
- NamedTuple: a tuple containing `id, task_id, version, state`
Raises:
- ClientError: if the GraphQL mutation is bad for any reason | src/prefect/client/client.py | get_task_run_info | zmac12/prefect | python | def get_task_run_info(self, flow_run_id: str, task_id: str, map_index: Optional[int]=None) -> TaskRunInfoResult:
'\n Retrieves version and current state information for the given task run.\n\n Args:\n - flow_run_id (str): the id of the flow run that this task run lives in\n - task_id (str): the task id for this task run\n - map_index (int, optional): the mapping index for this task run; if\n `None`, it is assumed this task is _not_ mapped\n\n Returns:\n - NamedTuple: a tuple containing `id, task_id, version, state`\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n '
mutation = {'mutation': {with_args('get_or_create_task_run', {'input': {'flow_run_id': flow_run_id, 'task_id': task_id, 'map_index': ((- 1) if (map_index is None) else map_index)}}): {'id': True}}}
result = self.graphql(mutation)
if (result is None):
raise ClientError('Failed to create task run.')
task_run_id = result.data.get_or_create_task_run.id
query = {'query': {with_args('task_run_by_pk', {'id': task_run_id}): {'version': True, 'serialized_state': True, 'task': {'slug': True}}}}
task_run = self.graphql(query).data.task_run_by_pk
if (task_run is None):
raise ClientError('Task run ID not found: "{}"'.format(task_run_id))
state = prefect.engine.state.State.deserialize(task_run.serialized_state)
return TaskRunInfoResult(id=task_run_id, task_id=task_id, task_slug=task_run.task.slug, version=task_run.version, state=state) |
def set_task_run_name(self, task_run_id: str, name: str) -> bool:
'\n Set the name of a task run\n\n Args:\n - task_run_id (str): the id of a task run\n - name (str): a name for this task run\n\n Returns:\n - bool: whether or not the task run name was updated\n '
mutation = {'mutation($input: set_task_run_name_input!)': {'set_task_run_name(input: $input)': {'success': True}}}
result = self.graphql(mutation, variables=dict(input=dict(task_run_id=task_run_id, name=name)))
return result.data.set_task_run_name.success | -5,408,736,090,355,613,000 | Set the name of a task run
Args:
- task_run_id (str): the id of a task run
- name (str): a name for this task run
Returns:
- bool: whether or not the task run name was updated | src/prefect/client/client.py | set_task_run_name | zmac12/prefect | python | def set_task_run_name(self, task_run_id: str, name: str) -> bool:
'\n Set the name of a task run\n\n Args:\n - task_run_id (str): the id of a task run\n - name (str): a name for this task run\n\n Returns:\n - bool: whether or not the task run name was updated\n '
mutation = {'mutation($input: set_task_run_name_input!)': {'set_task_run_name(input: $input)': {'success': True}}}
result = self.graphql(mutation, variables=dict(input=dict(task_run_id=task_run_id, name=name)))
return result.data.set_task_run_name.success |
def get_task_run_state(self, task_run_id: str) -> 'prefect.engine.state.State':
'\n Retrieves the current state for a task run.\n\n Args:\n - task_run_id (str): the id for this task run\n\n Returns:\n - State: a Prefect State object\n '
query = {'query': {with_args('task_run_by_pk', {'id': task_run_id}): {'serialized_state': True}}}
task_run = self.graphql(query).data.task_run_by_pk
return prefect.engine.state.State.deserialize(task_run.serialized_state) | -7,783,051,125,377,341,000 | Retrieves the current state for a task run.
Args:
- task_run_id (str): the id for this task run
Returns:
- State: a Prefect State object | src/prefect/client/client.py | get_task_run_state | zmac12/prefect | python | def get_task_run_state(self, task_run_id: str) -> 'prefect.engine.state.State':
'\n Retrieves the current state for a task run.\n\n Args:\n - task_run_id (str): the id for this task run\n\n Returns:\n - State: a Prefect State object\n '
query = {'query': {with_args('task_run_by_pk', {'id': task_run_id}): {'serialized_state': True}}}
task_run = self.graphql(query).data.task_run_by_pk
return prefect.engine.state.State.deserialize(task_run.serialized_state) |
def set_task_run_state(self, task_run_id: str, state: 'prefect.engine.state.State', version: int=None, cache_for: datetime.timedelta=None) -> 'prefect.engine.state.State':
'\n Sets new state for a task run.\n\n Args:\n - task_run_id (str): the id of the task run to set state for\n - state (State): the new state for this task run\n - version (int, optional): the current version of the task run state. This is optional\n but it can be supplied to enforce version-locking.\n - cache_for (timedelta, optional): how long to store the result of this task for,\n using the serializer set in config; if not provided, no caching occurs\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n\n Returns:\n - State: the state the current task run should be considered in\n '
mutation = {'mutation($input: set_task_run_states_input!)': {'set_task_run_states(input: $input)': {'states': {'id', 'status', 'message'}}}}
serialized_state = state.serialize()
result = self.graphql(mutation, variables=dict(input=dict(states=[dict(state=serialized_state, task_run_id=task_run_id, version=version)])))
state_payload = result.data.set_task_run_states.states[0]
if (state_payload.status == 'QUEUED'):
return prefect.engine.state.Queued(message=state_payload.get('message'), start_time=pendulum.now('UTC').add(seconds=prefect.context.config.cloud.queue_interval))
return state | 7,802,373,459,408,090,000 | Sets new state for a task run.
Args:
- task_run_id (str): the id of the task run to set state for
- state (State): the new state for this task run
- version (int, optional): the current version of the task run state. This is optional
but it can be supplied to enforce version-locking.
- cache_for (timedelta, optional): how long to store the result of this task for,
using the serializer set in config; if not provided, no caching occurs
Raises:
- ClientError: if the GraphQL mutation is bad for any reason
Returns:
- State: the state the current task run should be considered in | src/prefect/client/client.py | set_task_run_state | zmac12/prefect | python | def set_task_run_state(self, task_run_id: str, state: 'prefect.engine.state.State', version: int=None, cache_for: datetime.timedelta=None) -> 'prefect.engine.state.State':
'\n Sets new state for a task run.\n\n Args:\n - task_run_id (str): the id of the task run to set state for\n - state (State): the new state for this task run\n - version (int, optional): the current version of the task run state. This is optional\n but it can be supplied to enforce version-locking.\n - cache_for (timedelta, optional): how long to store the result of this task for,\n using the serializer set in config; if not provided, no caching occurs\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n\n Returns:\n - State: the state the current task run should be considered in\n '
mutation = {'mutation($input: set_task_run_states_input!)': {'set_task_run_states(input: $input)': {'states': {'id', 'status', 'message'}}}}
serialized_state = state.serialize()
result = self.graphql(mutation, variables=dict(input=dict(states=[dict(state=serialized_state, task_run_id=task_run_id, version=version)])))
state_payload = result.data.set_task_run_states.states[0]
if (state_payload.status == 'QUEUED'):
return prefect.engine.state.Queued(message=state_payload.get('message'), start_time=pendulum.now('UTC').add(seconds=prefect.context.config.cloud.queue_interval))
return state |
def set_secret(self, name: str, value: Any) -> None:
'\n Set a secret with the given name and value.\n\n Args:\n - name (str): the name of the secret; used for retrieving the secret\n during task runs\n - value (Any): the value of the secret\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the secret-setting was unsuccessful\n '
mutation = {'mutation($input: set_secret_input!)': {'set_secret(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(name=name, value=value)))
if (not result.data.set_secret.success):
raise ValueError('Setting secret failed.') | -493,880,310,508,623,550 | Set a secret with the given name and value.
Args:
- name (str): the name of the secret; used for retrieving the secret
during task runs
- value (Any): the value of the secret
Raises:
- ClientError: if the GraphQL mutation is bad for any reason
- ValueError: if the secret-setting was unsuccessful | src/prefect/client/client.py | set_secret | zmac12/prefect | python | def set_secret(self, name: str, value: Any) -> None:
'\n Set a secret with the given name and value.\n\n Args:\n - name (str): the name of the secret; used for retrieving the secret\n during task runs\n - value (Any): the value of the secret\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the secret-setting was unsuccessful\n '
mutation = {'mutation($input: set_secret_input!)': {'set_secret(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(name=name, value=value)))
if (not result.data.set_secret.success):
raise ValueError('Setting secret failed.') |
def get_task_tag_limit(self, tag: str) -> Optional[int]:
'\n Retrieve the current task tag concurrency limit for a given tag.\n\n Args:\n - tag (str): the tag to update\n\n Raises:\n - ClientError: if the GraphQL query fails\n '
query = {'query': {with_args('task_tag_limit', {'where': {'tag': {'_eq': tag}}}): {'limit': True}}}
result = self.graphql(query)
if result.data.task_tag_limit:
return result.data.task_tag_limit[0].limit
else:
return None | -1,634,685,958,949,177,300 | Retrieve the current task tag concurrency limit for a given tag.
Args:
- tag (str): the tag to update
Raises:
- ClientError: if the GraphQL query fails | src/prefect/client/client.py | get_task_tag_limit | zmac12/prefect | python | def get_task_tag_limit(self, tag: str) -> Optional[int]:
'\n Retrieve the current task tag concurrency limit for a given tag.\n\n Args:\n - tag (str): the tag to update\n\n Raises:\n - ClientError: if the GraphQL query fails\n '
query = {'query': {with_args('task_tag_limit', {'where': {'tag': {'_eq': tag}}}): {'limit': True}}}
result = self.graphql(query)
if result.data.task_tag_limit:
return result.data.task_tag_limit[0].limit
else:
return None |
def update_task_tag_limit(self, tag: str, limit: int) -> None:
'\n Update the task tag concurrency limit for a given tag; requires tenant admin permissions.\n\n Args:\n - tag (str): the tag to update\n - limit (int): the concurrency limit to enforce on the tag; should be a value >= 0\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the tag limit-setting was unsuccessful, or if a bad limit was provided\n '
if (limit < 0):
raise ValueError('Concurrency limits must be >= 0')
mutation = {'mutation($input: update_task_tag_limit_input!)': {'update_task_tag_limit(input: $input)': {'id'}}}
result = self.graphql(mutation, variables=dict(input=dict(tag=tag, limit=limit)))
if (not result.data.update_task_tag_limit.id):
raise ValueError('Updating the task tag concurrency limit failed.') | 5,336,804,441,202,090,000 | Update the task tag concurrency limit for a given tag; requires tenant admin permissions.
Args:
- tag (str): the tag to update
- limit (int): the concurrency limit to enforce on the tag; should be a value >= 0
Raises:
- ClientError: if the GraphQL mutation is bad for any reason
- ValueError: if the tag limit-setting was unsuccessful, or if a bad limit was provided | src/prefect/client/client.py | update_task_tag_limit | zmac12/prefect | python | def update_task_tag_limit(self, tag: str, limit: int) -> None:
'\n Update the task tag concurrency limit for a given tag; requires tenant admin permissions.\n\n Args:\n - tag (str): the tag to update\n - limit (int): the concurrency limit to enforce on the tag; should be a value >= 0\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the tag limit-setting was unsuccessful, or if a bad limit was provided\n '
if (limit < 0):
raise ValueError('Concurrency limits must be >= 0')
mutation = {'mutation($input: update_task_tag_limit_input!)': {'update_task_tag_limit(input: $input)': {'id'}}}
result = self.graphql(mutation, variables=dict(input=dict(tag=tag, limit=limit)))
if (not result.data.update_task_tag_limit.id):
raise ValueError('Updating the task tag concurrency limit failed.') |
def delete_task_tag_limit(self, limit_id: str) -> None:
'\n Deletes a given task tag concurrency limit; requires tenant admin permissions.\n\n Args:\n - limit_id (str): the ID of the tag to delete\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the tag deletion was unsuccessful, or if a bad tag ID was provided\n '
mutation = {'mutation($input: delete_task_tag_limit_input!)': {'delete_task_tag_limit(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(limit_id=limit_id)))
if (not result.data.delete_task_tag_limit.success):
raise ValueError('Deleting the task tag concurrency limit failed.') | -925,700,551,522,546,800 | Deletes a given task tag concurrency limit; requires tenant admin permissions.
Args:
- limit_id (str): the ID of the tag to delete
Raises:
- ClientError: if the GraphQL mutation is bad for any reason
- ValueError: if the tag deletion was unsuccessful, or if a bad tag ID was provided | src/prefect/client/client.py | delete_task_tag_limit | zmac12/prefect | python | def delete_task_tag_limit(self, limit_id: str) -> None:
'\n Deletes a given task tag concurrency limit; requires tenant admin permissions.\n\n Args:\n - limit_id (str): the ID of the tag to delete\n\n Raises:\n - ClientError: if the GraphQL mutation is bad for any reason\n - ValueError: if the tag deletion was unsuccessful, or if a bad tag ID was provided\n '
mutation = {'mutation($input: delete_task_tag_limit_input!)': {'delete_task_tag_limit(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(limit_id=limit_id)))
if (not result.data.delete_task_tag_limit.success):
raise ValueError('Deleting the task tag concurrency limit failed.') |
def write_run_logs(self, logs: List[Dict]) -> None:
'\n Uploads a collection of logs to Cloud.\n\n Args:\n - logs (List[Dict]): a list of log entries to add\n\n Raises:\n - ValueError: if uploading the logs fail\n '
mutation = {'mutation($input: write_run_logs_input!)': {'write_run_logs(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(logs=logs)))
if (not result.data.write_run_logs.success):
raise ValueError('Writing logs failed.') | 5,444,238,842,283,366,000 | Uploads a collection of logs to Cloud.
Args:
- logs (List[Dict]): a list of log entries to add
Raises:
- ValueError: if uploading the logs fail | src/prefect/client/client.py | write_run_logs | zmac12/prefect | python | def write_run_logs(self, logs: List[Dict]) -> None:
'\n Uploads a collection of logs to Cloud.\n\n Args:\n - logs (List[Dict]): a list of log entries to add\n\n Raises:\n - ValueError: if uploading the logs fail\n '
mutation = {'mutation($input: write_run_logs_input!)': {'write_run_logs(input: $input)': {'success'}}}
result = self.graphql(mutation, variables=dict(input=dict(logs=logs)))
if (not result.data.write_run_logs.success):
raise ValueError('Writing logs failed.') |
def register_agent(self, agent_type: str, name: str=None, labels: List[str]=None, agent_config_id: str=None) -> str:
'\n Register an agent with a backend API\n\n Args:\n - agent_type (str): The type of agent being registered\n - name: (str, optional): The name of the agent being registered\n - labels (List[str], optional): A list of any present labels on the agent\n being registered\n - agent_config_id (str, optional): The ID of an agent configuration to register with\n\n Returns:\n - The agent ID as a string\n '
mutation = {'mutation($input: register_agent_input!)': {'register_agent(input: $input)': {'id'}}}
result = self.graphql(mutation, variables=dict(input=dict(type=agent_type, name=name, labels=(labels or []), tenant_id=self._active_tenant_id, agent_config_id=agent_config_id)))
if (not result.data.register_agent.id):
raise ValueError('Error registering agent')
return result.data.register_agent.id | -199,111,105,601,504,480 | Register an agent with a backend API
Args:
- agent_type (str): The type of agent being registered
- name: (str, optional): The name of the agent being registered
- labels (List[str], optional): A list of any present labels on the agent
being registered
- agent_config_id (str, optional): The ID of an agent configuration to register with
Returns:
- The agent ID as a string | src/prefect/client/client.py | register_agent | zmac12/prefect | python | def register_agent(self, agent_type: str, name: str=None, labels: List[str]=None, agent_config_id: str=None) -> str:
'\n Register an agent with a backend API\n\n Args:\n - agent_type (str): The type of agent being registered\n - name: (str, optional): The name of the agent being registered\n - labels (List[str], optional): A list of any present labels on the agent\n being registered\n - agent_config_id (str, optional): The ID of an agent configuration to register with\n\n Returns:\n - The agent ID as a string\n '
mutation = {'mutation($input: register_agent_input!)': {'register_agent(input: $input)': {'id'}}}
result = self.graphql(mutation, variables=dict(input=dict(type=agent_type, name=name, labels=(labels or []), tenant_id=self._active_tenant_id, agent_config_id=agent_config_id)))
if (not result.data.register_agent.id):
raise ValueError('Error registering agent')
return result.data.register_agent.id |
def get_agent_config(self, agent_config_id: str) -> dict:
"\n Get agent config settings\n\n Args:\n - agent_config_id (str): The ID of an agent configuration to retrieve\n\n Returns:\n - dict: the agent configuration's `settings`\n "
query = {'query': {with_args('agent_config', {'where': {'id': {'_eq': agent_config_id}}}): {'settings': True}}}
result = self.graphql(query)
return result.data.agent_config[0].settings | 209,077,097,488,946,200 | Get agent config settings
Args:
- agent_config_id (str): The ID of an agent configuration to retrieve
Returns:
- dict: the agent configuration's `settings` | src/prefect/client/client.py | get_agent_config | zmac12/prefect | python | def get_agent_config(self, agent_config_id: str) -> dict:
"\n Get agent config settings\n\n Args:\n - agent_config_id (str): The ID of an agent configuration to retrieve\n\n Returns:\n - dict: the agent configuration's `settings`\n "
query = {'query': {with_args('agent_config', {'where': {'id': {'_eq': agent_config_id}}}): {'settings': True}}}
result = self.graphql(query)
return result.data.agent_config[0].settings |
def initialize(self, tank_capacity, inputs, outputs, water_level):
'\n Initializes the simulation with the specified data.\n @param tank_capacity Capacity of the water tank, in liters.\n @param Array containing the flow volume of the inputs (such as water pumps), in liters per second. \n The flow can be modified dynamically, but no inputs can be added. \n @param Array containing the outputs (such as a water hose or evaporation), in liters per second. \n The flow can be modified dynamically, but no inputs can be added.\n @param water_level The starting water level. Value from 0 to 1.\n '
self.tank_capacity = tank_capacity
self.inputs = inputs
self.outputs = outputs
self.current_volume = (water_level * tank_capacity)
self.firstPumpTemperature = 20
self.secondPumpTemperature = 20
self.firstPumpWorkRange = [20, 200]
self.secondPumpWorkRange = [20, 200]
self.pumpTemperatureVariationPerSeconds = 6
self.simlock = threading.RLock()
self._thread = None
self._autoupdating = False
self._autoupdating_interval = 1000 | 5,134,381,525,889,772,000 | Initializes the simulation with the specified data.
@param tank_capacity Capacity of the water tank, in liters.
@param Array containing the flow volume of the inputs (such as water pumps), in liters per second.
The flow can be modified dynamically, but no inputs can be added.
@param Array containing the outputs (such as a water hose or evaporation), in liters per second.
The flow can be modified dynamically, but no inputs can be added.
@param water_level The starting water level. Value from 0 to 1. | server/src/experiments/ud_xilinx/watertank_simulation.py | initialize | LR-FGMM/weblabdeusto | python | def initialize(self, tank_capacity, inputs, outputs, water_level):
'\n Initializes the simulation with the specified data.\n @param tank_capacity Capacity of the water tank, in liters.\n @param Array containing the flow volume of the inputs (such as water pumps), in liters per second. \n The flow can be modified dynamically, but no inputs can be added. \n @param Array containing the outputs (such as a water hose or evaporation), in liters per second. \n The flow can be modified dynamically, but no inputs can be added.\n @param water_level The starting water level. Value from 0 to 1.\n '
self.tank_capacity = tank_capacity
self.inputs = inputs
self.outputs = outputs
self.current_volume = (water_level * tank_capacity)
self.firstPumpTemperature = 20
self.secondPumpTemperature = 20
self.firstPumpWorkRange = [20, 200]
self.secondPumpWorkRange = [20, 200]
self.pumpTemperatureVariationPerSeconds = 6
self.simlock = threading.RLock()
self._thread = None
self._autoupdating = False
self._autoupdating_interval = 1000 |
def update(self, delta):
'\n Updates the simulation. Can be done automatically if the autoupdater is used.\n @param delta Delta in seconds.\n @see autoupdater_start\n '
total_output = 0
for out in self.outputs:
total_output += (out * delta)
total_input = 0
(pump1, pump2) = self.inputs
if (pump1 > 0):
self.firstPumpTemperature += ((delta * self.pumpTemperatureVariationPerSeconds) * 1.1)
total_input += (pump1 * delta)
else:
self.firstPumpTemperature -= (delta * self.pumpTemperatureVariationPerSeconds)
self.firstPumpTemperature = max(20, self.firstPumpTemperature)
total_input -= (pump1 * delta)
if (pump2 > 0):
self.secondPumpTemperature += (delta * self.pumpTemperatureVariationPerSeconds)
total_input += (pump2 * delta)
else:
self.secondPumpTemperature -= (delta * self.pumpTemperatureVariationPerSeconds)
self.secondPumpTemperature = max(20, self.secondPumpTemperature)
total_input -= (pump2 * delta)
increment = (total_input - total_output)
with self.simlock:
self.current_volume += increment
if (self.current_volume >= self.tank_capacity):
self.current_volume = self.tank_capacity
elif (self.current_volume < 0):
self.current_volume = 0.0 | 7,955,144,620,373,460,000 | Updates the simulation. Can be done automatically if the autoupdater is used.
@param delta Delta in seconds.
@see autoupdater_start | server/src/experiments/ud_xilinx/watertank_simulation.py | update | LR-FGMM/weblabdeusto | python | def update(self, delta):
'\n Updates the simulation. Can be done automatically if the autoupdater is used.\n @param delta Delta in seconds.\n @see autoupdater_start\n '
total_output = 0
for out in self.outputs:
total_output += (out * delta)
total_input = 0
(pump1, pump2) = self.inputs
if (pump1 > 0):
self.firstPumpTemperature += ((delta * self.pumpTemperatureVariationPerSeconds) * 1.1)
total_input += (pump1 * delta)
else:
self.firstPumpTemperature -= (delta * self.pumpTemperatureVariationPerSeconds)
self.firstPumpTemperature = max(20, self.firstPumpTemperature)
total_input -= (pump1 * delta)
if (pump2 > 0):
self.secondPumpTemperature += (delta * self.pumpTemperatureVariationPerSeconds)
total_input += (pump2 * delta)
else:
self.secondPumpTemperature -= (delta * self.pumpTemperatureVariationPerSeconds)
self.secondPumpTemperature = max(20, self.secondPumpTemperature)
total_input -= (pump2 * delta)
increment = (total_input - total_output)
with self.simlock:
self.current_volume += increment
if (self.current_volume >= self.tank_capacity):
self.current_volume = self.tank_capacity
elif (self.current_volume < 0):
self.current_volume = 0.0 |
def t_updater(self):
'\n This internal method is used by the autoupdating thread to update\n the simulation every few seconds (specified as the autoupdater interval).\n '
while self._autoupdating:
time.sleep(self._autoupdating_interval)
self.update(self._autoupdating_interval) | -6,640,372,441,248,582,000 | This internal method is used by the autoupdating thread to update
the simulation every few seconds (specified as the autoupdater interval). | server/src/experiments/ud_xilinx/watertank_simulation.py | t_updater | LR-FGMM/weblabdeusto | python | def t_updater(self):
'\n This internal method is used by the autoupdating thread to update\n the simulation every few seconds (specified as the autoupdater interval).\n '
while self._autoupdating:
time.sleep(self._autoupdating_interval)
self.update(self._autoupdating_interval) |
def autoupdater_start(self, interval):
'\n Starts the autoupdating thread. That is, a thread that will call update\n every so often. If started, it should eventually be stopped. Otherwise,\n it will run forever in the background.\n @param interval Interval between updates, in seconds.\n @see autoupdater_stop\n '
self._autoupdating = True
self._autoupdating_interval = interval
self._thread = threading.Thread(None, self.t_updater)
self._thread.start() | -5,620,668,677,739,745,000 | Starts the autoupdating thread. That is, a thread that will call update
every so often. If started, it should eventually be stopped. Otherwise,
it will run forever in the background.
@param interval Interval between updates, in seconds.
@see autoupdater_stop | server/src/experiments/ud_xilinx/watertank_simulation.py | autoupdater_start | LR-FGMM/weblabdeusto | python | def autoupdater_start(self, interval):
'\n Starts the autoupdating thread. That is, a thread that will call update\n every so often. If started, it should eventually be stopped. Otherwise,\n it will run forever in the background.\n @param interval Interval between updates, in seconds.\n @see autoupdater_stop\n '
self._autoupdating = True
self._autoupdating_interval = interval
self._thread = threading.Thread(None, self.t_updater)
self._thread.start() |
def autoupdater_stop(self):
'\n Stops the autoupdating thread. This method is non-blocking. It will signal\n the thread to stop, but may take a while before it *really* does stop.\n There is a blocking version of this method.\n @see autoupdater_join\n '
self._autoupdating = False | -3,828,925,256,979,739,000 | Stops the autoupdating thread. This method is non-blocking. It will signal
the thread to stop, but may take a while before it *really* does stop.
There is a blocking version of this method.
@see autoupdater_join | server/src/experiments/ud_xilinx/watertank_simulation.py | autoupdater_stop | LR-FGMM/weblabdeusto | python | def autoupdater_stop(self):
'\n Stops the autoupdating thread. This method is non-blocking. It will signal\n the thread to stop, but may take a while before it *really* does stop.\n There is a blocking version of this method.\n @see autoupdater_join\n '
self._autoupdating = False |
def autoupdater_join(self):
"\n Stops the autoupdating thread, and joins that thread until it really does stop.\n May block forever if for some reason the thread won't stop, but that\n should not happen.\n "
self._autoupdating = False
self._thread.join(0) | -1,852,508,963,353,255,200 | Stops the autoupdating thread, and joins that thread until it really does stop.
May block forever if for some reason the thread won't stop, but that
should not happen. | server/src/experiments/ud_xilinx/watertank_simulation.py | autoupdater_join | LR-FGMM/weblabdeusto | python | def autoupdater_join(self):
"\n Stops the autoupdating thread, and joins that thread until it really does stop.\n May block forever if for some reason the thread won't stop, but that\n should not happen.\n "
self._autoupdating = False
self._thread.join(0) |
def set_input(self, input_number, input_flow):
'\n Sets the value for an input in the simulation. \n @param input_number Number identifying the input. The input should exist.\n @param input_flow New flow of the input, in liters per second.\n '
with self.simlock:
self.inputs[input_number] = input_flow | -6,037,607,105,013,283,000 | Sets the value for an input in the simulation.
@param input_number Number identifying the input. The input should exist.
@param input_flow New flow of the input, in liters per second. | server/src/experiments/ud_xilinx/watertank_simulation.py | set_input | LR-FGMM/weblabdeusto | python | def set_input(self, input_number, input_flow):
'\n Sets the value for an input in the simulation. \n @param input_number Number identifying the input. The input should exist.\n @param input_flow New flow of the input, in liters per second.\n '
with self.simlock:
self.inputs[input_number] = input_flow |
def set_output(self, output_number, output_flow):
'\n Sets the value for an output in the simulation.\n @param output_number Number identifying the output. The output should exist.\n @param output_flow New flow of the output, in liters per second.\n '
with self.simlock:
self.outputs[output_number] = output_flow | 8,023,729,128,761,339,000 | Sets the value for an output in the simulation.
@param output_number Number identifying the output. The output should exist.
@param output_flow New flow of the output, in liters per second. | server/src/experiments/ud_xilinx/watertank_simulation.py | set_output | LR-FGMM/weblabdeusto | python | def set_output(self, output_number, output_flow):
'\n Sets the value for an output in the simulation.\n @param output_number Number identifying the output. The output should exist.\n @param output_flow New flow of the output, in liters per second.\n '
with self.simlock:
self.outputs[output_number] = output_flow |
def set_inputs(self, inputs):
'\n Redefines the whole array of inputs.\n @param inputs Array containing the flow of every input.\n '
with self.simlock:
self.inputs = inputs | -5,571,642,313,052,897,000 | Redefines the whole array of inputs.
@param inputs Array containing the flow of every input. | server/src/experiments/ud_xilinx/watertank_simulation.py | set_inputs | LR-FGMM/weblabdeusto | python | def set_inputs(self, inputs):
'\n Redefines the whole array of inputs.\n @param inputs Array containing the flow of every input.\n '
with self.simlock:
self.inputs = inputs |
def set_outputs(self, outputs):
'\n Redefines the whole array of outputs.\n @param outputs Array containing the flow of every output.\n '
with self.simlock:
self.outputs = outputs | -8,458,866,352,859,930,000 | Redefines the whole array of outputs.
@param outputs Array containing the flow of every output. | server/src/experiments/ud_xilinx/watertank_simulation.py | set_outputs | LR-FGMM/weblabdeusto | python | def set_outputs(self, outputs):
'\n Redefines the whole array of outputs.\n @param outputs Array containing the flow of every output.\n '
with self.simlock:
self.outputs = outputs |
def get_temperatures(self):
'\n Get temperatures.\n :return:\n '
return [self.firstPumpTemperature, self.secondPumpTemperature] | -5,976,381,320,454,369,000 | Get temperatures.
:return: | server/src/experiments/ud_xilinx/watertank_simulation.py | get_temperatures | LR-FGMM/weblabdeusto | python | def get_temperatures(self):
'\n Get temperatures.\n :return:\n '
return [self.firstPumpTemperature, self.secondPumpTemperature] |
def get_water_volume(self):
"\n Gets the current water volume in liters. It will vary dynamically according to the \n simulation's state.\n "
with self.simlock:
return self.current_volume | -3,104,628,016,230,668,300 | Gets the current water volume in liters. It will vary dynamically according to the
simulation's state. | server/src/experiments/ud_xilinx/watertank_simulation.py | get_water_volume | LR-FGMM/weblabdeusto | python | def get_water_volume(self):
"\n Gets the current water volume in liters. It will vary dynamically according to the \n simulation's state.\n "
with self.simlock:
return self.current_volume |
def get_water_level(self):
"\n Gets the current water level, as a number from 0 to 1 (empty to full). It will vary dynamically\n according to the simulation's state.\n "
with self.simlock:
return ((1.0 * self.current_volume) / self.tank_capacity) | 964,212,182,402,237,200 | Gets the current water level, as a number from 0 to 1 (empty to full). It will vary dynamically
according to the simulation's state. | server/src/experiments/ud_xilinx/watertank_simulation.py | get_water_level | LR-FGMM/weblabdeusto | python | def get_water_level(self):
"\n Gets the current water level, as a number from 0 to 1 (empty to full). It will vary dynamically\n according to the simulation's state.\n "
with self.simlock:
return ((1.0 * self.current_volume) / self.tank_capacity) |
def get_json_state(self, input_capacities, output_capacities):
"\n Gets a json-encoded description of the simulation's state. \n As of now, it takes output and input capacities as arguments because the JSON state\n is described through relative values. (For instance, first output at 0.3 capacity).\n \n @param input_capacities An array containing the maximum capacities of the input.\n @param output_capacities An array containing the maximum capacities of the output.\n "
if (len(self.inputs) != len(input_capacities)):
return '{}'
inputs = []
for (inp, cap) in zip(self.inputs, input_capacities):
inputs.append(((1.0 * inp) / cap))
outputs = []
for (inp, cap) in zip(self.outputs, output_capacities):
outputs.append(((1.0 * inp) / cap))
state = {'water': self.get_water_level(), 'inputs': inputs, 'outputs': outputs}
temperatures = [0, 0]
temperatures[0] = self.firstPumpTemperature
temperatures[1] = self.secondPumpTemperature
state['temperatures'] = temperatures
return json.dumps(state) | -4,236,027,061,501,498,000 | Gets a json-encoded description of the simulation's state.
As of now, it takes output and input capacities as arguments because the JSON state
is described through relative values. (For instance, first output at 0.3 capacity).
@param input_capacities An array containing the maximum capacities of the input.
@param output_capacities An array containing the maximum capacities of the output. | server/src/experiments/ud_xilinx/watertank_simulation.py | get_json_state | LR-FGMM/weblabdeusto | python | def get_json_state(self, input_capacities, output_capacities):
"\n Gets a json-encoded description of the simulation's state. \n As of now, it takes output and input capacities as arguments because the JSON state\n is described through relative values. (For instance, first output at 0.3 capacity).\n \n @param input_capacities An array containing the maximum capacities of the input.\n @param output_capacities An array containing the maximum capacities of the output.\n "
if (len(self.inputs) != len(input_capacities)):
return '{}'
inputs = []
for (inp, cap) in zip(self.inputs, input_capacities):
inputs.append(((1.0 * inp) / cap))
outputs = []
for (inp, cap) in zip(self.outputs, output_capacities):
outputs.append(((1.0 * inp) / cap))
state = {'water': self.get_water_level(), 'inputs': inputs, 'outputs': outputs}
temperatures = [0, 0]
temperatures[0] = self.firstPumpTemperature
temperatures[1] = self.secondPumpTemperature
state['temperatures'] = temperatures
return json.dumps(state) |
def add_new_user_history(user_profile: UserProfile, streams: Iterable[Stream]) -> None:
'Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public\n streams, so you have something to look at in your home view once\n you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES\n are marked unread.\n '
one_week_ago = (timezone_now() - datetime.timedelta(weeks=1))
recipient_ids = [stream.recipient_id for stream in streams if (not stream.invite_only)]
recent_messages = Message.objects.filter(recipient_id__in=recipient_ids, date_sent__gt=one_week_ago).order_by('-id')
message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:ONBOARDING_TOTAL_MESSAGES]))
if (len(message_ids_to_use) == 0):
return
already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use, user_profile=user_profile).values_list('message_id', flat=True))
marked_unread = 0
ums_to_create = []
for message_id in reversed(message_ids_to_use):
if (message_id in already_ids):
continue
um = UserMessage(user_profile=user_profile, message_id=message_id)
if (marked_unread < ONBOARDING_UNREAD_MESSAGES):
marked_unread += 1
else:
um.flags = UserMessage.flags.read
ums_to_create.append(um)
UserMessage.objects.bulk_create(reversed(ums_to_create)) | 4,170,579,497,540,251,000 | Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public
streams, so you have something to look at in your home view once
you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES
are marked unread. | zerver/lib/actions.py | add_new_user_history | gutalavijay1111/zulip-vijay | python | def add_new_user_history(user_profile: UserProfile, streams: Iterable[Stream]) -> None:
'Give you the last ONBOARDING_TOTAL_MESSAGES messages on your public\n streams, so you have something to look at in your home view once\n you finish the tutorial. The most recent ONBOARDING_UNREAD_MESSAGES\n are marked unread.\n '
one_week_ago = (timezone_now() - datetime.timedelta(weeks=1))
recipient_ids = [stream.recipient_id for stream in streams if (not stream.invite_only)]
recent_messages = Message.objects.filter(recipient_id__in=recipient_ids, date_sent__gt=one_week_ago).order_by('-id')
message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:ONBOARDING_TOTAL_MESSAGES]))
if (len(message_ids_to_use) == 0):
return
already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use, user_profile=user_profile).values_list('message_id', flat=True))
marked_unread = 0
ums_to_create = []
for message_id in reversed(message_ids_to_use):
if (message_id in already_ids):
continue
um = UserMessage(user_profile=user_profile, message_id=message_id)
if (marked_unread < ONBOARDING_UNREAD_MESSAGES):
marked_unread += 1
else:
um.flags = UserMessage.flags.read
ums_to_create.append(um)
UserMessage.objects.bulk_create(reversed(ums_to_create)) |
def do_set_realm_property(realm: Realm, name: str, value: Any, acting_user: Optional[UserProfile]=None) -> None:
'Takes in a realm object, the name of an attribute to update, the\n value to update and and the user who initiated the update.\n '
property_type = Realm.property_types[name]
assert isinstance(value, property_type), f'Cannot update {name}: {value} is not an instance of {property_type}'
old_value = getattr(realm, name)
setattr(realm, name, value)
realm.save(update_fields=[name])
event = dict(type='realm', op='update', property=name, value=value)
send_event(realm, event, active_user_ids(realm.id))
event_time = timezone_now()
RealmAuditLog.objects.create(realm=realm, event_type=RealmAuditLog.REALM_PROPERTY_CHANGED, event_time=event_time, acting_user=acting_user, extra_data=ujson.dumps({RealmAuditLog.OLD_VALUE: {'property': name, 'value': old_value}, RealmAuditLog.NEW_VALUE: {'property': name, 'value': value}}))
if (name == 'email_address_visibility'):
if (Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE not in [old_value, value]):
return
user_profiles = UserProfile.objects.filter(realm=realm, is_bot=False)
for user_profile in user_profiles:
user_profile.email = get_display_email_address(user_profile, realm)
send_user_email_update_event(user_profile)
UserProfile.objects.bulk_update(user_profiles, ['email'])
for user_profile in user_profiles:
flush_user_profile(sender=UserProfile, instance=user_profile) | 7,533,641,336,225,873,000 | Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update. | zerver/lib/actions.py | do_set_realm_property | gutalavijay1111/zulip-vijay | python | def do_set_realm_property(realm: Realm, name: str, value: Any, acting_user: Optional[UserProfile]=None) -> None:
'Takes in a realm object, the name of an attribute to update, the\n value to update and and the user who initiated the update.\n '
property_type = Realm.property_types[name]
assert isinstance(value, property_type), f'Cannot update {name}: {value} is not an instance of {property_type}'
old_value = getattr(realm, name)
setattr(realm, name, value)
realm.save(update_fields=[name])
event = dict(type='realm', op='update', property=name, value=value)
send_event(realm, event, active_user_ids(realm.id))
event_time = timezone_now()
RealmAuditLog.objects.create(realm=realm, event_type=RealmAuditLog.REALM_PROPERTY_CHANGED, event_time=event_time, acting_user=acting_user, extra_data=ujson.dumps({RealmAuditLog.OLD_VALUE: {'property': name, 'value': old_value}, RealmAuditLog.NEW_VALUE: {'property': name, 'value': value}}))
if (name == 'email_address_visibility'):
if (Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE not in [old_value, value]):
return
user_profiles = UserProfile.objects.filter(realm=realm, is_bot=False)
for user_profile in user_profiles:
user_profile.email = get_display_email_address(user_profile, realm)
send_user_email_update_event(user_profile)
UserProfile.objects.bulk_update(user_profiles, ['email'])
for user_profile in user_profiles:
flush_user_profile(sender=UserProfile, instance=user_profile) |
def do_deactivate_realm(realm: Realm, acting_user: Optional[UserProfile]=None) -> None:
"\n Deactivate this realm. Do NOT deactivate the users -- we need to be able to\n tell the difference between users that were intentionally deactivated,\n e.g. by a realm admin, and users who can't currently use Zulip because their\n realm has been deactivated.\n "
if realm.deactivated:
return
realm.deactivated = True
realm.save(update_fields=['deactivated'])
if settings.BILLING_ENABLED:
downgrade_now(realm)
event_time = timezone_now()
RealmAuditLog.objects.create(realm=realm, event_type=RealmAuditLog.REALM_DEACTIVATED, event_time=event_time, acting_user=acting_user, extra_data=ujson.dumps({RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(realm)}))
ScheduledEmail.objects.filter(realm=realm).delete()
for user in active_humans_in_realm(realm):
delete_user_sessions(user)
event = dict(type='realm', op='deactivated', realm_id=realm.id)
send_event(realm, event, active_user_ids(realm.id)) | -3,333,272,059,511,270,000 | Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip because their
realm has been deactivated. | zerver/lib/actions.py | do_deactivate_realm | gutalavijay1111/zulip-vijay | python | def do_deactivate_realm(realm: Realm, acting_user: Optional[UserProfile]=None) -> None:
"\n Deactivate this realm. Do NOT deactivate the users -- we need to be able to\n tell the difference between users that were intentionally deactivated,\n e.g. by a realm admin, and users who can't currently use Zulip because their\n realm has been deactivated.\n "
if realm.deactivated:
return
realm.deactivated = True
realm.save(update_fields=['deactivated'])
if settings.BILLING_ENABLED:
downgrade_now(realm)
event_time = timezone_now()
RealmAuditLog.objects.create(realm=realm, event_type=RealmAuditLog.REALM_DEACTIVATED, event_time=event_time, acting_user=acting_user, extra_data=ujson.dumps({RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(realm)}))
ScheduledEmail.objects.filter(realm=realm).delete()
for user in active_humans_in_realm(realm):
delete_user_sessions(user)
event = dict(type='realm', op='deactivated', realm_id=realm.id)
send_event(realm, event, active_user_ids(realm.id)) |
def do_send_messages(messages_maybe_none: Sequence[Optional[MutableMapping[(str, Any)]]], email_gateway: bool=False, mark_as_read: Sequence[int]=[]) -> List[int]:
'See\n https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n for high-level documentation on this subsystem.\n '
messages = [message for message in messages_maybe_none if (message is not None)]
already_sent_ids: List[int] = []
new_messages: List[MutableMapping[(str, Any)]] = []
for message in messages:
if isinstance(message['message'], int):
already_sent_ids.append(message['message'])
else:
new_messages.append(message)
messages = new_messages
links_for_embed: Set[str] = set()
for message in messages:
message['rendered_content'] = message.get('rendered_content', None)
message['stream'] = message.get('stream', None)
message['local_id'] = message.get('local_id', None)
message['sender_queue_id'] = message.get('sender_queue_id', None)
message['realm'] = message.get('realm', message['message'].sender.realm)
mention_data = MentionData(realm_id=message['realm'].id, content=message['message'].content)
message['mention_data'] = mention_data
if message['message'].is_stream_message():
stream_id = message['message'].recipient.type_id
stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=message['message'].topic_name())
else:
stream_topic = None
info = get_recipient_info(recipient=message['message'].recipient, sender_id=message['message'].sender_id, stream_topic=stream_topic, possibly_mentioned_user_ids=mention_data.get_user_ids(), possible_wildcard_mention=mention_data.message_has_wildcards())
message['active_user_ids'] = info['active_user_ids']
message['push_notify_user_ids'] = info['push_notify_user_ids']
message['stream_push_user_ids'] = info['stream_push_user_ids']
message['stream_email_user_ids'] = info['stream_email_user_ids']
message['um_eligible_user_ids'] = info['um_eligible_user_ids']
message['long_term_idle_user_ids'] = info['long_term_idle_user_ids']
message['default_bot_user_ids'] = info['default_bot_user_ids']
message['service_bot_tuples'] = info['service_bot_tuples']
assert (message['message'].rendered_content is None)
rendered_content = render_incoming_message(message['message'], message['message'].content, message['active_user_ids'], message['realm'], mention_data=message['mention_data'], email_gateway=email_gateway)
message['message'].rendered_content = rendered_content
message['message'].rendered_content_version = markdown_version
links_for_embed |= message['message'].links_for_preview
for group_id in message['message'].mentions_user_group_ids:
members = message['mention_data'].get_group_members(group_id)
message['message'].mentions_user_ids.update(members)
if message['message'].mentions_wildcard:
message['wildcard_mention_user_ids'] = info['wildcard_mention_user_ids']
else:
message['wildcard_mention_user_ids'] = []
'\n Once we have the actual list of mentioned ids from message\n rendering, we can patch in "default bots" (aka normal bots)\n who were directly mentioned in this message as eligible to\n get UserMessage rows.\n '
mentioned_user_ids = message['message'].mentions_user_ids
default_bot_user_ids = message['default_bot_user_ids']
mentioned_bot_user_ids = (default_bot_user_ids & mentioned_user_ids)
message['um_eligible_user_ids'] |= mentioned_bot_user_ids
user_message_flags: Dict[(int, Dict[(int, List[str])])] = defaultdict(dict)
with transaction.atomic():
Message.objects.bulk_create([message['message'] for message in messages])
for message in messages:
if do_claim_attachments(message['message'], message['message'].potential_attachment_path_ids):
message['message'].has_attachment = True
message['message'].save(update_fields=['has_attachment'])
ums: List[UserMessageLite] = []
for message in messages:
mentioned_user_ids = message['message'].mentions_user_ids
user_messages = create_user_messages(message=message['message'], um_eligible_user_ids=message['um_eligible_user_ids'], long_term_idle_user_ids=message['long_term_idle_user_ids'], stream_push_user_ids=message['stream_push_user_ids'], stream_email_user_ids=message['stream_email_user_ids'], mentioned_user_ids=mentioned_user_ids, mark_as_read=mark_as_read)
for um in user_messages:
user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
ums.extend(user_messages)
message['message'].service_queue_events = get_service_bot_events(sender=message['message'].sender, service_bot_tuples=message['service_bot_tuples'], mentioned_user_ids=mentioned_user_ids, active_user_ids=message['active_user_ids'], recipient_type=message['message'].recipient.type)
bulk_insert_ums(ums)
for message in messages:
do_widget_post_save_actions(message)
for message in messages:
realm_id: Optional[int] = None
if message['message'].is_stream_message():
if (message['stream'] is None):
stream_id = message['message'].recipient.type_id
message['stream'] = Stream.objects.select_related().get(id=stream_id)
assert (message['stream'] is not None)
realm_id = message['stream'].realm_id
wide_message_dict = MessageDict.wide_dict(message['message'], realm_id)
user_flags = user_message_flags.get(message['message'].id, {})
sender = message['message'].sender
message_type = wide_message_dict['type']
presence_idle_user_ids = get_active_presence_idle_user_ids(realm=sender.realm, sender_id=sender.id, message_type=message_type, active_user_ids=message['active_user_ids'], user_flags=user_flags)
event = dict(type='message', message=message['message'].id, message_dict=wide_message_dict, presence_idle_user_ids=presence_idle_user_ids)
"\n TODO: We may want to limit user_ids to only those users who have\n UserMessage rows, if only for minor performance reasons.\n\n For now we queue events for all subscribers/sendees of the\n message, since downstream code may still do notifications\n that don't require UserMessage rows.\n\n Our automated tests have gotten better on this codepath,\n but we may have coverage gaps, so we should be careful\n about changing the next line.\n "
user_ids = (message['active_user_ids'] | set(user_flags.keys()))
users = [dict(id=user_id, flags=user_flags.get(user_id, []), always_push_notify=(user_id in message['push_notify_user_ids']), stream_push_notify=(user_id in message['stream_push_user_ids']), stream_email_notify=(user_id in message['stream_email_user_ids']), wildcard_mention_notify=(user_id in message['wildcard_mention_user_ids'])) for user_id in user_ids]
if message['message'].is_stream_message():
assert (message['stream'] is not None)
if message['stream'].is_public():
event['realm_id'] = message['stream'].realm_id
event['stream_name'] = message['stream'].name
if message['stream'].invite_only:
event['invite_only'] = True
if (message['stream'].first_message_id is None):
message['stream'].first_message_id = message['message'].id
message['stream'].save(update_fields=['first_message_id'])
if (message['local_id'] is not None):
event['local_id'] = message['local_id']
if (message['sender_queue_id'] is not None):
event['sender_queue_id'] = message['sender_queue_id']
send_event(message['realm'], event, users)
if links_for_embed:
event_data = {'message_id': message['message'].id, 'message_content': message['message'].content, 'message_realm_id': message['realm'].id, 'urls': links_for_embed}
queue_json_publish('embed_links', event_data)
if (message['message'].recipient.type == Recipient.PERSONAL):
welcome_bot_id = get_system_bot(settings.WELCOME_BOT).id
if ((welcome_bot_id in message['active_user_ids']) and (welcome_bot_id != message['message'].sender_id)):
send_welcome_bot_response(message)
for (queue_name, events) in message['message'].service_queue_events.items():
for event in events:
queue_json_publish(queue_name, {'message': wide_message_dict, 'trigger': event['trigger'], 'user_profile_id': event['user_profile_id']})
return (already_sent_ids + [message['message'].id for message in messages]) | 1,167,765,137,967,222,500 | See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem. | zerver/lib/actions.py | do_send_messages | gutalavijay1111/zulip-vijay | python | def do_send_messages(messages_maybe_none: Sequence[Optional[MutableMapping[(str, Any)]]], email_gateway: bool=False, mark_as_read: Sequence[int]=[]) -> List[int]:
'See\n https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n for high-level documentation on this subsystem.\n '
messages = [message for message in messages_maybe_none if (message is not None)]
already_sent_ids: List[int] = []
new_messages: List[MutableMapping[(str, Any)]] = []
for message in messages:
if isinstance(message['message'], int):
already_sent_ids.append(message['message'])
else:
new_messages.append(message)
messages = new_messages
links_for_embed: Set[str] = set()
for message in messages:
message['rendered_content'] = message.get('rendered_content', None)
message['stream'] = message.get('stream', None)
message['local_id'] = message.get('local_id', None)
message['sender_queue_id'] = message.get('sender_queue_id', None)
message['realm'] = message.get('realm', message['message'].sender.realm)
mention_data = MentionData(realm_id=message['realm'].id, content=message['message'].content)
message['mention_data'] = mention_data
if message['message'].is_stream_message():
stream_id = message['message'].recipient.type_id
stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=message['message'].topic_name())
else:
stream_topic = None
info = get_recipient_info(recipient=message['message'].recipient, sender_id=message['message'].sender_id, stream_topic=stream_topic, possibly_mentioned_user_ids=mention_data.get_user_ids(), possible_wildcard_mention=mention_data.message_has_wildcards())
message['active_user_ids'] = info['active_user_ids']
message['push_notify_user_ids'] = info['push_notify_user_ids']
message['stream_push_user_ids'] = info['stream_push_user_ids']
message['stream_email_user_ids'] = info['stream_email_user_ids']
message['um_eligible_user_ids'] = info['um_eligible_user_ids']
message['long_term_idle_user_ids'] = info['long_term_idle_user_ids']
message['default_bot_user_ids'] = info['default_bot_user_ids']
message['service_bot_tuples'] = info['service_bot_tuples']
assert (message['message'].rendered_content is None)
rendered_content = render_incoming_message(message['message'], message['message'].content, message['active_user_ids'], message['realm'], mention_data=message['mention_data'], email_gateway=email_gateway)
message['message'].rendered_content = rendered_content
message['message'].rendered_content_version = markdown_version
links_for_embed |= message['message'].links_for_preview
for group_id in message['message'].mentions_user_group_ids:
members = message['mention_data'].get_group_members(group_id)
message['message'].mentions_user_ids.update(members)
if message['message'].mentions_wildcard:
message['wildcard_mention_user_ids'] = info['wildcard_mention_user_ids']
else:
message['wildcard_mention_user_ids'] = []
'\n Once we have the actual list of mentioned ids from message\n rendering, we can patch in "default bots" (aka normal bots)\n who were directly mentioned in this message as eligible to\n get UserMessage rows.\n '
mentioned_user_ids = message['message'].mentions_user_ids
default_bot_user_ids = message['default_bot_user_ids']
mentioned_bot_user_ids = (default_bot_user_ids & mentioned_user_ids)
message['um_eligible_user_ids'] |= mentioned_bot_user_ids
user_message_flags: Dict[(int, Dict[(int, List[str])])] = defaultdict(dict)
with transaction.atomic():
Message.objects.bulk_create([message['message'] for message in messages])
for message in messages:
if do_claim_attachments(message['message'], message['message'].potential_attachment_path_ids):
message['message'].has_attachment = True
message['message'].save(update_fields=['has_attachment'])
ums: List[UserMessageLite] = []
for message in messages:
mentioned_user_ids = message['message'].mentions_user_ids
user_messages = create_user_messages(message=message['message'], um_eligible_user_ids=message['um_eligible_user_ids'], long_term_idle_user_ids=message['long_term_idle_user_ids'], stream_push_user_ids=message['stream_push_user_ids'], stream_email_user_ids=message['stream_email_user_ids'], mentioned_user_ids=mentioned_user_ids, mark_as_read=mark_as_read)
for um in user_messages:
user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
ums.extend(user_messages)
message['message'].service_queue_events = get_service_bot_events(sender=message['message'].sender, service_bot_tuples=message['service_bot_tuples'], mentioned_user_ids=mentioned_user_ids, active_user_ids=message['active_user_ids'], recipient_type=message['message'].recipient.type)
bulk_insert_ums(ums)
for message in messages:
do_widget_post_save_actions(message)
for message in messages:
realm_id: Optional[int] = None
if message['message'].is_stream_message():
if (message['stream'] is None):
stream_id = message['message'].recipient.type_id
message['stream'] = Stream.objects.select_related().get(id=stream_id)
assert (message['stream'] is not None)
realm_id = message['stream'].realm_id
wide_message_dict = MessageDict.wide_dict(message['message'], realm_id)
user_flags = user_message_flags.get(message['message'].id, {})
sender = message['message'].sender
message_type = wide_message_dict['type']
presence_idle_user_ids = get_active_presence_idle_user_ids(realm=sender.realm, sender_id=sender.id, message_type=message_type, active_user_ids=message['active_user_ids'], user_flags=user_flags)
event = dict(type='message', message=message['message'].id, message_dict=wide_message_dict, presence_idle_user_ids=presence_idle_user_ids)
"\n TODO: We may want to limit user_ids to only those users who have\n UserMessage rows, if only for minor performance reasons.\n\n For now we queue events for all subscribers/sendees of the\n message, since downstream code may still do notifications\n that don't require UserMessage rows.\n\n Our automated tests have gotten better on this codepath,\n but we may have coverage gaps, so we should be careful\n about changing the next line.\n "
user_ids = (message['active_user_ids'] | set(user_flags.keys()))
users = [dict(id=user_id, flags=user_flags.get(user_id, []), always_push_notify=(user_id in message['push_notify_user_ids']), stream_push_notify=(user_id in message['stream_push_user_ids']), stream_email_notify=(user_id in message['stream_email_user_ids']), wildcard_mention_notify=(user_id in message['wildcard_mention_user_ids'])) for user_id in user_ids]
if message['message'].is_stream_message():
assert (message['stream'] is not None)
if message['stream'].is_public():
event['realm_id'] = message['stream'].realm_id
event['stream_name'] = message['stream'].name
if message['stream'].invite_only:
event['invite_only'] = True
if (message['stream'].first_message_id is None):
message['stream'].first_message_id = message['message'].id
message['stream'].save(update_fields=['first_message_id'])
if (message['local_id'] is not None):
event['local_id'] = message['local_id']
if (message['sender_queue_id'] is not None):
event['sender_queue_id'] = message['sender_queue_id']
send_event(message['realm'], event, users)
if links_for_embed:
event_data = {'message_id': message['message'].id, 'message_content': message['message'].content, 'message_realm_id': message['realm'].id, 'urls': links_for_embed}
queue_json_publish('embed_links', event_data)
if (message['message'].recipient.type == Recipient.PERSONAL):
welcome_bot_id = get_system_bot(settings.WELCOME_BOT).id
if ((welcome_bot_id in message['active_user_ids']) and (welcome_bot_id != message['message'].sender_id)):
send_welcome_bot_response(message)
for (queue_name, events) in message['message'].service_queue_events.items():
for event in events:
queue_json_publish(queue_name, {'message': wide_message_dict, 'trigger': event['trigger'], 'user_profile_id': event['user_profile_id']})
return (already_sent_ids + [message['message'].id for message in messages]) |
def bulk_insert_ums(ums: List[UserMessageLite]) -> None:
"\n Doing bulk inserts this way is much faster than using Django,\n since we don't have any ORM overhead. Profiling with 1000\n users shows a speedup of 0.436 -> 0.027 seconds, so we're\n talking about a 15x speedup.\n "
if (not ums):
return
vals = [(um.user_profile_id, um.message_id, um.flags) for um in ums]
query = SQL('\n INSERT into\n zerver_usermessage (user_profile_id, message_id, flags)\n VALUES %s\n ')
with connection.cursor() as cursor:
execute_values(cursor.cursor, query, vals) | -8,615,920,368,105,321,000 | Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup. | zerver/lib/actions.py | bulk_insert_ums | gutalavijay1111/zulip-vijay | python | def bulk_insert_ums(ums: List[UserMessageLite]) -> None:
"\n Doing bulk inserts this way is much faster than using Django,\n since we don't have any ORM overhead. Profiling with 1000\n users shows a speedup of 0.436 -> 0.027 seconds, so we're\n talking about a 15x speedup.\n "
if (not ums):
return
vals = [(um.user_profile_id, um.message_id, um.flags) for um in ums]
query = SQL('\n INSERT into\n zerver_usermessage (user_profile_id, message_id, flags)\n VALUES %s\n ')
with connection.cursor() as cursor:
execute_values(cursor.cursor, query, vals) |
def send_rate_limited_pm_notification_to_bot_owner(sender: UserProfile, realm: Realm, content: str) -> None:
"\n Sends a PM error notification to a bot's owner if one hasn't already\n been sent in the last 5 minutes.\n "
if (sender.realm.is_zephyr_mirror_realm or sender.realm.deactivated):
return
if ((not sender.is_bot) or (sender.bot_owner is None)):
return
if (sender.realm != realm):
return
last_reminder = sender.last_reminder
waitperiod = datetime.timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)
if (last_reminder and ((timezone_now() - last_reminder) <= waitperiod)):
return
internal_send_private_message(realm, get_system_bot(settings.NOTIFICATION_BOT), sender.bot_owner, content)
sender.last_reminder = timezone_now()
sender.save(update_fields=['last_reminder']) | -3,291,042,250,313,544,000 | Sends a PM error notification to a bot's owner if one hasn't already
been sent in the last 5 minutes. | zerver/lib/actions.py | send_rate_limited_pm_notification_to_bot_owner | gutalavijay1111/zulip-vijay | python | def send_rate_limited_pm_notification_to_bot_owner(sender: UserProfile, realm: Realm, content: str) -> None:
"\n Sends a PM error notification to a bot's owner if one hasn't already\n been sent in the last 5 minutes.\n "
if (sender.realm.is_zephyr_mirror_realm or sender.realm.deactivated):
return
if ((not sender.is_bot) or (sender.bot_owner is None)):
return
if (sender.realm != realm):
return
last_reminder = sender.last_reminder
waitperiod = datetime.timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)
if (last_reminder and ((timezone_now() - last_reminder) <= waitperiod)):
return
internal_send_private_message(realm, get_system_bot(settings.NOTIFICATION_BOT), sender.bot_owner, content)
sender.last_reminder = timezone_now()
sender.save(update_fields=['last_reminder']) |
def send_pm_if_empty_stream(stream: Optional[Stream], realm: Realm, sender: UserProfile, stream_name: Optional[str]=None, stream_id: Optional[int]=None) -> None:
"If a bot sends a message to a stream that doesn't exist or has no\n subscribers, sends a notification to the bot owner (if not a\n cross-realm bot) so that the owner can correct the issue."
if ((not sender.is_bot) or (sender.bot_owner is None)):
return
arg_dict = {'bot_identity': f'`{sender.delivery_email}`', 'stream_id': stream_id, 'stream_name': f'#**{stream_name}**', 'new_stream_link': '#streams/new'}
if (sender.bot_owner is not None):
with override_language(sender.bot_owner.default_language):
if (stream is None):
if (stream_id is not None):
content = _('Your bot {bot_identity} tried to send a message to stream ID {stream_id}, but there is no stream with that ID.').format(**arg_dict)
else:
assert (stream_name is not None)
content = _('Your bot {bot_identity} tried to send a message to stream {stream_name}, but that stream does not exist. Click [here]({new_stream_link}) to create it.').format(**arg_dict)
else:
if (num_subscribers_for_stream_id(stream.id) > 0):
return
content = _('Your bot {bot_identity} tried to send a message to stream {stream_name}. The stream exists but does not have any subscribers.').format(**arg_dict)
send_rate_limited_pm_notification_to_bot_owner(sender, realm, content) | -8,537,584,179,513,448,000 | If a bot sends a message to a stream that doesn't exist or has no
subscribers, sends a notification to the bot owner (if not a
cross-realm bot) so that the owner can correct the issue. | zerver/lib/actions.py | send_pm_if_empty_stream | gutalavijay1111/zulip-vijay | python | def send_pm_if_empty_stream(stream: Optional[Stream], realm: Realm, sender: UserProfile, stream_name: Optional[str]=None, stream_id: Optional[int]=None) -> None:
"If a bot sends a message to a stream that doesn't exist or has no\n subscribers, sends a notification to the bot owner (if not a\n cross-realm bot) so that the owner can correct the issue."
if ((not sender.is_bot) or (sender.bot_owner is None)):
return
arg_dict = {'bot_identity': f'`{sender.delivery_email}`', 'stream_id': stream_id, 'stream_name': f'#**{stream_name}**', 'new_stream_link': '#streams/new'}
if (sender.bot_owner is not None):
with override_language(sender.bot_owner.default_language):
if (stream is None):
if (stream_id is not None):
content = _('Your bot {bot_identity} tried to send a message to stream ID {stream_id}, but there is no stream with that ID.').format(**arg_dict)
else:
assert (stream_name is not None)
content = _('Your bot {bot_identity} tried to send a message to stream {stream_name}, but that stream does not exist. Click [here]({new_stream_link}) to create it.').format(**arg_dict)
else:
if (num_subscribers_for_stream_id(stream.id) > 0):
return
content = _('Your bot {bot_identity} tried to send a message to stream {stream_name}. The stream exists but does not have any subscribers.').format(**arg_dict)
send_rate_limited_pm_notification_to_bot_owner(sender, realm, content) |
def check_message(sender: UserProfile, client: Client, addressee: Addressee, message_content_raw: str, realm: Optional[Realm]=None, forged: bool=False, forged_timestamp: Optional[float]=None, forwarder_user_profile: Optional[UserProfile]=None, local_id: Optional[str]=None, sender_queue_id: Optional[str]=None, widget_content: Optional[str]=None) -> Dict[(str, Any)]:
'See\n https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n for high-level documentation on this subsystem.\n '
stream = None
message_content = message_content_raw.rstrip()
if (len(message_content) == 0):
raise JsonableError(_('Message must not be empty'))
if ('\x00' in message_content):
raise JsonableError(_('Message must not contain null bytes'))
message_content = truncate_body(message_content)
if (realm is None):
realm = sender.realm
if addressee.is_stream():
topic_name = addressee.topic()
topic_name = truncate_topic(topic_name)
stream_name = addressee.stream_name()
stream_id = addressee.stream_id()
if (stream_name is not None):
stream = validate_stream_name_with_pm_notification(stream_name, realm, sender)
elif (stream_id is not None):
stream = validate_stream_id_with_pm_notification(stream_id, realm, sender)
else:
stream = addressee.stream()
assert (stream is not None)
recipient = stream.recipient
if (sender.bot_type != sender.OUTGOING_WEBHOOK_BOT):
access_stream_for_send_message(sender=sender, stream=stream, forwarder_user_profile=forwarder_user_profile)
elif addressee.is_private():
user_profiles = addressee.user_profiles()
mirror_message = (client and (client.name in ['zephyr_mirror', 'irc_mirror', 'jabber_mirror', 'JabberMirror']))
check_private_message_policy(realm, sender, user_profiles)
forwarded_mirror_message = (mirror_message and (not forged))
try:
recipient = recipient_for_user_profiles(user_profiles, forwarded_mirror_message, forwarder_user_profile, sender)
except ValidationError as e:
assert isinstance(e.messages[0], str)
raise JsonableError(e.messages[0])
else:
raise AssertionError('Invalid message type')
message = Message()
message.sender = sender
message.content = message_content
message.recipient = recipient
if addressee.is_stream():
message.set_topic_name(topic_name)
if (forged and (forged_timestamp is not None)):
message.date_sent = timestamp_to_datetime(forged_timestamp)
else:
message.date_sent = timezone_now()
message.sending_client = client
assert (message.rendered_content is None)
if (client.name == 'zephyr_mirror'):
id = already_sent_mirrored_message_id(message)
if (id is not None):
return {'message': id}
if (widget_content is not None):
try:
widget_content = ujson.loads(widget_content)
except Exception:
raise JsonableError(_('Widgets: API programmer sent invalid JSON content'))
try:
check_widget_content(widget_content)
except ValidationError as error:
raise JsonableError(_('Widgets: {error_msg}').format(error_msg=error.message))
return {'message': message, 'stream': stream, 'local_id': local_id, 'sender_queue_id': sender_queue_id, 'realm': realm, 'widget_content': widget_content} | -1,645,878,623,583,306,000 | See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem. | zerver/lib/actions.py | check_message | gutalavijay1111/zulip-vijay | python | def check_message(sender: UserProfile, client: Client, addressee: Addressee, message_content_raw: str, realm: Optional[Realm]=None, forged: bool=False, forged_timestamp: Optional[float]=None, forwarder_user_profile: Optional[UserProfile]=None, local_id: Optional[str]=None, sender_queue_id: Optional[str]=None, widget_content: Optional[str]=None) -> Dict[(str, Any)]:
'See\n https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html\n for high-level documentation on this subsystem.\n '
stream = None
message_content = message_content_raw.rstrip()
if (len(message_content) == 0):
raise JsonableError(_('Message must not be empty'))
if ('\x00' in message_content):
raise JsonableError(_('Message must not contain null bytes'))
message_content = truncate_body(message_content)
if (realm is None):
realm = sender.realm
if addressee.is_stream():
topic_name = addressee.topic()
topic_name = truncate_topic(topic_name)
stream_name = addressee.stream_name()
stream_id = addressee.stream_id()
if (stream_name is not None):
stream = validate_stream_name_with_pm_notification(stream_name, realm, sender)
elif (stream_id is not None):
stream = validate_stream_id_with_pm_notification(stream_id, realm, sender)
else:
stream = addressee.stream()
assert (stream is not None)
recipient = stream.recipient
if (sender.bot_type != sender.OUTGOING_WEBHOOK_BOT):
access_stream_for_send_message(sender=sender, stream=stream, forwarder_user_profile=forwarder_user_profile)
elif addressee.is_private():
user_profiles = addressee.user_profiles()
mirror_message = (client and (client.name in ['zephyr_mirror', 'irc_mirror', 'jabber_mirror', 'JabberMirror']))
check_private_message_policy(realm, sender, user_profiles)
forwarded_mirror_message = (mirror_message and (not forged))
try:
recipient = recipient_for_user_profiles(user_profiles, forwarded_mirror_message, forwarder_user_profile, sender)
except ValidationError as e:
assert isinstance(e.messages[0], str)
raise JsonableError(e.messages[0])
else:
raise AssertionError('Invalid message type')
message = Message()
message.sender = sender
message.content = message_content
message.recipient = recipient
if addressee.is_stream():
message.set_topic_name(topic_name)
if (forged and (forged_timestamp is not None)):
message.date_sent = timestamp_to_datetime(forged_timestamp)
else:
message.date_sent = timezone_now()
message.sending_client = client
assert (message.rendered_content is None)
if (client.name == 'zephyr_mirror'):
id = already_sent_mirrored_message_id(message)
if (id is not None):
return {'message': id}
if (widget_content is not None):
try:
widget_content = ujson.loads(widget_content)
except Exception:
raise JsonableError(_('Widgets: API programmer sent invalid JSON content'))
try:
check_widget_content(widget_content)
except ValidationError as error:
raise JsonableError(_('Widgets: {error_msg}').format(error_msg=error.message))
return {'message': message, 'stream': stream, 'local_id': local_id, 'sender_queue_id': sender_queue_id, 'realm': realm, 'widget_content': widget_content} |
def _internal_prep_message(realm: Realm, sender: UserProfile, addressee: Addressee, content: str) -> Optional[Dict[(str, Any)]]:
"\n Create a message object and checks it, but doesn't send it or save it to the database.\n The internal function that calls this can therefore batch send a bunch of created\n messages together as one database query.\n Call do_send_messages with a list of the return values of this method.\n "
if (len(content) > MAX_MESSAGE_LENGTH):
content = (content[0:3900] + '\n\n[message was too long and has been truncated]')
if addressee.is_stream():
stream_name = addressee.stream_name()
if (stream_name is not None):
ensure_stream(realm, stream_name, acting_user=sender)
try:
return check_message(sender, get_client('Internal'), addressee, content, realm=realm)
except JsonableError as e:
logging.exception('Error queueing internal message by %s: %s', sender.delivery_email, e.msg)
return None | -3,711,186,963,448,017,400 | Create a message object and checks it, but doesn't send it or save it to the database.
The internal function that calls this can therefore batch send a bunch of created
messages together as one database query.
Call do_send_messages with a list of the return values of this method. | zerver/lib/actions.py | _internal_prep_message | gutalavijay1111/zulip-vijay | python | def _internal_prep_message(realm: Realm, sender: UserProfile, addressee: Addressee, content: str) -> Optional[Dict[(str, Any)]]:
"\n Create a message object and checks it, but doesn't send it or save it to the database.\n The internal function that calls this can therefore batch send a bunch of created\n messages together as one database query.\n Call do_send_messages with a list of the return values of this method.\n "
if (len(content) > MAX_MESSAGE_LENGTH):
content = (content[0:3900] + '\n\n[message was too long and has been truncated]')
if addressee.is_stream():
stream_name = addressee.stream_name()
if (stream_name is not None):
ensure_stream(realm, stream_name, acting_user=sender)
try:
return check_message(sender, get_client('Internal'), addressee, content, realm=realm)
except JsonableError as e:
logging.exception('Error queueing internal message by %s: %s', sender.delivery_email, e.msg)
return None |
def internal_prep_stream_message(realm: Realm, sender: UserProfile, stream: Stream, topic: str, content: str) -> Optional[Dict[(str, Any)]]:
'\n See _internal_prep_message for details of how this works.\n '
addressee = Addressee.for_stream(stream, topic)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) | -3,348,404,627,655,703,000 | See _internal_prep_message for details of how this works. | zerver/lib/actions.py | internal_prep_stream_message | gutalavijay1111/zulip-vijay | python | def internal_prep_stream_message(realm: Realm, sender: UserProfile, stream: Stream, topic: str, content: str) -> Optional[Dict[(str, Any)]]:
'\n \n '
addressee = Addressee.for_stream(stream, topic)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) |
def internal_prep_stream_message_by_name(realm: Realm, sender: UserProfile, stream_name: str, topic: str, content: str) -> Optional[Dict[(str, Any)]]:
'\n See _internal_prep_message for details of how this works.\n '
addressee = Addressee.for_stream_name(stream_name, topic)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) | 1,024,521,372,594,651,600 | See _internal_prep_message for details of how this works. | zerver/lib/actions.py | internal_prep_stream_message_by_name | gutalavijay1111/zulip-vijay | python | def internal_prep_stream_message_by_name(realm: Realm, sender: UserProfile, stream_name: str, topic: str, content: str) -> Optional[Dict[(str, Any)]]:
'\n \n '
addressee = Addressee.for_stream_name(stream_name, topic)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) |
def internal_prep_private_message(realm: Realm, sender: UserProfile, recipient_user: UserProfile, content: str) -> Optional[Dict[(str, Any)]]:
'\n See _internal_prep_message for details of how this works.\n '
addressee = Addressee.for_user_profile(recipient_user)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) | -2,965,441,005,731,838,500 | See _internal_prep_message for details of how this works. | zerver/lib/actions.py | internal_prep_private_message | gutalavijay1111/zulip-vijay | python | def internal_prep_private_message(realm: Realm, sender: UserProfile, recipient_user: UserProfile, content: str) -> Optional[Dict[(str, Any)]]:
'\n \n '
addressee = Addressee.for_user_profile(recipient_user)
return _internal_prep_message(realm=realm, sender=sender, addressee=addressee, content=content) |
def validate_user_access_to_subscribers(user_profile: Optional[UserProfile], stream: Stream) -> None:
' Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:\n * The user and the stream are in different realms\n * The realm is MIT and the stream is not invite only.\n * The stream is invite only, requesting_user is passed, and that user\n does not subscribe to the stream.\n '
validate_user_access_to_subscribers_helper(user_profile, {'realm_id': stream.realm_id, 'invite_only': stream.invite_only}, (lambda user_profile: subscribed_to_stream(user_profile, stream.id))) | -7,392,364,703,648,287,000 | Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
* The user and the stream are in different realms
* The realm is MIT and the stream is not invite only.
* The stream is invite only, requesting_user is passed, and that user
does not subscribe to the stream. | zerver/lib/actions.py | validate_user_access_to_subscribers | gutalavijay1111/zulip-vijay | python | def validate_user_access_to_subscribers(user_profile: Optional[UserProfile], stream: Stream) -> None:
' Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:\n * The user and the stream are in different realms\n * The realm is MIT and the stream is not invite only.\n * The stream is invite only, requesting_user is passed, and that user\n does not subscribe to the stream.\n '
validate_user_access_to_subscribers_helper(user_profile, {'realm_id': stream.realm_id, 'invite_only': stream.invite_only}, (lambda user_profile: subscribed_to_stream(user_profile, stream.id))) |
def validate_user_access_to_subscribers_helper(user_profile: Optional[UserProfile], stream_dict: Mapping[(str, Any)], check_user_subscribed: Callable[([UserProfile], bool)]) -> None:
"Helper for validate_user_access_to_subscribers that doesn't require\n a full stream object. This function is a bit hard to read,\n because it is carefully optimized for performance in the two code\n paths we call it from:\n\n * In `bulk_get_subscriber_user_ids`, we already know whether the\n user was subscribed via `sub_dict`, and so we want to avoid a\n database query at all (especially since it calls this in a loop);\n * In `validate_user_access_to_subscribers`, we want to only check\n if the user is subscribed when we absolutely have to, since it\n costs a database query.\n\n The `check_user_subscribed` argument is a function that reports\n whether the user is subscribed to the stream.\n\n Note also that we raise a ValidationError in cases where the\n caller is doing the wrong thing (maybe these should be\n AssertionErrors), and JsonableError for 400 type errors.\n "
if (user_profile is None):
raise ValidationError('Missing user to validate access for')
if (user_profile.realm_id != stream_dict['realm_id']):
raise ValidationError('Requesting user not in given realm')
if user_profile.is_guest:
if check_user_subscribed(user_profile):
return
if ((not user_profile.can_access_public_streams()) and (not stream_dict['invite_only'])):
raise JsonableError(_('Subscriber data is not available for this stream'))
if user_profile.is_realm_admin:
return
if (stream_dict['invite_only'] and (not check_user_subscribed(user_profile))):
raise JsonableError(_('Unable to retrieve subscribers for private stream')) | 5,070,930,250,182,283,000 | Helper for validate_user_access_to_subscribers that doesn't require
a full stream object. This function is a bit hard to read,
because it is carefully optimized for performance in the two code
paths we call it from:
* In `bulk_get_subscriber_user_ids`, we already know whether the
user was subscribed via `sub_dict`, and so we want to avoid a
database query at all (especially since it calls this in a loop);
* In `validate_user_access_to_subscribers`, we want to only check
if the user is subscribed when we absolutely have to, since it
costs a database query.
The `check_user_subscribed` argument is a function that reports
whether the user is subscribed to the stream.
Note also that we raise a ValidationError in cases where the
caller is doing the wrong thing (maybe these should be
AssertionErrors), and JsonableError for 400 type errors. | zerver/lib/actions.py | validate_user_access_to_subscribers_helper | gutalavijay1111/zulip-vijay | python | def validate_user_access_to_subscribers_helper(user_profile: Optional[UserProfile], stream_dict: Mapping[(str, Any)], check_user_subscribed: Callable[([UserProfile], bool)]) -> None:
"Helper for validate_user_access_to_subscribers that doesn't require\n a full stream object. This function is a bit hard to read,\n because it is carefully optimized for performance in the two code\n paths we call it from:\n\n * In `bulk_get_subscriber_user_ids`, we already know whether the\n user was subscribed via `sub_dict`, and so we want to avoid a\n database query at all (especially since it calls this in a loop);\n * In `validate_user_access_to_subscribers`, we want to only check\n if the user is subscribed when we absolutely have to, since it\n costs a database query.\n\n The `check_user_subscribed` argument is a function that reports\n whether the user is subscribed to the stream.\n\n Note also that we raise a ValidationError in cases where the\n caller is doing the wrong thing (maybe these should be\n AssertionErrors), and JsonableError for 400 type errors.\n "
if (user_profile is None):
raise ValidationError('Missing user to validate access for')
if (user_profile.realm_id != stream_dict['realm_id']):
raise ValidationError('Requesting user not in given realm')
if user_profile.is_guest:
if check_user_subscribed(user_profile):
return
if ((not user_profile.can_access_public_streams()) and (not stream_dict['invite_only'])):
raise JsonableError(_('Subscriber data is not available for this stream'))
if user_profile.is_realm_admin:
return
if (stream_dict['invite_only'] and (not check_user_subscribed(user_profile))):
raise JsonableError(_('Unable to retrieve subscribers for private stream')) |
def bulk_get_subscriber_user_ids(stream_dicts: Iterable[Mapping[(str, Any)]], user_profile: UserProfile, sub_dict: Mapping[(int, bool)], stream_recipient: StreamRecipientMap) -> Dict[(int, List[int])]:
'sub_dict maps stream_id => whether the user is subscribed to that stream.'
target_stream_dicts = []
for stream_dict in stream_dicts:
stream_recipient.populate_with(stream_id=stream_dict['id'], recipient_id=stream_dict['recipient_id'])
try:
validate_user_access_to_subscribers_helper(user_profile, stream_dict, (lambda user_profile: sub_dict[stream_dict['id']]))
except JsonableError:
continue
target_stream_dicts.append(stream_dict)
stream_ids = [stream['id'] for stream in target_stream_dicts]
recipient_ids = sorted([stream_recipient.recipient_id_for(stream_id) for stream_id in stream_ids])
result: Dict[(int, List[int])] = {stream['id']: [] for stream in stream_dicts}
if (not recipient_ids):
return result
'\n The raw SQL below leads to more than a 2x speedup when tested with\n 20k+ total subscribers. (For large realms with lots of default\n streams, this function deals with LOTS of data, so it is important\n to optimize.)\n '
query = SQL('\n SELECT\n zerver_subscription.recipient_id,\n zerver_subscription.user_profile_id\n FROM\n zerver_subscription\n INNER JOIN zerver_userprofile ON\n zerver_userprofile.id = zerver_subscription.user_profile_id\n WHERE\n zerver_subscription.recipient_id in %(recipient_ids)s AND\n zerver_subscription.active AND\n zerver_userprofile.is_active\n ORDER BY\n zerver_subscription.recipient_id,\n zerver_subscription.user_profile_id\n ')
cursor = connection.cursor()
cursor.execute(query, {'recipient_ids': tuple(recipient_ids)})
rows = cursor.fetchall()
cursor.close()
recip_to_stream_id = stream_recipient.recipient_to_stream_id_dict()
'\n Using groupby/itemgetter here is important for performance, at scale.\n It makes it so that all interpreter overhead is just O(N) in nature.\n '
for (recip_id, recip_rows) in itertools.groupby(rows, itemgetter(0)):
user_profile_ids = [r[1] for r in recip_rows]
stream_id = recip_to_stream_id[recip_id]
result[stream_id] = list(user_profile_ids)
return result | -7,196,757,676,079,950,000 | sub_dict maps stream_id => whether the user is subscribed to that stream. | zerver/lib/actions.py | bulk_get_subscriber_user_ids | gutalavijay1111/zulip-vijay | python | def bulk_get_subscriber_user_ids(stream_dicts: Iterable[Mapping[(str, Any)]], user_profile: UserProfile, sub_dict: Mapping[(int, bool)], stream_recipient: StreamRecipientMap) -> Dict[(int, List[int])]:
target_stream_dicts = []
for stream_dict in stream_dicts:
stream_recipient.populate_with(stream_id=stream_dict['id'], recipient_id=stream_dict['recipient_id'])
try:
validate_user_access_to_subscribers_helper(user_profile, stream_dict, (lambda user_profile: sub_dict[stream_dict['id']]))
except JsonableError:
continue
target_stream_dicts.append(stream_dict)
stream_ids = [stream['id'] for stream in target_stream_dicts]
recipient_ids = sorted([stream_recipient.recipient_id_for(stream_id) for stream_id in stream_ids])
result: Dict[(int, List[int])] = {stream['id']: [] for stream in stream_dicts}
if (not recipient_ids):
return result
'\n The raw SQL below leads to more than a 2x speedup when tested with\n 20k+ total subscribers. (For large realms with lots of default\n streams, this function deals with LOTS of data, so it is important\n to optimize.)\n '
query = SQL('\n SELECT\n zerver_subscription.recipient_id,\n zerver_subscription.user_profile_id\n FROM\n zerver_subscription\n INNER JOIN zerver_userprofile ON\n zerver_userprofile.id = zerver_subscription.user_profile_id\n WHERE\n zerver_subscription.recipient_id in %(recipient_ids)s AND\n zerver_subscription.active AND\n zerver_userprofile.is_active\n ORDER BY\n zerver_subscription.recipient_id,\n zerver_subscription.user_profile_id\n ')
cursor = connection.cursor()
cursor.execute(query, {'recipient_ids': tuple(recipient_ids)})
rows = cursor.fetchall()
cursor.close()
recip_to_stream_id = stream_recipient.recipient_to_stream_id_dict()
'\n Using groupby/itemgetter here is important for performance, at scale.\n It makes it so that all interpreter overhead is just O(N) in nature.\n '
for (recip_id, recip_rows) in itertools.groupby(rows, itemgetter(0)):
user_profile_ids = [r[1] for r in recip_rows]
stream_id = recip_to_stream_id[recip_id]
result[stream_id] = list(user_profile_ids)
return result |
def get_subscribers_query(stream: Stream, requesting_user: Optional[UserProfile]) -> QuerySet:
" Build a query to get the subscribers list for a stream, raising a JsonableError if:\n\n 'realm' is optional in stream.\n\n The caller can refine this query with select_related(), values(), etc. depending\n on whether it wants objects or just certain fields\n "
validate_user_access_to_subscribers(requesting_user, stream)
subscriptions = get_active_subscriptions_for_stream_id(stream.id).filter(user_profile__is_active=True)
return subscriptions | -4,328,253,176,587,639,300 | Build a query to get the subscribers list for a stream, raising a JsonableError if:
'realm' is optional in stream.
The caller can refine this query with select_related(), values(), etc. depending
on whether it wants objects or just certain fields | zerver/lib/actions.py | get_subscribers_query | gutalavijay1111/zulip-vijay | python | def get_subscribers_query(stream: Stream, requesting_user: Optional[UserProfile]) -> QuerySet:
" Build a query to get the subscribers list for a stream, raising a JsonableError if:\n\n 'realm' is optional in stream.\n\n The caller can refine this query with select_related(), values(), etc. depending\n on whether it wants objects or just certain fields\n "
validate_user_access_to_subscribers(requesting_user, stream)
subscriptions = get_active_subscriptions_for_stream_id(stream.id).filter(user_profile__is_active=True)
return subscriptions |
def get_peer_user_ids_for_stream_change(stream: Stream, altered_user_ids: Iterable[int], subscribed_user_ids: Iterable[int]) -> Set[int]:
'\n altered_user_ids is the user_ids that we are adding/removing\n subscribed_user_ids is the already-subscribed user_ids\n\n Based on stream policy, we notify the correct bystanders, while\n not notifying altered_users (who get subscribers via another event)\n '
if stream.invite_only:
realm_admin_ids = [user.id for user in stream.realm.get_admin_users_and_bots()]
user_ids_to_notify = []
user_ids_to_notify.extend(realm_admin_ids)
user_ids_to_notify.extend(subscribed_user_ids)
return (set(user_ids_to_notify) - set(altered_user_ids))
else:
return (set(active_non_guest_user_ids(stream.realm_id)) - set(altered_user_ids)) | -4,022,933,929,084,802,600 | altered_user_ids is the user_ids that we are adding/removing
subscribed_user_ids is the already-subscribed user_ids
Based on stream policy, we notify the correct bystanders, while
not notifying altered_users (who get subscribers via another event) | zerver/lib/actions.py | get_peer_user_ids_for_stream_change | gutalavijay1111/zulip-vijay | python | def get_peer_user_ids_for_stream_change(stream: Stream, altered_user_ids: Iterable[int], subscribed_user_ids: Iterable[int]) -> Set[int]:
'\n altered_user_ids is the user_ids that we are adding/removing\n subscribed_user_ids is the already-subscribed user_ids\n\n Based on stream policy, we notify the correct bystanders, while\n not notifying altered_users (who get subscribers via another event)\n '
if stream.invite_only:
realm_admin_ids = [user.id for user in stream.realm.get_admin_users_and_bots()]
user_ids_to_notify = []
user_ids_to_notify.extend(realm_admin_ids)
user_ids_to_notify.extend(subscribed_user_ids)
return (set(user_ids_to_notify) - set(altered_user_ids))
else:
return (set(active_non_guest_user_ids(stream.realm_id)) - set(altered_user_ids)) |
def check_change_full_name(user_profile: UserProfile, full_name_raw: str, acting_user: UserProfile) -> str:
"Verifies that the user's proposed full name is valid. The caller\n is responsible for checking check permissions. Returns the new\n full name, which may differ from what was passed in (because this\n function strips whitespace)."
new_full_name = check_full_name(full_name_raw)
do_change_full_name(user_profile, new_full_name, acting_user)
return new_full_name | -3,665,740,692,360,973,000 | Verifies that the user's proposed full name is valid. The caller
is responsible for checking check permissions. Returns the new
full name, which may differ from what was passed in (because this
function strips whitespace). | zerver/lib/actions.py | check_change_full_name | gutalavijay1111/zulip-vijay | python | def check_change_full_name(user_profile: UserProfile, full_name_raw: str, acting_user: UserProfile) -> str:
"Verifies that the user's proposed full name is valid. The caller\n is responsible for checking check permissions. Returns the new\n full name, which may differ from what was passed in (because this\n function strips whitespace)."
new_full_name = check_full_name(full_name_raw)
do_change_full_name(user_profile, new_full_name, acting_user)
return new_full_name |
def do_change_notification_settings(user_profile: UserProfile, name: str, value: Union[(bool, int, str)], log: bool=True) -> None:
'Takes in a UserProfile object, the name of a global notification\n preference to update, and the value to update to\n '
notification_setting_type = UserProfile.notification_setting_types[name]
assert isinstance(value, notification_setting_type), f'Cannot update {name}: {value} is not an instance of {notification_setting_type}'
setattr(user_profile, name, value)
if ((name == 'enable_digest_emails') and (not value)):
clear_scheduled_emails([user_profile.id], ScheduledEmail.DIGEST)
user_profile.save(update_fields=[name])
event = {'type': 'update_global_notifications', 'user': user_profile.email, 'notification_name': name, 'setting': value}
if log:
log_event(event)
send_event(user_profile.realm, event, [user_profile.id]) | 2,400,474,181,266,589,700 | Takes in a UserProfile object, the name of a global notification
preference to update, and the value to update to | zerver/lib/actions.py | do_change_notification_settings | gutalavijay1111/zulip-vijay | python | def do_change_notification_settings(user_profile: UserProfile, name: str, value: Union[(bool, int, str)], log: bool=True) -> None:
'Takes in a UserProfile object, the name of a global notification\n preference to update, and the value to update to\n '
notification_setting_type = UserProfile.notification_setting_types[name]
assert isinstance(value, notification_setting_type), f'Cannot update {name}: {value} is not an instance of {notification_setting_type}'
setattr(user_profile, name, value)
if ((name == 'enable_digest_emails') and (not value)):
clear_scheduled_emails([user_profile.id], ScheduledEmail.DIGEST)
user_profile.save(update_fields=[name])
event = {'type': 'update_global_notifications', 'user': user_profile.email, 'notification_name': name, 'setting': value}
if log:
log_event(event)
send_event(user_profile.realm, event, [user_profile.id]) |
def update_to_dict_cache(changed_messages: List[Message], realm_id: Optional[int]=None) -> List[int]:
'Updates the message as stored in the to_dict cache (for serving\n messages).'
items_for_remote_cache = {}
message_ids = []
changed_messages_to_dict = MessageDict.to_dict_uncached(changed_messages, realm_id)
for (msg_id, msg) in changed_messages_to_dict.items():
message_ids.append(msg_id)
key = to_dict_cache_key_id(msg_id)
items_for_remote_cache[key] = (msg,)
cache_set_many(items_for_remote_cache)
return message_ids | -8,672,592,399,726,761,000 | Updates the message as stored in the to_dict cache (for serving
messages). | zerver/lib/actions.py | update_to_dict_cache | gutalavijay1111/zulip-vijay | python | def update_to_dict_cache(changed_messages: List[Message], realm_id: Optional[int]=None) -> List[int]:
'Updates the message as stored in the to_dict cache (for serving\n messages).'
items_for_remote_cache = {}
message_ids = []
changed_messages_to_dict = MessageDict.to_dict_uncached(changed_messages, realm_id)
for (msg_id, msg) in changed_messages_to_dict.items():
message_ids.append(msg_id)
key = to_dict_cache_key_id(msg_id)
items_for_remote_cache[key] = (msg,)
cache_set_many(items_for_remote_cache)
return message_ids |
@transaction.atomic
def do_update_message(user_profile: UserProfile, message: Message, new_stream: Optional[Stream], topic_name: Optional[str], propagate_mode: str, send_notification_to_old_thread: bool, send_notification_to_new_thread: bool, content: Optional[str], rendered_content: Optional[str], prior_mention_user_ids: Set[int], mention_user_ids: Set[int], mention_data: Optional[MentionData]=None) -> int:
"\n The main function for message editing. A message edit event can\n modify:\n * the message's content (in which case the caller will have\n set both content and rendered_content),\n * the topic, in which case the caller will have set topic_name\n * or both\n\n With topic edits, propagate_mode determines whether other message\n also have their topics edited.\n "
timestamp = timezone_now()
message.last_edit_time = timestamp
event: Dict[(str, Any)] = {'type': 'update_message', 'user_id': user_profile.id, 'edit_timestamp': datetime_to_timestamp(timestamp), 'message_id': message.id}
edit_history_event: Dict[(str, Any)] = {'user_id': user_profile.id, 'timestamp': event['edit_timestamp']}
changed_messages = [message]
stream_being_edited = None
if message.is_stream_message():
stream_id = message.recipient.type_id
stream_being_edited = get_stream_by_id_in_realm(stream_id, user_profile.realm)
event['stream_name'] = stream_being_edited.name
ums = UserMessage.objects.filter(message=message.id)
if (content is not None):
assert (rendered_content is not None)
assert (mention_data is not None)
for group_id in message.mentions_user_group_ids:
members = mention_data.get_group_members(group_id)
message.mentions_user_ids.update(members)
update_user_message_flags(message, ums)
event['orig_content'] = message.content
event['orig_rendered_content'] = message.rendered_content
edit_history_event['prev_content'] = message.content
edit_history_event['prev_rendered_content'] = message.rendered_content
edit_history_event['prev_rendered_content_version'] = message.rendered_content_version
message.content = content
message.rendered_content = rendered_content
message.rendered_content_version = markdown_version
event['content'] = content
event['rendered_content'] = rendered_content
event['prev_rendered_content_version'] = message.rendered_content_version
event['is_me_message'] = Message.is_status_message(content, rendered_content)
message.has_attachment = check_attachment_reference_change(message)
if message.is_stream_message():
if (topic_name is not None):
new_topic_name = topic_name
else:
new_topic_name = message.topic_name()
stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=new_topic_name)
else:
stream_topic = None
info = get_recipient_info(recipient=message.recipient, sender_id=message.sender_id, stream_topic=stream_topic, possible_wildcard_mention=mention_data.message_has_wildcards())
event['push_notify_user_ids'] = list(info['push_notify_user_ids'])
event['stream_push_user_ids'] = list(info['stream_push_user_ids'])
event['stream_email_user_ids'] = list(info['stream_email_user_ids'])
event['prior_mention_user_ids'] = list(prior_mention_user_ids)
event['mention_user_ids'] = list(mention_user_ids)
event['presence_idle_user_ids'] = filter_presence_idle_user_ids(info['active_user_ids'])
if message.mentions_wildcard:
event['wildcard_mention_user_ids'] = list(info['wildcard_mention_user_ids'])
else:
event['wildcard_mention_user_ids'] = []
do_update_mobile_push_notification(message, prior_mention_user_ids, info['stream_push_user_ids'])
if ((topic_name is not None) or (new_stream is not None)):
orig_topic_name = message.topic_name()
event['propagate_mode'] = propagate_mode
event['stream_id'] = message.recipient.type_id
if (new_stream is not None):
assert (content is None)
assert message.is_stream_message()
assert (stream_being_edited is not None)
edit_history_event['prev_stream'] = stream_being_edited.id
event[ORIG_TOPIC] = orig_topic_name
message.recipient_id = new_stream.recipient_id
event['new_stream_id'] = new_stream.id
event['propagate_mode'] = propagate_mode
subscribers = get_active_subscriptions_for_stream_id(stream_id).select_related('user_profile')
subs_to_new_stream = list(get_active_subscriptions_for_stream_id(new_stream.id).select_related('user_profile'))
new_stream_sub_ids = [user.user_profile_id for user in subs_to_new_stream]
subs_losing_usermessages = [sub for sub in subscribers if (sub.user_profile_id not in new_stream_sub_ids)]
subs_losing_access = [sub for sub in subs_losing_usermessages if sub.user_profile.is_guest]
ums = ums.exclude(user_profile_id__in=[sub.user_profile_id for sub in subs_losing_usermessages])
if (topic_name is not None):
topic_name = truncate_topic(topic_name)
message.set_topic_name(topic_name)
event[ORIG_TOPIC] = orig_topic_name
event[TOPIC_NAME] = topic_name
event[TOPIC_LINKS] = topic_links(message.sender.realm_id, topic_name)
edit_history_event[LEGACY_PREV_TOPIC] = orig_topic_name
delete_event_notify_user_ids: List[int] = []
if (propagate_mode in ['change_later', 'change_all']):
assert ((topic_name is not None) or (new_stream is not None))
messages_list = update_messages_for_topic_edit(message=message, propagate_mode=propagate_mode, orig_topic_name=orig_topic_name, topic_name=topic_name, new_stream=new_stream)
changed_messages += messages_list
if (new_stream is not None):
assert (stream_being_edited is not None)
message_ids = [msg.id for msg in changed_messages]
UserMessage.objects.filter(user_profile_id__in=[sub.user_profile_id for sub in subs_losing_usermessages], message_id__in=message_ids).delete()
delete_event: DeleteMessagesEvent = {'type': 'delete_message', 'message_ids': message_ids, 'message_type': 'stream', 'stream_id': stream_being_edited.id, 'topic': orig_topic_name}
delete_event_notify_user_ids = [sub.user_profile_id for sub in subs_losing_access]
send_event(user_profile.realm, delete_event, delete_event_notify_user_ids)
if (message.edit_history is not None):
edit_history = ujson.loads(message.edit_history)
edit_history.insert(0, edit_history_event)
else:
edit_history = [edit_history_event]
message.edit_history = ujson.dumps(edit_history)
save_message_for_edit_use_case(message=message)
realm_id: Optional[int] = None
if (stream_being_edited is not None):
realm_id = stream_being_edited.realm_id
event['message_ids'] = update_to_dict_cache(changed_messages, realm_id)
def user_info(um: UserMessage) -> Dict[(str, Any)]:
return {'id': um.user_profile_id, 'flags': um.flags_list()}
users_to_be_notified = list(map(user_info, ums))
if (stream_being_edited is not None):
if stream_being_edited.is_history_public_to_subscribers:
subscribers = get_active_subscriptions_for_stream_id(stream_id)
subscribers = subscribers.exclude(user_profile__long_term_idle=True)
subscribers = subscribers.exclude(user_profile_id__in=[um.user_profile_id for um in ums])
if (new_stream is not None):
assert (delete_event_notify_user_ids is not None)
subscribers = subscribers.exclude(user_profile_id__in=delete_event_notify_user_ids)
subscriber_ids = [user.user_profile_id for user in subscribers]
if (new_stream is not None):
old_stream_unsubbed_guests = [sub for sub in subs_to_new_stream if (sub.user_profile.is_guest and (sub.user_profile_id not in subscriber_ids))]
subscribers = subscribers.exclude(user_profile_id__in=[sub.user_profile_id for sub in old_stream_unsubbed_guests])
subscriber_ids = [user.user_profile_id for user in subscribers]
users_to_be_notified += list(map(subscriber_info, subscriber_ids))
send_event(user_profile.realm, event, users_to_be_notified)
if ((len(changed_messages) > 0) and (new_stream is not None) and (stream_being_edited is not None)):
notify_topic_moved_streams(user_profile, stream_being_edited, orig_topic_name, new_stream, topic_name, send_notification_to_old_thread, send_notification_to_new_thread)
return len(changed_messages) | -8,048,410,790,288,677,000 | The main function for message editing. A message edit event can
modify:
* the message's content (in which case the caller will have
set both content and rendered_content),
* the topic, in which case the caller will have set topic_name
* or both
With topic edits, propagate_mode determines whether other message
also have their topics edited. | zerver/lib/actions.py | do_update_message | gutalavijay1111/zulip-vijay | python | @transaction.atomic
def do_update_message(user_profile: UserProfile, message: Message, new_stream: Optional[Stream], topic_name: Optional[str], propagate_mode: str, send_notification_to_old_thread: bool, send_notification_to_new_thread: bool, content: Optional[str], rendered_content: Optional[str], prior_mention_user_ids: Set[int], mention_user_ids: Set[int], mention_data: Optional[MentionData]=None) -> int:
"\n The main function for message editing. A message edit event can\n modify:\n * the message's content (in which case the caller will have\n set both content and rendered_content),\n * the topic, in which case the caller will have set topic_name\n * or both\n\n With topic edits, propagate_mode determines whether other message\n also have their topics edited.\n "
timestamp = timezone_now()
message.last_edit_time = timestamp
event: Dict[(str, Any)] = {'type': 'update_message', 'user_id': user_profile.id, 'edit_timestamp': datetime_to_timestamp(timestamp), 'message_id': message.id}
edit_history_event: Dict[(str, Any)] = {'user_id': user_profile.id, 'timestamp': event['edit_timestamp']}
changed_messages = [message]
stream_being_edited = None
if message.is_stream_message():
stream_id = message.recipient.type_id
stream_being_edited = get_stream_by_id_in_realm(stream_id, user_profile.realm)
event['stream_name'] = stream_being_edited.name
ums = UserMessage.objects.filter(message=message.id)
if (content is not None):
assert (rendered_content is not None)
assert (mention_data is not None)
for group_id in message.mentions_user_group_ids:
members = mention_data.get_group_members(group_id)
message.mentions_user_ids.update(members)
update_user_message_flags(message, ums)
event['orig_content'] = message.content
event['orig_rendered_content'] = message.rendered_content
edit_history_event['prev_content'] = message.content
edit_history_event['prev_rendered_content'] = message.rendered_content
edit_history_event['prev_rendered_content_version'] = message.rendered_content_version
message.content = content
message.rendered_content = rendered_content
message.rendered_content_version = markdown_version
event['content'] = content
event['rendered_content'] = rendered_content
event['prev_rendered_content_version'] = message.rendered_content_version
event['is_me_message'] = Message.is_status_message(content, rendered_content)
message.has_attachment = check_attachment_reference_change(message)
if message.is_stream_message():
if (topic_name is not None):
new_topic_name = topic_name
else:
new_topic_name = message.topic_name()
stream_topic: Optional[StreamTopicTarget] = StreamTopicTarget(stream_id=stream_id, topic_name=new_topic_name)
else:
stream_topic = None
info = get_recipient_info(recipient=message.recipient, sender_id=message.sender_id, stream_topic=stream_topic, possible_wildcard_mention=mention_data.message_has_wildcards())
event['push_notify_user_ids'] = list(info['push_notify_user_ids'])
event['stream_push_user_ids'] = list(info['stream_push_user_ids'])
event['stream_email_user_ids'] = list(info['stream_email_user_ids'])
event['prior_mention_user_ids'] = list(prior_mention_user_ids)
event['mention_user_ids'] = list(mention_user_ids)
event['presence_idle_user_ids'] = filter_presence_idle_user_ids(info['active_user_ids'])
if message.mentions_wildcard:
event['wildcard_mention_user_ids'] = list(info['wildcard_mention_user_ids'])
else:
event['wildcard_mention_user_ids'] = []
do_update_mobile_push_notification(message, prior_mention_user_ids, info['stream_push_user_ids'])
if ((topic_name is not None) or (new_stream is not None)):
orig_topic_name = message.topic_name()
event['propagate_mode'] = propagate_mode
event['stream_id'] = message.recipient.type_id
if (new_stream is not None):
assert (content is None)
assert message.is_stream_message()
assert (stream_being_edited is not None)
edit_history_event['prev_stream'] = stream_being_edited.id
event[ORIG_TOPIC] = orig_topic_name
message.recipient_id = new_stream.recipient_id
event['new_stream_id'] = new_stream.id
event['propagate_mode'] = propagate_mode
subscribers = get_active_subscriptions_for_stream_id(stream_id).select_related('user_profile')
subs_to_new_stream = list(get_active_subscriptions_for_stream_id(new_stream.id).select_related('user_profile'))
new_stream_sub_ids = [user.user_profile_id for user in subs_to_new_stream]
subs_losing_usermessages = [sub for sub in subscribers if (sub.user_profile_id not in new_stream_sub_ids)]
subs_losing_access = [sub for sub in subs_losing_usermessages if sub.user_profile.is_guest]
ums = ums.exclude(user_profile_id__in=[sub.user_profile_id for sub in subs_losing_usermessages])
if (topic_name is not None):
topic_name = truncate_topic(topic_name)
message.set_topic_name(topic_name)
event[ORIG_TOPIC] = orig_topic_name
event[TOPIC_NAME] = topic_name
event[TOPIC_LINKS] = topic_links(message.sender.realm_id, topic_name)
edit_history_event[LEGACY_PREV_TOPIC] = orig_topic_name
delete_event_notify_user_ids: List[int] = []
if (propagate_mode in ['change_later', 'change_all']):
assert ((topic_name is not None) or (new_stream is not None))
messages_list = update_messages_for_topic_edit(message=message, propagate_mode=propagate_mode, orig_topic_name=orig_topic_name, topic_name=topic_name, new_stream=new_stream)
changed_messages += messages_list
if (new_stream is not None):
assert (stream_being_edited is not None)
message_ids = [msg.id for msg in changed_messages]
UserMessage.objects.filter(user_profile_id__in=[sub.user_profile_id for sub in subs_losing_usermessages], message_id__in=message_ids).delete()
delete_event: DeleteMessagesEvent = {'type': 'delete_message', 'message_ids': message_ids, 'message_type': 'stream', 'stream_id': stream_being_edited.id, 'topic': orig_topic_name}
delete_event_notify_user_ids = [sub.user_profile_id for sub in subs_losing_access]
send_event(user_profile.realm, delete_event, delete_event_notify_user_ids)
if (message.edit_history is not None):
edit_history = ujson.loads(message.edit_history)
edit_history.insert(0, edit_history_event)
else:
edit_history = [edit_history_event]
message.edit_history = ujson.dumps(edit_history)
save_message_for_edit_use_case(message=message)
realm_id: Optional[int] = None
if (stream_being_edited is not None):
realm_id = stream_being_edited.realm_id
event['message_ids'] = update_to_dict_cache(changed_messages, realm_id)
def user_info(um: UserMessage) -> Dict[(str, Any)]:
return {'id': um.user_profile_id, 'flags': um.flags_list()}
users_to_be_notified = list(map(user_info, ums))
if (stream_being_edited is not None):
if stream_being_edited.is_history_public_to_subscribers:
subscribers = get_active_subscriptions_for_stream_id(stream_id)
subscribers = subscribers.exclude(user_profile__long_term_idle=True)
subscribers = subscribers.exclude(user_profile_id__in=[um.user_profile_id for um in ums])
if (new_stream is not None):
assert (delete_event_notify_user_ids is not None)
subscribers = subscribers.exclude(user_profile_id__in=delete_event_notify_user_ids)
subscriber_ids = [user.user_profile_id for user in subscribers]
if (new_stream is not None):
old_stream_unsubbed_guests = [sub for sub in subs_to_new_stream if (sub.user_profile.is_guest and (sub.user_profile_id not in subscriber_ids))]
subscribers = subscribers.exclude(user_profile_id__in=[sub.user_profile_id for sub in old_stream_unsubbed_guests])
subscriber_ids = [user.user_profile_id for user in subscribers]
users_to_be_notified += list(map(subscriber_info, subscriber_ids))
send_event(user_profile.realm, event, users_to_be_notified)
if ((len(changed_messages) > 0) and (new_stream is not None) and (stream_being_edited is not None)):
notify_topic_moved_streams(user_profile, stream_being_edited, orig_topic_name, new_stream, topic_name, send_notification_to_old_thread, send_notification_to_new_thread)
return len(changed_messages) |
def get_active_presence_idle_user_ids(realm: Realm, sender_id: int, message_type: str, active_user_ids: Set[int], user_flags: Dict[(int, List[str])]) -> List[int]:
'\n Given a list of active_user_ids, we build up a subset\n of those users who fit these criteria:\n\n * They are likely to need notifications (either due\n to mentions, alert words, or being PM\'ed).\n * They are no longer "present" according to the\n UserPresence table.\n '
if realm.presence_disabled:
return []
is_pm = (message_type == 'private')
user_ids = set()
for user_id in active_user_ids:
flags: Iterable[str] = user_flags.get(user_id, [])
mentioned = (('mentioned' in flags) or ('wildcard_mentioned' in flags))
private_message = (is_pm and (user_id != sender_id))
alerted = ('has_alert_word' in flags)
if (mentioned or private_message or alerted):
user_ids.add(user_id)
return filter_presence_idle_user_ids(user_ids) | 8,566,640,318,382,904,000 | Given a list of active_user_ids, we build up a subset
of those users who fit these criteria:
* They are likely to need notifications (either due
to mentions, alert words, or being PM'ed).
* They are no longer "present" according to the
UserPresence table. | zerver/lib/actions.py | get_active_presence_idle_user_ids | gutalavijay1111/zulip-vijay | python | def get_active_presence_idle_user_ids(realm: Realm, sender_id: int, message_type: str, active_user_ids: Set[int], user_flags: Dict[(int, List[str])]) -> List[int]:
'\n Given a list of active_user_ids, we build up a subset\n of those users who fit these criteria:\n\n * They are likely to need notifications (either due\n to mentions, alert words, or being PM\'ed).\n * They are no longer "present" according to the\n UserPresence table.\n '
if realm.presence_disabled:
return []
is_pm = (message_type == 'private')
user_ids = set()
for user_id in active_user_ids:
flags: Iterable[str] = user_flags.get(user_id, [])
mentioned = (('mentioned' in flags) or ('wildcard_mentioned' in flags))
private_message = (is_pm and (user_id != sender_id))
alerted = ('has_alert_word' in flags)
if (mentioned or private_message or alerted):
user_ids.add(user_id)
return filter_presence_idle_user_ids(user_ids) |
def do_send_confirmation_email(invitee: PreregistrationUser, referrer: UserProfile) -> str:
'\n Send the confirmation/welcome e-mail to an invited user.\n '
activation_url = create_confirmation_link(invitee, Confirmation.INVITATION)
context = {'referrer_full_name': referrer.full_name, 'referrer_email': referrer.delivery_email, 'activate_url': activation_url, 'referrer_realm_name': referrer.realm.name}
from_name = f'{referrer.full_name} (via Zulip)'
send_email('zerver/emails/invitation', to_emails=[invitee.email], from_name=from_name, from_address=FromAddress.tokenized_no_reply_address(), language=referrer.realm.default_language, context=context, realm=referrer.realm)
return activation_url | -1,069,681,938,076,176,300 | Send the confirmation/welcome e-mail to an invited user. | zerver/lib/actions.py | do_send_confirmation_email | gutalavijay1111/zulip-vijay | python | def do_send_confirmation_email(invitee: PreregistrationUser, referrer: UserProfile) -> str:
'\n \n '
activation_url = create_confirmation_link(invitee, Confirmation.INVITATION)
context = {'referrer_full_name': referrer.full_name, 'referrer_email': referrer.delivery_email, 'activate_url': activation_url, 'referrer_realm_name': referrer.realm.name}
from_name = f'{referrer.full_name} (via Zulip)'
send_email('zerver/emails/invitation', to_emails=[invitee.email], from_name=from_name, from_address=FromAddress.tokenized_no_reply_address(), language=referrer.realm.default_language, context=context, realm=referrer.realm)
return activation_url |
def estimate_recent_invites(realms: Iterable[Realm], *, days: int) -> int:
'An upper bound on the number of invites sent in the last `days` days'
recent_invites = RealmCount.objects.filter(realm__in=realms, property='invites_sent::day', end_time__gte=(timezone_now() - datetime.timedelta(days=days))).aggregate(Sum('value'))['value__sum']
if (recent_invites is None):
return 0
return recent_invites | 8,210,028,317,846,155,000 | An upper bound on the number of invites sent in the last `days` days | zerver/lib/actions.py | estimate_recent_invites | gutalavijay1111/zulip-vijay | python | def estimate_recent_invites(realms: Iterable[Realm], *, days: int) -> int:
recent_invites = RealmCount.objects.filter(realm__in=realms, property='invites_sent::day', end_time__gte=(timezone_now() - datetime.timedelta(days=days))).aggregate(Sum('value'))['value__sum']
if (recent_invites is None):
return 0
return recent_invites |
def check_invite_limit(realm: Realm, num_invitees: int) -> None:
'Discourage using invitation emails as a vector for carrying spam.'
msg = _('You do not have enough remaining invites. Please contact {email} to have your limit raised. No invitations were sent.').format(email=settings.ZULIP_ADMINISTRATOR)
if (not settings.OPEN_REALM_CREATION):
return
recent_invites = estimate_recent_invites([realm], days=1)
if ((num_invitees + recent_invites) > realm.max_invites):
raise InvitationError(msg, [], sent_invitations=False)
default_max = settings.INVITES_DEFAULT_REALM_DAILY_MAX
newrealm_age = datetime.timedelta(days=settings.INVITES_NEW_REALM_DAYS)
if (realm.date_created <= (timezone_now() - newrealm_age)):
return
if (realm.max_invites > default_max):
return
new_realms = Realm.objects.filter(date_created__gte=(timezone_now() - newrealm_age), _max_invites__lte=default_max).all()
for (days, count) in settings.INVITES_NEW_REALM_LIMIT_DAYS:
recent_invites = estimate_recent_invites(new_realms, days=days)
if ((num_invitees + recent_invites) > count):
raise InvitationError(msg, [], sent_invitations=False) | 2,595,359,616,693,616,600 | Discourage using invitation emails as a vector for carrying spam. | zerver/lib/actions.py | check_invite_limit | gutalavijay1111/zulip-vijay | python | def check_invite_limit(realm: Realm, num_invitees: int) -> None:
msg = _('You do not have enough remaining invites. Please contact {email} to have your limit raised. No invitations were sent.').format(email=settings.ZULIP_ADMINISTRATOR)
if (not settings.OPEN_REALM_CREATION):
return
recent_invites = estimate_recent_invites([realm], days=1)
if ((num_invitees + recent_invites) > realm.max_invites):
raise InvitationError(msg, [], sent_invitations=False)
default_max = settings.INVITES_DEFAULT_REALM_DAILY_MAX
newrealm_age = datetime.timedelta(days=settings.INVITES_NEW_REALM_DAYS)
if (realm.date_created <= (timezone_now() - newrealm_age)):
return
if (realm.max_invites > default_max):
return
new_realms = Realm.objects.filter(date_created__gte=(timezone_now() - newrealm_age), _max_invites__lte=default_max).all()
for (days, count) in settings.INVITES_NEW_REALM_LIMIT_DAYS:
recent_invites = estimate_recent_invites(new_realms, days=days)
if ((num_invitees + recent_invites) > count):
raise InvitationError(msg, [], sent_invitations=False) |
def get_occupied_streams(realm: Realm) -> QuerySet:
' Get streams with subscribers '
exists_expression = Exists(Subscription.objects.filter(active=True, user_profile__is_active=True, user_profile__realm=realm, recipient_id=OuterRef('recipient_id')))
occupied_streams = Stream.objects.filter(realm=realm, deactivated=False).annotate(occupied=exists_expression).filter(occupied=True)
return occupied_streams | 5,858,783,591,674,588,000 | Get streams with subscribers | zerver/lib/actions.py | get_occupied_streams | gutalavijay1111/zulip-vijay | python | def get_occupied_streams(realm: Realm) -> QuerySet:
' '
exists_expression = Exists(Subscription.objects.filter(active=True, user_profile__is_active=True, user_profile__realm=realm, recipient_id=OuterRef('recipient_id')))
occupied_streams = Stream.objects.filter(realm=realm, deactivated=False).annotate(occupied=exists_expression).filter(occupied=True)
return occupied_streams |
def do_remove_realm_custom_profile_field(realm: Realm, field: CustomProfileField) -> None:
'\n Deleting a field will also delete the user profile data\n associated with it in CustomProfileFieldValue model.\n '
field.delete()
notify_realm_custom_profile_fields(realm, 'delete') | -8,935,250,695,324,977,000 | Deleting a field will also delete the user profile data
associated with it in CustomProfileFieldValue model. | zerver/lib/actions.py | do_remove_realm_custom_profile_field | gutalavijay1111/zulip-vijay | python | def do_remove_realm_custom_profile_field(realm: Realm, field: CustomProfileField) -> None:
'\n Deleting a field will also delete the user profile data\n associated with it in CustomProfileFieldValue model.\n '
field.delete()
notify_realm_custom_profile_fields(realm, 'delete') |
def get_ids_for(f: Callable[([Dict[(str, Any)]], bool)]) -> Set[int]:
'Only includes users on the explicit message to line'
return ({row['id'] for row in rows if f(row)} & message_to_user_id_set) | -8,346,664,401,585,981,000 | Only includes users on the explicit message to line | zerver/lib/actions.py | get_ids_for | gutalavijay1111/zulip-vijay | python | def get_ids_for(f: Callable[([Dict[(str, Any)]], bool)]) -> Set[int]:
return ({row['id'] for row in rows if f(row)} & message_to_user_id_set) |
def train(self, mode=True):
'Populate label similarity map based on cosine similarity before running epoch\n\n If the `num_negative_labels_to_sample` is set to an integer value then before starting\n each epoch the model would create a similarity measure between the label names based\n on cosine distances between their BERT encoded embeddings.\n '
if (mode and (self.num_negative_labels_to_sample is not None)):
self._compute_label_similarity_for_current_epoch()
super().train(mode)
super().train(mode) | -4,809,101,940,404,317,000 | Populate label similarity map based on cosine similarity before running epoch
If the `num_negative_labels_to_sample` is set to an integer value then before starting
each epoch the model would create a similarity measure between the label names based
on cosine distances between their BERT encoded embeddings. | flair/models/tars_model.py | train | garciaeduardo7143/flair | python | def train(self, mode=True):
'Populate label similarity map based on cosine similarity before running epoch\n\n If the `num_negative_labels_to_sample` is set to an integer value then before starting\n each epoch the model would create a similarity measure between the label names based\n on cosine distances between their BERT encoded embeddings.\n '
if (mode and (self.num_negative_labels_to_sample is not None)):
self._compute_label_similarity_for_current_epoch()
super().train(mode)
super().train(mode) |
def _compute_label_similarity_for_current_epoch(self):
'\n Compute the similarity between all labels for better sampling of negatives\n '
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
label_sentences = [Sentence(label) for label in all_labels]
self.tars_embeddings.eval()
self.tars_embeddings.embed(label_sentences)
self.tars_embeddings.train()
if isinstance(self.tars_embeddings, TokenEmbeddings):
encodings_np = [sentence[0].get_embedding().cpu().detach().numpy() for sentence in label_sentences]
else:
encodings_np = [sentence.get_embedding().cpu().detach().numpy() for sentence in label_sentences]
normalized_encoding = minmax_scale(encodings_np)
similarity_matrix = cosine_similarity(normalized_encoding)
negative_label_probabilities = {}
for (row_index, label) in enumerate(all_labels):
negative_label_probabilities[label] = {}
for (column_index, other_label) in enumerate(all_labels):
if (label != other_label):
negative_label_probabilities[label][other_label] = similarity_matrix[row_index][column_index]
self.label_nearest_map = negative_label_probabilities | -4,897,460,015,375,832,000 | Compute the similarity between all labels for better sampling of negatives | flair/models/tars_model.py | _compute_label_similarity_for_current_epoch | garciaeduardo7143/flair | python | def _compute_label_similarity_for_current_epoch(self):
'\n \n '
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
label_sentences = [Sentence(label) for label in all_labels]
self.tars_embeddings.eval()
self.tars_embeddings.embed(label_sentences)
self.tars_embeddings.train()
if isinstance(self.tars_embeddings, TokenEmbeddings):
encodings_np = [sentence[0].get_embedding().cpu().detach().numpy() for sentence in label_sentences]
else:
encodings_np = [sentence.get_embedding().cpu().detach().numpy() for sentence in label_sentences]
normalized_encoding = minmax_scale(encodings_np)
similarity_matrix = cosine_similarity(normalized_encoding)
negative_label_probabilities = {}
for (row_index, label) in enumerate(all_labels):
negative_label_probabilities[label] = {}
for (column_index, other_label) in enumerate(all_labels):
if (label != other_label):
negative_label_probabilities[label][other_label] = similarity_matrix[row_index][column_index]
self.label_nearest_map = negative_label_probabilities |
def add_and_switch_to_new_task(self, task_name, label_dictionary: Union[(List, Set, Dictionary, str)], label_type: str, multi_label: bool=True, force_switch: bool=False):
"\n Adds a new task to an existing TARS model. Sets necessary attributes and finally 'switches'\n to the new task. Parameters are similar to the constructor except for model choice, batch\n size and negative sampling. This method does not store the resultant model onto disk.\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of the labels you want to predict\n :param label_type: string to identify the label type ('ner', 'sentiment', etc.)\n :param multi_label: whether this task is a multi-label prediction problem\n :param force_switch: if True, will overwrite existing task with same name\n "
if ((task_name in self._task_specific_attributes) and (not force_switch)):
log.warning('Task `%s` already exists in TARS model. Switching to it.', task_name)
else:
if isinstance(label_dictionary, Dictionary):
label_dictionary = label_dictionary.get_items()
if (type(label_dictionary) == str):
label_dictionary = [label_dictionary]
tag_dictionary = Dictionary(add_unk=False)
for tag in label_dictionary:
if ((tag == '<unk>') or (tag == 'O')):
continue
if (tag[1] == '-'):
tag = tag[2:]
tag_dictionary.add_item(tag)
else:
tag_dictionary.add_item(tag)
self._task_specific_attributes[task_name] = {'label_dictionary': tag_dictionary, 'label_type': label_type, 'multi_label': multi_label}
self.switch_to_task(task_name) | -2,168,035,682,850,008,600 | Adds a new task to an existing TARS model. Sets necessary attributes and finally 'switches'
to the new task. Parameters are similar to the constructor except for model choice, batch
size and negative sampling. This method does not store the resultant model onto disk.
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of the labels you want to predict
:param label_type: string to identify the label type ('ner', 'sentiment', etc.)
:param multi_label: whether this task is a multi-label prediction problem
:param force_switch: if True, will overwrite existing task with same name | flair/models/tars_model.py | add_and_switch_to_new_task | garciaeduardo7143/flair | python | def add_and_switch_to_new_task(self, task_name, label_dictionary: Union[(List, Set, Dictionary, str)], label_type: str, multi_label: bool=True, force_switch: bool=False):
"\n Adds a new task to an existing TARS model. Sets necessary attributes and finally 'switches'\n to the new task. Parameters are similar to the constructor except for model choice, batch\n size and negative sampling. This method does not store the resultant model onto disk.\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of the labels you want to predict\n :param label_type: string to identify the label type ('ner', 'sentiment', etc.)\n :param multi_label: whether this task is a multi-label prediction problem\n :param force_switch: if True, will overwrite existing task with same name\n "
if ((task_name in self._task_specific_attributes) and (not force_switch)):
log.warning('Task `%s` already exists in TARS model. Switching to it.', task_name)
else:
if isinstance(label_dictionary, Dictionary):
label_dictionary = label_dictionary.get_items()
if (type(label_dictionary) == str):
label_dictionary = [label_dictionary]
tag_dictionary = Dictionary(add_unk=False)
for tag in label_dictionary:
if ((tag == '<unk>') or (tag == 'O')):
continue
if (tag[1] == '-'):
tag = tag[2:]
tag_dictionary.add_item(tag)
else:
tag_dictionary.add_item(tag)
self._task_specific_attributes[task_name] = {'label_dictionary': tag_dictionary, 'label_type': label_type, 'multi_label': multi_label}
self.switch_to_task(task_name) |
def list_existing_tasks(self) -> Set[str]:
'\n Lists existing tasks in the loaded TARS model on the console.\n '
return set(self._task_specific_attributes.keys()) | 6,965,795,004,101,275,000 | Lists existing tasks in the loaded TARS model on the console. | flair/models/tars_model.py | list_existing_tasks | garciaeduardo7143/flair | python | def list_existing_tasks(self) -> Set[str]:
'\n \n '
return set(self._task_specific_attributes.keys()) |
def switch_to_task(self, task_name):
'\n Switches to a task which was previously added.\n '
if (task_name not in self._task_specific_attributes):
log.error('Provided `%s` does not exist in the model. Consider calling `add_and_switch_to_new_task` first.', task_name)
else:
self._current_task = task_name | -3,186,966,254,722,553,300 | Switches to a task which was previously added. | flair/models/tars_model.py | switch_to_task | garciaeduardo7143/flair | python | def switch_to_task(self, task_name):
'\n \n '
if (task_name not in self._task_specific_attributes):
log.error('Provided `%s` does not exist in the model. Consider calling `add_and_switch_to_new_task` first.', task_name)
else:
self._current_task = task_name |
def predict_zero_shot(self, sentences: Union[(List[Sentence], Sentence)], candidate_label_set: Union[(List[str], Set[str], str)], multi_label: bool=True):
'\n Method to make zero shot predictions from the TARS model\n :param sentences: input sentence objects to classify\n :param candidate_label_set: set of candidate labels\n :param multi_label: indicates whether multi-label or single class prediction. Defaults to True.\n '
if ((candidate_label_set is None) or (len(candidate_label_set) == 0)):
log.warning('Provided candidate_label_set is empty')
return
if isinstance(candidate_label_set, str):
candidate_label_set = {candidate_label_set}
label_dictionary = Dictionary(add_unk=False)
for label in candidate_label_set:
label_dictionary.add_item(label)
existing_current_task = self._current_task
self.add_and_switch_to_new_task(task_name='ZeroShot', label_dictionary=label_dictionary, label_type='-'.join(label_dictionary.get_items()), multi_label=multi_label)
try:
self.predict(sentences)
finally:
self.switch_to_task(existing_current_task)
self._drop_task('ZeroShot')
return | -1,446,347,997,733,357,300 | Method to make zero shot predictions from the TARS model
:param sentences: input sentence objects to classify
:param candidate_label_set: set of candidate labels
:param multi_label: indicates whether multi-label or single class prediction. Defaults to True. | flair/models/tars_model.py | predict_zero_shot | garciaeduardo7143/flair | python | def predict_zero_shot(self, sentences: Union[(List[Sentence], Sentence)], candidate_label_set: Union[(List[str], Set[str], str)], multi_label: bool=True):
'\n Method to make zero shot predictions from the TARS model\n :param sentences: input sentence objects to classify\n :param candidate_label_set: set of candidate labels\n :param multi_label: indicates whether multi-label or single class prediction. Defaults to True.\n '
if ((candidate_label_set is None) or (len(candidate_label_set) == 0)):
log.warning('Provided candidate_label_set is empty')
return
if isinstance(candidate_label_set, str):
candidate_label_set = {candidate_label_set}
label_dictionary = Dictionary(add_unk=False)
for label in candidate_label_set:
label_dictionary.add_item(label)
existing_current_task = self._current_task
self.add_and_switch_to_new_task(task_name='ZeroShot', label_dictionary=label_dictionary, label_type='-'.join(label_dictionary.get_items()), multi_label=multi_label)
try:
self.predict(sentences)
finally:
self.switch_to_task(existing_current_task)
self._drop_task('ZeroShot')
return |
def __init__(self, task_name: Optional[str]=None, label_dictionary: Optional[Dictionary]=None, label_type: Optional[str]=None, embeddings: Union[(TransformerWordEmbeddings, str)]='bert-base-uncased', num_negative_labels_to_sample: int=2, prefix: bool=True, **tagger_args):
"\n Initializes a TextClassifier\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of labels you want to predict\n :param embeddings: name of the pre-trained transformer model e.g.,\n 'bert-base-uncased' etc\n :param num_negative_labels_to_sample: number of negative labels to sample for each\n positive labels against a sentence during training. Defaults to 2 negative\n labels for each positive label. The model would sample all the negative labels\n if None is passed. That slows down the training considerably.\n "
super(TARSTagger, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerWordEmbeddings(model=embeddings, fine_tune=True, layers='-1', layer_mean=False)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item('entity')
tars_dictionary.span_labels = True
self.tars_model: SequenceTagger = SequenceTagger(hidden_size=123, embeddings=embeddings, tag_dictionary=tars_dictionary, tag_type=self.static_label_type, use_crf=False, use_rnn=False, reproject_embeddings=False, **tagger_args)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if (task_name and label_dictionary and label_type):
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info('TARS initialized without a task. You need to call .add_and_switch_to_new_task() before training this model') | -356,820,534,521,518,200 | Initializes a TextClassifier
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of labels you want to predict
:param embeddings: name of the pre-trained transformer model e.g.,
'bert-base-uncased' etc
:param num_negative_labels_to_sample: number of negative labels to sample for each
positive labels against a sentence during training. Defaults to 2 negative
labels for each positive label. The model would sample all the negative labels
if None is passed. That slows down the training considerably. | flair/models/tars_model.py | __init__ | garciaeduardo7143/flair | python | def __init__(self, task_name: Optional[str]=None, label_dictionary: Optional[Dictionary]=None, label_type: Optional[str]=None, embeddings: Union[(TransformerWordEmbeddings, str)]='bert-base-uncased', num_negative_labels_to_sample: int=2, prefix: bool=True, **tagger_args):
"\n Initializes a TextClassifier\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of labels you want to predict\n :param embeddings: name of the pre-trained transformer model e.g.,\n 'bert-base-uncased' etc\n :param num_negative_labels_to_sample: number of negative labels to sample for each\n positive labels against a sentence during training. Defaults to 2 negative\n labels for each positive label. The model would sample all the negative labels\n if None is passed. That slows down the training considerably.\n "
super(TARSTagger, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerWordEmbeddings(model=embeddings, fine_tune=True, layers='-1', layer_mean=False)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item('entity')
tars_dictionary.span_labels = True
self.tars_model: SequenceTagger = SequenceTagger(hidden_size=123, embeddings=embeddings, tag_dictionary=tars_dictionary, tag_type=self.static_label_type, use_crf=False, use_rnn=False, reproject_embeddings=False, **tagger_args)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if (task_name and label_dictionary and label_type):
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info('TARS initialized without a task. You need to call .add_and_switch_to_new_task() before training this model') |
def predict(self, sentences: Union[(List[Sentence], Sentence)], mini_batch_size=32, return_probabilities_for_all_classes: bool=False, verbose: bool=False, label_name: Optional[str]=None, return_loss=False, embedding_storage_mode='none', most_probable_first: bool=True):
"\n Predict sequence tags for Named Entity Recognition task\n :param sentences: a Sentence or a List of Sentence\n :param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,\n up to a point when it has no more effect.\n :param all_tag_prob: True to compute the score for each tag on each token,\n otherwise only the score of the best tag is returned\n :param verbose: set to True to display a progress bar\n :param return_loss: set to True to return loss\n :param label_name: set this to change the name of the label type that is predicted\n :param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if\n you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.\n 'gpu' to store embeddings in GPU memory.\n "
if (label_name is None):
label_name = self.get_current_label_type()
if (not sentences):
return sentences
if (not isinstance(sentences, list)):
sentences = [sentences]
reordered_sentences = sorted(sentences, key=(lambda s: len(s)), reverse=True)
dataloader = DataLoader(dataset=FlairDatapointDataset(reordered_sentences), batch_size=mini_batch_size)
if verbose:
dataloader = tqdm(dataloader)
overall_loss = 0
overall_count = 0
with torch.no_grad():
for batch in dataloader:
batch = self._filter_empty_sentences(batch)
if (not batch):
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
all_detected = {}
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(tars_sentence, label_name=label_name, return_loss=True)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted in tars_sentence.get_labels(label_name):
predicted.value = label
all_detected[predicted] = predicted.score
if most_probable_first:
import operator
already_set_indices: List[int] = []
sorted_x = sorted(all_detected.items(), key=operator.itemgetter(1))
sorted_x.reverse()
for tuple in sorted_x:
label = tuple[0]
label_length = (0 if (not self.prefix) else (len(label.value.split(' ')) + len(self.separator.split(' '))))
tag_this = True
for token in label.span:
corresponding_token = sentence.get_token((token.idx - label_length))
if (corresponding_token is None):
tag_this = False
continue
if (token.idx in already_set_indices):
tag_this = False
continue
if tag_this:
already_set_indices.extend((token.idx for token in label.span))
predicted_span = [sentence.get_token((token.idx - label_length)) for token in label.span]
sentence.add_complex_label(label_name, label=SpanLabel(Span(predicted_span), value=label.value, score=label.score))
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return (overall_loss, overall_count) | -2,638,801,726,960,084,000 | Predict sequence tags for Named Entity Recognition task
:param sentences: a Sentence or a List of Sentence
:param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,
up to a point when it has no more effect.
:param all_tag_prob: True to compute the score for each tag on each token,
otherwise only the score of the best tag is returned
:param verbose: set to True to display a progress bar
:param return_loss: set to True to return loss
:param label_name: set this to change the name of the label type that is predicted
:param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if
you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.
'gpu' to store embeddings in GPU memory. | flair/models/tars_model.py | predict | garciaeduardo7143/flair | python | def predict(self, sentences: Union[(List[Sentence], Sentence)], mini_batch_size=32, return_probabilities_for_all_classes: bool=False, verbose: bool=False, label_name: Optional[str]=None, return_loss=False, embedding_storage_mode='none', most_probable_first: bool=True):
"\n Predict sequence tags for Named Entity Recognition task\n :param sentences: a Sentence or a List of Sentence\n :param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,\n up to a point when it has no more effect.\n :param all_tag_prob: True to compute the score for each tag on each token,\n otherwise only the score of the best tag is returned\n :param verbose: set to True to display a progress bar\n :param return_loss: set to True to return loss\n :param label_name: set this to change the name of the label type that is predicted\n :param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if\n you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.\n 'gpu' to store embeddings in GPU memory.\n "
if (label_name is None):
label_name = self.get_current_label_type()
if (not sentences):
return sentences
if (not isinstance(sentences, list)):
sentences = [sentences]
reordered_sentences = sorted(sentences, key=(lambda s: len(s)), reverse=True)
dataloader = DataLoader(dataset=FlairDatapointDataset(reordered_sentences), batch_size=mini_batch_size)
if verbose:
dataloader = tqdm(dataloader)
overall_loss = 0
overall_count = 0
with torch.no_grad():
for batch in dataloader:
batch = self._filter_empty_sentences(batch)
if (not batch):
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
all_detected = {}
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(tars_sentence, label_name=label_name, return_loss=True)
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted in tars_sentence.get_labels(label_name):
predicted.value = label
all_detected[predicted] = predicted.score
if most_probable_first:
import operator
already_set_indices: List[int] = []
sorted_x = sorted(all_detected.items(), key=operator.itemgetter(1))
sorted_x.reverse()
for tuple in sorted_x:
label = tuple[0]
label_length = (0 if (not self.prefix) else (len(label.value.split(' ')) + len(self.separator.split(' '))))
tag_this = True
for token in label.span:
corresponding_token = sentence.get_token((token.idx - label_length))
if (corresponding_token is None):
tag_this = False
continue
if (token.idx in already_set_indices):
tag_this = False
continue
if tag_this:
already_set_indices.extend((token.idx for token in label.span))
predicted_span = [sentence.get_token((token.idx - label_length)) for token in label.span]
sentence.add_complex_label(label_name, label=SpanLabel(Span(predicted_span), value=label.value, score=label.score))
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return (overall_loss, overall_count) |
def __init__(self, task_name: Optional[str]=None, label_dictionary: Optional[Dictionary]=None, label_type: Optional[str]=None, embeddings: Union[(TransformerDocumentEmbeddings, str)]='bert-base-uncased', num_negative_labels_to_sample: int=2, prefix: bool=True, **tagger_args):
"\n Initializes a TextClassifier\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of labels you want to predict\n :param embeddings: name of the pre-trained transformer model e.g.,\n 'bert-base-uncased' etc\n :param num_negative_labels_to_sample: number of negative labels to sample for each\n positive labels against a sentence during training. Defaults to 2 negative\n labels for each positive label. The model would sample all the negative labels\n if None is passed. That slows down the training considerably.\n :param multi_label: auto-detected by default, but you can set this to True\n to force multi-label predictionor False to force single-label prediction\n :param multi_label_threshold: If multi-label you can set the threshold to make predictions\n :param beta: Parameter for F-beta score for evaluation and training annealing\n "
super(TARSClassifier, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerDocumentEmbeddings(model=embeddings, fine_tune=True, layers='-1', layer_mean=False)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item(self.LABEL_NO_MATCH)
tars_dictionary.add_item(self.LABEL_MATCH)
self.tars_model = TextClassifier(document_embeddings=embeddings, label_dictionary=tars_dictionary, label_type=self.static_label_type, **tagger_args)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if (task_name and label_dictionary and label_type):
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info('TARS initialized without a task. You need to call .add_and_switch_to_new_task() before training this model')
self.clean_up_labels = True | 1,821,094,420,257,161,000 | Initializes a TextClassifier
:param task_name: a string depicting the name of the task
:param label_dictionary: dictionary of labels you want to predict
:param embeddings: name of the pre-trained transformer model e.g.,
'bert-base-uncased' etc
:param num_negative_labels_to_sample: number of negative labels to sample for each
positive labels against a sentence during training. Defaults to 2 negative
labels for each positive label. The model would sample all the negative labels
if None is passed. That slows down the training considerably.
:param multi_label: auto-detected by default, but you can set this to True
to force multi-label predictionor False to force single-label prediction
:param multi_label_threshold: If multi-label you can set the threshold to make predictions
:param beta: Parameter for F-beta score for evaluation and training annealing | flair/models/tars_model.py | __init__ | garciaeduardo7143/flair | python | def __init__(self, task_name: Optional[str]=None, label_dictionary: Optional[Dictionary]=None, label_type: Optional[str]=None, embeddings: Union[(TransformerDocumentEmbeddings, str)]='bert-base-uncased', num_negative_labels_to_sample: int=2, prefix: bool=True, **tagger_args):
"\n Initializes a TextClassifier\n :param task_name: a string depicting the name of the task\n :param label_dictionary: dictionary of labels you want to predict\n :param embeddings: name of the pre-trained transformer model e.g.,\n 'bert-base-uncased' etc\n :param num_negative_labels_to_sample: number of negative labels to sample for each\n positive labels against a sentence during training. Defaults to 2 negative\n labels for each positive label. The model would sample all the negative labels\n if None is passed. That slows down the training considerably.\n :param multi_label: auto-detected by default, but you can set this to True\n to force multi-label predictionor False to force single-label prediction\n :param multi_label_threshold: If multi-label you can set the threshold to make predictions\n :param beta: Parameter for F-beta score for evaluation and training annealing\n "
super(TARSClassifier, self).__init__()
if isinstance(embeddings, str):
embeddings = TransformerDocumentEmbeddings(model=embeddings, fine_tune=True, layers='-1', layer_mean=False)
tars_dictionary = Dictionary(add_unk=False)
tars_dictionary.add_item(self.LABEL_NO_MATCH)
tars_dictionary.add_item(self.LABEL_MATCH)
self.tars_model = TextClassifier(document_embeddings=embeddings, label_dictionary=tars_dictionary, label_type=self.static_label_type, **tagger_args)
self.separator = str(self.tars_embeddings.tokenizer.sep_token)
if self.tars_embeddings.tokenizer._bos_token:
self.separator += str(self.tars_embeddings.tokenizer.bos_token)
self.prefix = prefix
self.num_negative_labels_to_sample = num_negative_labels_to_sample
if (task_name and label_dictionary and label_type):
self.add_and_switch_to_new_task(task_name, label_dictionary, label_type)
else:
log.info('TARS initialized without a task. You need to call .add_and_switch_to_new_task() before training this model')
self.clean_up_labels = True |
def predict(self, sentences: Union[(List[Sentence], Sentence)], mini_batch_size=32, return_probabilities_for_all_classes: bool=False, verbose: bool=False, label_name: Optional[str]=None, return_loss=False, embedding_storage_mode='none', label_threshold: float=0.5, multi_label: Optional[bool]=None):
"\n Predict sequence tags for Named Entity Recognition task\n :param sentences: a Sentence or a List of Sentence\n :param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,\n up to a point when it has no more effect.\n :param all_tag_prob: True to compute the score for each tag on each token,\n otherwise only the score of the best tag is returned\n :param verbose: set to True to display a progress bar\n :param return_loss: set to True to return loss\n :param label_name: set this to change the name of the label type that is predicted\n :param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if\n you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.\n 'gpu' to store embeddings in GPU memory.\n "
if (label_name is None):
label_name = self.get_current_label_type()
if (multi_label is None):
multi_label = self.is_current_task_multi_label()
if (not sentences):
return sentences
if isinstance(sentences, Sentence):
sentences = [sentences]
previous_sentence = None
for sentence in sentences:
if sentence.is_context_set():
continue
sentence._previous_sentence = previous_sentence
sentence._next_sentence = None
if previous_sentence:
previous_sentence._next_sentence = sentence
previous_sentence = sentence
reordered_sentences = sorted(sentences, key=(lambda s: len(s)), reverse=True)
dataloader = DataLoader(dataset=FlairDatapointDataset(reordered_sentences), batch_size=mini_batch_size)
if verbose:
progressbar = tqdm(dataloader)
progressbar.set_description('Batch inference')
dataloader = progressbar
overall_loss = 0
overall_count = 0
batch_no = 0
with torch.no_grad():
for batch in dataloader:
batch_no += 1
batch = self._filter_empty_sentences(batch)
if (not batch):
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
best_label = None
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(tars_sentence, label_name=label_name, return_loss=True, return_probabilities_for_all_classes=(True if (label_threshold < 0.5) else False))
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted_tars_label in tars_sentence.get_labels(label_name):
if ((predicted_tars_label.value == self.LABEL_MATCH) and (predicted_tars_label.score > label_threshold)):
sentence.add_label(label_name, label, predicted_tars_label.score)
if (not multi_label):
if (len(sentence.get_labels(label_name)) > 0):
label_scores = torch.tensor([label.score for label in sentence.get_labels(label_name)], dtype=torch.float)
best_label = sentence.get_labels(label_name)[torch.argmax(label_scores)]
sentence.remove_labels(label_name)
sentence.add_label(typename=label_name, value=best_label.value, score=best_label.score)
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return (overall_loss, overall_count) | -6,983,995,804,185,518,000 | Predict sequence tags for Named Entity Recognition task
:param sentences: a Sentence or a List of Sentence
:param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,
up to a point when it has no more effect.
:param all_tag_prob: True to compute the score for each tag on each token,
otherwise only the score of the best tag is returned
:param verbose: set to True to display a progress bar
:param return_loss: set to True to return loss
:param label_name: set this to change the name of the label type that is predicted
:param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if
you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.
'gpu' to store embeddings in GPU memory. | flair/models/tars_model.py | predict | garciaeduardo7143/flair | python | def predict(self, sentences: Union[(List[Sentence], Sentence)], mini_batch_size=32, return_probabilities_for_all_classes: bool=False, verbose: bool=False, label_name: Optional[str]=None, return_loss=False, embedding_storage_mode='none', label_threshold: float=0.5, multi_label: Optional[bool]=None):
"\n Predict sequence tags for Named Entity Recognition task\n :param sentences: a Sentence or a List of Sentence\n :param mini_batch_size: size of the minibatch, usually bigger is more rapid but consume more memory,\n up to a point when it has no more effect.\n :param all_tag_prob: True to compute the score for each tag on each token,\n otherwise only the score of the best tag is returned\n :param verbose: set to True to display a progress bar\n :param return_loss: set to True to return loss\n :param label_name: set this to change the name of the label type that is predicted\n :param embedding_storage_mode: default is 'none' which is always best. Only set to 'cpu' or 'gpu' if\n you wish to not only predict, but also keep the generated embeddings in CPU or GPU memory respectively.\n 'gpu' to store embeddings in GPU memory.\n "
if (label_name is None):
label_name = self.get_current_label_type()
if (multi_label is None):
multi_label = self.is_current_task_multi_label()
if (not sentences):
return sentences
if isinstance(sentences, Sentence):
sentences = [sentences]
previous_sentence = None
for sentence in sentences:
if sentence.is_context_set():
continue
sentence._previous_sentence = previous_sentence
sentence._next_sentence = None
if previous_sentence:
previous_sentence._next_sentence = sentence
previous_sentence = sentence
reordered_sentences = sorted(sentences, key=(lambda s: len(s)), reverse=True)
dataloader = DataLoader(dataset=FlairDatapointDataset(reordered_sentences), batch_size=mini_batch_size)
if verbose:
progressbar = tqdm(dataloader)
progressbar.set_description('Batch inference')
dataloader = progressbar
overall_loss = 0
overall_count = 0
batch_no = 0
with torch.no_grad():
for batch in dataloader:
batch_no += 1
batch = self._filter_empty_sentences(batch)
if (not batch):
continue
for sentence in batch:
sentence.remove_labels(label_name)
all_labels = [label.decode('utf-8') for label in self.get_current_label_dictionary().idx2item]
best_label = None
for label in all_labels:
tars_sentence = self._get_tars_formatted_sentence(label, sentence)
loss_and_count = self.tars_model.predict(tars_sentence, label_name=label_name, return_loss=True, return_probabilities_for_all_classes=(True if (label_threshold < 0.5) else False))
overall_loss += loss_and_count[0].item()
overall_count += loss_and_count[1]
for predicted_tars_label in tars_sentence.get_labels(label_name):
if ((predicted_tars_label.value == self.LABEL_MATCH) and (predicted_tars_label.score > label_threshold)):
sentence.add_label(label_name, label, predicted_tars_label.score)
if (not multi_label):
if (len(sentence.get_labels(label_name)) > 0):
label_scores = torch.tensor([label.score for label in sentence.get_labels(label_name)], dtype=torch.float)
best_label = sentence.get_labels(label_name)[torch.argmax(label_scores)]
sentence.remove_labels(label_name)
sentence.add_label(typename=label_name, value=best_label.value, score=best_label.score)
store_embeddings(batch, storage_mode=embedding_storage_mode)
if return_loss:
return (overall_loss, overall_count) |
@click.command()
def main(args=None):
'Console script for python_learn.'
click.echo('Replace this message by putting your code into python_learn.cli.main')
click.echo('See click documentation at http://click.pocoo.org/')
return 0 | -3,725,427,754,268,343,300 | Console script for python_learn. | python_learn/cli.py | main | Zhazhanan/python_learn | python | @click.command()
def main(args=None):
click.echo('Replace this message by putting your code into python_learn.cli.main')
click.echo('See click documentation at http://click.pocoo.org/')
return 0 |
@classmethod
def from_artifact(cls, artifact):
'Upsert logic to generate an ArtifactReference object from an artifact'
obj = cls.query.get(_id=artifact.index_id())
if (obj is not None):
return obj
try:
obj = cls(_id=artifact.index_id(), artifact_reference=dict(cls=bson.Binary(dumps(artifact.__class__, protocol=2)), project_id=artifact.app_config.project_id, app_config_id=artifact.app_config._id, artifact_id=artifact._id))
session(obj).flush(obj)
return obj
except pymongo.errors.DuplicateKeyError:
session(obj).expunge(obj)
return cls.query.get(_id=artifact.index_id()) | 4,642,030,310,060,067,000 | Upsert logic to generate an ArtifactReference object from an artifact | Allura/allura/model/index.py | from_artifact | brondsem/allura | python | @classmethod
def from_artifact(cls, artifact):
obj = cls.query.get(_id=artifact.index_id())
if (obj is not None):
return obj
try:
obj = cls(_id=artifact.index_id(), artifact_reference=dict(cls=bson.Binary(dumps(artifact.__class__, protocol=2)), project_id=artifact.app_config.project_id, app_config_id=artifact.app_config._id, artifact_id=artifact._id))
session(obj).flush(obj)
return obj
except pymongo.errors.DuplicateKeyError:
session(obj).expunge(obj)
return cls.query.get(_id=artifact.index_id()) |
@LazyProperty
def artifact(self):
'Look up the artifact referenced'
aref = self.artifact_reference
try:
cls = loads(six.binary_type(aref.cls))
with h.push_context(aref.project_id):
return cls.query.get(_id=aref.artifact_id)
except Exception:
log.exception('Error loading artifact for %s: %r', self._id, aref) | -8,850,843,363,701,119,000 | Look up the artifact referenced | Allura/allura/model/index.py | artifact | brondsem/allura | python | @LazyProperty
def artifact(self):
aref = self.artifact_reference
try:
cls = loads(six.binary_type(aref.cls))
with h.push_context(aref.project_id):
return cls.query.get(_id=aref.artifact_id)
except Exception:
log.exception('Error loading artifact for %s: %r', self._id, aref) |
@classmethod
def from_links(cls, *links):
'Convert a sequence of shortlinks to the matching Shortlink objects'
if len(links):
result = {}
parsed_links = dict(((link, cls._parse_link(link)) for link in links))
links_by_artifact = defaultdict(list)
project_ids = set()
for (link, d) in list(parsed_links.items()):
if d:
project_ids.add(d['project_id'])
links_by_artifact[unquote(d['artifact'])].append(d)
else:
result[link] = parsed_links.pop(link)
q = cls.query.find(dict(link={'$in': list(links_by_artifact.keys())}, project_id={'$in': list(project_ids)}), validate=False, sort=[('_id', pymongo.DESCENDING)])
matches_by_artifact = dict(((link, list(matches)) for (link, matches) in groupby(q, key=(lambda s: unquote(s.link)))))
for (link, d) in six.iteritems(parsed_links):
matches = matches_by_artifact.get(unquote(d['artifact']), [])
matches = (m for m in matches if ((m.project.shortname == d['project']) and (m.project.neighborhood_id == d['nbhd']) and (m.app_config is not None) and m.project.app_instance(m.app_config.options.mount_point)))
if d['app']:
matches = (m for m in matches if (m.app_config.options.mount_point == d['app']))
result[link] = cls._get_correct_match(link, list(matches))
return result
else:
return {} | -9,188,563,132,522,894,000 | Convert a sequence of shortlinks to the matching Shortlink objects | Allura/allura/model/index.py | from_links | brondsem/allura | python | @classmethod
def from_links(cls, *links):
if len(links):
result = {}
parsed_links = dict(((link, cls._parse_link(link)) for link in links))
links_by_artifact = defaultdict(list)
project_ids = set()
for (link, d) in list(parsed_links.items()):
if d:
project_ids.add(d['project_id'])
links_by_artifact[unquote(d['artifact'])].append(d)
else:
result[link] = parsed_links.pop(link)
q = cls.query.find(dict(link={'$in': list(links_by_artifact.keys())}, project_id={'$in': list(project_ids)}), validate=False, sort=[('_id', pymongo.DESCENDING)])
matches_by_artifact = dict(((link, list(matches)) for (link, matches) in groupby(q, key=(lambda s: unquote(s.link)))))
for (link, d) in six.iteritems(parsed_links):
matches = matches_by_artifact.get(unquote(d['artifact']), [])
matches = (m for m in matches if ((m.project.shortname == d['project']) and (m.project.neighborhood_id == d['nbhd']) and (m.app_config is not None) and m.project.app_instance(m.app_config.options.mount_point)))
if d['app']:
matches = (m for m in matches if (m.app_config.options.mount_point == d['app']))
result[link] = cls._get_correct_match(link, list(matches))
return result
else:
return {} |
@classmethod
def _parse_link(cls, s):
'Parse a shortlink into its nbhd/project/app/artifact parts'
s = s.strip()
if s.startswith('['):
s = s[1:]
if s.endswith(']'):
s = s[:(- 1)]
parts = s.split(':')
p_shortname = None
p_id = None
p_nbhd = None
if getattr(c, 'project', None):
p_shortname = getattr(c.project, 'shortname', None)
p_id = getattr(c.project, '_id', None)
p_nbhd = c.project.neighborhood_id
if (len(parts) == 3):
p = Project.query.get(shortname=parts[0], neighborhood_id=p_nbhd)
if p:
p_id = p._id
return dict(nbhd=p_nbhd, project=parts[0], project_id=p_id, app=parts[1], artifact=parts[2])
elif (len(parts) == 2):
return dict(nbhd=p_nbhd, project=p_shortname, project_id=p_id, app=parts[0], artifact=parts[1])
elif (len(parts) == 1):
return dict(nbhd=p_nbhd, project=p_shortname, project_id=p_id, app=None, artifact=parts[0])
else:
return None | -1,522,056,454,869,889,800 | Parse a shortlink into its nbhd/project/app/artifact parts | Allura/allura/model/index.py | _parse_link | brondsem/allura | python | @classmethod
def _parse_link(cls, s):
s = s.strip()
if s.startswith('['):
s = s[1:]
if s.endswith(']'):
s = s[:(- 1)]
parts = s.split(':')
p_shortname = None
p_id = None
p_nbhd = None
if getattr(c, 'project', None):
p_shortname = getattr(c.project, 'shortname', None)
p_id = getattr(c.project, '_id', None)
p_nbhd = c.project.neighborhood_id
if (len(parts) == 3):
p = Project.query.get(shortname=parts[0], neighborhood_id=p_nbhd)
if p:
p_id = p._id
return dict(nbhd=p_nbhd, project=parts[0], project_id=p_id, app=parts[1], artifact=parts[2])
elif (len(parts) == 2):
return dict(nbhd=p_nbhd, project=p_shortname, project_id=p_id, app=parts[0], artifact=parts[1])
elif (len(parts) == 1):
return dict(nbhd=p_nbhd, project=p_shortname, project_id=p_id, app=None, artifact=parts[0])
else:
return None |
def grow(plant=[], branch=0.01):
' Updates each root in the given list to a new position.\n Roots can branch and will disappear over time.\n Returns the updated list.\n '
new = []
for root in plant:
root.update()
if (root.time > 0.05):
new.append(root)
elif (len(plant) < 50):
(x, y, angle) = choice((((200 + random(50)), (- 50), (90 + random((- 10), 10))),))
new.append(Root(x, y, angle=angle, color=CLR, time=random(0.5, 3.5, bias=0.3)))
if (random() < branch):
new.append(root.copy())
return new | -5,876,942,146,591,880,000 | Updates each root in the given list to a new position.
Roots can branch and will disappear over time.
Returns the updated list. | examples/07-filter/09-buffer.py | grow | pepsipepsi/nodebox_opengl_python3 | python | def grow(plant=[], branch=0.01):
' Updates each root in the given list to a new position.\n Roots can branch and will disappear over time.\n Returns the updated list.\n '
new = []
for root in plant:
root.update()
if (root.time > 0.05):
new.append(root)
elif (len(plant) < 50):
(x, y, angle) = choice((((200 + random(50)), (- 50), (90 + random((- 10), 10))),))
new.append(Root(x, y, angle=angle, color=CLR, time=random(0.5, 3.5, bias=0.3)))
if (random() < branch):
new.append(root.copy())
return new |
def __init__(self, master: object, shape: object, value=0, maximum=100, bg='#231303', trough_color='#8a7852', bar_color='#f7f4bf'):
'Creating the alpha mask and creating a custom widget of the given shape and dimensions.'
im_shape_alpha = Image.open(shape).convert('L')
im_shape = Image.new('RGBA', im_shape_alpha.size, bg)
im_shape.putalpha(im_shape_alpha)
(width, height) = im_shape_alpha.size
tk.Canvas.__init__(self, master, bg=trough_color, width=width, height=height, highlightthickness=0)
self._value = value
self.maximum = maximum
self.height = height
self.width = width
self.img_trough = ImageTk.PhotoImage(im_shape, master=self)
self.create_rectangle(0, height, width, (height * (1 - (value / self.maximum))), width=0, fill=bar_color, tags='pbar')
self.create_image(0, 0, anchor='nw', image=self.img_trough) | -57,122,219,250,956,210 | Creating the alpha mask and creating a custom widget of the given shape and dimensions. | Scripts/mybar.py | __init__ | 1337-inc/Captain | python | def __init__(self, master: object, shape: object, value=0, maximum=100, bg='#231303', trough_color='#8a7852', bar_color='#f7f4bf'):
im_shape_alpha = Image.open(shape).convert('L')
im_shape = Image.new('RGBA', im_shape_alpha.size, bg)
im_shape.putalpha(im_shape_alpha)
(width, height) = im_shape_alpha.size
tk.Canvas.__init__(self, master, bg=trough_color, width=width, height=height, highlightthickness=0)
self._value = value
self.maximum = maximum
self.height = height
self.width = width
self.img_trough = ImageTk.PhotoImage(im_shape, master=self)
self.create_rectangle(0, height, width, (height * (1 - (value / self.maximum))), width=0, fill=bar_color, tags='pbar')
self.create_image(0, 0, anchor='nw', image=self.img_trough) |
@property
def value(self):
"Return bar's value."
return self._value | 6,355,790,876,013,271,000 | Return bar's value. | Scripts/mybar.py | value | 1337-inc/Captain | python | @property
def value(self):
return self._value |
@value.setter
def value(self, value: int):
"Set bar's value."
self._value = value
self.coords('pbar', 0, self.height, self.width, (self.height * (1 - (value / self.maximum)))) | -8,252,413,346,168,670,000 | Set bar's value. | Scripts/mybar.py | value | 1337-inc/Captain | python | @value.setter
def value(self, value: int):
self._value = value
self.coords('pbar', 0, self.height, self.width, (self.height * (1 - (value / self.maximum)))) |
def _common_args():
'ArgumentParser setup for all CLI commands.'
parser = argparse.ArgumentParser(description='Start a new profiler process.')
parser.add_argument('--config', required=True, help='The Python configuration file for the process.')
return parser | 3,170,931,945,910,749,000 | ArgumentParser setup for all CLI commands. | pyperf/cmd/daemons.py | _common_args | kevinconway/PyPerf | python | def _common_args():
parser = argparse.ArgumentParser(description='Start a new profiler process.')
parser.add_argument('--config', required=True, help='The Python configuration file for the process.')
return parser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.