code stringlengths 1 18.2k |
|---|
def _get_formatted_date(dataset_date, date_format=None): # type: (Optional[datetime], Optional[str]) -> Optional[str] """Get supplied dataset date as string in specified format. If no format is supplied, an ISO 8601 string is returned. Args: dataset_date (Optional[datetime.datetime]): dataset date in datetime.datetime ... |
if dataset_date: if date_format: return dataset_date.strftime(date_format) else: return dataset_date.date().isoformat() else: return None |
def get_dataset_date(self, date_format=None): # type: (Optional[str]) -> Optional[str] """Get dataset date as string in specified format. For range returns start date. If no format is supplied, an ISO 8601 string is returned. Args: date_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to None... |
self._get_formatted_date(dataset_date, date_format) |
def get_dataset_end_date(self, date_format=None): # type: (Optional[str]) -> Optional[str] """Get dataset date as string in specified format. For range returns start date. If no format is supplied, an ISO 8601 string is returned. Args: date_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to ... |
self._get_formatted_date(dataset_date, date_format) |
def set_dataset_date_from_datetime(self, dataset_date, dataset_end_date=None): # type: (datetime, Optional[datetime]) -> None """Set dataset date from datetime.datetime object Args: dataset_date (datetime.datetime): Dataset date dataset_end_date (Optional[datetime.datetime]): Dataset end date Returns: None """ start_da... |
def _parse_date(dataset_date, date_format): # type: (str, Optional[str]) -> datetime """Parse dataset date from string using specified format. If no format is supplied, the function will guess. For unambiguous formats, this should be fine. Args: dataset_date (str): Dataset date string date_format (Optional[str]): Date ... |
except (ValueError, OverflowError) as e: raisefrom(HDXError, 'Invalid dataset date!', e) else: try: return datetime.strptime(dataset_date, date_format) except ValueError as e: raisefrom(HDXError, 'Invalid dataset date!', e) |
def set_dataset_date(self, dataset_date, dataset_end_date=None, date_format=None): # type: (str, Optional[str], Optional[str]) -> None """Set dataset date from string using specified format. If no format is supplied, the function will guess. For unambiguous formats, this should be fine. Args: dataset_date (str): Datase... |
None """ parsed_date = self._parse_date(dataset_date, date_format) if dataset_end_date is None: self.set_dataset_date_from_datetime(parsed_date) else: parsed_end_date = self._parse_date(dataset_end_date, date_format) self.set_dataset_date_from_datetime(parsed_date, parsed_end_date) |
def set_dataset_year_range(self, dataset_year, dataset_end_year=None): # type: (Union[str, int], Optional[Union[str, int]]) -> None """Set dataset date as a range from year or start and end year. Args: dataset_year (Union[str, int]): Dataset year given as string or int dataset_end_year (Optional[Union[str, int]]): Data... |
% dataset_year else: raise hdx.data.hdxobject.HDXError('dataset_year has type %s which is not supported!' % type(dataset_year).__name__) if dataset_end_year is None: dataset_end_year = dataset_year if isinstance(dataset_end_year, int): dataset_end_date = '31/12/%d' % dataset_end_year elif isinstance(dataset_end_year, s... |
def get_expected_update_frequency(self): # type: () -> Optional[str] """Get expected update frequency (in textual rather than numeric form) Returns: Optional[str]: Update frequency in textual form or None if the update frequency doesn't exist or is blank. """ days = self.data.get('data_update_frequency', None) if days:... |
def set_expected_update_frequency(self, update_frequency): # type: (str) -> None """Set expected update frequency Args: update_frequency (str): Update frequency Returns: None """ try: int(update_frequency) except ValueError: update_frequency = Dataset.transform_update_frequency(update_frequency) if not update_frequency... |
def remove_tag(self, tag): # type: (str) -> bool """Remove a tag Args: tag (str): Tag to remove Returns: bool: True if tag removed or False if not """ return self._remove_hdxobject(self.data.get('tags'), tag, matchon='name') |
def get_location(self, locations=None): # type: (Optional[List[str]]) -> List[str] """Return the dataset's location Args: locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX. Returns: List[str]: list of locations or [] if there are none """ countries = self.data.get('groups', Non... |
def add_country_location(self, country, exact=True, locations=None, use_live=True): # type: (str, bool, Optional[List[str]], bool) -> bool """Add a country. If an iso 3 code is not provided, value is parsed and if it is a valid country name, converted to an iso 3 code. If the country is already added, it is ignored. Ar... |
False to allow fuzzy matching. Defaults to True. locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX. use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True. Returns: bool: True if country added or False if country already prese... |
cannot find iso3 code!' % country) return self.add_other_location(iso3, exact=exact, alterror='Country: %s with iso3: %s could not be found in HDX list!' % (country, iso3), locations=locations) |
def add_country_locations(self, countries, locations=None, use_live=True): # type: (List[str], Optional[List[str]], bool) -> bool """Add a list of countries. If iso 3 codes are not provided, values are parsed and where they are valid country names, converted to iso 3 codes. If any country is already added, it is ignore... |
downloaded from HDX. use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True. Returns: bool: True if all countries added or False if any already present. """ allcountriesadded = True for country in countries: if not self.add_country_location(country, locations=location... |
def add_region_location(self, region, locations=None, use_live=True): # type: (str, Optional[List[str]], bool) -> bool """Add all countries in a region. If a 3 digit UNStats M49 region code is not provided, value is parsed as a region name. If any country is already added, it is ignored. Args: region (str): M49 region,... |
downloaded from HDX. use_live (bool): Try to get use latest country data from web rather than file in package. Defaults to True. Returns: bool: True if all countries in region added or False if any already present. """ return self.add_country_locations(Country.get_countries_in_region(region, exception=HDXError, use_liv... |
def add_other_location(self, location, exact=True, alterror=None, locations=None): # type: (str, bool, Optional[str], Optional[List[str]]) -> bool """Add a location which is not a country or region. Value is parsed and compared to existing locations in HDX. If the location is already added, it is ignored. Args: locatio... |
alterror (Optional[str]): Alternative error message to builtin if location not found. Defaults to None. locations (Optional[List[str]]): Valid locations list. Defaults to list downloaded from HDX. Returns: bool: True if location added or False if location already present """ hdx_code, match = Locations.get_HDX_code_fro... |
cannot find in HDX!' % location) else: raise HDXError(alterror) groups = self.data.get('groups', None) hdx_code = hdx_code.lower() if groups: if hdx_code in [x['name'] for x in groups]: return False else: groups = list() groups.append({'name': hdx_code}) self.data['groups'] = groups return True |
def remove_location(self, location): # type: (str) -> bool """Remove a location. If the location is already added, it is ignored. Args: location (str): Location to remove Returns: bool: True if location removed or False if not """ res = self._remove_hdxobject(self.data.get('groups'), location, matchon='name') if not re... |
def get_maintainer(self): # type: () -> hdx.data.user.User """Get the dataset's maintainer. Returns: User: Dataset's maintainer """ return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration) |
def set_maintainer(self, maintainer): # type: (Union[hdx.data.user.User,Dict,str]) -> None """Set the dataset's maintainer. Args: maintainer (Union[User,Dict,str]): Either a user id or User metadata from a User object or dictionary. Returns: None """ if isinstance(maintainer, hdx.data.user.User) or isinstance(maintaine... |
if is_valid_uuid(maintainer) is False: raise HDXError('%s is not a valid user id for a maintainer!' % maintainer) self.data['maintainer'] = maintainer |
def get_organization(self): # type: () -> hdx.data.organization.Organization """Get the dataset's organization. Returns: Organization: Dataset's organization """ return hdx.data.organization.Organization.read_from_hdx(self.data['owner_org'], configuration=self.configuration) |
def set_organization(self, organization): # type: (Union[hdx.data.organization.Organization,Dict,str]) -> None """Set the dataset's organization. Args: organization (Union[Organization,Dict,str]): Either an Organization id or Organization metadata from an Organization object or dictionary. Returns: None """ if isinstan... |
if is_valid_uuid(organization) is False and organization != 'hdx': raise HDXError('%s is not a valid organization id!' % organization) self.data['owner_org'] = organization |
def get_showcases(self): # type: () -> List[hdx.data.showcase.Showcase] """Get any showcases the dataset is in Returns: List[Showcase]: list of showcases """ assoc_result, showcases_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='package_id', action=hdx.data.showcase.Showcase.actions()['list_showcas... |
def _get_dataset_showcase_dict(self, showcase): # type: (Union[hdx.data.showcase.Showcase, Dict,str]) -> Dict """Get dataset showcase dict Args: showcase (Union[Showcase,Dict,str]): Either a showcase id or Showcase metadata from a Showcase object or dictionary Returns: dict: dataset showcase dict """ if isinstance(show... |
showcase!' % type(showcase).__name__) if is_valid_uuid(showcase) is False: raise HDXError('%s is not a valid showcase id!' % showcase) return {'package_id': self.data['id'], 'showcase_id': showcase} |
def add_showcase(self, showcase, showcases_to_check=None): # type: (Union[hdx.data.showcase.Showcase,Dict,str], List[hdx.data.showcase.Showcase]) -> bool """Add dataset to showcase Args: showcase (Union[Showcase,Dict,str]): Either a showcase id or showcase metadata from a Showcase object or dictionary showcases_to_chec... |
showcases_to_check is None: showcases_to_check = self.get_showcases() for showcase in showcases_to_check: if dataset_showcase['showcase_id'] == showcase['id']: return False showcase = hdx.data.showcase.Showcase({'id': dataset_showcase['showcase_id']}, configuration=self.configuration) showcase._write_to_hdx('associate'... |
def add_showcases(self, showcases, showcases_to_check=None): # type: (List[Union[hdx.data.showcase.Showcase,Dict,str]], List[hdx.data.showcase.Showcase]) -> bool """Add dataset to multiple showcases Args: showcases (List[Union[Showcase,Dict,str]]): A list of either showcase ids or showcase metadata from Showcase object... |
showcases_to_check is None: showcases_to_check = self.get_showcases() allshowcasesadded = True for showcase in showcases: if not self.add_showcase(showcase, showcases_to_check=showcases_to_check): allshowcasesadded = False return allshowcasesadded |
def remove_showcase(self, showcase): # type: (Union[hdx.data.showcase.Showcase,Dict,str]) -> None """Remove dataset from showcase Args: showcase (Union[Showcase,Dict,str]): Either a showcase id string or showcase metadata from a Showcase object or dictionary Returns: None """ dataset_showcase = self._get_dataset_showca... |
def set_requestable(self, requestable=True): # type: (bool) -> None """Set the dataset to be of type requestable or not Args: requestable (bool): Set whether dataset is requestable. Defaults to True. Returns: None """ self.data['is_requestdata_type'] = requestable if requestable: self.data['private'] = False |
def get_filetypes(self): # type: () -> List[str] """Return list of filetypes in your data Returns: List[str]: List of filetypes """ if not self.is_requestable(): return [resource.get_file_type() for resource in self.get_resources()] return self._get_stringlist_from_commastring('file_types') |
def clean_dataset_tags(self): # type: () -> Tuple[bool, bool] """Clean dataset tags according to tags cleanup spreadsheet and return if any changes occurred Returns: Tuple[bool, bool]: Returns (True if tags changed or False if not, True if error or False if not) """ tags_dict, wildcard_tags = Tags.tagscleanupdicts() de... |
text = '%s - %s: %s -> ' % (self.data['name'], wording, tag) if not final_tags: logger.error('%snothing!' % text) return False, True tags_lower_five = final_tags[:5].lower() if tags_lower_five == 'merge' or tags_lower_five == 'split' or ( ';' not in final_tags and len(final_tags) > 50): logger.error('%s%s - Invalid fin... |
tags: %s' % (text, final_tags, tags)) else: logger.warning( '%s%s - At least one of the tags already exists! Dataset tags: %s' % (text, final_tags, tags)) return True, False def do_action(tag, tags_dict_key): whattodo = tags_dict[tags_dict_key] action = whattodo[u'action'] final_tags = whattodo[u'final tags (semicolon ... |
u'Fix spelling': changed, error = update_tag(tag, final_tags, 'Fixing spelling') elif action == u'Non English': changed, error = update_tag(tag, final_tags, 'Anglicising', remove_existing=False) else: changed = False error = False return changed, error def process_tag(tag): changed = False error = False if tag in tags_... |
error anychange = False anyerror = False for tag in self.get_tags(): changed, error = process_tag(tag) if changed: anychange = True if error: anyerror = True return anychange, anyerror |
def set_quickchart_resource(self, resource): # type: (Union[hdx.data.resource.Resource,Dict,str,int]) -> bool """Set the resource that will be used for displaying QuickCharts in dataset preview Args: resource (Union[hdx.data.resource.Resource,Dict,str,int]): Either resource id or name, resource metadata from a Resource... |
resource = self.get_resources()[resource] if isinstance(resource, hdx.data.resource.Resource) or isinstance(resource, dict): res = resource.get('id') if res is None: resource = resource['name'] else: resource = res elif not isinstance(resource, str): raise hdx.data.hdxobject.HDXError('Resource id cannot be found in typ... |
True else: dataset_resource.disable_dataset_preview() return changed |
def create_default_views(self, create_datastore_views=False): # type: (bool) -> None """Create default resource views for all resources in dataset Args: create_datastore_views (bool): Whether to try to create resource views that point to the datastore Returns: None """ package = deepcopy(self.data) if self.resources: p... |
def _get_credentials(self): # type: () -> Optional[Tuple[str, str]] """ Return HDX site username and password Returns: Optional[Tuple[str, str]]: HDX site username and password or None """ site = self.data[self.hdx_site] username = site.get('username') if username: return b64decode(username).decode('utf-8'), b64decode(... |
def call_remoteckan(self, *args, **kwargs): # type: (Any, Any) -> Dict """ Calls the remote CKAN Args: *args: Arguments to pass to remote CKAN call_action method **kwargs: Keyword arguments to pass to remote CKAN call_action method Returns: Dict: The response from the remote CKAN call_action method """ requests_kwargs ... |
self.get_api_key()) kwargs['apikey'] = apikey return self.remoteckan().call_action(*args, **kwargs) |
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below hdx_url (str): HDX url to use. Overrides hdx_site. hdx_site (str): HDX site to use eg. prod, test. Defaults to test. hdx_key (str): Your HDX key. Ignored if hdx_read_only = Tru... |
hdx_key hdx_url = os.getenv('HDX_URL') if hdx_url is not None: kwargs['hdx_url'] = hdx_url else: hdx_site = os.getenv('HDX_SITE') if hdx_site is not None: kwargs['hdx_site'] = hdx_site return kwargs |
def create_remoteckan(cls, site_url, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, session=None, **kwargs): # type: (str, Optional[str], Optional[str], Optional[str], requests.Session, Any) -> ckanapi.RemoteCKAN """ Create remote CKAN instance from configuration Args: site_url (str): Site url. u... |
(requests.Session): requests Session object to use. Defaults to calling hdx.utilities.session.get_session() Returns: ckanapi.RemoteCKAN: Remote CKAN instance """ if not session: session = get_session(user_agent, user_agent_config_yaml, user_agent_lookup, prefix=Configuration.prefix, method_whitelist=frozenset(['HEAD', ... |
def setup_remoteckan(self, remoteckan=None, **kwargs): # type: (Optional[ckanapi.RemoteCKAN], Any) -> None """ Set up remote CKAN from provided CKAN or by creating from configuration Args: remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration. Returns: None """ if remot... |
def setup(cls, configuration=None, **kwargs): # type: (Optional['Configuration'], Any) -> None """ Set up the HDX configuration Args: configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments. **kwargs: See below user_agent (str): User agent string. HDXPythonLibra... |
Lookup key for YAML. Ignored if user_agent supplied. hdx_url (str): HDX url to use. Overrides hdx_site. hdx_site (str): HDX site to use eg. prod, test. hdx_read_only (bool): Whether to access HDX in read only mode. Defaults to False. hdx_key (str): Your HDX key. Ignored if hdx_read_only = True. hdx_config_dict (dict): ... |
to JSON HDX configuration OR hdx_config_yaml (str): Path to YAML HDX configuration project_config_dict (dict): Project configuration dictionary OR project_config_json (str): Path to JSON Project configuration OR project_config_yaml (str): Path to YAML Project configuration hdx_base_config_dict (dict): HDX base configur... |
""" if configuration is None: cls._configuration = Configuration(**kwargs) else: cls._configuration = configuration |
def _create(cls, configuration=None, remoteckan=None, **kwargs): # type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str """ Create HDX configuration Args: configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments. remoteckan (Optional[ckanap... |
agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup (str): Lookup key for YAML. Ignored if user_agent supplied. hdx_url (str): HDX url to use. Overrides hdx_site. hdx_site (str): HDX site to use eg. prod, test. hdx_read_only (bool): Whether to access HDX in read only mod... |
to use instead of above 3 parameters OR hdx_config_json (str): Path to JSON HDX configuration OR hdx_config_yaml (str): Path to YAML HDX configuration project_config_dict (dict): Project configuration dictionary OR project_config_json (str): Path to JSON Project configuration OR project_config_yaml (str): Path to YAML ... |
YAML HDX base configuration. Defaults to library's internal hdx_base_configuration.yml. Returns: str: HDX site url """ kwargs = cls._environment_variables(**kwargs) cls.setup(configuration, **kwargs) cls._configuration.setup_remoteckan(remoteckan, **kwargs) return cls._configuration.get_hdx_site_url() |
def create(cls, configuration=None, remoteckan=None, **kwargs): # type: (Optional['Configuration'], Optional[ckanapi.RemoteCKAN], Any) -> str """ Create HDX configuration. Can only be called once (will raise an error if called more than once). Args: configuration (Optional[Configuration]): Configuration instance. Defau... |
prefixed. Must be supplied if remoteckan is not. user_agent_config_yaml (str): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup (str): Lookup key for YAML. Ignored if user_agent supplied. hdx_url (str): HDX url to use. Overrides hdx_site. hdx_site (s... |
(str): Your HDX key. Ignored if hdx_read_only = True. hdx_config_dict (dict): HDX configuration dictionary to use instead of above 3 parameters OR hdx_config_json (str): Path to JSON HDX configuration OR hdx_config_yaml (str): Path to YAML HDX configuration project_config_dict (dict): Project configuration dictionary O... |
OR hdx_base_config_json (str): Path to JSON HDX base configuration OR hdx_base_config_yaml (str): Path to YAML HDX base configuration. Defaults to library's internal hdx_base_configuration.yml. Returns: str: HDX site url """ if cls._configuration is not None: raise ConfigurationError('Configuration already created!') r... |
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr, assignment_operator: str = ' = ', statement_separator: str = '\n', statement_per_line: bool = False) -> str: """ Convert a dictionary into a string with assignments Each assignment is constructed based on: key assignment_operator value_represent... |
: dict assignment_operator: str, optional: Assignment operator (" = " in python) value_representation: str, optinal How to represent the value in the assignments (repr function in python) statement_separator : str, optional: Statement separator (new line in python) statement_per_line: bool, optional Insert each stateme... |
kwargs_to_variable_assignment({'a':2 ,'b': "abc"}, statement_per_line=True) "a = 2\\n\\nb = 'abc'\\n" >>> kwargs_to_variable_assignment({'a': 2}) 'a = 2\\n' >>> kwargs_to_variable_assignment({'a': 2}, statement_per_line=True) 'a = 2\\n' """ code = [] join_str = '\n' if statement_per_line else '' for key, value in kwarg... |
def decode_json(json_input: Union[str, None] = None): """ Simple wrapper of json.load and json.loads. If json_input is None the output is an empty dictionary. If the input is a string that ends in .json it is decoded using json.load. Otherwise it is decoded using json.loads. Parameters ---------- json_input : str, None... |
{'flag': True} >>> decode_json('{"value":null}') {'value': None} """ if json_input is None: return {} else: if isinstance(json_input, str) is False: raise TypeError() elif json_input[-5:] == ".json": with open(json_input) as f: decoded_json = json.load(f) else: decoded_json = json.loads(json_input) return decoded_json |
def is_jsonable(obj) -> bool: """ Check if an object is jsonable. An object is jsonable if it is json serialisable and by loading its json representation the same object is recovered. Parameters ---------- obj : Python object Returns ------- bool >>> is_jsonable([1,2,3]) True >>> is_jsonable((1,2,3)) False >>> is_jsona... |
def is_literal_eval(node_or_string) -> tuple: """ Check if an expresion can be literal_eval. ---------- node_or_string : Input Returns ------- tuple (bool,python object) If it can be literal_eval the python object is returned. Otherwise None it is returned. >>> is_literal_eval('[1,2,3]') (True, [1, 2, 3]) >>> is_litera... |
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> find_duplicates([1,2,3]) set() >>> find_duplicates([1,2,1]) {1} ... |
def sort_dict(d: dict, by: str = 'key', allow_duplicates: bool = True) -> collections.OrderedDict: """ Sort a dictionary by key or value. The function relies on https://docs.python.org/3/library/collections.html#collections.OrderedDict . The dulicated are determined based on https://stackoverflow.com/questions/9835762/... |
allowed. Returns ------- collections.OrderedDict Sorted dictionary. >>> sort_dict({2: 3, 1: 2, 3: 1}) OrderedDict([(1, 2), (2, 3), (3, 1)]) >>> sort_dict({2: 3, 1: 2, 3: 1}, by='value') OrderedDict([(3, 1), (1, 2), (2, 3)]) >>> sort_dict({'2': 3, '1': 2}, by='value') OrderedDict([('1', 2), ('2', 3)]) >>> sort_dict({2: ... |
values: {1} >>> sort_dict({1:1,2:3},by=True) Traceback (most recent call last): ... ValueError: by can be 'key' or 'value'. """ if by == 'key': i = 0 elif by == 'value': values = list(d.values()) if len(values) != len(set(values)) and not allow_duplicates: duplicates = find_duplicates(values) raise ValueError("There ar... |
t: t[i])) |
def group_dict_by_value(d: dict) -> dict: """ Group a dictionary by values. Parameters ---------- d : dict Input dictionary Returns ------- dict Output dictionary. The keys are the values of the initial dictionary and the values ae given by a list of keys corresponding to the value. >>> group_dict_by_value({2: 3, 1: 2,... |
3: 1, 10:1, 12: 3}) {3: [2, 12], 2: [1], 1: [3, 10]} """ d_out = {} for k, v in d.items(): if v in d_out: d_out[v].append(k) else: d_out[v] = [k] return d_out |
def variable_status(code: str, exclude_variable: Union[set, None] = None, jsonable_parameter: bool = True) -> tuple: """ Find the possible parameters and "global" variables from a python code. This is achieved by parsing the abstract syntax tree. Parameters ---------- code : str Input code as string. exclude_variable :... |
set of possible parameter, a set of parameter to exclude, a dictionary of possible parameter ) A variable is a possible parameter if 1) it is not in the input exclude_variable, 2) the code contains only assignments, and 3) it is used only to bound objects. The set of parameter to exclude is the union of the input exclu... |
like a global variable. The dictionary of possible parameter {parameter name, parameter value} is available only if jsonable_parameter is True. >>> variable_status("a=3") ({'a'}, {'a'}, {'a': 3}) >>> variable_status("a=3",jsonable_parameter=False) ({'a'}, {'a'}, {}) >>> variable_status("a += 1") (set(), {'a'}, {}) >>> ... |
{'g'}, {}) >>> variable_status("from X import f") (set(), {'f'}, {}) >>> variable_status("from X import f as g") (set(), {'g'}, {}) """ if exclude_variable is None: exclude_variable = set() else: exclude_variable = copy.deepcopy(exclude_variable) root = ast.parse(code) store_variable_name = set() assign_only = True dic... |
|= {assign_node.id} else: exclude_variable |= {assign_node.id} _is_literal_eval,_value=is_literal_eval(node.value) if jsonable_parameter is True: for assign_node in ast.iter_child_nodes(node): if isinstance(assign_node, ast.Tuple): i=0 for assign_tuple_node in ast.iter_child_nodes(assign_node): if isinstance(assign_tup... |
in ast.walk(node): if isinstance(assign_node, ast.Name): exclude_variable |= {assign_node.id} # class and function elif isinstance(node, (ast.FunctionDef, ast.ClassDef)): assign_only = False exclude_variable |= {node.name} # import elif isinstance(node, ast.Import): assign_only = False for node1 in ast.iter_child_nodes... |
exclude_variable |= {node1.asname} else: exclude_variable |= {node1.name} else: assign_only = False if assign_only is True: possible_parameter = store_variable_name-exclude_variable if jsonable_parameter is True: dict_parameter = {k:dict_parameter[k] for k in possible_parameter} return (possible_parameter, store_variab... |
def increment_name(name: str, start_marker: str = " (", end_marker: str = ")") -> str: """ Increment the name where the incremental part is given by parameters. Parameters ---------- name : str, nbformat.notebooknode.NotebookNode Name start_marker : str The marker used before the incremental end_marker : str The marker... |
increment_name('abc (123)') 'abc (124)' >>> increment_name('abc-1',start_marker='-',end_marker='') 'abc-2' >>> increment_name('abc[2]',start_marker='[',end_marker=']') 'abc[3]' >>> increment_name('abc1',start_marker='',end_marker='') Traceback (most recent call last): ... ValueError: start_marker can not be the empty s... |
old_int+1 new_name = a[:start]+str(new_int)+end_marker else: new_name = a+start_marker+'1'+end_marker return new_name |
def read_from_hdx(identifier, configuration=None): # type: (str, Optional[Configuration]) -> Optional['ResourceView'] """Reads the resource view given by identifier from HDX and returns ResourceView object Args: identifier (str): Identifier of resource view configuration (Optional[Configuration]): HDX configuration. De... |
def get_all_for_resource(identifier, configuration=None): # type: (str, Optional[Configuration]) -> List['ResourceView'] """Read all resource views for a resource given by identifier from HDX and returns list of ResourceView objects Args: identifier (str): Identifier of resource configuration (Optional[Configuration]):... |
for resourceviewdict in result: resourceview = ResourceView(resourceviewdict, configuration=configuration) resourceviews.append(resourceview) return resourceviews |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.