INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Parse the result element of the observation type
def _parse_result(self): ''' Parse the result element of the observation type ''' if self.result is not None: result = self.result.find(nspv( "wml2:MeasurementTimeseries")) self.result = MeasurementTimeseries(result)
implements Requirement 5 (/ req/ core/ conformance - op )
def conformance(self): """ implements Requirement 5 (/req/core/conformance-op) @returns: conformance object """ url = self._build_url('conformance') LOGGER.debug('Request: {}'.format(url)) response = requests.get(url, headers=REQUEST_HEADERS).json() return response
implements Requirement 15 (/ req/ core/ sfc - md - op )
def collection(self, collection_name): """ implements Requirement 15 (/req/core/sfc-md-op) @type collection_name: string @param collection_name: name of collection @returns: feature collection metadata """ path = 'collections/{}'.format(collection_name) url = self._build_url(path) LOGGER.debug('Request: {}'.format(url)) response = requests.get(url, headers=REQUEST_HEADERS).json() return response
implements Requirement 17 (/ req/ core/ fc - op )
def collection_items(self, collection_name, **kwargs): """ implements Requirement 17 (/req/core/fc-op) @type collection_name: string @param collection_name: name of collection @type bbox: list @param bbox: list of minx,miny,maxx,maxy @type time: string @param time: time extent or time instant @type limit: int @param limit: limit number of features @type startindex: int @param startindex: start position of results @returns: feature results """ if 'bbox' in kwargs: kwargs['bbox'] = ','.join(kwargs['bbox']) path = 'collections/{}/items'.format(collection_name) url = self._build_url(path) LOGGER.debug('Request: {}'.format(url)) response = requests.get(url, headers=REQUEST_HEADERS, params=kwargs).json() return response
helper function to build a WFS 3. 0 URL
def _build_url(self, path=None): """ helper function to build a WFS 3.0 URL @type path: string @param path: path of WFS URL @returns: fully constructed URL path """ url = self.url if self.url_query_string is not None: LOGGER.debug('base URL has a query string') url = urljoin(url, path) url = '?'.join([url, self.url_query_string]) else: url = urljoin(url, path) LOGGER.debug('URL: {}'.format(url)) return url
Parses DescribeFeatureType response and creates schema compatible with: class: fiona
def get_schema(url, typename, version='1.0.0', timeout=30, username=None, password=None): """Parses DescribeFeatureType response and creates schema compatible with :class:`fiona` :param str url: url of the service :param str version: version of the service :param str typename: name of the layer :param int timeout: request timeout """ url = _get_describefeaturetype_url(url, version, typename) res = openURL(url, timeout=timeout, username=username, password=password) root = etree.fromstring(res.read()) if ':' in typename: typename = typename.split(':')[1] type_element = findall(root, '{%s}element' % XS_NAMESPACE, attribute_name='name', attribute_value=typename)[0] complex_type = type_element.attrib['type'].split(":")[1] elements = _get_elements(complex_type, root) nsmap = None if hasattr(root, 'nsmap'): nsmap = root.nsmap return _construct_schema(elements, nsmap)
Get attribute elements
def _get_elements(complex_type, root): """Get attribute elements """ found_elements = [] element = findall(root, '{%s}complexType' % XS_NAMESPACE, attribute_name='name', attribute_value=complex_type)[0] found_elements = findall(element, '{%s}element' % XS_NAMESPACE) return found_elements
Consruct fiona schema based on given elements
def _construct_schema(elements, nsmap): """Consruct fiona schema based on given elements :param list Element: list of elements :param dict nsmap: namespace map :return dict: schema """ schema = { 'properties': {}, 'geometry': None } schema_key = None gml_key = None # if nsmap is defined, use it if nsmap: for key in nsmap: if nsmap[key] == XS_NAMESPACE: schema_key = key if nsmap[key] in GML_NAMESPACES: gml_key = key # if no nsmap is defined, we have to guess else: gml_key = 'gml' schema_key = 'xsd' mappings = { 'PointPropertyType': 'Point', 'PolygonPropertyType': 'Polygon', 'LineStringPropertyType': 'LineString', 'MultiPointPropertyType': 'MultiPoint', 'MultiLineStringPropertyType': 'MultiLineString', 'MultiPolygonPropertyType': 'MultiPolygon', 'MultiGeometryPropertyType': 'MultiGeometry', 'GeometryPropertyType': 'GeometryCollection', 'SurfacePropertyType': '3D Polygon', 'MultiSurfacePropertyType': '3D MultiPolygon' } for element in elements: data_type = element.attrib['type'].replace(gml_key + ':', '') name = element.attrib['name'] if data_type in mappings: schema['geometry'] = mappings[data_type] schema['geometry_column'] = name else: schema['properties'][name] = data_type.replace(schema_key+':', '') if schema['properties'] or schema['geometry']: return schema else: return None
Get url for describefeaturetype request
def _get_describefeaturetype_url(url, version, typename): """Get url for describefeaturetype request :return str: url """ query_string = [] if url.find('?') != -1: query_string = cgi.parse_qsl(url.split('?')[1]) params = [x[0] for x in query_string] if 'service' not in params: query_string.append(('service', 'WFS')) if 'request' not in params: query_string.append(('request', 'DescribeFeatureType')) if 'version' not in params: query_string.append(('version', version)) query_string.append(('typeName', typename)) urlqs = urlencode(tuple(query_string)) return url.split('?')[0] + '?' + urlqs
use ComplexDataInput with a reference to a document
def complex_input_with_reference(): """ use ComplexDataInput with a reference to a document """ print("\ncomplex_input_with_reference ...") wps = WebProcessingService('http://localhost:8094/wps', verbose=verbose) processid = 'wordcount' textdoc = ComplexDataInput("http://www.gutenberg.org/files/28885/28885-h/28885-h.htm") # alice in wonderland inputs = [("text", textdoc)] # list of tuple (output identifier, asReference attribute, mimeType attribute) # when asReference or mimeType is None - the wps service will use its default option outputs = [("output",True,'some/mime-type')] execution = wps.execute(processid, inputs, output=outputs) monitorExecution(execution) # show status print('percent complete', execution.percentCompleted) print('status message', execution.statusMessage) for output in execution.processOutputs: print('identifier=%s, dataType=%s, data=%s, reference=%s' % (output.identifier, output.dataType, output.data, output.reference))
Get the list of Movie genres.
def movie_list(self, **kwargs): """ Get the list of Movie genres. Args: language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('movie_list') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of TV genres.
def tv_list(self, **kwargs): """ Get the list of TV genres. Args: language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('tv_list') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of movies for a particular genre by id. By default only movies with 10 or more votes are included.
def movies(self, **kwargs): """ Get the list of movies for a particular genre by id. By default, only movies with 10 or more votes are included. Args: page: (optional) Minimum 1, maximum 1000. language: (optional) ISO 639-1 code. include_all_movies: (optional) Toggle the inclusion of all movies and not just those with 10 or more ratings. Expected value is: True or False. include_adult: (optional) Toggle the inclusion of adult titles. Expected value is: True or False. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('movies') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the basic movie information for a specific movie id.
def info(self, **kwargs): """ Get the basic movie information for a specific movie id. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the alternative titles for a specific movie id.
def alternative_titles(self, **kwargs): """ Get the alternative titles for a specific movie id. Args: country: (optional) ISO 3166-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('alternative_titles') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the cast and crew information for a specific movie id.
def credits(self, **kwargs): """ Get the cast and crew information for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the external ids for a specific movie id.
def external_ids(self, **kwargs): """ Get the external ids for a specific movie id. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('external_ids') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the images ( posters and backdrops ) for a specific movie id.
def images(self, **kwargs): """ Get the images (posters and backdrops) for a specific movie id. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. include_image_language: (optional) Comma separated, a valid ISO 69-1. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('images') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the plot keywords for a specific movie id.
def keywords(self): """ Get the plot keywords for a specific movie id. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('keywords') response = self._GET(path) self._set_attrs_to_values(response) return response
Get a list of recommended movies for a movie.
def recommendations(self, **kwargs): """ Get a list of recommended movies for a movie. Args: language: (optional) ISO 639-1 code. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('recommendations') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the release dates and certification for a specific movie id.
def release_dates(self, **kwargs): """ Get the release dates and certification for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('release_dates') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the release date and certification information by country for a specific movie id.
def releases(self, **kwargs): """ Get the release date and certification information by country for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('releases') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the videos ( trailers teasers clips etc... ) for a specific movie id.
def videos(self, **kwargs): """ Get the videos (trailers, teasers, clips, etc...) for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('videos') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the translations for a specific movie id.
def translations(self, **kwargs): """ Get the translations for a specific movie id. Args: append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('translations') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the similar movies for a specific movie id.
def similar_movies(self, **kwargs): """ Get the similar movies for a specific movie id. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('similar_movies') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the reviews for a particular movie id.
def reviews(self, **kwargs): """ Get the reviews for a particular movie id. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any movie method. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('reviews') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the changes for a specific movie id.
def changes(self, **kwargs): """ Get the changes for a specific movie id. Changes are grouped by key, and ordered by date in descending order. By default, only the last 24 hours of changes are returned. The maximum number of days that can be returned in a single request is 14. The language is present on fields that are translatable. Args: start_date: (optional) Expected format is 'YYYY-MM-DD'. end_date: (optional) Expected format is 'YYYY-MM-DD'. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('changes') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of upcoming movies. This list refreshes every day. The maximum number of items this list will include is 100.
def upcoming(self, **kwargs): """ Get the list of upcoming movies. This list refreshes every day. The maximum number of items this list will include is 100. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the API. """ path = self._get_path('upcoming') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of movies playing in theatres. This list refreshes every day. The maximum number of items this list will include is 100.
def now_playing(self, **kwargs): """ Get the list of movies playing in theatres. This list refreshes every day. The maximum number of items this list will include is 100. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the API. """ path = self._get_path('now_playing') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of popular movies on The Movie Database. This list refreshes every day.
def popular(self, **kwargs): """ Get the list of popular movies on The Movie Database. This list refreshes every day. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the API. """ path = self._get_path('popular') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of top rated movies. By default this list will only include movies that have 10 or more votes. This list refreshes every day.
def top_rated(self, **kwargs): """ Get the list of top rated movies. By default, this list will only include movies that have 10 or more votes. This list refreshes every day. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict representation of the JSON returned from the API. """ path = self._get_path('top_rated') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
This method lets users get the status of whether or not the movie has been rated or added to their favourite or watch lists. A valid session id is required.
def account_states(self, **kwargs): """ This method lets users get the status of whether or not the movie has been rated or added to their favourite or watch lists. A valid session id is required. Args: session_id: see Authentication. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('account_states') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
This method lets users rate a movie. A valid session id or guest session id is required.
def rating(self, **kwargs): """ This method lets users rate a movie. A valid session id or guest session id is required. Args: session_id: see Authentication. guest_session_id: see Authentication. value: Rating value. Returns: A dict representation of the JSON returned from the API. """ path = self._get_id_path('rating') payload = { 'value': kwargs.pop('value', None), } response = self._POST(path, kwargs, payload) self._set_attrs_to_values(response) return response
Get the movie credits for a specific person id.
def movie_credits(self, **kwargs): """ Get the movie credits for a specific person id. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any person method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('movie_credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the TV credits for a specific person id.
def tv_credits(self, **kwargs): """ Get the TV credits for a specific person id. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any person method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('tv_credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the combined ( movie and TV ) credits for a specific person id.
def combined_credits(self, **kwargs): """ Get the combined (movie and TV) credits for a specific person id. To get the expanded details for each TV record, call the /credit method with the provided credit_id. This will provide details about which episode and/or season the credit is for. Args: language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any person method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('combined_credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for people.
def info(self, **kwargs): """ Get the detailed information about a particular credit record. This is currently only supported with the new credit model found in TV. These ids can be found from any TV credit response as well as the tv_credits and combined_credits methods for people. The episodes object returns a list of episodes and are generally going to be guest stars. The season array will return a list of season numbers. Season credits are credits that were marked with the "add to every season" option in the editing interface and are assumed to be "season regulars". Args: language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_credit_id_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Discover TV shows by different types of data like average rating number of votes genres the network they aired on and air dates.
def tv(self, **kwargs): """ Discover TV shows by different types of data like average rating, number of votes, genres, the network they aired on and air dates. Args: page: (optional) Minimum 1, maximum 1000. language: (optional) ISO 639-1 code. sort_by: (optional) Available options are 'vote_average.desc', 'vote_average.asc', 'first_air_date.desc', 'first_air_date.asc', 'popularity.desc', 'popularity.asc' first_air_year: (optional) Filter the results release dates to matches that include this value. Expected value is a year. vote_count.gte or vote_count_gte: (optional) Only include TV shows that are equal to, or have vote count higher than this value. Expected value is an integer. vote_average.gte or vote_average_gte: (optional) Only include TV shows that are equal to, or have a higher average rating than this value. Expected value is a float. with_genres: (optional) Only include TV shows with the specified genres. Expected value is an integer (the id of a genre). Multiple valued can be specified. Comma separated indicates an 'AND' query, while a pipe (|) separated value indicates an 'OR'. with_networks: (optional) Filter TV shows to include a specific network. Expected value is an integer (the id of a network). They can be comma separated to indicate an 'AND' query. first_air_date.gte or first_air_date_gte: (optional) The minimum release to include. Expected format is 'YYYY-MM-DD'. first_air_date.lte or first_air_date_lte: (optional) The maximum release to include. Expected format is 'YYYY-MM-DD'. Returns: A dict respresentation of the JSON returned from the API. """ # Periods are not allowed in keyword arguments but several API # arguments contain periods. See both usages in tests/test_discover.py. for param in kwargs: if '_lte' in param: kwargs[param.replace('_lte', '.lte')] = kwargs.pop(param) if '_gte' in param: kwargs[param.replace('_gte', '.gte')] = kwargs.pop(param) path = self._get_path('tv') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the system wide configuration info.
def info(self, **kwargs): """ Get the system wide configuration info. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of supported certifications for movies.
def list(self, **kwargs): """ Get the list of supported certifications for movies. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('movie_list') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the basic information for an account.
def info(self, **kwargs): """ Get the basic information for an account. Call this method first, before calling other Account methods. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('info') kwargs.update({'session_id': self.session_id}) response = self._GET(path, kwargs) self.id = response['id'] self._set_attrs_to_values(response) return response
Get the list of movies on an account watchlist.
def watchlist_movies(self, **kwargs): """ Get the list of movies on an account watchlist. Args: page: (optional) Minimum 1, maximum 1000. sort_by: (optional) 'created_at.asc' | 'created_at.desc' language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('watchlist_movies') kwargs.update({'session_id': self.session_id}) response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Generate a valid request token for user based authentication.
def token_new(self, **kwargs): """ Generate a valid request token for user based authentication. A request token is required to ask the user for permission to access their account. After obtaining the request_token, either: (1) Direct your user to: https://www.themoviedb.org/authenticate/REQUEST_TOKEN or: (2) Call token_validate_with_login() below. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('token_new') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Authenticate a user with a TMDb username and password. The user must have a verified email address and be registered on TMDb.
def token_validate_with_login(self, **kwargs): """ Authenticate a user with a TMDb username and password. The user must have a verified email address and be registered on TMDb. Args: request_token: The token you generated for the user to approve. username: The user's username on TMDb. password: The user's password on TMDb. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('token_validate_with_login') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Generate a session id for user based authentication.
def session_new(self, **kwargs): """ Generate a session id for user based authentication. A session id is required in order to use any of the write methods. Args: request_token: The token you generated for the user to approve. The token needs to be approved before being used here. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('session_new') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Generate a guest session id.
def guest_session_new(self, **kwargs): """ Generate a guest session id. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('guest_session_new') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get a list of rated moview for a specific guest session id.
def rated_movies(self, **kwargs): """ Get a list of rated moview for a specific guest session id. Args: page: (optional) Minimum 1, maximum 1000. sort_by: (optional) 'created_at.asc' | 'created_at.desc' language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_guest_session_id_path('rated_movies') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Check to see if a movie id is already added to a list.
def item_status(self, **kwargs): """ Check to see if a movie id is already added to a list. Args: movie_id: The id of the movie. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('item_status') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Create a new list.
def create_list(self, **kwargs): """ Create a new list. A valid session id is required. Args: name: Name of the list. description: Description of the list. language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('create_list') kwargs.update({'session_id': self.session_id}) payload = { 'name': kwargs.pop('name', None), 'description': kwargs.pop('description', None), } if 'language' in kwargs: payload['language'] = kwargs['language'] response = self._POST(path, kwargs, payload) self._set_attrs_to_values(response) return response
Delete movies from a list that the user created.
def remove_item(self, **kwargs): """ Delete movies from a list that the user created. A valid session id is required. Args: media_id: A movie id. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('remove_item') kwargs.update({'session_id': self.session_id}) payload = { 'media_id': kwargs.pop('media_id', None), } response = self._POST(path, kwargs, payload) self._set_attrs_to_values(response) return response
Clears all of the items within a list. This is an irreversible action and should be treated with caution.
def clear_list(self, **kwargs): """ Clears all of the items within a list. This is an irreversible action and should be treated with caution. A valid session id is required. Args: confirm: True (do it) | False (don't do it) Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('clear') kwargs.update({'session_id': self.session_id}) payload = {} response = self._POST(path, kwargs, payload) self._set_attrs_to_values(response) return response
Get the content ratings for a TV Series.
def content_ratings(self, **kwargs): """ Get the content ratings for a TV Series. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any collection method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('content_ratings') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the similar TV series for a specific TV series id.
def similar(self, **kwargs): """ Get the similar TV series for a specific TV series id. Args: page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. append_to_response: (optional) Comma separated, any TV method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_id_path('similar') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of TV shows that are currently on the air. This query looks for any TV show that has an episode with an air date in the next 7 days.
def on_the_air(self, **kwargs): """ Get the list of TV shows that are currently on the air. This query looks for any TV show that has an episode with an air date in the next 7 days. Args: page: (optional) Minimum 1, maximum 1000. language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('on_the_air') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the list of TV shows that air today. Without a specified timezone this query defaults to EST ( Eastern Time UTC - 05: 00 ).
def airing_today(self, **kwargs): """ Get the list of TV shows that air today. Without a specified timezone, this query defaults to EST (Eastern Time UTC-05:00). Args: page: (optional) Minimum 1, maximum 1000. language: (optional) ISO 639 code. timezone: (optional) Valid value from the list of timezones. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('airing_today') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the primary information about a TV season by its season number.
def info(self, **kwargs): """ Get the primary information about a TV season by its season number. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any TV series method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the cast & crew credits for a TV season by season number.
def credits(self, **kwargs): """ Get the cast & crew credits for a TV season by season number. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the external ids that we have stored for a TV season by season number.
def external_ids(self, **kwargs): """ Get the external ids that we have stored for a TV season by season number. Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('external_ids') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the images ( posters ) that we have stored for a TV season by season number.
def images(self, **kwargs): """ Get the images (posters) that we have stored for a TV season by season number. Args: language: (optional) ISO 639 code. include_image_language: (optional) Comma separated, a valid ISO 69-1. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('images') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the videos that have been added to a TV season ( trailers teasers etc... ).
def videos(self, **kwargs): """ Get the videos that have been added to a TV season (trailers, teasers, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_path('videos') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the primary information about a TV episode by combination of a season and episode number.
def info(self, **kwargs): """ Get the primary information about a TV episode by combination of a season and episode number. Args: language: (optional) ISO 639 code. append_to_response: (optional) Comma separated, any TV series method. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_episode_number_path('info') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the TV episode credits by combination of season and episode number.
def credits(self, **kwargs): """ Get the TV episode credits by combination of season and episode number. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_episode_number_path('credits') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the external ids for a TV episode by combination of a season and episode number.
def external_ids(self, **kwargs): """ Get the external ids for a TV episode by combination of a season and episode number. Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_episode_number_path( 'external_ids') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the images ( episode stills ) for a TV episode by combination of a season and episode number. Since episode stills don t have a language this call will always return all images.
def images(self, **kwargs): """ Get the images (episode stills) for a TV episode by combination of a season and episode number. Since episode stills don't have a language, this call will always return all images. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_episode_number_path('images') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get the videos that have been added to a TV episode ( teasers clips etc... ).
def videos(self, **kwargs): """ Get the videos that have been added to a TV episode (teasers, clips, etc...). Args: language: (optional) ISO 639 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_series_id_season_number_episode_number_path('videos') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Set attributes to dictionary values.
def _set_attrs_to_values(self, response={}): """ Set attributes to dictionary values. - e.g. >>> import tmdbsimple as tmdb >>> movie = tmdb.Movies(103332) >>> response = movie.info() >>> movie.title # instead of response['title'] """ if isinstance(response, dict): for key in response.keys(): if not hasattr(self, key) or not callable(getattr(self, key)): setattr(self, key, response[key])
Search for movies by title.
def movie(self, **kwargs): """ Search for movies by title. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. include_adult: (optional) Toggle the inclusion of adult titles. Expected value is True or False. year: (optional) Filter the results release dates to matches that include this value. primary_release_year: (optional) Filter the results so that only the primary release dates have this value. search_type: (optional) By default, the search type is 'phrase'. This is almost guaranteed the option you will want. It's a great all purpose search type and by far the most tuned for every day querying. For those wanting more of an "autocomplete" type search, set this option to 'ngram'. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('movie') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search for collections by name.
def collection(self, **kwargs): """ Search for collections by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('collection') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search for TV shows by title.
def tv(self, **kwargs): """ Search for TV shows by title. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. first_air_date_year: (optional) Filter the results to only match shows that have a air date with with value. search_type: (optional) By default, the search type is 'phrase'. This is almost guaranteed the option you will want. It's a great all purpose search type and by far the most tuned for every day querying. For those wanting more of an "autocomplete" type search, set this option to 'ngram'. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('tv') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search for people by name.
def person(self, **kwargs): """ Search for people by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. include_adult: (optional) Toggle the inclusion of adult titles. Expected value is True or False. search_type: (optional) By default, the search type is 'phrase'. This is almost guaranteed the option you will want. It's a great all purpose search type and by far the most tuned for every day querying. For those wanting more of an "autocomplete" type search, set this option to 'ngram'. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('person') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search for companies by name.
def company(self, **kwargs): """ Search for companies by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('company') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search for keywords by name.
def keyword(self, **kwargs): """ Search for keywords by name. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('keyword') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Search the movie tv show and person collections with a single query.
def multi(self, **kwargs): """ Search the movie, tv show and person collections with a single query. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. include_adult: (optional) Toggle the inclusion of adult titles. Expected value is True or False. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('multi') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Normalize and tokenize text. This is lifted from NIST mteval - v11a. pl.
def normalize(s): '''Normalize and tokenize text. This is lifted from NIST mteval-v11a.pl.''' # Added to bypass NIST-style pre-processing of hyp and ref files -- wade if (nonorm): return s.split() try: s.split() except: s = " ".join(s) # language-independent part: for (pattern, replace) in normalize1: s = re.sub(pattern, replace, s) s = xml.sax.saxutils.unescape(s, {'"':'"'}) # language-dependent part (assuming Western languages): s = " %s " % s if not preserve_case: s = s.lower() # this might not be identical to the original return [tok for tok in normalize3.split(s) if tok and tok != ' ']
Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them.
def cook_refs(refs, n=4): '''Takes a list of reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them.''' refs = [normalize(ref) for ref in refs] maxcounts = {} for ref in refs: counts = count_ngrams(ref, n) for (ngram,count) in list(counts.items()): maxcounts[ngram] = max(maxcounts.get(ngram,0), count) return ([len(ref) for ref in refs], maxcounts)
Takes a reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. Also provides a set cause bleualign wants it
def cook_ref_set(ref, n=4): '''Takes a reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. Also provides a set cause bleualign wants it''' ref = normalize(ref) counts = count_ngrams(ref, n) return (len(ref), counts, frozenset(counts))
Complementary error function.
def erfcc(x): """Complementary error function.""" z = abs(x) t = 1 / (1 + 0.5 * z) r = t * math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (.37409196 + t * (.09678418 + t * (-.18628806 + t * (.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-.82215223 + t * .17087277))))))))) if (x >= 0.): return r else: return 2. - r
Returns the probability of the two sentences C { source_sentences [ i ] } C { target_sentences [ j ] } being aligned with a specific C { alignment }.
def align_probability(i, j, source_sentences, target_sentences, alignment, params): """Returns the probability of the two sentences C{source_sentences[i]}, C{target_sentences[j]} being aligned with a specific C{alignment}. @param i: The offset of the source sentence. @param j: The offset of the target sentence. @param source_sentences: The list of source sentence lengths. @param target_sentences: The list of target sentence lengths. @param alignment: The alignment type, a tuple of two integers. @param params: The sentence alignment parameters. @returns: The probability of a specific alignment between the two sentences, given the parameters. """ l_s = sum(source_sentences[i - offset] for offset in range(alignment[0])) l_t = sum(target_sentences[j - offset] for offset in range(alignment[1])) try: # actually, the paper says l_s * params.VARIANCE_CHARACTERS, this is based on the C # reference implementation. With l_s in the denominator, insertions are impossible. m = (l_s + l_t / params.AVERAGE_CHARACTERS) / 2 delta = (l_t - l_s * params.AVERAGE_CHARACTERS) / math.sqrt(m * params.VARIANCE_CHARACTERS) except ZeroDivisionError: delta = infinity return 2 * (1 - norm_cdf(abs(delta))) * params.PRIORS[alignment]
Creates the sentence alignment of two blocks of texts ( usually paragraphs ).
def align_blocks(source_sentences, target_sentences, params = LanguageIndependent): """Creates the sentence alignment of two blocks of texts (usually paragraphs). @param source_sentences: The list of source sentence lengths. @param target_sentences: The list of target sentence lengths. @param params: the sentence alignment parameters. @return: The sentence alignments, a list of index pairs. """ alignment_types = list(params.PRIORS.keys()) # there are always three rows in the history (with the last of them being filled) # and the rows are always |target_text| + 2, so that we never have to do # boundary checks D = [(len(target_sentences) + 2) * [0] for x in range(2)] # for the first sentence, only substitution, insertion or deletion are # allowed, and they are all equally likely ( == 1) D.append([0, 1]) try: D[-2][1] = 1 D[-2][2] = 1 except: pass backlinks = {} for i in range(len(source_sentences)): for j in range(len(target_sentences)): m = [] for a in alignment_types: k = D[-(1 + a[0])][j + 2 - a[1]] if k > 0: p = k * \ align_probability(i, j, source_sentences, target_sentences, a, params) m.append((p, a)) if len(m) > 0: v = max(m) backlinks[(i, j)] = v[1] D[-1].append(v[0]) else: backlinks[(i, j)] = (1, 1) D[-1].append(0) D.pop(0) D.append([0, 0]) return trace(backlinks, source_sentences, target_sentences)
Creates the sentence alignment of two texts.
def align_texts(source_blocks, target_blocks, params = LanguageIndependent): """Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of the sentences in this block. @param source_blocks: The list of blocks in the source text. @param target_blocks: The list of blocks in the target text. @param params: the sentence alignment parameters. @returns: A list of sentence alignment lists """ if len(source_blocks) != len(target_blocks): raise ValueError("Source and target texts do not have the same number of blocks.") return [align_blocks(source_block, target_block, params) for source_block, target_block in zip(source_blocks, target_blocks)]
Splits an iterator C { it } at values of C { split_value }.
def split_at(it, split_value): """Splits an iterator C{it} at values of C{split_value}. Each instance of C{split_value} is swallowed. The iterator produces subiterators which need to be consumed fully before the next subiterator can be used. """ def _chunk_iterator(first): v = first while v != split_value: yield v v = next(it) while True: yield _chunk_iterator(next(it))
Parses a stream of tokens and splits it into sentences ( using C { soft_delimiter } tokens ) and blocks ( using C { hard_delimiter } tokens ) for use with the L { align_texts } function.
def parse_token_stream(stream, soft_delimiter, hard_delimiter): """Parses a stream of tokens and splits it into sentences (using C{soft_delimiter} tokens) and blocks (using C{hard_delimiter} tokens) for use with the L{align_texts} function. """ return [ [sum(len(token) for token in sentence_it) for sentence_it in split_at(block_it, soft_delimiter)] for block_it in split_at(stream, hard_delimiter)]
r [ DEPRECATED ] Get descriptors from module.
def get_descriptors_from_module(mdl, submodule=False): r"""[DEPRECATED] Get descriptors from module. Parameters: mdl(module): module to search Returns: [Descriptor] """ warnings.warn("use get_descriptors_in_module", DeprecationWarning) __all__ = getattr(mdl, "__all__", None) if __all__ is None: __all__ = dir(mdl) all_functions = (getattr(mdl, name) for name in __all__ if name[:1] != "_") if submodule: descs = [ d for fn in all_functions if is_descriptor_class(fn) or isinstance(fn, ModuleType) for d in ( [fn] if is_descriptor_class(fn) else get_descriptors_from_module(fn, submodule=True) ) ] else: descs = [ fn for fn in all_functions if is_descriptor_class(fn) ] return descs
r Get descriptors in module.
def get_descriptors_in_module(mdl, submodule=True): r"""Get descriptors in module. Parameters: mdl(module): module to search submodule(bool): search recursively Returns: Iterator[Descriptor] """ __all__ = getattr(mdl, "__all__", None) if __all__ is None: __all__ = dir(mdl) all_values = (getattr(mdl, name) for name in __all__ if name[:1] != "_") if submodule: for v in all_values: if is_descriptor_class(v): yield v if isinstance(v, ModuleType): for v in get_descriptors_in_module(v, submodule=True): yield v else: for v in all_values: if is_descriptor_class(v): yield v
Register Descriptors from json descriptor objects.
def register_json(self, obj): """Register Descriptors from json descriptor objects. Parameters: obj(list or dict): descriptors to register """ if not isinstance(obj, list): obj = [obj] self.register(Descriptor.from_json(j) for j in obj)
r Register descriptors.
def register(self, desc, version=None, ignore_3D=False): r"""Register descriptors. Descriptor-like: * Descriptor instance: self * Descriptor class: use Descriptor.preset() method * module: use Descriptor-likes in module * Iterable: use Descriptor-likes in Iterable Parameters: desc(Descriptor-like): descriptors to register version(str): version ignore_3D(bool): ignore 3D descriptors """ if version is None: version = __version__ version = StrictVersion(version) return self._register(desc, version, ignore_3D)
Output message.
def echo(self, s, file=sys.stdout, end="\n"): """Output message. Parameters: s(str): message to output file(file-like): output to end(str): end mark of message Return: None """ p = getattr(self, "_progress_bar", None) if p is not None: p.write(s, file=file, end="\n") return print(s, file=file, end="\n")
r Calculate descriptors over mols.
def map(self, mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1): r"""Calculate descriptors over mols. Parameters: mols(Iterable[rdkit.Mol]): moleculars nproc(int): number of process to use. default: multiprocessing.cpu_count() nmols(int): number of all mols to use in progress-bar. default: mols.__len__() quiet(bool): don't show progress bar. default: False ipynb(bool): use ipython notebook progress bar. default: False id(int): conformer id to use. default: -1. Returns: Iterator[Result[scalar]] """ if nproc is None: nproc = cpu_count() if hasattr(mols, "__len__"): nmols = len(mols) if nproc == 1: return self._serial(mols, nmols=nmols, quiet=quiet, ipynb=ipynb, id=id) else: return self._parallel(mols, nproc, nmols=nmols, quiet=quiet, ipynb=ipynb, id=id)
r Calculate descriptors over mols.
def pandas(self, mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1): r"""Calculate descriptors over mols. Returns: pandas.DataFrame """ from .pandas_module import MordredDataFrame, Series if isinstance(mols, Series): index = mols.index else: index = None return MordredDataFrame( (list(r) for r in self.map(mols, nproc, nmols, quiet, ipynb, id)), columns=[str(d) for d in self.descriptors], index=index, )
r Check calculatable descriptor class or not.
def is_descriptor_class(desc, include_abstract=False): r"""Check calculatable descriptor class or not. Returns: bool """ return ( isinstance(desc, type) and issubclass(desc, Descriptor) and (True if include_abstract else not inspect.isabstract(desc)) )
Convert to json serializable dictionary.
def to_json(self): """Convert to json serializable dictionary. Returns: dict: dictionary of descriptor """ d, ps = self._to_json() if len(ps) == 0: return {"name": d} else: return {"name": d, "args": ps}
Get 3D coordinate.
def coord(self): """Get 3D coordinate. Returns: numpy.array[3, N]: coordinate matrix """ if not self.require_3D: self.fail(AttributeError("use 3D coordinate in 2D descriptor")) return self._context.get_coord(self)
[ contextmanager ] treat zero div as known exception.
def rethrow_zerodiv(self): """[contextmanager] treat zero div as known exception.""" with np.errstate(divide="raise", invalid="raise"): try: yield except (FloatingPointError, ZeroDivisionError) as e: self.fail(ZeroDivisionError(*e.args))
r Calculate atomic surface area.
def atomic_sa(self, i): r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float """ sa = 4.0 * np.pi * self.rads2[i] neighbors = self.neighbors.get(i) if neighbors is None: return sa XYZi = self.xyzs[i, np.newaxis].T sphere = self.sphere * self.rads[i] + XYZi N = sphere.shape[1] for j, _ in neighbors: XYZj = self.xyzs[j, np.newaxis].T d2 = (sphere - XYZj) ** 2 mask = (d2[0] + d2[1] + d2[2]) > self.rads2[j] sphere = np.compress(mask, sphere, axis=1) return sa * sphere.shape[1] / N
r Calculate all atomic surface area.
def surface_area(self): r"""Calculate all atomic surface area. :rtype: [float] """ return [self.atomic_sa(i) for i in range(len(self.rads))]
r Construct SurfaceArea from rdkit Mol type.
def from_mol(cls, mol, conformer=-1, solvent_radius=1.4, level=4): r"""Construct SurfaceArea from rdkit Mol type. :type mol: rdkit.Chem.Mol :param mol: input molecule :type conformer: int :param conformer: conformer id :type solvent_radius: float :param solvent_radius: solvent radius :type level: int :param level: mesh level :rtype: SurfaceArea """ rs = atoms_to_numpy(lambda a: vdw_radii[a.GetAtomicNum()] + solvent_radius, mol) conf = mol.GetConformer(conformer) ps = np.array([list(conf.GetAtomPosition(i)) for i in range(mol.GetNumAtoms())]) return cls(rs, ps, level)
Create Descriptor instance from json dict.
def _Descriptor_from_json(self, obj): """Create Descriptor instance from json dict. Parameters: obj(dict): descriptor dict Returns: Descriptor: descriptor """ descs = getattr(self, "_all_descriptors", None) if descs is None: from mordred import descriptors descs = { cls.__name__: cls for cls in get_descriptors_in_module(descriptors) } descs[ConstDescriptor.__name__] = ConstDescriptor self._all_descriptors = descs return _from_json(obj, descs)
r Replace missing value to value.
def fill_missing(self, value=np.nan): r"""Replace missing value to "value". Parameters: value: value that missing value is replaced Returns: Result """ return self.__class__( self.mol, [(value if is_missing(v) else v) for v in self.values()], self.keys(), )
r Delete missing value.
def drop_missing(self): r"""Delete missing value. Returns: Result """ newvalues = [] newdescs = [] for d, v in self.items(): if not is_missing(v): newvalues.append(v) newdescs.append(d) return self.__class__(self.mol, newvalues, newdescs)
r Get items.
def items(self): r"""Get items. Returns: Iterable[(Descriptor, value)] """ return ((k, v) for k, v in zip(self.keys(), self.values()))