Search is not available for this dataset
text
stringlengths
75
104k
def get_orders(self, instrument=None, count=50): """ See more: http://developer.oanda.com/rest-live/orders/#getOrdersForAnAccount """ url = "{0}/{1}/accounts/{2}/orders".format( self.domain, self.API_VERSION, self.account_id ) ...
def get_order(self, order_id): """ See more: http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder """ url = "{0}/{1}/accounts/{2}/orders/{3}".format( self.domain, self.API_VERSION, self.account_id, order_id ...
def create_order(self, order): """ See more: http://developer.oanda.com/rest-live/orders/#createNewOrder """ url = "{0}/{1}/accounts/{2}/orders".format( self.domain, self.API_VERSION, self.account_id ) try: r...
def get_trades(self, max_id=None, count=None, instrument=None, ids=None): """ Get a list of open trades Parameters ---------- max_id : int The server will return trades with id less than or equal to this, in descending order (for pagination) ...
def update_trade( self, trade_id, stop_loss=None, take_profit=None, trailing_stop=None ): """ Modify an existing trade. Note: Only the specified parameters will be modified. All other parameters will remain unchanged. To remove an ...
def request_transaction_history(self): """ Request full account history. Submit a request for a full transaction history. A successfully accepted submission results in a response containing a URL in the Location header to a file that will be available once the r...
def get_transaction_history(self, max_wait=5.0): """ Download full account history. Uses request_transaction_history to get the transaction history URL, then polls the given URL until it's ready (or the max_wait time is reached) and provides the decoded response....
def create_account(self, currency=None): """ Create a new account. This call is only available on the sandbox system. Please create accounts on fxtrade.oanda.com on our production system. See more: http://developer.oanda.com/rest-sandbox/accounts/#-a...
def get_accounts(self, username=None): """ Get a list of accounts owned by the user. Parameters ---------- username : string The name of the user. Note: This is only required on the sandbox, on production systems your access token will ...
def choose(self): """Marks the item as the one the user is in.""" if not self.choosed: self.choosed = True self.pos = self.pos + Sep(5, 0)
def stop_choose(self): """Marks the item as the one the user is not in.""" if self.choosed: self.choosed = False self.pos = self.pos + Sep(-5, 0)
def get_darker_color(self): """The color of the clicked version of the MenuElement. Darker than the normal one.""" # we change a bit the color in one direction if bw_contrasted(self._true_color, 30) == WHITE: color = mix(self._true_color, WHITE, 0.9) else: color =...
def render(self, screen): """Renders the MenuElement""" self.rect.render(screen) super(MenuElement, self).render(screen)
def gui(): """Main function""" # ####### # setup all objects # ####### zones = [ALL] last_zones = [] COLORS.remove(WHITE) screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF) pygame.display.set_caption('Bezier simulator') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTT...
def gui(): """Main function""" # ####### # setup all objects # ####### os.environ['SDL_VIDEO_CENTERED'] = '1' clock = pygame.time.Clock() screen = pygame.display.set_mode(SCREEN_SIZE, DOUBLEBUF | NOFRAME) pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) game = Morpion() ...
def px_to_pt(self, px): """Convert a size in pxel to a size in points.""" if px < 200: pt = self.PX_TO_PT[px] else: pt = int(floor((px - 1.21) / 1.332)) return pt
def set_size(self, pt=None, px=None): """ Set the size of the font, in px or pt. The px method is a bit inacurate, there can be one or two px less, and max 4 for big numbers (like 503) but the size is never over-estimated. It makes almost the good value. """ assert (pt,...
def text(self): """Return the string to render.""" if callable(self._text): return str(self._text()) return str(self._text)
def color(self, value): """Set the color to a new value (tuple). Renders the text if needed.""" if value != self.color: self._color = value self._render()
def bg_color(self, value): """Sets the color to a new value (tuple). Renders the text if needed.""" if value != self.bg_color: self._bg_color = value self._render()
def set_font_size(self, pt=None, px=None): """Set the font size to the desired size, in pt or px.""" self.font.set_size(pt, px) self._render()
def _render(self): """ Render the text. Avoid using this fonction too many time as it is slow as it is low to render text and blit it. """ self._last_text = self.text self._surface = self.font.render(self.text, True, self.color, self.bg_color) rect = self._surf...
def render(self, display): """Render basicly the text.""" # to handle changing objects / callable if self.text != self._last_text: self._render() display.blit(self._surface, (self.topleft, self.size))
def cursor(self): """The position of the cursor in the text.""" if self._cursor < 0: self.cursor = 0 if self._cursor > len(self): self.cursor = len(self) return self._cursor
def move_cursor_one_letter(self, letter=RIGHT): """Move the cursor of one letter to the right (1) or the the left.""" assert letter in (self.RIGHT, self.LEFT) if letter == self.RIGHT: self.cursor += 1 if self.cursor > len(self.text): self.cursor -= 1 ...
def move_cursor_one_word(self, word=LEFT): """Move the cursor of one word to the right (1) or the the left (-1).""" assert word in (self.RIGHT, self.LEFT) if word == self.RIGHT: papy = self.text.find(' ', self.cursor) + 1 if not papy: papy = len(self) ...
def delete_one_letter(self, letter=RIGHT): """Delete one letter the right or the the left of the cursor.""" assert letter in (self.RIGHT, self.LEFT) if letter == self.LEFT: papy = self.cursor self.text = self.text[:self.cursor - 1] + self.text[self.cursor:] ...
def delete_one_word(self, word=RIGHT): """Delete one word the right or the the left of the cursor.""" assert word in (self.RIGHT, self.LEFT) if word == self.RIGHT: papy = self.text.find(' ', self.cursor) + 1 if not papy: papy = len(self.text) ...
def add_letter(self, letter): """Add a letter at the cursor pos.""" assert isinstance(letter, str) assert len(letter) == 1 self.text = self.text[:self.cursor] + letter + self.text[self.cursor:] self.cursor += 1
def update(self, event_or_list): """Update the text and position of cursor according to the event passed.""" event_or_list = super().update(event_or_list) for e in event_or_list: if e.type == KEYDOWN: if e.key == K_RIGHT: if e.mod * KMOD_CTRL: ...
def _render(self): """ Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. """ self._last_text = self.text self._surface = self.font.render(self.text, True, self.color, self.bg_color) size = self.wid...
def shawn_text(self): """The text displayed instead of the real one.""" if len(self._shawn_text) == len(self): return self._shawn_text if self.style == self.DOTS: return chr(0x2022) * len(self) ranges = [ (902, 1366), (192, 683), ...
def cursor_pos(self): """The cursor position in pixels.""" if len(self) == 0: return self.left + self.default_text.get_width() papy = self._surface.get_width() if papy > self.w: shift = papy - self.width else: shift = 0 return self.le...
def _render(self): """ Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. """ self._last_text = self.shawn_text self._surface = self.font.render(self.shawn_text, True, self.color, self.bg_color) siz...
def render(self, display): """Render basicly the text.""" # to handle changing objects / callable if self.shawn_text != self._last_text: self._render() if self.text: papy = self._surface.get_width() if papy <= self.width: display.blit...
def latex_to_img(tex): """Return a pygame image from a latex template.""" with tempfile.TemporaryDirectory() as tmpdirname: with open(tmpdirname + r'\tex.tex', 'w') as f: f.write(tex) os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-in...
def mix(color1, color2, pos=0.5): """ Return the mix of two colors at a state of :pos: Retruns color1 * pos + color2 * (1 - pos) """ opp_pos = 1 - pos red = color1[0] * pos + color2[0] * opp_pos green = color1[1] * pos + color2[1] * opp_pos blue = color1[2] * pos + color2[2] * opp_pos ...
def name2rgb(name): """Convert the name of a color into its RGB value""" try: import colour except ImportError: raise ImportError('You need colour to be installed: pip install colour') c = colour.Color(name) color = int(c.red * 255), int(c.green * 255), int(c.blue * 255) return ...
def parse_page(page): """Parse the command man page.""" colors = get_config()['colors'] with io.open(page, encoding='utf-8') as f: lines = f.readlines() output_lines = [] for line in lines[1:]: if is_headline(line): continue elif is_description(line): ...
def configure_logging(level=logging.DEBUG): """Configure the module logging engine.""" if level == logging.DEBUG: # For debugging purposes, log from everyone! logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' ) re...
def path_join(*args): """ Wrapper around `os.path.join`. Makes sure to join paths of the same type (bytes). """ args = (paramiko.py3compat.u(arg) for arg in args) return os.path.join(*args)
def parse_username_password_hostname(remote_url): """ Parse a command line string and return username, password, remote hostname and remote path. :param remote_url: A command line string. :return: A tuple, containing username, password, remote hostname and remote path. """ assert remote_url ...
def get_ssh_agent_keys(logger): """ Ask the SSH agent for a list of keys, and return it. :return: A reference to the SSH agent and a list of keys. """ agent, agent_keys = None, None try: agent = paramiko.agent.Agent() _agent_keys = agent.get_keys() if not _agent_keys: ...
def create_parser(): """Create the CLI argument parser.""" parser = argparse.ArgumentParser( description='Sync a local and a remote folder through SFTP.' ) parser.add_argument( "path", type=str, metavar="local-path", help="the path of the local folder", ) ...
def main(args=None): """The main.""" parser = create_parser() args = vars(parser.parse_args(args)) log_mapping = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, 'NOTSET': lo...
def _must_be_deleted(local_path, r_st): """Return True if the remote correspondent of local_path has to be deleted. i.e. if it doesn't exists locally or if it has a different type from the remote one.""" # if the file doesn't exists if not os.path.lexists(local_path): return...
def _match_modes(self, remote_path, l_st): """Match mod, utime and uid/gid with locals one.""" self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode)) self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime)) if self.chown: self.sftp.chown(remote_path, l_st.st_uid, l_st.st_gi...
def file_upload(self, local_path, remote_path, l_st): """Upload local_path to remote_path and set permission and mtime.""" self.sftp.put(local_path, remote_path) self._match_modes(remote_path, l_st)
def remote_delete(self, remote_path, r_st): """Remove the remote directory node.""" # If it's a directory, then delete content and directory if S_ISDIR(r_st.st_mode): for item in self.sftp.listdir_attr(remote_path): full_path = path_join(remote_path, item.filename) ...
def check_for_deletion(self, relative_path=None): """Traverse the entire remote_path tree. Find files/directories that need to be deleted, not being present in the local folder. """ if not relative_path: relative_path = str() # root of shared directory tree ...
def create_update_symlink(self, link_destination, remote_path): """Create a new link pointing to link_destination in remote_path position.""" try: # if there's anything, delete it self.sftp.remove(remote_path) except IOError: # that's fine, nothing exists there! pass ...
def node_check_for_upload_create(self, relative_path, f): """Check if the given directory tree node has to be uploaded/created on the remote folder.""" if not relative_path: # we're at the root of the shared directory tree relative_path = str() # the (absolute) local add...
def check_for_upload_create(self, relative_path=None): """Traverse the relative_path tree and check for files that need to be uploaded/created. Relativity here refers to the shared directory tree.""" for f in os.listdir( path_join( self.local_path, relative_path) if ...
def run(self): """Run the sync. Confront the local and the remote directories and perform the needed changes.""" # Check if remote path is present try: self.sftp.stat(self.remote_path) except FileNotFoundError as e: if self.create_remote_directory: ...
def list_files(start_path): """tree unix command replacement.""" s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) sub_indent = ' ' * 4 * (...
def file_tree(start_path): """ Create a nested dictionary that represents the folder structure of `start_path`. Liberally adapted from http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/ """ nested_dirs = {} root_dir = start_path.rstrip(os.sep) start = roo...
def capture_sys_output(): """Capture standard output and error.""" capture_out, capture_err = StringIO(), StringIO() current_out, current_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = capture_out, capture_err yield capture_out, capture_err finally: sys.stdout, sy...
def suppress_logging(log_level=logging.CRITICAL): """Suppress logging.""" logging.disable(log_level) yield logging.disable(logging.NOTSET)
def override_env_variables(): """Override user environmental variables with custom one.""" env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME") old = [os.environ[v] if v in os.environ else None for v in env_vars] for v in env_vars: os.environ[v] = "test" yield for i, v in enumerate(env_...
def override_ssh_auth_env(): """Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent.""" ssh_auth_sock = "SSH_AUTH_SOCK" old_ssh_auth_sock = os.environ.get(ssh_auth_sock) del os.environ[ssh_auth_sock] yield if old_ssh_auth_sock: os.environ[ssh_auth_sock] = ol...
def get_config(): """Get the configurations from .tldrrc and return it as a dict.""" config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if not path.exists(config_path): sys.exit("Can't find config file at: {0}. You may use `tldr init` " ...
def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
def find_page_location(command, specified_platform): """Find the command man page in the pages directory.""" repo_directory = get_config()['repo_directory'] default_platform = get_config()['platform'] command_platform = ( specified_platform if specified_platform else default_platform) with ...
def find(command, on): """Find the command usage.""" output_lines = parse_man_page(command, on) click.echo(''.join(output_lines))
def update(): """Update to the latest pages.""" repo_directory = get_config()['repo_directory'] os.chdir(repo_directory) click.echo("Check for updates...") local = subprocess.check_output('git rev-parse master'.split()).strip() remote = subprocess.check_output( 'git ls-remote https://gi...
def init(): """Init config file.""" default_config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if path.exists(default_config_path): click.echo("There is already a config file exists, " "skip initializing it.") else:...
def locate(command, on): """Locate the command's man page.""" location = find_page_location(command, on) click.echo(location)
def relate(cls, propname, *args, **kwargs): """Produce a relationship between this mapped table and another one. This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship` construct. """ class_mapper(cls)._configure_property(propname, relation...
def execute(self, stmt, **params): """Execute a SQL statement. The statement may be a string SQL string, an :func:`sqlalchemy.sql.expression.select` construct, or a :func:`sqlalchemy.sql.expression.text` construct. """ return self.session.execute(sql.text(stmt...
def map_to(self, attrname, tablename=None, selectable=None, schema=None, base=None, mapper_args=util.immutabledict()): """Configure a mapping to the given attrname. This is the "master" method that can be used to create any configuration. :param attrname: String a...
def map(self, selectable, base=None, **mapper_args): """Map a selectable directly. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param selectable: an :func:`.expression.select` construct. :param base: a Python class which will ...
def with_labels(self, selectable, base=None, **mapper_args): """Map a selectable directly, wrapping the selectable in a subquery with labels. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param selectable: an :func:`.expressio...
def join(self, left, right, onclause=None, isouter=False, base=None, **mapper_args): """Create an :func:`.expression.join` and map to it. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param left: a mapped class or tabl...
def entity(self, attr, schema=None): """Return the named entity from this :class:`.SQLSoup`, or create if not present. For more generalized mapping, see :meth:`.map_to`. """ try: return self._cache[attr] except KeyError, ke: return self.map_to(a...
def distance(f1, f2): """\ Distance between 2 features. The integer result is always positive or zero. If the features overlap or touch, it is zero. >>> from intersecter import Feature, distance >>> distance(Feature(1, 2), Feature(12, 13)) 10 >>> distance(Feature(1, 2), Feature(2, 3)) 0 ...
def find(self, start, end, chrom=None): """Return a object of all stored intervals intersecting between (start, end) inclusive.""" intervals = self.intervals[chrom] ilen = len(intervals) # NOTE: we only search for starts, since any feature that starts within max_len of # the quer...
def left(self, f, n=1): """return the nearest n features strictly to the left of a Feature f. Overlapping features are not considered as to the left. f: a Feature object n: the number of features to return """ intervals = self.intervals[f.chrom] if intervals == [...
def right(self, f, n=1): """return the nearest n features strictly to the right of a Feature f. Overlapping features are not considered as to the right. f: a Feature object n: the number of features to return """ intervals = self.intervals[f.chrom] ilen = len(int...
def upstream(self, f, n=1): """find n upstream features where upstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return """ if f.strand == -1: return se...
def downstream(self, f, n=1): """find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return """ if f.strand == -1: ret...
def knearest(self, f_or_start, end=None, chrom=None, k=1): """return the n nearest neighbors to the given feature f: a Feature object k: the number of features to return """ if end is not None: f = Feature(f_or_start, end, chrom=chrom) else: f = ...
def find(self, start, end): """find all elements between (or overlapping) start and end""" if self.intervals and not end < self.intervals[0].start: overlapping = [i for i in self.intervals if i.end >= start and i.start <= end] else:...
def sequence(db, chrom, start, end): """ return the sequence for a region using the UCSC DAS server. note the start is 1-based each feature will have it's own .sequence method which sends the correct start and end to this function. >>> sequence('hg18', 'chr2', 2223, 2230) 'caacttag' """...
def set_table(genome, table, table_name, connection_string, metadata): """ alter the table to work between different dialects """ table = Table(table_name, genome._metadata, autoload=True, autoload_with=genome.bind, extend_existing=True) #print "\t".join([c.name for c in tab...
def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu", password="", dialect="mysqldb"): """ internal: create a dburl from a set of parameters or the defaults on this object """ if os.path.exists(db): db = "sqlite:///" + db # Is t...
def mirror(self, tables, dest_url): """ miror a set of `tables` from `dest_url` Returns a new Genome object Parameters ---------- tables : list an iterable of tables dest_url: str a dburl string, e.g. 'sqlite:///local.db' """ ...
def dataframe(self, table): """ create a pandas dataframe from a table or query Parameters ---------- table : table a table in this database or a query limit: integer an integer limit on the query offset: integer an offset f...
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None): """ use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file t...
def david_go(refseq_list, annot=('SP_PIR_KEYWORDS', 'GOTERM_BP_FAT', 'GOTERM_CC_FAT', 'GOTERM_MF_FAT')): """ open a web-browser to the DAVID online enrichment tool Parameters ---------- refseq_list : list list of refseq names ...
def bin_query(self, table, chrom, start, end): """ perform an efficient spatial query using the bin column if available. The possible bins are calculated from the `start` and `end` sent to this function. Parameters ---------- table : str or table tabl...
def upstream(self, table, chrom_or_feat, start=None, end=None, k=1): """ Return k-nearest upstream features Parameters ---------- table : str or table table against which to query chrom_or_feat : str or feat either a chromosome, e.g. 'chr3' or a...
def knearest(self, table, chrom_or_feat, start=None, end=None, k=1, _direction=None): """ Return k-nearest features Parameters ---------- table : str or table table against which to query chrom_or_feat : str or feat either a chromoso...
def annotate(self, fname, tables, feature_strand=False, in_memory=False, header=None, out=sys.stdout, parallel=False): """ annotate a file with a number of tables Parameters ---------- fname : str or file file name or file-handle tables : list ...
def bins(start, end): """ Get all the bin numbers for a particular interval defined by (start, end] """ if end - start < 536870912: offsets = [585, 73, 9, 1] else: raise BigException offsets = [4681, 585, 73, 9, 1] binFirstShift...
def save_bed(cls, query, filename=sys.stdout): """ write a bed12 file of the query. Parameters ---------- query : query a table or query to save to file filename : file string or filehandle to write output """ out = _open(filename...
def staticfile_node(parser, token, optimize_if_possible=False): """For example: {% staticfile "/js/foo.js" %} or {% staticfile "/js/foo.js" as variable_name %} Or for multiples: {% staticfile "/foo.js; /bar.js" %} or {% staticfile "/foo.js; /bar.js" as varia...
def _mkdir(newdir): """works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ if os.path.isdir(newdir): pass elif os.path.isfile(newdir): ...
def _find_filepath_in_roots(filename): """Look for filename in all MEDIA_ROOTS, and return the first one found.""" for root in settings.DJANGO_STATIC_MEDIA_ROOTS: filepath = _filename2filepath(filename, root) if os.path.isfile(filepath): return filepath, root # havent found it in...
def default_combine_filenames_generator(filenames, max_length=40): """Return a new filename to use as the combined file name for a bunch of files. A precondition is that they all have the same file extension Given that the list of files can have different paths, we aim to use the most common path. ...
def render(self, context): """inspect the code and look for files that can be turned into combos. Basically, the developer could type this: {% slimall %} <link href="/one.css"/> <link href="/two.css"/> {% endslimall %} And it should be reconsidered like this: ...