INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Loads config checking CLI arguments for a config file
def load_config_from_cli(config: GoodConf, argv: List[str]) -> List[str]: """Loads config, checking CLI arguments for a config file""" # Monkey patch Django's command parser from django.core.management.base import BaseCommand original_parser = BaseCommand.create_parser def patched_parser(self, pro...
Load s config then runs Django s execute_from_command_line
def execute_from_command_line_with_config(config: GoodConf, argv: List[str]): """Load's config then runs Django's execute_from_command_line""" with load_config_from_cli(config, argv) as args: from django.core.management import execute_from_command_line execute_from_command_line(args)
Adds argument for config to existing argparser
def argparser_add_argument(parser: argparse.ArgumentParser, config: GoodConf): """Adds argument for config to existing argparser""" help = "Config file." if config.file_env_var: help += (" Can also be configured via the " "environment variable: {}".format(config.file_env_var)) i...
Given a file path parse it based on its extension ( YAML or JSON ) and return the values as a Python dictionary. JSON is the default if an extension can t be determined.
def _load_config(path: str) -> dict: """ Given a file path, parse it based on its extension (YAML or JSON) and return the values as a Python dictionary. JSON is the default if an extension can't be determined. """ __, ext = os.path.splitext(path) if ext in ['.yaml', '.yml']: import r...
Find config file and set values
def load(self, filename: str = None): """Find config file and set values""" if filename: self.config_file = _find_file(filename) else: if self.file_env_var and self.file_env_var in os.environ: self.config_file = _find_file(os.environ[self.file_env_var]) ...
Dumps initial config in YAML
def generate_yaml(cls, **override): """ Dumps initial config in YAML """ import ruamel.yaml yaml = ruamel.yaml.YAML() yaml_str = StringIO() yaml.dump(cls.get_initial(**override), stream=yaml_str) yaml_str.seek(0) dict_from_yaml = yaml.load(yaml_str...
Documents values in markdown
def generate_markdown(cls): """ Documents values in markdown """ lines = [] if cls.__doc__: lines.extend(['# {}'.format(cls.__doc__), '']) for k, v in cls._values.items(): lines.append('* **{}** '.format(k)) if v.required: ...
converts string to type requested by cast_as
def cast(self, val: str): """converts string to type requested by `cast_as`""" try: return getattr(self, 'cast_as_{}'.format( self.cast_as.__name__.lower()))(val) except AttributeError: return self.cast_as(val)
Returns all dates from first to last included.
def list_dates_between(first_date, last_date): """Returns all dates from first to last included.""" return [first_date + timedelta(days=n) for n in range(1 + (last_date - first_date).days)]
Fast %Y - %m - %d parsing.
def parse_date(s): """Fast %Y-%m-%d parsing.""" try: return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10])) except ValueError: # other accepted format used in one-day data set return datetime.datetime.strptime(s, '%d %B %Y').date()
To be subclassed if alternate methods of loading data.
def load_file(self, currency_file): """To be subclassed if alternate methods of loading data. """ if currency_file.startswith(('http://', 'https://')): content = urlopen(currency_file).read() else: with open(currency_file, 'rb') as f: content = f.r...
Fill missing rates of a currency with the closest available ones.
def _set_missing_to_none(self, currency): """Fill missing rates of a currency with the closest available ones.""" rates = self._rates[currency] first_date, last_date = self.bounds[currency] for date in list_dates_between(first_date, last_date): if date not in rates: ...
Fill missing rates of a currency.
def _compute_missing_rates(self, currency): """Fill missing rates of a currency. This is done by linear interpolation of the two closest available rates. :param str currency: The currency to fill missing rates for. """ rates = self._rates[currency] # tmp will store the...
Get a rate for a given currency and date.
def _get_rate(self, currency, date): """Get a rate for a given currency and date. :type date: datetime.date >>> from datetime import date >>> c = CurrencyConverter() >>> c._get_rate('USD', date=date(2014, 3, 28)) 1.375... >>> c._get_rate('BGN', date=date(2010, 1...
Convert amount from a currency to another one.
def convert(self, amount, currency, new_currency='EUR', date=None): """Convert amount from a currency to another one. :param float amount: The amount of `currency` to convert. :param str currency: The currency to convert from. :param str new_currency: The currency to convert to. ...
Group iterable by n elements.
def grouper(iterable, n, fillvalue=None): """Group iterable by n elements. >>> for t in grouper('abcdefg', 3, fillvalue='x'): ... print(''.join(t)) abc def gxx """ return list(zip_longest(*[iter(iterable)] * n, fillvalue=fillvalue))
Animate given frame for set number of iterations.
def animate(frames, interval, name, iterations=2): """Animate given frame for set number of iterations. Parameters ---------- frames : list Frames for animating interval : float Interval between two frames name : str Name of animation iterations : int, optional ...
Convert Cnf object ot Dimacs cnf string cnf: Cnf object In the converted Cnf there will be only numbers for variable names. The conversion guarantees that the variables will be numbered alphabetically.
def tostring(self, cnf): """Convert Cnf object ot Dimacs cnf string cnf: Cnf object In the converted Cnf there will be only numbers for variable names. The conversion guarantees that the variables will be numbered alphabetically. """ self.varname...
I just found a remarkably large bug in my SAT solver and found an interesting solution. Remove all b | - b ( - b | b ) & ( b | - a ) & ( - b | a ) & ( a | - a ) becomes ( b | - a ) & ( - b | a )
def reduceCnf(cnf): """ I just found a remarkably large bug in my SAT solver and found an interesting solution. Remove all b | -b (-b | b) & (b | -a) & (-b | a) & (a | -a) becomes (b | -a) & (-b | a) Remove all (-e) & (-e) (-e | a) & (-e | a) & (-e | a) & (-e | a) becomes (-...
[ DEPRECATED ] Load the polynomial series for name and return it.
def load(self, name): """[DEPRECATED] Load the polynomial series for `name` and return it.""" s = self.sets.get(name) if s is None: self.sets[name] = s = np.load(self.path('jpl-%s.npy' % name)) return s
[ DEPRECATED ] Compute the position of name at time tdb [ + tdb2 ].
def position(self, name, tdb, tdb2=0.0): """[DEPRECATED] Compute the position of `name` at time ``tdb [+ tdb2]``. The position is returned as a NumPy array ``[x y z]``. The barycentric dynamical time `tdb` argument should be a float. If there are many dates you want computed, then make...
[ DEPRECATED ] Compute the position and velocity of name at tdb [ + tdb2 ].
def position_and_velocity(self, name, tdb, tdb2=0.0): """[DEPRECATED] Compute the position and velocity of `name` at ``tdb [+ tdb2]``. The position and velocity are returned in a 2-tuple:: ([x y z], [xdot ydot zdot]) The barycentric dynamical time `tdb` argument should be a float....
[ DEPRECATED ] Legacy routine that concatenates position and velocity vectors.
def compute(self, name, tdb): """[DEPRECATED] Legacy routine that concatenates position and velocity vectors. This routine is deprecated. Use the methods `position()` and `position_and_velocity()` instead. This method follows the same calling convention, but incurs extra copy operatio...
[ DEPRECATED ] Return a tuple of coefficients and parameters for tdb.
def compute_bundle(self, name, tdb, tdb2=0.0): """[DEPRECATED] Return a tuple of coefficients and parameters for `tdb`. The return value is a tuple that bundles together the coefficients and other Chebyshev intermediate values that are needed for the computation of either the position o...
[ DEPRECATED ] Return position given the coefficient_bundle () return value.
def position_from_bundle(self, bundle): """[DEPRECATED] Return position, given the `coefficient_bundle()` return value.""" coefficients, days_per_set, T, twot1 = bundle return (T.T * coefficients).sum(axis=2)
[ DEPRECATED ] Return velocity given the coefficient_bundle () return value.
def velocity_from_bundle(self, bundle): """[DEPRECATED] Return velocity, given the `coefficient_bundle()` return value.""" coefficients, days_per_set, T, twot1 = bundle coefficient_count = coefficients.shape[2] # Chebyshev derivative: dT = np.empty_like(T) dT[0] = 0.0 ...
Return record n as 1 024 bytes ; records are indexed from 1.
def read_record(self, n): """Return record `n` as 1,024 bytes; records are indexed from 1.""" self.file.seek(n * K - K) return self.file.read(K)
Write data to file record n ; records are indexed from 1.
def write_record(self, n, data): """Write `data` to file record `n`; records are indexed from 1.""" self.file.seek(n * K - K) return self.file.write(data)
Return a memory - map of the elements start through end.
def map_words(self, start, end): """Return a memory-map of the elements `start` through `end`. The memory map will offer the 8-byte double-precision floats ("elements") in the file from index `start` through to the index `end`, inclusive, both counting the first float as element 1. ...
Return the text inside the comment area of the file.
def comments(self): """Return the text inside the comment area of the file.""" record_numbers = range(2, self.fward) if not record_numbers: return '' data = b''.join(self.read_record(n)[0:1000] for n in record_numbers) try: return data[:data.find(b'\4')].d...
Return floats from start to end inclusive indexed from 1.
def read_array(self, start, end): """Return floats from `start` to `end` inclusive, indexed from 1. The entire range of floats is immediately read into memory from the file, making this efficient for small sequences of floats whose values are all needed immediately. """ ...
Return floats from start to end inclusive indexed from 1.
def map_array(self, start, end): """Return floats from `start` to `end` inclusive, indexed from 1. Instead of pausing to load all of the floats into RAM, this routine creates a memory map which will load data from the file only as it is accessed, and then will let it expire back out to ...
Yield ( record_number n_summaries record_data ) for each record.
def summary_records(self): """Yield (record_number, n_summaries, record_data) for each record. Readers will only use the second two values in each tuple. Writers can update the record using the `record_number`. """ record_number = self.fward unpack = self.summary_contro...
Yield ( name ( value value... )) for each summary in the file.
def summaries(self): """Yield (name, (value, value, ...)) for each summary in the file.""" length = self.summary_length step = self.summary_step for record_number, n_summaries, summary_data in self.summary_records(): name_data = self.read_record(record_number + 1) ...
Add a new array to the DAF file.
def add_array(self, name, values, array): """Add a new array to the DAF file. The summary will be initialized with the `name` and `values`, and will have its start word and end word fields set to point to where the `array` of floats has been appended to the file. """ f ...
Close this SPK file.
def close(self): """Close this SPK file.""" self.daf.file.close() for segment in self.segments: if hasattr(segment, '_data'): del segment._data self.daf._array = None self.daf._map = None
Return a textual description of the segment.
def describe(self, verbose=True): """Return a textual description of the segment.""" center = titlecase(target_names.get(self.center, 'Unknown center')) target = titlecase(target_names.get(self.target, 'Unknown target')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} {1} ({0.center})' ...
Compute the component values for the time tdb plus tdb2.
def compute(self, tdb, tdb2=0.0): """Compute the component values for the time `tdb` plus `tdb2`.""" for position in self.generate(tdb, tdb2): return position
Close this file.
def close(self): """Close this file.""" self.daf.file.close() for segment in self.segments: if hasattr(segment, '_data'): del segment._data
Return a textual description of the segment.
def describe(self, verbose=True): """Return a textual description of the segment.""" body = titlecase(target_names.get(self.body, 'Unknown body')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} frame={0.frame}' ' {1} ({0.body})'.format(self, body)) if verbose: tex...
Map the coefficients into memory using a NumPy array.
def _load(self): """Map the coefficients into memory using a NumPy array. """ if self.data_type == 2: component_count = 3 else: raise ValueError('only binary PCK data type 2 is supported') init, intlen, rsize, n = self.daf.read_array(self.end_i - 3, self...
Generate angles and derivatives for time tdb plus tdb2.
def compute(self, tdb, tdb2, derivative=True): """Generate angles and derivatives for time `tdb` plus `tdb2`. If ``derivative`` is true, return a tuple containing both the angle and its derivative; otherwise simply return the angles. """ scalar = not getattr(tdb, 'shape', 0) an...
Show system notification with duration t ( ms )
def notify(msg, msg_type=0, t=None): "Show system notification with duration t (ms)" if platform.system() == 'Darwin': command = notify_command_osx(msg, msg_type, t) else: command = notify_command_linux(msg, t) os.system(command.encode('utf-8'))
批量获取音乐的地址
def geturls_new_api(song_ids): """ 批量获取音乐的地址 """ br_to_quality = {128000: 'MD 128k', 320000: 'HD 320k'} alters = NetEase().songs_detail_new_api(song_ids) urls = [alter['url'] for alter in alters] return urls
Visit a function call.
def visit_Call(self, node): """ Visit a function call. We expect every logging statement and string format to be a function call. """ # CASE 1: We're in a logging statement if self.within_logging_statement(): if self.within_logging_argument() and self.is_for...
Process binary operations while processing the first logging argument.
def visit_BinOp(self, node): """ Process binary operations while processing the first logging argument. """ if self.within_logging_statement() and self.within_logging_argument(): # handle percent format if isinstance(node.op, Mod): self.violations...
Process dict arguments.
def visit_Dict(self, node): """ Process dict arguments. """ if self.should_check_whitelist(node): for key in node.keys: if key.s in self.whitelist or key.s.startswith("debug_"): continue self.violations.append((self.current...
Process f - string arguments.
def visit_JoinedStr(self, node): """ Process f-string arguments. """ if version_info >= (3, 6): if self.within_logging_statement(): if any(isinstance(i, FormattedValue) for i in node.values): if self.within_logging_argument(): ...
Process keyword arguments.
def visit_keyword(self, node): """ Process keyword arguments. """ if self.should_check_whitelist(node): if node.arg not in self.whitelist and not node.arg.startswith("debug_"): self.violations.append((self.current_logging_call, WHITELIST_VIOLATION.format(node...
Process except blocks.
def visit_ExceptHandler(self, node): """ Process except blocks. """ name = self.get_except_handler_name(node) if not name: super(LoggingVisitor, self).generic_visit(node) return self.current_except_names.append(name) super(LoggingVisitor,...
Heuristic to decide whether an AST Call is a logging call.
def detect_logging_level(self, node): """ Heuristic to decide whether an AST Call is a logging call. """ try: if self.get_id_attr(node.func.value) == "warnings": return None # NB: We could also look at the argument signature or the target attribut...
Helper to get the exception name from an ExceptHandler node in both py2 and py3.
def get_except_handler_name(self, node): """ Helper to get the exception name from an ExceptHandler node in both py2 and py3. """ name = node.name if not name: return None if version_info < (3,): return name.id return name
Check if value has id attribute and return it.
def get_id_attr(self, value): """Check if value has id attribute and return it. :param value: The value to get id from. :return: The value.id. """ if not hasattr(value, "id") and hasattr(value, "value"): value = value.value return value.id
Checks if the node is a bare exception name from an except block.
def is_bare_exception(self, node): """ Checks if the node is a bare exception name from an except block. """ return isinstance(node, Name) and node.id in self.current_except_names
Checks if the node is the expression str ( e ) or unicode ( e ) where e is an exception name from an except block
def is_str_exception(self, node): """ Checks if the node is the expression str(e) or unicode(e), where e is an exception name from an except block """ return ( isinstance(node, Call) and isinstance(node.func, Name) and node.func.id in ('str', 'unicode...
Reports a violation if exc_info keyword is used with logging. error or logging. exception.
def check_exc_info(self, node): """ Reports a violation if exc_info keyword is used with logging.error or logging.exception. """ if self.current_logging_level not in ('error', 'exception'): return for kw in node.keywords: if kw.arg == 'exc_info': ...
Delete file from database only if needed.
def delete_file_if_needed(instance, filefield_name): """Delete file from database only if needed. When editing and the filefield is a new file, deletes the previous file (if any) from the database. Call this function immediately BEFORE saving the instance. """ if instance.pk: model_clas...
Delete the file ( if any ) from the database.
def delete_file(instance, filefield_name): """Delete the file (if any) from the database. Call this function immediately AFTER deleting the instance. """ file_instance = getattr(instance, filefield_name) if file_instance: DatabaseFileStorage().delete(file_instance.name)
Edit the download - link inner text.
def db_file_widget(cls): """Edit the download-link inner text.""" def get_link_display(url): unquoted = unquote(url.split('%2F')[-1]) if sys.version_info.major == 2: # python 2 from django.utils.encoding import force_unicode unquoted = force_unicode(unquoted) re...
Returns the freshly rendered content for the template and context described by the PDFResponse.
def rendered_content(self): """Returns the freshly rendered content for the template and context described by the PDFResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using t...
Returns a PDF response with a template rendered with the given context.
def render_to_response(self, context, **response_kwargs): """ Returns a PDF response with a template rendered with the given context. """ filename = response_kwargs.pop('filename', None) cmd_options = response_kwargs.pop('cmd_options', None) if issubclass(self.response_c...
Converts options into a list of command - line arguments. Skip arguments where no value is provided For flag - type ( No argument ) variables pass only the name and only then if the value is True
def _options_to_args(**options): """ Converts ``options`` into a list of command-line arguments. Skip arguments where no value is provided For flag-type (No argument) variables, pass only the name and only then if the value is True """ flags = [] for name in sorted(options): value = ...
Converts html to PDF using http:// wkhtmltopdf. org/.
def wkhtmltopdf(pages, output=None, **kwargs): """ Converts html to PDF using http://wkhtmltopdf.org/. pages: List of file paths or URLs of the html to be converted. output: Optional output file path. If None, the output is returned. **kwargs: Passed to wkhtmltopdf via _extra_args() (See ...
Given a unicode string will do its dandiest to give you back a valid ascii charset string you can use in say http headers and the like.
def http_quote(string): """ Given a unicode string, will do its dandiest to give you back a valid ascii charset string you can use in, say, http headers and the like. """ if isinstance(string, six.text_type): try: import unidecode except ImportError: pass ...
Convert all MEDIA files into a file:// URL paths in order to correctly get it displayed in PDFs.
def make_absolute_paths(content): """Convert all MEDIA files into a file://URL paths in order to correctly get it displayed in PDFs.""" overrides = [ { 'root': settings.MEDIA_ROOT, 'url': settings.MEDIA_URL, }, { 'root': settings.STATIC_ROOT, ...
If text is matched with pattern return variable names specified ( % { pattern: variable name } ) in pattern and their corresponding values. If not matched return None. custom patterns can be passed in by custom_patterns ( pattern name pattern regular expression pair ) or custom_patterns_dir.
def match(self, text): """If text is matched with pattern, return variable names specified(%{pattern:variable name}) in pattern and their corresponding values.If not matched, return None. custom patterns can be passed in by custom_patterns(pattern name, pattern regular expression pair) o...
Sets defaults for class Meta declarations.
def configure(module=None, prefix='MONGODB_', **kwargs): """Sets defaults for ``class Meta`` declarations. Arguments can either be extracted from a `module` (in that case all attributes starting from `prefix` are used): >>> import foo >>> configure(foo) or passed explicictly as keyword argume...
Updates class - level defaults for: class: _Options container.
def _configure(cls, **defaults): """Updates class-level defaults for :class:`_Options` container.""" for attr in defaults: setattr(cls, attr, defaults[attr])
Converts a given string from CamelCase to under_score.
def to_underscore(string): """Converts a given string from CamelCase to under_score. >>> to_underscore('FooBar') 'foo_bar' """ new_string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string) new_string = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', new_string) return new_string.lower()
Builds all indices listed in model s Meta class.
def auto_index(mcs): """Builds all indices, listed in model's Meta class. >>> class SomeModel(Model) ... class Meta: ... indices = ( ... Index('foo'), ... ) .. note:: this will result in calls to :...
Same as: meth: pymongo. collection. Collection. find except it returns the right document class.
def find(self, *args, **kwargs): """Same as :meth:`pymongo.collection.Collection.find`, except it returns the right document class. """ return Cursor(self, *args, wrap=self.document_class, **kwargs)
Same as: meth: pymongo. collection. Collection. find_one except it returns the right document class.
def find_one(self, *args, **kwargs): """Same as :meth:`pymongo.collection.Collection.find_one`, except it returns the right document class. """ data = super(Collection, self).find_one(*args, **kwargs) if data: return self.document_class(data) return None
Load and parse a. csv file
def parse_file(self, file_path, currency) -> List[PriceModel]: """ Load and parse a .csv file """ # load file # read csv into memory? contents = self.load_file(file_path) prices = [] # parse price elements for line in contents: price = self.pa...
Loads the content of the text file
def load_file(self, file_path) -> List[str]: """ Loads the content of the text file """ content = [] content = read_lines_from_file(file_path) return content
Parse a CSV line into a price element
def parse_line(self, line: str) -> PriceModel: """ Parse a CSV line into a price element """ line = line.rstrip() parts = line.split(',') result = PriceModel() # symbol result.symbol = self.translate_symbol(parts[0]) # value result.value = Decimal(parts...
translate the incoming symbol into locally - used
def translate_symbol(self, in_symbol: str) -> str: """ translate the incoming symbol into locally-used """ # read all mappings from the db if not self.symbol_maps: self.__load_symbol_maps() # translate the incoming symbol result = self.symbol_maps[in_symbol] if in_sym...
Loads all symbol maps from db
def __load_symbol_maps(self): """ Loads all symbol maps from db """ repo = SymbolMapRepository(self.__get_session()) all_maps = repo.get_all() self.symbol_maps = {} for item in all_maps: self.symbol_maps[item.in_symbol] = item.out_symbol
Reuses the same db session
def __get_session(self): """ Reuses the same db session """ if not self.session: self.session = dal.get_default_session() return self.session
Add individual price
def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security = SecuritySymbol("", "") price.symbol.parse(symbol) # price.symbol.mnemonic = price.symbol.mnemo...
Import prices from CSV file
def import_csv(filepath: str, currency: str): """ Import prices from CSV file """ logger.debug(f"currency = {currency}") # auto-convert to uppercase. currency = currency.upper() app = PriceDbApplication() app.logger = logger app.import_prices(filepath, currency)
displays last price for symbol if provided
def last(symbol: str): """ displays last price, for symbol if provided """ app = PriceDbApplication() # convert to uppercase if symbol: symbol = symbol.upper() # extract namespace sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) latest = app.get_late...
Display all prices
def list_prices(date, currency, last): """ Display all prices """ app = PriceDbApplication() app.logger = logger if last: # fetch only the last prices prices = app.get_latest_prices() else: prices = app.get_prices(date, currency) for price in prices: print(price)...
Download the latest prices
def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str): """ Download the latest prices """ if help: click.echo(ctx.get_help()) ctx.exit() app = PriceDbApplication() app.logger = logger if currency: currency = currency.strip() currency ...
Delete old prices leaving just the last.
def prune(symbol: str, all: str): """ Delete old prices, leaving just the last. """ app = PriceDbApplication() app.logger = logger count = 0 if symbol is not None: sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) deleted = app.prune(sec_symbol) if delete...
Return the default session. The path is read from the default config.
def get_default_session(): """ Return the default session. The path is read from the default config. """ from .config import Config, ConfigKeys db_path = Config().get(ConfigKeys.price_database) if not db_path: raise ValueError("Price database not set in the configuration file!") return get_...
Creates a symbol mapping
def add_map(incoming, outgoing): """ Creates a symbol mapping """ db_path = Config().get(ConfigKeys.pricedb_path) session = get_session(db_path) new_map = SymbolMap() new_map.in_symbol = incoming new_map.out_symbol = outgoing session.add(new_map) session.commit() click.echo("Record...
Displays all symbol maps
def list_maps(): """ Displays all symbol maps """ db_path = Config().get(ConfigKeys.price_database) session = get_session(db_path) maps = session.query(SymbolMap).all() for item in maps: click.echo(item)
Finds the map by in - symbol
def get_by_id(self, symbol: str) -> SymbolMap: """ Finds the map by in-symbol """ return self.query.filter(SymbolMap.in_symbol == symbol).first()
Read text lines from a file
def read_lines_from_file(file_path: str) -> List[str]: """ Read text lines from a file """ # check if the file exists? with open(file_path) as csv_file: content = csv_file.readlines() return content
Map the price entity
def map_entity(self, entity: dal.Price) -> PriceModel: """ Map the price entity """ if not entity: return None result = PriceModel() result.currency = entity.currency # date/time dt_string = entity.date format_string = "%Y-%m-%d" if entity.ti...
Parse into the Price entity ready for saving
def map_model(self, model: PriceModel) -> Price: """ Parse into the Price entity, ready for saving """ # assert isinstance(model, PriceModel) assert isinstance(model.symbol, SecuritySymbol) assert isinstance(model.datum, Datum) entity = Price() # Format date as ISO stri...
Read the config file
def __read_config(self, file_path: str): """ Read the config file """ if not os.path.exists(file_path): raise FileNotFoundError(f"File path not found: {file_path}") # check if file exists if not os.path.isfile(file_path): self.logger.error(f"file not found: {file_...
gets the default config path from resources
def __get_config_template_path(self) -> str: """ gets the default config path from resources """ filename = resource_filename( Requirement.parse(package_name), template_path + config_filename) return filename
Copy the config template into user s directory
def __create_user_config(self): """ Copy the config template into user's directory """ src_path = self.__get_config_template_path() src = os.path.abspath(src_path) if not os.path.exists(src): message = f"Config template not found {src}" self.logger.error(message)...
Returns the path where the active config file is expected. This is the user s profile folder.
def get_config_path(self) -> str: """ Returns the path where the active config file is expected. This is the user's profile folder. """ dst_dir = self.__get_user_path() dst = dst_dir + "/" + config_filename return dst
Reads the contents of the config file
def get_contents(self) -> str: """ Reads the contents of the config file """ content = None # with open(file_path) as cfg_file: # contents = cfg_file.read() # Dump the current contents into an in-memory file. in_memory = io.StringIO("") self.config.write(in_m...
Sets a value in config
def set(self, option: ConfigKeys, value): """ Sets a value in config """ assert isinstance(option, ConfigKeys) # As currently we only have 1 section. section = SECTION self.config.set(section, option.name, value) self.save()
Retrieves a config value
def get(self, option: ConfigKeys): """ Retrieves a config value """ assert isinstance(option, ConfigKeys) # Currently only one section is used section = SECTION return self.config.get(section, option.name)
Save the config file
def save(self): """ Save the config file """ file_path = self.get_config_path() contents = self.get_contents() with open(file_path, mode='w') as cfg_file: cfg_file.write(contents)
Splits the symbol into namespace symbol tuple
def parse(self, symbol: str) -> (str, str): """ Splits the symbol into namespace, symbol tuple """ symbol_parts = symbol.split(":") namespace = None mnemonic = symbol if len(symbol_parts) > 1: namespace = symbol_parts[0] mnemonic = symbol_parts[1] ...