body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
ac83887e59b9acdb71b2cfc3324d4e7cf4ced2525cf352ad32398ea824a734ed
def intersection(self, *others: Iterable[Any]) -> Set[Any]: 'Return the intersection of two sets as a new set. O(n)' return self.__set_op(*others, redis_method='sinter', set_method='intersection')
Return the intersection of two sets as a new set. O(n)
pottery/set.py
intersection
sthagen/pottery
1
python
def intersection(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sinter', set_method='intersection')
def intersection(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sinter', set_method='intersection')<|docstring|>Return the intersection of two sets as a new set. O(n)<|endoftext|>
474d2c5c3b09aa00f3d67efe70e8880a31e07bef9415481a1bf4608a7b403aa4
def union(self, *others: Iterable[Any]) -> Set[Any]: 'Return the union of sets as a new set. O(n)' return self.__set_op(*others, redis_method='sunion', set_method='union')
Return the union of sets as a new set. O(n)
pottery/set.py
union
sthagen/pottery
1
python
def union(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sunion', set_method='union')
def union(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sunion', set_method='union')<|docstring|>Return the union of sets as a new set. O(n)<|endoftext|>
1c515a7edc94ac8ccaba857a73c539700674a39c41bae85beb51e89ea9fd4efd
def difference(self, *others: Iterable[Any]) -> Set[Any]: 'Return the difference of two or more sets as a new set. O(n)' return self.__set_op(*others, redis_method='sdiff', set_method='difference')
Return the difference of two or more sets as a new set. O(n)
pottery/set.py
difference
sthagen/pottery
1
python
def difference(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sdiff', set_method='difference')
def difference(self, *others: Iterable[Any]) -> Set[Any]: return self.__set_op(*others, redis_method='sdiff', set_method='difference')<|docstring|>Return the difference of two or more sets as a new set. O(n)<|endoftext|>
0f572f2c0d4d36d14388b787cc2b494685024e3b44b7750be2bb94362686bc24
def issubset(self, other: Iterable[Any]) -> bool: 'Report whether another set contains this set. O(n)' return self.__sub_or_super(other, set_method='__le__')
Report whether another set contains this set. O(n)
pottery/set.py
issubset
sthagen/pottery
1
python
def issubset(self, other: Iterable[Any]) -> bool: return self.__sub_or_super(other, set_method='__le__')
def issubset(self, other: Iterable[Any]) -> bool: return self.__sub_or_super(other, set_method='__le__')<|docstring|>Report whether another set contains this set. O(n)<|endoftext|>
ef28e0d6a83dc0470a0bccf70c545265156ea673fd62c5a3f19d0261ec68956a
def issuperset(self, other: Iterable[Any]) -> bool: 'Report whether this set contains another set. O(n)' return self.__sub_or_super(other, set_method='__ge__')
Report whether this set contains another set. O(n)
pottery/set.py
issuperset
sthagen/pottery
1
python
def issuperset(self, other: Iterable[Any]) -> bool: return self.__sub_or_super(other, set_method='__ge__')
def issuperset(self, other: Iterable[Any]) -> bool: return self.__sub_or_super(other, set_method='__ge__')<|docstring|>Report whether this set contains another set. O(n)<|endoftext|>
ef102675ff65b552bf44d3fc5cec1d13391fc93af3cfa9d6d7999227868d3466
def update(self, *others: Iterable[JSONTypes]) -> None: 'Update a set with the union of itself and others. O(n)' self.__update(*others, redis_method='sunionstore', pipeline_method='sadd')
Update a set with the union of itself and others. O(n)
pottery/set.py
update
sthagen/pottery
1
python
def update(self, *others: Iterable[JSONTypes]) -> None: self.__update(*others, redis_method='sunionstore', pipeline_method='sadd')
def update(self, *others: Iterable[JSONTypes]) -> None: self.__update(*others, redis_method='sunionstore', pipeline_method='sadd')<|docstring|>Update a set with the union of itself and others. O(n)<|endoftext|>
61d3dee19a89ede9a58f4532630c17934e9297f2008a2537b006331103629187
def difference_update(self, *others: Iterable[JSONTypes]) -> None: 'Remove all elements of another set from this set. O(n)' self.__update(*others, redis_method='sdiffstore', pipeline_method='srem')
Remove all elements of another set from this set. O(n)
pottery/set.py
difference_update
sthagen/pottery
1
python
def difference_update(self, *others: Iterable[JSONTypes]) -> None: self.__update(*others, redis_method='sdiffstore', pipeline_method='srem')
def difference_update(self, *others: Iterable[JSONTypes]) -> None: self.__update(*others, redis_method='sdiffstore', pipeline_method='srem')<|docstring|>Remove all elements of another set from this set. O(n)<|endoftext|>
745092a4bb6e747ef34c4a76ed267a12551c50714b851bce54fbaaa7854654df
def to_set(self): 'Convert a RedisSet into a plain Python set.' return set(self)
Convert a RedisSet into a plain Python set.
pottery/set.py
to_set
sthagen/pottery
1
python
def to_set(self): return set(self)
def to_set(self): return set(self)<|docstring|>Convert a RedisSet into a plain Python set.<|endoftext|>
9839a59667c24776c2b55e4a53dba5be837c2d88f791c98e82241f28abc8f407
def __init__(self, agentml, element, file_path, **kwargs): '\n Initialize a new Trigger instance\n :param agentml: The parent AgentML instance\n :type agentml: AgentML\n\n :param element: The XML Element object\n :type element: etree._Element\n\n :param file_path: The absolute path to the AgentML file\n :type file_path: str\n\n :param kwargs: Default attributes\n ' self.priority = int_attribute(element, 'priority') self.normalize = bool_attribute(element, 'normalize') self.blocking = bool_element(element, 'blocking') self.pattern = (kwargs['pattern'] if ('pattern' in kwargs) else None) self.groups = (kwargs['groups'] if ('groups' in kwargs) else None) self.topic = (kwargs['topic'] if ('topic' in kwargs) else None) self._responses = (kwargs['responses'] if ('responses' in kwargs) else ResponseContainer()) self.vars = [] self.pattern_is_atomic = False self.pattern_words = 0 self.pattern_len = 0 self.stars = {'normalized': (), 'case_preserved': (), 'raw': ()} self.user = None Restrictable.__init__(self) Element.__init__(self, agentml, element, file_path) self._log = logging.getLogger('agentml.parser.trigger')
Initialize a new Trigger instance :param agentml: The parent AgentML instance :type agentml: AgentML :param element: The XML Element object :type element: etree._Element :param file_path: The absolute path to the AgentML file :type file_path: str :param kwargs: Default attributes
agentml/parser/trigger/__init__.py
__init__
FujiMakoto/SAML
5
python
def __init__(self, agentml, element, file_path, **kwargs): '\n Initialize a new Trigger instance\n :param agentml: The parent AgentML instance\n :type agentml: AgentML\n\n :param element: The XML Element object\n :type element: etree._Element\n\n :param file_path: The absolute path to the AgentML file\n :type file_path: str\n\n :param kwargs: Default attributes\n ' self.priority = int_attribute(element, 'priority') self.normalize = bool_attribute(element, 'normalize') self.blocking = bool_element(element, 'blocking') self.pattern = (kwargs['pattern'] if ('pattern' in kwargs) else None) self.groups = (kwargs['groups'] if ('groups' in kwargs) else None) self.topic = (kwargs['topic'] if ('topic' in kwargs) else None) self._responses = (kwargs['responses'] if ('responses' in kwargs) else ResponseContainer()) self.vars = [] self.pattern_is_atomic = False self.pattern_words = 0 self.pattern_len = 0 self.stars = {'normalized': (), 'case_preserved': (), 'raw': ()} self.user = None Restrictable.__init__(self) Element.__init__(self, agentml, element, file_path) self._log = logging.getLogger('agentml.parser.trigger')
def __init__(self, agentml, element, file_path, **kwargs): '\n Initialize a new Trigger instance\n :param agentml: The parent AgentML instance\n :type agentml: AgentML\n\n :param element: The XML Element object\n :type element: etree._Element\n\n :param file_path: The absolute path to the AgentML file\n :type file_path: str\n\n :param kwargs: Default attributes\n ' self.priority = int_attribute(element, 'priority') self.normalize = bool_attribute(element, 'normalize') self.blocking = bool_element(element, 'blocking') self.pattern = (kwargs['pattern'] if ('pattern' in kwargs) else None) self.groups = (kwargs['groups'] if ('groups' in kwargs) else None) self.topic = (kwargs['topic'] if ('topic' in kwargs) else None) self._responses = (kwargs['responses'] if ('responses' in kwargs) else ResponseContainer()) self.vars = [] self.pattern_is_atomic = False self.pattern_words = 0 self.pattern_len = 0 self.stars = {'normalized': (), 'case_preserved': (), 'raw': ()} self.user = None Restrictable.__init__(self) Element.__init__(self, agentml, element, file_path) self._log = logging.getLogger('agentml.parser.trigger')<|docstring|>Initialize a new Trigger instance :param agentml: The parent AgentML instance :type agentml: AgentML :param element: The XML Element object :type element: etree._Element :param file_path: The absolute path to the AgentML file :type file_path: str :param kwargs: Default attributes<|endoftext|>
436dd47020bdcd3dcaf9b17f929ea1053607fb016066fc6ed3c282d7857cdd70
def match(self, user, message): '\n Returns a response message if a match is found, otherwise None\n :param user: The requesting client\n :type user: agentml.User\n\n :param message: The message to match\n :type message: agentml.Message\n\n :rtype: str or None\n ' self._log.info('Attempting to match message against Pattern: {pattern}'.format(pattern=(self.pattern.pattern if hasattr(self.pattern, 'pattern') else self.pattern))) self.user = user if (user.topic != self.topic): self._log.debug('User topic "{u_topic}" does not match Trigger topic "{t_topic}", skipping check'.format(u_topic=user.topic, t_topic=self.topic)) return def get_response(): if user.is_limited(self): if self.ulimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced against the user {uid}, no trigger will be matched'.format(uid=user.id)) raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return '' if self.agentml.is_limited(self): if self.glimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced globally, no trigger will be matched') raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return '' if ((self.chance is not None) and (self.chance != 100)): if (self.chance >= random.uniform(0, 100)): self._log.info('Trigger had a {chance}% chance of being selected and succeeded selection'.format(chance=self.chance)) else: if self.chance_blocking: self._log.info('Trigger had a blocking {chance}% chance of being selected but failed selection, no trigger will be matched'.format(chance=self.chance)) raise ChanceError self._log.info('Response had a {chance}% chance of being selected but failed selection'.format(chance=self.chance)) return '' random_response = self._responses.random(user) if ((not random_response) and self.blocking): self._log.info('Trigger was matched, but there are no available responses and the trigger is blocking any further attempts. Giving up') raise ParserBlockingError if random_response: self.apply_reactions(user) else: self._log.info('Trigger was matched, but there are no available responses') random_response = '' return random_response if (isinstance(self.pattern, string_types) and (str(message) == self.pattern)): self._log.info('String Pattern matched: {match}'.format(match=self.pattern)) return get_response() if hasattr(self.pattern, 'match'): match = self.pattern.match(str(message)) if match: self._log.info('Regex pattern matched: {match}'.format(match=self.pattern.pattern)) self.stars['normalized'] = match.groups() for message_format in [message.CASE_PRESERVED, message.RAW]: message.format = message_format format_match = self.pattern.match(str(message)) if format_match: self.stars[message_format] = format_match.groups() self._log.debug('Assigning pattern wildcards: {stars}'.format(stars=str(self.stars))) return get_response()
Returns a response message if a match is found, otherwise None :param user: The requesting client :type user: agentml.User :param message: The message to match :type message: agentml.Message :rtype: str or None
agentml/parser/trigger/__init__.py
match
FujiMakoto/SAML
5
python
def match(self, user, message): '\n Returns a response message if a match is found, otherwise None\n :param user: The requesting client\n :type user: agentml.User\n\n :param message: The message to match\n :type message: agentml.Message\n\n :rtype: str or None\n ' self._log.info('Attempting to match message against Pattern: {pattern}'.format(pattern=(self.pattern.pattern if hasattr(self.pattern, 'pattern') else self.pattern))) self.user = user if (user.topic != self.topic): self._log.debug('User topic "{u_topic}" does not match Trigger topic "{t_topic}", skipping check'.format(u_topic=user.topic, t_topic=self.topic)) return def get_response(): if user.is_limited(self): if self.ulimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced against the user {uid}, no trigger will be matched'.format(uid=user.id)) raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return if self.agentml.is_limited(self): if self.glimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced globally, no trigger will be matched') raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return if ((self.chance is not None) and (self.chance != 100)): if (self.chance >= random.uniform(0, 100)): self._log.info('Trigger had a {chance}% chance of being selected and succeeded selection'.format(chance=self.chance)) else: if self.chance_blocking: self._log.info('Trigger had a blocking {chance}% chance of being selected but failed selection, no trigger will be matched'.format(chance=self.chance)) raise ChanceError self._log.info('Response had a {chance}% chance of being selected but failed selection'.format(chance=self.chance)) return random_response = self._responses.random(user) if ((not random_response) and self.blocking): self._log.info('Trigger was matched, but there are no available responses and the trigger is blocking any further attempts. Giving up') raise ParserBlockingError if random_response: self.apply_reactions(user) else: self._log.info('Trigger was matched, but there are no available responses') random_response = return random_response if (isinstance(self.pattern, string_types) and (str(message) == self.pattern)): self._log.info('String Pattern matched: {match}'.format(match=self.pattern)) return get_response() if hasattr(self.pattern, 'match'): match = self.pattern.match(str(message)) if match: self._log.info('Regex pattern matched: {match}'.format(match=self.pattern.pattern)) self.stars['normalized'] = match.groups() for message_format in [message.CASE_PRESERVED, message.RAW]: message.format = message_format format_match = self.pattern.match(str(message)) if format_match: self.stars[message_format] = format_match.groups() self._log.debug('Assigning pattern wildcards: {stars}'.format(stars=str(self.stars))) return get_response()
def match(self, user, message): '\n Returns a response message if a match is found, otherwise None\n :param user: The requesting client\n :type user: agentml.User\n\n :param message: The message to match\n :type message: agentml.Message\n\n :rtype: str or None\n ' self._log.info('Attempting to match message against Pattern: {pattern}'.format(pattern=(self.pattern.pattern if hasattr(self.pattern, 'pattern') else self.pattern))) self.user = user if (user.topic != self.topic): self._log.debug('User topic "{u_topic}" does not match Trigger topic "{t_topic}", skipping check'.format(u_topic=user.topic, t_topic=self.topic)) return def get_response(): if user.is_limited(self): if self.ulimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced against the user {uid}, no trigger will be matched'.format(uid=user.id)) raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return if self.agentml.is_limited(self): if self.glimit_blocking: self._log.debug('An active blocking limit for this trigger is being enforced globally, no trigger will be matched') raise LimitError self._log.debug('An active limit for this response is being enforced against the user {uid}, skipping'.format(uid=user.id)) return if ((self.chance is not None) and (self.chance != 100)): if (self.chance >= random.uniform(0, 100)): self._log.info('Trigger had a {chance}% chance of being selected and succeeded selection'.format(chance=self.chance)) else: if self.chance_blocking: self._log.info('Trigger had a blocking {chance}% chance of being selected but failed selection, no trigger will be matched'.format(chance=self.chance)) raise ChanceError self._log.info('Response had a {chance}% chance of being selected but failed selection'.format(chance=self.chance)) return random_response = self._responses.random(user) if ((not random_response) and self.blocking): self._log.info('Trigger was matched, but there are no available responses and the trigger is blocking any further attempts. Giving up') raise ParserBlockingError if random_response: self.apply_reactions(user) else: self._log.info('Trigger was matched, but there are no available responses') random_response = return random_response if (isinstance(self.pattern, string_types) and (str(message) == self.pattern)): self._log.info('String Pattern matched: {match}'.format(match=self.pattern)) return get_response() if hasattr(self.pattern, 'match'): match = self.pattern.match(str(message)) if match: self._log.info('Regex pattern matched: {match}'.format(match=self.pattern.pattern)) self.stars['normalized'] = match.groups() for message_format in [message.CASE_PRESERVED, message.RAW]: message.format = message_format format_match = self.pattern.match(str(message)) if format_match: self.stars[message_format] = format_match.groups() self._log.debug('Assigning pattern wildcards: {stars}'.format(stars=str(self.stars))) return get_response()<|docstring|>Returns a response message if a match is found, otherwise None :param user: The requesting client :type user: agentml.User :param message: The message to match :type message: agentml.Message :rtype: str or None<|endoftext|>
cfd7b6a7e393ffc62ff8d89ee62ba6b1c7671306e5a6c19b0b61f780655d2409
def apply_reactions(self, user): '\n Set active topics and limits after a response has been triggered\n :param user: The user triggering the response\n :type user: agentml.User\n ' if self.global_limit: self._log.info('Enforcing Global Trigger Limit of {num} seconds'.format(num=self.global_limit)) self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking) if self.user_limit: self._log.info('Enforcing User Trigger Limit of {num} seconds'.format(num=self.user_limit)) user.set_limit(self, (time() + self.user_limit), self.ulimit_blocking) for var in self.vars: (var_type, var_name, var_value) = var var_name = (''.join(map(str, var_name)) if isinstance(var_name, Iterable) else var_name) var_value = (''.join(map(str, var_value)) if isinstance(var_value, Iterable) else var_value) if (var_type == 'user'): self.user.set_var(var_name, var_value) if (var_type == 'global'): self.agentml.set_var(var_name, var_value)
Set active topics and limits after a response has been triggered :param user: The user triggering the response :type user: agentml.User
agentml/parser/trigger/__init__.py
apply_reactions
FujiMakoto/SAML
5
python
def apply_reactions(self, user): '\n Set active topics and limits after a response has been triggered\n :param user: The user triggering the response\n :type user: agentml.User\n ' if self.global_limit: self._log.info('Enforcing Global Trigger Limit of {num} seconds'.format(num=self.global_limit)) self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking) if self.user_limit: self._log.info('Enforcing User Trigger Limit of {num} seconds'.format(num=self.user_limit)) user.set_limit(self, (time() + self.user_limit), self.ulimit_blocking) for var in self.vars: (var_type, var_name, var_value) = var var_name = (.join(map(str, var_name)) if isinstance(var_name, Iterable) else var_name) var_value = (.join(map(str, var_value)) if isinstance(var_value, Iterable) else var_value) if (var_type == 'user'): self.user.set_var(var_name, var_value) if (var_type == 'global'): self.agentml.set_var(var_name, var_value)
def apply_reactions(self, user): '\n Set active topics and limits after a response has been triggered\n :param user: The user triggering the response\n :type user: agentml.User\n ' if self.global_limit: self._log.info('Enforcing Global Trigger Limit of {num} seconds'.format(num=self.global_limit)) self.agentml.set_limit(self, (time() + self.global_limit), self.glimit_blocking) if self.user_limit: self._log.info('Enforcing User Trigger Limit of {num} seconds'.format(num=self.user_limit)) user.set_limit(self, (time() + self.user_limit), self.ulimit_blocking) for var in self.vars: (var_type, var_name, var_value) = var var_name = (.join(map(str, var_name)) if isinstance(var_name, Iterable) else var_name) var_value = (.join(map(str, var_value)) if isinstance(var_value, Iterable) else var_value) if (var_type == 'user'): self.user.set_var(var_name, var_value) if (var_type == 'global'): self.agentml.set_var(var_name, var_value)<|docstring|>Set active topics and limits after a response has been triggered :param user: The user triggering the response :type user: agentml.User<|endoftext|>
c709b3aec021da04cfa60aaf7e8b4b88c2ddd8771cc2fad0a8d0b364a9de1ada
def _add_response(self, response, weight=1): '\n Add a new trigger\n :param response: The Response object\n :type response: Response or Condition\n\n :param weight: The weight of the response\n :type weight: int\n ' if (response.priority not in self._responses): self._responses[response.priority] = [(response, weight)] return self._responses[response.priority].append((response, weight))
Add a new trigger :param response: The Response object :type response: Response or Condition :param weight: The weight of the response :type weight: int
agentml/parser/trigger/__init__.py
_add_response
FujiMakoto/SAML
5
python
def _add_response(self, response, weight=1): '\n Add a new trigger\n :param response: The Response object\n :type response: Response or Condition\n\n :param weight: The weight of the response\n :type weight: int\n ' if (response.priority not in self._responses): self._responses[response.priority] = [(response, weight)] return self._responses[response.priority].append((response, weight))
def _add_response(self, response, weight=1): '\n Add a new trigger\n :param response: The Response object\n :type response: Response or Condition\n\n :param weight: The weight of the response\n :type weight: int\n ' if (response.priority not in self._responses): self._responses[response.priority] = [(response, weight)] return self._responses[response.priority].append((response, weight))<|docstring|>Add a new trigger :param response: The Response object :type response: Response or Condition :param weight: The weight of the response :type weight: int<|endoftext|>
e65169c5af79a09d04182ab3f8a585f5cff80e70ee556564c7c4060324472a1f
@staticmethod def replace_wildcards(string, wildcard, regex): '\n Replace wildcard symbols with regular expressions\n :param wildcard:\n :type wildcard: _sre.SRE_Pattern\n\n :param regex:\n :type regex: str\n\n :rtype: tuple of (str, bool)\n ' replaced = False match = wildcard.search(string) if match: string = wildcard.sub(regex, string) logging.getLogger('agentml.trigger').debug('Parsing Pattern wildcards: {pattern}'.format(pattern=string)) replaced = True return (string, replaced)
Replace wildcard symbols with regular expressions :param wildcard: :type wildcard: _sre.SRE_Pattern :param regex: :type regex: str :rtype: tuple of (str, bool)
agentml/parser/trigger/__init__.py
replace_wildcards
FujiMakoto/SAML
5
python
@staticmethod def replace_wildcards(string, wildcard, regex): '\n Replace wildcard symbols with regular expressions\n :param wildcard:\n :type wildcard: _sre.SRE_Pattern\n\n :param regex:\n :type regex: str\n\n :rtype: tuple of (str, bool)\n ' replaced = False match = wildcard.search(string) if match: string = wildcard.sub(regex, string) logging.getLogger('agentml.trigger').debug('Parsing Pattern wildcards: {pattern}'.format(pattern=string)) replaced = True return (string, replaced)
@staticmethod def replace_wildcards(string, wildcard, regex): '\n Replace wildcard symbols with regular expressions\n :param wildcard:\n :type wildcard: _sre.SRE_Pattern\n\n :param regex:\n :type regex: str\n\n :rtype: tuple of (str, bool)\n ' replaced = False match = wildcard.search(string) if match: string = wildcard.sub(regex, string) logging.getLogger('agentml.trigger').debug('Parsing Pattern wildcards: {pattern}'.format(pattern=string)) replaced = True return (string, replaced)<|docstring|>Replace wildcard symbols with regular expressions :param wildcard: :type wildcard: _sre.SRE_Pattern :param regex: :type regex: str :rtype: tuple of (str, bool)<|endoftext|>
ac65c5ebd3441d3fc9d17f5dadd3b5d23a232ffcc614a23c24e2d881203e40f7
@staticmethod def count_words(pattern): '\n Count the number of words in a pattern as well as the total length of those words\n :param pattern: The pattern to parse\n :type pattern: str\n\n :return: The word count first, then the total length of all words\n :rtype : tuple of (int, int)\n ' word_pattern = re.compile('(\\b(?<![\\(\\)\\[\\]\\|])\\w\\w*\\b(?![\\(\\)\\[\\]\\|]))', re.IGNORECASE) words = word_pattern.findall(pattern) word_count = len(words) word_len = sum((len(word) for word in words)) return (word_count, word_len)
Count the number of words in a pattern as well as the total length of those words :param pattern: The pattern to parse :type pattern: str :return: The word count first, then the total length of all words :rtype : tuple of (int, int)
agentml/parser/trigger/__init__.py
count_words
FujiMakoto/SAML
5
python
@staticmethod def count_words(pattern): '\n Count the number of words in a pattern as well as the total length of those words\n :param pattern: The pattern to parse\n :type pattern: str\n\n :return: The word count first, then the total length of all words\n :rtype : tuple of (int, int)\n ' word_pattern = re.compile('(\\b(?<![\\(\\)\\[\\]\\|])\\w\\w*\\b(?![\\(\\)\\[\\]\\|]))', re.IGNORECASE) words = word_pattern.findall(pattern) word_count = len(words) word_len = sum((len(word) for word in words)) return (word_count, word_len)
@staticmethod def count_words(pattern): '\n Count the number of words in a pattern as well as the total length of those words\n :param pattern: The pattern to parse\n :type pattern: str\n\n :return: The word count first, then the total length of all words\n :rtype : tuple of (int, int)\n ' word_pattern = re.compile('(\\b(?<![\\(\\)\\[\\]\\|])\\w\\w*\\b(?![\\(\\)\\[\\]\\|]))', re.IGNORECASE) words = word_pattern.findall(pattern) word_count = len(words) word_len = sum((len(word) for word in words)) return (word_count, word_len)<|docstring|>Count the number of words in a pattern as well as the total length of those words :param pattern: The pattern to parse :type pattern: str :return: The word count first, then the total length of all words :rtype : tuple of (int, int)<|endoftext|>
dddb2683004c1ed835bc31ff98d2a696af353e658247a29be5b1013c7dddc40f
def _parse_priority(self, element): '\n Parse and assign the priority for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger priority: {priority}'.format(priority=element.text)) self.priority = int(element.text)
Parse and assign the priority for this trigger :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_priority
FujiMakoto/SAML
5
python
def _parse_priority(self, element): '\n Parse and assign the priority for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger priority: {priority}'.format(priority=element.text)) self.priority = int(element.text)
def _parse_priority(self, element): '\n Parse and assign the priority for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger priority: {priority}'.format(priority=element.text)) self.priority = int(element.text)<|docstring|>Parse and assign the priority for this trigger :param element: The XML Element object :type element: etree._Element<|endoftext|>
32345b57898b9a066e0da21ea7832fd49396e32e4b09c3444e2411fc3e3f2219
def _parse_group(self, element): '\n Parse and add a group requirement for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Adding Trigger group: {group}'.format(group=element.text)) if isinstance(self.groups, set): self.groups.add(element.text) elif (self.groups is None): self.groups = {element.text} else: raise TypeError('Unrecognized group type, {type}: {groups}'.format(type=type(self.groups), groups=str(self.groups)))
Parse and add a group requirement for this trigger :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_group
FujiMakoto/SAML
5
python
def _parse_group(self, element): '\n Parse and add a group requirement for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Adding Trigger group: {group}'.format(group=element.text)) if isinstance(self.groups, set): self.groups.add(element.text) elif (self.groups is None): self.groups = {element.text} else: raise TypeError('Unrecognized group type, {type}: {groups}'.format(type=type(self.groups), groups=str(self.groups)))
def _parse_group(self, element): '\n Parse and add a group requirement for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Adding Trigger group: {group}'.format(group=element.text)) if isinstance(self.groups, set): self.groups.add(element.text) elif (self.groups is None): self.groups = {element.text} else: raise TypeError('Unrecognized group type, {type}: {groups}'.format(type=type(self.groups), groups=str(self.groups)))<|docstring|>Parse and add a group requirement for this trigger :param element: The XML Element object :type element: etree._Element<|endoftext|>
98768269315676e8f8ffd1f0b791459f34739064ff1b1777e1b9b145fd8f6667
def _parse_topic(self, element): '\n Parse and assign the topic for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger topic: {topic}'.format(topic=element.text)) super(Trigger, self)._parse_topic(element)
Parse and assign the topic for this trigger :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_topic
FujiMakoto/SAML
5
python
def _parse_topic(self, element): '\n Parse and assign the topic for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger topic: {topic}'.format(topic=element.text)) super(Trigger, self)._parse_topic(element)
def _parse_topic(self, element): '\n Parse and assign the topic for this trigger\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.debug('Setting Trigger topic: {topic}'.format(topic=element.text)) super(Trigger, self)._parse_topic(element)<|docstring|>Parse and assign the topic for this trigger :param element: The XML Element object :type element: etree._Element<|endoftext|>
eff2a0df34fb53a9e9c272c0e5777237a224235ac71ae0dd5f586473056a3acf
def _parse_emotion(self, element): '\n Parse an emotion element\n :param element: The XML Element object\n :type element: etree._Element\n ' self.emotion = normalize(element.text)
Parse an emotion element :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_emotion
FujiMakoto/SAML
5
python
def _parse_emotion(self, element): '\n Parse an emotion element\n :param element: The XML Element object\n :type element: etree._Element\n ' self.emotion = normalize(element.text)
def _parse_emotion(self, element): '\n Parse an emotion element\n :param element: The XML Element object\n :type element: etree._Element\n ' self.emotion = normalize(element.text)<|docstring|>Parse an emotion element :param element: The XML Element object :type element: etree._Element<|endoftext|>
cd5008b1f2d9441c0da61c338f80b9007d560b1f4297b70f54e6aa5b6e571892
def _parse_pattern(self, element): '\n Parse the trigger pattern\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info(('Parsing Trigger Pattern: ' + element.text)) (self.pattern_words, self.pattern_len) = self.count_words(element.text) self._log.debug('Pattern contains {wc} words with a total length of {cc}'.format(wc=self.pattern_words, cc=self.pattern_len)) regex = bool_attribute(self._element, 'regex', False) if regex: self._log.info('Attempting to compile trigger as a raw regex') try: self.pattern = re.compile(element.text) except sre_constants.error: self._log.warn('Attempted to compile an invalid regular expression in {path} ; {regex}'.format(path=self.file_path, regex=element.text)) raise AgentMLSyntaxError return self.pattern = normalize(element.text, True) self._log.debug(('Normalizing pattern: ' + self.pattern)) compile_as_regex = False captured_wildcard = re.compile('(?<!\\\\)\\(\\*\\)') wildcard = re.compile('(?<!\\\\)\\*') capt_wild_numeric = re.compile('(?<!\\\\)\\(#\\)') wild_numeric = re.compile('(?<!\\\\)#') capt_wild_alpha = re.compile('(?<!\\\\)\\(_\\)') wild_alpha = re.compile('(?<!\\\\)_') wildcard_replacements = [(captured_wildcard, '(.+)'), (wildcard, '(?:.+)'), (capt_wild_numeric, '(\\d+)'), (wild_numeric, '(?:\\d+)'), (capt_wild_alpha, '([a-zA-Z]+)'), (wild_alpha, '(?:[a-zA-Z]+)')] for (wildcard, replacement) in wildcard_replacements: (self.pattern, match) = self.replace_wildcards(self.pattern, wildcard, replacement) compile_as_regex = (bool(match) or compile_as_regex) req_choice = re.compile('\\(([\\w\\s\\|]+)\\)') opt_choice = re.compile('\\s?\\[([\\w\\s\\|]+)\\]\\s?') if req_choice.search(self.pattern): def sub_required(pattern): patterns = pattern.group(1).split('|') return '(\\b{options})\\b'.format(options='|'.join(patterns)) self.pattern = req_choice.sub(sub_required, self.pattern) self._log.debug(('Parsing Pattern required choices: ' + self.pattern)) compile_as_regex = True if opt_choice.search(self.pattern): def sub_optional(pattern): patterns = pattern.group(1).split('|') return '\\s?(?:\\b(?:{options})\\b)?\\s?'.format(options='|'.join(patterns)) self.pattern = opt_choice.sub(sub_optional, self.pattern) self._log.debug(('Parsing Pattern optional choices: ' + self.pattern)) compile_as_regex = True if compile_as_regex: self._log.debug('Compiling Pattern as regex') self.pattern = re.compile('^{pattern}$'.format(pattern=self.pattern), re.IGNORECASE) else: self._log.debug('Pattern is atomic') self.pattern_is_atomic = True self._log.debug('Replacing any escaped sequences in Pattern') self.pattern = self.pattern.replace('\\*', '*') self.pattern = self.pattern.replace('\\#', '#') self.pattern = self.pattern.replace('\\_', '_') self.pattern = self.pattern.replace('\\(*)', '(*)') self.pattern = self.pattern.replace('\\(#)', '(#)') self.pattern = self.pattern.replace('\\(_)', '(_)')
Parse the trigger pattern :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_pattern
FujiMakoto/SAML
5
python
def _parse_pattern(self, element): '\n Parse the trigger pattern\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info(('Parsing Trigger Pattern: ' + element.text)) (self.pattern_words, self.pattern_len) = self.count_words(element.text) self._log.debug('Pattern contains {wc} words with a total length of {cc}'.format(wc=self.pattern_words, cc=self.pattern_len)) regex = bool_attribute(self._element, 'regex', False) if regex: self._log.info('Attempting to compile trigger as a raw regex') try: self.pattern = re.compile(element.text) except sre_constants.error: self._log.warn('Attempted to compile an invalid regular expression in {path} ; {regex}'.format(path=self.file_path, regex=element.text)) raise AgentMLSyntaxError return self.pattern = normalize(element.text, True) self._log.debug(('Normalizing pattern: ' + self.pattern)) compile_as_regex = False captured_wildcard = re.compile('(?<!\\\\)\\(\\*\\)') wildcard = re.compile('(?<!\\\\)\\*') capt_wild_numeric = re.compile('(?<!\\\\)\\(#\\)') wild_numeric = re.compile('(?<!\\\\)#') capt_wild_alpha = re.compile('(?<!\\\\)\\(_\\)') wild_alpha = re.compile('(?<!\\\\)_') wildcard_replacements = [(captured_wildcard, '(.+)'), (wildcard, '(?:.+)'), (capt_wild_numeric, '(\\d+)'), (wild_numeric, '(?:\\d+)'), (capt_wild_alpha, '([a-zA-Z]+)'), (wild_alpha, '(?:[a-zA-Z]+)')] for (wildcard, replacement) in wildcard_replacements: (self.pattern, match) = self.replace_wildcards(self.pattern, wildcard, replacement) compile_as_regex = (bool(match) or compile_as_regex) req_choice = re.compile('\\(([\\w\\s\\|]+)\\)') opt_choice = re.compile('\\s?\\[([\\w\\s\\|]+)\\]\\s?') if req_choice.search(self.pattern): def sub_required(pattern): patterns = pattern.group(1).split('|') return '(\\b{options})\\b'.format(options='|'.join(patterns)) self.pattern = req_choice.sub(sub_required, self.pattern) self._log.debug(('Parsing Pattern required choices: ' + self.pattern)) compile_as_regex = True if opt_choice.search(self.pattern): def sub_optional(pattern): patterns = pattern.group(1).split('|') return '\\s?(?:\\b(?:{options})\\b)?\\s?'.format(options='|'.join(patterns)) self.pattern = opt_choice.sub(sub_optional, self.pattern) self._log.debug(('Parsing Pattern optional choices: ' + self.pattern)) compile_as_regex = True if compile_as_regex: self._log.debug('Compiling Pattern as regex') self.pattern = re.compile('^{pattern}$'.format(pattern=self.pattern), re.IGNORECASE) else: self._log.debug('Pattern is atomic') self.pattern_is_atomic = True self._log.debug('Replacing any escaped sequences in Pattern') self.pattern = self.pattern.replace('\\*', '*') self.pattern = self.pattern.replace('\\#', '#') self.pattern = self.pattern.replace('\\_', '_') self.pattern = self.pattern.replace('\\(*)', '(*)') self.pattern = self.pattern.replace('\\(#)', '(#)') self.pattern = self.pattern.replace('\\(_)', '(_)')
def _parse_pattern(self, element): '\n Parse the trigger pattern\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info(('Parsing Trigger Pattern: ' + element.text)) (self.pattern_words, self.pattern_len) = self.count_words(element.text) self._log.debug('Pattern contains {wc} words with a total length of {cc}'.format(wc=self.pattern_words, cc=self.pattern_len)) regex = bool_attribute(self._element, 'regex', False) if regex: self._log.info('Attempting to compile trigger as a raw regex') try: self.pattern = re.compile(element.text) except sre_constants.error: self._log.warn('Attempted to compile an invalid regular expression in {path} ; {regex}'.format(path=self.file_path, regex=element.text)) raise AgentMLSyntaxError return self.pattern = normalize(element.text, True) self._log.debug(('Normalizing pattern: ' + self.pattern)) compile_as_regex = False captured_wildcard = re.compile('(?<!\\\\)\\(\\*\\)') wildcard = re.compile('(?<!\\\\)\\*') capt_wild_numeric = re.compile('(?<!\\\\)\\(#\\)') wild_numeric = re.compile('(?<!\\\\)#') capt_wild_alpha = re.compile('(?<!\\\\)\\(_\\)') wild_alpha = re.compile('(?<!\\\\)_') wildcard_replacements = [(captured_wildcard, '(.+)'), (wildcard, '(?:.+)'), (capt_wild_numeric, '(\\d+)'), (wild_numeric, '(?:\\d+)'), (capt_wild_alpha, '([a-zA-Z]+)'), (wild_alpha, '(?:[a-zA-Z]+)')] for (wildcard, replacement) in wildcard_replacements: (self.pattern, match) = self.replace_wildcards(self.pattern, wildcard, replacement) compile_as_regex = (bool(match) or compile_as_regex) req_choice = re.compile('\\(([\\w\\s\\|]+)\\)') opt_choice = re.compile('\\s?\\[([\\w\\s\\|]+)\\]\\s?') if req_choice.search(self.pattern): def sub_required(pattern): patterns = pattern.group(1).split('|') return '(\\b{options})\\b'.format(options='|'.join(patterns)) self.pattern = req_choice.sub(sub_required, self.pattern) self._log.debug(('Parsing Pattern required choices: ' + self.pattern)) compile_as_regex = True if opt_choice.search(self.pattern): def sub_optional(pattern): patterns = pattern.group(1).split('|') return '\\s?(?:\\b(?:{options})\\b)?\\s?'.format(options='|'.join(patterns)) self.pattern = opt_choice.sub(sub_optional, self.pattern) self._log.debug(('Parsing Pattern optional choices: ' + self.pattern)) compile_as_regex = True if compile_as_regex: self._log.debug('Compiling Pattern as regex') self.pattern = re.compile('^{pattern}$'.format(pattern=self.pattern), re.IGNORECASE) else: self._log.debug('Pattern is atomic') self.pattern_is_atomic = True self._log.debug('Replacing any escaped sequences in Pattern') self.pattern = self.pattern.replace('\\*', '*') self.pattern = self.pattern.replace('\\#', '#') self.pattern = self.pattern.replace('\\_', '_') self.pattern = self.pattern.replace('\\(*)', '(*)') self.pattern = self.pattern.replace('\\(#)', '(#)') self.pattern = self.pattern.replace('\\(_)', '(_)')<|docstring|>Parse the trigger pattern :param element: The XML Element object :type element: etree._Element<|endoftext|>
e227be157618a7640f955ade7d091c50b6359c6e00903e4ea3bb3926c3c1f26e
def _parse_response(self, element): '\n Parse a trigger response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Response') self._responses.add(Response(self, element, self.file_path))
Parse a trigger response :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_response
FujiMakoto/SAML
5
python
def _parse_response(self, element): '\n Parse a trigger response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Response') self._responses.add(Response(self, element, self.file_path))
def _parse_response(self, element): '\n Parse a trigger response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Response') self._responses.add(Response(self, element, self.file_path))<|docstring|>Parse a trigger response :param element: The XML Element object :type element: etree._Element<|endoftext|>
c0a739a6e6effe1e8447601dab16f13bc2c3c80a45ebdda7d07ddd3ef365f673
def _parse_template(self, element): '\n Parse a trigger shorthand response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new shorthand Response') self._responses.add(Response(self, element, self.file_path))
Parse a trigger shorthand response :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_template
FujiMakoto/SAML
5
python
def _parse_template(self, element): '\n Parse a trigger shorthand response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new shorthand Response') self._responses.add(Response(self, element, self.file_path))
def _parse_template(self, element): '\n Parse a trigger shorthand response\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new shorthand Response') self._responses.add(Response(self, element, self.file_path))<|docstring|>Parse a trigger shorthand response :param element: The XML Element object :type element: etree._Element<|endoftext|>
0b8a098de412c2b71a0974eee2fb89c1d9e8d3688893baec521c5970ec4a5cd8
def _parse_redirect(self, element): '\n Parse a trigger redirect\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new redirected Response') self._responses.add(Response(self, element, self.file_path))
Parse a trigger redirect :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_redirect
FujiMakoto/SAML
5
python
def _parse_redirect(self, element): '\n Parse a trigger redirect\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new redirected Response') self._responses.add(Response(self, element, self.file_path))
def _parse_redirect(self, element): '\n Parse a trigger redirect\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new redirected Response') self._responses.add(Response(self, element, self.file_path))<|docstring|>Parse a trigger redirect :param element: The XML Element object :type element: etree._Element<|endoftext|>
b2b64fe29d157a51954b5a29957d8d6a7075f7f2483b8532c49cf4302f0fbfa9
def _parse_condition(self, element): '\n Parse a trigger condition\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Condition') condition = Condition(self, element, self.file_path) for statement in condition.statements: for response in statement.contents: self._responses.add(response, condition) if condition.else_statement: self._responses.add(condition.else_statement[0], condition)
Parse a trigger condition :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_condition
FujiMakoto/SAML
5
python
def _parse_condition(self, element): '\n Parse a trigger condition\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Condition') condition = Condition(self, element, self.file_path) for statement in condition.statements: for response in statement.contents: self._responses.add(response, condition) if condition.else_statement: self._responses.add(condition.else_statement[0], condition)
def _parse_condition(self, element): '\n Parse a trigger condition\n :param element: The XML Element object\n :type element: etree._Element\n ' self._log.info('Parsing new Condition') condition = Condition(self, element, self.file_path) for statement in condition.statements: for response in statement.contents: self._responses.add(response, condition) if condition.else_statement: self._responses.add(condition.else_statement[0], condition)<|docstring|>Parse a trigger condition :param element: The XML Element object :type element: etree._Element<|endoftext|>
eb9de0cd32a0cb99b1672dd35066d282801cb0ae388979007243f70be7232825
def _parse_chance(self, element): '\n Parse the chance of this trigger being successfully called\n :param element: The XML Element object\n :type element: etree._Element\n ' try: chance = element.text.strip('%') chance = float(chance) except (ValueError, TypeError, AttributeError): self._log.warn('Invalid Chance string: {chance}'.format(chance=element.text)) return if (not (0 <= chance <= 100)): self._log.warn('Chance percent must contain an integer or float between 0 and 100') return self.chance = chance
Parse the chance of this trigger being successfully called :param element: The XML Element object :type element: etree._Element
agentml/parser/trigger/__init__.py
_parse_chance
FujiMakoto/SAML
5
python
def _parse_chance(self, element): '\n Parse the chance of this trigger being successfully called\n :param element: The XML Element object\n :type element: etree._Element\n ' try: chance = element.text.strip('%') chance = float(chance) except (ValueError, TypeError, AttributeError): self._log.warn('Invalid Chance string: {chance}'.format(chance=element.text)) return if (not (0 <= chance <= 100)): self._log.warn('Chance percent must contain an integer or float between 0 and 100') return self.chance = chance
def _parse_chance(self, element): '\n Parse the chance of this trigger being successfully called\n :param element: The XML Element object\n :type element: etree._Element\n ' try: chance = element.text.strip('%') chance = float(chance) except (ValueError, TypeError, AttributeError): self._log.warn('Invalid Chance string: {chance}'.format(chance=element.text)) return if (not (0 <= chance <= 100)): self._log.warn('Chance percent must contain an integer or float between 0 and 100') return self.chance = chance<|docstring|>Parse the chance of this trigger being successfully called :param element: The XML Element object :type element: etree._Element<|endoftext|>
34181bf5a6f7ab8707e0e92eceaa7a2f8226cf99fb0b73e09042c7f43310179a
@staticmethod def _retry_on_error(error_cls: type[Exception], max_retries: int, backoff: int=0, msg_regex: (str | None)=None) -> Callable[([FT], FT)]: '\n A decorator to retry a function call if a specified exception occurs.\n\n :param error_cls: Error type to catch.\n :param max_retries: Maximum number of retries.\n :param msg_regex: If provided, retry errors only if the regex matches the error\n message. Matches are found with :meth:`re.search()`.\n :param backoff: Time in seconds to sleep before retry.\n ' def decorator(func: FT) -> FT: @functools.wraps(func) def wrapper(self, *args, **kwargs): tries = 0 while True: try: return func(self, *args, **kwargs) except error_cls as exc: if (msg_regex is not None): if ((len(exc.args[0]) == 0) or (not isinstance(exc.args[0], str))): raise exc if (not re.search(msg_regex, exc.args[0])): raise exc if (tries < max_retries): tries += 1 if (backoff > 0): time.sleep(backoff) self._logger.debug('Retrying call %s on %s: %s/%s', func, error_cls, tries, max_retries) else: raise exc return cast(FT, wrapper) return decorator
A decorator to retry a function call if a specified exception occurs. :param error_cls: Error type to catch. :param max_retries: Maximum number of retries. :param msg_regex: If provided, retry errors only if the regex matches the error message. Matches are found with :meth:`re.search()`. :param backoff: Time in seconds to sleep before retry.
src/maestral/client.py
_retry_on_error
samschott/maestral
436
python
@staticmethod def _retry_on_error(error_cls: type[Exception], max_retries: int, backoff: int=0, msg_regex: (str | None)=None) -> Callable[([FT], FT)]: '\n A decorator to retry a function call if a specified exception occurs.\n\n :param error_cls: Error type to catch.\n :param max_retries: Maximum number of retries.\n :param msg_regex: If provided, retry errors only if the regex matches the error\n message. Matches are found with :meth:`re.search()`.\n :param backoff: Time in seconds to sleep before retry.\n ' def decorator(func: FT) -> FT: @functools.wraps(func) def wrapper(self, *args, **kwargs): tries = 0 while True: try: return func(self, *args, **kwargs) except error_cls as exc: if (msg_regex is not None): if ((len(exc.args[0]) == 0) or (not isinstance(exc.args[0], str))): raise exc if (not re.search(msg_regex, exc.args[0])): raise exc if (tries < max_retries): tries += 1 if (backoff > 0): time.sleep(backoff) self._logger.debug('Retrying call %s on %s: %s/%s', func, error_cls, tries, max_retries) else: raise exc return cast(FT, wrapper) return decorator
@staticmethod def _retry_on_error(error_cls: type[Exception], max_retries: int, backoff: int=0, msg_regex: (str | None)=None) -> Callable[([FT], FT)]: '\n A decorator to retry a function call if a specified exception occurs.\n\n :param error_cls: Error type to catch.\n :param max_retries: Maximum number of retries.\n :param msg_regex: If provided, retry errors only if the regex matches the error\n message. Matches are found with :meth:`re.search()`.\n :param backoff: Time in seconds to sleep before retry.\n ' def decorator(func: FT) -> FT: @functools.wraps(func) def wrapper(self, *args, **kwargs): tries = 0 while True: try: return func(self, *args, **kwargs) except error_cls as exc: if (msg_regex is not None): if ((len(exc.args[0]) == 0) or (not isinstance(exc.args[0], str))): raise exc if (not re.search(msg_regex, exc.args[0])): raise exc if (tries < max_retries): tries += 1 if (backoff > 0): time.sleep(backoff) self._logger.debug('Retrying call %s on %s: %s/%s', func, error_cls, tries, max_retries) else: raise exc return cast(FT, wrapper) return decorator<|docstring|>A decorator to retry a function call if a specified exception occurs. :param error_cls: Error type to catch. :param max_retries: Maximum number of retries. :param msg_regex: If provided, retry errors only if the regex matches the error message. Matches are found with :meth:`re.search()`. :param backoff: Time in seconds to sleep before retry.<|endoftext|>
5f4b8abf42ae36bf7f3e9ff739754a79187d8a26c715f8d1535fb16aa7c00ebd
@property def dbx_base(self) -> Dropbox: 'The underlying Dropbox SDK instance without namespace headers.' if (not self._dbx_base): self._init_sdk() return self._dbx_base
The underlying Dropbox SDK instance without namespace headers.
src/maestral/client.py
dbx_base
samschott/maestral
436
python
@property def dbx_base(self) -> Dropbox: if (not self._dbx_base): self._init_sdk() return self._dbx_base
@property def dbx_base(self) -> Dropbox: if (not self._dbx_base): self._init_sdk() return self._dbx_base<|docstring|>The underlying Dropbox SDK instance without namespace headers.<|endoftext|>
f62939268eb19b21ecd13565f99d587556d1a8654f36ead30bbb8256864c44e3
@property def dbx(self) -> Dropbox: 'The underlying Dropbox SDK instance with namespace headers.' if (not self._dbx): self._init_sdk() return self._dbx
The underlying Dropbox SDK instance with namespace headers.
src/maestral/client.py
dbx
samschott/maestral
436
python
@property def dbx(self) -> Dropbox: if (not self._dbx): self._init_sdk() return self._dbx
@property def dbx(self) -> Dropbox: if (not self._dbx): self._init_sdk() return self._dbx<|docstring|>The underlying Dropbox SDK instance with namespace headers.<|endoftext|>
e828bedb3595e272fdf53b6a599d6deddc9733e67bdb8fc30df51af04133fd91
@property def linked(self) -> bool: "\n Indicates if the client is linked to a Dropbox account (read only). This will\n block until the user's keyring is unlocked to load the saved auth token.\n\n :raises KeyringAccessError: if keyring access fails.\n " return (self._cred_storage.token is not None)
Indicates if the client is linked to a Dropbox account (read only). This will block until the user's keyring is unlocked to load the saved auth token. :raises KeyringAccessError: if keyring access fails.
src/maestral/client.py
linked
samschott/maestral
436
python
@property def linked(self) -> bool: "\n Indicates if the client is linked to a Dropbox account (read only). This will\n block until the user's keyring is unlocked to load the saved auth token.\n\n :raises KeyringAccessError: if keyring access fails.\n " return (self._cred_storage.token is not None)
@property def linked(self) -> bool: "\n Indicates if the client is linked to a Dropbox account (read only). This will\n block until the user's keyring is unlocked to load the saved auth token.\n\n :raises KeyringAccessError: if keyring access fails.\n " return (self._cred_storage.token is not None)<|docstring|>Indicates if the client is linked to a Dropbox account (read only). This will block until the user's keyring is unlocked to load the saved auth token. :raises KeyringAccessError: if keyring access fails.<|endoftext|>
fa6792df8d672377ea20b1466030f2bb2106d70a65c24a71f2dcd9e6182d4465
def get_auth_url(self) -> str: '\n Returns a URL to authorize access to a Dropbox account. To link a Dropbox\n account, retrieve an auth token from the URL and link Maestral by calling\n :meth:`link` with the provided token.\n\n :returns: URL to retrieve an OAuth token.\n ' self._auth_flow = DropboxOAuth2FlowNoRedirect(consumer_key=DROPBOX_APP_KEY, token_access_type='offline', use_pkce=True) return self._auth_flow.start()
Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an auth token from the URL and link Maestral by calling :meth:`link` with the provided token. :returns: URL to retrieve an OAuth token.
src/maestral/client.py
get_auth_url
samschott/maestral
436
python
def get_auth_url(self) -> str: '\n Returns a URL to authorize access to a Dropbox account. To link a Dropbox\n account, retrieve an auth token from the URL and link Maestral by calling\n :meth:`link` with the provided token.\n\n :returns: URL to retrieve an OAuth token.\n ' self._auth_flow = DropboxOAuth2FlowNoRedirect(consumer_key=DROPBOX_APP_KEY, token_access_type='offline', use_pkce=True) return self._auth_flow.start()
def get_auth_url(self) -> str: '\n Returns a URL to authorize access to a Dropbox account. To link a Dropbox\n account, retrieve an auth token from the URL and link Maestral by calling\n :meth:`link` with the provided token.\n\n :returns: URL to retrieve an OAuth token.\n ' self._auth_flow = DropboxOAuth2FlowNoRedirect(consumer_key=DROPBOX_APP_KEY, token_access_type='offline', use_pkce=True) return self._auth_flow.start()<|docstring|>Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an auth token from the URL and link Maestral by calling :meth:`link` with the provided token. :returns: URL to retrieve an OAuth token.<|endoftext|>
e8bdd0e59ae50e3e3324db361f49a0f948fda04567ea09b2a4b95c096e1cc565
def link(self, token: str) -> int: '\n Links Maestral with a Dropbox account using the given access token. The token\n will be stored for future usage in the provided credential store.\n\n :param token: OAuth token for Dropbox access.\n :returns: 0 on success, 1 for an invalid token and 2 for connection errors.\n ' if (not self._auth_flow): raise RuntimeError("Please start auth flow with 'get_auth_url' first") try: res = self._auth_flow.finish(token) except requests.exceptions.HTTPError: return 1 except CONNECTION_ERRORS: return 2 self._init_sdk(res.refresh_token, TokenType.Offline) try: self.update_path_root() except CONNECTION_ERRORS: return 2 self._cred_storage.save_creds(res.account_id, res.refresh_token, TokenType.Offline) self._auth_flow = None return 0
Links Maestral with a Dropbox account using the given access token. The token will be stored for future usage in the provided credential store. :param token: OAuth token for Dropbox access. :returns: 0 on success, 1 for an invalid token and 2 for connection errors.
src/maestral/client.py
link
samschott/maestral
436
python
def link(self, token: str) -> int: '\n Links Maestral with a Dropbox account using the given access token. The token\n will be stored for future usage in the provided credential store.\n\n :param token: OAuth token for Dropbox access.\n :returns: 0 on success, 1 for an invalid token and 2 for connection errors.\n ' if (not self._auth_flow): raise RuntimeError("Please start auth flow with 'get_auth_url' first") try: res = self._auth_flow.finish(token) except requests.exceptions.HTTPError: return 1 except CONNECTION_ERRORS: return 2 self._init_sdk(res.refresh_token, TokenType.Offline) try: self.update_path_root() except CONNECTION_ERRORS: return 2 self._cred_storage.save_creds(res.account_id, res.refresh_token, TokenType.Offline) self._auth_flow = None return 0
def link(self, token: str) -> int: '\n Links Maestral with a Dropbox account using the given access token. The token\n will be stored for future usage in the provided credential store.\n\n :param token: OAuth token for Dropbox access.\n :returns: 0 on success, 1 for an invalid token and 2 for connection errors.\n ' if (not self._auth_flow): raise RuntimeError("Please start auth flow with 'get_auth_url' first") try: res = self._auth_flow.finish(token) except requests.exceptions.HTTPError: return 1 except CONNECTION_ERRORS: return 2 self._init_sdk(res.refresh_token, TokenType.Offline) try: self.update_path_root() except CONNECTION_ERRORS: return 2 self._cred_storage.save_creds(res.account_id, res.refresh_token, TokenType.Offline) self._auth_flow = None return 0<|docstring|>Links Maestral with a Dropbox account using the given access token. The token will be stored for future usage in the provided credential store. :param token: OAuth token for Dropbox access. :returns: 0 on success, 1 for an invalid token and 2 for connection errors.<|endoftext|>
794fad8473176f64e8becae3e45082451016a685dfe5295a1bde6946d6c37cfa
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def unlink(self) -> None: '\n Unlinks the Dropbox account. The password will be deleted from the provided\n credential storage.\n\n :raises KeyringAccessError: if keyring access fails.\n :raises DropboxAuthError: if we cannot authenticate with Dropbox.\n ' self._dbx = None self._dbx_base = None self._cached_account_info = None with convert_api_errors(): self.dbx_base.auth_token_revoke() self._cred_storage.delete_creds()
Unlinks the Dropbox account. The password will be deleted from the provided credential storage. :raises KeyringAccessError: if keyring access fails. :raises DropboxAuthError: if we cannot authenticate with Dropbox.
src/maestral/client.py
unlink
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def unlink(self) -> None: '\n Unlinks the Dropbox account. The password will be deleted from the provided\n credential storage.\n\n :raises KeyringAccessError: if keyring access fails.\n :raises DropboxAuthError: if we cannot authenticate with Dropbox.\n ' self._dbx = None self._dbx_base = None self._cached_account_info = None with convert_api_errors(): self.dbx_base.auth_token_revoke() self._cred_storage.delete_creds()
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def unlink(self) -> None: '\n Unlinks the Dropbox account. The password will be deleted from the provided\n credential storage.\n\n :raises KeyringAccessError: if keyring access fails.\n :raises DropboxAuthError: if we cannot authenticate with Dropbox.\n ' self._dbx = None self._dbx_base = None self._cached_account_info = None with convert_api_errors(): self.dbx_base.auth_token_revoke() self._cred_storage.delete_creds()<|docstring|>Unlinks the Dropbox account. The password will be deleted from the provided credential storage. :raises KeyringAccessError: if keyring access fails. :raises DropboxAuthError: if we cannot authenticate with Dropbox.<|endoftext|>
cd5f44bb5aebe21ddc5fa20fc48257f4de898abf713d68e1feae4ae1443c8eaf
def _init_sdk(self, token: (str | None)=None, token_type: (TokenType | None)=None) -> None: '\n Initialise the SDK. If no token is given, get the token from our credential\n storage.\n\n :param token: Token for the SDK.\n :param token_type: Token type\n :raises RuntimeError: if token is not available from storage and no token is\n passed as an argument.\n ' with self._lock: if self._dbx: return if (not (token or self._cred_storage.token)): raise NotLinkedError('No auth token set', 'Please link a Dropbox account first.') token = (token or self._cred_storage.token) token_type = (token_type or self._cred_storage.token_type) if (token_type is TokenType.Offline): self._dbx_base = Dropbox(oauth2_refresh_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) else: self._dbx_base = Dropbox(oauth2_access_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) if self._namespace_id: root_path = common.PathRoot.root(self._namespace_id) self._dbx = self._dbx_base.with_path_root(root_path) else: self._dbx = self._dbx_base self._dbx._logger = self._dropbox_sdk_logger self._dbx_base._logger = self._dropbox_sdk_logger
Initialise the SDK. If no token is given, get the token from our credential storage. :param token: Token for the SDK. :param token_type: Token type :raises RuntimeError: if token is not available from storage and no token is passed as an argument.
src/maestral/client.py
_init_sdk
samschott/maestral
436
python
def _init_sdk(self, token: (str | None)=None, token_type: (TokenType | None)=None) -> None: '\n Initialise the SDK. If no token is given, get the token from our credential\n storage.\n\n :param token: Token for the SDK.\n :param token_type: Token type\n :raises RuntimeError: if token is not available from storage and no token is\n passed as an argument.\n ' with self._lock: if self._dbx: return if (not (token or self._cred_storage.token)): raise NotLinkedError('No auth token set', 'Please link a Dropbox account first.') token = (token or self._cred_storage.token) token_type = (token_type or self._cred_storage.token_type) if (token_type is TokenType.Offline): self._dbx_base = Dropbox(oauth2_refresh_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) else: self._dbx_base = Dropbox(oauth2_access_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) if self._namespace_id: root_path = common.PathRoot.root(self._namespace_id) self._dbx = self._dbx_base.with_path_root(root_path) else: self._dbx = self._dbx_base self._dbx._logger = self._dropbox_sdk_logger self._dbx_base._logger = self._dropbox_sdk_logger
def _init_sdk(self, token: (str | None)=None, token_type: (TokenType | None)=None) -> None: '\n Initialise the SDK. If no token is given, get the token from our credential\n storage.\n\n :param token: Token for the SDK.\n :param token_type: Token type\n :raises RuntimeError: if token is not available from storage and no token is\n passed as an argument.\n ' with self._lock: if self._dbx: return if (not (token or self._cred_storage.token)): raise NotLinkedError('No auth token set', 'Please link a Dropbox account first.') token = (token or self._cred_storage.token) token_type = (token_type or self._cred_storage.token_type) if (token_type is TokenType.Offline): self._dbx_base = Dropbox(oauth2_refresh_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) else: self._dbx_base = Dropbox(oauth2_access_token=token, app_key=DROPBOX_APP_KEY, session=self._session, user_agent=USER_AGENT, timeout=self._timeout) if self._namespace_id: root_path = common.PathRoot.root(self._namespace_id) self._dbx = self._dbx_base.with_path_root(root_path) else: self._dbx = self._dbx_base self._dbx._logger = self._dropbox_sdk_logger self._dbx_base._logger = self._dropbox_sdk_logger<|docstring|>Initialise the SDK. If no token is given, get the token from our credential storage. :param token: Token for the SDK. :param token_type: Token type :raises RuntimeError: if token is not available from storage and no token is passed as an argument.<|endoftext|>
2296e8161a8d95dcee67496e095d17cf087dd9ce8b6790402ed564762ee70dbd
@property def account_info(self) -> FullAccount: 'Returns cached account info. Use :meth:`get_account_info` to get the latest\n account info from Dropbox servers.' if (not self._cached_account_info): return self.get_account_info() else: return self._cached_account_info
Returns cached account info. Use :meth:`get_account_info` to get the latest account info from Dropbox servers.
src/maestral/client.py
account_info
samschott/maestral
436
python
@property def account_info(self) -> FullAccount: 'Returns cached account info. Use :meth:`get_account_info` to get the latest\n account info from Dropbox servers.' if (not self._cached_account_info): return self.get_account_info() else: return self._cached_account_info
@property def account_info(self) -> FullAccount: 'Returns cached account info. Use :meth:`get_account_info` to get the latest\n account info from Dropbox servers.' if (not self._cached_account_info): return self.get_account_info() else: return self._cached_account_info<|docstring|>Returns cached account info. Use :meth:`get_account_info` to get the latest account info from Dropbox servers.<|endoftext|>
d22e696e9ed0135101599e7991dcb2f7a514bc2a97fcd016e9192b70009ddd1d
@property def namespace_id(self) -> str: 'The namespace ID of the path root currently used by the DropboxClient. All\n file paths will be interpreted as relative to the root namespace. Use\n :meth:`update_path_root` to update the root namespace after the user joins or\n leaves a team with a Team Space.' return self._namespace_id
The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space.
src/maestral/client.py
namespace_id
samschott/maestral
436
python
@property def namespace_id(self) -> str: 'The namespace ID of the path root currently used by the DropboxClient. All\n file paths will be interpreted as relative to the root namespace. Use\n :meth:`update_path_root` to update the root namespace after the user joins or\n leaves a team with a Team Space.' return self._namespace_id
@property def namespace_id(self) -> str: 'The namespace ID of the path root currently used by the DropboxClient. All\n file paths will be interpreted as relative to the root namespace. Use\n :meth:`update_path_root` to update the root namespace after the user joins or\n leaves a team with a Team Space.' return self._namespace_id<|docstring|>The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use :meth:`update_path_root` to update the root namespace after the user joins or leaves a team with a Team Space.<|endoftext|>
23c294582e7204eb03ea09aeda90c63f56ebe638269924ecc9f82e2445e7d8a8
@property def is_team_space(self) -> bool: "Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to\n update the root namespace after the user joins or eaves a team with a Team\n Space." return self._is_team_space
Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to update the root namespace after the user joins or eaves a team with a Team Space.
src/maestral/client.py
is_team_space
samschott/maestral
436
python
@property def is_team_space(self) -> bool: "Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to\n update the root namespace after the user joins or eaves a team with a Team\n Space." return self._is_team_space
@property def is_team_space(self) -> bool: "Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to\n update the root namespace after the user joins or eaves a team with a Team\n Space." return self._is_team_space<|docstring|>Whether the user's Dropbox uses a Team Space. Use :meth:`update_path_root` to update the root namespace after the user joins or eaves a team with a Team Space.<|endoftext|>
db332fe49843f136c954cfb37f13174608daf0d78e8a80a2ad67af9d84290e22
def close(self) -> None: 'Cleans up all resources like the request session/network connection.' if self._dbx: self._dbx.close()
Cleans up all resources like the request session/network connection.
src/maestral/client.py
close
samschott/maestral
436
python
def close(self) -> None: if self._dbx: self._dbx.close()
def close(self) -> None: if self._dbx: self._dbx.close()<|docstring|>Cleans up all resources like the request session/network connection.<|endoftext|>
fabf3f60bdfe84b64de3982727a09fc9561ad24d1f9ab5bf94039dc719ba36fd
def clone(self, config_name: (str | None)=None, cred_storage: (CredentialStorage | None)=None, timeout: (float | None)=None, session: (requests.Session | None)=None) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults unless modified\n by arguments to :meth:`clone`.\n\n :param config_name: Name of config file and state file to use.\n :param timeout: Timeout for individual requests.\n :param session: Requests session to use.\n :returns: A new instance of DropboxClient.\n ' config_name = (config_name or self.config_name) timeout = (timeout or self._timeout) session = (session or self._session) cred_storage = (cred_storage or self._cred_storage) client = self.__class__(config_name, cred_storage, timeout, session) if self._dbx: client._dbx = self._dbx.clone(session=session) client._dbx._logger = self._dropbox_sdk_logger if self._dbx_base: client._dbx_base = self._dbx_base.clone(session=session) client._dbx_base._logger = self._dropbox_sdk_logger return client
Creates a new copy of the Dropbox client with the same defaults unless modified by arguments to :meth:`clone`. :param config_name: Name of config file and state file to use. :param timeout: Timeout for individual requests. :param session: Requests session to use. :returns: A new instance of DropboxClient.
src/maestral/client.py
clone
samschott/maestral
436
python
def clone(self, config_name: (str | None)=None, cred_storage: (CredentialStorage | None)=None, timeout: (float | None)=None, session: (requests.Session | None)=None) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults unless modified\n by arguments to :meth:`clone`.\n\n :param config_name: Name of config file and state file to use.\n :param timeout: Timeout for individual requests.\n :param session: Requests session to use.\n :returns: A new instance of DropboxClient.\n ' config_name = (config_name or self.config_name) timeout = (timeout or self._timeout) session = (session or self._session) cred_storage = (cred_storage or self._cred_storage) client = self.__class__(config_name, cred_storage, timeout, session) if self._dbx: client._dbx = self._dbx.clone(session=session) client._dbx._logger = self._dropbox_sdk_logger if self._dbx_base: client._dbx_base = self._dbx_base.clone(session=session) client._dbx_base._logger = self._dropbox_sdk_logger return client
def clone(self, config_name: (str | None)=None, cred_storage: (CredentialStorage | None)=None, timeout: (float | None)=None, session: (requests.Session | None)=None) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults unless modified\n by arguments to :meth:`clone`.\n\n :param config_name: Name of config file and state file to use.\n :param timeout: Timeout for individual requests.\n :param session: Requests session to use.\n :returns: A new instance of DropboxClient.\n ' config_name = (config_name or self.config_name) timeout = (timeout or self._timeout) session = (session or self._session) cred_storage = (cred_storage or self._cred_storage) client = self.__class__(config_name, cred_storage, timeout, session) if self._dbx: client._dbx = self._dbx.clone(session=session) client._dbx._logger = self._dropbox_sdk_logger if self._dbx_base: client._dbx_base = self._dbx_base.clone(session=session) client._dbx_base._logger = self._dropbox_sdk_logger return client<|docstring|>Creates a new copy of the Dropbox client with the same defaults unless modified by arguments to :meth:`clone`. :param config_name: Name of config file and state file to use. :param timeout: Timeout for individual requests. :param session: Requests session to use. :returns: A new instance of DropboxClient.<|endoftext|>
730d9ff02241fa8fd000330e711363aedc4f059a5a922c443207f6f81ec6e442
def clone_with_new_session(self) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults but a new\n requests session.\n\n :returns: A new instance of DropboxClient.\n ' return self.clone(session=create_session())
Creates a new copy of the Dropbox client with the same defaults but a new requests session. :returns: A new instance of DropboxClient.
src/maestral/client.py
clone_with_new_session
samschott/maestral
436
python
def clone_with_new_session(self) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults but a new\n requests session.\n\n :returns: A new instance of DropboxClient.\n ' return self.clone(session=create_session())
def clone_with_new_session(self) -> DropboxClient: '\n Creates a new copy of the Dropbox client with the same defaults but a new\n requests session.\n\n :returns: A new instance of DropboxClient.\n ' return self.clone(session=create_session())<|docstring|>Creates a new copy of the Dropbox client with the same defaults but a new requests session. :returns: A new instance of DropboxClient.<|endoftext|>
83817883fbd13d03385fc702f0a2a1d74eaee1cec86668038b0f18dd7e8af590
def update_path_root(self, root_info: (RootInfo | None)=None) -> None: "\n Updates the root path for the Dropbox client. All files paths given as arguments\n to API calls such as :meth:`list_folder` or :meth:`get_metadata` will be\n interpreted as relative to the root path. All file paths returned by API calls,\n for instance in file metadata, will be relative to this root path.\n\n The root namespace will change when the user joins or leaves a Dropbox Team with\n Team Spaces. If this happens, API calls using the old root namespace will raise\n a :exc:`maestral.exceptions.PathRootError`. Use this method to update to the new\n root namespace.\n\n See https://developers.dropbox.com/dbx-team-files-guide and\n https://www.dropbox.com/developers/reference/path-root-header-modes for more\n information on Dropbox Team namespaces and path root headers in API calls.\n\n .. note:: We don't automatically switch root namespaces because API users may\n want to take action when the path root has changed before making further API\n calls. Be prepared to handle :exc:`maestral.exceptions.PathRootError`\n and act accordingly for all methods.\n\n :param root_info: Optional :class:`core.RootInfo` describing the path\n root. If not given, the latest root info will be fetched from Dropbox\n servers.\n " if (not root_info): account_info = self.get_account_info() root_info = account_info.root_info root_nsid = root_info.root_namespace_id path_root = common.PathRoot.root(root_nsid) self._dbx = self.dbx_base.with_path_root(path_root) self._dbx._logger = self._dropbox_sdk_logger if isinstance(root_info, UserRootInfo): actual_root_type = 'user' actual_home_path = '' elif isinstance(root_info, TeamRootInfo): actual_root_type = 'team' actual_home_path = root_info.home_path else: raise MaestralApiError('Unknown root namespace type', f'Got {root_info!r} but expected UserRootInfo or TeamRootInfo.') self._namespace_id = root_nsid self._is_team_space = (actual_root_type == 'team') self._state.set('account', 'path_root_nsid', root_nsid) self._state.set('account', 'path_root_type', actual_root_type) self._state.set('account', 'home_path', actual_home_path) self._logger.debug('Path root type: %s', actual_root_type) self._logger.debug('Path root nsid: %s', root_info.root_namespace_id) self._logger.debug('User home path: %s', actual_home_path)
Updates the root path for the Dropbox client. All files paths given as arguments to API calls such as :meth:`list_folder` or :meth:`get_metadata` will be interpreted as relative to the root path. All file paths returned by API calls, for instance in file metadata, will be relative to this root path. The root namespace will change when the user joins or leaves a Dropbox Team with Team Spaces. If this happens, API calls using the old root namespace will raise a :exc:`maestral.exceptions.PathRootError`. Use this method to update to the new root namespace. See https://developers.dropbox.com/dbx-team-files-guide and https://www.dropbox.com/developers/reference/path-root-header-modes for more information on Dropbox Team namespaces and path root headers in API calls. .. note:: We don't automatically switch root namespaces because API users may want to take action when the path root has changed before making further API calls. Be prepared to handle :exc:`maestral.exceptions.PathRootError` and act accordingly for all methods. :param root_info: Optional :class:`core.RootInfo` describing the path root. If not given, the latest root info will be fetched from Dropbox servers.
src/maestral/client.py
update_path_root
samschott/maestral
436
python
def update_path_root(self, root_info: (RootInfo | None)=None) -> None: "\n Updates the root path for the Dropbox client. All files paths given as arguments\n to API calls such as :meth:`list_folder` or :meth:`get_metadata` will be\n interpreted as relative to the root path. All file paths returned by API calls,\n for instance in file metadata, will be relative to this root path.\n\n The root namespace will change when the user joins or leaves a Dropbox Team with\n Team Spaces. If this happens, API calls using the old root namespace will raise\n a :exc:`maestral.exceptions.PathRootError`. Use this method to update to the new\n root namespace.\n\n See https://developers.dropbox.com/dbx-team-files-guide and\n https://www.dropbox.com/developers/reference/path-root-header-modes for more\n information on Dropbox Team namespaces and path root headers in API calls.\n\n .. note:: We don't automatically switch root namespaces because API users may\n want to take action when the path root has changed before making further API\n calls. Be prepared to handle :exc:`maestral.exceptions.PathRootError`\n and act accordingly for all methods.\n\n :param root_info: Optional :class:`core.RootInfo` describing the path\n root. If not given, the latest root info will be fetched from Dropbox\n servers.\n " if (not root_info): account_info = self.get_account_info() root_info = account_info.root_info root_nsid = root_info.root_namespace_id path_root = common.PathRoot.root(root_nsid) self._dbx = self.dbx_base.with_path_root(path_root) self._dbx._logger = self._dropbox_sdk_logger if isinstance(root_info, UserRootInfo): actual_root_type = 'user' actual_home_path = elif isinstance(root_info, TeamRootInfo): actual_root_type = 'team' actual_home_path = root_info.home_path else: raise MaestralApiError('Unknown root namespace type', f'Got {root_info!r} but expected UserRootInfo or TeamRootInfo.') self._namespace_id = root_nsid self._is_team_space = (actual_root_type == 'team') self._state.set('account', 'path_root_nsid', root_nsid) self._state.set('account', 'path_root_type', actual_root_type) self._state.set('account', 'home_path', actual_home_path) self._logger.debug('Path root type: %s', actual_root_type) self._logger.debug('Path root nsid: %s', root_info.root_namespace_id) self._logger.debug('User home path: %s', actual_home_path)
def update_path_root(self, root_info: (RootInfo | None)=None) -> None: "\n Updates the root path for the Dropbox client. All files paths given as arguments\n to API calls such as :meth:`list_folder` or :meth:`get_metadata` will be\n interpreted as relative to the root path. All file paths returned by API calls,\n for instance in file metadata, will be relative to this root path.\n\n The root namespace will change when the user joins or leaves a Dropbox Team with\n Team Spaces. If this happens, API calls using the old root namespace will raise\n a :exc:`maestral.exceptions.PathRootError`. Use this method to update to the new\n root namespace.\n\n See https://developers.dropbox.com/dbx-team-files-guide and\n https://www.dropbox.com/developers/reference/path-root-header-modes for more\n information on Dropbox Team namespaces and path root headers in API calls.\n\n .. note:: We don't automatically switch root namespaces because API users may\n want to take action when the path root has changed before making further API\n calls. Be prepared to handle :exc:`maestral.exceptions.PathRootError`\n and act accordingly for all methods.\n\n :param root_info: Optional :class:`core.RootInfo` describing the path\n root. If not given, the latest root info will be fetched from Dropbox\n servers.\n " if (not root_info): account_info = self.get_account_info() root_info = account_info.root_info root_nsid = root_info.root_namespace_id path_root = common.PathRoot.root(root_nsid) self._dbx = self.dbx_base.with_path_root(path_root) self._dbx._logger = self._dropbox_sdk_logger if isinstance(root_info, UserRootInfo): actual_root_type = 'user' actual_home_path = elif isinstance(root_info, TeamRootInfo): actual_root_type = 'team' actual_home_path = root_info.home_path else: raise MaestralApiError('Unknown root namespace type', f'Got {root_info!r} but expected UserRootInfo or TeamRootInfo.') self._namespace_id = root_nsid self._is_team_space = (actual_root_type == 'team') self._state.set('account', 'path_root_nsid', root_nsid) self._state.set('account', 'path_root_type', actual_root_type) self._state.set('account', 'home_path', actual_home_path) self._logger.debug('Path root type: %s', actual_root_type) self._logger.debug('Path root nsid: %s', root_info.root_namespace_id) self._logger.debug('User home path: %s', actual_home_path)<|docstring|>Updates the root path for the Dropbox client. All files paths given as arguments to API calls such as :meth:`list_folder` or :meth:`get_metadata` will be interpreted as relative to the root path. All file paths returned by API calls, for instance in file metadata, will be relative to this root path. The root namespace will change when the user joins or leaves a Dropbox Team with Team Spaces. If this happens, API calls using the old root namespace will raise a :exc:`maestral.exceptions.PathRootError`. Use this method to update to the new root namespace. See https://developers.dropbox.com/dbx-team-files-guide and https://www.dropbox.com/developers/reference/path-root-header-modes for more information on Dropbox Team namespaces and path root headers in API calls. .. note:: We don't automatically switch root namespaces because API users may want to take action when the path root has changed before making further API calls. Be prepared to handle :exc:`maestral.exceptions.PathRootError` and act accordingly for all methods. :param root_info: Optional :class:`core.RootInfo` describing the path root. If not given, the latest root info will be fetched from Dropbox servers.<|endoftext|>
a5d22f9f5a1dfbee63e4242f14b1d32979e334d98fd10c9782a4c05f1c5b0256
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_account_info(self, dbid=None): '\n Gets current account information.\n\n :param dbid: Dropbox ID of account. If not given, will get the info of the\n currently linked account.\n :returns: Account info.\n ' with convert_api_errors(): if dbid: res = self.dbx_base.users_get_account(dbid) return convert_account(res) res = self.dbx_base.users_get_current_account() if res.account_type.is_basic(): account_type = AccountType.Basic elif res.account_type.is_business(): account_type = AccountType.Business elif res.account_type.is_pro(): account_type = AccountType.Pro else: account_type = AccountType.Other self._state.set('account', 'email', res.email) self._state.set('account', 'display_name', res.name.display_name) self._state.set('account', 'abbreviated_name', res.name.abbreviated_name) self._state.set('account', 'type', account_type.value) if (not self._namespace_id): home_nsid = res.root_info.home_namespace_id self._namespace_id = home_nsid self._state.set('account', 'path_root_nsid', home_nsid) self._cached_account_info = convert_full_account(res) return self._cached_account_info
Gets current account information. :param dbid: Dropbox ID of account. If not given, will get the info of the currently linked account. :returns: Account info.
src/maestral/client.py
get_account_info
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_account_info(self, dbid=None): '\n Gets current account information.\n\n :param dbid: Dropbox ID of account. If not given, will get the info of the\n currently linked account.\n :returns: Account info.\n ' with convert_api_errors(): if dbid: res = self.dbx_base.users_get_account(dbid) return convert_account(res) res = self.dbx_base.users_get_current_account() if res.account_type.is_basic(): account_type = AccountType.Basic elif res.account_type.is_business(): account_type = AccountType.Business elif res.account_type.is_pro(): account_type = AccountType.Pro else: account_type = AccountType.Other self._state.set('account', 'email', res.email) self._state.set('account', 'display_name', res.name.display_name) self._state.set('account', 'abbreviated_name', res.name.abbreviated_name) self._state.set('account', 'type', account_type.value) if (not self._namespace_id): home_nsid = res.root_info.home_namespace_id self._namespace_id = home_nsid self._state.set('account', 'path_root_nsid', home_nsid) self._cached_account_info = convert_full_account(res) return self._cached_account_info
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_account_info(self, dbid=None): '\n Gets current account information.\n\n :param dbid: Dropbox ID of account. If not given, will get the info of the\n currently linked account.\n :returns: Account info.\n ' with convert_api_errors(): if dbid: res = self.dbx_base.users_get_account(dbid) return convert_account(res) res = self.dbx_base.users_get_current_account() if res.account_type.is_basic(): account_type = AccountType.Basic elif res.account_type.is_business(): account_type = AccountType.Business elif res.account_type.is_pro(): account_type = AccountType.Pro else: account_type = AccountType.Other self._state.set('account', 'email', res.email) self._state.set('account', 'display_name', res.name.display_name) self._state.set('account', 'abbreviated_name', res.name.abbreviated_name) self._state.set('account', 'type', account_type.value) if (not self._namespace_id): home_nsid = res.root_info.home_namespace_id self._namespace_id = home_nsid self._state.set('account', 'path_root_nsid', home_nsid) self._cached_account_info = convert_full_account(res) return self._cached_account_info<|docstring|>Gets current account information. :param dbid: Dropbox ID of account. If not given, will get the info of the currently linked account. :returns: Account info.<|endoftext|>
5f1f2cf3229c344e0b27f300b57108fe757700bc7e182d5ee376da797ff729ff
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_space_usage(self) -> SpaceUsage: '\n :returns: The space usage of the currently linked account.\n ' with convert_api_errors(): res = self.dbx_base.users_get_space_usage() if res.allocation.is_team(): usage_type = 'team' elif res.allocation.is_individual(): usage_type = 'individual' else: usage_type = '' if res.allocation.is_team(): used = res.allocation.get_team().used allocated = res.allocation.get_team().allocated else: used = res.used allocated = res.allocation.get_individual().allocated percent = (used / allocated) space_usage = f'{percent:.1%} of {natural_size(allocated)} used' self._state.set('account', 'usage', space_usage) self._state.set('account', 'usage_type', usage_type) return convert_space_usage(res)
:returns: The space usage of the currently linked account.
src/maestral/client.py
get_space_usage
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_space_usage(self) -> SpaceUsage: '\n \n ' with convert_api_errors(): res = self.dbx_base.users_get_space_usage() if res.allocation.is_team(): usage_type = 'team' elif res.allocation.is_individual(): usage_type = 'individual' else: usage_type = if res.allocation.is_team(): used = res.allocation.get_team().used allocated = res.allocation.get_team().allocated else: used = res.used allocated = res.allocation.get_individual().allocated percent = (used / allocated) space_usage = f'{percent:.1%} of {natural_size(allocated)} used' self._state.set('account', 'usage', space_usage) self._state.set('account', 'usage_type', usage_type) return convert_space_usage(res)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_space_usage(self) -> SpaceUsage: '\n \n ' with convert_api_errors(): res = self.dbx_base.users_get_space_usage() if res.allocation.is_team(): usage_type = 'team' elif res.allocation.is_individual(): usage_type = 'individual' else: usage_type = if res.allocation.is_team(): used = res.allocation.get_team().used allocated = res.allocation.get_team().allocated else: used = res.used allocated = res.allocation.get_individual().allocated percent = (used / allocated) space_usage = f'{percent:.1%} of {natural_size(allocated)} used' self._state.set('account', 'usage', space_usage) self._state.set('account', 'usage_type', usage_type) return convert_space_usage(res)<|docstring|>:returns: The space usage of the currently linked account.<|endoftext|>
107c6664de547709023084392ddd71509940233308e6785e277968a0b182f0ae
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_metadata(self, dbx_path: str, include_deleted: bool=False) -> (Metadata | None): '\n Gets metadata for an item on Dropbox or returns ``False`` if no metadata is\n available. Keyword arguments are passed on to Dropbox SDK files_get_metadata\n call.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_deleted: Whether to return data for deleted items.\n :returns: Metadata of item at the given path or ``None`` if item cannot be found.\n ' try: with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_get_metadata(dbx_path, include_deleted=include_deleted) return convert_metadata(res) except (NotFoundError, PathError): return None
Gets metadata for an item on Dropbox or returns ``False`` if no metadata is available. Keyword arguments are passed on to Dropbox SDK files_get_metadata call. :param dbx_path: Path of folder on Dropbox. :param include_deleted: Whether to return data for deleted items. :returns: Metadata of item at the given path or ``None`` if item cannot be found.
src/maestral/client.py
get_metadata
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_metadata(self, dbx_path: str, include_deleted: bool=False) -> (Metadata | None): '\n Gets metadata for an item on Dropbox or returns ``False`` if no metadata is\n available. Keyword arguments are passed on to Dropbox SDK files_get_metadata\n call.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_deleted: Whether to return data for deleted items.\n :returns: Metadata of item at the given path or ``None`` if item cannot be found.\n ' try: with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_get_metadata(dbx_path, include_deleted=include_deleted) return convert_metadata(res) except (NotFoundError, PathError): return None
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_metadata(self, dbx_path: str, include_deleted: bool=False) -> (Metadata | None): '\n Gets metadata for an item on Dropbox or returns ``False`` if no metadata is\n available. Keyword arguments are passed on to Dropbox SDK files_get_metadata\n call.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_deleted: Whether to return data for deleted items.\n :returns: Metadata of item at the given path or ``None`` if item cannot be found.\n ' try: with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_get_metadata(dbx_path, include_deleted=include_deleted) return convert_metadata(res) except (NotFoundError, PathError): return None<|docstring|>Gets metadata for an item on Dropbox or returns ``False`` if no metadata is available. Keyword arguments are passed on to Dropbox SDK files_get_metadata call. :param dbx_path: Path of folder on Dropbox. :param include_deleted: Whether to return data for deleted items. :returns: Metadata of item at the given path or ``None`` if item cannot be found.<|endoftext|>
ff41950222d90fb4377315b13a056c8192ded40eebc0b0dcfb67d5971c158e27
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_revisions(self, dbx_path: str, mode: str='path', limit: int=10) -> list[FileMetadata]: "\n Lists all file revisions for the given file.\n\n :param dbx_path: Path to file on Dropbox.\n :param mode: Must be 'path' or 'id'. If 'id', specify the Dropbox file ID\n instead of the file path to get revisions across move and rename events.\n :param limit: Maximum number of revisions to list.\n :returns: File revision history.\n " with convert_api_errors(dbx_path=dbx_path): dbx_mode = files.ListRevisionsMode(mode) res = self.dbx.files_list_revisions(dbx_path, mode=dbx_mode, limit=limit) return [convert_metadata(entry) for entry in res.entries]
Lists all file revisions for the given file. :param dbx_path: Path to file on Dropbox. :param mode: Must be 'path' or 'id'. If 'id', specify the Dropbox file ID instead of the file path to get revisions across move and rename events. :param limit: Maximum number of revisions to list. :returns: File revision history.
src/maestral/client.py
list_revisions
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_revisions(self, dbx_path: str, mode: str='path', limit: int=10) -> list[FileMetadata]: "\n Lists all file revisions for the given file.\n\n :param dbx_path: Path to file on Dropbox.\n :param mode: Must be 'path' or 'id'. If 'id', specify the Dropbox file ID\n instead of the file path to get revisions across move and rename events.\n :param limit: Maximum number of revisions to list.\n :returns: File revision history.\n " with convert_api_errors(dbx_path=dbx_path): dbx_mode = files.ListRevisionsMode(mode) res = self.dbx.files_list_revisions(dbx_path, mode=dbx_mode, limit=limit) return [convert_metadata(entry) for entry in res.entries]
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_revisions(self, dbx_path: str, mode: str='path', limit: int=10) -> list[FileMetadata]: "\n Lists all file revisions for the given file.\n\n :param dbx_path: Path to file on Dropbox.\n :param mode: Must be 'path' or 'id'. If 'id', specify the Dropbox file ID\n instead of the file path to get revisions across move and rename events.\n :param limit: Maximum number of revisions to list.\n :returns: File revision history.\n " with convert_api_errors(dbx_path=dbx_path): dbx_mode = files.ListRevisionsMode(mode) res = self.dbx.files_list_revisions(dbx_path, mode=dbx_mode, limit=limit) return [convert_metadata(entry) for entry in res.entries]<|docstring|>Lists all file revisions for the given file. :param dbx_path: Path to file on Dropbox. :param mode: Must be 'path' or 'id'. If 'id', specify the Dropbox file ID instead of the file path to get revisions across move and rename events. :param limit: Maximum number of revisions to list. :returns: File revision history.<|endoftext|>
c59f59bf42f5e29b7a1a16fe8922afe823fab59c9e0076d3313a225e7c9419a6
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def restore(self, dbx_path: str, rev: str) -> FileMetadata: '\n Restore an old revision of a file.\n\n :param dbx_path: The path to save the restored file.\n :param rev: The revision to restore. Old revisions can be listed with\n :meth:`list_revisions`.\n :returns: Metadata of restored file.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_restore(dbx_path, rev) return convert_metadata(res)
Restore an old revision of a file. :param dbx_path: The path to save the restored file. :param rev: The revision to restore. Old revisions can be listed with :meth:`list_revisions`. :returns: Metadata of restored file.
src/maestral/client.py
restore
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def restore(self, dbx_path: str, rev: str) -> FileMetadata: '\n Restore an old revision of a file.\n\n :param dbx_path: The path to save the restored file.\n :param rev: The revision to restore. Old revisions can be listed with\n :meth:`list_revisions`.\n :returns: Metadata of restored file.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_restore(dbx_path, rev) return convert_metadata(res)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def restore(self, dbx_path: str, rev: str) -> FileMetadata: '\n Restore an old revision of a file.\n\n :param dbx_path: The path to save the restored file.\n :param rev: The revision to restore. Old revisions can be listed with\n :meth:`list_revisions`.\n :returns: Metadata of restored file.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_restore(dbx_path, rev) return convert_metadata(res)<|docstring|>Restore an old revision of a file. :param dbx_path: The path to save the restored file. :param rev: The revision to restore. Old revisions can be listed with :meth:`list_revisions`. :returns: Metadata of restored file.<|endoftext|>
237ee64ec7fd90b260684a298f9ecac677452ba773fa36026801a69a55f9eb0e
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') @_retry_on_error(DataCorruptionError, MAX_TRANSFER_RETRIES) def download(self, dbx_path: str, local_path: str, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Downloads a file from Dropbox to given local path.\n\n :param dbx_path: Path to file on Dropbox or rev number.\n :param local_path: Path to local download destination.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :returns: Metadata of downloaded item.\n :raises DataCorruptionError: if data is corrupted during download.\n ' with convert_api_errors(dbx_path=dbx_path): md = self.dbx.files_get_metadata(dbx_path) if (isinstance(md, files.FileMetadata) and md.symlink_info): try: os.unlink(local_path) except FileNotFoundError: pass os.symlink(md.symlink_info.target, local_path) else: chunk_size = (2 ** 13) (md, http_resp) = self.dbx.files_download(dbx_path) hasher = DropboxContentHasher() with open(local_path, 'wb', opener=opener_no_symlink) as f: wrapped_f = StreamHasher(f, hasher) with contextlib.closing(http_resp): for c in http_resp.iter_content(chunk_size): wrapped_f.write(c) if sync_event: sync_event.completed = wrapped_f.tell() local_hash = hasher.hexdigest() if (md.content_hash != local_hash): delete(local_path) raise DataCorruptionError('Data corrupted', 'Please retry download.') client_mod = md.client_modified.replace(tzinfo=timezone.utc) server_mod = md.server_modified.replace(tzinfo=timezone.utc) timestamp = min(client_mod.timestamp(), server_mod.timestamp(), time.time()) os.utime(local_path, (time.time(), timestamp), follow_symlinks=False) return convert_metadata(md)
Downloads a file from Dropbox to given local path. :param dbx_path: Path to file on Dropbox or rev number. :param local_path: Path to local download destination. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :returns: Metadata of downloaded item. :raises DataCorruptionError: if data is corrupted during download.
src/maestral/client.py
download
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') @_retry_on_error(DataCorruptionError, MAX_TRANSFER_RETRIES) def download(self, dbx_path: str, local_path: str, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Downloads a file from Dropbox to given local path.\n\n :param dbx_path: Path to file on Dropbox or rev number.\n :param local_path: Path to local download destination.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :returns: Metadata of downloaded item.\n :raises DataCorruptionError: if data is corrupted during download.\n ' with convert_api_errors(dbx_path=dbx_path): md = self.dbx.files_get_metadata(dbx_path) if (isinstance(md, files.FileMetadata) and md.symlink_info): try: os.unlink(local_path) except FileNotFoundError: pass os.symlink(md.symlink_info.target, local_path) else: chunk_size = (2 ** 13) (md, http_resp) = self.dbx.files_download(dbx_path) hasher = DropboxContentHasher() with open(local_path, 'wb', opener=opener_no_symlink) as f: wrapped_f = StreamHasher(f, hasher) with contextlib.closing(http_resp): for c in http_resp.iter_content(chunk_size): wrapped_f.write(c) if sync_event: sync_event.completed = wrapped_f.tell() local_hash = hasher.hexdigest() if (md.content_hash != local_hash): delete(local_path) raise DataCorruptionError('Data corrupted', 'Please retry download.') client_mod = md.client_modified.replace(tzinfo=timezone.utc) server_mod = md.server_modified.replace(tzinfo=timezone.utc) timestamp = min(client_mod.timestamp(), server_mod.timestamp(), time.time()) os.utime(local_path, (time.time(), timestamp), follow_symlinks=False) return convert_metadata(md)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') @_retry_on_error(DataCorruptionError, MAX_TRANSFER_RETRIES) def download(self, dbx_path: str, local_path: str, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Downloads a file from Dropbox to given local path.\n\n :param dbx_path: Path to file on Dropbox or rev number.\n :param local_path: Path to local download destination.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :returns: Metadata of downloaded item.\n :raises DataCorruptionError: if data is corrupted during download.\n ' with convert_api_errors(dbx_path=dbx_path): md = self.dbx.files_get_metadata(dbx_path) if (isinstance(md, files.FileMetadata) and md.symlink_info): try: os.unlink(local_path) except FileNotFoundError: pass os.symlink(md.symlink_info.target, local_path) else: chunk_size = (2 ** 13) (md, http_resp) = self.dbx.files_download(dbx_path) hasher = DropboxContentHasher() with open(local_path, 'wb', opener=opener_no_symlink) as f: wrapped_f = StreamHasher(f, hasher) with contextlib.closing(http_resp): for c in http_resp.iter_content(chunk_size): wrapped_f.write(c) if sync_event: sync_event.completed = wrapped_f.tell() local_hash = hasher.hexdigest() if (md.content_hash != local_hash): delete(local_path) raise DataCorruptionError('Data corrupted', 'Please retry download.') client_mod = md.client_modified.replace(tzinfo=timezone.utc) server_mod = md.server_modified.replace(tzinfo=timezone.utc) timestamp = min(client_mod.timestamp(), server_mod.timestamp(), time.time()) os.utime(local_path, (time.time(), timestamp), follow_symlinks=False) return convert_metadata(md)<|docstring|>Downloads a file from Dropbox to given local path. :param dbx_path: Path to file on Dropbox or rev number. :param local_path: Path to local download destination. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :returns: Metadata of downloaded item. :raises DataCorruptionError: if data is corrupted during download.<|endoftext|>
b134a1d762a452550a61522208d01f668fa903e7789d6bb568e0b2377f7d55c5
def upload(self, local_path: str, dbx_path: str, chunk_size: int=(5 * (10 ** 6)), write_mode: WriteMode=WriteMode.Add, update_rev: (str | None)=None, autorename: bool=False, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Uploads local file to Dropbox.\n\n :param local_path: Path of local file to upload.\n :param dbx_path: Path to save file on Dropbox.\n :param chunk_size: Maximum size for individual uploads. If larger than 150 MB,\n it will be set to 150 MB.\n :param write_mode: Your intent when writing a file to some path. This is used to\n determine what constitutes a conflict and what the autorename strategy is.\n This is used to determine what\n constitutes a conflict and what the autorename strategy is. In some\n situations, the conflict behavior is identical: (a) If the target path\n doesn\'t refer to anything, the file is always written; no conflict. (b) If\n the target path refers to a folder, it\'s always a conflict. (c) If the\n target path refers to a file with identical contents, nothing gets written;\n no conflict. The conflict checking differs in the case where there\'s a file\n at the target path with contents different from the contents you\'re trying\n to write.\n :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a\n conflict. The autorename strategy is to append a number to the file\n name. For example, "document.txt" might become "document (2).txt".\n :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The\n autorename strategy is the same as it is for ``add``.\n :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the\n existing file\'s "rev". The supplied value should be the latest known\n "rev" of the file, for example, from :class:`core.FileMetadata`, from when the\n file was last downloaded by the app. This will cause the file on the\n Dropbox servers to be overwritten if the given "rev" matches the\n existing file\'s current "rev" on the Dropbox servers. The autorename\n strategy is to append the string "conflicted copy" to the file name. For\n example, "document.txt" might become "document (conflicted copy).txt" or\n "document (Panda\'s conflicted copy).txt".\n :param update_rev: Rev to match for :class:`core.WriteMode.Update`.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :param autorename: If there\'s a conflict, as determined by ``mode``, have the\n Dropbox server try to autorename the file to avoid conflict. The default for\n this field is False.\n :returns: Metadata of uploaded file.\n :raises DataCorruptionError: if data is corrupted during upload.\n ' chunk_size = clamp(chunk_size, (10 ** 5), (150 * (10 ** 6))) if (write_mode is WriteMode.Add): dbx_write_mode = files.WriteMode.add elif (write_mode is WriteMode.Overwrite): dbx_write_mode = files.WriteMode.overwrite elif (write_mode is WriteMode.Update): if (update_rev is None): raise RuntimeError("Please provide 'update_rev'") dbx_write_mode = files.WriteMode.update(update_rev) else: raise RuntimeError('No write mode for uploading file.') with convert_api_errors(dbx_path=dbx_path, local_path=local_path): stat = os.lstat(local_path) mtime_dt = datetime.utcfromtimestamp(stat.st_mtime) if (stat.st_size <= chunk_size): res = self._upload_helper(local_path, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) else: with open(local_path, 'rb', opener=opener_no_symlink) as f: session_id = self._upload_session_start_helper(f, chunk_size, dbx_path, sync_event) while ((stat.st_size - f.tell()) > chunk_size): self._upload_session_append_helper(f, session_id, chunk_size, dbx_path, sync_event) res = self._upload_session_finish_helper(f, session_id, chunk_size, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) return convert_metadata(res)
Uploads local file to Dropbox. :param local_path: Path of local file to upload. :param dbx_path: Path to save file on Dropbox. :param chunk_size: Maximum size for individual uploads. If larger than 150 MB, it will be set to 150 MB. :param write_mode: Your intent when writing a file to some path. This is used to determine what constitutes a conflict and what the autorename strategy is. This is used to determine what constitutes a conflict and what the autorename strategy is. In some situations, the conflict behavior is identical: (a) If the target path doesn't refer to anything, the file is always written; no conflict. (b) If the target path refers to a folder, it's always a conflict. (c) If the target path refers to a file with identical contents, nothing gets written; no conflict. The conflict checking differs in the case where there's a file at the target path with contents different from the contents you're trying to write. :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a conflict. The autorename strategy is to append a number to the file name. For example, "document.txt" might become "document (2).txt". :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The autorename strategy is the same as it is for ``add``. :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the existing file's "rev". The supplied value should be the latest known "rev" of the file, for example, from :class:`core.FileMetadata`, from when the file was last downloaded by the app. This will cause the file on the Dropbox servers to be overwritten if the given "rev" matches the existing file's current "rev" on the Dropbox servers. The autorename strategy is to append the string "conflicted copy" to the file name. For example, "document.txt" might become "document (conflicted copy).txt" or "document (Panda's conflicted copy).txt". :param update_rev: Rev to match for :class:`core.WriteMode.Update`. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :param autorename: If there's a conflict, as determined by ``mode``, have the Dropbox server try to autorename the file to avoid conflict. The default for this field is False. :returns: Metadata of uploaded file. :raises DataCorruptionError: if data is corrupted during upload.
src/maestral/client.py
upload
samschott/maestral
436
python
def upload(self, local_path: str, dbx_path: str, chunk_size: int=(5 * (10 ** 6)), write_mode: WriteMode=WriteMode.Add, update_rev: (str | None)=None, autorename: bool=False, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Uploads local file to Dropbox.\n\n :param local_path: Path of local file to upload.\n :param dbx_path: Path to save file on Dropbox.\n :param chunk_size: Maximum size for individual uploads. If larger than 150 MB,\n it will be set to 150 MB.\n :param write_mode: Your intent when writing a file to some path. This is used to\n determine what constitutes a conflict and what the autorename strategy is.\n This is used to determine what\n constitutes a conflict and what the autorename strategy is. In some\n situations, the conflict behavior is identical: (a) If the target path\n doesn\'t refer to anything, the file is always written; no conflict. (b) If\n the target path refers to a folder, it\'s always a conflict. (c) If the\n target path refers to a file with identical contents, nothing gets written;\n no conflict. The conflict checking differs in the case where there\'s a file\n at the target path with contents different from the contents you\'re trying\n to write.\n :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a\n conflict. The autorename strategy is to append a number to the file\n name. For example, "document.txt" might become "document (2).txt".\n :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The\n autorename strategy is the same as it is for ``add``.\n :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the\n existing file\'s "rev". The supplied value should be the latest known\n "rev" of the file, for example, from :class:`core.FileMetadata`, from when the\n file was last downloaded by the app. This will cause the file on the\n Dropbox servers to be overwritten if the given "rev" matches the\n existing file\'s current "rev" on the Dropbox servers. The autorename\n strategy is to append the string "conflicted copy" to the file name. For\n example, "document.txt" might become "document (conflicted copy).txt" or\n "document (Panda\'s conflicted copy).txt".\n :param update_rev: Rev to match for :class:`core.WriteMode.Update`.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :param autorename: If there\'s a conflict, as determined by ``mode``, have the\n Dropbox server try to autorename the file to avoid conflict. The default for\n this field is False.\n :returns: Metadata of uploaded file.\n :raises DataCorruptionError: if data is corrupted during upload.\n ' chunk_size = clamp(chunk_size, (10 ** 5), (150 * (10 ** 6))) if (write_mode is WriteMode.Add): dbx_write_mode = files.WriteMode.add elif (write_mode is WriteMode.Overwrite): dbx_write_mode = files.WriteMode.overwrite elif (write_mode is WriteMode.Update): if (update_rev is None): raise RuntimeError("Please provide 'update_rev'") dbx_write_mode = files.WriteMode.update(update_rev) else: raise RuntimeError('No write mode for uploading file.') with convert_api_errors(dbx_path=dbx_path, local_path=local_path): stat = os.lstat(local_path) mtime_dt = datetime.utcfromtimestamp(stat.st_mtime) if (stat.st_size <= chunk_size): res = self._upload_helper(local_path, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) else: with open(local_path, 'rb', opener=opener_no_symlink) as f: session_id = self._upload_session_start_helper(f, chunk_size, dbx_path, sync_event) while ((stat.st_size - f.tell()) > chunk_size): self._upload_session_append_helper(f, session_id, chunk_size, dbx_path, sync_event) res = self._upload_session_finish_helper(f, session_id, chunk_size, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) return convert_metadata(res)
def upload(self, local_path: str, dbx_path: str, chunk_size: int=(5 * (10 ** 6)), write_mode: WriteMode=WriteMode.Add, update_rev: (str | None)=None, autorename: bool=False, sync_event: (SyncEvent | None)=None) -> FileMetadata: '\n Uploads local file to Dropbox.\n\n :param local_path: Path of local file to upload.\n :param dbx_path: Path to save file on Dropbox.\n :param chunk_size: Maximum size for individual uploads. If larger than 150 MB,\n it will be set to 150 MB.\n :param write_mode: Your intent when writing a file to some path. This is used to\n determine what constitutes a conflict and what the autorename strategy is.\n This is used to determine what\n constitutes a conflict and what the autorename strategy is. In some\n situations, the conflict behavior is identical: (a) If the target path\n doesn\'t refer to anything, the file is always written; no conflict. (b) If\n the target path refers to a folder, it\'s always a conflict. (c) If the\n target path refers to a file with identical contents, nothing gets written;\n no conflict. The conflict checking differs in the case where there\'s a file\n at the target path with contents different from the contents you\'re trying\n to write.\n :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a\n conflict. The autorename strategy is to append a number to the file\n name. For example, "document.txt" might become "document (2).txt".\n :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The\n autorename strategy is the same as it is for ``add``.\n :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the\n existing file\'s "rev". The supplied value should be the latest known\n "rev" of the file, for example, from :class:`core.FileMetadata`, from when the\n file was last downloaded by the app. This will cause the file on the\n Dropbox servers to be overwritten if the given "rev" matches the\n existing file\'s current "rev" on the Dropbox servers. The autorename\n strategy is to append the string "conflicted copy" to the file name. For\n example, "document.txt" might become "document (conflicted copy).txt" or\n "document (Panda\'s conflicted copy).txt".\n :param update_rev: Rev to match for :class:`core.WriteMode.Update`.\n :param sync_event: If given, the sync event will be updated with the number of\n downloaded bytes.\n :param autorename: If there\'s a conflict, as determined by ``mode``, have the\n Dropbox server try to autorename the file to avoid conflict. The default for\n this field is False.\n :returns: Metadata of uploaded file.\n :raises DataCorruptionError: if data is corrupted during upload.\n ' chunk_size = clamp(chunk_size, (10 ** 5), (150 * (10 ** 6))) if (write_mode is WriteMode.Add): dbx_write_mode = files.WriteMode.add elif (write_mode is WriteMode.Overwrite): dbx_write_mode = files.WriteMode.overwrite elif (write_mode is WriteMode.Update): if (update_rev is None): raise RuntimeError("Please provide 'update_rev'") dbx_write_mode = files.WriteMode.update(update_rev) else: raise RuntimeError('No write mode for uploading file.') with convert_api_errors(dbx_path=dbx_path, local_path=local_path): stat = os.lstat(local_path) mtime_dt = datetime.utcfromtimestamp(stat.st_mtime) if (stat.st_size <= chunk_size): res = self._upload_helper(local_path, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) else: with open(local_path, 'rb', opener=opener_no_symlink) as f: session_id = self._upload_session_start_helper(f, chunk_size, dbx_path, sync_event) while ((stat.st_size - f.tell()) > chunk_size): self._upload_session_append_helper(f, session_id, chunk_size, dbx_path, sync_event) res = self._upload_session_finish_helper(f, session_id, chunk_size, dbx_path, mtime_dt, dbx_write_mode, autorename, sync_event) return convert_metadata(res)<|docstring|>Uploads local file to Dropbox. :param local_path: Path of local file to upload. :param dbx_path: Path to save file on Dropbox. :param chunk_size: Maximum size for individual uploads. If larger than 150 MB, it will be set to 150 MB. :param write_mode: Your intent when writing a file to some path. This is used to determine what constitutes a conflict and what the autorename strategy is. This is used to determine what constitutes a conflict and what the autorename strategy is. In some situations, the conflict behavior is identical: (a) If the target path doesn't refer to anything, the file is always written; no conflict. (b) If the target path refers to a folder, it's always a conflict. (c) If the target path refers to a file with identical contents, nothing gets written; no conflict. The conflict checking differs in the case where there's a file at the target path with contents different from the contents you're trying to write. :class:`core.WriteMode.Add` Do not overwrite an existing file if there is a conflict. The autorename strategy is to append a number to the file name. For example, "document.txt" might become "document (2).txt". :class:`core.WriteMode.Overwrite` Always overwrite the existing file. The autorename strategy is the same as it is for ``add``. :class:`core.WriteMode.Update` Overwrite if the given "update_rev" matches the existing file's "rev". The supplied value should be the latest known "rev" of the file, for example, from :class:`core.FileMetadata`, from when the file was last downloaded by the app. This will cause the file on the Dropbox servers to be overwritten if the given "rev" matches the existing file's current "rev" on the Dropbox servers. The autorename strategy is to append the string "conflicted copy" to the file name. For example, "document.txt" might become "document (conflicted copy).txt" or "document (Panda's conflicted copy).txt". :param update_rev: Rev to match for :class:`core.WriteMode.Update`. :param sync_event: If given, the sync event will be updated with the number of downloaded bytes. :param autorename: If there's a conflict, as determined by ``mode``, have the Dropbox server try to autorename the file to avoid conflict. The default for this field is False. :returns: Metadata of uploaded file. :raises DataCorruptionError: if data is corrupted during upload.<|endoftext|>
125b9dbf603c225b0664d0fd67b6128e40985c8e707213746c435c82291819ca
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove(self, dbx_path: str, parent_rev: (str | None)=None) -> (FileMetadata | FolderMetadata): '\n Removes a file / folder from Dropbox.\n\n :param dbx_path: Path to file on Dropbox.\n :param parent_rev: Perform delete if given "rev" matches the existing file\'s\n latest "rev". This field does not support deleting a folder.\n :returns: Metadata of deleted item.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_delete_v2(dbx_path, parent_rev=parent_rev) return convert_metadata(res.metadata)
Removes a file / folder from Dropbox. :param dbx_path: Path to file on Dropbox. :param parent_rev: Perform delete if given "rev" matches the existing file's latest "rev". This field does not support deleting a folder. :returns: Metadata of deleted item.
src/maestral/client.py
remove
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove(self, dbx_path: str, parent_rev: (str | None)=None) -> (FileMetadata | FolderMetadata): '\n Removes a file / folder from Dropbox.\n\n :param dbx_path: Path to file on Dropbox.\n :param parent_rev: Perform delete if given "rev" matches the existing file\'s\n latest "rev". This field does not support deleting a folder.\n :returns: Metadata of deleted item.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_delete_v2(dbx_path, parent_rev=parent_rev) return convert_metadata(res.metadata)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove(self, dbx_path: str, parent_rev: (str | None)=None) -> (FileMetadata | FolderMetadata): '\n Removes a file / folder from Dropbox.\n\n :param dbx_path: Path to file on Dropbox.\n :param parent_rev: Perform delete if given "rev" matches the existing file\'s\n latest "rev". This field does not support deleting a folder.\n :returns: Metadata of deleted item.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_delete_v2(dbx_path, parent_rev=parent_rev) return convert_metadata(res.metadata)<|docstring|>Removes a file / folder from Dropbox. :param dbx_path: Path to file on Dropbox. :param parent_rev: Perform delete if given "rev" matches the existing file's latest "rev". This field does not support deleting a folder. :returns: Metadata of deleted item.<|endoftext|>
f3b65bc90158323632b892f1f5063c12fb081eed7f4e55725246d1d1c19913ca
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove_batch(self, entries: Sequence[tuple[(str, (str | None))]], batch_size: int=900) -> list[((FileMetadata | FolderMetadata) | MaestralApiError)]: '\n Deletes multiple items on Dropbox in a batch job.\n\n :param entries: List of Dropbox paths and "rev"s to delete. If a "rev" is not\n None, the file will only be deleted if it matches the rev on Dropbox. This\n is not supported when deleting a folder.\n :param batch_size: Number of items to delete in each batch. Dropbox allows\n batches of up to 1,000 items. Larger values will be capped automatically.\n :returns: List of Metadata for deleted items or SyncErrors for failures. Results\n will be in the same order as the original input.\n ' batch_size = clamp(batch_size, 1, 1000) res_entries = [] result_list: list[((FileMetadata | FolderMetadata) | MaestralApiError)] = [] for chunk in chunks(list(entries), n=batch_size): arg = [files.DeleteArg(e[0], e[1]) for e in chunk] with convert_api_errors(): res = self.dbx.files_delete_batch(arg) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_write_operations(): title = 'Could not delete items' text = 'There are too many write operations happening in your Dropbox. Please try again later.' raise SyncError(title, text) for (i, entry) in enumerate(res_entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text='', user_message_locale='', request_id='') sync_err = dropbox_to_maestral_error(exc, dbx_path=entries[i][0]) result_list.append(sync_err) return result_list
Deletes multiple items on Dropbox in a batch job. :param entries: List of Dropbox paths and "rev"s to delete. If a "rev" is not None, the file will only be deleted if it matches the rev on Dropbox. This is not supported when deleting a folder. :param batch_size: Number of items to delete in each batch. Dropbox allows batches of up to 1,000 items. Larger values will be capped automatically. :returns: List of Metadata for deleted items or SyncErrors for failures. Results will be in the same order as the original input.
src/maestral/client.py
remove_batch
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove_batch(self, entries: Sequence[tuple[(str, (str | None))]], batch_size: int=900) -> list[((FileMetadata | FolderMetadata) | MaestralApiError)]: '\n Deletes multiple items on Dropbox in a batch job.\n\n :param entries: List of Dropbox paths and "rev"s to delete. If a "rev" is not\n None, the file will only be deleted if it matches the rev on Dropbox. This\n is not supported when deleting a folder.\n :param batch_size: Number of items to delete in each batch. Dropbox allows\n batches of up to 1,000 items. Larger values will be capped automatically.\n :returns: List of Metadata for deleted items or SyncErrors for failures. Results\n will be in the same order as the original input.\n ' batch_size = clamp(batch_size, 1, 1000) res_entries = [] result_list: list[((FileMetadata | FolderMetadata) | MaestralApiError)] = [] for chunk in chunks(list(entries), n=batch_size): arg = [files.DeleteArg(e[0], e[1]) for e in chunk] with convert_api_errors(): res = self.dbx.files_delete_batch(arg) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_write_operations(): title = 'Could not delete items' text = 'There are too many write operations happening in your Dropbox. Please try again later.' raise SyncError(title, text) for (i, entry) in enumerate(res_entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text=, user_message_locale=, request_id=) sync_err = dropbox_to_maestral_error(exc, dbx_path=entries[i][0]) result_list.append(sync_err) return result_list
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def remove_batch(self, entries: Sequence[tuple[(str, (str | None))]], batch_size: int=900) -> list[((FileMetadata | FolderMetadata) | MaestralApiError)]: '\n Deletes multiple items on Dropbox in a batch job.\n\n :param entries: List of Dropbox paths and "rev"s to delete. If a "rev" is not\n None, the file will only be deleted if it matches the rev on Dropbox. This\n is not supported when deleting a folder.\n :param batch_size: Number of items to delete in each batch. Dropbox allows\n batches of up to 1,000 items. Larger values will be capped automatically.\n :returns: List of Metadata for deleted items or SyncErrors for failures. Results\n will be in the same order as the original input.\n ' batch_size = clamp(batch_size, 1, 1000) res_entries = [] result_list: list[((FileMetadata | FolderMetadata) | MaestralApiError)] = [] for chunk in chunks(list(entries), n=batch_size): arg = [files.DeleteArg(e[0], e[1]) for e in chunk] with convert_api_errors(): res = self.dbx.files_delete_batch(arg) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) with convert_api_errors(): res = self.dbx.files_delete_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() res_entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_write_operations(): title = 'Could not delete items' text = 'There are too many write operations happening in your Dropbox. Please try again later.' raise SyncError(title, text) for (i, entry) in enumerate(res_entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text=, user_message_locale=, request_id=) sync_err = dropbox_to_maestral_error(exc, dbx_path=entries[i][0]) result_list.append(sync_err) return result_list<|docstring|>Deletes multiple items on Dropbox in a batch job. :param entries: List of Dropbox paths and "rev"s to delete. If a "rev" is not None, the file will only be deleted if it matches the rev on Dropbox. This is not supported when deleting a folder. :param batch_size: Number of items to delete in each batch. Dropbox allows batches of up to 1,000 items. Larger values will be capped automatically. :returns: List of Metadata for deleted items or SyncErrors for failures. Results will be in the same order as the original input.<|endoftext|>
e5f8749f2cc6516cd29e349709ae04989e8a4998b02ce39209264ad1a2112831
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def move(self, dbx_path: str, new_path: str, autorename: bool=False) -> (FileMetadata | FolderMetadata): '\n Moves / renames files or folders on Dropbox.\n\n :param dbx_path: Path to file/folder on Dropbox.\n :param new_path: New path on Dropbox to move to.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of moved item.\n ' with convert_api_errors(dbx_path=new_path): res = self.dbx.files_move_v2(dbx_path, new_path, allow_shared_folder=True, allow_ownership_transfer=True, autorename=autorename) return convert_metadata(res.metadata)
Moves / renames files or folders on Dropbox. :param dbx_path: Path to file/folder on Dropbox. :param new_path: New path on Dropbox to move to. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of moved item.
src/maestral/client.py
move
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def move(self, dbx_path: str, new_path: str, autorename: bool=False) -> (FileMetadata | FolderMetadata): '\n Moves / renames files or folders on Dropbox.\n\n :param dbx_path: Path to file/folder on Dropbox.\n :param new_path: New path on Dropbox to move to.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of moved item.\n ' with convert_api_errors(dbx_path=new_path): res = self.dbx.files_move_v2(dbx_path, new_path, allow_shared_folder=True, allow_ownership_transfer=True, autorename=autorename) return convert_metadata(res.metadata)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def move(self, dbx_path: str, new_path: str, autorename: bool=False) -> (FileMetadata | FolderMetadata): '\n Moves / renames files or folders on Dropbox.\n\n :param dbx_path: Path to file/folder on Dropbox.\n :param new_path: New path on Dropbox to move to.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of moved item.\n ' with convert_api_errors(dbx_path=new_path): res = self.dbx.files_move_v2(dbx_path, new_path, allow_shared_folder=True, allow_ownership_transfer=True, autorename=autorename) return convert_metadata(res.metadata)<|docstring|>Moves / renames files or folders on Dropbox. :param dbx_path: Path to file/folder on Dropbox. :param new_path: New path on Dropbox to move to. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of moved item.<|endoftext|>
b7b90f1ab9ae3a6d4fb51c38f715a5335dbd9d342094fcd03db26d25f2fac8d7
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir(self, dbx_path: str, autorename: bool=False) -> FolderMetadata: '\n Creates a folder on Dropbox.\n\n :param dbx_path: Path of Dropbox folder.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of created folder.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_create_folder_v2(dbx_path, autorename) md = cast(files.FolderMetadata, res.metadata) return convert_metadata(md)
Creates a folder on Dropbox. :param dbx_path: Path of Dropbox folder. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of created folder.
src/maestral/client.py
make_dir
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir(self, dbx_path: str, autorename: bool=False) -> FolderMetadata: '\n Creates a folder on Dropbox.\n\n :param dbx_path: Path of Dropbox folder.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of created folder.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_create_folder_v2(dbx_path, autorename) md = cast(files.FolderMetadata, res.metadata) return convert_metadata(md)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir(self, dbx_path: str, autorename: bool=False) -> FolderMetadata: '\n Creates a folder on Dropbox.\n\n :param dbx_path: Path of Dropbox folder.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :returns: Metadata of created folder.\n ' with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_create_folder_v2(dbx_path, autorename) md = cast(files.FolderMetadata, res.metadata) return convert_metadata(md)<|docstring|>Creates a folder on Dropbox. :param dbx_path: Path of Dropbox folder. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :returns: Metadata of created folder.<|endoftext|>
800de53bd549223441664a8eef0e52b19f8e0839296d07dd38663fadc363a471
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir_batch(self, dbx_paths: list[str], batch_size: int=900, autorename: bool=False, force_async: bool=False) -> list[(FolderMetadata | MaestralApiError)]: '\n Creates multiple folders on Dropbox in a batch job.\n\n :param dbx_paths: List of dropbox folder paths.\n :param batch_size: Number of folders to create in each batch. Dropbox allows\n batches of up to 1,000 folders. Larger values will be capped automatically.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :param force_async: Whether to force asynchronous creation on Dropbox servers.\n :returns: List of Metadata for created folders or SyncError for failures.\n Entries will be in the same order as given paths.\n ' batch_size = clamp(batch_size, 1, 1000) entries = [] result_list: list[(FolderMetadata | MaestralApiError)] = [] with convert_api_errors(): for chunk in chunks(dbx_paths, n=batch_size): res = self.dbx.files_create_folder_batch(chunk, autorename, force_async) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) res = self.dbx.files_create_folder_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) res = self.dbx.files_create_folder_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_files(): res_list = self.make_dir_batch(chunk, round((batch_size / 2)), autorename, force_async) result_list.extend(res_list) for (i, entry) in enumerate(entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text='', user_message_locale='', request_id='') sync_err = dropbox_to_maestral_error(exc, dbx_path=dbx_paths[i]) result_list.append(sync_err) return result_list
Creates multiple folders on Dropbox in a batch job. :param dbx_paths: List of dropbox folder paths. :param batch_size: Number of folders to create in each batch. Dropbox allows batches of up to 1,000 folders. Larger values will be capped automatically. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :param force_async: Whether to force asynchronous creation on Dropbox servers. :returns: List of Metadata for created folders or SyncError for failures. Entries will be in the same order as given paths.
src/maestral/client.py
make_dir_batch
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir_batch(self, dbx_paths: list[str], batch_size: int=900, autorename: bool=False, force_async: bool=False) -> list[(FolderMetadata | MaestralApiError)]: '\n Creates multiple folders on Dropbox in a batch job.\n\n :param dbx_paths: List of dropbox folder paths.\n :param batch_size: Number of folders to create in each batch. Dropbox allows\n batches of up to 1,000 folders. Larger values will be capped automatically.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :param force_async: Whether to force asynchronous creation on Dropbox servers.\n :returns: List of Metadata for created folders or SyncError for failures.\n Entries will be in the same order as given paths.\n ' batch_size = clamp(batch_size, 1, 1000) entries = [] result_list: list[(FolderMetadata | MaestralApiError)] = [] with convert_api_errors(): for chunk in chunks(dbx_paths, n=batch_size): res = self.dbx.files_create_folder_batch(chunk, autorename, force_async) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) res = self.dbx.files_create_folder_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) res = self.dbx.files_create_folder_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_files(): res_list = self.make_dir_batch(chunk, round((batch_size / 2)), autorename, force_async) result_list.extend(res_list) for (i, entry) in enumerate(entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text=, user_message_locale=, request_id=) sync_err = dropbox_to_maestral_error(exc, dbx_path=dbx_paths[i]) result_list.append(sync_err) return result_list
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def make_dir_batch(self, dbx_paths: list[str], batch_size: int=900, autorename: bool=False, force_async: bool=False) -> list[(FolderMetadata | MaestralApiError)]: '\n Creates multiple folders on Dropbox in a batch job.\n\n :param dbx_paths: List of dropbox folder paths.\n :param batch_size: Number of folders to create in each batch. Dropbox allows\n batches of up to 1,000 folders. Larger values will be capped automatically.\n :param autorename: Have the Dropbox server try to rename the item in case of a\n conflict.\n :param force_async: Whether to force asynchronous creation on Dropbox servers.\n :returns: List of Metadata for created folders or SyncError for failures.\n Entries will be in the same order as given paths.\n ' batch_size = clamp(batch_size, 1, 1000) entries = [] result_list: list[(FolderMetadata | MaestralApiError)] = [] with convert_api_errors(): for chunk in chunks(dbx_paths, n=batch_size): res = self.dbx.files_create_folder_batch(chunk, autorename, force_async) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.5) res = self.dbx.files_create_folder_batch_check(async_job_id) check_interval = round((len(chunk) / 100), 1) while res.is_in_progress(): time.sleep(check_interval) res = self.dbx.files_create_folder_batch_check(async_job_id) if res.is_complete(): batch_res = res.get_complete() entries.extend(batch_res.entries) elif res.is_failed(): error = res.get_failed() if error.is_too_many_files(): res_list = self.make_dir_batch(chunk, round((batch_size / 2)), autorename, force_async) result_list.extend(res_list) for (i, entry) in enumerate(entries): if entry.is_success(): result_list.append(convert_metadata(entry.get_success().metadata)) elif entry.is_failure(): exc = exceptions.ApiError(error=entry.get_failure(), user_message_text=, user_message_locale=, request_id=) sync_err = dropbox_to_maestral_error(exc, dbx_path=dbx_paths[i]) result_list.append(sync_err) return result_list<|docstring|>Creates multiple folders on Dropbox in a batch job. :param dbx_paths: List of dropbox folder paths. :param batch_size: Number of folders to create in each batch. Dropbox allows batches of up to 1,000 folders. Larger values will be capped automatically. :param autorename: Have the Dropbox server try to rename the item in case of a conflict. :param force_async: Whether to force asynchronous creation on Dropbox servers. :returns: List of Metadata for created folders or SyncError for failures. Entries will be in the same order as given paths.<|endoftext|>
3a6e4ca6ce7b11c35bc6871c75d7ad6e3c1a87bff3ab7ce6651d82616bab7158
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def share_dir(self, dbx_path: str, **kwargs) -> (FolderMetadata | None): '\n Converts a Dropbox folder to a shared folder. Creates the folder if it does not\n exist. May return None if the folder is immediately deleted after creation.\n\n :param dbx_path: Path of Dropbox folder.\n :param kwargs: Keyword arguments for the Dropbox API sharing/share_folder\n endpoint.\n :returns: Metadata of shared folder.\n ' dbx_path = ('' if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_share_folder(dbx_path, **kwargs) if res.is_complete(): shared_folder_md = res.get_complete() elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) while job_status.is_in_progress(): time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) if job_status.is_complete(): shared_folder_md = job_status.get_complete() elif job_status.is_failed(): error = job_status.get_failed() exc = exceptions.ApiError(error=error, user_message_locale='', user_message_text='', request_id='') raise dropbox_to_maestral_error(exc) else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/check_share_job_status endpoint: {res}.') else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/share_folder endpoint: {res}.') md = self.get_metadata(f'ns:{shared_folder_md.shared_folder_id}') if isinstance(md, FolderMetadata): return md else: return None
Converts a Dropbox folder to a shared folder. Creates the folder if it does not exist. May return None if the folder is immediately deleted after creation. :param dbx_path: Path of Dropbox folder. :param kwargs: Keyword arguments for the Dropbox API sharing/share_folder endpoint. :returns: Metadata of shared folder.
src/maestral/client.py
share_dir
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def share_dir(self, dbx_path: str, **kwargs) -> (FolderMetadata | None): '\n Converts a Dropbox folder to a shared folder. Creates the folder if it does not\n exist. May return None if the folder is immediately deleted after creation.\n\n :param dbx_path: Path of Dropbox folder.\n :param kwargs: Keyword arguments for the Dropbox API sharing/share_folder\n endpoint.\n :returns: Metadata of shared folder.\n ' dbx_path = ( if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_share_folder(dbx_path, **kwargs) if res.is_complete(): shared_folder_md = res.get_complete() elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) while job_status.is_in_progress(): time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) if job_status.is_complete(): shared_folder_md = job_status.get_complete() elif job_status.is_failed(): error = job_status.get_failed() exc = exceptions.ApiError(error=error, user_message_locale=, user_message_text=, request_id=) raise dropbox_to_maestral_error(exc) else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/check_share_job_status endpoint: {res}.') else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/share_folder endpoint: {res}.') md = self.get_metadata(f'ns:{shared_folder_md.shared_folder_id}') if isinstance(md, FolderMetadata): return md else: return None
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def share_dir(self, dbx_path: str, **kwargs) -> (FolderMetadata | None): '\n Converts a Dropbox folder to a shared folder. Creates the folder if it does not\n exist. May return None if the folder is immediately deleted after creation.\n\n :param dbx_path: Path of Dropbox folder.\n :param kwargs: Keyword arguments for the Dropbox API sharing/share_folder\n endpoint.\n :returns: Metadata of shared folder.\n ' dbx_path = ( if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_share_folder(dbx_path, **kwargs) if res.is_complete(): shared_folder_md = res.get_complete() elif res.is_async_job_id(): async_job_id = res.get_async_job_id() time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) while job_status.is_in_progress(): time.sleep(0.2) with convert_api_errors(dbx_path=dbx_path): job_status = self.dbx.sharing_check_share_job_status(async_job_id) if job_status.is_complete(): shared_folder_md = job_status.get_complete() elif job_status.is_failed(): error = job_status.get_failed() exc = exceptions.ApiError(error=error, user_message_locale=, user_message_text=, request_id=) raise dropbox_to_maestral_error(exc) else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/check_share_job_status endpoint: {res}.') else: raise MaestralApiError('Could not create shared folder', f'Unexpected response from sharing/share_folder endpoint: {res}.') md = self.get_metadata(f'ns:{shared_folder_md.shared_folder_id}') if isinstance(md, FolderMetadata): return md else: return None<|docstring|>Converts a Dropbox folder to a shared folder. Creates the folder if it does not exist. May return None if the folder is immediately deleted after creation. :param dbx_path: Path of Dropbox folder. :param kwargs: Keyword arguments for the Dropbox API sharing/share_folder endpoint. :returns: Metadata of shared folder.<|endoftext|>
6e50086bc6eb50381254b429b60f42231f86ea9a7345e62e9fec593d63991220
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_latest_cursor(self, dbx_path: str, include_non_downloadable_files: bool=False, **kwargs) -> str: '\n Gets the latest cursor for the given folder and subfolders.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_non_downloadable_files: If ``True``, files that cannot be\n downloaded (at the moment only G-suite files on Dropbox) will be included.\n :param kwargs: Additional keyword arguments for Dropbox API\n files/list_folder/get_latest_cursor endpoint.\n :returns: The latest cursor representing a state of a folder and its subfolders.\n ' dbx_path = ('' if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_list_folder_get_latest_cursor(dbx_path, include_non_downloadable_files=include_non_downloadable_files, recursive=True, **kwargs) return res.cursor
Gets the latest cursor for the given folder and subfolders. :param dbx_path: Path of folder on Dropbox. :param include_non_downloadable_files: If ``True``, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included. :param kwargs: Additional keyword arguments for Dropbox API files/list_folder/get_latest_cursor endpoint. :returns: The latest cursor representing a state of a folder and its subfolders.
src/maestral/client.py
get_latest_cursor
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_latest_cursor(self, dbx_path: str, include_non_downloadable_files: bool=False, **kwargs) -> str: '\n Gets the latest cursor for the given folder and subfolders.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_non_downloadable_files: If ``True``, files that cannot be\n downloaded (at the moment only G-suite files on Dropbox) will be included.\n :param kwargs: Additional keyword arguments for Dropbox API\n files/list_folder/get_latest_cursor endpoint.\n :returns: The latest cursor representing a state of a folder and its subfolders.\n ' dbx_path = ( if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_list_folder_get_latest_cursor(dbx_path, include_non_downloadable_files=include_non_downloadable_files, recursive=True, **kwargs) return res.cursor
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def get_latest_cursor(self, dbx_path: str, include_non_downloadable_files: bool=False, **kwargs) -> str: '\n Gets the latest cursor for the given folder and subfolders.\n\n :param dbx_path: Path of folder on Dropbox.\n :param include_non_downloadable_files: If ``True``, files that cannot be\n downloaded (at the moment only G-suite files on Dropbox) will be included.\n :param kwargs: Additional keyword arguments for Dropbox API\n files/list_folder/get_latest_cursor endpoint.\n :returns: The latest cursor representing a state of a folder and its subfolders.\n ' dbx_path = ( if (dbx_path == '/') else dbx_path) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_list_folder_get_latest_cursor(dbx_path, include_non_downloadable_files=include_non_downloadable_files, recursive=True, **kwargs) return res.cursor<|docstring|>Gets the latest cursor for the given folder and subfolders. :param dbx_path: Path of folder on Dropbox. :param include_non_downloadable_files: If ``True``, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included. :param kwargs: Additional keyword arguments for Dropbox API files/list_folder/get_latest_cursor endpoint. :returns: The latest cursor representing a state of a folder and its subfolders.<|endoftext|>
68cda85c9e0157b8b648488bf93187a99f0256820a117e9cabca2a0498a6f105
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, include_non_downloadable_files: bool=False) -> ListFolderResult: '\n Lists the contents of a folder on Dropbox. Similar to\n :meth:`list_folder_iterator` but returns all entries in a single\n :class:`core.ListFolderResult` instance.\n\n :param dbx_path: Path of folder on Dropbox.\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Content of given folder.\n ' iterator = self.list_folder_iterator(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, include_non_downloadable_files=include_non_downloadable_files) return self.flatten_results(list(iterator))
Lists the contents of a folder on Dropbox. Similar to :meth:`list_folder_iterator` but returns all entries in a single :class:`core.ListFolderResult` instance. :param dbx_path: Path of folder on Dropbox. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Content of given folder.
src/maestral/client.py
list_folder
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, include_non_downloadable_files: bool=False) -> ListFolderResult: '\n Lists the contents of a folder on Dropbox. Similar to\n :meth:`list_folder_iterator` but returns all entries in a single\n :class:`core.ListFolderResult` instance.\n\n :param dbx_path: Path of folder on Dropbox.\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Content of given folder.\n ' iterator = self.list_folder_iterator(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, include_non_downloadable_files=include_non_downloadable_files) return self.flatten_results(list(iterator))
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, include_non_downloadable_files: bool=False) -> ListFolderResult: '\n Lists the contents of a folder on Dropbox. Similar to\n :meth:`list_folder_iterator` but returns all entries in a single\n :class:`core.ListFolderResult` instance.\n\n :param dbx_path: Path of folder on Dropbox.\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Content of given folder.\n ' iterator = self.list_folder_iterator(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, include_non_downloadable_files=include_non_downloadable_files) return self.flatten_results(list(iterator))<|docstring|>Lists the contents of a folder on Dropbox. Similar to :meth:`list_folder_iterator` but returns all entries in a single :class:`core.ListFolderResult` instance. :param dbx_path: Path of folder on Dropbox. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Content of given folder.<|endoftext|>
f2ac19abdbbe0d107e9f93531d4a0747e26cc2b3c0ae1e72dbad08ac81687413
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder_iterator(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, limit: (int | None)=None, include_non_downloadable_files: bool=False) -> Iterator[ListFolderResult]: '\n Lists the contents of a folder on Dropbox. Returns an iterator yielding\n :class:`core.ListFolderResult` instances. The number of entries\n returned in each iteration corresponds to the number of entries returned by a\n single Dropbox API call and will be typically around 500.\n\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param Nullable[int] limit: The maximum number of results to return per\n request. Note: This is an approximate number and there can be\n slightly more entries returned in some cases.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Iterator over content of given folder.\n ' with convert_api_errors(dbx_path): dbx_path = ('' if (dbx_path == '/') else dbx_path) res = self.dbx.files_list_folder(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, limit=limit, include_non_downloadable_files=include_non_downloadable_files) (yield convert_list_folder_result(res)) while res.has_more: res = self._list_folder_continue_helper(res.cursor) (yield convert_list_folder_result(res))
Lists the contents of a folder on Dropbox. Returns an iterator yielding :class:`core.ListFolderResult` instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param Nullable[int] limit: The maximum number of results to return per request. Note: This is an approximate number and there can be slightly more entries returned in some cases. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Iterator over content of given folder.
src/maestral/client.py
list_folder_iterator
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder_iterator(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, limit: (int | None)=None, include_non_downloadable_files: bool=False) -> Iterator[ListFolderResult]: '\n Lists the contents of a folder on Dropbox. Returns an iterator yielding\n :class:`core.ListFolderResult` instances. The number of entries\n returned in each iteration corresponds to the number of entries returned by a\n single Dropbox API call and will be typically around 500.\n\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param Nullable[int] limit: The maximum number of results to return per\n request. Note: This is an approximate number and there can be\n slightly more entries returned in some cases.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Iterator over content of given folder.\n ' with convert_api_errors(dbx_path): dbx_path = ( if (dbx_path == '/') else dbx_path) res = self.dbx.files_list_folder(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, limit=limit, include_non_downloadable_files=include_non_downloadable_files) (yield convert_list_folder_result(res)) while res.has_more: res = self._list_folder_continue_helper(res.cursor) (yield convert_list_folder_result(res))
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_folder_iterator(self, dbx_path: str, recursive: bool=False, include_deleted: bool=False, include_mounted_folders: bool=True, limit: (int | None)=None, include_non_downloadable_files: bool=False) -> Iterator[ListFolderResult]: '\n Lists the contents of a folder on Dropbox. Returns an iterator yielding\n :class:`core.ListFolderResult` instances. The number of entries\n returned in each iteration corresponds to the number of entries returned by a\n single Dropbox API call and will be typically around 500.\n\n :param dbx_path: Path of folder on Dropbox.\n :param recursive: If true, the list folder operation will be applied recursively\n to all subfolders and the response will contain contents of all subfolders.\n :param include_deleted: If true, the results will include entries for files and\n folders that used to exist but were deleted.\n :param bool include_mounted_folders: If true, the results will include\n entries under mounted folders which includes app folder, shared\n folder and team folder.\n :param Nullable[int] limit: The maximum number of results to return per\n request. Note: This is an approximate number and there can be\n slightly more entries returned in some cases.\n :param bool include_non_downloadable_files: If true, include files that\n are not downloadable, i.e. Google Docs.\n :returns: Iterator over content of given folder.\n ' with convert_api_errors(dbx_path): dbx_path = ( if (dbx_path == '/') else dbx_path) res = self.dbx.files_list_folder(dbx_path, recursive=recursive, include_deleted=include_deleted, include_mounted_folders=include_mounted_folders, limit=limit, include_non_downloadable_files=include_non_downloadable_files) (yield convert_list_folder_result(res)) while res.has_more: res = self._list_folder_continue_helper(res.cursor) (yield convert_list_folder_result(res))<|docstring|>Lists the contents of a folder on Dropbox. Returns an iterator yielding :class:`core.ListFolderResult` instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500. :param dbx_path: Path of folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param Nullable[int] limit: The maximum number of results to return per request. Note: This is an approximate number and there can be slightly more entries returned in some cases. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Iterator over content of given folder.<|endoftext|>
7ac650aec4b1537dad27a93823bf789795c3b57d53de5d6783281584e288cb86
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def wait_for_remote_changes(self, last_cursor: str, timeout: int=40) -> bool: '\n Waits for remote changes since ``last_cursor``. Call this method after\n starting the Dropbox client and periodically to get the latest updates.\n\n :param last_cursor: Last to cursor to compare for changes.\n :param timeout: Seconds to wait until timeout. Must be between 30 and 480. The\n Dropbox API will add a random jitter of up to 60 sec to this value.\n :returns: ``True`` if changes are available, ``False`` otherwise.\n ' if (not (30 <= timeout <= 480)): raise ValueError('Timeout must be in range [30, 480]') time_to_backoff = max((self._backoff_until - time.time()), 0) time.sleep(time_to_backoff) with convert_api_errors(): res = self.dbx.files_list_folder_longpoll(last_cursor, timeout=timeout) if res.backoff: self._logger.debug('Backoff requested for %s sec', res.backoff) self._backoff_until = ((time.time() + res.backoff) + 5.0) else: self._backoff_until = 0 return res.changes
Waits for remote changes since ``last_cursor``. Call this method after starting the Dropbox client and periodically to get the latest updates. :param last_cursor: Last to cursor to compare for changes. :param timeout: Seconds to wait until timeout. Must be between 30 and 480. The Dropbox API will add a random jitter of up to 60 sec to this value. :returns: ``True`` if changes are available, ``False`` otherwise.
src/maestral/client.py
wait_for_remote_changes
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def wait_for_remote_changes(self, last_cursor: str, timeout: int=40) -> bool: '\n Waits for remote changes since ``last_cursor``. Call this method after\n starting the Dropbox client and periodically to get the latest updates.\n\n :param last_cursor: Last to cursor to compare for changes.\n :param timeout: Seconds to wait until timeout. Must be between 30 and 480. The\n Dropbox API will add a random jitter of up to 60 sec to this value.\n :returns: ``True`` if changes are available, ``False`` otherwise.\n ' if (not (30 <= timeout <= 480)): raise ValueError('Timeout must be in range [30, 480]') time_to_backoff = max((self._backoff_until - time.time()), 0) time.sleep(time_to_backoff) with convert_api_errors(): res = self.dbx.files_list_folder_longpoll(last_cursor, timeout=timeout) if res.backoff: self._logger.debug('Backoff requested for %s sec', res.backoff) self._backoff_until = ((time.time() + res.backoff) + 5.0) else: self._backoff_until = 0 return res.changes
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def wait_for_remote_changes(self, last_cursor: str, timeout: int=40) -> bool: '\n Waits for remote changes since ``last_cursor``. Call this method after\n starting the Dropbox client and periodically to get the latest updates.\n\n :param last_cursor: Last to cursor to compare for changes.\n :param timeout: Seconds to wait until timeout. Must be between 30 and 480. The\n Dropbox API will add a random jitter of up to 60 sec to this value.\n :returns: ``True`` if changes are available, ``False`` otherwise.\n ' if (not (30 <= timeout <= 480)): raise ValueError('Timeout must be in range [30, 480]') time_to_backoff = max((self._backoff_until - time.time()), 0) time.sleep(time_to_backoff) with convert_api_errors(): res = self.dbx.files_list_folder_longpoll(last_cursor, timeout=timeout) if res.backoff: self._logger.debug('Backoff requested for %s sec', res.backoff) self._backoff_until = ((time.time() + res.backoff) + 5.0) else: self._backoff_until = 0 return res.changes<|docstring|>Waits for remote changes since ``last_cursor``. Call this method after starting the Dropbox client and periodically to get the latest updates. :param last_cursor: Last to cursor to compare for changes. :param timeout: Seconds to wait until timeout. Must be between 30 and 480. The Dropbox API will add a random jitter of up to 60 sec to this value. :returns: ``True`` if changes are available, ``False`` otherwise.<|endoftext|>
e6145aea0fdc0855fee5e899667e6fafd7d49694317e516f4de3c220dc9a5a76
def list_remote_changes(self, last_cursor: str) -> ListFolderResult: '\n Lists changes to remote Dropbox since ``last_cursor``. Same as\n :meth:`list_remote_changes_iterator` but fetches all changes first and returns\n a single :class:`core.ListFolderResult`. This may be useful if you want\n to fetch all changes in advance before starting to process them.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Remote changes since given cursor.\n ' iterator = self.list_remote_changes_iterator(last_cursor) return self.flatten_results(list(iterator))
Lists changes to remote Dropbox since ``last_cursor``. Same as :meth:`list_remote_changes_iterator` but fetches all changes first and returns a single :class:`core.ListFolderResult`. This may be useful if you want to fetch all changes in advance before starting to process them. :param last_cursor: Last to cursor to compare for changes. :returns: Remote changes since given cursor.
src/maestral/client.py
list_remote_changes
samschott/maestral
436
python
def list_remote_changes(self, last_cursor: str) -> ListFolderResult: '\n Lists changes to remote Dropbox since ``last_cursor``. Same as\n :meth:`list_remote_changes_iterator` but fetches all changes first and returns\n a single :class:`core.ListFolderResult`. This may be useful if you want\n to fetch all changes in advance before starting to process them.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Remote changes since given cursor.\n ' iterator = self.list_remote_changes_iterator(last_cursor) return self.flatten_results(list(iterator))
def list_remote_changes(self, last_cursor: str) -> ListFolderResult: '\n Lists changes to remote Dropbox since ``last_cursor``. Same as\n :meth:`list_remote_changes_iterator` but fetches all changes first and returns\n a single :class:`core.ListFolderResult`. This may be useful if you want\n to fetch all changes in advance before starting to process them.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Remote changes since given cursor.\n ' iterator = self.list_remote_changes_iterator(last_cursor) return self.flatten_results(list(iterator))<|docstring|>Lists changes to remote Dropbox since ``last_cursor``. Same as :meth:`list_remote_changes_iterator` but fetches all changes first and returns a single :class:`core.ListFolderResult`. This may be useful if you want to fetch all changes in advance before starting to process them. :param last_cursor: Last to cursor to compare for changes. :returns: Remote changes since given cursor.<|endoftext|>
f3289b938abac3dc8df4148af5b959523aab5552ae315f26c76fc2b52eff84ce
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_remote_changes_iterator(self, last_cursor: str) -> Iterator[ListFolderResult]: '\n Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator\n yielding :class:`core.ListFolderResult` instances. The number of\n entries returned in each iteration corresponds to the number of entries returned\n by a single Dropbox API call and will be typically around 500.\n\n Call this after :meth:`wait_for_remote_changes` returns ``True``.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Iterator over remote changes since given cursor.\n ' with convert_api_errors(): res = self.dbx.files_list_folder_continue(last_cursor) (yield convert_list_folder_result(res)) while res.has_more: res = self.dbx.files_list_folder_continue(res.cursor) (yield convert_list_folder_result(res))
Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator yielding :class:`core.ListFolderResult` instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500. Call this after :meth:`wait_for_remote_changes` returns ``True``. :param last_cursor: Last to cursor to compare for changes. :returns: Iterator over remote changes since given cursor.
src/maestral/client.py
list_remote_changes_iterator
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_remote_changes_iterator(self, last_cursor: str) -> Iterator[ListFolderResult]: '\n Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator\n yielding :class:`core.ListFolderResult` instances. The number of\n entries returned in each iteration corresponds to the number of entries returned\n by a single Dropbox API call and will be typically around 500.\n\n Call this after :meth:`wait_for_remote_changes` returns ``True``.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Iterator over remote changes since given cursor.\n ' with convert_api_errors(): res = self.dbx.files_list_folder_continue(last_cursor) (yield convert_list_folder_result(res)) while res.has_more: res = self.dbx.files_list_folder_continue(res.cursor) (yield convert_list_folder_result(res))
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_remote_changes_iterator(self, last_cursor: str) -> Iterator[ListFolderResult]: '\n Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator\n yielding :class:`core.ListFolderResult` instances. The number of\n entries returned in each iteration corresponds to the number of entries returned\n by a single Dropbox API call and will be typically around 500.\n\n Call this after :meth:`wait_for_remote_changes` returns ``True``.\n\n :param last_cursor: Last to cursor to compare for changes.\n :returns: Iterator over remote changes since given cursor.\n ' with convert_api_errors(): res = self.dbx.files_list_folder_continue(last_cursor) (yield convert_list_folder_result(res)) while res.has_more: res = self.dbx.files_list_folder_continue(res.cursor) (yield convert_list_folder_result(res))<|docstring|>Lists changes to the remote Dropbox since ``last_cursor``. Returns an iterator yielding :class:`core.ListFolderResult` instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500. Call this after :meth:`wait_for_remote_changes` returns ``True``. :param last_cursor: Last to cursor to compare for changes. :returns: Iterator over remote changes since given cursor.<|endoftext|>
457173e7bc39d35a948c5f2402b4f110619fe049a85a6f01dd2d0f255d9bafca
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def create_shared_link(self, dbx_path: str, visibility: LinkAudience=LinkAudience.Public, access_level: LinkAccessLevel=LinkAccessLevel.Viewer, allow_download: (bool | None)=None, password: (str | None)=None, expires: (datetime | None)=None) -> SharedLinkMetadata: '\n Creates a shared link for the given path. Some options are only available for\n Professional and Business accounts. Note that the requested visibility and\n access level for the link may not be granted, depending on the Dropbox folder or\n team settings. Check the returned link metadata to verify the visibility and\n access level.\n\n :param dbx_path: Dropbox path to file or folder to share.\n :param visibility: The visibility of the shared link. Can be public, team-only,\n or no-one. In case of the latter, the link merely points the user to the\n content and does not grant additional rights to the user. Users of this link\n can only access the content with their pre-existing access rights.\n :param access_level: The level of access granted with the link. Can be viewer,\n editor, or max for maximum possible access level.\n :param allow_download: Whether to allow download capabilities for the link.\n :param password: If given, enables password protection for the link.\n :param expires: Expiry time for shared link. If no timezone is given, assume\n UTC. May not be supported for all account types.\n :returns: Metadata for shared link.\n ' if (expires is not None): has_timezone = (expires.tzinfo and expires.tzinfo.utcoffset(expires)) if has_timezone: expires.astimezone(timezone.utc) settings = sharing.SharedLinkSettings(require_password=(password is not None), link_password=password, expires=expires, audience=sharing.LinkAudience(visibility.value), access=sharing.RequestedLinkAccessLevel(access_level.value), allow_download=allow_download) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_create_shared_link_with_settings(dbx_path, settings) return convert_shared_link_metadata(res)
Creates a shared link for the given path. Some options are only available for Professional and Business accounts. Note that the requested visibility and access level for the link may not be granted, depending on the Dropbox folder or team settings. Check the returned link metadata to verify the visibility and access level. :param dbx_path: Dropbox path to file or folder to share. :param visibility: The visibility of the shared link. Can be public, team-only, or no-one. In case of the latter, the link merely points the user to the content and does not grant additional rights to the user. Users of this link can only access the content with their pre-existing access rights. :param access_level: The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level. :param allow_download: Whether to allow download capabilities for the link. :param password: If given, enables password protection for the link. :param expires: Expiry time for shared link. If no timezone is given, assume UTC. May not be supported for all account types. :returns: Metadata for shared link.
src/maestral/client.py
create_shared_link
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def create_shared_link(self, dbx_path: str, visibility: LinkAudience=LinkAudience.Public, access_level: LinkAccessLevel=LinkAccessLevel.Viewer, allow_download: (bool | None)=None, password: (str | None)=None, expires: (datetime | None)=None) -> SharedLinkMetadata: '\n Creates a shared link for the given path. Some options are only available for\n Professional and Business accounts. Note that the requested visibility and\n access level for the link may not be granted, depending on the Dropbox folder or\n team settings. Check the returned link metadata to verify the visibility and\n access level.\n\n :param dbx_path: Dropbox path to file or folder to share.\n :param visibility: The visibility of the shared link. Can be public, team-only,\n or no-one. In case of the latter, the link merely points the user to the\n content and does not grant additional rights to the user. Users of this link\n can only access the content with their pre-existing access rights.\n :param access_level: The level of access granted with the link. Can be viewer,\n editor, or max for maximum possible access level.\n :param allow_download: Whether to allow download capabilities for the link.\n :param password: If given, enables password protection for the link.\n :param expires: Expiry time for shared link. If no timezone is given, assume\n UTC. May not be supported for all account types.\n :returns: Metadata for shared link.\n ' if (expires is not None): has_timezone = (expires.tzinfo and expires.tzinfo.utcoffset(expires)) if has_timezone: expires.astimezone(timezone.utc) settings = sharing.SharedLinkSettings(require_password=(password is not None), link_password=password, expires=expires, audience=sharing.LinkAudience(visibility.value), access=sharing.RequestedLinkAccessLevel(access_level.value), allow_download=allow_download) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_create_shared_link_with_settings(dbx_path, settings) return convert_shared_link_metadata(res)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def create_shared_link(self, dbx_path: str, visibility: LinkAudience=LinkAudience.Public, access_level: LinkAccessLevel=LinkAccessLevel.Viewer, allow_download: (bool | None)=None, password: (str | None)=None, expires: (datetime | None)=None) -> SharedLinkMetadata: '\n Creates a shared link for the given path. Some options are only available for\n Professional and Business accounts. Note that the requested visibility and\n access level for the link may not be granted, depending on the Dropbox folder or\n team settings. Check the returned link metadata to verify the visibility and\n access level.\n\n :param dbx_path: Dropbox path to file or folder to share.\n :param visibility: The visibility of the shared link. Can be public, team-only,\n or no-one. In case of the latter, the link merely points the user to the\n content and does not grant additional rights to the user. Users of this link\n can only access the content with their pre-existing access rights.\n :param access_level: The level of access granted with the link. Can be viewer,\n editor, or max for maximum possible access level.\n :param allow_download: Whether to allow download capabilities for the link.\n :param password: If given, enables password protection for the link.\n :param expires: Expiry time for shared link. If no timezone is given, assume\n UTC. May not be supported for all account types.\n :returns: Metadata for shared link.\n ' if (expires is not None): has_timezone = (expires.tzinfo and expires.tzinfo.utcoffset(expires)) if has_timezone: expires.astimezone(timezone.utc) settings = sharing.SharedLinkSettings(require_password=(password is not None), link_password=password, expires=expires, audience=sharing.LinkAudience(visibility.value), access=sharing.RequestedLinkAccessLevel(access_level.value), allow_download=allow_download) with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_create_shared_link_with_settings(dbx_path, settings) return convert_shared_link_metadata(res)<|docstring|>Creates a shared link for the given path. Some options are only available for Professional and Business accounts. Note that the requested visibility and access level for the link may not be granted, depending on the Dropbox folder or team settings. Check the returned link metadata to verify the visibility and access level. :param dbx_path: Dropbox path to file or folder to share. :param visibility: The visibility of the shared link. Can be public, team-only, or no-one. In case of the latter, the link merely points the user to the content and does not grant additional rights to the user. Users of this link can only access the content with their pre-existing access rights. :param access_level: The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level. :param allow_download: Whether to allow download capabilities for the link. :param password: If given, enables password protection for the link. :param expires: Expiry time for shared link. If no timezone is given, assume UTC. May not be supported for all account types. :returns: Metadata for shared link.<|endoftext|>
165f9ce0ef39ab959c319310180bd0ad0d3dae12721cf1cfdcc3d6a58a4c610b
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def revoke_shared_link(self, url: str) -> None: '\n Revokes a shared link.\n\n :param url: URL to revoke.\n ' with convert_api_errors(): self.dbx.sharing_revoke_shared_link(url)
Revokes a shared link. :param url: URL to revoke.
src/maestral/client.py
revoke_shared_link
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def revoke_shared_link(self, url: str) -> None: '\n Revokes a shared link.\n\n :param url: URL to revoke.\n ' with convert_api_errors(): self.dbx.sharing_revoke_shared_link(url)
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def revoke_shared_link(self, url: str) -> None: '\n Revokes a shared link.\n\n :param url: URL to revoke.\n ' with convert_api_errors(): self.dbx.sharing_revoke_shared_link(url)<|docstring|>Revokes a shared link. :param url: URL to revoke.<|endoftext|>
9b73a58001ffe0d12907451fa15c80f17e13ac2b86b4e6bbc3de7f779f123d58
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_shared_links(self, dbx_path: (str | None)=None) -> list[SharedLinkMetadata]: '\n Lists all shared links for a given Dropbox path (file or folder). If no path is\n given, list all shared links for the account, up to a maximum of 1,000 links.\n\n :param dbx_path: Dropbox path to file or folder.\n :returns: Shared links for a path, including any shared links for parents\n through which this path is accessible.\n ' results = [] with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_list_shared_links(dbx_path) results.append(convert_list_shared_link_result(res)) while results[(- 1)].has_more: res = self.dbx.sharing_list_shared_links(dbx_path, results[(- 1)].cursor) results.append(convert_list_shared_link_result(res)) return self.flatten_results(results).entries
Lists all shared links for a given Dropbox path (file or folder). If no path is given, list all shared links for the account, up to a maximum of 1,000 links. :param dbx_path: Dropbox path to file or folder. :returns: Shared links for a path, including any shared links for parents through which this path is accessible.
src/maestral/client.py
list_shared_links
samschott/maestral
436
python
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_shared_links(self, dbx_path: (str | None)=None) -> list[SharedLinkMetadata]: '\n Lists all shared links for a given Dropbox path (file or folder). If no path is\n given, list all shared links for the account, up to a maximum of 1,000 links.\n\n :param dbx_path: Dropbox path to file or folder.\n :returns: Shared links for a path, including any shared links for parents\n through which this path is accessible.\n ' results = [] with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_list_shared_links(dbx_path) results.append(convert_list_shared_link_result(res)) while results[(- 1)].has_more: res = self.dbx.sharing_list_shared_links(dbx_path, results[(- 1)].cursor) results.append(convert_list_shared_link_result(res)) return self.flatten_results(results).entries
@_retry_on_error(BadInputError, max_retries=5, backoff=2, msg_regex='v1_retired') def list_shared_links(self, dbx_path: (str | None)=None) -> list[SharedLinkMetadata]: '\n Lists all shared links for a given Dropbox path (file or folder). If no path is\n given, list all shared links for the account, up to a maximum of 1,000 links.\n\n :param dbx_path: Dropbox path to file or folder.\n :returns: Shared links for a path, including any shared links for parents\n through which this path is accessible.\n ' results = [] with convert_api_errors(dbx_path=dbx_path): res = self.dbx.sharing_list_shared_links(dbx_path) results.append(convert_list_shared_link_result(res)) while results[(- 1)].has_more: res = self.dbx.sharing_list_shared_links(dbx_path, results[(- 1)].cursor) results.append(convert_list_shared_link_result(res)) return self.flatten_results(results).entries<|docstring|>Lists all shared links for a given Dropbox path (file or folder). If no path is given, list all shared links for the account, up to a maximum of 1,000 links. :param dbx_path: Dropbox path to file or folder. :returns: Shared links for a path, including any shared links for parents through which this path is accessible.<|endoftext|>
587014bdd1ab25abc26dff00047da68c756d4c4e78a1f6e268dc90a64cc47fa6
@staticmethod def flatten_results(results: list[PRT]) -> PRT: '\n Flattens a sequence listing results from a pagination to a single result with\n the cursor of the last result in the list.\n\n :param results: List of results to flatten.\n :returns: Flattened result.\n ' all_entries = [entry for res in results for entry in res.entries] result_cls = type(results[0]) return result_cls(entries=all_entries, has_more=False, cursor=results[(- 1)].cursor)
Flattens a sequence listing results from a pagination to a single result with the cursor of the last result in the list. :param results: List of results to flatten. :returns: Flattened result.
src/maestral/client.py
flatten_results
samschott/maestral
436
python
@staticmethod def flatten_results(results: list[PRT]) -> PRT: '\n Flattens a sequence listing results from a pagination to a single result with\n the cursor of the last result in the list.\n\n :param results: List of results to flatten.\n :returns: Flattened result.\n ' all_entries = [entry for res in results for entry in res.entries] result_cls = type(results[0]) return result_cls(entries=all_entries, has_more=False, cursor=results[(- 1)].cursor)
@staticmethod def flatten_results(results: list[PRT]) -> PRT: '\n Flattens a sequence listing results from a pagination to a single result with\n the cursor of the last result in the list.\n\n :param results: List of results to flatten.\n :returns: Flattened result.\n ' all_entries = [entry for res in results for entry in res.entries] result_cls = type(results[0]) return result_cls(entries=all_entries, has_more=False, cursor=results[(- 1)].cursor)<|docstring|>Flattens a sequence listing results from a pagination to a single result with the cursor of the last result in the list. :param results: List of results to flatten. :returns: Flattened result.<|endoftext|>
4140fe32667564e07ec7641a3f45b5d41c9935ce10fde92462a0c561ff086312
def is_multiple_32(x): 'multiple of 32 ' try: return (isinstance(int(x), numbers.Integral) and (not isinstance(x, bool)) and ((int(x) % 32) == 0)) except ValueError: return False
multiple of 32
var/spack/repos/builtin/packages/abyss/package.py
is_multiple_32
qoelet/spack
2,360
python
def is_multiple_32(x): ' ' try: return (isinstance(int(x), numbers.Integral) and (not isinstance(x, bool)) and ((int(x) % 32) == 0)) except ValueError: return False
def is_multiple_32(x): ' ' try: return (isinstance(int(x), numbers.Integral) and (not isinstance(x, bool)) and ((int(x) % 32) == 0)) except ValueError: return False<|docstring|>multiple of 32<|endoftext|>
0b0eec1de7faf34e94079137ba1eac487b36099c590ca0bd66528c238df375ba
def on_game_draw(self, player, cards): '\n Opponent drew cards.\n ' self.animating = True self.child_top(self.opponents[player.id]) self.opponents[player.id].animate_draw(cards, on_complete=self.animation_complete)
Opponent drew cards.
sciibo/scenes/game.py
on_game_draw
fdev/sciibo
14
python
def on_game_draw(self, player, cards): '\n \n ' self.animating = True self.child_top(self.opponents[player.id]) self.opponents[player.id].animate_draw(cards, on_complete=self.animation_complete)
def on_game_draw(self, player, cards): '\n \n ' self.animating = True self.child_top(self.opponents[player.id]) self.opponents[player.id].animate_draw(cards, on_complete=self.animation_complete)<|docstring|>Opponent drew cards.<|endoftext|>
9c1b39cc2669aa41ac64e03d3951bc7d33b37bed9129adcae02977b095fc463d
def on_game_hand(self, cards): '\n Player received hand cards.\n ' self.animating = True self.playfield.animate_hand(cards, on_complete=self.animation_complete)
Player received hand cards.
sciibo/scenes/game.py
on_game_hand
fdev/sciibo
14
python
def on_game_hand(self, cards): '\n \n ' self.animating = True self.playfield.animate_hand(cards, on_complete=self.animation_complete)
def on_game_hand(self, cards): '\n \n ' self.animating = True self.playfield.animate_hand(cards, on_complete=self.animation_complete)<|docstring|>Player received hand cards.<|endoftext|>
81b0bde7cdf1d6b587ddff803ecd3ecb3dde55646600732aa3d3f1a9181722ef
def on_game_turn(self, player): '\n Turn change.\n ' if (player.id == self.game.player_id): self.playfield.activate() else: self.child_top(self.opponents[player.id]) self.playfield.deactivate() self.update_statusbar()
Turn change.
sciibo/scenes/game.py
on_game_turn
fdev/sciibo
14
python
def on_game_turn(self, player): '\n \n ' if (player.id == self.game.player_id): self.playfield.activate() else: self.child_top(self.opponents[player.id]) self.playfield.deactivate() self.update_statusbar()
def on_game_turn(self, player): '\n \n ' if (player.id == self.game.player_id): self.playfield.activate() else: self.child_top(self.opponents[player.id]) self.playfield.deactivate() self.update_statusbar()<|docstring|>Turn change.<|endoftext|>
418ac6e94ff67a0b2ed1d763004ff51829e9ec4ff51a92e462bd87c67526f0ad
def on_game_invalid(self): '\n Invalid move was made, try again.\n ' self.playfield.activate(reset=False) self.update_statusbar() self.alerts.error('That card can not be placed here.')
Invalid move was made, try again.
sciibo/scenes/game.py
on_game_invalid
fdev/sciibo
14
python
def on_game_invalid(self): '\n \n ' self.playfield.activate(reset=False) self.update_statusbar() self.alerts.error('That card can not be placed here.')
def on_game_invalid(self): '\n \n ' self.playfield.activate(reset=False) self.update_statusbar() self.alerts.error('That card can not be placed here.')<|docstring|>Invalid move was made, try again.<|endoftext|>
b5bbaf7a3da3fc12d1e6b976771d9ab5bbcc8e9b043c353f77ff1fa3feb99017
def on_game_play(self, player, value, source, target, reveal): '\n Player moves around cards.\n ' if (player.id != self.game.player_id): def animation_complete(): self.playfield.update() self.animation_complete() self.animating = True self.opponents[player.id].animate_play(value, source, target, reveal, self.game.build_piles, on_complete=animation_complete) else: self.statusbar.text = '' self.statusbar.update() self.animating = True self.playfield.animate_play(value, source, target, reveal, on_complete=self.animation_complete)
Player moves around cards.
sciibo/scenes/game.py
on_game_play
fdev/sciibo
14
python
def on_game_play(self, player, value, source, target, reveal): '\n \n ' if (player.id != self.game.player_id): def animation_complete(): self.playfield.update() self.animation_complete() self.animating = True self.opponents[player.id].animate_play(value, source, target, reveal, self.game.build_piles, on_complete=animation_complete) else: self.statusbar.text = self.statusbar.update() self.animating = True self.playfield.animate_play(value, source, target, reveal, on_complete=self.animation_complete)
def on_game_play(self, player, value, source, target, reveal): '\n \n ' if (player.id != self.game.player_id): def animation_complete(): self.playfield.update() self.animation_complete() self.animating = True self.opponents[player.id].animate_play(value, source, target, reveal, self.game.build_piles, on_complete=animation_complete) else: self.statusbar.text = self.statusbar.update() self.animating = True self.playfield.animate_play(value, source, target, reveal, on_complete=self.animation_complete)<|docstring|>Player moves around cards.<|endoftext|>
8c5486bada484e2903993de7c5a94c23df5df12ed26d2c94eef522e5ed45589d
def on_game_end(self, winner): '\n Game ends.\n ' self.update_statusbar() if winner: if (winner.id == self.game.player_id): alert_text = 'You won the game, congratulations!' else: alert_text = ('%s won the game, better luck next time.' % winner.name) else: alert_text = 'The game has ended.' self.alerts.alert(alert_text, buttons=['Leave game'], on_dismiss=self.on_alert_end)
Game ends.
sciibo/scenes/game.py
on_game_end
fdev/sciibo
14
python
def on_game_end(self, winner): '\n \n ' self.update_statusbar() if winner: if (winner.id == self.game.player_id): alert_text = 'You won the game, congratulations!' else: alert_text = ('%s won the game, better luck next time.' % winner.name) else: alert_text = 'The game has ended.' self.alerts.alert(alert_text, buttons=['Leave game'], on_dismiss=self.on_alert_end)
def on_game_end(self, winner): '\n \n ' self.update_statusbar() if winner: if (winner.id == self.game.player_id): alert_text = 'You won the game, congratulations!' else: alert_text = ('%s won the game, better luck next time.' % winner.name) else: alert_text = 'The game has ended.' self.alerts.alert(alert_text, buttons=['Leave game'], on_dismiss=self.on_alert_end)<|docstring|>Game ends.<|endoftext|>
ffb0466f9459ad9c4055158e2b0367c9d59222a1cfb91df5008bffa6c21341c5
def on_game_leave(self, player): '\n Opponent left.\n ' self.animating = True self.opponents[player.id].update() alert = TimedAlert(Alert(('%s left the game.' % player.name), type='error'), on_complete=self.animation_complete) self.add_child(alert)
Opponent left.
sciibo/scenes/game.py
on_game_leave
fdev/sciibo
14
python
def on_game_leave(self, player): '\n \n ' self.animating = True self.opponents[player.id].update() alert = TimedAlert(Alert(('%s left the game.' % player.name), type='error'), on_complete=self.animation_complete) self.add_child(alert)
def on_game_leave(self, player): '\n \n ' self.animating = True self.opponents[player.id].update() alert = TimedAlert(Alert(('%s left the game.' % player.name), type='error'), on_complete=self.animation_complete) self.add_child(alert)<|docstring|>Opponent left.<|endoftext|>
c72a94082f61221d7d1c1972f21898f975f391484bd93fe37436b75fcde1edcc
def on_game_disconnect(self): '\n Disconnected from server.\n ' self.update_statusbar() self.alerts.error('The connection to the server was lost.', on_dismiss=self.on_alert_end)
Disconnected from server.
sciibo/scenes/game.py
on_game_disconnect
fdev/sciibo
14
python
def on_game_disconnect(self): '\n \n ' self.update_statusbar() self.alerts.error('The connection to the server was lost.', on_dismiss=self.on_alert_end)
def on_game_disconnect(self): '\n \n ' self.update_statusbar() self.alerts.error('The connection to the server was lost.', on_dismiss=self.on_alert_end)<|docstring|>Disconnected from server.<|endoftext|>
7c432f54e96fe77304b1d1dd23914f2be3ec606794ca4ba67708d25f4ba0d10a
@distributed_trace_async async def check_resource_name(self, resource_name_definition: Optional['_models.ResourceName']=None, **kwargs: Any) -> '_models.CheckResourceNameResult': 'Checks resource name validity.\n\n A resource name is valid if it is not a reserved word, does not contains a reserved word and\n does not start with a reserved word.\n\n :param resource_name_definition: Resource object with values for resource name and resource\n type.\n :type resource_name_definition:\n ~azure.mgmt.resource.subscriptions.v2018_06_01.models.ResourceName\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: CheckResourceNameResult, or the result of cls(response)\n :rtype: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.CheckResourceNameResult\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', 'application/json') if (resource_name_definition is not None): _json = self._serialize.body(resource_name_definition, 'ResourceName') else: _json = None request = build_check_resource_name_request(content_type=content_type, json=_json, template_url=self.check_resource_name.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs)) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('CheckResourceNameResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Checks resource name validity. A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. :param resource_name_definition: Resource object with values for resource name and resource type. :type resource_name_definition: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.ResourceName :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckResourceNameResult, or the result of cls(response) :rtype: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.CheckResourceNameResult :raises: ~azure.core.exceptions.HttpResponseError
sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2018_06_01/aio/operations/_subscription_client_operations.py
check_resource_name
automagically/azure-sdk-for-python
1
python
@distributed_trace_async async def check_resource_name(self, resource_name_definition: Optional['_models.ResourceName']=None, **kwargs: Any) -> '_models.CheckResourceNameResult': 'Checks resource name validity.\n\n A resource name is valid if it is not a reserved word, does not contains a reserved word and\n does not start with a reserved word.\n\n :param resource_name_definition: Resource object with values for resource name and resource\n type.\n :type resource_name_definition:\n ~azure.mgmt.resource.subscriptions.v2018_06_01.models.ResourceName\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: CheckResourceNameResult, or the result of cls(response)\n :rtype: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.CheckResourceNameResult\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', 'application/json') if (resource_name_definition is not None): _json = self._serialize.body(resource_name_definition, 'ResourceName') else: _json = None request = build_check_resource_name_request(content_type=content_type, json=_json, template_url=self.check_resource_name.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs)) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('CheckResourceNameResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
@distributed_trace_async async def check_resource_name(self, resource_name_definition: Optional['_models.ResourceName']=None, **kwargs: Any) -> '_models.CheckResourceNameResult': 'Checks resource name validity.\n\n A resource name is valid if it is not a reserved word, does not contains a reserved word and\n does not start with a reserved word.\n\n :param resource_name_definition: Resource object with values for resource name and resource\n type.\n :type resource_name_definition:\n ~azure.mgmt.resource.subscriptions.v2018_06_01.models.ResourceName\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: CheckResourceNameResult, or the result of cls(response)\n :rtype: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.CheckResourceNameResult\n :raises: ~azure.core.exceptions.HttpResponseError\n ' cls = kwargs.pop('cls', None) error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', 'application/json') if (resource_name_definition is not None): _json = self._serialize.body(resource_name_definition, 'ResourceName') else: _json = None request = build_check_resource_name_request(content_type=content_type, json=_json, template_url=self.check_resource_name.metadata['url']) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs)) response = pipeline_response.http_response if (response.status_code not in [200]): map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponseAutoGenerated, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('CheckResourceNameResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized<|docstring|>Checks resource name validity. A resource name is valid if it is not a reserved word, does not contains a reserved word and does not start with a reserved word. :param resource_name_definition: Resource object with values for resource name and resource type. :type resource_name_definition: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.ResourceName :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckResourceNameResult, or the result of cls(response) :rtype: ~azure.mgmt.resource.subscriptions.v2018_06_01.models.CheckResourceNameResult :raises: ~azure.core.exceptions.HttpResponseError<|endoftext|>
2a5843b252f765c9f2f703f848cd44119e8e5bafe11df048eefd93e944d2c5fa
def define_PV_controls(app): '\n define cos(phi)/Q(P) control for PVs\n ' o_QPCurves_IntPrjfolder = app.GetProjectFolder('qpc') for o in o_QPCurves_IntPrjfolder.GetContents(): o.Delete() o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') for o in o_QlimCurve_IntPrjfolder.GetContents(): o.Delete() o_IntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'QP acting as cosphi(P) char') o_IntcosphiPcurve.SetAttribute('inputmod', 1) o_IntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_IntcosphiPcurve.SetAttribute('Qpu', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221]) o_IntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'General PQ char') o_IntQpcurve.SetAttribute('inputmod', 1) o_IntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_IntQpcurve.SetAttribute('Qpu', [0, 0, (- 0.338)]) o_brokenIntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Broken PQ char') o_brokenIntQpcurve.SetAttribute('inputmod', 1) o_brokenIntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_brokenIntQpcurve.SetAttribute('Qpu', [0, 0, 0]) o_wrongIntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Wrong QP acting as cosphi(P) char') o_wrongIntcosphiPcurve.SetAttribute('inputmod', 1) o_wrongIntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_wrongIntcosphiPcurve.SetAttribute('Qpu', list((- np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221])))) return (o_IntcosphiPcurve, o_IntQpcurve, o_brokenIntQpcurve, o_wrongIntcosphiPcurve)
define cos(phi)/Q(P) control for PVs
raw_data_generation/grid_preparation.py
define_PV_controls
DavidFellner/Malfunctions_in_LV_grid_datase
0
python
def define_PV_controls(app): '\n \n ' o_QPCurves_IntPrjfolder = app.GetProjectFolder('qpc') for o in o_QPCurves_IntPrjfolder.GetContents(): o.Delete() o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') for o in o_QlimCurve_IntPrjfolder.GetContents(): o.Delete() o_IntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'QP acting as cosphi(P) char') o_IntcosphiPcurve.SetAttribute('inputmod', 1) o_IntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_IntcosphiPcurve.SetAttribute('Qpu', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221]) o_IntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'General PQ char') o_IntQpcurve.SetAttribute('inputmod', 1) o_IntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_IntQpcurve.SetAttribute('Qpu', [0, 0, (- 0.338)]) o_brokenIntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Broken PQ char') o_brokenIntQpcurve.SetAttribute('inputmod', 1) o_brokenIntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_brokenIntQpcurve.SetAttribute('Qpu', [0, 0, 0]) o_wrongIntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Wrong QP acting as cosphi(P) char') o_wrongIntcosphiPcurve.SetAttribute('inputmod', 1) o_wrongIntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_wrongIntcosphiPcurve.SetAttribute('Qpu', list((- np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221])))) return (o_IntcosphiPcurve, o_IntQpcurve, o_brokenIntQpcurve, o_wrongIntcosphiPcurve)
def define_PV_controls(app): '\n \n ' o_QPCurves_IntPrjfolder = app.GetProjectFolder('qpc') for o in o_QPCurves_IntPrjfolder.GetContents(): o.Delete() o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') for o in o_QlimCurve_IntPrjfolder.GetContents(): o.Delete() o_IntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'QP acting as cosphi(P) char') o_IntcosphiPcurve.SetAttribute('inputmod', 1) o_IntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_IntcosphiPcurve.SetAttribute('Qpu', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221]) o_IntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'General PQ char') o_IntQpcurve.SetAttribute('inputmod', 1) o_IntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_IntQpcurve.SetAttribute('Qpu', [0, 0, (- 0.338)]) o_brokenIntQpcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Broken PQ char') o_brokenIntQpcurve.SetAttribute('inputmod', 1) o_brokenIntQpcurve.SetAttribute('Ppu', [0, 0.5, 1]) o_brokenIntQpcurve.SetAttribute('Qpu', [0, 0, 0]) o_wrongIntcosphiPcurve = o_QPCurves_IntPrjfolder.CreateObject('IntQpcurve', 'Wrong QP acting as cosphi(P) char') o_wrongIntcosphiPcurve.SetAttribute('inputmod', 1) o_wrongIntcosphiPcurve.SetAttribute('Ppu', [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2, 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69, 0.7, 0.71, 0.72, 0.73, 0.74, 0.75, 0.76, 0.77, 0.78, 0.79, 0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9, 0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1]) o_wrongIntcosphiPcurve.SetAttribute('Qpu', list((- np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0633406, 0.08971208, 0.11004031, 0.12725592, 0.14249228, 0.15632983, 0.1691129, 0.18106551, 0.19234309, 0.20305866, 0.21329743, 0.22312553, 0.23259549, 0.24174985, 0.25062362, 0.25924607, 0.26764189, 0.2758322, 0.28383518, 0.29166667, 0.2993405, 0.3068689, 0.31426269, 0.32153154, 0.32868411, 0.33572819, 0.34267085, 0.34951849, 0.35627693, 0.36295153, 0.36954718, 0.37606838, 0.38251928, 0.38890373, 0.39522529, 0.40148728, 0.40769277, 0.41384466, 0.41994564, 0.42599822, 0.43200477, 0.43796754, 0.44388861, 0.44976996, 0.45561346, 0.46142089, 0.46719391, 0.47293413, 0.47864305, 0.4843221])))) return (o_IntcosphiPcurve, o_IntQpcurve, o_brokenIntQpcurve, o_wrongIntcosphiPcurve)<|docstring|>define cos(phi)/Q(P) control for PVs<|endoftext|>
811b2b1e995ab691f07c3fa1990e2717a68b21b6c374fd6dea8dd2712d18475c
def place_PVs(app, o_ElmNet, o_ChaTime, loads_by_type, PV_apparent_power=0.005, type_QDSL_model=None): '\n Place photvoltaics next to every load, assign control/capability curve & charactersitic and scale their output\n to the consumption of the load they are attached to so as it yields about the yearly consumption of the load\n ' type_qdsl_model = import_QDSL_type('cosphi(P)') curves = define_PV_controls(app) o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') o_IntQlim = o_QlimCurve_IntPrjfolder.SearchObject('Capability Curve') if ((o_IntQlim is None) or (o_IntQlim.loc_name != 'Capability Curve')): o_IntQlim = o_QlimCurve_IntPrjfolder.CreateObject('IntQlim', 'Capability Curve') o_IntQlim.SetAttribute('cap_Ppu', [0, 1]) o_IntQlim.SetAttribute('cap_Qmnpu', [0, (- 0.436)]) o_IntQlim.SetAttribute('cap_Qmxpu', [0, 0.436]) o_IntQlim.SetAttribute('inputmod', 1) for load in loads_by_type['regular_loads']: o_ElmLod = load[0] load_cubicle = o_ElmLod.bus1 o_ElmTerm = load_cubicle.cterm o_StaCubic = o_ElmTerm.CreateObject('StaCubic', ((('Cubicle_' + o_ElmLod.loc_name.split(' ')[0]) + ' SGen ') + o_ElmLod.loc_name.split(' ')[2])) o_Elm = o_ElmNet.CreateObject('ElmGenstat', ((((o_ElmLod.loc_name.split(' ')[0] + ' SGen ') + o_ElmLod.loc_name.split(' ')[2]) + ' @ ') + o_ElmLod.bus1.cterm.loc_name)) o_Elm.SetAttribute('bus1', o_StaCubic) o_Elm.SetAttribute('sgn', PV_apparent_power) o_Elm.cCategory = 'Photovoltaic' o_Elm.outserv = 1 if ((not config.QDSL_models_available) or (config.number_of_broken_devices_and_type[1] == 'PV')): o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) pf.set_referenced_characteristics(o_Elm, 'pgini', o_ChaTime) o_Elm.SetAttribute('av_mode', 'qpchar') o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_Elm.SetAttribute('Pmax_ucPU', 1) o_Elm.SetAttribute('pQlimType', o_IntQlim) elif config.QDSL_models_available: o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_ElmQDSLmodel = o_ElmNet.CreateObject('ElmQdsl', ((('QDSLmodel_' + o_ElmLod.loc_name.split(' ')[0]) + ' PV ') + o_ElmLod.loc_name.split(' ')[2])) o_ElmQDSLmodel.typ_id = type_qdsl_model o_ElmQDSLmodel.SetAttribute('e:initVals', [0.0, 0.0]) o_ElmQDSLmodel.SetAttribute('e:objectsLdf', [o_Elm, o_Elm]) o_Elm.i_scale = 0 return curves
Place photvoltaics next to every load, assign control/capability curve & charactersitic and scale their output to the consumption of the load they are attached to so as it yields about the yearly consumption of the load
raw_data_generation/grid_preparation.py
place_PVs
DavidFellner/Malfunctions_in_LV_grid_datase
0
python
def place_PVs(app, o_ElmNet, o_ChaTime, loads_by_type, PV_apparent_power=0.005, type_QDSL_model=None): '\n Place photvoltaics next to every load, assign control/capability curve & charactersitic and scale their output\n to the consumption of the load they are attached to so as it yields about the yearly consumption of the load\n ' type_qdsl_model = import_QDSL_type('cosphi(P)') curves = define_PV_controls(app) o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') o_IntQlim = o_QlimCurve_IntPrjfolder.SearchObject('Capability Curve') if ((o_IntQlim is None) or (o_IntQlim.loc_name != 'Capability Curve')): o_IntQlim = o_QlimCurve_IntPrjfolder.CreateObject('IntQlim', 'Capability Curve') o_IntQlim.SetAttribute('cap_Ppu', [0, 1]) o_IntQlim.SetAttribute('cap_Qmnpu', [0, (- 0.436)]) o_IntQlim.SetAttribute('cap_Qmxpu', [0, 0.436]) o_IntQlim.SetAttribute('inputmod', 1) for load in loads_by_type['regular_loads']: o_ElmLod = load[0] load_cubicle = o_ElmLod.bus1 o_ElmTerm = load_cubicle.cterm o_StaCubic = o_ElmTerm.CreateObject('StaCubic', ((('Cubicle_' + o_ElmLod.loc_name.split(' ')[0]) + ' SGen ') + o_ElmLod.loc_name.split(' ')[2])) o_Elm = o_ElmNet.CreateObject('ElmGenstat', ((((o_ElmLod.loc_name.split(' ')[0] + ' SGen ') + o_ElmLod.loc_name.split(' ')[2]) + ' @ ') + o_ElmLod.bus1.cterm.loc_name)) o_Elm.SetAttribute('bus1', o_StaCubic) o_Elm.SetAttribute('sgn', PV_apparent_power) o_Elm.cCategory = 'Photovoltaic' o_Elm.outserv = 1 if ((not config.QDSL_models_available) or (config.number_of_broken_devices_and_type[1] == 'PV')): o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) pf.set_referenced_characteristics(o_Elm, 'pgini', o_ChaTime) o_Elm.SetAttribute('av_mode', 'qpchar') o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_Elm.SetAttribute('Pmax_ucPU', 1) o_Elm.SetAttribute('pQlimType', o_IntQlim) elif config.QDSL_models_available: o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_ElmQDSLmodel = o_ElmNet.CreateObject('ElmQdsl', ((('QDSLmodel_' + o_ElmLod.loc_name.split(' ')[0]) + ' PV ') + o_ElmLod.loc_name.split(' ')[2])) o_ElmQDSLmodel.typ_id = type_qdsl_model o_ElmQDSLmodel.SetAttribute('e:initVals', [0.0, 0.0]) o_ElmQDSLmodel.SetAttribute('e:objectsLdf', [o_Elm, o_Elm]) o_Elm.i_scale = 0 return curves
def place_PVs(app, o_ElmNet, o_ChaTime, loads_by_type, PV_apparent_power=0.005, type_QDSL_model=None): '\n Place photvoltaics next to every load, assign control/capability curve & charactersitic and scale their output\n to the consumption of the load they are attached to so as it yields about the yearly consumption of the load\n ' type_qdsl_model = import_QDSL_type('cosphi(P)') curves = define_PV_controls(app) o_QlimCurve_IntPrjfolder = app.GetProjectFolder('mvar') o_IntQlim = o_QlimCurve_IntPrjfolder.SearchObject('Capability Curve') if ((o_IntQlim is None) or (o_IntQlim.loc_name != 'Capability Curve')): o_IntQlim = o_QlimCurve_IntPrjfolder.CreateObject('IntQlim', 'Capability Curve') o_IntQlim.SetAttribute('cap_Ppu', [0, 1]) o_IntQlim.SetAttribute('cap_Qmnpu', [0, (- 0.436)]) o_IntQlim.SetAttribute('cap_Qmxpu', [0, 0.436]) o_IntQlim.SetAttribute('inputmod', 1) for load in loads_by_type['regular_loads']: o_ElmLod = load[0] load_cubicle = o_ElmLod.bus1 o_ElmTerm = load_cubicle.cterm o_StaCubic = o_ElmTerm.CreateObject('StaCubic', ((('Cubicle_' + o_ElmLod.loc_name.split(' ')[0]) + ' SGen ') + o_ElmLod.loc_name.split(' ')[2])) o_Elm = o_ElmNet.CreateObject('ElmGenstat', ((((o_ElmLod.loc_name.split(' ')[0] + ' SGen ') + o_ElmLod.loc_name.split(' ')[2]) + ' @ ') + o_ElmLod.bus1.cterm.loc_name)) o_Elm.SetAttribute('bus1', o_StaCubic) o_Elm.SetAttribute('sgn', PV_apparent_power) o_Elm.cCategory = 'Photovoltaic' o_Elm.outserv = 1 if ((not config.QDSL_models_available) or (config.number_of_broken_devices_and_type[1] == 'PV')): o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) pf.set_referenced_characteristics(o_Elm, 'pgini', o_ChaTime) o_Elm.SetAttribute('av_mode', 'qpchar') o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_Elm.SetAttribute('Pmax_ucPU', 1) o_Elm.SetAttribute('pQlimType', o_IntQlim) elif config.QDSL_models_available: o_Elm.pgini = ((o_Elm.sgn * 0.9) * (o_ElmLod.plini / 0.004)) o_Elm.SetAttribute('pQPcurve', curves[config.control_curve_choice]) o_ElmQDSLmodel = o_ElmNet.CreateObject('ElmQdsl', ((('QDSLmodel_' + o_ElmLod.loc_name.split(' ')[0]) + ' PV ') + o_ElmLod.loc_name.split(' ')[2])) o_ElmQDSLmodel.typ_id = type_qdsl_model o_ElmQDSLmodel.SetAttribute('e:initVals', [0.0, 0.0]) o_ElmQDSLmodel.SetAttribute('e:objectsLdf', [o_Elm, o_Elm]) o_Elm.i_scale = 0 return curves<|docstring|>Place photvoltaics next to every load, assign control/capability curve & charactersitic and scale their output to the consumption of the load they are attached to so as it yields about the yearly consumption of the load<|endoftext|>
ee712a2d1b8961829211c67fcc7d1f27ce3c3948c54a7a62109b50d559116257
def place_EVCS(o_ElmNet, loads_by_type): '\n Place EV charging stations next to every load and assign charactersitic (according to load type)\n ' homes = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'H')] companies = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'G')] type_qdsl_model = import_QDSL_type('p_of_u') EV_charging_stations = place_home_or_work_EVCS(loads_by_type, homes, 'Home', o_ElmNet, type_qdsl_model) EV_charging_stations = (EV_charging_stations + place_home_or_work_EVCS(loads_by_type, companies, 'Work', o_ElmNet, type_qdsl_model)) return EV_charging_stations
Place EV charging stations next to every load and assign charactersitic (according to load type)
raw_data_generation/grid_preparation.py
place_EVCS
DavidFellner/Malfunctions_in_LV_grid_datase
0
python
def place_EVCS(o_ElmNet, loads_by_type): '\n \n ' homes = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'H')] companies = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'G')] type_qdsl_model = import_QDSL_type('p_of_u') EV_charging_stations = place_home_or_work_EVCS(loads_by_type, homes, 'Home', o_ElmNet, type_qdsl_model) EV_charging_stations = (EV_charging_stations + place_home_or_work_EVCS(loads_by_type, companies, 'Work', o_ElmNet, type_qdsl_model)) return EV_charging_stations
def place_EVCS(o_ElmNet, loads_by_type): '\n \n ' homes = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'H')] companies = [i for i in loads_by_type['regular_loads'] if (i[1].loc_name[0] == 'G')] type_qdsl_model = import_QDSL_type('p_of_u') EV_charging_stations = place_home_or_work_EVCS(loads_by_type, homes, 'Home', o_ElmNet, type_qdsl_model) EV_charging_stations = (EV_charging_stations + place_home_or_work_EVCS(loads_by_type, companies, 'Work', o_ElmNet, type_qdsl_model)) return EV_charging_stations<|docstring|>Place EV charging stations next to every load and assign charactersitic (according to load type)<|endoftext|>
d1f1e6031bc280ce0578aed5935ccf52278c4231b9ad6a461efb7323e7cc7b60
def utf8_complaint_naming(o_ElmNet): '\n Check for UTF-8 correct naming of elements (important for reading the result file into a dataframe)\n ' l_objects = o_ElmNet.GetContents(1) not_utf = [] for o in l_objects: string = o.loc_name if (len(string.encode('utf-8')) == len(string)): continue else: print('string is not UTF-8') count = 0 not_utf.append(o) for l in string: if (len(l.encode('utf-8')) > 1): new = string.replace(l, '_', count) string = new count += 1 o.loc_name = string print(('%d element names changed to match UTF-8 format' % len(not_utf))) return 0
Check for UTF-8 correct naming of elements (important for reading the result file into a dataframe)
raw_data_generation/grid_preparation.py
utf8_complaint_naming
DavidFellner/Malfunctions_in_LV_grid_datase
0
python
def utf8_complaint_naming(o_ElmNet): '\n \n ' l_objects = o_ElmNet.GetContents(1) not_utf = [] for o in l_objects: string = o.loc_name if (len(string.encode('utf-8')) == len(string)): continue else: print('string is not UTF-8') count = 0 not_utf.append(o) for l in string: if (len(l.encode('utf-8')) > 1): new = string.replace(l, '_', count) string = new count += 1 o.loc_name = string print(('%d element names changed to match UTF-8 format' % len(not_utf))) return 0
def utf8_complaint_naming(o_ElmNet): '\n \n ' l_objects = o_ElmNet.GetContents(1) not_utf = [] for o in l_objects: string = o.loc_name if (len(string.encode('utf-8')) == len(string)): continue else: print('string is not UTF-8') count = 0 not_utf.append(o) for l in string: if (len(l.encode('utf-8')) > 1): new = string.replace(l, '_', count) string = new count += 1 o.loc_name = string print(('%d element names changed to match UTF-8 format' % len(not_utf))) return 0<|docstring|>Check for UTF-8 correct naming of elements (important for reading the result file into a dataframe)<|endoftext|>
c696f4a3fd89859b98590affc9f37014b3a2932ed7ad7e9c596fc50d806e15a6
def mkpath(*segments, **query): '\n Constructs the path & query portion of a URI from path segments\n and a dict.\n ' segments = [bytes_to_str(s) for s in segments if (s is not None)] pathstring = '/'.join(segments) pathstring = re.sub('/+', '/', pathstring) _query = {} for key in query: if (query[key] in [False, True]): _query[key] = str(query[key]).lower() elif (query[key] is not None): if (PY2 and isinstance(query[key], unicode)): _query[key] = query[key].encode('utf-8') else: _query[key] = query[key] if (len(_query) > 0): pathstring += ('?' + urlencode(_query)) if (not pathstring.startswith('/')): pathstring = ('/' + pathstring) return pathstring
Constructs the path & query portion of a URI from path segments and a dict.
riak/transports/http/resources.py
mkpath
niklasekstrom/riak-python-client
89
python
def mkpath(*segments, **query): '\n Constructs the path & query portion of a URI from path segments\n and a dict.\n ' segments = [bytes_to_str(s) for s in segments if (s is not None)] pathstring = '/'.join(segments) pathstring = re.sub('/+', '/', pathstring) _query = {} for key in query: if (query[key] in [False, True]): _query[key] = str(query[key]).lower() elif (query[key] is not None): if (PY2 and isinstance(query[key], unicode)): _query[key] = query[key].encode('utf-8') else: _query[key] = query[key] if (len(_query) > 0): pathstring += ('?' + urlencode(_query)) if (not pathstring.startswith('/')): pathstring = ('/' + pathstring) return pathstring
def mkpath(*segments, **query): '\n Constructs the path & query portion of a URI from path segments\n and a dict.\n ' segments = [bytes_to_str(s) for s in segments if (s is not None)] pathstring = '/'.join(segments) pathstring = re.sub('/+', '/', pathstring) _query = {} for key in query: if (query[key] in [False, True]): _query[key] = str(query[key]).lower() elif (query[key] is not None): if (PY2 and isinstance(query[key], unicode)): _query[key] = query[key].encode('utf-8') else: _query[key] = query[key] if (len(_query) > 0): pathstring += ('?' + urlencode(_query)) if (not pathstring.startswith('/')): pathstring = ('/' + pathstring) return pathstring<|docstring|>Constructs the path & query portion of a URI from path segments and a dict.<|endoftext|>
f324ed181b40d3f1e122ab78515b38a5f60f377fe1e48133e14c9d46daaf0077
def search_index_path(self, index=None, **options): '\n Builds a Yokozuna search index URL.\n\n :param index: optional name of a yz index\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_index): raise RiakError('Yokozuna search is unsupported by this Riak node') if index: quote_plus(index) return mkpath(self.yz_wm_index, 'index', index, **options)
Builds a Yokozuna search index URL. :param index: optional name of a yz index :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string
riak/transports/http/resources.py
search_index_path
niklasekstrom/riak-python-client
89
python
def search_index_path(self, index=None, **options): '\n Builds a Yokozuna search index URL.\n\n :param index: optional name of a yz index\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_index): raise RiakError('Yokozuna search is unsupported by this Riak node') if index: quote_plus(index) return mkpath(self.yz_wm_index, 'index', index, **options)
def search_index_path(self, index=None, **options): '\n Builds a Yokozuna search index URL.\n\n :param index: optional name of a yz index\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_index): raise RiakError('Yokozuna search is unsupported by this Riak node') if index: quote_plus(index) return mkpath(self.yz_wm_index, 'index', index, **options)<|docstring|>Builds a Yokozuna search index URL. :param index: optional name of a yz index :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string<|endoftext|>
9ad7011756a49798f37121c47deaf24a35d4d1aad9b11e1e65d0d3471b266a4c
def search_schema_path(self, index, **options): '\n Builds a Yokozuna search Solr schema URL.\n\n :param index: a name of a yz solr schema\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_schema): raise RiakError('Yokozuna search is unsupported by this Riak node') return mkpath(self.yz_wm_schema, 'schema', quote_plus(index), **options)
Builds a Yokozuna search Solr schema URL. :param index: a name of a yz solr schema :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string
riak/transports/http/resources.py
search_schema_path
niklasekstrom/riak-python-client
89
python
def search_schema_path(self, index, **options): '\n Builds a Yokozuna search Solr schema URL.\n\n :param index: a name of a yz solr schema\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_schema): raise RiakError('Yokozuna search is unsupported by this Riak node') return mkpath(self.yz_wm_schema, 'schema', quote_plus(index), **options)
def search_schema_path(self, index, **options): '\n Builds a Yokozuna search Solr schema URL.\n\n :param index: a name of a yz solr schema\n :type index: string\n :param options: optional list of additional arguments\n :type index: dict\n :rtype URL string\n ' if (not self.yz_wm_schema): raise RiakError('Yokozuna search is unsupported by this Riak node') return mkpath(self.yz_wm_schema, 'schema', quote_plus(index), **options)<|docstring|>Builds a Yokozuna search Solr schema URL. :param index: a name of a yz solr schema :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string<|endoftext|>
23eb44e01c4b11ae5947c7b475dd45df340fbdbca3bae683b697f75cac9ec3fd
def preflist_path(self, bucket, key, bucket_type=None, **options): '\n Generate the URL for bucket/key preflist information\n\n :param bucket: Name of a Riak bucket\n :type bucket: string\n :param key: Name of a Key\n :type key: string\n :param bucket_type: Optional Riak Bucket Type\n :type bucket_type: None or string\n :rtype URL string\n ' if (not self.riak_kv_wm_preflist): raise RiakError('Preflists are unsupported by this Riak node') if (self.riak_kv_wm_bucket_type and bucket_type): return mkpath('/types', quote_plus(bucket_type), 'buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options) else: return mkpath('/buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options)
Generate the URL for bucket/key preflist information :param bucket: Name of a Riak bucket :type bucket: string :param key: Name of a Key :type key: string :param bucket_type: Optional Riak Bucket Type :type bucket_type: None or string :rtype URL string
riak/transports/http/resources.py
preflist_path
niklasekstrom/riak-python-client
89
python
def preflist_path(self, bucket, key, bucket_type=None, **options): '\n Generate the URL for bucket/key preflist information\n\n :param bucket: Name of a Riak bucket\n :type bucket: string\n :param key: Name of a Key\n :type key: string\n :param bucket_type: Optional Riak Bucket Type\n :type bucket_type: None or string\n :rtype URL string\n ' if (not self.riak_kv_wm_preflist): raise RiakError('Preflists are unsupported by this Riak node') if (self.riak_kv_wm_bucket_type and bucket_type): return mkpath('/types', quote_plus(bucket_type), 'buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options) else: return mkpath('/buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options)
def preflist_path(self, bucket, key, bucket_type=None, **options): '\n Generate the URL for bucket/key preflist information\n\n :param bucket: Name of a Riak bucket\n :type bucket: string\n :param key: Name of a Key\n :type key: string\n :param bucket_type: Optional Riak Bucket Type\n :type bucket_type: None or string\n :rtype URL string\n ' if (not self.riak_kv_wm_preflist): raise RiakError('Preflists are unsupported by this Riak node') if (self.riak_kv_wm_bucket_type and bucket_type): return mkpath('/types', quote_plus(bucket_type), 'buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options) else: return mkpath('/buckets', quote_plus(bucket), 'keys', quote_plus(key), 'preflist', **options)<|docstring|>Generate the URL for bucket/key preflist information :param bucket: Name of a Riak bucket :type bucket: string :param key: Name of a Key :type key: string :param bucket_type: Optional Riak Bucket Type :type bucket_type: None or string :rtype URL string<|endoftext|>
9194a84563f139cb40ee2b9da6cdd6a9dae71a86a85f1f52ec04d0dc25de8f54
def has_object_permission(self, request, view, obj): 'Same as super(), but check first if map is public' is_public_map = (obj.extra_fields and obj.extra_fields.get('public', False)) return (is_public_map or super().has_object_permission(request, view, obj))
Same as super(), but check first if map is public
projects/permissions.py
has_object_permission
dymaxionlabs/analytics-backend
0
python
def has_object_permission(self, request, view, obj): is_public_map = (obj.extra_fields and obj.extra_fields.get('public', False)) return (is_public_map or super().has_object_permission(request, view, obj))
def has_object_permission(self, request, view, obj): is_public_map = (obj.extra_fields and obj.extra_fields.get('public', False)) return (is_public_map or super().has_object_permission(request, view, obj))<|docstring|>Same as super(), but check first if map is public<|endoftext|>
8ab59f859b609faf7592fbd60183c52535dcb0dc66cd64f2685c4a448a1171d6
def __init__(self, api_key): "\n SlackWrapper constructor.\n Connect to the real-time messaging API and\n load the bot's login data.\n " self.api_key = api_key self.client = SlackClient(self.api_key) self.connected = self.client.rtm_connect() self.server = None self.username = None self.user_id = None if self.connected: self.server = self.client.server self.username = self.server.username self.user_id = self.server.login_data.get('self').get('id')
SlackWrapper constructor. Connect to the real-time messaging API and load the bot's login data.
util/slack_wrapper.py
__init__
Kileak/OTA-Challenge-Bot
0
python
def __init__(self, api_key): "\n SlackWrapper constructor.\n Connect to the real-time messaging API and\n load the bot's login data.\n " self.api_key = api_key self.client = SlackClient(self.api_key) self.connected = self.client.rtm_connect() self.server = None self.username = None self.user_id = None if self.connected: self.server = self.client.server self.username = self.server.username self.user_id = self.server.login_data.get('self').get('id')
def __init__(self, api_key): "\n SlackWrapper constructor.\n Connect to the real-time messaging API and\n load the bot's login data.\n " self.api_key = api_key self.client = SlackClient(self.api_key) self.connected = self.client.rtm_connect() self.server = None self.username = None self.user_id = None if self.connected: self.server = self.client.server self.username = self.server.username self.user_id = self.server.login_data.get('self').get('id')<|docstring|>SlackWrapper constructor. Connect to the real-time messaging API and load the bot's login data.<|endoftext|>
8a8cd13a3fa9b3dc9ba46fa6e7860e5cc13c5bbdf05e9fcf45a9f14bfc63575d
def read(self): 'Read from the real-time messaging API.' return self.client.rtm_read()
Read from the real-time messaging API.
util/slack_wrapper.py
read
Kileak/OTA-Challenge-Bot
0
python
def read(self): return self.client.rtm_read()
def read(self): return self.client.rtm_read()<|docstring|>Read from the real-time messaging API.<|endoftext|>
3550eab3deffd090d3300b619414d8d958a57f3e933c46347bcf5dc5fefa69b1
def invite_user(self, user, channel, is_private=False): '\n Invite a user to a given channel.\n ' api_call = ('groups.invite' if is_private else 'channels.invite') return self.client.api_call(api_call, channel=channel, user=user)
Invite a user to a given channel.
util/slack_wrapper.py
invite_user
Kileak/OTA-Challenge-Bot
0
python
def invite_user(self, user, channel, is_private=False): '\n \n ' api_call = ('groups.invite' if is_private else 'channels.invite') return self.client.api_call(api_call, channel=channel, user=user)
def invite_user(self, user, channel, is_private=False): '\n \n ' api_call = ('groups.invite' if is_private else 'channels.invite') return self.client.api_call(api_call, channel=channel, user=user)<|docstring|>Invite a user to a given channel.<|endoftext|>
b783607db30d6e2a991ff7e4e58c8c9f2e81e80919e20429018e93f80f2951c1
def set_purpose(self, channel, purpose, is_private=False): '\n Set the purpose of a given channel.\n ' api_call = ('groups.setPurpose' if is_private else 'channels.setPurpose') return self.client.api_call(api_call, purpose=purpose, channel=channel)
Set the purpose of a given channel.
util/slack_wrapper.py
set_purpose
Kileak/OTA-Challenge-Bot
0
python
def set_purpose(self, channel, purpose, is_private=False): '\n \n ' api_call = ('groups.setPurpose' if is_private else 'channels.setPurpose') return self.client.api_call(api_call, purpose=purpose, channel=channel)
def set_purpose(self, channel, purpose, is_private=False): '\n \n ' api_call = ('groups.setPurpose' if is_private else 'channels.setPurpose') return self.client.api_call(api_call, purpose=purpose, channel=channel)<|docstring|>Set the purpose of a given channel.<|endoftext|>
a0d4160c9395a84f383d40ded899114065ed47b03a8cc045add3a4432b9973b4
def get_members(self): '\n Return a list of all members.\n ' return self.client.api_call('users.list', presence=True)
Return a list of all members.
util/slack_wrapper.py
get_members
Kileak/OTA-Challenge-Bot
0
python
def get_members(self): '\n \n ' return self.client.api_call('users.list', presence=True)
def get_members(self): '\n \n ' return self.client.api_call('users.list', presence=True)<|docstring|>Return a list of all members.<|endoftext|>
a6a95fe717622834c9f9398b8fcddeefe245b78f2b515b76aab28937abe60a4a
def get_member(self, user_id): '\n Return a member for a given user_id.\n ' return self.client.api_call('users.info', user=user_id)
Return a member for a given user_id.
util/slack_wrapper.py
get_member
Kileak/OTA-Challenge-Bot
0
python
def get_member(self, user_id): '\n \n ' return self.client.api_call('users.info', user=user_id)
def get_member(self, user_id): '\n \n ' return self.client.api_call('users.info', user=user_id)<|docstring|>Return a member for a given user_id.<|endoftext|>
451cf0ddb40b379b9cefb0cb6f136d55cadc28600364ed10f3afc612dcf5223e
def create_channel(self, name, is_private=False): '\n Create a channel with a given name.\n ' api_call = ('groups.create' if is_private else 'channels.create') return self.client.api_call(api_call, name=name, validate=False)
Create a channel with a given name.
util/slack_wrapper.py
create_channel
Kileak/OTA-Challenge-Bot
0
python
def create_channel(self, name, is_private=False): '\n \n ' api_call = ('groups.create' if is_private else 'channels.create') return self.client.api_call(api_call, name=name, validate=False)
def create_channel(self, name, is_private=False): '\n \n ' api_call = ('groups.create' if is_private else 'channels.create') return self.client.api_call(api_call, name=name, validate=False)<|docstring|>Create a channel with a given name.<|endoftext|>
5f1c095aa8ba2e8c3e22409c8c9aacb07fe2526408926a6b3e10908fb1e038db
def rename_channel(self, channel_id, new_name, is_private=False): '\n Rename an existing channel.\n ' api_call = ('groups.rename' if is_private else 'channels.rename') return self.client.api_call(api_call, channel=channel_id, name=new_name, validate=False)
Rename an existing channel.
util/slack_wrapper.py
rename_channel
Kileak/OTA-Challenge-Bot
0
python
def rename_channel(self, channel_id, new_name, is_private=False): '\n \n ' api_call = ('groups.rename' if is_private else 'channels.rename') return self.client.api_call(api_call, channel=channel_id, name=new_name, validate=False)
def rename_channel(self, channel_id, new_name, is_private=False): '\n \n ' api_call = ('groups.rename' if is_private else 'channels.rename') return self.client.api_call(api_call, channel=channel_id, name=new_name, validate=False)<|docstring|>Rename an existing channel.<|endoftext|>
12eb4a08c964f9ee4909a3cea7ff052685fa55f1e892e02e4fbe33d1915ead6c
def get_channel_info(self, channel_id, is_private=False): '\n Return the channel info of a given channel ID.\n ' api_call = ('groups.info' if is_private else 'channels.info') return self.client.api_call(api_call, channel=channel_id)
Return the channel info of a given channel ID.
util/slack_wrapper.py
get_channel_info
Kileak/OTA-Challenge-Bot
0
python
def get_channel_info(self, channel_id, is_private=False): '\n \n ' api_call = ('groups.info' if is_private else 'channels.info') return self.client.api_call(api_call, channel=channel_id)
def get_channel_info(self, channel_id, is_private=False): '\n \n ' api_call = ('groups.info' if is_private else 'channels.info') return self.client.api_call(api_call, channel=channel_id)<|docstring|>Return the channel info of a given channel ID.<|endoftext|>
f688b7ba980170e365ab779963f1fdc7e4cc988d485225796c5484e09e4817fb
def update_channel_purpose_name(self, channel_id, new_name, is_private=False): "\n Updates the channel purpose 'name' field for a given channel ID.\n " channel_info = self.get_channel_info(channel_id, is_private) key = ('group' if is_private else 'channel') if channel_info: purpose = load_json(channel_info[key]['purpose']['value']) purpose['name'] = new_name self.set_purpose(channel_id, json.dumps(purpose), is_private)
Updates the channel purpose 'name' field for a given channel ID.
util/slack_wrapper.py
update_channel_purpose_name
Kileak/OTA-Challenge-Bot
0
python
def update_channel_purpose_name(self, channel_id, new_name, is_private=False): "\n \n " channel_info = self.get_channel_info(channel_id, is_private) key = ('group' if is_private else 'channel') if channel_info: purpose = load_json(channel_info[key]['purpose']['value']) purpose['name'] = new_name self.set_purpose(channel_id, json.dumps(purpose), is_private)
def update_channel_purpose_name(self, channel_id, new_name, is_private=False): "\n \n " channel_info = self.get_channel_info(channel_id, is_private) key = ('group' if is_private else 'channel') if channel_info: purpose = load_json(channel_info[key]['purpose']['value']) purpose['name'] = new_name self.set_purpose(channel_id, json.dumps(purpose), is_private)<|docstring|>Updates the channel purpose 'name' field for a given channel ID.<|endoftext|>
f9fa6af24c45e4d2bc853f9ae9a74441d45eb98cc9907ef89fa1a56191f85e9f
def post_message(self, channel_id, text, parse='full'): '\n Post a message in a given channel.\n channel_id can also be a user_id for private messages.\n ' self.client.api_call('chat.postMessage', channel=channel_id, text=text, as_user=True, parse=parse)
Post a message in a given channel. channel_id can also be a user_id for private messages.
util/slack_wrapper.py
post_message
Kileak/OTA-Challenge-Bot
0
python
def post_message(self, channel_id, text, parse='full'): '\n Post a message in a given channel.\n channel_id can also be a user_id for private messages.\n ' self.client.api_call('chat.postMessage', channel=channel_id, text=text, as_user=True, parse=parse)
def post_message(self, channel_id, text, parse='full'): '\n Post a message in a given channel.\n channel_id can also be a user_id for private messages.\n ' self.client.api_call('chat.postMessage', channel=channel_id, text=text, as_user=True, parse=parse)<|docstring|>Post a message in a given channel. channel_id can also be a user_id for private messages.<|endoftext|>
dadc1ca90819060cb1bd63e568ad9c0b8894836bb765205b04fca985726f851b
def get_public_channels(self): 'Fetch all public channels.' return self.client.api_call('channels.list')
Fetch all public channels.
util/slack_wrapper.py
get_public_channels
Kileak/OTA-Challenge-Bot
0
python
def get_public_channels(self): return self.client.api_call('channels.list')
def get_public_channels(self): return self.client.api_call('channels.list')<|docstring|>Fetch all public channels.<|endoftext|>
5e007d90f6740fbb8279531b8a03713d0f1d622fbe054de6b023c1ee3a2c3376
def get_private_channels(self): 'Fetch all private channels in which the user participates.' return self.client.api_call('groups.list')
Fetch all private channels in which the user participates.
util/slack_wrapper.py
get_private_channels
Kileak/OTA-Challenge-Bot
0
python
def get_private_channels(self): return self.client.api_call('groups.list')
def get_private_channels(self): return self.client.api_call('groups.list')<|docstring|>Fetch all private channels in which the user participates.<|endoftext|>
a54161b4796d5e0e08174d58be00737c6928e02e354909a560521c5dffd03d65
def archive_private_channel(self, channel_id): 'Archive a private channel' return self.client.api_call('groups.archive', channel=channel_id)
Archive a private channel
util/slack_wrapper.py
archive_private_channel
Kileak/OTA-Challenge-Bot
0
python
def archive_private_channel(self, channel_id): return self.client.api_call('groups.archive', channel=channel_id)
def archive_private_channel(self, channel_id): return self.client.api_call('groups.archive', channel=channel_id)<|docstring|>Archive a private channel<|endoftext|>
f12db1318e19ac496282ae8d6af56993709c7f39d43e85e30f6d60c24c408425
def load_data(filename: str) -> pd.DataFrame: '\n Load city daily temperature dataset and preprocess data.\n Parameters\n ----------\n filename: str\n Path to house prices dataset\n\n Returns\n -------\n Design matrix and response vector (Temp)\n ' df = pd.read_csv(filename, parse_dates=['Date']).dropna() df = df[(df['Temp'] > (- 70))] df['DayOfYear'] = df['Date'].dt.dayofyear df['Year'] = df['Year'].astype(str) return df
Load city daily temperature dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (Temp)
exercises/city_temperature_prediction.py
load_data
Tamarkom/IML.HUJI
0
python
def load_data(filename: str) -> pd.DataFrame: '\n Load city daily temperature dataset and preprocess data.\n Parameters\n ----------\n filename: str\n Path to house prices dataset\n\n Returns\n -------\n Design matrix and response vector (Temp)\n ' df = pd.read_csv(filename, parse_dates=['Date']).dropna() df = df[(df['Temp'] > (- 70))] df['DayOfYear'] = df['Date'].dt.dayofyear df['Year'] = df['Year'].astype(str) return df
def load_data(filename: str) -> pd.DataFrame: '\n Load city daily temperature dataset and preprocess data.\n Parameters\n ----------\n filename: str\n Path to house prices dataset\n\n Returns\n -------\n Design matrix and response vector (Temp)\n ' df = pd.read_csv(filename, parse_dates=['Date']).dropna() df = df[(df['Temp'] > (- 70))] df['DayOfYear'] = df['Date'].dt.dayofyear df['Year'] = df['Year'].astype(str) return df<|docstring|>Load city daily temperature dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (Temp)<|endoftext|>
c07630edc5c786f5361d2e71545a51e7db23e80a5de0f7220872874e336bca48
def format_subject(self, subject): '\n Escape CR and LF characters.\n ' return subject.replace('\n', '\\n').replace('\r', '\\r')
Escape CR and LF characters.
virtual/lib/python3.6/site-packages/django/utils/log.py
format_subject
Eccie-K/Awards
5,079
python
def format_subject(self, subject): '\n \n ' return subject.replace('\n', '\\n').replace('\r', '\\r')
def format_subject(self, subject): '\n \n ' return subject.replace('\n', '\\n').replace('\r', '\\r')<|docstring|>Escape CR and LF characters.<|endoftext|>
b298020b7222ef36349f30d252358de0bcacdc46abb02912659ff13ccec3ac59
def build_grab(*args, **kwargs): 'Builds the Grab instance with default options.' kwargs.setdefault('transport', GLOBAL['grab_transport']) return Grab(*args, **kwargs)
Builds the Grab instance with default options.
tests/util.py
build_grab
dimichxp/grab
2,266
python
def build_grab(*args, **kwargs): kwargs.setdefault('transport', GLOBAL['grab_transport']) return Grab(*args, **kwargs)
def build_grab(*args, **kwargs): kwargs.setdefault('transport', GLOBAL['grab_transport']) return Grab(*args, **kwargs)<|docstring|>Builds the Grab instance with default options.<|endoftext|>
6f10c471fff7266809cd976ef7ac97479d9d94963efd06bcc9afabb7d01da8e0
def build_spider(cls, **kwargs): 'Builds the Spider instance with default options.' kwargs.setdefault('grab_transport', GLOBAL['grab_transport']) kwargs.setdefault('network_service', GLOBAL['network_service']) return cls(**kwargs)
Builds the Spider instance with default options.
tests/util.py
build_spider
dimichxp/grab
2,266
python
def build_spider(cls, **kwargs): kwargs.setdefault('grab_transport', GLOBAL['grab_transport']) kwargs.setdefault('network_service', GLOBAL['network_service']) return cls(**kwargs)
def build_spider(cls, **kwargs): kwargs.setdefault('grab_transport', GLOBAL['grab_transport']) kwargs.setdefault('network_service', GLOBAL['network_service']) return cls(**kwargs)<|docstring|>Builds the Spider instance with default options.<|endoftext|>
779493fefd30388d1e0b145f752521d7007dbe26ac31acd6f2c6e10110971dc7
def check_if_matrix_is_generator_matrix(G): "\n Function that checks if a given matrix a generator matrix.\n The only requirement is that the matrix's rank is the same as the number of it's rows.\n :param G: numpy array\n :return: bool\n " if (lg.matrix_rank(G) == G.shape[0]): return True return False
Function that checks if a given matrix a generator matrix. The only requirement is that the matrix's rank is the same as the number of it's rows. :param G: numpy array :return: bool
Linear Coding.py
check_if_matrix_is_generator_matrix
Mythrillo/Information-Theory
0
python
def check_if_matrix_is_generator_matrix(G): "\n Function that checks if a given matrix a generator matrix.\n The only requirement is that the matrix's rank is the same as the number of it's rows.\n :param G: numpy array\n :return: bool\n " if (lg.matrix_rank(G) == G.shape[0]): return True return False
def check_if_matrix_is_generator_matrix(G): "\n Function that checks if a given matrix a generator matrix.\n The only requirement is that the matrix's rank is the same as the number of it's rows.\n :param G: numpy array\n :return: bool\n " if (lg.matrix_rank(G) == G.shape[0]): return True return False<|docstring|>Function that checks if a given matrix a generator matrix. The only requirement is that the matrix's rank is the same as the number of it's rows. :param G: numpy array :return: bool<|endoftext|>