code stringlengths 1 18.2k |
|---|
def peopleTable(self, request, tag): """ Return a L{PersonScrollingFragment} which will display the L{Person} items in the wrapped organizer. """ f = PersonScrollingFragment( self.organizer, None, Person.name, self.wt) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) return f |
def peopleFilters(self, request, tag): """ Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern. """ filters = iter(self.organizer.getPeopleFilte... |
def getPersonPluginWidget(self, name): """ Return the L{PersonPluginView} for the named person. @type name: C{unicode} @param name: A value which corresponds to the I{name} attribute of an extant L{Person}. @rtype: L{PersonPluginView} """ fragment = PersonPluginView( self.organizer.getOrganizerPlugins(), self.organizer... |
def editContactItems(self, nickname, **edits): """ Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: mapping from contact type identifiers to ListChanges instances. "... |
def makeEditorialLiveForms(self): """ Make some L{liveform.LiveForm} instances for editing the contact information of the wrapped L{Person}. """ parameters = [ liveform.Parameter( 'nickname', liveform.TEXT_INPUT, _normalizeWhitespace, 'Name', default=self.person.name)] separateForms = [] for contactType in self.organiz... |
def getParameters(self, phoneNumber): """ Return a C{list} of two liveform parameters, one for editing C{phoneNumber}'s I{number} attribute, and one for editing its I{label} attribute. @type phoneNumber: L{PhoneNumber} or C{NoneType} @param phoneNumber: If not C{None}, an existing contact item from which to get the par... |
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attri... |
def editContactItem(self, contact, label, number): """ Change the I{number} attribute of C{contact} to C{number}, and the I{label} attribute to C{label}. @type contact: L{PhoneNumber} @type label: C{unicode} @type number: C{unicode} @return: C{None} """ contact.label = label contact.number = number |
def getContactItems(self, person): """ Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person} """ return person.store.query( PhoneNumber, PhoneNumber.person == person) |
def getParameters(self, postalAddress): """ Return a C{list} of one L{LiveForm} parameter for editing a L{PostalAddress}. @type postalAddress: L{PostalAddress} or C{NoneType} @param postalAddress: If not C{None}, an existing contact item from which to get the postal address default value. @rtype: C{list} @return: The p... |
def createContactItem(self, person, address): """ Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type address: C{unicode} @param address: The value to use for the I{addre... |
def getContactItems(self, person): """ Return a C{list} of the L{PostalAddress} items associated with the given person. @type person: L{Person} """ return person.store.query(PostalAddress, PostalAddress.person == person) |
def getParameters(self, notes): """ Return a C{list} of one L{LiveForm} parameter for editing a L{Notes}. @type notes: L{Notes} or C{NoneType} @param notes: If not C{None}, an existing contact item from which to get the parameter's default value. @rtype: C{list} """ defaultNotes = u'' if notes is not None: defaultNotes... |
def createContactItem(self, person, notes): """ Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly crea... |
def getContactItems(self, person): """ Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person} """ notes = list(person.store.query(Notes, Notes.person == person)) if not notes: return [Notes(store=person.store, person=p... |
def render_addPersonForm(self, ctx, data): """ Create and return a L{liveform.LiveForm} for creating a new L{Person}. """ addPersonForm = liveform.LiveForm( self.addPerson, self._baseParameters, description='Add Person') addPersonForm.compact() addPersonForm.jsClass = u'Mantissa.People.AddPersonForm' addPersonForm.setF... |
def addPerson(self, nickname): """ Create a new L{Person} with the given C{nickname}. @type nickname: C{unicode} @param nickname: The value for the I{name} attribute of the created L{Person}. @raise L{liveform.InputError}: When some aspect of person creation raises a L{ValueError}. """ try: self.organizer.createPerson(... |
def _parseAddresses(addresses): """ Extract name/address pairs from an RFC 2822 style address list. For addresses without a display name, the name defaults to the local-part for the purpose of importing. @type addresses: unicode @return: a list of C{(name, email)} tuples """ def coerce((name, email)): if len(email): if... |
def importPeopleForm(self, request, tag): """ Create and return a L{liveform.LiveForm} for adding new L{Person}s. """ form = liveform.LiveForm( self.importAddresses, [liveform.Parameter('addresses', liveform.TEXTAREA_INPUT, self._parseAddresses, 'Email Addresses')], description='Import People') form.jsClass = u'Mantiss... |
def importAddresses(self, addresses): """ Create new L{Person}s for the given names and email addresses. Names and emails that already exist are ignored. @param addresses: a sequence of C{(name, email)} tuples (as returned from L{_parseAddresses}) @return: the names of people actually imported """ results = [] for (nam... |
def renderHTTP(self, ctx): """ Extract the data from the I{uploaddata} field of the request and pass it to our callback. """ req = inevow.IRequest(ctx) if req.method == 'POST': udata = req.fields['uploaddata'] self.cbGotMugshot(udata.type.decode('ascii'), udata.file) return rend.Page.renderHTTP(self, ctx) |
def fromFile(cls, person, inputFile, format): """ Create a L{Mugshot} item for C{person} out of the image data in C{inputFile}, or update C{person}'s existing L{Mugshot} item to reflect the new images. @param inputFile: An image of a person. @type inputFile: C{file} @param person: The person this mugshot is to be assoc... |
def makeThumbnail(cls, inputFile, person, format, smaller): """ Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person: L{Person} @param format: The format of the data ... |
def placeholderForPerson(cls, person): """ Make an unstored, placeholder L{Mugshot} instance for the given person. @param person: A person without a L{Mugshot}. @type person: L{Person} @rtype: L{Mugshot} """ imageDir = FilePath(__file__).parent().child( 'static').child('images') return cls( type=u'image/png', body=imag... |
def post_build(self, container_builder, container): """ Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals are functions. The tag must contain a name and a method opti... |
def cache_key(*args, **kwargs): """ Base method for computing the cache key with respect to the given arguments. """ key = "" for arg in args: if callable(arg): key += ":%s" % repr(arg) else: key += ":%s" % str(arg) return key |
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post): """Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters. """ filehash = sha1sum(filename) files = {'filedata': open(filename, 'rb')} payload = { 'sha1... |
def decode_values(fct): ''' Decode base64 encoded responses from Consul storage ''' def inner(*args, **kwargs): ''' decorator ''' data = fct(*args, **kwargs) if 'error' not in data: for result in data: result['Value'] = base64.b64decode(result['Value']) return data return inner |
def safe_request(fct): ''' Return json messages instead of raising errors ''' def inner(*args, **kwargs): ''' decorator ''' try: _data = fct(*args, **kwargs) except requests.exceptions.ConnectionError as error: return {'error': str(error), 'status': 404} if _data.ok: if _data.content: safe_data = _data.json() else: saf... |
def parseAddress(address): """ Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address. """ parts = [] parser = _AddressParser() end = parser(pa... |
def start(self): """ The main method that starts the service. This is blocking. """ self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._start_periodic_tasks() # starts the event handlers self._initialize_event_handl... |
def get_plugin(self, name): """ Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance. """ for plugin in self.plugins: if plugin.name == name: return plugin rais... |
def get_service(self, name): """ Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are multiple services with the same name running... |
strategy.locate(name) if not endpoints: continue random.shuffle(endpoints) for url in endpoints: try: service = get_remote_service_instance_for_url(url) self.remote_service_cache.add_entry(name, service) return service except ConnectionError: continue # could not establish connection, try next raise ValueError("Service... |
def start_thread(self, target, args, kwargs): """ Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0 """ thread_obj =... |
def emit_event(self, event_name, event_body): """ Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. :param event_name: a ``str`` representing ... |
def make_tornado_app(self): """ Creates a :py:class`tornado.web.Application` instance that respect the JSON RPC 2.0 specs and exposes the designated methods. Can be used in tests to obtain the Tornado application. :return: a :py:class:`tornado.web.Application` instance """ handlers = [ (self.endpoint, TornadoJsonRpcHan... |
def _add_extra_handlers(self, handlers): """ Adds the extra handler (defined by the user) :param handlers: a list of :py:class:`tornado.web.RequestHandler` instances. :return: """ extra_handlers = [(h[0], h[1], {"microservice": self}) for h in self.extra_handlers] handlers.extend(extra_handlers) |
def _add_static_handlers(self, handlers): """ Creates and adds the handles needed for serving static files. :param handlers: """ for url, path in self.static_dirs: handlers.append((url.rstrip("/") + "/(.*)", StaticFileHandler, {"path": path})) |
def _gather_exposed_methods(self): """ Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`. """ self._extract_methods_from_container(self) for module in self.modules: se... |
def _gather_event_handlers(self): """ Searches for the event handlers in the current microservice class. :return: """ self._extract_event_handlers_from_container(self) for module in self.modules: self._extract_event_handlers_from_container(module) |
def _periodic_task_iter(self): """ Iterates through all the periodic tasks: - the service registry pinging - default dummy task if on Windows - user defined periodic tasks :return: """ for strategy in self.discovery_strategies: self.default_periodic_tasks.append( (functools.partial(strategy.ping, self.name, self.access... |
def initialize(self): '''Calling this function initializes the printer. Args: None Returns: None Raises: None ''' self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64)) |
def select_charset(self, charset): '''Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset. ''' charsets = {'USA':0, 'France':1, 'Germany':2, 'UK':3, 'Denmark':4, 'Sweden':5, 'Italy':6, 'Spain... |
def select_char_code_table(self, table): '''Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable. ''' tables = {'standard': 0, 'eastern europe... |
def cut_setting(self, cut): '''Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type. ''' cut_settings = {'full' : 0b00000001, 'half' : 0b00000010, 'chain': 0b00000100, 'special': 0b00001000 } if ... |
def rotated_printing(self, action): '''Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeError: Invalid action. ''' if action=='r... |
def feed_amount(self, amount): '''Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: None Raises: No... |
def page_length(self, length): '''Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000. ''' mH = length/256 mL = length%256 if length < 12000: self.send(chr(2... |
def page_format(self, topmargin, bottommargin): '''Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top ... |
def left_margin(self, margin): '''Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter. ''' if margin <= 255 and margin >= 0: self.send(chr(27)+'I'+chr(margin)) else: raise RuntimeError('Invalid marg... |
def right_margin(self, margin): '''Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter ''' if margin >=1 and margin <=255: self.send(chr(27)+'Q'+chr(margin)) else: raise RuntimeError('Invalid marg... |
def vert_tab_pos(self, positions): '''Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeError: Too many positions. ''' if positions =... |
def forward_feed(self, amount): '''Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None Raises: RuntimeError: Invalid foward feed... |
def abs_vert_pos(self, amount): '''Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position. ''' mL = amount%256 mH = amount/256 if amount < 32767 and amount > 0: self.send(chr(2... |
def abs_horz_pos(self, amount): '''Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. Returns: None Raises:... |
def rel_horz_pos(self, amount): '''Calling this function sets the relative horizontal position for the next data, this is the position from the current position. The next character will be printed (x/180)inches away from the current position. The relative position CANNOT be specified to the left. This command is only v... |
def alignment(self, align): '''Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment. ''' if align=='left': align = '0' elif align=='center': align = '1' elif ali... |
def frame(self, action): '''Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' choices = {'on': '1', 'off': '0'} if action in choices: self.send(chr(27)+'if'+choices[action]) else: raise RuntimeError('Invalid actio... |
def bold(self, action): '''Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = 'E' elif action == 'off': action = 'F' else: raise RuntimeError('Invalid action for function bold. Options a... |
def italic(self, action): '''Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = '4' elif action=='off': action = '5' else: raise RuntimeError('Invalid action for function italic. Opt... |
def double_strike(self, action): '''Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 'G' elif action == 'off': action = 'H' else: raise RuntimeError('Invalid action fo... |
def double_width(self, action): '''Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = '1' elif action == 'off': action = '0' else: raise RuntimeError('Invalid action for f... |
def compressed_char(self, action): '''Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 15 elif action == 'off': action = 18 else: raise RuntimeError('I... |
def underline(self, action): '''Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None ''' if action == 'off': action = '0' self.send(chr(27)+chr(45)+action) else: self.send(chr(27)+chr(45)+action) |
def char_size(self, size): '''Changes font size Args: size: change font size. Options are 24' '32' '48' for bitmap fonts 33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233, 11, 44, 77, 111, 144 for outline fonts. Returns: None Raises: RuntimeError: Invalid font size. Warning: Your font is currentl... |
font is currently set to outline and you have selected a bitmap only font size') if size not in ['24', '32', '48'] and self.fonttype != self.font_types['outline']: raise Warning('Your font is currently set to bitmap and you have selected an outline only font size') self.send(chr(27)+'X'+chr(0)+chr(int(size))+chr(sizes[... |
def select_font(self, font): '''Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font: font type Returns: None Raises: RuntimeError: Invalid font. ''' fonts = {'brougham': 0, 'lette... |
def char_style(self, style): '''Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style ''' styleset = {'normal': 0, 'outline': 1, 'shadow': 2, 'outlineshadow': 3 } if style in styleset... |
def proportional_char(self, action): '''Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action. ''' actions = {'off': 0, 'on': 1 } if action in actions: self.send(chr(27)+'p'+... |
def char_spacing(self, dots): '''Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount. ''' if dots in range(0,127): self.send(chr(27)+chr(32)+chr(dots)) else: raise RuntimeError('Invalid dot amount in function charSpacing') |
def barcode(self, data, format, characters='off', height=48, width='small', parentheses='on', ratio='3:1', equalize='off', rss_symbol='rss14std', horiz_char_rss=2): '''Print a standard barcode in the specified format Args: data: the barcode data format: the barcode type you want. Choose between code39, itf, ean8/upca, ... |
b/w 2 and 20. ''' barcodes = {'code39': '0', 'itf': '1', 'ean8/upca': '5', 'upce': '6', 'codabar': '9', 'code128': 'a', 'gs1-128': 'b', 'rss': 'c'} widths = {'xsmall': '0', 'small': '1', 'medium': '2', 'large': '3'} ratios = {'3:1': '0', '2.5:1': '1', '2:1': '2'} rss_symbols = {'rss14std': '0', 'rss14trun': '1', 'rss14... |
chr(92)+ chr(92) self.send(sendstr) else: raise RuntimeError('Invalid parameters') |
def choose_template(self, template): '''Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None ''' n1 = int(template)/10 n2 = int(template)%10 self.send('^TS'+'0'+str(n1)+str(n2)) |
def machine_op(self, operation): '''Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation ''' operations = {'feed2start': 1, 'feedone': 2, 'cut': 3 } if operation in operations: self.send('^'+'O'+'P'+chr(operations[operation])) else: raise Runt... |
def print_start_trigger(self, type): '''Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type. ''' types = {'recieved': 1, 'filled': 2, 'num_recieved': 3} if type in types: self.send('^PT'+chr(types[type])) else: raise RuntimeError('Invalid type.') |
def print_start_command(self, command): '''Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long. ''' size = len(command) if size > 20: raise RuntimeError('Command too long') n1 = size/10 n2 = size%10 self.send('^PS'+chr(n1)+chr(n2)+command) |
def received_char_count(self, count): '''Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None ''' n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send('^PC'+chr(n1)+chr(n2)+chr(n3)) |
def select_delim(self, delim): '''Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long. ''' size = len(delim) if size > 20: raise RuntimeError('Delimeter too long') n1 = size/10 n2 = size%10 self.send('^SS'+chr(n1)+chr(n2)) |
def insert_into_obj(self, data): '''Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None ''' if not data: data = '' size = len(data) n1 = size%256 n2 = size/256 self.send('^DI'+chr(n1)+chr(n2)+data) |
def select_and_insert(self, name, data): '''Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None ''' self.select_obj(name) self.insert_into_obj(data) |
def connect_if_correct_version(db_path, version): """Return a sqlite3 database connection if the version in the database's metadata matches the version argument. Also implicitly checks for whether the data in this database has been completely filled, since we set the version last. TODO: Make an explicit 'complete' flag... |
def _create_cached_db( db_path, tables, version=1): """ Either create or retrieve sqlite database. Parameters -------- db_path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache.DatabaseTable objects version : int, optional Version acceptable as cached data. Returns sqlite3 co... |
tables] try: if db.has_tables(table_names) and \ db.has_version() and \ db.version() == version: logger.info("Found existing table in database %s", db_path) else: if len(db.table_names()) > 0: logger.info( "Dropping tables from database %s: %s", db_path, ", ".join(db.table_names())) db.drop_all_tables() logger.info( "C... |
def build_tables( table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}): """ Parameters ---------- table_names_to_dataframes : dict Dictionary mapping each table name to a DataFrame table_names_to_primary_keys : dict Dictionary mapping each table to its primary key table_names_to_indices... |
def db_from_dataframes_with_absolute_path( db_path, table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_path : str Path to database file to create table_names_to_d... |
def db_from_dataframes( db_filename, dataframes, primary_keys={}, indices={}, subdir=None, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_filename : str Name of database file to create dataframes : dict Dictionary from table names to DataFrame ... |
def db_from_dataframe( db_filename, table_name, df, primary_key=None, subdir=None, overwrite=False, indices=(), version=1): """ Given a dataframe `df`, turn it into a sqlite3 database. Store values in a table called `table_name`. Returns full path to the sqlite database file. """ return db_from_dataframes( db_filename=... |
def _db_filename_from_dataframe(base_filename, df): """ Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types. """ db_filename = base_filename + ("_nrows%d" % len(df)) for column_name in df.columns: column_db_type = db_type(d... |
def fetch_csv_db( table_name, download_url, csv_filename=None, db_filename=None, subdir=None, version=1, **pandas_kwargs): """ Download a remote CSV file and create a local sqlite3 database from its contents """ df = fetch_csv_dataframe( download_url=download_url, filename=csv_filename, subdir=subdir, **pandas_kwargs) ... |
def get_all(self, security): """ Get all available quote data for the given ticker security. Returns a dictionary. """ url = 'http://www.google.com/finance?q=%s' % security page = self._request(url) soup = BeautifulSoup(page) snapData = soup.find("table", {"class": "snap-data"}) if snapData is None: raise UfException(E... |
def quotes(self, security, start, end): """ Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list. """ try: url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (security.symbol, start, end) try: page = self._request(url) except UfExce... |
"Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc()) |
def financials(self, security): """ get financials: google finance provide annual and quanter financials, if annual is true, we will use annual data Up to four lastest year/quanter data will be provided by google Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii """ try: url = 'http://www.g... |
raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc()) |
def _parseTarget(self, target, keyTimeValue): ''' parse table for get financial ''' table = target.table timestamps = self._getTimeStamps(table) for tr in table.tbody.findChildren('tr'): for i, td in enumerate(tr.findChildren('td')): if 0 == i: key = td.getText() if key not in keyTimeValue: keyTimeValue[key] = {} else:... |
def _getTimeStamps(self, table): ''' get time stamps ''' timeStamps = [] for th in table.thead.tr.contents: if '\n' != th: timeStamps.append(th.getText()) return timeStamps[1:] |
def ticks(self, security, start, end): """ Get tick prices for the given ticker security. @security: stock security @interval: interval in mins(google finance only support query till 1 min) @start: start date(YYYYMMDD) @end: end date(YYYYMMDD) start and end is disabled since only 15 days data will show @Returns a neste... |
in days if len(day.split(',')) >= 6] for value in values: yield json.dumps({'date': value[0][1:].strip(), 'close': value[1].strip(), 'high': value[2].strip(), 'low': value[3].strip(), 'open': value[4].strip(), 'volume': value[5].strip()}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.