code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_states_geo_zone_by_id(cls, states_geo_zone_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_states_geo_zone_by_id_with_http_info(states_geo_zone_id, **kwargs) else: (data) = cls._get_states_geo_zone_by_id_with_http_info(states_geo_zone_id, **kwargs) return data
Find StatesGeoZone Return single instance of StatesGeoZone by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_states_geo_zone_by_id(states_geo_zone_id, async=True) >>> result = thread.get() :param async bool :param str states_geo_zone_id: ID of statesGeoZone to return (required) :return: StatesGeoZone If the method is called asynchronously, returns the request thread.
def list_all_states_geo_zones(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_states_geo_zones_with_http_info(**kwargs) else: (data) = cls._list_all_states_geo_zones_with_http_info(**kwargs) return data
List StatesGeoZones Return a list of StatesGeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_states_geo_zones(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[StatesGeoZone] If the method is called asynchronously, returns the request thread.
def replace_states_geo_zone_by_id(cls, states_geo_zone_id, states_geo_zone, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) else: (data) = cls._replace_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) return data
Replace StatesGeoZone Replace all attributes of StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_states_geo_zone_by_id(states_geo_zone_id, states_geo_zone, async=True) >>> result = thread.get() :param async bool :param str states_geo_zone_id: ID of statesGeoZone to replace (required) :param StatesGeoZone states_geo_zone: Attributes of statesGeoZone to replace (required) :return: StatesGeoZone If the method is called asynchronously, returns the request thread.
def update_states_geo_zone_by_id(cls, states_geo_zone_id, states_geo_zone, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) else: (data) = cls._update_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) return data
Update StatesGeoZone Update attributes of StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_states_geo_zone_by_id(states_geo_zone_id, states_geo_zone, async=True) >>> result = thread.get() :param async bool :param str states_geo_zone_id: ID of statesGeoZone to update. (required) :param StatesGeoZone states_geo_zone: Attributes of statesGeoZone to update. (required) :return: StatesGeoZone If the method is called asynchronously, returns the request thread.
def compaction(self, request_compaction=False): url = self._service_url + 'compaction/' if request_compaction: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indicating whether or not to request compaction.
def get_authenticated_connection(self, user, passwd, db='admin', ssl=True): # Attempt to establish an authenticated connection. try: connection = self.get_connection(ssl=ssl) connection[db].authenticate(user, passwd) return connection # Catch exception here for logging, then just re-raise. except pymongo.errors.OperationFailure as ex: logger.exception(ex) raise
Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to authenticate against. Defaults to ``'Admin'``. :param bool ssl: Use SSL/TLS if available for this instance. Defaults to ``True``. :raises: :py:class:`pymongo.errors.OperationFailure` if authentication fails.
def shards(self, add_shard=False): url = self._service_url + 'shards/' if add_shard: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to the specified instance.
def new_relic_stats(self): if self._new_relic_stats is None: # if this is a sharded instance, fetch shard stats in parallel if self.type == 'mongodb_sharded': shards = [Shard(self.name, self._service_url + 'shards/', self._client, shard_doc) for shard_doc in self.shards().get('data')] fs = [] with futures.ThreadPoolExecutor(len(shards)) as executor: for shard in shards: fs.append(executor.submit(shard.get_shard_stats)) futures.wait(fs, timeout=None, return_when=futures.ALL_COMPLETED) stats_this_second = self._rollup_shard_stats_to_instance_stats( {shard.name: future.result() for (shard, future) in zip(shards, fs)}) # power nap time.sleep(1) # fetch again fs = [] with futures.ThreadPoolExecutor(len(shards)) as executor: for shard in shards: fs.append(executor.submit(shard.get_shard_stats)) futures.wait(fs, timeout=None, return_when=futures.ALL_COMPLETED) stats_next_second = self._rollup_shard_stats_to_instance_stats( {shard.name: future.result() for (shard, future) in zip(shards, fs)}) self._new_relic_stats = self._compile_new_relic_stats(stats_this_second, stats_next_second) else: # fetch stats like we did before (by hitting new_relic_stats API resource) response = requests.get('{}{}'.format(self._url, 'new-relic-stats'), **self._instances._default_request_kwargs) self._new_relic_stats = json.loads(response.content).get( 'data') if response.status_code == 200 else {} return self._new_relic_stats
Get stats for this instance.
def _rollup_shard_stats_to_instance_stats(self, shard_stats): instance_stats = {} opcounters_per_node = [] # aggregate replication_lag instance_stats['replication_lag'] = max(map(lambda s: s['replication_lag'], shard_stats.values())) aggregate_server_statistics = {} for shard_name, stats in shard_stats.items(): for statistic_key in stats.get('shard_stats'): if statistic_key != 'connections' and statistic_key in aggregate_server_statistics: aggregate_server_statistics[statistic_key] = util.sum_values(aggregate_server_statistics[statistic_key], stats.get('shard_stats')[statistic_key]) else: aggregate_server_statistics[statistic_key] = stats.get('shard_stats')[statistic_key] # aggregate per_node_stats into opcounters_per_node opcounters_per_node.append({shard_name: {member: node_stats['opcounters'] for member, node_stats in stats.get('per_node_stats').items()}}) instance_stats['opcounters_per_node'] = opcounters_per_node instance_stats['aggregate_server_statistics'] = aggregate_server_statistics return instance_stats
roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard level stats}
def get_stepdown_window(self): url = self._service_url + 'stepdown/' response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
Get information on this instance's stepdown window.
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): # Ensure a logical start and endtime is requested. if not start < end: raise TypeError('Parameter "start" must occur earlier in time than "end".') # Ensure specified window is less than a week in length. week_delta = datetime.timedelta(days=7) if not ((end - start) <= week_delta): raise TypeError('Stepdown windows can not be longer than 1 week in length.') url = self._service_url + 'stepdown/' data = { 'start': int(start.strftime('%s')), 'end': int(end.strftime('%s')), 'enabled': enabled, 'scheduled': scheduled, 'weekly': weekly, } response = requests.post( url, data=json.dumps(data), **self._instances._default_request_kwargs ) return response.json()
Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetime.datetime end: The datetime which the stepdown window is to close. :param bool enabled: A boolean indicating whether or not stepdown is to be enabled. :param bool scheduled: A boolean indicating whether or not to schedule stepdown. :param bool weekly: A boolean indicating whether or not to schedule compaction weekly.
def _get_connection(self, ssl): # Use SSL/TLS if requested and available. connect_string = self.connect_string if ssl and self.ssl_connect_string: connect_string = self.ssl_connect_string return pymongo.MongoClient(connect_string)
Get a live connection to this instance.
def get_shard_stats(self): return requests.get(self._stats_url, params={'include_stats': True}, headers={'X-Auth-Token': self._client.auth._token} ).json()['data']['stats']
:return: get stats for this mongodb shard
def brand(self, brand): allowed_values = ["visa", "mastercard", "americanExpress", "discover"] if brand is not None and brand not in allowed_values: raise ValueError( "Invalid value for `brand` ({0}), must be one of {1}" .format(brand, allowed_values) ) self._brand = brand
Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str
def create_payment_card(cls, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_payment_card_with_http_info(payment_card, **kwargs) else: (data) = cls._create_payment_card_with_http_info(payment_card, **kwargs) return data
Create PaymentCard Create a new PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_payment_card(payment_card, async=True) >>> result = thread.get() :param async bool :param PaymentCard payment_card: Attributes of paymentCard to create (required) :return: PaymentCard If the method is called asynchronously, returns the request thread.
def delete_payment_card_by_id(cls, payment_card_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_payment_card_by_id_with_http_info(payment_card_id, **kwargs) else: (data) = cls._delete_payment_card_by_id_with_http_info(payment_card_id, **kwargs) return data
Delete PaymentCard Delete an instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_payment_card_by_id(payment_card_id, async=True) >>> result = thread.get() :param async bool :param str payment_card_id: ID of paymentCard to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_payment_card_by_id(cls, payment_card_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_payment_card_by_id_with_http_info(payment_card_id, **kwargs) else: (data) = cls._get_payment_card_by_id_with_http_info(payment_card_id, **kwargs) return data
Find PaymentCard Return single instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_card_by_id(payment_card_id, async=True) >>> result = thread.get() :param async bool :param str payment_card_id: ID of paymentCard to return (required) :return: PaymentCard If the method is called asynchronously, returns the request thread.
def list_all_payment_cards(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_payment_cards_with_http_info(**kwargs) else: (data) = cls._list_all_payment_cards_with_http_info(**kwargs) return data
List PaymentCards Return a list of PaymentCards This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_payment_cards(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[PaymentCard] If the method is called asynchronously, returns the request thread.
def replace_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) else: (data) = cls._replace_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) return data
Replace PaymentCard Replace all attributes of PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_payment_card_by_id(payment_card_id, payment_card, async=True) >>> result = thread.get() :param async bool :param str payment_card_id: ID of paymentCard to replace (required) :param PaymentCard payment_card: Attributes of paymentCard to replace (required) :return: PaymentCard If the method is called asynchronously, returns the request thread.
def update_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) else: (data) = cls._update_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) return data
Update PaymentCard Update attributes of PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_payment_card_by_id(payment_card_id, payment_card, async=True) >>> result = thread.get() :param async bool :param str payment_card_id: ID of paymentCard to update. (required) :param PaymentCard payment_card: Attributes of paymentCard to update. (required) :return: PaymentCard If the method is called asynchronously, returns the request thread.
def rec2csv(r, filename): names = r.dtype.names def translate(x): if x is None or str(x).lower == "none": x = "" return str(x) with open(filename, "w") as csv: csv.write(",".join([str(x) for x in names])+"\n") for data in r: csv.write(",".join([translate(x) for x in data])+"\n") #print "Wrote CSV table %r" % filename return filename
Export a recarray *r* to a CSV file *filename*
def latex_quote(s): special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] return s
Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.)
def rec2latex(r, filename, empty=""): with open(filename, "w") as latex: latex.write(s_rec2latex(r, empty=empty)) return filename
Export a recarray *r* to a LaTeX table in *filename*
def s_rec2latex(r, empty=""): latex = "" names = r.dtype.names def translate(x): if x is None or str(x).lower == "none": x = empty return latex_quote(x) latex += r"\begin{tabular}{%s}" % ("".join(["c"]*len(names)),) + "\n" # simple c columns latex += r"\hline"+"\n" latex += " & ".join([latex_quote(x) for x in names])+r"\\"+"\n" latex += r"\hline"+"\n" for data in r: latex += " & ".join([translate(x) for x in data])+r"\\"+"\n" latex += r"\hline"+"\n" latex += r"\end{tabular}"+"\n" return latex
Export a recarray *r* to a LaTeX table in a string
def on(self, type): '''Decorator function''' def decorator(self, func): '''decorated functions should be written as class methods @on('join') def on_join(self, channel): print("Joined channel %s" % channel) ''' self._handlers[type].append(func) return func return decoratof on(self, type): '''Decorator function''' def decorator(self, func): '''decorated functions should be written as class methods @on('join') def on_join(self, channel): print("Joined channel %s" % channel) ''' self._handlers[type].append(func) return func return decorator
Decorator function
def tree_to_file(tree:'BubbleTree', outfile:str): with open(outfile, 'w') as fd: fd.write(tree_to_bubble(tree))
Compute the bubble representation of given power graph, and push it into given file.
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) for node in tree.powernodes(): yield SET.format(node) for node, includeds in tree.inclusions.items(): for included in includeds: yield INCL.format(included, node) for node, succs in tree.edges.items(): for succ in succs: yield EDGE.format(node, succ)
Yield lines of bubble describing given BubbleTree
def to_python(self): if isinstance(self.data, str): return self.data.strip().lower() == 'true' if isinstance(self.data, int): return self.data > 0 return bool(self.data)
The string ``'True'`` (case insensitive) will be converted to ``True``, as will any positive integers.
def to_python(self): '''A :class:`datetime.datetime` object is returned.''' if self.data is None: return None # don't parse data that is already native if isinstance(self.data, datetime.datetime): return self.data elif self.use_int: return datetime.datetime.utcfromtimestamp(self.data / 1000) elif self.format is None: # parse as iso8601 return PySO8601.parse(self.data) else: return datetime.datetime.strptime(self.data, self.formatf to_python(self): '''A :class:`datetime.datetime` object is returned.''' if self.data is None: return None # don't parse data that is already native if isinstance(self.data, datetime.datetime): return self.data elif self.use_int: return datetime.datetime.utcfromtimestamp(self.data / 1000) elif self.format is None: # parse as iso8601 return PySO8601.parse(self.data) else: return datetime.datetime.strptime(self.data, self.format)
A :class:`datetime.datetime` object is returned.
def get_api_call_headers(app): headers = { "content-type": "application/json;charset=UTF-8", "User-Agent": app.user_agent, } if not app.developer_settings: raise AuthError({"message": "Для корректной работы SDK нужно установить настройки разработчика", "url": "https://apps.devision.io/page?a=63&p=3975"}) headers.update(app.developer_settings.get('api_headers')) return headers
Генерирует заголовки для API запроса. Тут же подкладывается авторизация :type app: metasdk.MetaApp
def extract_filename_from_url(log, url): ## > IMPORTS ## import re # EXTRACT THE FILENAME FROM THE URL try: log.debug("extracting filename from url " + url) reEoURL = re.compile('([\w\.]*)$') filename = reEoURL.findall(url)[0] # log.debug(filename) if(len(filename) == 0): filename = 'untitled.html' if not (re.search('\.', filename)): filename = filename + '.html' except Exception as e: filename = None # print url log.warning("could not extracting filename from url : " + str(e) + "\n") return filename
*get the filename from a URL.* *Will return 'untitled.html', if no filename is found.* **Key Arguments:** - ``url`` -- the url to extract filename from Returns: - ``filename`` -- the filename **Usage:** .. code-block:: python from fundamentals.download import extract_filename_from_url name = extract_filename_from_url( log=log, url="https://en.wikipedia.org/wiki/Docstring" ) print name # OUT: Docstring.html
def build_from_developer_settings(api_name: str, api_version: str): developer_settings = read_developer_settings() api_host = "http://" + api_name + ".apis.devision.io" return ApiClient( host=api_host, api_version=api_version, access_token=None, refresh_token=developer_settings['refreshToken'], client_id=developer_settings['clientId'], client_secret=developer_settings['clientSecret'], )
:param api_name: Example hello :param api_version: Example v1, v2alpha :return: ApiClient
def process_formdata(self, valuelist): if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: self.data = None raise
Join time string.
def validate_csrf_token(self, field): if current_app.testing: return super(InvenioBaseForm, self).validate_csrf_token(field)
Disable CRSF proection during testing.
def access_SUSY_dataset_format_file(filename): # Load the CSV file to a list. with open(filename, "rb") as dataset_file: dataset_CSV = [row for row in csv.reader(dataset_file, delimiter = ",")] # Reorganise the data. return [ i for i in itertools.chain(*[list((element[1:], [int(float(element[0]))])) for element in dataset_CSV]) ]
This function accesses a CSV file containing data of the form of the [SUSY dataset](https://archive.ics.uci.edu/ml/datasets/SUSY), i.e. with the first column being class labels and other columns being features.
def select_event( event = None, selection = "ejets" ): if selection == "ejets": # Require single lepton. # Require >= 4 jets. if \ 0 < len(event.el_pt) < 2 and \ len(event.jet_pt) >= 4 and \ len(event.ljet_m) >= 1: return True else: return False
Select a HEP event.
def sentiment( text = None, confidence = False ): try: words = text.split(" ") # Remove empty strings. words = [word for word in words if word] features = word_features(words) classification = classifier.classify(features) confidence_classification = classifier.prob_classify(features).prob(classification) except: classification = None confidence_classification = None if confidence: return ( classification, confidence_classification ) else: return classification
This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By default, it returns this calculated sentiment. If selected, it returns a tuple of the calculated sentiment and the classificaton confidence.
def usernames( self ): try: return list(set([tweet.username for tweet in self])) except: log.error("error -- possibly a problem with tweets stored")
This function returns the list of unique usernames corresponding to the tweets stored in self.
def user_sentiments( self, username = None ): try: return [tweet.sentiment for tweet in self if tweet.username == username] except: log.error("error -- possibly no username specified") return None
This function returns a list of all sentiments of the tweets of a specified user.
def user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): try: sentiment_frequencies = collections.Counter(self.user_sentiments( username = username )) if single_most_frequent: return sentiment_frequencies.most_common(1)[0][0] else: return dict(sentiment_frequencies) except: log.error("error -- possibly no username specified") return None
This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment is returned. All sentiments with their corresponding frequencies can be returned also.
def users_sentiments_single_most_frequent( self, usernames = None, ): users_sentiments_single_most_frequent = dict() if usernames is None: usernames = self.usernames() try: for username in usernames: sentiment = self.user_sentiments_most_frequent( username = username, single_most_frequent = True ) users_sentiments_single_most_frequent[username] = sentiment return users_sentiments_single_most_frequent except: log.error("error -- possibly a problem with tweets stored") return None
This function returns the single most frequent calculated sentiment expressed by all stored users or by a list of specified users as a dictionary.
def create_stripe_gateway(cls, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_stripe_gateway_with_http_info(stripe_gateway, **kwargs) else: (data) = cls._create_stripe_gateway_with_http_info(stripe_gateway, **kwargs) return data
Create StripeGateway Create a new StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_stripe_gateway(stripe_gateway, async=True) >>> result = thread.get() :param async bool :param StripeGateway stripe_gateway: Attributes of stripeGateway to create (required) :return: StripeGateway If the method is called asynchronously, returns the request thread.
def delete_stripe_gateway_by_id(cls, stripe_gateway_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) else: (data) = cls._delete_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) return data
Delete StripeGateway Delete an instance of StripeGateway by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_stripe_gateway_by_id(stripe_gateway_id, async=True) >>> result = thread.get() :param async bool :param str stripe_gateway_id: ID of stripeGateway to delete. (required) :return: None If the method is called asynchronously, returns the request thread.
def get_stripe_gateway_by_id(cls, stripe_gateway_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) else: (data) = cls._get_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) return data
Find StripeGateway Return single instance of StripeGateway by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_stripe_gateway_by_id(stripe_gateway_id, async=True) >>> result = thread.get() :param async bool :param str stripe_gateway_id: ID of stripeGateway to return (required) :return: StripeGateway If the method is called asynchronously, returns the request thread.
def list_all_stripe_gateways(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_stripe_gateways_with_http_info(**kwargs) else: (data) = cls._list_all_stripe_gateways_with_http_info(**kwargs) return data
List StripeGateways Return a list of StripeGateways This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_stripe_gateways(async=True) >>> result = thread.get() :param async bool :param int page: page number :param int size: page size :param str sort: page order :return: page[StripeGateway] If the method is called asynchronously, returns the request thread.
def replace_stripe_gateway_by_id(cls, stripe_gateway_id, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) else: (data) = cls._replace_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) return data
Replace StripeGateway Replace all attributes of StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_stripe_gateway_by_id(stripe_gateway_id, stripe_gateway, async=True) >>> result = thread.get() :param async bool :param str stripe_gateway_id: ID of stripeGateway to replace (required) :param StripeGateway stripe_gateway: Attributes of stripeGateway to replace (required) :return: StripeGateway If the method is called asynchronously, returns the request thread.
def update_stripe_gateway_by_id(cls, stripe_gateway_id, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) else: (data) = cls._update_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) return data
Update StripeGateway Update attributes of StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_stripe_gateway_by_id(stripe_gateway_id, stripe_gateway, async=True) >>> result = thread.get() :param async bool :param str stripe_gateway_id: ID of stripeGateway to update. (required) :param StripeGateway stripe_gateway: Attributes of stripeGateway to update. (required) :return: StripeGateway If the method is called asynchronously, returns the request thread.
def format_underline(s, char="=", indents=0): n = len(s) ind = " " * indents return ["{}{}".format(ind, s), "{}{}".format(ind, char*n)]
Traces a dashed line below string Args: s: string char: indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_underline("Life of João da Silva", "^", 2))) Life of João da Silva ^^^^^^^^^^^^^^^^^^^^^
def format_h1(s, format="text", indents=0): _CHAR = "=" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["# {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args: s: string format: string starting with "text", "markdown", or "rest" indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_h2("Header 1", indents=10))) Header 1 -------- >>> print("\\n".join(format_h2("Header 1", "markdown", 0))) ## Header 1
def format_h2(s, format="text", indents=0): _CHAR = "-" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["## {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1() >>> print("\\n".join(format_h2("Header 2", indents=2))) Header 2 -------- >>> print("\\n".join(format_h2("Header 2", "markdown", 2))) ## Header 2
def format_h3(s, format="text", indents=0): _CHAR = "~" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["### {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1()
def format_h4(s, format="text", indents=0): _CHAR = "^" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["#### {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1()
def question(question, options, default=None): # Make sure options is a list options_ = [x for x in options] if default is not None and default not in options_: raise ValueError("Default option '{}' is not in options {}.".format(default, options)) oto = "/".join([x.upper() if x == default else x.lower() for x in options_]) # to show ocomp = [x.lower() for x in options_] # to be used in comparison while True: ans = input("{} ({})? ".format(question, oto)).lower() if ans == "" and default is not None: ret = default break elif ans in ocomp: ret = options_[ocomp.index(ans)] break return ret
Ask a question with case-insensitive options of answers Args: question: string **without** the question mark and without the options. Example: 'Commit changes' options_: string or sequence of strings. If string, options will be single-lettered. Examples: 'YNC', ['yes', 'no', 'cancel']. options are case-insensitive default: default option. If passed, default option will be shown in uppercase. Answers are case-insensitive, but options will be shown in lowercase, except for the default option. Returns: str: chosen option. Although the answer is case-insensitive, the result will be as informed in the 'options' argument.
def yesno(question, default=None): if default is not None: if isinstance(default, bool): pass else: default_ = default.upper() if default_ not in ('Y', 'YES', 'N', 'NO'): raise RuntimeError("Invalid default value: '{}'".format(default)) default = default_ in ('Y', 'YES') while True: ans = input("{} ({}/{})? ".format(question, "Y" if default == True else "y", "N" if default == False else "n")).upper() if ans == "" and default is not None: ret = default break elif ans in ("N", "NO"): ret = False break elif ans in ("Y", "YES"): ret = True break return ret
Asks a yes/no question Args: question: string **without** the question mark and without the options. Example: 'Create links' default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of these valus (this argument is case-insensitive) Returns: bool: True if user answered Yes, False otherwise
def menu(title, options, cancel_label="Cancel", flag_allow_empty=False, flag_cancel=True, ch='.'): num_options, flag_ok = len(options), 0 option = None # result min_allowed = 0 if flag_cancel else 1 # minimum option value allowed (if option not empty) while True: print("") for line in format_box(title, ch): print(" "+line) for i, s in enumerate(options): print((" {0:d} - {1!s}".format(i+1, s))) if flag_cancel: print((" 0 - << (*{0!s}*)".format(cancel_label))) try: s_option = input('? ') except KeyboardInterrupt: raise except: print("") n_try = 0 while True: if n_try >= 10: print('You are messing up!') break if len(s_option) == 0 and flag_allow_empty: flag_ok = True break try: option = int(s_option) if min_allowed <= option <= num_options: flag_ok = True break except ValueError: print("Invalid integer value!") print(("Invalid option, range is [{0:d}, {1:d}]!".format(0 if flag_cancel else 1, num_options))) n_try += 1 s_option = input("? ") if flag_ok: break return option
Text menu. Arguments: title -- menu title, to appear at the top options -- sequence of strings cancel_label='Cancel' -- label to show at last "zero" option flag_allow_empty=0 -- Whether to allow empty option flag_cancel=True -- whether there is a "0 - Cancel" option ch="." -- character to use to draw frame around title Returns: option -- an integer: None; 0-Back/Cancel/etc; 1, 2, ... Adapted from irootlab menu.m
def format_box(title, ch="*"): lt = len(title) return [(ch * (lt + 8)), (ch * 3 + " " + title + " " + ch * 3), (ch * (lt + 8)) ]
Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** *************************
def format_progress(i, n): if n == 0: fraction = 0 else: fraction = float(i)/n LEN_BAR = 25 num_plus = int(round(fraction*LEN_BAR)) s_plus = '+'*num_plus s_point = '.'*(LEN_BAR-num_plus) return '[{0!s}{1!s}] {2:d}/{3:d} - {4:.1f}%'.format(s_plus, s_point, i, n, fraction*100)
Returns string containing a progress bar, a percentage, etc.
def _format_exe_info(py_len, exeinfo, format, indlevel): ret = [] ind = " " * indlevel * NIND if format.startswith("text") else "" if format == "markdown-list": for si in exeinfo: ret.append(" - `{0!s}`: {1!s}".format(si.filename, si.description)) if format == "rest-list": for si in exeinfo: ret.append("* ``{0!s}``: {1!s}".format(si.filename, si.description)) elif format == "markdown-table": mask = "%-{0:d}s | %s".format(py_len+2 ) ret.append(mask % ("Script name", "Purpose")) ret.append("-" * (py_len + 3) + "|" + "-" * 10) for si in exeinfo: ret.append(mask % ("`{0!s}`".format(si.filename), si.description)) elif format == "text": sbc = 1 # spaces between columns for si in exeinfo: ss = textwrap.wrap(si.description, 79 - py_len - sbc - indlevel*NIND) for i, s in enumerate(ss): if i == 0: filecolumn = si.filename + " " + ("." * (py_len - len(si.filename))) else: filecolumn = " " * (py_len + 1) ret.append("{}{}{}{}".format(ind, filecolumn, " "*sbc, s)) ret.append("") return ret
Renders ExeInfo object in specified format
def format_exe_info(exeinfo, format="text", indlevel=0): py_len = max([len(si.filename) for si in exeinfo]) sisi_gra = [si for si in exeinfo if si.flag_gui == True] sisi_cmd = [si for si in exeinfo if si.flag_gui == False] sisi_none = [si for si in exeinfo if si.flag_gui is None] def get_title(x): return format_h4(x, format, indlevel*NIND) + [""] ret = [] if len(sisi_gra) > 0: ret.extend(get_title("Graphical applications")) ret.extend(_format_exe_info(py_len, sisi_gra, format, indlevel + 1)) if len(sisi_cmd) > 0: ret.extend(get_title("Command-line tools", )) ret.extend(_format_exe_info(py_len, sisi_cmd, format, indlevel + 1)) if len(sisi_none) > 0: ret.extend(_format_exe_info(py_len, sisi_none, format, indlevel + 1)) return ret, py_len
Generates listing of all Python scripts available as command-line programs. Args: exeinfo -- list of ExeInfo objects format -- One of the options below: "text" -- generates plain text for printing at the console "markdown-list" -- generates MarkDown as list "markdown-table" -- generates MarkDown as tables "rest-list" -- generates reStructuredText as lists indents -- indentation level ("text" format only) Returns: (list of strings, maximum filename size) list of strings -- can be joined with a "\n" maximum filename size
def markdown_table(data, headers): maxx = [max([len(x) for x in column]) for column in zip(*data)] maxx = [max(ll) for ll in zip(maxx, [len(x) for x in headers])] mask = " | ".join(["%-{0:d}s".format(n) for n in maxx]) ret = [mask % headers] ret.append(" | ".join(["-"*n for n in maxx])) for line in data: ret.append(mask % line) return ret
Creates MarkDown table. Returns list of strings Arguments: data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...] headers -- sequence of strings: (header0, header1, ...)
def expand_multirow_data(data): num_cols = len(data[0]) # number of columns # calculates row heights row_heights = [] for mlrow in data: row_height = 0 for j, cell in enumerate(mlrow): row_height = max(row_height, 1 if not isinstance(cell, (list, tuple)) else len(cell)) row_heights.append(row_height) num_lines = sum(row_heights) # line != row (rows are multiline) # rebuilds table data new_data = [[""]*num_cols for i in range(num_lines)] i0 = 0 for row_height, mlrow in zip(row_heights, data): for j, cell in enumerate(mlrow): if not isinstance(cell, (list, tuple)): cell = [cell] for incr, x in enumerate(cell): new_data[i0+incr][j] = x i0 += row_height return new_data, row_heights
Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights
def rest_table(data, headers): num_cols = len(headers) new_data, row_heights = expand_multirow_data(data) new_data = [[str(x) for x in row] for row in new_data] col_widths = [max([len(x) for x in col]) for col in zip(*new_data)] col_widths = [max(cw, len(s)) for cw, s in zip(col_widths, headers)] if any([x == 0 for x in col_widths]): raise RuntimeError("Column widths ({}) has at least one zero".format(col_widths)) num_lines = sum(row_heights) # line != row (rows are multiline) # horizontal lines hl0 = "+"+"+".join(["-"*(n+2) for n in col_widths])+"+" hl1 = "+"+"+".join(["="*(n+2) for n in col_widths])+"+" frmtd = ["{0:{1}}".format(x, width) for x, width in zip(headers, col_widths)] ret = [hl0, "| "+" | ".join(frmtd)+" |", hl1] i0 = 0 for i, row_height in enumerate(row_heights): if i > 0: ret.append(hl0) for incr in range(row_height): frmtd = ["{0:{1}}".format(x, width) for x, width in zip(new_data[i0+incr], col_widths)] ret.append("| "+" | ".join(frmtd)+" |") i0 += row_height ret.append(hl0) return ret
Creates reStructuredText table (grid format), allowing for multiline cells Arguments: data -- [((cell000, cell001, ...), (cell010, cell011, ...), ...), ...] headers -- sequence of strings: (header0, header1, ...) **Note** Tolerant to non-strings **Note** Cells may or may not be multiline >>> rest_table([["Eric", "Idle"], ["Graham", "Chapman"], ["Terry", "Gilliam"]], ["Name", "Surname"])
def _map_relations(relations, p, language='any'): ''' :param: :class:`list` relations: Relations to be mapped. These are concept or collection id's. :param: :class:`skosprovider.providers.VocabularyProvider` p: Provider to look up id's. :param string language: Language to render the relations' labels in :rtype: :class:`list` ''' ret = [] for r in relations: c = p.get_by_id(r) if c: ret.append(_map_relation(c, language)) else: log.warning( 'A relation references a concept or collection %d in provider %s that can not be found. Please check the integrity of your data.' % (r, p.get_vocabulary_id()) ) return ref _map_relations(relations, p, language='any'): ''' :param: :class:`list` relations: Relations to be mapped. These are concept or collection id's. :param: :class:`skosprovider.providers.VocabularyProvider` p: Provider to look up id's. :param string language: Language to render the relations' labels in :rtype: :class:`list` ''' ret = [] for r in relations: c = p.get_by_id(r) if c: ret.append(_map_relation(c, language)) else: log.warning( 'A relation references a concept or collection %d in provider %s that can not be found. Please check the integrity of your data.' % (r, p.get_vocabulary_id()) ) return ret
:param: :class:`list` relations: Relations to be mapped. These are concept or collection id's. :param: :class:`skosprovider.providers.VocabularyProvider` p: Provider to look up id's. :param string language: Language to render the relations' labels in :rtype: :class:`list`
def _map_relation(c, language='any'): label = c.label(language) return { 'id': c.id, 'type': c.type, 'uri': c.uri, 'label': label.label if label else None }
Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict`
def note_adapter(obj, request): ''' Adapter for rendering a :class:`skosprovider.skos.Note` to json. :param skosprovider.skos.Note obj: The note to be rendered. :rtype: :class:`dict` ''' return { 'note': obj.note, 'type': obj.type, 'language': obj.language, 'markup': obj.markup f note_adapter(obj, request): ''' Adapter for rendering a :class:`skosprovider.skos.Note` to json. :param skosprovider.skos.Note obj: The note to be rendered. :rtype: :class:`dict` ''' return { 'note': obj.note, 'type': obj.type, 'language': obj.language, 'markup': obj.markup }
Adapter for rendering a :class:`skosprovider.skos.Note` to json. :param skosprovider.skos.Note obj: The note to be rendered. :rtype: :class:`dict`
def get_indicators(self): response = self._get('', 'get-indicators') response['message'] = "%i indicators:\n%s" % ( len(response['indicators']), "\n".join(response['indicators']) ) return response
List indicators available on the remote instance.
def to_unicode(obj, encoding='utf-8'): if isinstance(obj, basestring): if not isinstance(obj, unicode): obj = unicode(obj, encoding) return obj
Convert obj to unicode (if it can be be converted) from http://farmdev.com/talks/unicode/
def besttype(x, encoding="utf-8", percentify=True): def unicodify(x): return to_unicode(x, encoding) def percent(x): try: if x.endswith("%"): x = float(x[:-1]) / 100. else: raise ValueError except (AttributeError, ValueError): raise ValueError return x x = unicodify(x) # make unicode as soon as possible try: x = x.strip() except AttributeError: pass m = re.match(r"""(?P<quote>['"])(?P<value>.*)(?P=quote)$""", x) # matches "<value>" or '<value>' where <value> COULD contain " or '! if m is None: # not a quoted string, try different types for converter in int, float, percent, unicodify: # try them in increasing order of lenience try: return converter(x) except ValueError: pass else: # quoted string x = unicodify(m.group('value')) return x
Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only important that it begins and ends with either single or double quotes. *percentify* = ``True`` turns "34.4%" into the float 0.344. .. Note:: Strings will be returned as Unicode strings (using :func:`unicode`), based on the *encoding* argument, which is utf-8 by default.
def _onsuccess(cls, kmsg, result): logger.info( "{}.Success: {}[{}]: {}".format( cls.__name__, kmsg.entrypoint, kmsg.uuid, result ), extra=dict( kmsg=kmsg.dump(), kresult=ResultSchema().dump(result) if result else dict() ) ) return cls.onsuccess(kmsg, result)
To execute on execution success :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result
def _onerror(cls, kmsg, result): logger.error( "{}.Failed: {}[{}]: {}".format( cls.__name__, kmsg.entrypoint, kmsg.uuid, result ), extra=dict( kmsg=kmsg.dump(), kresult=ResultSchema().dump(result) if result else dict() ) ) return cls.onerror(kmsg, result)
To execute on execution failure :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result
def _onmessage(cls, kmsg): logger.debug( "{}.ReceivedMessage {}[{}]".format( cls.__name__, kmsg.entrypoint, kmsg.uuid ), extra=dict(kmsg=kmsg.dump()) ) return cls.onmessage(kmsg)
Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message
def register(cls, name, entrypoint): if not issubclass(entrypoint, Entrypoint): raise ValidationError( "Invalid type for entry '{}', MUST implement " "kser.entry.Entrypoint".format(name), extra=dict(entrypoint=name) ) cls.ENTRYPOINTS[name] = entrypoint logger.debug("{}.Registered: {}".format(cls.__name__, name))
Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :raises ValidationError: Invalid entry
def run(cls, raw_data): logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.ImportError: Failed to load data from kafka: {}".format( cls.__name__, exc ), extra=dict(kafka_raw_data=raw_data) ) return Result.from_exception(exc) try: cls.start_processing(kmsg) if kmsg.entrypoint not in cls.ENTRYPOINTS: raise ValidationError( "Entrypoint '{}' not registred".format(kmsg.entrypoint), extra=dict( uuid=kmsg.uuid, entrypoint=kmsg.entrypoint, allowed=list(cls.ENTRYPOINTS.keys()) ) ) result = cls.ENTRYPOINTS[kmsg.entrypoint].from_Message( kmsg ).execute() except Exception as exc: result = Result.from_exception(exc, kmsg.uuid) finally: cls.stop_processing() # noinspection PyUnboundLocalVariable if result and result.retcode < 300: return cls._onsuccess(kmsg=kmsg, result=result) else: return cls._onerror(kmsg=kmsg, result=result)
description of run
def interval_condition(value, inf, sup, dist): return (value > inf - dist and value < sup + dist)
Checks if value belongs to the interval [inf - dist, sup + dist].
def deactivate(self, node_id): node = self.node_list[node_id] self.node_list[node_id] = node._replace(active=False)
Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the output of a nearest_point query. Note: The node is not removed from the tree, its data is steel available. Args: node_id (int): The node identifier (given to the user after its insertion).
def insert(self, point, data=None): assert len(point) == self.k if self.size == 0: if self.region is None: self.region = [[-math.inf, math.inf]] * self.k axis = 0 return self.new_node(point, self.region, axis, data) # Iteratively descends to one leaf current_id = 0 while True: parent_node = self.node_list[current_id] axis = parent_node.axis if point[axis] < parent_node.point[axis]: next_id, left = parent_node.left, True else: next_id, left = parent_node.right, False if next_id is None: break current_id = next_id # Get the region delimited by the parent node region = parent_node.region[:] region[axis] = parent_node.region[axis][:] # Limit to the child's region limit = parent_node.point[axis] # Update reference to the new node if left: self.node_list[current_id] = parent_node._replace(left=self.size) region[axis][1] = limit else: self.node_list[current_id] = parent_node._replace(right=self.size) region[axis][0] = limit return self.new_node(point, region, (axis + 1) % self.k, data)
Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, optional): The information stored by the node. Returns: int: The identifier of the new node. Example: >>> tree = Tree(4, 800) >>> point = (3, 7) >>> data = {'name': Fresnel, 'label': blue, 'speed': 98.2} >>> node_id = tree.insert(point, data)
def find_nearest_point(self, query, dist_fun=euclidean_dist): def get_properties(node_id): return self.node_list[node_id][:6] return nearest_point(query, 0, get_properties, dist_fun)
Find the point in the tree that minimizes the distance to the query. Args: query (:obj:`tuple` of float or int): Stores the position of the node. dist_fun (:obj:`function`, optional): The distance function, euclidean distance by default. Returns: :obj:`tuple`: Tuple of length 2, where the first element is the identifier of the nearest node, the second is the distance to the query. Example: >>> tree = Tree(2, 3) >>> tree.insert((0, 0)) >>> tree.insert((3, 5)) >>> tree.insert((-1, 7)) >>> query = (-1, 8) >>> nearest_node_id, dist = tree.find_nearest_point(query) >>> dist 1
def set_to_public(self, request, queryset): queryset.update(is_public=True, modified=now())
Set one or several releases to public
def loads(cls, json_data): try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
description of load
def format(self, response): res = self._prepare_response(response) res.content = self._format_data(res.content, self.charset) return self._finalize_response(res)
Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: devil's ``Response`` object or the data itself. May also be ``None``. :return: django's ``HttpResponse`` todo: this shouldn't change the given response. only return the formatted response.
def parse(self, data, charset=None): charset = charset or self.charset return self._parse_data(data, charset)
Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param charset: the charset of the data. Uses datamapper's default (``self.charset``) if not given. :returns:
def _decode_data(self, data, charset): try: return smart_unicode(data, charset) except UnicodeDecodeError: raise errors.BadRequest('wrong charset')
Decode string data. :returns: unicode string
def _parse_data(self, data, charset): return self._decode_data(data, charset) if data else u''
Parse the data :param data: the data (may be None)
def _finalize_response(self, response): res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set separately to allow zero res.status_code = response.code return res
Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse``
def register_mapper(self, mapper, content_type, shortname=None): self._check_mapper(mapper) cont_type_names = self._get_content_type_names(content_type, shortname) self._datamappers.update(dict([(name, mapper) for name in cont_type_names]))
Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``format()`` functions.
def select_formatter(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from accept header mapper_name = self._get_name_from_accept(request) if mapper_name: return self._get_mapper(mapper_name) # 4. use resource's default if resource.default_mapper: return resource.default_mapper # 5. use manager's default return self._get_default_mapper()
Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invoked resource
def select_parser(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from content type mapper_name = self._get_name_from_content_type(request) if mapper_name: return self._get_mapper(mapper_name) # 3. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 4. use resource's default if resource.default_mapper: return resource.default_mapper # 5. use manager's default return self._get_default_mapper()
Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked resource
def get_mapper_by_content_type(self, content_type): content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
Returs mapper based on the content type.
def _get_mapper(self, mapper_name): if mapper_name in self._datamappers: # mapper found return self._datamappers[mapper_name] else: # unsupported format return self._unknown_format(mapper_name)
Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable if we don't support the requested format.
def _get_name_from_content_type(self, request): content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
Get name from Content-Type header
def _get_name_from_accept(self, request): accepts = util.parse_accept_header(request.META.get("HTTP_ACCEPT", "")) if not accepts: return None for accept in accepts: if accept[0] in self._datamappers: return accept[0] raise errors.NotAcceptable()
Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the preferred mapper based on the accept header or ``None``.
def _get_name_from_url(self, request): format = request.GET.get('format', None) if not format: match = self._format_query_pattern.match(request.path) if match and match.group('format'): format = match.group('format') return format
Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json). :returns: short name of the mapper or ``None`` if not found.
def _check_mapper(self, mapper): if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise ValueError('mapper must implement format()')
Check that the mapper has valid signature.
def cleanup(self, cluster): if self._storage_path and os.path.exists(self._storage_path): fname = '%s.%s' % (AnsibleSetupProvider.inventory_file_ending, cluster.name) inventory_path = os.path.join(self._storage_path, fname) if os.path.exists(inventory_path): try: os.unlink(inventory_path) if self._storage_path_tmp: if len(os.listdir(self._storage_path)) == 0: shutil.rmtree(self._storage_path) except OSError as ex: log.warning( "AnsibileProvider: Ignoring error while deleting " "inventory file %s: %s", inventory_path, ex)
Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster`
def await_task(self, task_id, service_id, callback_fn=None, sleep_sec=15): while True: import time time.sleep(sleep_sec) task_info = self.__metadb.one(""" SELECT id, service_id, status, result_data FROM job.task WHERE id=:task_id::uuid AND service_id=:service_id::job.service_id LIMIT 1 """, { "task_id": task_id, "service_id": service_id, }) self.log.info("Ждем выполнения задачи", { "task_info": task_info }) if task_info is None: break is_finish = task_info['status'] != 'NEW' and task_info['status'] != 'PROCESSING' if callback_fn: # Уведомляем вызывающего callback_fn(task_info, is_finish) if is_finish: break
Подождать выполнения задачи запускатора :param task_id: ID задачи, за которой нужно следить :param service_id: ID сервиса :param callback_fn: Функция обратного вызова, в нее будет передаваться task_info и is_finish как признак, что обработка завершена :param sleep_sec: задержка между проверкой по БД. Не рекомендуется делать меньше 10, так как это может очень сильно ударить по производительности БД :return: void
def submit(self, service_id: str, data: dict = None): if self.__app.starter_api_url == 'http://STUB_URL': self.log.info('STARTER DEV. Задача условно поставлена', { "service_id": service_id, "data": data, }) return task = {"serviceId": service_id, "data": data} url = self.__app.starter_api_url + '/services/' + service_id + '/tasks' last_e = None for _idx in range(self.max_retries): try: resp = requests.post( url=url, data=json.dumps(task), headers=self.headers, timeout=15 ) try: return json.loads(resp.text) except Exception: raise IOError("Starter response read error: " + resp.text) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e: # При ошибках подключения пытаемся еще раз last_e = e sleep(3) raise last_e
Отправить задачу в запускатор :param service_id: ID службы. Например "meta.docs_generate" :param data: Полезная нагрузка задачи :return: dict
def parse_version_string(version_string): components = version_string.split('-') + [None, None] version = list(map(int, components[0].split('.'))) build_tag = components[1] if components[1] else BUILD_TAG build_number = int(components[2]) if components[2] else components[2] return (version, build_tag, build_number)
Parse a version string into it's components. >>> parse_version_string("0.1") ([0, 1], 'jenkins', None) >>> parse_version_string("0.3.2-jenkins-3447876") ([0, 3, 2], 'jenkins', 3447876)
def format_version(version, build_number=None, build_tag=BUILD_TAG): formatted_version = ".".join(map(str, version)) if build_number is not None: return "{formatted_version}-{build_tag}-{build_number}".format(**locals()) return formatted_version
Format a version string for use in packaging. >>> format_version([0,3,5]) '0.3.5' >>> format_version([8, 8, 9], 23676) '8.8.9-jenkins-23676' >>> format_version([8, 8, 9], 23676, 'koekjes') '8.8.9-koekjes-23676'
def based_on(self, based_on): allowed_values = ["shippingAddress", "billingAddress"] if based_on is not None and based_on not in allowed_values: raise ValueError( "Invalid value for `based_on` ({0}), must be one of {1}" .format(based_on, allowed_values) ) self._based_on = based_on
Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str
def create_tax_rate(cls, tax_rate, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_tax_rate_with_http_info(tax_rate, **kwargs) else: (data) = cls._create_tax_rate_with_http_info(tax_rate, **kwargs) return data
Create TaxRate Create a new TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_tax_rate(tax_rate, async=True) >>> result = thread.get() :param async bool :param TaxRate tax_rate: Attributes of taxRate to create (required) :return: TaxRate If the method is called asynchronously, returns the request thread.