_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q38300
User.wrap_json
train
def wrap_json(cls, json): """Create a User instance for the given json :param json: the dict with the information of the user :type json: :class:`dict` | None :returns: the new user instance :rtype: :class:`User` :raises: None """ u = User(usertype=json['...
python
{ "resource": "" }
q38301
_wrap_execute_after
train
def _wrap_execute_after(funcname): """Warp the given method, so it gets executed by the reactor Wrap a method of :data:`IRCCLient.out_connection`. The returned function should be assigned to a :class:`irc.client.SimpleIRCClient` class. :param funcname: the name of a :class:`irc.client.ServerConnectio...
python
{ "resource": "" }
q38302
Reactor.shutdown
train
def shutdown(self): """Disconnect all connections and end the loop :returns: None :rtype: None :raises: None """ log.debug('Shutting down %s' % self) self.disconnect_all() self._looping.clear()
python
{ "resource": "" }
q38303
Reactor3.server
train
def server(self, ): """Creates and returns a ServerConnection :returns: a server connection :rtype: :class:`connection.ServerConnection3` :raises: None """ c = connection.ServerConnection3(self) with self.mutex: self.connections.append(c) retu...
python
{ "resource": "" }
q38304
init_run
train
def init_run(shell, no_daemon, daemon_options, daemon_outfile): """ Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify sh...
python
{ "resource": "" }
q38305
update_data
train
def update_data(func): """ Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function """ default = dict([ (param.name, param.default) for param in inspect.signature(func).parameter...
python
{ "resource": "" }
q38306
save_data
train
def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs): """ Save data to file Args: data: pd.DataFrame file_fmt: data file format in terms of f-strings append: if append data to existing data drop_dups: list, drop duplicates in columns info:...
python
{ "resource": "" }
q38307
data_file
train
def data_file(file_fmt, info=None, **kwargs): """ Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments f...
python
{ "resource": "" }
q38308
index_run
train
def index_run(record_path, keep_json, check_duplicate): """ Convert raw JSON records into sqlite3 DB. Normally RASH launches a daemon that takes care of indexing. See ``rash daemon --help``. """ from .config import ConfigStore from .indexer import Indexer cfstore = ConfigStore() in...
python
{ "resource": "" }
q38309
DataLoggingService.list
train
def list(self): """ List all available data logging sessions """ # We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(DataLogging) self._pebble.send_packet(DataLogging(data=DataLoggingRepo...
python
{ "resource": "" }
q38310
DataLoggingService.get_send_enable
train
def get_send_enable(self): """ Return true if sending of sessions is enabled on the watch """ # We have to open this queue before we make the request, to ensure we don't miss the response. queue = self._pebble.get_endpoint_queue(DataLogging) self._pebble.send_packet(Dat...
python
{ "resource": "" }
q38311
DataLoggingService.set_send_enable
train
def set_send_enable(self, setting): """ Set the send enable setting on the watch """ self._pebble.send_packet(DataLogging(data=DataLoggingSetSendEnable(enabled=setting)))
python
{ "resource": "" }
q38312
loglevel
train
def loglevel(level): """ Convert any representation of `level` to an int appropriately. :type level: int or str :rtype: int >>> loglevel('DEBUG') == logging.DEBUG True >>> loglevel(10) 10 >>> loglevel(None) Traceback (most recent call last): ... ValueError: None is no...
python
{ "resource": "" }
q38313
setup_daemon_log_file
train
def setup_daemon_log_file(cfstore): """ Attach file handler to RASH logger. :type cfstore: rash.config.ConfigStore """ level = loglevel(cfstore.daemon_log_level) handler = logging.FileHandler(filename=cfstore.daemon_log_path) handler.setLevel(level) logger.setLevel(level) logger.ad...
python
{ "resource": "" }
q38314
gzip_encode
train
def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO() gzf = gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) gzf.write(data) gzf.close() ...
python
{ "resource": "" }
q38315
gzip_decode
train
def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = StringIO.StringIO(data) gzf = gzip.GzipFile(mode="rb", fileobj=f) try: if ma...
python
{ "resource": "" }
q38316
result_headers
train
def result_headers(context, cl): """ Generates the list column headers. """ for i, field_name in enumerate(cl.list_display): text, attr = label_for_field(field_name, cl.model, return_attr=True) if attr: # Potentially not sortable # if the field is the action che...
python
{ "resource": "" }
q38317
Tag.from_str
train
def from_str(cls, tagstring): """Create a tag by parsing the tag of a message :param tagstring: A tag string described in the irc protocol :type tagstring: :class:`str` :returns: A tag :rtype: :class:`Tag` :raises: None """ m = cls._parse_regexp.match(tag...
python
{ "resource": "" }
q38318
Emote.from_str
train
def from_str(cls, emotestr): """Create an emote from the emote tag key :param emotestr: the tag key, e.g. ``'123:0-4'`` :type emotestr: :class:`str` :returns: an emote :rtype: :class:`Emote` :raises: None """ emoteid, occstr = emotestr.split(':') ...
python
{ "resource": "" }
q38319
Message3.from_event
train
def from_event(cls, event): """Create a message from an event :param event: the event that was received of type ``pubmsg`` or ``privmsg`` :type event: :class:`Event3` :returns: a message that resembles the event :rtype: :class:`Message3` :raises: None """ ...
python
{ "resource": "" }
q38320
Message3.set_tags
train
def set_tags(self, tags): """For every known tag, set the appropriate attribute. Known tags are: :color: The user color :emotes: A list of emotes :subscriber: True, if subscriber :turbo: True, if turbo user :user_type: None, mod, staff, globa...
python
{ "resource": "" }
q38321
Message3.emotes
train
def emotes(self, emotes): """Set the emotes :param emotes: the key of the emotes tag :type emotes: :class:`str` :returns: None :rtype: None :raises: None """ if emotes is None: self._emotes = [] return es = [] for e...
python
{ "resource": "" }
q38322
coerce_types
train
def coerce_types(T1, T2): """Coerce types T1 and T2 to a common type. Coercion is performed according to this table, where "N/A" means that a TypeError exception is raised. +----------+-----------+-----------+-----------+----------+ | | int | Fraction | Decimal | float | +...
python
{ "resource": "" }
q38323
median_low
train
def median_low(data): """Return the low median of numeric data. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned. """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median f...
python
{ "resource": "" }
q38324
median_high
train
def median_high(data): """Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for emp...
python
{ "resource": "" }
q38325
variance
train
def variance(data, xbar=None): """Return the sample variance of data. data should be an iterable of Real-valued numbers, with at least two values. The optional argument xbar, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this function...
python
{ "resource": "" }
q38326
pvariance
train
def pvariance(data, mu=None): """Return the population variance of ``data``. data should be an iterable of Real-valued numbers, with at least one value. The optional argument mu, if given, should be the mean of the data. If it is missing or None, the mean is automatically calculated. Use this func...
python
{ "resource": "" }
q38327
stdev
train
def stdev(data, xbar=None): """Return the square root of the sample variance. See ``variance`` for arguments and other details. """ var = variance(data, xbar) try: return var.sqrt() except AttributeError: return math.sqrt(var)
python
{ "resource": "" }
q38328
pstdev
train
def pstdev(data, mu=None): """Return the square root of the population variance. See ``pvariance`` for arguments and other details. """ var = pvariance(data, mu) try: return var.sqrt() except AttributeError: return math.sqrt(var)
python
{ "resource": "" }
q38329
geometric_mean
train
def geometric_mean(data): """Return the geometric mean of data """ if not data: raise StatisticsError('geometric_mean requires at least one data point') # in order to support negative or null values data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data] return math.pow(math....
python
{ "resource": "" }
q38330
harmonic_mean
train
def harmonic_mean(data): """Return the harmonic mean of data """ if not data: raise StatisticsError('harmonic_mean requires at least one data point') divisor = sum(map(lambda x: 1.0 / x if x else 0.0, data)) return len(data) / divisor if divisor else 0.0
python
{ "resource": "" }
q38331
kurtosis
train
def kurtosis(data): """Return the kurtosis of the data's distribution """ if not data: raise StatisticsError('kurtosis requires at least one data point') size = len(data) sd = stdev(data) ** 4 if not sd: return 0.0 mn = mean(data) return sum(map(lambda x: ((x - mn) *...
python
{ "resource": "" }
q38332
percentile
train
def percentile(data, n): """Return the n-th percentile of the given data Assume that the data are already sorted """ size = len(data) idx = (n / 100.0) * size - 0.5 if idx < 0 or idx > size: raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n)) re...
python
{ "resource": "" }
q38333
get_histogram
train
def get_histogram(data): """Return the histogram relative to the given data Assume that the data are already sorted """ count = len(data) if count < 2: raise StatisticsError('Too few data points ({}) for get_histogram'.format(count)) min_ = data[0] max_ = data[-1] std = stde...
python
{ "resource": "" }
q38334
get_histogram_bins
train
def get_histogram_bins(min_, max_, std, count): """ Return optimal bins given the input parameters """ width = _get_bin_width(std, count) count = int(round((max_ - min_) / width) + 1) if count: bins = [i * width + min_ for i in xrange(1, count + 1)] else: bins = [min_] ...
python
{ "resource": "" }
q38335
_get_bin_width
train
def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 """ w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
python
{ "resource": "" }
q38336
_longest_common_subsequence
train
def _longest_common_subsequence(x, y): """ Return the longest common subsequence between two sequences. Parameters ---------- x, y : sequence Returns ------- sequence Longest common subsequence of x and y. Examples -------- >>> _longest_common_subsequence("AGGTAB",...
python
{ "resource": "" }
q38337
tower_layout
train
def tower_layout(graph, height='freeenergy', scale=None, center=None, dim=2): """ Position all nodes of graph stacked on top of each other. Parameters ---------- graph : `networkx.Graph` or `list` of nodes A position will be assigned to every node in graph. height : `str` or `None`, opt...
python
{ "resource": "" }
q38338
diagram_layout
train
def diagram_layout(graph, height='freeenergy', sources=None, targets=None, pos=None, scale=None, center=None, dim=2): """ Position nodes such that paths are highlighted, from left to right. Parameters ---------- graph : `networkx.Graph` or `list` of nodes A position will ...
python
{ "resource": "" }
q38339
draw_diagram_nodes
train
def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7, node_color='k', style='solid', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, label=None): """ Draw nodes of graph. This draws only the nodes of graph as horizontal lines at each ``y...
python
{ "resource": "" }
q38340
draw_diagram_labels
train
def draw_diagram_labels(graph, pos=None, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, bbox=None, ax=None, offset=None, **kwds): """ Draw node labels of graph. This draws only the...
python
{ "resource": "" }
q38341
draw_diagram
train
def draw_diagram(graph, pos=None, with_labels=True, offset=None, **kwds): """ Draw a diagram for graph using Matplotlib. Draw graph as a simple energy diagram with Matplotlib with options for node positions, labeling, titles, and many other drawing features. See examples below. Parameters ...
python
{ "resource": "" }
q38342
PebblePacket.serialise
train
def serialise(self, default_endianness=None): """ Serialise a message, without including any framing. :param default_endianness: The default endianness, unless overridden by the fields or class metadata. Should usually be left at ``None``. Otherwise, use ``'<'...
python
{ "resource": "" }
q38343
PebblePacket.serialise_packet
train
def serialise_packet(self): """ Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet. ``self.Meta.endpoint`` must be defined to call this method. :return: A serialised message, ready to be sent to the Pebble. """ if not ...
python
{ "resource": "" }
q38344
expand_query
train
def expand_query(config, kwds): """ Expand `kwds` based on `config.search.query_expander`. :type config: .config.Configuration :type kwds: dict :rtype: dict :return: Return `kwds`, modified in place. """ pattern = [] for query in kwds.pop('pattern', []): expansion = config....
python
{ "resource": "" }
q38345
preprocess_kwds
train
def preprocess_kwds(kwds): """ Preprocess keyword arguments for `DataBase.search_command_record`. """ from .utils.timeutils import parse_datetime, parse_duration for key in ['output', 'format', 'format_level', 'with_command_id', 'with_session_id']: kwds.pop(key, None) f...
python
{ "resource": "" }
q38346
__fix_args
train
def __fix_args(kwargs): """ Set all named arguments shortcuts and flags. """ kwargs.setdefault('fixed_strings', kwargs.get('F')) kwargs.setdefault('basic_regexp', kwargs.get('G')) kwargs.setdefault('extended_regexp', kwargs.get('E')) kwargs.setdefault('ignore_case', kwargs.get('i')) kwar...
python
{ "resource": "" }
q38347
__process_line
train
def __process_line(line, strip_eol, strip): """ process a single line value. """ if strip: line = line.strip() elif strip_eol and line.endswith('\n'): line = line[:-1] return line
python
{ "resource": "" }
q38348
get_parser
train
def get_parser(commands): """ Generate argument parser given a list of subcommand specifications. :type commands: list of (str, function, function) :arg commands: Each element must be a tuple ``(name, adder, runner)``. :param name: subcommand :param adder: a function takes ...
python
{ "resource": "" }
q38349
locate_run
train
def locate_run(output, target, no_newline): """ Print location of RASH related file. """ from .config import ConfigStore cfstore = ConfigStore() path = getattr(cfstore, "{0}_path".format(target)) output.write(path) if not no_newline: output.write("\n")
python
{ "resource": "" }
q38350
UserInteractionFragment.userBrowser
train
def userBrowser(self, request, tag): """ Render a TDB of local users. """ f = LocalUserBrowserFragment(self.browser) f.docFactory = webtheme.getLoader(f.fragmentName) f.setFragmentParent(self) return f
python
{ "resource": "" }
q38351
UserInteractionFragment.userCreate
train
def userCreate(self, request, tag): """ Render a form for creating new users. """ userCreator = liveform.LiveForm( self.createUser, [liveform.Parameter( "localpart", liveform.TEXT_INPUT, unicode, ...
python
{ "resource": "" }
q38352
UserInteractionFragment.createUser
train
def createUser(self, localpart, domain, password=None): """ Create a new, blank user account with the given name and domain and, if specified, with the given password. @type localpart: C{unicode} @param localpart: The local portion of the username. ie, the C{'alice'} in...
python
{ "resource": "" }
q38353
LocalUserBrowserFragment.doAction
train
def doAction(self, loginMethod, actionClass): """ Show the form for the requested action. """ loginAccount = loginMethod.account return actionClass( self, loginMethod.localpart + u'@' + loginMethod.domain, loginAccount)
python
{ "resource": "" }
q38354
REPL.getStore
train
def getStore(self, name, domain): """Convenience method for the REPL. I got tired of typing this string every time I logged in.""" return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open()
python
{ "resource": "" }
q38355
PortConfiguration.createPort
train
def createPort(self, portNumber, ssl, certPath, factory, interface=u''): """ Create a new listening port. @type portNumber: C{int} @param portNumber: Port number on which to listen. @type ssl: C{bool} @param ssl: Indicates whether this should be an SSL port or not. ...
python
{ "resource": "" }
q38356
FactoryColumn.extractValue
train
def extractValue(self, model, item): """ Get the class name of the factory referenced by a port. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). ...
python
{ "resource": "" }
q38357
CertificateColumn.extractValue
train
def extractValue(self, model, item): """ Get the path referenced by this column's attribute. @param model: Either a TabularDataModel or a ScrollableView, depending on what this column is part of. @param item: A port item instance (as defined by L{xmantissa.port}). @rty...
python
{ "resource": "" }
q38358
connectRoute
train
def connectRoute(amp, router, receiver, protocol): """ Connect the given receiver to a new box receiver for the given protocol. After connecting this router to an AMP server, use this method similarly to how you would use C{reactor.connectTCP} to establish a new connection to an HTTP, SMTP, or ...
python
{ "resource": "" }
q38359
AMPConfiguration.getFactory
train
def getFactory(self): """ Return a server factory which creates AMP protocol instances. """ factory = ServerFactory() def protocol(): proto = CredReceiver() proto.portal = Portal( self.loginSystem, [self.loginSystem, ...
python
{ "resource": "" }
q38360
getfirstline
train
def getfirstline(file, default): """ Returns the first line of a file. """ with open(file, 'rb') as fh: content = fh.readlines() if len(content) == 1: return content[0].decode('utf-8').strip('\n') return default
python
{ "resource": "" }
q38361
JsonRpcResponseBatch.add_item
train
def add_item(self, item): """Adds an item to the batch.""" if not isinstance(item, JsonRpcResponse): raise TypeError( "Expected JsonRpcResponse but got {} instead".format(type(item).__name__)) self.items.append(item)
python
{ "resource": "" }
q38362
LocalPool.manifest
train
def manifest(self, subvol): """ Generator for manifest, yields 7-tuples """ subvol_path = os.path.join(self.path, str(subvol)) builtin_path = os.path.join(subvol_path, MANIFEST_DIR[1:], str(subvol)) manifest_path = os.path.join(MANIFEST_DIR, str(subvol)) if os.pa...
python
{ "resource": "" }
q38363
event_handler
train
def event_handler(event_name): """ Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a J...
python
{ "resource": "" }
q38364
exposed_method
train
def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False): """ Marks a method as exposed via JSON RPC. :param name: the name of the exposed method. Must contains only letters, digits, dots and underscores. If not present or is set explicitly to ``Non...
python
{ "resource": "" }
q38365
Metrics.available
train
def available(self): ''' Check if a related database exists ''' return self.db_name in map( lambda x: x['name'], self._db.get_database_list() )
python
{ "resource": "" }
q38366
make_geohash_tables
train
def make_geohash_tables(table,listofprecisions,**kwargs): ''' sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table ''' return_squares = False sort_by = 'COUNT' # logic for accepting kwarg inputs for key,value in kwargs.iteritems...
python
{ "resource": "" }
q38367
expand_includes
train
def expand_includes(text, path='.'): """Recursively expands includes in given text.""" def read_and_expand(match): filename = match.group('filename') filename = join(path, filename) text = read(filename) return expand_includes( text, path=join(path, dirname(filename))...
python
{ "resource": "" }
q38368
angSepVincenty
train
def angSepVincenty(ra1, dec1, ra2, dec2): """ Vincenty formula for distances on a sphere """ ra1_rad = np.radians(ra1) dec1_rad = np.radians(dec1) ra2_rad = np.radians(ra2) dec2_rad = np.radians(dec2) sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad) sin_dec2, cos_dec2 = np.si...
python
{ "resource": "" }
q38369
parse_file
train
def parse_file(infile, exit_on_error=True): """Parse a comma-separated file with columns "ra,dec,magnitude". """ try: a, b, mag = np.atleast_2d( np.genfromtxt( infile, usecols=[0, 1, 2], ...
python
{ "resource": "" }
q38370
onSiliconCheck
train
def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a single position.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) if dist >= 90.: return False # padding_pix=3 means that objects less than 3 pixels off the edge of # a channel are ...
python
{ "resource": "" }
q38371
onSiliconCheckList
train
def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING): """Check a list of positions.""" dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg) mask = (dist < 90.) out = np.zeros(len(dist), dtype=bool) out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[ma...
python
{ "resource": "" }
q38372
K2onSilicon
train
def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False): """Checks whether targets are on silicon during a given campaign. This function will write a csv table called targets_siliconFlag.csv, which details the silicon status for each target listed in `infile` (0 = not on silicon, 2 = on silion). ...
python
{ "resource": "" }
q38373
K2onSilicon_main
train
def K2onSilicon_main(args=None): """Function called when `K2onSilicon` is executed on the command line.""" import argparse parser = argparse.ArgumentParser( description="Run K2onSilicon to find which targets in a " "list call on active silicon for a given K2 campaign.") parse...
python
{ "resource": "" }
q38374
Template._get_template
train
def _get_template(self, template_name): """ Retrieve the cached version of the template """ if template_name not in self.chached_templates: self.chached_templates[template_name] = self.env.get_template(template_name) return self.chached_templates[template_name]
python
{ "resource": "" }
q38375
Template._render_context
train
def _render_context(self, template, block, **context): """ Render a block to a string with its context """ return u''.join(block(template.new_context(context)))
python
{ "resource": "" }
q38376
Mail.init_app
train
def init_app(self, app): """ For Flask using the app config """ self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"), aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"), region=app.config.get("SES_REGION", "us-east-1"), ...
python
{ "resource": "" }
q38377
Mail.send_template
train
def send_template(self, template, to, reply_to=None, **context): """ Send email from template """ mail_data = self.parse_template(template, **context) subject = mail_data["subject"] body = mail_data["body"] del(mail_data["subject"]) del(mail_data["body"]) ...
python
{ "resource": "" }
q38378
Mail.parse_template
train
def parse_template(self, template, **context): """ To parse a template and return all the blocks """ required_blocks = ["subject", "body"] optional_blocks = ["text_body", "html_body", "return_path", "format"] if self.template_context: context = dict(self.temp...
python
{ "resource": "" }
q38379
_typelist
train
def _typelist(x): """Helper function converting all items of x to instances.""" if isinstance(x, collections.Sequence): return list(map(_to_instance, x)) elif isinstance(x, collections.Iterable): return x return None if x is None else [_to_instance(x)]
python
{ "resource": "" }
q38380
Command.write
train
def write(self, transport, protocol, *data): """Generates and sends a command message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message. :param protocol: An object implementing the `.Protocol` interface. ...
python
{ "resource": "" }
q38381
Command.query
train
def query(self, transport, protocol, *data): """Generates and sends a query message unit. :param transport: An object implementing the `.Transport` interface. It is used by the protocol to send the message and receive the response. :param protocol: An object implementing...
python
{ "resource": "" }
q38382
Driver._write
train
def _write(self, cmd, *datas): """Helper function to simplify writing.""" cmd = Command(write=cmd) cmd.write(self._transport, self._protocol, *datas)
python
{ "resource": "" }
q38383
Driver._query
train
def _query(self, cmd, *datas): """Helper function to allow method queries.""" cmd = Command(query=cmd) return cmd.query(self._transport, self._protocol, *datas)
python
{ "resource": "" }
q38384
YahooFinance.getAll
train
def getAll(self, symbol): """ Get all available quote data for the given ticker symbol. Returns a dictionary. """ values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',') data = {} data['price'] = values[0] data['change'] = va...
python
{ "resource": "" }
q38385
YahooFinance.getQuotes
train
def getQuotes(self, symbol, start, end): """ Get historical prices for the given ticker symbol. Date format is 'YYYY-MM-DD' Returns a nested list. """ try: start = str(start).replace('-', '') end = str(end).replace('-', '') ...
python
{ "resource": "" }
q38386
Product.installProductOn
train
def installProductOn(self, userstore): """ Creates an Installation in this user store for our collection of powerups, and then install those powerups on the user's store. """ def install(): i = Installation(store=userstore) i.types = self.types ...
python
{ "resource": "" }
q38387
Product.installOrResume
train
def installOrResume(self, userstore): """ Install this product on a user store. If this product has been installed on the user store already and the installation is suspended, it will be resumed. If it exists and is not suspended, an error will be raised. """ for ...
python
{ "resource": "" }
q38388
Installation.items
train
def items(self): """ Loads the items this Installation refers to. """ for id in self._items: yield self.store.getItemByID(int(id))
python
{ "resource": "" }
q38389
Installation.install
train
def install(self): """ Called when installed on the user store. Installs my powerups. """ items = [] for typeName in self.types: it = self.store.findOrCreate(namedAny(typeName)) installOn(it, self.store) items.append(str(it.storeID).decode('asc...
python
{ "resource": "" }
q38390
Installation.uninstall
train
def uninstall(self): """ Called when uninstalled from the user store. Uninstalls all my powerups. """ for item in self.items: uninstallFrom(item, self.store) self._items = []
python
{ "resource": "" }
q38391
ProductFragment.coerceProduct
train
def coerceProduct(self, **kw): """ Create a product and return a status string which should be part of a template. @param **kw: Fully qualified Python names for powerup types to associate with the created product. """ self.original.createProduct(filter(None, kw.v...
python
{ "resource": "" }
q38392
Action.fetch
train
def fetch(self): """ Fetch & return a new `Action` object representing the action's current state :rtype: Action :raises DOAPIError: if the API endpoint replies with an error """ api = self.doapi_manager return api._action(api.request(self.url)["action"])
python
{ "resource": "" }
q38393
Action.wait
train
def wait(self, wait_interval=None, wait_time=None): """ Poll the server periodically until the action has either completed or errored out and return its final state. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the action's most recently fetched state) is raise...
python
{ "resource": "" }
q38394
CachedJSModule.wasModified
train
def wasModified(self): """ Check to see if this module has been modified on disk since the last time it was cached. @return: True if it has been modified, False if not. """ self.filePath.restat() mtime = self.filePath.getmtime() if mtime >= self.lastModif...
python
{ "resource": "" }
q38395
CachedJSModule.maybeUpdate
train
def maybeUpdate(self): """ Check this cache entry and update it if any filesystem information has changed. """ if self.wasModified(): self.lastModified = self.filePath.getmtime() self.fileContents = self.filePath.getContent() self.hashValue = h...
python
{ "resource": "" }
q38396
HashedJSModuleProvider.getModule
train
def getModule(self, moduleName): """ Retrieve a JavaScript module cache from the file path cache. @returns: Module cache for the named module. @rtype: L{CachedJSModule} """ if moduleName not in self.moduleCache: modulePath = FilePath( athena.j...
python
{ "resource": "" }
q38397
check_result
train
def check_result(data, key=''): """Check the result of an API response. Ideally, this should be done by checking that the value of the ``resultCode`` attribute is 0, but there are endpoints that simply do not follow this rule. Args: data (dict): Response obtained from the API endpoint. ...
python
{ "resource": "" }
q38398
datetime_string
train
def datetime_string(day, month, year, hour, minute): """Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Yea...
python
{ "resource": "" }
q38399
response_list
train
def response_list(data, key): """Obtain the relevant response data in a list. If the response does not already contain the result in a list, a new one will be created to ease iteration in the parser methods. Args: data (dict): API response. key (str): Attribute of the response that con...
python
{ "resource": "" }