_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q39600
Arg.undone
train
def undone(self, index): """Handles the 'D' command. :index: Index of the item to mark as not done. """ if self.model.exists(index): self.model.edit(index, done=False)
python
{ "resource": "" }
q39601
Arg.options
train
def options(self, glob=False, **args): """Handles the 'o' command. :glob: Whether to store specified options globally. :args: Arguments supplied to the 'o' command (excluding '-g'). """ kwargs = {} for argname, argarg in args.items(): if argname == "sort": ...
python
{ "resource": "" }
q39602
Arg.getKwargs
train
def getKwargs(self, args, values={}, get=Get()): """Gets necessary data from user input. :args: Dictionary of arguments supplied in command line. :values: Default values dictionary, supplied for editing. :get: Object used to get values from user input. :returns: A dictionary con...
python
{ "resource": "" }
q39603
CacheEntry.url
train
def url(self): """ The cache entry's URL. The URL is constructed from the values of the scheme, host, and path attributes. Assigning a value to the URL attribute causes the value to be parsed and the scheme, host and path attributes updated. """ return urlparse.urlunparse((self.scheme, self.host, self.p...
python
{ "resource": "" }
q39604
CacheEntry.from_T050017
train
def from_T050017(cls, url, coltype = LIGOTimeGPS): """ Parse a URL in the style of T050017-00 into a CacheEntry. The T050017-00 file name format is, essentially, observatory-description-start-duration.extension Example: >>> c = CacheEntry.from_T050017("file://localhost/data/node144/frames/S5/strain-L2/LL...
python
{ "resource": "" }
q39605
Cache.fromfile
train
def fromfile(cls, fileobj, coltype=LIGOTimeGPS): """ Return a Cache object whose entries are read from an open file. """ c = [cls.entry_class(line, coltype=coltype) for line in fileobj] return cls(c)
python
{ "resource": "" }
q39606
Cache.fromfilenames
train
def fromfilenames(cls, filenames, coltype=LIGOTimeGPS): """ Read Cache objects from the files named and concatenate the results into a single Cache. """ cache = cls() for filename in filenames: cache.extend(cls.fromfile(open(filename), coltype=coltype)) return cache
python
{ "resource": "" }
q39607
Cache.unique
train
def unique(self): """ Return a Cache which has every element of self, but without duplication. Preserve order. Does not hash, so a bit slow. """ new = self.__class__([]) for elem in self: if elem not in new: new.append(elem) return new
python
{ "resource": "" }
q39608
Cache.tofile
train
def tofile(self, fileobj): """ write a cache object to the fileobj as a lal cache file """ for entry in self: print >>fileobj, str(entry) fileobj.close()
python
{ "resource": "" }
q39609
Cache.topfnfile
train
def topfnfile(self, fileobj): """ write a cache object to filename as a plain text pfn file """ for entry in self: print >>fileobj, entry.path fileobj.close()
python
{ "resource": "" }
q39610
Cache.to_segmentlistdict
train
def to_segmentlistdict(self): """ Return a segmentlistdict object describing the instruments and times spanned by the entries in this Cache. The return value is coalesced. """ d = segments.segmentlistdict() for entry in self: d |= entry.segmentlistdict return d
python
{ "resource": "" }
q39611
get_ilwdchar_class
train
def get_ilwdchar_class(tbl_name, col_name, namespace = globals()): """ Searches this module's namespace for a subclass of _ilwd.ilwdchar whose table_name and column_name attributes match those provided. If a matching subclass is found it is returned; otherwise a new class is defined, added to this module's namespa...
python
{ "resource": "" }
q39612
doc_includes_process
train
def doc_includes_process(xmldoc, program): """ Return True if the process table in xmldoc includes entries for a program named program. """ return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program")
python
{ "resource": "" }
q39613
plugitInclude
train
def plugitInclude(parser, token): """ Load and render a template, using the same context of a specific action. Example: {% plugitInclude "/menuBar" %} """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'plugitInclude' tag takes one argument: the tem...
python
{ "resource": "" }
q39614
set_temp_store_directory
train
def set_temp_store_directory(connection, temp_store_directory, verbose = False): """ Sets the temp_store_directory parameter in sqlite. """ if temp_store_directory == "_CONDOR_SCRATCH_DIR": temp_store_directory = os.getenv("_CONDOR_SCRATCH_DIR") if verbose: print >>sys.stderr, "setting the temp_store_directory...
python
{ "resource": "" }
q39615
idmap_sync
train
def idmap_sync(connection): """ Iterate over the tables in the database, ensure that there exists a custom DBTable class for each, and synchronize that table's ID generator to the ID values in the database. """ xmldoc = get_xml(connection) for tbl in xmldoc.getElementsByTagName(DBTable.tagName): tbl.sync_next_...
python
{ "resource": "" }
q39616
idmap_get_new
train
def idmap_get_new(connection, old, tbl): """ From the old ID string, obtain a replacement ID string by either grabbing it from the _idmap_ table if one has already been assigned to the old ID, or by using the current value of the Table instance's next_id class attribute. In the latter case, the new ID is recorde...
python
{ "resource": "" }
q39617
get_table_names
train
def get_table_names(connection): """ Return a list of the table names in the database. """ cursor = connection.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'") return [name for (name,) in cursor]
python
{ "resource": "" }
q39618
build_indexes
train
def build_indexes(connection, verbose = False): """ Using the how_to_index annotations in the table class definitions, construct a set of indexes for the database at the given connection. """ cursor = connection.cursor() for table_name in get_table_names(connection): # FIXME: figure out how to do this extensi...
python
{ "resource": "" }
q39619
DBTable.row_from_cols
train
def row_from_cols(self, values): """ Given an iterable of values in the order of columns in the database, construct and return a row object. This is a convenience function for turning the results of database queries into Python objects. """ row = self.RowType() for c, t, v in zip(self.dbcolumnnames, se...
python
{ "resource": "" }
q39620
DBTable.applyKeyMapping
train
def applyKeyMapping(self): """ Used as the second half of the key reassignment algorithm. Loops over each row in the table, replacing references to old row keys with the new values from the _idmap_ table. """ assignments = ", ".join("%s = (SELECT new FROM _idmap_ WHERE old == %s)" % (colname, colname) for c...
python
{ "resource": "" }
q39621
findCredential
train
def findCredential(): """ Follow the usual path that GSI libraries would follow to find a valid proxy credential but also allow an end entity certificate to be used along with an unencrypted private key if they are pointed to by X509_USER_CERT and X509_USER_KEY since we expect this will be t...
python
{ "resource": "" }
q39622
validateProxy
train
def validateProxy(path): """ Test that the proxy certificate is RFC 3820 compliant and that it is valid for at least the next 15 minutes. """ # load the proxy from path try: proxy = M2Crypto.X509.load_cert(path) except Exception, e: msg = "Unable to load proxy from path ...
python
{ "resource": "" }
q39623
CustomerProfile.save
train
def save(self, *args, **kwargs): """If creating new instance, create profile on Authorize.NET also""" data = kwargs.pop('data', {}) sync = kwargs.pop('sync', True) if not self.id and sync: self.push_to_server(data) super(CustomerProfile, self).save(*args, **kwargs)
python
{ "resource": "" }
q39624
CustomerProfile.delete
train
def delete(self): """Delete the customer profile remotely and locally""" response = delete_profile(self.profile_id) response.raise_if_error() super(CustomerProfile, self).delete()
python
{ "resource": "" }
q39625
CustomerProfile.push_to_server
train
def push_to_server(self, data): """Create customer profile for given ``customer`` on Authorize.NET""" output = add_profile(self.customer.pk, data, data) output['response'].raise_if_error() self.profile_id = output['profile_id'] self.payment_profile_ids = output['payment_profile_i...
python
{ "resource": "" }
q39626
CustomerProfile.sync
train
def sync(self): """Overwrite local customer profile data with remote data""" output = get_profile(self.profile_id) output['response'].raise_if_error() for payment_profile in output['payment_profiles']: instance, created = CustomerPaymentProfile.objects.get_or_create( ...
python
{ "resource": "" }
q39627
CustomerPaymentProfile.save
train
def save(self, *args, **kwargs): """Sync payment profile on Authorize.NET if sync kwarg is not False""" if kwargs.pop('sync', True): self.push_to_server() self.card_code = None self.card_number = "XXXX%s" % self.card_number[-4:] super(CustomerPaymentProfile, self).sav...
python
{ "resource": "" }
q39628
CustomerPaymentProfile.push_to_server
train
def push_to_server(self): """ Use appropriate CIM API call to save payment profile to Authorize.NET 1. If customer has no profile yet, create one with this payment profile 2. If payment profile is not on Authorize.NET yet, create it there 3. If payment profile exists on Authorize...
python
{ "resource": "" }
q39629
CustomerPaymentProfile.sync
train
def sync(self, data): """Overwrite local customer payment profile data with remote data""" for k, v in data.get('billing', {}).items(): setattr(self, k, v) self.card_number = data.get('credit_card', {}).get('card_number', sel...
python
{ "resource": "" }
q39630
CustomerPaymentProfile.delete
train
def delete(self): """Delete the customer payment profile remotely and locally""" response = delete_payment_profile(self.customer_profile.profile_id, self.payment_profile_id) response.raise_if_error() return super(CustomerPaymentProfile, self).del...
python
{ "resource": "" }
q39631
get_changelog_file_for_database
train
def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS): """get changelog filename for given `database` DB alias""" from django.conf import settings try: return settings.LIQUIMIGRATE_CHANGELOG_FILES[database] except AttributeError: if database == DEFAULT_DB_ALIAS: tr...
python
{ "resource": "" }
q39632
find_target_migration_file
train
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None): """Finds best matching target migration file""" if not database: database = DEFAULT_DB_ALIAS if not changelog_file: changelog_file = get_changelog_file_for_database(database) try: doc = minidom.par...
python
{ "resource": "" }
q39633
BOSHClient.connection
train
def connection(self): """Returns an stablished connection""" if self._connection: return self._connection self.log.debug('Initializing connection to %s' % (self.bosh_service. netloc)) if self.bosh_service.scheme == '...
python
{ "resource": "" }
q39634
BOSHClient.send_challenge_response
train
def send_challenge_response(self, response_plain): """Send a challenge response to server""" # Get a basic stanza body body = self.get_body() # Create a response tag and add the response content on it # using base64 encoding response_node = ET.SubElement(body, 'respon...
python
{ "resource": "" }
q39635
BOSHClient.authenticate_xmpp
train
def authenticate_xmpp(self): """Authenticate the user to the XMPP server via the BOSH connection.""" self.request_sid() self.log.debug('Prepare the XMPP authentication') # Instantiate a sasl object sasl = SASLClient( host=self.to, service='xmpp', ...
python
{ "resource": "" }
q39636
getParamsByName
train
def getParamsByName(elem, name): """ Return a list of params with name name under elem. """ name = StripParamName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Param.tagName) and (e.Name == name))
python
{ "resource": "" }
q39637
get_param
train
def get_param(xmldoc, name): """ Scan xmldoc for a param named name. Raises ValueError if not exactly 1 such param is found. """ params = getParamsByName(xmldoc, name) if len(params) != 1: raise ValueError("document must contain exactly one %s param" % StripParamName(name)) return params[0]
python
{ "resource": "" }
q39638
pickle_to_param
train
def pickle_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the pickled serialization of a Python object. """ return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj)))
python
{ "resource": "" }
q39639
pickle_from_param
train
def pickle_from_param(elem, name): """ Retrieve a pickled Python object from the document tree rooted at elem. """ return pickle.loads(str(get_pyvalue(elem, u"pickle:%s" % name)))
python
{ "resource": "" }
q39640
yaml_to_param
train
def yaml_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the YAML serialization of a Python object. """ return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
python
{ "resource": "" }
q39641
use_in
train
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Param class defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> def MyContentHandler(ligolw.LIGOLWContentHandler): ... pass ...
python
{ "resource": "" }
q39642
RoundRobinConnectionPool.all_connections
train
def all_connections(self): """Returns a generator over all current connection objects""" for i in _xrange(self.num_patterns): for c in self._available_connections[i]: yield c for c in self._in_use_connections[i]: yield c
python
{ "resource": "" }
q39643
RoundRobinConnectionPool.purge
train
def purge(self, connection): """Remove the connection from rotation""" self._checkpid() if connection.pid == self.pid: idx = connection._pattern_idx if connection in self._in_use_connections[idx]: self._in_use_connections[idx].remove(connection) ...
python
{ "resource": "" }
q39644
local_path_from_url
train
def local_path_from_url(url): """ For URLs that point to locations in the local filesystem, extract and return the filesystem path of the object to which they point. As a special case pass-through, if the URL is None, the return value is None. Raises ValueError if the URL is not None and does not point to a loca...
python
{ "resource": "" }
q39645
load_fileobj
train
def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None): """ Parse the contents of the file object fileobj, and return the contents as a LIGO Light Weight document tree. The file object does not need to be seekable. If the gz parameter is None (the default) then gzip compressed data will be a...
python
{ "resource": "" }
q39646
write_filename
train
def write_filename(xmldoc, filename, verbose = False, gz = False, **kwargs): """ Writes the LIGO Light Weight document tree rooted at xmldoc to the file name filename. Friendly verbosity messages are printed while doing so if verbose is True. The output data is gzip compressed on the fly if gz is True. Interna...
python
{ "resource": "" }
q39647
home
train
def home(request): """Show the home page. Send the list of polls""" polls = [] for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'): polls.append({'id': row[0], 'name': row[1]}) return {'polls': polls}
python
{ "resource": "" }
q39648
show
train
def show(request, pollId): """Show a poll. We send informations about votes only if the user is an administrator""" # Get the poll curDB.execute('SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title', (pollId,)) poll = curDB.fetchone() if poll is None: return {} respons...
python
{ "resource": "" }
q39649
vote
train
def vote(request, pollId, responseId): """Vote for a poll""" username = request.args.get('ebuio_u_username') # Remove old votes from the same user on the same poll curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId)) ...
python
{ "resource": "" }
q39650
create
train
def create(request): """Create a new poll""" errors = [] success = False listOfResponses = ['', '', ''] # 3 Blank lines by default title = '' description = '' id = '' if request.method == 'POST': # User saved the form # Retrieve parameters title = request.form.get('ti...
python
{ "resource": "" }
q39651
HasNonLSCTables
train
def HasNonLSCTables(elem): """ Return True if the document tree below elem contains non-LSC tables, otherwise return False. """ return any(t.Name not in TableByName for t in elem.getElementsByTagName(ligolw.Table.tagName))
python
{ "resource": "" }
q39652
ifos_from_instrument_set
train
def ifos_from_instrument_set(instruments): """ Convert an iterable of instrument names into a value suitable for storage in the "ifos" column found in many tables. This function is mostly for internal use by the .instruments properties of the corresponding row classes. The input can be None or an iterable of ze...
python
{ "resource": "" }
q39653
use_in
train
def use_in(ContentHandler): """ Modify ContentHandler, a sub-class of pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table classes defined in this module when parsing XML documents. Example: >>> from pycbc_glue.ligolw import ligolw >>> class MyContentHandler(ligolw.LIGOLWContentHandler): ... p...
python
{ "resource": "" }
q39654
ProcessTable.get_ids_by_program
train
def get_ids_by_program(self, program): """ Return a set containing the process IDs from rows whose program string equals the given program. """ return set(row.process_id for row in self if row.program == program)
python
{ "resource": "" }
q39655
SearchSummaryTable.get_in_segmentlistdict
train
def get_in_segmentlistdict(self, process_ids = None): """ Return a segmentlistdict mapping instrument to in segment list. If process_ids is a sequence of process IDs, then only rows with matching IDs are included otherwise all rows are included. Note: the result is not coalesced, each segmentlist conta...
python
{ "resource": "" }
q39656
SearchSummaryTable.get_out_segmentlistdict
train
def get_out_segmentlistdict(self, process_ids = None): """ Return a segmentlistdict mapping instrument to out segment list. If process_ids is a sequence of process IDs, then only rows with matching IDs are included otherwise all rows are included. Note: the result is not coalesced, each segmentlist con...
python
{ "resource": "" }
q39657
ExperimentTable.get_expr_id
train
def get_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None): """ Return the expr_def_id for the row in the table whose values match the givens. If a matching row is not found, returns None. @search_group: string representing the search group (e.g., cbc) ...
python
{ "resource": "" }
q39658
ExperimentTable.write_new_expr_id
train
def write_new_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None): """ Creates a new def_id for the given arguments and returns it. If an entry already exists with these, will just return that id. @search_group: string representing the search group (e.g., c...
python
{ "resource": "" }
q39659
ExperimentTable.get_row_from_id
train
def get_row_from_id(self, experiment_id): """ Returns row in matching the given experiment_id. """ row = [row for row in self if row.experiment_id == experiment_id] if len(row) > 1: raise ValueError("duplicate ids in experiment table") if len(row) == 0: raise ValueError("id '%s' not found in table" % ...
python
{ "resource": "" }
q39660
ExperimentSummaryTable.get_expr_summ_id
train
def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None): """ Return the expr_summ_id for the row in the table whose experiment_id, time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id, will retrieve the injection run matching that sim_proc_id....
python
{ "resource": "" }
q39661
ExperimentSummaryTable.write_experiment_summ
train
def write_experiment_summ(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None ): """ Writes a single entry to the experiment_summ table. This can be used for either injections or non-injection experiments. However, it is recommended that this only be used for injection experiments; f...
python
{ "resource": "" }
q39662
ExperimentSummaryTable.add_nevents
train
def add_nevents(self, experiment_summ_id, num_events, add_to_current = True): """ Add num_events to the nevents column in a specific entry in the table. If add_to_current is set to False, will overwrite the current nevents entry in the row with num_events. Otherwise, default is to add num_events to the curren...
python
{ "resource": "" }
q39663
ExperimentMapTable.get_experiment_summ_ids
train
def get_experiment_summ_ids( self, coinc_event_id ): """ Gets all the experiment_summ_ids that map to a given coinc_event_id. """ experiment_summ_ids = [] for row in self: if row.coinc_event_id == coinc_event_id: experiment_summ_ids.append(row.experiment_summ_id) if len(experiment_summ_ids) == 0: ...
python
{ "resource": "" }
q39664
SnglInspiralTable.ifocut
train
def ifocut(self, ifo, inplace=False): """ Return a SnglInspiralTable with rows from self having IFO equal to the given ifo. If inplace, modify self directly, else create a new table and fill it. """ if inplace: iterutils.inplace_filter(lambda row: row.ifo == ifo, self) return self else: ifoTrigs ...
python
{ "resource": "" }
q39665
SnglInspiralTable.getslide
train
def getslide(self,slide_num): """ Return the triggers with a specific slide number. @param slide_num: the slide number to recover (contained in the event_id) """ slideTrigs = self.copy() slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num) return slideTrigs
python
{ "resource": "" }
q39666
SnglInspiral.get_id_parts
train
def get_id_parts(self): """ Return the three pieces of the int_8s-style sngl_inspiral event_id. """ int_event_id = int(self.event_id) a = int_event_id // 1000000000 slidenum = (int_event_id % 1000000000) // 100000 b = int_event_id % 100000 return int(a), int(slidenum), int(b)
python
{ "resource": "" }
q39667
SnglInspiral.get_slide_number
train
def get_slide_number(self): """ Return the slide-number for this trigger """ a, slide_number, b = self.get_id_parts() if slide_number > 5000: slide_number = 5000 - slide_number return slide_number
python
{ "resource": "" }
q39668
MultiInspiralTable.get_null_snr
train
def get_null_snr(self): """ Get the coherent Null SNR for each row in the table. """ null_snr_sq = self.get_coinc_snr()**2 - self.get_column('snr')**2 null_snr_sq[null_snr_sq < 0] = 0. return null_snr_sq**(1./2.)
python
{ "resource": "" }
q39669
MultiInspiralTable.get_sigmasqs
train
def get_sigmasqs(self, instruments=None): """ Return dictionary of single-detector sigmas for each row in the table. """ if len(self): if not instruments: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) return dict((ifo, self.get_sigmasq(ifo))\ for ifo in instruments) ...
python
{ "resource": "" }
q39670
MultiInspiralTable.get_sngl_snrs
train
def get_sngl_snrs(self, instruments=None): """ Get the single-detector SNRs for each row in the table. """ if len(self) and instruments is None: instruments = map(str, \ instrument_set_from_ifos(self[0].ifos)) elif instruments is None: instruments = [] return dict((ifo, self.get_sng...
python
{ "resource": "" }
q39671
MultiInspiralTable.get_bestnr
train
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Get the BestNR statistic for each row in the table """ return [row.get_bestnr(index=index, nhigh=nhigh, null_snr_threshold=null_snr_threshold, ...
python
{ "resource": "" }
q39672
MultiInspiral.get_null_snr
train
def get_null_snr(self): """ Get the coherent Null SNR for this row. """ null_snr_sq = (numpy.asarray(self.get_sngl_snrs().values())**2)\ .sum() - self.snr**2 if null_snr_sq < 0: return 0 else: return null_snr_sq**(1./2.)
python
{ "resource": "" }
q39673
MultiInspiral.get_sngl_snrs
train
def get_sngl_snrs(self): """ Return a dictionary of single-detector SNRs for this row. """ return dict((ifo, self.get_sngl_snr(ifo)) for ifo in\ instrument_set_from_ifos(self.ifos))
python
{ "resource": "" }
q39674
MultiInspiral.get_bestnr
train
def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\ null_grad_thresh=20., null_grad_val = 1./5.): """ Return the BestNR statistic for this row. """ # weight SNR by chisq bestnr = self.get_new_snr(index=index, nhigh=nhigh, column="chisq") if len(self....
python
{ "resource": "" }
q39675
SegmentSumTable.get
train
def get(self, segment_def_id = None): """ Return a segmentlist object describing the times spanned by the segments carrying the given segment_def_id. If segment_def_id is None then all segments are returned. Note: the result is not coalesced, the segmentlist contains the segments as they appear in the ta...
python
{ "resource": "" }
q39676
CoincDefTable.get_coinc_def_id
train
def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None): """ Return the coinc_def_id for the row in the table whose search string and search_coinc_type integer have the values given. If a matching row is not found, the default behaviour is to create a new row and return t...
python
{ "resource": "" }
q39677
DQSpec.apply_to_segmentlist
train
def apply_to_segmentlist(self, seglist): """ Apply our low and high windows to the segments in a segmentlist. """ for i, seg in enumerate(seglist): seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window)
python
{ "resource": "" }
q39678
synchronizeLayout
train
def synchronizeLayout(primary, secondary, surface_size): """Synchronizes given layouts by normalizing height by using max height of given layouts to avoid transistion dirty effects. :param primary: Primary layout used. :param secondary: Secondary layout used. :param surface_size: Target surface siz...
python
{ "resource": "" }
q39679
VKeyboardRenderer.draw_uppercase_key
train
def draw_uppercase_key(self, surface, key): """Default drawing method for uppercase key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'\u21e7' if key.is_activated(): key.v...
python
{ "resource": "" }
q39680
VKeyboardRenderer.draw_special_char_key
train
def draw_special_char_key(self, surface, key): """Default drawing method for special char key. Drawn as character key. :param surface: Surface background should be drawn in. :param key: Target key to be drawn. """ key.value = u'#' if key.is_activated(): key....
python
{ "resource": "" }
q39681
VKeyRow.add_key
train
def add_key(self, key, first=False): """Adds the given key to this row. :param key: Key to be added to this row. :param first: BOolean flag that indicates if key is added at the beginning or at the end. """ if first: self.keys = [key] + self.keys else: ...
python
{ "resource": "" }
q39682
VKeyRow.set_size
train
def set_size(self, position, size, padding): """Row size setter. The size correspond to the row height, since the row width is constraint to the surface width the associated keyboard belongs. Once size is settled, the size for each child keys is associated. :param posit...
python
{ "resource": "" }
q39683
VKeyboardLayout.configure_specials_key
train
def configure_specials_key(self, keyboard): """Configures specials key if needed. :param keyboard: Keyboard instance this layout belong. """ special_row = VKeyRow() max_length = self.max_length i = len(self.rows) - 1 current_row = self.rows[i] special_key...
python
{ "resource": "" }
q39684
VKeyboardLayout.configure_bound
train
def configure_bound(self, surface_size): """Compute keyboard bound regarding of this layout. If key_size is None, then it will compute it regarding of the given surface_size. :param surface_size: Size of the surface this layout will be rendered on. :raise ValueError: If the lay...
python
{ "resource": "" }
q39685
VKeyboardLayout.set_size
train
def set_size(self, size, surface_size): """Sets the size of this layout, and updates position, and rows accordingly. :param size: Size of this layout. :param surface_size: Target surface size on which layout will be displayed. """ self.size = size self.position =...
python
{ "resource": "" }
q39686
VKeyboardLayout.invalidate
train
def invalidate(self): """ Rests all keys states. """ for row in self.rows: for key in row.keys: key.state = 0
python
{ "resource": "" }
q39687
VKeyboardLayout.set_uppercase
train
def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value ...
python
{ "resource": "" }
q39688
VKeyboard.draw
train
def draw(self): """ Draw the virtual keyboard into the delegate surface object if enabled. """ if self.state > 0: self.renderer.draw_background(self.surface, self.layout.position, self.layout.size) for row in self.layout.rows: for key in row.keys: ...
python
{ "resource": "" }
q39689
VKeyboard.on_uppercase
train
def on_uppercase(self): """ Uppercase key press handler. """ self.uppercase = not self.uppercase self.original_layout.set_uppercase(self.uppercase) self.special_char_layout.set_uppercase(self.uppercase) self.invalidate()
python
{ "resource": "" }
q39690
VKeyboard.on_special_char
train
def on_special_char(self): """ Special char key press handler. """ self.special_char = not self.special_char if self.special_char: self.set_layout(self.special_char_layout) else: self.set_layout(self.original_layout) self.invalidate()
python
{ "resource": "" }
q39691
VKeyboard.on_event
train
def on_event(self, event): """Pygame event processing callback method. :param event: Event to process. """ if self.state > 0: if event.type == MOUSEBUTTONDOWN: key = self.layout.get_key_at(pygame.mouse.get_pos()) if key is not None: ...
python
{ "resource": "" }
q39692
VKeyboard.set_key_state
train
def set_key_state(self, key, state): """Sets the key state and redraws it. :param key: Key to update state for. :param state: New key state. """ key.state = state self.renderer.draw_key(self.surface, key)
python
{ "resource": "" }
q39693
VKeyboard.on_key_up
train
def on_key_up(self): """ Process key up event by updating buffer and release key. """ if (self.last_pressed is not None): self.set_key_state(self.last_pressed, 0) self.buffer = self.last_pressed.update_buffer(self.buffer) self.text_consumer(self.buffer) se...
python
{ "resource": "" }
q39694
Cell.same_player
train
def same_player(self, other): """ Compares name and color. Returns True if both are owned by the same player. """ return self.name == other.name \ and self.color == other.color
python
{ "resource": "" }
q39695
World.reset
train
def reset(self): """ Clears the `cells` and leaderboards, and sets all corners to `0,0`. """ self.cells.clear() self.leaderboard_names.clear() self.leaderboard_groups.clear() self.top_left.set(0, 0) self.bottom_right.set(0, 0)
python
{ "resource": "" }
q39696
Player.cells_changed
train
def cells_changed(self): """ Calculates `total_size`, `total_mass`, `scale`, and `center`. Has to be called when the controlled cells (`own_ids`) change. """ self.total_size = sum(cell.size for cell in self.own_cells) self.total_mass = sum(cell.mass for cell in self.own_...
python
{ "resource": "" }
q39697
has_segment_tables
train
def has_segment_tables(xmldoc, name = None): """ Return True if the document contains a complete set of segment tables. Returns False otherwise. If name is given and not None then the return value is True only if the document's segment tables, if present, contain a segment list by that name. """ try: names =...
python
{ "resource": "" }
q39698
segmenttable_get_by_name
train
def segmenttable_get_by_name(xmldoc, name): """ Retrieve the segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. The output of this function is not coalesced, each segmentlist contains the segments as found in the segment table. NOTE: this is a light-weight version of t...
python
{ "resource": "" }
q39699
LigolwSegments.insert_from_segwizard
train
def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None): """ Parse the contents of the file object fileobj as a segwizard-format segment list, and insert the result as a new list of "active" segments into this LigolwSegments object. A new entry will be created in the segme...
python
{ "resource": "" }