Code
stringlengths
103
85.9k
Summary
sequencelengths
0
94
Please provide a description of the function:def run_azure(target, jobs, n=1, nproc=None, path='.', delete=True, config=None, **kwargs): import ecell4.extra.azure_batch as azure_batch return azure_batch.run_azure(target, jobs, n, path, delete, config)
[ "\n Evaluate the given function with each set of arguments, and return a list of results.\n This function does in parallel with Microsoft Azure Batch.\n\n This function is the work in progress.\n The argument `nproc` doesn't work yet.\n See `ecell4.extra.azure_batch.run_azure` for details.\n\n See Also\n --------\n ecell4.extra.ensemble.run_serial\n ecell4.extra.ensemble.run_sge\n ecell4.extra.ensemble.run_slurm\n ecell4.extra.ensemble.run_multiprocessing\n ecell4.extra.ensemble.run_azure\n ecell4.extra.azure_batch.run_azure\n\n " ]
Please provide a description of the function:def getseed(myseed, i): rndseed = int(myseed[(i - 1) * 8: i * 8], 16) rndseed = rndseed % (2 ** 31) #XXX: trancate the first bit return rndseed
[ "\n Return a single seed from a long seed given by `genseeds`.\n\n Parameters\n ----------\n myseed : bytes\n A long seed given by `genseeds(n)`.\n i : int\n An index less than n.\n\n Returns\n -------\n rndseed : int\n A seed (less than (2 ** 31))\n\n " ]
Please provide a description of the function:def list_species(model, seeds=None): seeds = None or [] from ecell4_base.core import Species if not isinstance(seeds, list): seeds = list(seeds) expanded = model.expand([Species(serial) for serial in seeds]) species_list = [sp.serial() for sp in expanded.list_species()] species_list = sorted(set(seeds + species_list)) return species_list
[ "This function is deprecated." ]
Please provide a description of the function:def ensemble_simulations( t, y0=None, volume=1.0, model=None, solver='ode', is_netfree=False, species_list=None, without_reset=False, return_type='matplotlib', opt_args=(), opt_kwargs=None, structures=None, rndseed=None, n=1, nproc=None, method=None, errorbar=True, **kwargs): y0 = y0 or {} opt_kwargs = opt_kwargs or {} structures = structures or {} for key, value in kwargs.items(): if key == 'r': return_type = value elif key == 'v': volume = value elif key == 's': solver = value elif key == 'm': model = value if model is None: model = ecell4.util.decorator.get_model(is_netfree, without_reset) if species_list is None: species_list = list_species(model, y0.keys()) if rndseed is None: myseed = genseeds(n) elif (not isinstance(rndseed, bytes) or len(rndseed) != n * 4 * 2): raise ValueError( "A wrong seed for the random number generation was given. Use 'genseeds'.") jobs = [{'t': t, 'y0': y0, 'volume': volume, 'model': model, 'solver': solver, 'species_list': species_list, 'structures': structures, 'myseed': myseed}] if method is None or method.lower() == "serial": retval = run_serial(singlerun, jobs, n=n, **kwargs) elif method.lower() == "sge": retval = run_sge(singlerun, jobs, n=n, nproc=nproc, **kwargs) elif method.lower() == "slurm": retval = run_slurm(singlerun, jobs, n=n, nproc=nproc, **kwargs) elif method.lower() == "multiprocessing": retval = run_multiprocessing(singlerun, jobs, n=n, nproc=nproc, **kwargs) elif method.lower() == "azure": retval = run_azure(singlerun, jobs, n=n, nproc=nproc, **kwargs) else: raise ValueError( 'Argument "method" must be one of "serial", "multiprocessing", "slurm" and "sge".') if return_type is None or return_type in ("none", ): return assert len(retval) == len(jobs) == 1 if return_type in ("array", 'a'): return retval[0] import numpy class DummyObserver: def __init__(self, inputs, species_list, errorbar=True): if len(inputs) == 0: raise ValueError("No input was given.") t = numpy.array(inputs[0], numpy.float64).T[0] mean = sum([numpy.array(data, numpy.float64).T[1: ] for data in inputs]) mean /= len(inputs) self.__data = numpy.vstack([t, mean]).T if errorbar: var = sum([(numpy.array(data, numpy.float64).T[1: ] - mean) ** 2 for data in inputs]) / len(inputs) stdev = numpy.sqrt(var) stder = stdev / numpy.sqrt(len(inputs)) # self.__error = numpy.vstack([t, stdev]).T self.__error = numpy.vstack([t, stder]).T else: self.__error = None self.__species_list = [ecell4_base.core.Species(serial) for serial in species_list] def targets(self): return self.__species_list def data(self): return self.__data def t(self): return self.__data.T[0] def error(self): return self.__error def save(self, filename): with open(filename, 'w') as fout: writer = csv.writer(fout, delimiter=',', lineterminator='\n') writer.writerow(['"{}"'.format(sp.serial()) for sp in self.__species_list]) writer.writerows(self.data()) if return_type in ("matplotlib", 'm'): if isinstance(opt_args, (list, tuple)): ecell4.util.viz.plot_number_observer_with_matplotlib( DummyObserver(retval[0], species_list, errorbar), *opt_args, **opt_kwargs) elif isinstance(opt_args, dict): # opt_kwargs is ignored ecell4.util.viz.plot_number_observer_with_matplotlib( DummyObserver(retval[0], species_list, errorbar), **opt_args) else: raise ValueError('opt_args [{}] must be list or dict.'.format( repr(opt_args))) elif return_type in ("nyaplot", 'n'): if isinstance(opt_args, (list, tuple)): ecell4.util.viz.plot_number_observer_with_nya( DummyObserver(retval[0], species_list, errorbar), *opt_args, **opt_kwargs) elif isinstance(opt_args, dict): # opt_kwargs is ignored ecell4.util.viz.plot_number_observer_with_nya( DummyObserver(retval[0], species_list, errorbar), **opt_args) else: raise ValueError('opt_args [{}] must be list or dict.'.format( repr(opt_args))) elif return_type in ("observer", 'o'): return DummyObserver(retval[0], species_list, errorbar) elif return_type in ("dataframe", 'd'): import pandas return [ pandas.concat([ pandas.DataFrame(dict(Time=numpy.array(data).T[0], Value=numpy.array(data).T[i + 1], Species=serial)) for i, serial in enumerate(species_list)]) for data in retval[0]] else: raise ValueError( 'An invald value for "return_type" was given [{}].'.format(str(return_type)) + 'Use "none" if you need nothing to be returned.')
[ "\n Run simulations multiple times and return its ensemble.\n Arguments are almost same with ``ecell4.util.simulation.run_simulation``.\n `observers` and `progressbar` is not available here.\n\n Parameters\n ----------\n n : int, optional\n A number of runs. Default is 1.\n nproc : int, optional\n A number of processors. Ignored when method='serial'.\n Default is None.\n method : str, optional\n The way for running multiple jobs.\n Choose one from 'serial', 'multiprocessing', 'sge', 'slurm', 'azure'.\n Default is None, which works as 'serial'.\n **kwargs : dict, optional\n Optional keyword arugments are passed through to `run_serial`,\n `run_sge`, or `run_multiprocessing`.\n See each function for more details.\n\n Returns\n -------\n value : list, DummyObserver, or None\n Return a value suggested by ``return_type``.\n When ``return_type`` is 'array', return a time course data.\n When ``return_type`` is 'observer', return a DummyObserver.\n DummyObserver is a wrapper, which has the almost same interface\n with NumberObservers.\n Return nothing if else.\n\n See Also\n --------\n ecell4.util.simulation.run_simulation\n ecell4.extra.ensemble.run_serial\n ecell4.extra.ensemble.run_sge\n ecell4.extra.ensemble.run_slurm\n ecell4.extra.ensemble.run_multiprocessing\n ecell4.extra.ensemble.run_azure\n\n " ]
Please provide a description of the function:def save_bd5( space, filename, group_index=0, object_name="molecule", spatial_unit="meter", time_unit="second", trunc=False, with_radius=False): if isinstance(space, (list, tuple, set)): for i, space_ in enumerate(space): assert not isinstance(space_, (list, tuple, set)) save_bd5( space_, filename, group_index + i, object_name, spatial_unit, time_unit, trunc if i == 0 else False, with_radius) elif isinstance(space, str): save_bd5(load_world(space), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius) elif isinstance(space, pathlib.PurePath): save_bd5(str(space), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius) else: # space is expected to be either Space or World. _save_bd5(space.as_base(), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius)
[ "Save a space in the BDML-BD5 format (https://github.com/openssbd/BDML-BD5).\n\n Open file for read/write, if it already exists, and create a new file, otherwise.\n If trunc is True, always create a new file.\n A new group named `group_name` is created. If the group already exists, returns\n an exception.\n\n Parameters\n ----------\n space : Space, str, pathlib.PurePath, list, tuple or set\n A Space or World to be saved. If str or pathlib.PurePath is given, a space is\n loaded from the given path. If this is an iterable (list, tuple, set), apply\n this function to each element of the given.\n filename : str\n A HDF5 filename.\n group_index : int, optional\n An index of the group written (0, 1, ..., n). Defaults to 0.\n object_name : str, optional\n A name of the object. Its length must be less than 128. Defaults to \"molecule\".\n spatial_unit : str, optional\n An unit of the length scale. Its length must be less than 16. Defaults to \"meter\".\n time_unit : str, optional\n An unit of the time scale. Its length must be less than 16. Defaults to \"second\".\n trunc : bool, optional\n Whether truncate file or not. If True, always overwrite the file when open it.\n Defaults to False.\n with_radius : bool, optional\n Whether save the radius of particles. If True, particles are saved as 'sphere',\n otherwise, as 'point'. Defaults to False.\n\n " ]
Please provide a description of the function:def _escapeCharacters(tag): for i,c in enumerate(tag.contents): if type(c) != bs4.element.NavigableString: continue c.replace_with(_escapeCharSub(r'\\\1', c))
[ "non-recursively escape underlines and asterisks\n\tin the tag" ]
Please provide a description of the function:def _breakRemNewlines(tag): for i,c in enumerate(tag.contents): if type(c) != bs4.element.NavigableString: continue c.replace_with(re.sub(r' {2,}', ' ', c).replace('\n',''))
[ "non-recursively break spaces and remove newlines in the tag" ]
Please provide a description of the function:def _markdownify(tag, _listType=None, _blockQuote=False, _listIndex=1): children = tag.find_all(recursive=False) if tag.name == '[document]': for child in children: _markdownify(child) return if tag.name not in _supportedTags or not _supportedAttrs(tag): if tag.name not in _inlineTags: tag.insert_before('\n\n') tag.insert_after('\n\n') else: _escapeCharacters(tag) for child in children: _markdownify(child) return if tag.name not in ('pre', 'code'): _escapeCharacters(tag) _breakRemNewlines(tag) if tag.name == 'p': if tag.string != None: if tag.string.strip() == u'': tag.string = u'\xa0' tag.unwrap() return if not _blockQuote: tag.insert_before('\n\n') tag.insert_after('\n\n') else: tag.insert_before('\n') tag.insert_after('\n') tag.unwrap() for child in children: _markdownify(child) elif tag.name == 'br': tag.string = ' \n' tag.unwrap() elif tag.name == 'img': alt = '' title = '' if tag.has_attr('alt'): alt = tag['alt'] if tag.has_attr('title') and tag['title']: title = ' "%s"' % tag['title'] tag.string = '![%s](%s%s)' % (alt, tag['src'], title) tag.unwrap() elif tag.name == 'hr': tag.string = '\n---\n' tag.unwrap() elif tag.name == 'pre': tag.insert_before('\n\n') tag.insert_after('\n\n') if tag.code: if not _supportedAttrs(tag.code): return for child in tag.code.find_all(recursive=False): if child.name != 'br': return # code block for br in tag.code.find_all('br'): br.string = '\n' br.unwrap() tag.code.unwrap() lines = unicode(tag).strip().split('\n') lines[0] = lines[0][5:] lines[-1] = lines[-1][:-6] if not lines[-1]: lines.pop() for i,line in enumerate(lines): line = line.replace(u'\xa0', ' ') lines[i] = ' %s' % line tag.replace_with(BeautifulSoup('\n'.join(lines), 'html.parser')) return elif tag.name == 'code': # inline code if children: return tag.insert_before('`` ') tag.insert_after(' ``') tag.unwrap() elif _recursivelyValid(tag): if tag.name == 'blockquote': # ! FIXME: hack tag.insert_before('<<<BLOCKQUOTE: ') tag.insert_after('>>>') tag.unwrap() for child in children: _markdownify(child, _blockQuote=True) return elif tag.name == 'a': # process children first for child in children: _markdownify(child) if not tag.has_attr('href'): return if tag.string != tag.get('href') or tag.has_attr('title'): title = '' if tag.has_attr('title'): title = ' "%s"' % tag['title'] tag.string = '[%s](%s%s)' % (BeautifulSoup(unicode(tag), 'html.parser').string, tag.get('href', ''), title) else: # ! FIXME: hack tag.string = '<<<FLOATING LINK: %s>>>' % tag.string tag.unwrap() return elif tag.name == 'h1': tag.insert_before('\n\n# ') tag.insert_after('\n\n') tag.unwrap() elif tag.name == 'h2': tag.insert_before('\n\n## ') tag.insert_after('\n\n') tag.unwrap() elif tag.name == 'h3': tag.insert_before('\n\n### ') tag.insert_after('\n\n') tag.unwrap() elif tag.name == 'h4': tag.insert_before('\n\n#### ') tag.insert_after('\n\n') tag.unwrap() elif tag.name == 'h5': tag.insert_before('\n\n##### ') tag.insert_after('\n\n') tag.unwrap() elif tag.name == 'h6': tag.insert_before('\n\n###### ') tag.insert_after('\n\n') tag.unwrap() elif tag.name in ('ul', 'ol'): tag.insert_before('\n\n') tag.insert_after('\n\n') tag.unwrap() for i, child in enumerate(children): _markdownify(child, _listType=tag.name, _listIndex=i+1) return elif tag.name == 'li': if not _listType: # <li> outside of list; ignore return if _listType == 'ul': tag.insert_before('* ') else: tag.insert_before('%d. ' % _listIndex) for child in children: _markdownify(child) for c in tag.contents: if type(c) != bs4.element.NavigableString: continue c.replace_with('\n '.join(c.split('\n'))) tag.insert_after('\n') tag.unwrap() return elif tag.name in ('strong','b'): tag.insert_before('__') tag.insert_after('__') tag.unwrap() elif tag.name in ('em','i'): tag.insert_before('_') tag.insert_after('_') tag.unwrap() for child in children: _markdownify(child)
[ "recursively converts a tag into markdown" ]
Please provide a description of the function:def convert(html): bs = BeautifulSoup(html, 'html.parser') _markdownify(bs) ret = unicode(bs).replace(u'\xa0', '&nbsp;') ret = re.sub(r'\n{3,}', r'\n\n', ret) # ! FIXME: hack ret = re.sub(r'&lt;&lt;&lt;FLOATING LINK: (.+)&gt;&gt;&gt;', r'<\1>', ret) # ! FIXME: hack sp = re.split(r'(&lt;&lt;&lt;BLOCKQUOTE: .*?&gt;&gt;&gt;)', ret, flags=re.DOTALL) for i,e in enumerate(sp): if e[:len('&lt;&lt;&lt;BLOCKQUOTE:')] == '&lt;&lt;&lt;BLOCKQUOTE:': sp[i] = '> ' + e[len('&lt;&lt;&lt;BLOCKQUOTE:') : -len('&gt;&gt;&gt;')] sp[i] = sp[i].replace('\n', '\n> ') ret = ''.join(sp) return ret.strip('\n')
[ "converts an html string to markdown while preserving unsupported markup." ]
Please provide a description of the function:def create(cls, type): if type == 0: return FilterDropShadow(id) elif type == 1: return FilterBlur(id) elif type == 2: return FilterGlow(id) elif type == 3: return FilterBevel(id) elif type == 4: return FilterGradientGlow(id) elif type == 5: return FilterConvolution(id) elif type == 6: return FilterColorMatrix(id) elif type == 7: return FilterGradientBevel(id) else: raise Exception("Unknown filter type: %d" % type)
[ " Return the specified Filter " ]
Please provide a description of the function:def dimensions(self): return (self.xmax - self.xmin, self.ymax - self.ymin)
[ "\n Returns dimensions as (x, y) tuple.\n " ]
Please provide a description of the function:def export(self, exporter=None, force_stroke=False): exporter = SVGExporter() if exporter is None else exporter if self._data is None: raise Exception("This SWF was not loaded! (no data)") if len(self.tags) == 0: raise Exception("This SWF doesn't contain any tags!") return exporter.export(self, force_stroke)
[ "\n Export this SWF using the specified exporter. \n When no exporter is passed in the default exporter used \n is swf.export.SVGExporter.\n \n Exporters should extend the swf.export.BaseExporter class.\n \n @param exporter : the exporter to use\n @param force_stroke : set to true to force strokes on fills,\n useful for some edge cases.\n " ]
Please provide a description of the function:def parse(self, data): self._data = data = data if isinstance(data, SWFStream) else SWFStream(data) self._header = SWFHeader(self._data) if self._header.compressed: temp = BytesIO() if self._header.compressed_zlib: import zlib data = data.f.read() zip = zlib.decompressobj() temp.write(zip.decompress(data)) else: import pylzma data.readUI32() #consume compressed length data = data.f.read() temp.write(pylzma.decompress(data)) temp.seek(0) data = SWFStream(temp) self._header._frame_size = data.readRECT() self._header._frame_rate = data.readFIXED8() self._header._frame_count = data.readUI16() self.parse_tags(data)
[ " \n Parses the SWF.\n \n The @data parameter can be a file object or a SWFStream\n " ]
Please provide a description of the function:def int32(x): if x>0xFFFFFFFF: raise OverflowError if x>0x7FFFFFFF: x=int(0x100000000-x) if x<2147483648: return -x else: return -2147483648 return x
[ " Return a signed or unsigned int " ]
Please provide a description of the function:def bin(self, s): return str(s) if s<=1 else bin(s>>1) + str(s&1)
[ " Return a value as a binary string " ]
Please provide a description of the function:def calc_max_bits(self, signed, values): b = 0 vmax = -10000000 for val in values: if signed: b = b | val if val >= 0 else b | ~val << 1 vmax = val if vmax < val else vmax else: b |= val; bits = 0 if b > 0: bits = len(self.bin(b)) - 2 if signed and vmax > 0 and len(self.bin(vmax)) - 2 >= bits: bits += 1 return bits
[ " Calculates the maximim needed bits to represent a value " ]
Please provide a description of the function:def readbits(self, bits): if bits == 0: return 0 # fast byte-aligned path if bits % 8 == 0 and self._bits_pending == 0: return self._read_bytes_aligned(bits // 8) out = 0 masks = self._masks def transfer_bits(x, y, n, t): if n == t: # taking all return (x << t) | y, 0 mask = masks[t] # (1 << t) - 1 remainmask = masks[n - t] # (1 << n - t) - 1 taken = ((y >> n - t) & mask) return (x << t) | taken, y & remainmask while bits > 0: if self._bits_pending > 0: assert self._partial_byte is not None take = min(self._bits_pending, bits) out, self._partial_byte = transfer_bits(out, self._partial_byte, self._bits_pending, take) if take == self._bits_pending: # we took them all self._partial_byte = None self._bits_pending -= take bits -= take continue r = self.f.read(1) if r == b'': raise EOFError self._partial_byte = ord(r) self._bits_pending = 8 return out
[ "\n Read the specified number of bits from the stream.\n Returns 0 for bits == 0.\n ", "\n transfers t bits from the top of y_n to the bottom of x.\n then returns x and the remaining bits in y\n " ]
Please provide a description of the function:def readSB(self, bits): shift = 32 - bits return int32(self.readbits(bits) << shift) >> shift
[ " Read a signed int using the specified number of bits " ]
Please provide a description of the function:def readEncodedU32(self): self.reset_bits_pending(); result = self.readUI8(); if result & 0x80 != 0: result = (result & 0x7f) | (self.readUI8() << 7) if result & 0x4000 != 0: result = (result & 0x3fff) | (self.readUI8() << 14) if result & 0x200000 != 0: result = (result & 0x1fffff) | (self.readUI8() << 21) if result & 0x10000000 != 0: result = (result & 0xfffffff) | (self.readUI8() << 28) return result
[ " Read a encoded unsigned int " ]
Please provide a description of the function:def readFLOAT16(self): self.reset_bits_pending() word = self.readUI16() sign = -1 if ((word & 0x8000) != 0) else 1 exponent = (word >> 10) & 0x1f significand = word & 0x3ff if exponent == 0: if significand == 0: return 0.0 else: return sign * math.pow(2, 1 - SWFStream.FLOAT16_EXPONENT_BASE) * (significand / 1024.0) if exponent == 31: if significand == 0: return float('-inf') if sign < 0 else float('inf') else: return float('nan') # normal number return sign * math.pow(2, exponent - SWFStream.FLOAT16_EXPONENT_BASE) * (1 + significand / 1024.0)
[ " Read a 2 byte float " ]
Please provide a description of the function:def readSTYLECHANGERECORD(self, states, fill_bits, line_bits, level = 1): return SWFShapeRecordStyleChange(self, states, fill_bits, line_bits, level)
[ " Read a SWFShapeRecordStyleChange " ]
Please provide a description of the function:def readTEXTRECORD(self, glyphBits, advanceBits, previousRecord=None, level=1): if self.readUI8() == 0: return None else: self.seek(self.tell() - 1) return SWFTextRecord(self, glyphBits, advanceBits, previousRecord, level)
[ " Read a SWFTextRecord " ]
Please provide a description of the function:def readACTIONRECORD(self): action = None actionCode = self.readUI8() if actionCode != 0: actionLength = self.readUI16() if actionCode >= 0x80 else 0 #print "0x%x"%actionCode, actionLength action = SWFActionFactory.create(actionCode, actionLength) action.parse(self) return action
[ " Read a SWFActionRecord " ]
Please provide a description of the function:def readACTIONRECORDs(self): out = [] while 1: action = self.readACTIONRECORD() if action: out.append(action) else: break return out
[ " Read zero or more button records (zero-terminated) " ]
Please provide a description of the function:def readCLIPACTIONRECORD(self, version): pos = self.tell() flags = self.readUI32() if version >= 6 else self.readUI16() if flags == 0: return None else: self.seek(pos) return SWFClipActionRecord(self, version)
[ " Read a SWFClipActionRecord " ]
Please provide a description of the function:def readRGB(self): self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() return (0xff << 24) | (r << 16) | (g << 8) | b
[ " Read a RGB color " ]
Please provide a description of the function:def readRGBA(self): self.reset_bits_pending(); r = self.readUI8() g = self.readUI8() b = self.readUI8() a = self.readUI8() return (a << 24) | (r << 16) | (g << 8) | b
[ " Read a RGBA color " ]
Please provide a description of the function:def readString(self): s = self.f.read(1) string = b"" while ord(s) > 0: string += s s = self.f.read(1) return string.decode()
[ " Read a string " ]
Please provide a description of the function:def readFILTER(self): filterId = self.readUI8() filter = SWFFilterFactory.create(filterId) filter.parse(self) return filter
[ " Read a SWFFilter " ]
Please provide a description of the function:def readFILTERLIST(self): number = self.readUI8() return [self.readFILTER() for _ in range(number)]
[ " Read a length-prefixed list of FILTERs " ]
Please provide a description of the function:def readBUTTONRECORDs(self, version): out = [] while 1: button = self.readBUTTONRECORD(version) if button: out.append(button) else: break return out
[ " Read zero or more button records (zero-terminated) " ]
Please provide a description of the function:def readBUTTONCONDACTIONSs(self): out = [] while 1: action = self.readBUTTONCONDACTION() if action: out.append(action) else: break return out
[ " Read zero or more button-condition actions " ]
Please provide a description of the function:def readtag_header(self): pos = self.tell() tag_type_and_length = self.readUI16() tag_length = tag_type_and_length & 0x003f if tag_length == 0x3f: # The SWF10 spec sez that this is a signed int. # Shouldn't it be an unsigned int? tag_length = self.readSI32(); return SWFRecordHeader(tag_type_and_length >> 6, tag_length, self.tell() - pos)
[ " Read a tag header " ]
Please provide a description of the function:def read(self, count=0): return self.f.read(count) if count > 0 else self.f.read()
[ " Read " ]
Please provide a description of the function:def create(cls, type): if type == 0: return TagEnd() elif type == 1: return TagShowFrame() elif type == 2: return TagDefineShape() elif type == 4: return TagPlaceObject() elif type == 5: return TagRemoveObject() elif type == 6: return TagDefineBits() elif type == 7: return TagDefineButton() elif type == 8: return TagJPEGTables() elif type == 9: return TagSetBackgroundColor() elif type == 10: return TagDefineFont() elif type == 11: return TagDefineText() elif type == 12: return TagDoAction() elif type == 13: return TagDefineFontInfo() elif type == 14: return TagDefineSound() elif type == 15: return TagStartSound() elif type == 17: return TagDefineButtonSound() elif type == 18: return TagSoundStreamHead() elif type == 19: return TagSoundStreamBlock() elif type == 20: return TagDefineBitsLossless() elif type == 21: return TagDefineBitsJPEG2() elif type == 22: return TagDefineShape2() elif type == 24: return TagProtect() elif type == 26: return TagPlaceObject2() elif type == 28: return TagRemoveObject2() elif type == 32: return TagDefineShape3() elif type == 33: return TagDefineText2() elif type == 34: return TagDefineButton2() elif type == 35: return TagDefineBitsJPEG3() elif type == 36: return TagDefineBitsLossless2() elif type == 37: return TagDefineEditText() elif type == 39: return TagDefineSprite() elif type == 41: return TagProductInfo() elif type == 43: return TagFrameLabel() elif type == 45: return TagSoundStreamHead2() elif type == 46: return TagDefineMorphShape() elif type == 48: return TagDefineFont2() elif type == 56: return TagExportAssets() elif type == 58: return TagEnableDebugger() elif type == 59: return TagDoInitAction() elif type == 60: return TagDefineVideoStream() elif type == 61: return TagVideoFrame() elif type == 63: return TagDebugID() elif type == 64: return TagEnableDebugger2() elif type == 65: return TagScriptLimits() elif type == 69: return TagFileAttributes() elif type == 70: return TagPlaceObject3() elif type == 73: return TagDefineFontAlignZones() elif type == 74: return TagCSMTextSettings() elif type == 75: return TagDefineFont3() elif type == 76: return TagSymbolClass() elif type == 77: return TagMetadata() elif type == 78: return TagDefineScalingGrid() elif type == 82: return TagDoABC() elif type == 83: return TagDefineShape4() elif type == 84: return TagDefineMorphShape2() elif type == 86: return TagDefineSceneAndFrameLabelData() elif type == 87: return TagDefineBinaryData() elif type == 88: return TagDefineFontName() elif type == 89: return TagStartSound2() else: return None
[ " Return the created tag by specifying an integer " ]
Please provide a description of the function:def get_dependencies(self): s = super(SWFTimelineContainer, self).get_dependencies() for dt in self.all_tags_of_type(DefinitionTag): s.update(dt.get_dependencies()) return s
[ " Returns the character ids this tag refers to " ]
Please provide a description of the function:def all_tags_of_type(self, type_or_types, recurse_into_sprites = True): for t in self.tags: if isinstance(t, type_or_types): yield t if recurse_into_sprites: for t in self.tags: # recurse into nested sprites if isinstance(t, SWFTimelineContainer): for containedtag in t.all_tags_of_type(type_or_types): yield containedtag
[ "\n Generator for all tags of the given type_or_types.\n\n Generates in breadth-first order, optionally including all sub-containers.\n " ]
Please provide a description of the function:def build_dictionary(self): d = {} for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False): if t.characterId in d: #print 'redefinition of characterId %d:' % (t.characterId) #print ' was:', d[t.characterId] #print 'redef:', t raise ValueError('illegal redefinition of character') d[t.characterId] = t return d
[ "\n Return a dictionary of characterIds to their defining tags.\n " ]
Please provide a description of the function:def collect_sound_streams(self): rc = [] current_stream = None # looking in all containers for frames for tag in self.all_tags_of_type((TagSoundStreamHead, TagSoundStreamBlock)): if isinstance(tag, TagSoundStreamHead): # we have a new stream current_stream = [ tag ] rc.append(current_stream) if isinstance(tag, TagSoundStreamBlock): # we have a frame for the current stream current_stream.append(tag) return rc
[ "\n Return a list of sound streams in this timeline and its children.\n The streams are returned in order with respect to the timeline.\n\n A stream is returned as a list: the first element is the tag\n which introduced that stream; other elements are the tags\n which made up the stream body (if any).\n " ]
Please provide a description of the function:def collect_video_streams(self): rc = [] streams_by_id = {} # scan first for all streams for t in self.all_tags_of_type(TagDefineVideoStream): stream = [ t ] streams_by_id[t.characterId] = stream rc.append(stream) # then find the frames for t in self.all_tags_of_type(TagVideoFrame): # we have a frame for the /named/ stream assert t.streamId in streams_by_id streams_by_id[t.streamId].append(t) return rc
[ "\n Return a list of video streams in this timeline and its children.\n The streams are returned in order with respect to the timeline.\n\n A stream is returned as a list: the first element is the tag\n which introduced that stream; other elements are the tags\n which made up the stream body (if any).\n " ]
Please provide a description of the function:def parse(self, data, length, version=1): pos = data.tell() self.characterId = data.readUI16() self.depth = data.readUI16(); self.matrix = data.readMATRIX(); self.hasCharacter = True; self.hasMatrix = True; if data.tell() - pos < length: colorTransform = data.readCXFORM() self.hasColorTransform = True
[ " Parses this tag " ]
Please provide a description of the function:def parse(self, data, length, version=1): self.characterId = data.readUI16() self.depth = data.readUI16()
[ " Parses this tag " ]
Please provide a description of the function:def export(self, swf, force_stroke=False): self.svg = self._e.svg(version=SVG_VERSION) self.force_stroke = force_stroke self.defs = self._e.defs() self.root = self._e.g() self.svg.append(self.defs) self.svg.append(self.root) self.shape_exporter.defs = self.defs self._num_filters = 0 self.fonts = dict([(x.characterId,x) for x in swf.all_tags_of_type(TagDefineFont)]) self.fontInfos = dict([(x.characterId,x) for x in swf.all_tags_of_type(TagDefineFontInfo)]) # GO! super(SVGExporter, self).export(swf, force_stroke) # Setup svg @width, @height and @viewBox # and add the optional margin self.bounds = SVGBounds(self.svg) self.svg.set("width", "%dpx" % round(self.bounds.width)) self.svg.set("height", "%dpx" % round(self.bounds.height)) if self._margin > 0: self.bounds.grow(self._margin) vb = [self.bounds.minx, self.bounds.miny, self.bounds.width, self.bounds.height] self.svg.set("viewBox", "%s" % " ".join(map(str,vb))) # Return the SVG as StringIO return self._serialize()
[ " Exports the specified SWF to SVG.\n\n @param swf The SWF.\n @param force_stroke Whether to force strokes on non-stroked fills.\n " ]
Please provide a description of the function:def export(self, swf, shape, **export_opts): # If `shape` is given as int, find corresponding shape tag. if isinstance(shape, Tag): shape_tag = shape else: shapes = [x for x in swf.all_tags_of_type((TagDefineShape, TagDefineSprite)) if x.characterId == shape] if len(shapes): shape_tag = shapes[0] else: raise Exception("Shape %s not found" % shape) from swf.movie import SWF # find a typical use of this shape example_place_objects = [x for x in swf.all_tags_of_type(TagPlaceObject) if x.hasCharacter and x.characterId == shape_tag.characterId] if len(example_place_objects): place_object = example_place_objects[0] characters = swf.build_dictionary() ids_to_export = place_object.get_dependencies() ids_exported = set() tags_to_export = [] # this had better form a dag! while len(ids_to_export): id = ids_to_export.pop() if id in ids_exported or id not in characters: continue tag = characters[id] ids_to_export.update(tag.get_dependencies()) tags_to_export.append(tag) ids_exported.add(id) tags_to_export.reverse() tags_to_export.append(place_object) else: place_object = TagPlaceObject() place_object.hasCharacter = True place_object.characterId = shape_tag.characterId tags_to_export = [ shape_tag, place_object ] stunt_swf = SWF() stunt_swf.tags = tags_to_export return super(SingleShapeSVGExporterMixin, self).export(stunt_swf, **export_opts)
[ " Exports the specified shape of the SWF to SVG.\n\n @param swf The SWF.\n @param shape Which shape to export, either by characterId(int) or as a Tag object.\n " ]
Please provide a description of the function:def export(self, swf, frame, **export_opts): self.wanted_frame = frame return super(FrameSVGExporterMixin, self).export(swf, *export_opts)
[ " Exports a frame of the specified SWF to SVG.\n\n @param swf The SWF.\n @param frame Which frame to export, by 0-based index (int)\n " ]
Please provide a description of the function:def parse_arg(f, kwd, offset=0): vnames = describe(f) return tuple([kwd[k] for k in vnames[offset:]])
[ "\n convert dictionary of keyword argument and value to positional argument\n equivalent to::\n\n vnames = describe(f)\n return tuple([kwd[k] for k in vnames[offset:]])\n\n " ]
Please provide a description of the function:def _get_args_and_errors(self, minuit=None, args=None, errors=None): ret_arg = None ret_error = None if minuit is not None: # case 1 ret_arg = minuit.args ret_error = minuit.errors return ret_arg, ret_error # no minuit specified use args and errors if args is not None: if isinstance(args, dict): ret_arg = parse_arg(self, args) else: ret_arg = args else: # case 3 ret_arg = self.last_arg if errors is not None: ret_error = errors return ret_arg, ret_error
[ "\n consistent algorithm to get argument and errors\n 1) get it from minuit if minuit is available\n 2) if not get it from args and errors\n 2.1) if args is dict parse it.\n 3) if all else fail get it from self.last_arg\n " ]
Please provide a description of the function:def draw_residual(x, y, yerr, xerr, show_errbars=True, ax=None, zero_line=True, grid=True, **kwargs): from matplotlib import pyplot as plt ax = plt.gca() if ax is None else ax if show_errbars: plotopts = dict(fmt='b.', capsize=0) plotopts.update(kwargs) pp = ax.errorbar(x, y, yerr, xerr, zorder=0, **plotopts) else: plotopts = dict(color='k') plotopts.update(kwargs) pp = ax.bar(x - xerr, y, width=2*xerr, **plotopts) if zero_line: ax.plot([x[0] - xerr[0], x[-1] + xerr[-1]], [0, 0], 'r-', zorder=2) # Take the `grid` kwarg to mean 'add a grid if True'; if grid is False and # we called ax.grid(False) then any existing grid on ax would be turned off if grid: ax.grid(grid) return ax
[ "Draw a residual plot on the axis.\n\n By default, if show_errbars if True, residuals are drawn as blue points\n with errorbars with no endcaps. If show_errbars is False, residuals are\n drawn as a bar graph with black bars.\n\n **Arguments**\n\n - **x** array of numbers, x-coordinates\n\n - **y** array of numbers, y-coordinates\n\n - **yerr** array of numbers, the uncertainty on the y-values\n\n - **xerr** array of numbers, the uncertainty on the x-values\n\n - **show_errbars** If True, draw the data as a bar plot, else as an\n errorbar plot\n\n - **ax** Optional matplotlib axis instance on which to draw the plot\n\n - **zero_line** If True, draw a red line at :math:`y = 0` along the\n full extent in :math:`x`\n\n - **grid** If True, draw gridlines\n\n - **kwargs** passed to ``ax.errorbar`` (if ``show_errbars`` is True) or\n ``ax.bar`` (if ``show_errbars`` if False)\n\n **Returns**\n\n The matplotlib axis instance the plot was drawn on.\n " ]
Please provide a description of the function:def draw_compare(f, arg, edges, data, errors=None, ax=None, grid=True, normed=False, parts=False): from matplotlib import pyplot as plt # arg is either map or tuple ax = plt.gca() if ax is None else ax arg = parse_arg(f, arg, 1) if isinstance(arg, dict) else arg x = (edges[:-1] + edges[1:]) / 2.0 bw = np.diff(edges) yf = vector_apply(f, x, *arg) total = np.sum(data) if normed: ax.errorbar(x, data / bw / total, errors / bw / total, fmt='.b', zorder=0) ax.plot(x, yf, 'r', lw=2, zorder=2) else: ax.errorbar(x, data, errors, fmt='.b', zorder=0) ax.plot(x, yf * bw, 'r', lw=2, zorder=2) # now draw the parts if parts: if not hasattr(f, 'eval_parts'): warn(RuntimeWarning('parts is set to True but function does ' 'not have eval_parts method')) else: scale = bw if not normed else 1. parts_val = list() for tx in x: val = f.eval_parts(tx, *arg) parts_val.append(val) py = zip(*parts_val) for y in py: tmpy = np.array(y) ax.plot(x, tmpy * scale, lw=2, alpha=0.5) plt.grid(grid) return x, yf, data
[ "\n TODO: this needs to be rewritten\n " ]
Please provide a description of the function:def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True, normed_pdf=False, ax=None, **kwds): edges = np.linspace(bound[0], bound[1], bins) return draw_pdf_with_edges(f, arg, edges, ax=ax, scale=scale, density=density, normed_pdf=normed_pdf, **kwds)
[ "\n draw pdf with given argument and bounds.\n\n **Arguments**\n\n * **f** your pdf. The first argument is assumed to be independent\n variable\n\n * **arg** argument can be tuple or list\n\n * **bound** tuple(xmin,xmax)\n\n * **bins** number of bins to plot pdf. Default 100.\n\n * **scale** multiply pdf by given number. Default 1.0.\n\n * **density** plot density instead of expected count in each bin\n (pdf*bin width). Default True.\n\n * **normed_pdf** Normalize pdf in given bound. Default False\n\n * The rest of keyword argument will be pass to pyplot.plot\n\n **Returns**\n\n x, y of what's being plot\n " ]
Please provide a description of the function:def draw_compare_hist(f, arg, data, bins=100, bound=None, ax=None, weights=None, normed=False, use_w2=False, parts=False, grid=True): from matplotlib import pyplot as plt ax = plt.gca() if ax is None else ax bound = minmax(data) if bound is None else bound h, e = np.histogram(data, bins=bins, range=bound, weights=weights) err = None if weights is not None and use_w2: err, _ = np.histogram(data, bins=bins, range=bound, weights=weights * weights) err = np.sqrt(err) else: err = np.sqrt(h) return draw_compare(f, arg, e, h, err, ax=ax, grid=grid, normed=normed, parts=parts)
[ "\n draw histogram of data with poisson error bar and f(x,*arg).\n\n ::\n\n data = np.random.rand(10000)\n f = gaussian\n draw_compare_hist(f, {'mean':0,'sigma':1}, data, normed=True)\n\n **Arguments**\n\n - **f**\n - **arg** argument pass to f. Can be dictionary or list.\n - **data** data array\n - **bins** number of bins. Default 100.\n - **bound** optional boundary of plot in tuple form. If `None` is\n given, the bound is determined from min and max of the data. Default\n `None`\n - **weights** weights array. Default None.\n - **normed** optional normalized data flag. Default False.\n - **use_w2** scaled error down to the original statistics instead of\n weighted statistics.\n - **parts** draw parts of pdf. (Works with AddPdf and Add2PdfNorm).\n Default False.\n " ]
Please provide a description of the function:def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd): return gen_toy(f, nsample * ntoy, bound, accuracy, quiet, **kwd).reshape((ntoy, nsample))
[ "\n just alias of gentoy for nample and then reshape to ntoy,nsample)\n :param f:\n :param nsample:\n :param bound:\n :param accuracy:\n :param quiet:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def gen_toy(f, nsample, bound, accuracy=10000, quiet=True, **kwd): # based on inverting cdf this is fast but you will need to give it a reasonable range # unlike roofit which is based on accept reject vnames = describe(f) if not quiet: print(vnames) my_arg = [kwd[v] for v in vnames[1:]] # random number # if accuracy is None: accuracy=10*numtoys r = npr.random_sample(nsample) x = np.linspace(bound[0], bound[1], accuracy) pdf = _vector_apply(f, x, tuple(my_arg)) cdf = compute_cdf(pdf, x) if cdf[-1] < 0.01: warn(SmallIntegralWarning('Integral for given funcition is' ' really low. Did you give it a reasonable range?')) cdfnorm = cdf[-1] cdf /= cdfnorm # now convert that to toy ret = invert_cdf(r, cdf, x) if not quiet: # move this to plotting from matplotlib import pyplot as plt plt.figure() plt.title('comparison') numbin = 100 h, e = np.histogram(ret, bins=numbin) mp = (e[1:] + e[:-1]) / 2. err = np.sqrt(h) plt.errorbar(mp, h, err, fmt='.b') bw = e[1] - e[0] y = pdf * len(ret) / cdfnorm * bw ylow = y + np.sqrt(y) yhigh = y - np.sqrt(y) plt.plot(x, y, label='pdf', color='r') plt.fill_between(x, yhigh, ylow, color='g', alpha=0.2) plt.grid(True) plt.xlim(bound) plt.ylim(ymin=0) return ret
[ "\n generate ntoy\n :param f:\n :param nsample:\n :param ntoy:\n :param bound:\n :param accuracy:\n :param quiet:\n :param kwd: the rest of keyword argument will be passed to f\n :return: numpy.ndarray\n " ]
Please provide a description of the function:def fit_uml(f, data, quiet=False, print_level=0, *arg, **kwd): uml = UnbinnedLH(f, data) minuit = Minuit(uml, print_level=print_level, **kwd) minuit.set_strategy(2) minuit.migrad() if not minuit.migrad_ok() or not minuit.matrix_accurate(): if not quiet: from matplotlib import pyplot as plt plt.figure() uml.show() print(minuit.values) return (uml, minuit)
[ "\n perform unbinned likelihood fit\n :param f: pdf\n :param data: data\n :param quiet: if not quite draw latest fit on fail fit\n :param printlevel: minuit printlevel\n :return:\n " ]
Please provide a description of the function:def fit_binx2(f, data, bins=30, bound=None, print_level=0, quiet=False, *arg, **kwd): uml = BinnedChi2(f, data, bins=bins, bound=bound) minuit = Minuit(uml, print_level=print_level, **kwd) minuit.set_strategy(2) minuit.migrad() if not minuit.migrad_ok() or not minuit.matrix_accurate(): if not quiet: from matplotlib import pyplot as plt plt.figure() uml.show() print(minuit.values) return (uml, minuit)
[ "\n perform chi^2 fit\n :param f:\n :param data:\n :param bins:\n :param range:\n :param printlevel:\n :param quiet:\n :param arg:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def fit_binlh(f, data, bins=30, bound=None, quiet=False, weights=None, use_w2=False, print_level=0, pedantic=True, extended=False, *arg, **kwd): uml = BinnedLH(f, data, bins=bins, bound=bound, weights=weights, use_w2=use_w2, extended=extended) minuit = Minuit(uml, print_level=print_level, pedantic=pedantic, **kwd) minuit.set_strategy(2) minuit.migrad() if not minuit.migrad_ok() or not minuit.matrix_accurate(): if not quiet: from matplotlib import pyplot as plt plt.figure() uml.show() print(minuit.values) return (uml, minuit)
[ "\n perform bin likelihood fit\n :param f:\n :param data:\n :param bins:\n :param range:\n :param quiet:\n :param weights:\n :param use_w2:\n :param printlevel:\n :param pedantic:\n :param extended:\n :param arg:\n :param kwd:\n :return:\n " ]
Please provide a description of the function:def pprint_arg(vnames, value): ret = '' for name, v in zip(vnames, value): ret += '%s=%s;' % (name, str(v)) return ret;
[ "\n pretty print argument\n :param vnames:\n :param value:\n :return:\n " ]
Please provide a description of the function:def gauss_pdf(x, mu, sigma): return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)
[ "Normalized Gaussian" ]
Please provide a description of the function:def get_chunks(sequence, chunk_size): return [ sequence[idx:idx + chunk_size] for idx in range(0, len(sequence), chunk_size) ]
[ "Split sequence into chunks.\n\n :param list sequence:\n :param int chunk_size:\n " ]
Please provide a description of the function:def get_kwargs(kwargs): return { key: value for key, value in six.iteritems(kwargs) if key != 'self' }
[ "Get all keys and values from dictionary where key is not `self`.\n\n :param dict kwargs: Input parameters\n " ]
Please provide a description of the function:def check_status_code(response, codes=None): codes = codes or [httplib.OK] checker = ( codes if callable(codes) else lambda resp: resp.status_code in codes ) if not checker(response): raise exceptions.ApiError(response, response.json())
[ "Check HTTP status code and raise exception if incorrect.\n\n :param Response response: HTTP response\n :param codes: List of accepted codes or callable\n :raises: ApiError if code invalid\n " ]
Please provide a description of the function:def result_or_error(response): data = response.json() result = data.get('result') if result is not None: return result raise exceptions.ApiError(response, data)
[ "Get `result` field from Betfair response or raise exception if not\n found.\n\n :param Response response:\n :raises: ApiError if no results passed\n " ]
Please provide a description of the function:def process_result(result, model=None): if model is None: return result if isinstance(result, collections.Sequence): return [model(**item) for item in result] return model(**result)
[ "Cast response JSON to Betfair model(s).\n\n :param result: Betfair response JSON\n :param BetfairModel model: Deserialization format; if `None`, return raw\n JSON\n " ]
Please provide a description of the function:def make_payload(base, method, params): payload = { 'jsonrpc': '2.0', 'method': '{base}APING/v1.0/{method}'.format(**locals()), 'params': utils.serialize_dict(params), 'id': 1, } return payload
[ "Build Betfair JSON-RPC payload.\n\n :param str base: Betfair base (\"Sports\" or \"Account\")\n :param str method: Betfair endpoint\n :param dict params: Request parameters\n " ]
Please provide a description of the function:def requires_login(func, *args, **kwargs): self = args[0] if self.session_token: return func(*args, **kwargs) raise exceptions.NotLoggedIn()
[ "Decorator to check that the user is logged in. Raises `BetfairError`\n if instance variable `session_token` is absent.\n " ]
Please provide a description of the function:def nearest_price(price, cutoffs=CUTOFFS): if price <= MIN_PRICE: return MIN_PRICE if price > MAX_PRICE: return MAX_PRICE price = as_dec(price) for cutoff, step in cutoffs: if price < cutoff: break step = as_dec(step) return float((price * step).quantize(2, ROUND_HALF_UP) / step)
[ "Returns the nearest Betfair odds value to price.\n\n Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).\n https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js\n\n :param float price: Approximate Betfair price (i.e. decimal odds value)\n :param tuple cutoffs: Optional tuple of (cutoff, step) pairs\n :returns: The nearest Befair price\n :rtype: float\n " ]
Please provide a description of the function:def ticks_difference(price_1, price_2): price_1_index = PRICES.index(as_dec(price_1)) price_2_index = PRICES.index(as_dec(price_2)) return abs(price_1_index - price_2_index)
[ "Returns the absolute difference in terms of \"ticks\" (i.e. individual\n price increments) between two Betfair prices.\n\n :param float price_1: An exact, valid Betfair price\n :param float price_2: An exact, valid Betfair price\n :returns: The absolute value of the difference between the prices in \"ticks\"\n :rtype: int\n " ]
Please provide a description of the function:def price_ticks_away(price, n_ticks): price_index = PRICES.index(as_dec(price)) return float(PRICES[price_index + n_ticks])
[ "Returns an exact, valid Betfair price that is n_ticks \"ticks\" away from\n the given price. n_ticks may positive, negative or zero (in which case the\n same price is returned) but if there is no price n_ticks away from the\n given price then an exception will be thrown.\n\n :param float price: An exact, valid Betfair price\n :param float n_ticks: The number of ticks away from price the new price is\n :returns: An exact, valid Betfair price\n :rtype: float\n " ]
Please provide a description of the function:def login(self, username, password): response = self.session.post( os.path.join(self.identity_url, 'certlogin'), cert=self.cert_file, data=urllib.urlencode({ 'username': username, 'password': password, }), headers={ 'X-Application': self.app_key, 'Content-Type': 'application/x-www-form-urlencoded', }, timeout=self.timeout, ) utils.check_status_code(response, [httplib.OK]) data = response.json() if data.get('loginStatus') != 'SUCCESS': raise exceptions.LoginError(response, data) self.session_token = data['sessionToken']
[ "Log in to Betfair. Sets `session_token` if successful.\n\n :param str username: Username\n :param str password: Password\n :raises: BetfairLoginError\n " ]
Please provide a description of the function:def list_market_profit_and_loss( self, market_ids, include_settled_bets=False, include_bsp_bets=None, net_of_commission=None): return self.make_api_request( 'Sports', 'listMarketProfitAndLoss', utils.get_kwargs(locals()), model=models.MarketProfitAndLoss, )
[ "Retrieve profit and loss for a given list of markets.\n\n :param list market_ids: List of markets to calculate profit and loss\n :param bool include_settled_bets: Option to include settled bets\n :param bool include_bsp_bets: Option to include BSP bets\n :param bool net_of_commission: Option to return profit and loss net of\n users current commission rate for this market including any special\n tariffs\n " ]
Please provide a description of the function:def iter_list_market_book(self, market_ids, chunk_size, **kwargs): return itertools.chain(*( self.list_market_book(market_chunk, **kwargs) for market_chunk in utils.get_chunks(market_ids, chunk_size) ))
[ "Split call to `list_market_book` into separate requests.\n\n :param list market_ids: List of market IDs\n :param int chunk_size: Number of records per chunk\n :param dict kwargs: Arguments passed to `list_market_book`\n " ]
Please provide a description of the function:def iter_list_market_profit_and_loss( self, market_ids, chunk_size, **kwargs): return itertools.chain(*( self.list_market_profit_and_loss(market_chunk, **kwargs) for market_chunk in utils.get_chunks(market_ids, chunk_size) ))
[ "Split call to `list_market_profit_and_loss` into separate requests.\n\n :param list market_ids: List of market IDs\n :param int chunk_size: Number of records per chunk\n :param dict kwargs: Arguments passed to `list_market_profit_and_loss`\n " ]
Please provide a description of the function:def place_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'placeOrders', utils.get_kwargs(locals()), model=models.PlaceExecutionReport, )
[ "Place new orders into market. This operation is atomic in that all\n orders will be placed or none will be placed.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `PlaceInstruction` objects\n :param str customer_ref: Optional order identifier string\n " ]
Please provide a description of the function:def cancel_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'cancelOrders', utils.get_kwargs(locals()), model=models.CancelExecutionReport, )
[ "Cancel all bets OR cancel all bets on a market OR fully or\n partially cancel particular orders on a market.\n\n :param str market_id: If not supplied all bets are cancelled\n :param list instructions: List of `CancelInstruction` objects\n :param str customer_ref: Optional order identifier string\n " ]
Please provide a description of the function:def replace_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'replaceOrders', utils.get_kwargs(locals()), model=models.ReplaceExecutionReport, )
[ "This operation is logically a bulk cancel followed by a bulk place.\n The cancel is completed first then the new orders are placed.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `ReplaceInstruction` objects\n :param str customer_ref: Optional order identifier string\n " ]
Please provide a description of the function:def update_orders(self, market_id, instructions, customer_ref=None): return self.make_api_request( 'Sports', 'updateOrders', utils.get_kwargs(locals()), model=models.UpdateExecutionReport, )
[ "Update non-exposure changing fields.\n\n :param str market_id: The market id these orders are to be placed on\n :param list instructions: List of `UpdateInstruction` objects\n :param str customer_ref: Optional order identifier string\n " ]
Please provide a description of the function:def get_account_funds(self, wallet=None): return self.make_api_request( 'Account', 'getAccountFunds', utils.get_kwargs(locals()), model=models.AccountFundsResponse, )
[ "Get available to bet amount.\n\n :param Wallet wallet: Name of the wallet in question\n " ]
Please provide a description of the function:def get_account_statement( self, locale=None, from_record=None, record_count=None, item_date_range=None, include_item=None, wallet=None): return self.make_api_request( 'Account', 'getAccountStatement', utils.get_kwargs(locals()), model=models.AccountStatementReport, )
[ "Get account statement.\n\n :param str locale: The language to be used where applicable\n :param int from_record: Specifies the first record that will be returned\n :param int record_count: Specifies the maximum number of records to be returned\n :param TimeRange item_date_range: Return items with an itemDate within this date range\n :param IncludeItem include_item: Which items to include\n :param Wallet wallte: Which wallet to return statementItems for\n " ]
Please provide a description of the function:def get_account_details(self): return self.make_api_request( 'Account', 'getAccountDetails', utils.get_kwargs(locals()), model=models.AccountDetailsResponse, )
[ "Returns the details relating your account, including your discount\n rate and Betfair point balance.\n " ]
Please provide a description of the function:def list_currency_rates(self, from_currency=None): return self.make_api_request( 'Account', 'listCurrencyRates', utils.get_kwargs(locals()), model=models.CurrencyRate, )
[ "Returns a list of currency rates based on given currency\n\n :param str from_currency: The currency from which the rates are computed\n " ]
Please provide a description of the function:def transfer_funds(self, from_, to, amount): return self.make_api_request( 'Account', 'transferFunds', utils.get_kwargs(locals()), model=models.TransferResponse, )
[ "Transfer funds between the UK Exchange and Australian Exchange wallets.\n\n :param Wallet from_: Source wallet\n :param Wallet to: Destination wallet\n :param float amount: Amount to transfer\n " ]
Please provide a description of the function:def comment_count(object): return Comment.objects.filter( object_id=object.pk, content_type=ContentType.objects.get_for_model(object) ).count()
[ "\n Usage:\n {% comment_count obj %}\n or\n {% comment_count obj as var %}\n " ]
Please provide a description of the function:def comments(object): return Comment.objects.filter( object_id=object.pk, content_type=ContentType.objects.get_for_model(object) )
[ "\n Usage:\n {% comments obj as var %}\n " ]
Please provide a description of the function:def comment_form(context, object): user = context.get("user") form_class = context.get("form", CommentForm) form = form_class(obj=object, user=user) return form
[ "\n Usage:\n {% comment_form obj as comment_form %}\n Will read the `user` var out of the contex to know if the form should be\n form an auth'd user or not.\n " ]
Please provide a description of the function:def comment_target(object): return reverse("pinax_comments:post_comment", kwargs={ "content_type_id": ContentType.objects.get_for_model(object).pk, "object_id": object.pk })
[ "\n Usage:\n {% comment_target obj [as varname] %}\n " ]
Please provide a description of the function:def parse(self, text, html=True): '''Parse the text and return a ParseResult instance.''' self._urls = [] self._users = [] self._lists = [] self._tags = [] reply = REPLY_REGEX.match(text) reply = reply.groups(0)[0] if reply is not None else None parsed_html = self._html(text) if html else self._text(text) return ParseResult(self._urls, self._users, reply, self._lists, self._tags, parsed_html)
[]
Please provide a description of the function:def _text(self, text): '''Parse a Tweet without generating HTML.''' URL_REGEX.sub(self._parse_urls, text) USERNAME_REGEX.sub(self._parse_users, text) LIST_REGEX.sub(self._parse_lists, text) HASHTAG_REGEX.sub(self._parse_tags, text) return None
[]
Please provide a description of the function:def _html(self, text): '''Parse a Tweet and generate HTML.''' html = URL_REGEX.sub(self._parse_urls, text) html = USERNAME_REGEX.sub(self._parse_users, html) html = LIST_REGEX.sub(self._parse_lists, html) return HASHTAG_REGEX.sub(self._parse_tags, html)
[]
Please provide a description of the function:def _parse_urls(self, match): '''Parse URLs.''' mat = match.group(0) # Fix a bug in the regex concerning www...com and www.-foo.com domains # TODO fix this in the regex instead of working around it here domain = match.group(5) if domain[0] in '.-': return mat # Only allow IANA one letter domains that are actually registered if len(domain) == 5 \ and domain[-4:].lower() in ('.com', '.org', '.net') \ and not domain.lower() in IANA_ONE_LETTER_DOMAINS: return mat # Check for urls without http(s) pos = mat.find('http') if pos != -1: pre, url = mat[:pos], mat[pos:] full_url = url # Find the www and force https:// else: pos = mat.lower().find('www') pre, url = mat[:pos], mat[pos:] full_url = 'https://%s' % url if self._include_spans: span = match.span(0) # add an offset if pre is e.g. ' ' span = (span[0] + len(pre), span[1]) self._urls.append((url, span)) else: self._urls.append(url) if self._html: return '%s%s' % (pre, self.format_url(full_url, self._shorten_url(escape(url))))
[]
Please provide a description of the function:def _parse_users(self, match): '''Parse usernames.''' # Don't parse lists here if match.group(2) is not None: return match.group(0) mat = match.group(0) if self._include_spans: self._users.append((mat[1:], match.span(0))) else: self._users.append(mat[1:]) if self._html: return self.format_username(mat[0:1], mat[1:])
[]
Please provide a description of the function:def _parse_lists(self, match): '''Parse lists.''' # Don't parse usernames here if match.group(4) is None: return match.group(0) pre, at_char, user, list_name = match.groups() list_name = list_name[1:] if self._include_spans: self._lists.append((user, list_name, match.span(0))) else: self._lists.append((user, list_name)) if self._html: return '%s%s' % (pre, self.format_list(at_char, user, list_name))
[]
Please provide a description of the function:def _parse_tags(self, match): '''Parse hashtags.''' mat = match.group(0) # Fix problems with the regex capturing stuff infront of the # tag = None for i in '#\uff03': pos = mat.rfind(i) if pos != -1: tag = i break pre, text = mat[:pos], mat[pos + 1:] if self._include_spans: span = match.span(0) # add an offset if pre is e.g. ' ' span = (span[0] + len(pre), span[1]) self._tags.append((text, span)) else: self._tags.append(text) if self._html: return '%s%s' % (pre, self.format_tag(tag, text))
[]
Please provide a description of the function:def _shorten_url(self, text): '''Shorten a URL and make sure to not cut of html entities.''' if len(text) > self._max_url_length and self._max_url_length != -1: text = text[0:self._max_url_length - 3] amp = text.rfind('&') close = text.rfind(';') if amp != -1 and (close == -1 or close < amp): text = text[0:amp] return text + '...' else: return text
[]
Please provide a description of the function:def format_list(self, at_char, user, list_name): '''Return formatted HTML for a list.''' return '<a href="https://twitter.com/%s/lists/%s">%s%s/%s</a>' \ % (user, list_name, at_char, user, list_name)
[]
Please provide a description of the function:def follow_shortlinks(shortlinks): links_followed = {} for shortlink in shortlinks: url = shortlink request_result = requests.get(url) redirect_history = request_result.history # history might look like: # (<Response [301]>, <Response [301]>) # where each response object has a URL all_urls = [] for redirect in redirect_history: all_urls.append(redirect.url) # append the final URL that we finish with all_urls.append(request_result.url) links_followed[shortlink] = all_urls return links_followed
[ "Follow redirects in list of shortlinks, return dict of resulting URLs" ]
Please provide a description of the function:def _GetFieldAttributes(field): if not isinstance(field, messages.Field): raise TypeError('Field %r to be copied not a ProtoRPC field.' % (field,)) positional_args = [] kwargs = { 'required': field.required, 'repeated': field.repeated, 'variant': field.variant, 'default': field._Field__default, # pylint: disable=protected-access } if isinstance(field, messages.MessageField): # Message fields can't have a default kwargs.pop('default') if not isinstance(field, message_types.DateTimeField): positional_args.insert(0, field.message_type) elif isinstance(field, messages.EnumField): positional_args.insert(0, field.type) return positional_args, kwargs
[ "Decomposes field into the needed arguments to pass to the constructor.\n\n This can be used to create copies of the field or to compare if two fields\n are \"equal\" (since __eq__ is not implemented on messages.Field).\n\n Args:\n field: A ProtoRPC message field (potentially to be copied).\n\n Raises:\n TypeError: If the field is not an instance of messages.Field.\n\n Returns:\n A pair of relevant arguments to be passed to the constructor for the field\n type. The first element is a list of positional arguments for the\n constructor and the second is a dictionary of keyword arguments.\n " ]
Please provide a description of the function:def _CompareFields(field, other_field): field_attrs = _GetFieldAttributes(field) other_field_attrs = _GetFieldAttributes(other_field) if field_attrs != other_field_attrs: return False return field.__class__ == other_field.__class__
[ "Checks if two ProtoRPC fields are \"equal\".\n\n Compares the arguments, rather than the id of the elements (which is\n the default __eq__ behavior) as well as the class of the fields.\n\n Args:\n field: A ProtoRPC message field to be compared.\n other_field: A ProtoRPC message field to be compared.\n\n Returns:\n Boolean indicating whether the fields are equal.\n " ]
Please provide a description of the function:def _CopyField(field, number=None): positional_args, kwargs = _GetFieldAttributes(field) number = number or field.number positional_args.append(number) return field.__class__(*positional_args, **kwargs)
[ "Copies a (potentially) owned ProtoRPC field instance into a new copy.\n\n Args:\n field: A ProtoRPC message field to be copied.\n number: An integer for the field to override the number of the field.\n Defaults to None.\n\n Raises:\n TypeError: If the field is not an instance of messages.Field.\n\n Returns:\n A copy of the ProtoRPC message field.\n " ]
Please provide a description of the function:def combined_message_class(self): if self.__combined_message_class is not None: return self.__combined_message_class fields = {} # We don't need to preserve field.number since this combined class is only # used for the protorpc remote.method and is not needed for the API config. # The only place field.number matters is in parameterOrder, but this is set # based on container.parameters_message_class which will use the field # numbers originally passed in. # Counter for fields. field_number = 1 for field in self.body_message_class.all_fields(): fields[field.name] = _CopyField(field, number=field_number) field_number += 1 for field in self.parameters_message_class.all_fields(): if field.name in fields: if not _CompareFields(field, fields[field.name]): raise TypeError('Field %r contained in both parameters and request ' 'body, but the fields differ.' % (field.name,)) else: # Skip a field that's already there. continue fields[field.name] = _CopyField(field, number=field_number) field_number += 1 self.__combined_message_class = type('CombinedContainer', (messages.Message,), fields) return self.__combined_message_class
[ "A ProtoRPC message class with both request and parameters fields.\n\n Caches the result in a local private variable. Uses _CopyField to create\n copies of the fields from the existing request and parameters classes since\n those fields are \"owned\" by the message classes.\n\n Raises:\n TypeError: If a field name is used in both the request message and the\n parameters but the two fields do not represent the same type.\n\n Returns:\n Value of combined message class for this property.\n " ]
Please provide a description of the function:def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name if not isinstance(container, cls): raise TypeError('%r not an instance of %r, could not be added to cache.' % (container, cls)) if remote_info in cls.__remote_info_cache: raise KeyError('Cache has collision but should not.') cls.__remote_info_cache[remote_info] = container
[ "Adds a ResourceContainer to a cache tying it to a protorpc method.\n\n Args:\n remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding\n to a method.\n container: An instance of ResourceContainer.\n\n Raises:\n TypeError: if the container is not an instance of cls.\n KeyError: if the remote method has been reference by a container before.\n This created remote method should never occur because a remote method\n is created once.\n " ]