_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q38400
Graph.base_uri
train
def base_uri(self): """ Resolution base for JSON schema. Also used as the default graph ID for RDF. """ if self._base_uri is None: if self._resolver is not None: self._base_uri = self.resolver.resolution_scope else: self._base_uri = 'http:/...
python
{ "resource": "" }
q38401
Graph.resolver
train
def resolver(self): """ Resolver for JSON Schema references. This can be based around a file or HTTP-based resolution base URI. """ if self._resolver is None: self._resolver = RefResolver(self.base_uri, {}) # if self.base_uri not in self._resolver.store: # self._re...
python
{ "resource": "" }
q38402
Graph.store
train
def store(self): """ Backend storage for RDF data. Either an in-memory store, or an external triple store controlled via SPARQL. """ if self._store is None: config = self.config.get('store', {}) if 'query' in config and 'update' in config: self._store = sp...
python
{ "resource": "" }
q38403
Graph.graph
train
def graph(self): """ A conjunctive graph of all statements in the current instance. """ if not hasattr(self, '_graph') or self._graph is None: self._graph = ConjunctiveGraph(store=self.store, identifier=self.base_uri) return self._graph
python
{ "resource": "" }
q38404
Graph.buffered
train
def buffered(self): """ Whether write operations should be buffered, i.e. run against a local graph before being stored to the main data store. """ if 'buffered' not in self.config: return not isinstance(self.store, (Memory, IOMemory)) return self.config.get('buffered')
python
{ "resource": "" }
q38405
Graph.register
train
def register(self, alias, uri): """ Register a new schema URI under a given name. """ # TODO: do we want to constrain the valid alias names. if isinstance(uri, dict): id = uri.get('id', alias) self.resolver.store[id] = uri uri = id self.aliases[alias] ...
python
{ "resource": "" }
q38406
Graph.get_uri
train
def get_uri(self, alias): """ Get the URI for a given alias. A registered URI will return itself, otherwise ``None`` is returned. """ if alias in self.aliases.keys(): return self.aliases[alias] if alias in self.aliases.values(): return alias raise GraphExc...
python
{ "resource": "" }
q38407
is_url
train
def is_url(text): """ Check if the given text looks like a URL. """ if text is None: return False text = text.lower() return text.startswith('http://') or text.startswith('https://') or \ text.startswith('urn:') or text.startswith('file://')
python
{ "resource": "" }
q38408
safe_uriref
train
def safe_uriref(text): """ Escape a URL properly. """ url_ = url.parse(text).sanitize().deuserinfo().canonical() return URIRef(url_.punycode().unicode())
python
{ "resource": "" }
q38409
KeplerFov.computePointing
train
def computePointing(self, ra_deg, dec_deg, roll_deg, cartesian=False): """Compute a pointing model without changing the internal object pointing""" # Roll FOV Rrotate = r.rotateInXMat(roll_deg) # Roll # Slew from ra/dec of zero Ra = r.rightAscensionRotationMatrix(ra_deg) ...
python
{ "resource": "" }
q38410
KeplerFov.getRaDecs
train
def getRaDecs(self, mods): """Internal function converting cartesian coords to ra dec""" raDecOut = np.empty( (len(mods), 5)) raDecOut[:,0:3] = mods[:,0:3] for i, row in enumerate(mods): raDecOut[i, 3:5] = r.raDecFromVec(row[3:6]) return raDecOut
python
{ "resource": "" }
q38411
KeplerFov.isOnSilicon
train
def isOnSilicon(self, ra_deg, dec_deg, padding_pix=DEFAULT_PADDING): """Returns True if the given location is observable with a science CCD. Parameters ---------- ra_deg : float Right Ascension (J2000) in decimal degrees. dec_deg : float Declination (J20...
python
{ "resource": "" }
q38412
KeplerFov.getAllChannelsAsPolygons
train
def getAllChannelsAsPolygons(self, maptype=None): """Return slew the telescope and return the corners of the modules as Polygon objects. If a projection is supplied, the ras and decs are mapped onto x, y using that projection """ polyList = [] for ch in self.orig...
python
{ "resource": "" }
q38413
KeplerFov.plotPointing
train
def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs): """Plot the FOV """ if maptype is None: maptype=self.defaultMap radec = self.currentRaDec for ch in radec[:,2][::4]: idx = np.where(radec[:,2].astype(np.int) == ch)[0] ...
python
{ "resource": "" }
q38414
KeplerFov.plotOutline
train
def plotOutline(self, maptype=None, colour='#AAAAAA', **kwargs): """Plot an outline of the FOV. """ if maptype is None: maptype=self.defaultMap xarr = [] yarr = [] radec = self.currentRaDec for ch in [20,4,11,28,32, 71,68, 84, 75, 60, 56, 15 ]: ...
python
{ "resource": "" }
q38415
KeplerFov.plotSpacecraftYAxis
train
def plotSpacecraftYAxis(self, maptype=None): """Plot a line pointing in the direction of the spacecraft y-axis (i.e normal to the solar panel """ if maptype is None: maptype=self.defaultMap #Plot direction of spacecraft +y axis. The subtraction of #90 degrees...
python
{ "resource": "" }
q38416
KeplerFov.plotChIds
train
def plotChIds(self, maptype=None, modout=False): """Print the channel numbers on the plotting display Note: --------- This method will behave poorly if you are plotting in mixed projections. Because the channel vertex polygons are already projected using self.defaultMap,...
python
{ "resource": "" }
q38417
Polygon.isPointInside
train
def isPointInside(self, xp, yp): """Is the given point inside the polygon? Input: ------------ xp, yp (floats) Coordinates of point in same units that array vertices are specified when object created. Returns: ----------- **True** / **Fals...
python
{ "resource": "" }
q38418
Polygon.draw
train
def draw(self, **kwargs): """Draw the polygon Optional Inputs: ------------ All optional inputs are passed to ``matplotlib.patches.Polygon`` Notes: --------- Does not accept maptype as an argument. """ ax = mp.gca() shape = matplotlib.pa...
python
{ "resource": "" }
q38419
IEC60488.parse_response
train
def parse_response(self, response, header=None): """Parses the response message. The following graph shows the structure of response messages. :: +----------+ +--+ data sep +<-+ ...
python
{ "resource": "" }
q38420
IEC60488.trigger
train
def trigger(self, transport): """Triggers the transport.""" logger.debug('IEC60488 trigger') with transport: try: transport.trigger() except AttributeError: trigger_msg = self.create_message('*TRG') transport.write(trigger_m...
python
{ "resource": "" }
q38421
IEC60488.clear
train
def clear(self, transport): """Issues a device clear command.""" logger.debug('IEC60488 clear') with transport: try: transport.clear() except AttributeError: clear_msg = self.create_message('*CLS') transport.write(clear_msg)
python
{ "resource": "" }
q38422
SignalRecovery.query_bytes
train
def query_bytes(self, transport, num_bytes, header, *data): """Queries for binary data :param transport: A transport object. :param num_bytes: The exact number of data bytes expected. :param header: The message header. :param data: Optional data. :returns: The raw unpar...
python
{ "resource": "" }
q38423
rotateAroundVector
train
def rotateAroundVector(v1, w, theta_deg): """Rotate vector v1 by an angle theta around w Taken from https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation (see Section "Rotating a vector") Notes: Rotating the x axis 90 degrees about the y axis gives -z Rotating the x axis 90 degrees a...
python
{ "resource": "" }
q38424
rotateInDeclination
train
def rotateInDeclination(v1, theta_deg): """Rotation is chosen so a rotation of 90 degrees from zenith ends up at ra=0, dec=0""" axis = np.array([0,-1,0]) return rotateAroundVector(v1, axis, theta_deg)
python
{ "resource": "" }
q38425
MPS4G.sweep
train
def sweep(self, mode, speed=None): """Starts the output current sweep. :param mode: The sweep mode. Valid entries are `'UP'`, `'DOWN'`, `'PAUSE'`or `'ZERO'`. If in shim mode, `'LIMIT'` is valid as well. :param speed: The sweeping speed. Valid entries are `'FAST'`, `'SLOW'` ...
python
{ "resource": "" }
q38426
BaseEventTransport.run_on_main_thread
train
def run_on_main_thread(self, func, args=None, kwargs=None): """ Runs the ``func`` callable on the main thread, by using the provided microservice instance's IOLoop. :param func: callable to run on the main thread :param args: tuple or list with the positional arguments. ...
python
{ "resource": "" }
q38427
rotateAboutVectorMatrix
train
def rotateAboutVectorMatrix(vec, theta_deg): """Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should...
python
{ "resource": "" }
q38428
rotateInZMat
train
def rotateInZMat(theta_deg): """Rotate a vector theta degrees around the z-axis Equivalent to yaw left Rotates the vector in the sense that the x-axis is rotated towards the y-axis. If looking along the z-axis (which is not the way you usually look at it), the vector rotates clockwise. If...
python
{ "resource": "" }
q38429
SqlDAM.getReadSession
train
def getReadSession(self): ''' return scopted session ''' if self.ReadSession is None: self.ReadSession=scoped_session(sessionmaker(bind=self.engine)) return self.ReadSession
python
{ "resource": "" }
q38430
SqlDAM.readTupleQuotes
train
def readTupleQuotes(self, symbol, start, end): ''' read quotes as tuple ''' if end is None: end=sys.maxint session=self.getReadSession()() try: rows=session.query(Quote).filter(and_(Quote.symbol == symbol, ...
python
{ "resource": "" }
q38431
SqlDAM.readBatchTupleQuotes
train
def readBatchTupleQuotes(self, symbols, start, end): ''' read batch quotes as tuple to save memory ''' if end is None: end=sys.maxint ret={} session=self.getReadSession()() try: symbolChunks=splitListEqually(symbols, 100) ...
python
{ "resource": "" }
q38432
SqlDAM.read_tuple_ticks
train
def read_tuple_ticks(self, symbol, start, end): ''' read ticks as tuple ''' if end is None: end=sys.maxint session=self.getReadSession()() try: rows=session.query(Tick).filter(and_(Tick.symbol == symbol, ...
python
{ "resource": "" }
q38433
SqlDAM._fundamentalToSqls
train
def _fundamentalToSqls(self, symbol, keyTimeValueDict): ''' convert fundament dict to sqls ''' sqls=[] for key, timeValues in keyTimeValueDict.iteritems(): for timeStamp, value in timeValues.iteritems(): sqls.append(FmSql(symbol, key, timeStamp, value)) ...
python
{ "resource": "" }
q38434
Curve.delete
train
def delete(self): """Deletes the current curve. :raises RuntimeError: Raises when` when one tries to delete a read-only curve. """ if self._writeable: self._write(('CRVDEL', Integer), self.idx) else: raise RuntimeError('Can not delete read-on...
python
{ "resource": "" }
q38435
Program.line
train
def line(self, idx): """Return the i'th program line. :param i: The i'th program line. """ # TODO: We should parse the response properly. return self._query(('PGM?', [Integer, Integer], String), self.idx, idx)
python
{ "resource": "" }
q38436
Program.append_line
train
def append_line(self, new_line): """Appends the new_line to the LS340 program.""" # TODO: The user still has to write the raw line, this is error prone. self._write(('PGM', [Integer, String]), self.idx, new_line)
python
{ "resource": "" }
q38437
LS340.softcal
train
def softcal(self, std, dest, serial, T1, U1, T2, U2, T3=None, U3=None): """Generates a softcal curve. :param std: The standard curve index used to calculate the softcal curve. Valid entries are 1-20 :param dest: The user curve index where the softcal curve is stored. Val...
python
{ "resource": "" }
q38438
VIPPersonContactType.getParameters
train
def getParameters(self, contactItem): """ Return a list containing a single parameter suitable for changing the VIP status of a person. @type contactItem: L{_PersonVIPStatus} @rtype: C{list} of L{liveform.Parameter} """ isVIP = False # default if contact...
python
{ "resource": "" }
q38439
Person.getEmailAddresses
train
def getEmailAddresses(self): """ Return an iterator of all email addresses associated with this person. @return: an iterator of unicode strings in RFC2822 address format. """ return self.store.query( EmailAddress, EmailAddress.person == self).getColumn('a...
python
{ "resource": "" }
q38440
Organizer.groupReadOnlyViews
train
def groupReadOnlyViews(self, person): """ Collect all contact items from the available contact types for the given person, organize them by contact group, and turn them into read-only views. @type person: L{Person} @param person: The person whose contact items we're inte...
python
{ "resource": "" }
q38441
PersonPluginView.getPluginWidget
train
def getPluginWidget(self, pluginName): """ Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement} """ # this will always pick the first plugin with pluginName if there is # more than...
python
{ "resource": "" }
q38442
Mugshot.makeThumbnail
train
def makeThumbnail(cls, inputFile, person, format, smaller): """ Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person...
python
{ "resource": "" }
q38443
Extension.post_build
train
def post_build(self, container_builder, container): """ Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals...
python
{ "resource": "" }
q38444
cache_key
train
def cache_key(*args, **kwargs): """ Base method for computing the cache key with respect to the given arguments. """ key = "" for arg in args: if callable(arg): key += ":%s" % repr(arg) else: key += ":%s" % str(arg) return key
python
{ "resource": "" }
q38445
decode_values
train
def decode_values(fct): ''' Decode base64 encoded responses from Consul storage ''' def inner(*args, **kwargs): ''' decorator ''' data = fct(*args, **kwargs) if 'error' not in data: for result in data: result['Value'] = base64.b64decode(result['Value']) ...
python
{ "resource": "" }
q38446
safe_request
train
def safe_request(fct): ''' Return json messages instead of raising errors ''' def inner(*args, **kwargs): ''' decorator ''' try: _data = fct(*args, **kwargs) except requests.exceptions.ConnectionError as error: return {'error': str(error), 'status': 404} ...
python
{ "resource": "" }
q38447
parseAddress
train
def parseAddress(address): """ Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address. """ parts = [] ...
python
{ "resource": "" }
q38448
MicroService.start
train
def start(self): """ The main method that starts the service. This is blocking. """ self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._star...
python
{ "resource": "" }
q38449
MicroService.get_plugin
train
def get_plugin(self, name): """ Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance. """ for plugin in...
python
{ "resource": "" }
q38450
MicroService.start_thread
train
def start_thread(self, target, args, kwargs): """ Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments....
python
{ "resource": "" }
q38451
MicroService.emit_event
train
def emit_event(self, event_name, event_body): """ Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. ...
python
{ "resource": "" }
q38452
MicroService._add_static_handlers
train
def _add_static_handlers(self, handlers): """ Creates and adds the handles needed for serving static files. :param handlers: """ for url, path in self.static_dirs: handlers.append((url.rstrip("/") + "/(.*)", StaticFileHandler, {"path": path}))
python
{ "resource": "" }
q38453
MicroService._gather_event_handlers
train
def _gather_event_handlers(self): """ Searches for the event handlers in the current microservice class. :return: """ self._extract_event_handlers_from_container(self) for module in self.modules: self._extract_event_handlers_from_container(module)
python
{ "resource": "" }
q38454
connect_if_correct_version
train
def connect_if_correct_version(db_path, version): """Return a sqlite3 database connection if the version in the database's metadata matches the version argument. Also implicitly checks for whether the data in this database has been completely filled, since we set the version last. TODO: Make an ex...
python
{ "resource": "" }
q38455
_create_cached_db
train
def _create_cached_db( db_path, tables, version=1): """ Either create or retrieve sqlite database. Parameters -------- db_path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache.DatabaseTable objects versio...
python
{ "resource": "" }
q38456
db_from_dataframe
train
def db_from_dataframe( db_filename, table_name, df, primary_key=None, subdir=None, overwrite=False, indices=(), version=1): """ Given a dataframe `df`, turn it into a sqlite3 database. Store values in a table called `table_name`. Returns f...
python
{ "resource": "" }
q38457
_db_filename_from_dataframe
train
def _db_filename_from_dataframe(base_filename, df): """ Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types. """ db_filename = base_filename + ("_nrows%d" % len(df)) for column_name in df.columns...
python
{ "resource": "" }
q38458
fetch_csv_db
train
def fetch_csv_db( table_name, download_url, csv_filename=None, db_filename=None, subdir=None, version=1, **pandas_kwargs): """ Download a remote CSV file and create a local sqlite3 database from its contents """ df = fetch_csv_dataframe( ...
python
{ "resource": "" }
q38459
GoogleFinance.get_all
train
def get_all(self, security): """ Get all available quote data for the given ticker security. Returns a dictionary. """ url = 'http://www.google.com/finance?q=%s' % security page = self._request(url) soup = BeautifulSoup(page) snapData = soup.find...
python
{ "resource": "" }
q38460
GoogleFinance.quotes
train
def quotes(self, security, start, end): """ Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list. """ try: url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (secu...
python
{ "resource": "" }
q38461
GoogleFinance._parseTarget
train
def _parseTarget(self, target, keyTimeValue): ''' parse table for get financial ''' table = target.table timestamps = self._getTimeStamps(table) for tr in table.tbody.findChildren('tr'): for i, td in enumerate(tr.findChildren('td')): if 0 == i: ...
python
{ "resource": "" }
q38462
GoogleFinance._getTimeStamps
train
def _getTimeStamps(self, table): ''' get time stamps ''' timeStamps = [] for th in table.thead.tr.contents: if '\n' != th: timeStamps.append(th.getText()) return timeStamps[1:]
python
{ "resource": "" }
q38463
GoogleFinance.ticks
train
def ticks(self, security, start, end): """ Get tick prices for the given ticker security. @security: stock security @interval: interval in mins(google finance only support query till 1 min) @start: start date(YYYYMMDD) @end: end date(YYYYMMDD) start and e...
python
{ "resource": "" }
q38464
GraphOperations.get_binding
train
def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF terms matching that schema. """ schema = self.parent.get_schema(schema) return Binding(schema, self.parent.resolver, data=data)
python
{ "resource": "" }
q38465
GraphOperations.get
train
def get(self, id, depth=3, schema=None): """ Construct a single object based on its ID. """ uri = URIRef(id) if schema is None: for o in self.graph.objects(subject=uri, predicate=RDF.type): schema = self.parent.get_schema(str(o)) if schema is not None:...
python
{ "resource": "" }
q38466
BaseOAIRELoader.get_text_node
train
def get_text_node(self, tree, xpath_str): """Return a text node from given XML tree given an lxml XPath.""" try: text = tree.xpath(xpath_str, namespaces=self.namespaces)[0].text return text_type(text) if text else '' except IndexError: # pragma: nocover retur...
python
{ "resource": "" }
q38467
BaseOAIRELoader.get_subtree
train
def get_subtree(self, tree, xpath_str): """Return a subtree given an lxml XPath.""" return tree.xpath(xpath_str, namespaces=self.namespaces)
python
{ "resource": "" }
q38468
BaseOAIRELoader.fundertree2json
train
def fundertree2json(self, tree, oai_id): """Convert OpenAIRE's funder XML to JSON.""" try: tree = self.get_subtree(tree, 'fundingtree')[0] except IndexError: # pragma: nocover pass funder_node = self.get_subtree(tree, 'funder') subfunder_node = self.get_...
python
{ "resource": "" }
q38469
BaseOAIRELoader.grantxml2json
train
def grantxml2json(self, grant_xml): """Convert OpenAIRE grant XML into JSON.""" tree = etree.fromstring(grant_xml) # XML harvested from OAI-PMH has a different format/structure if tree.prefix == 'oai': ptree = self.get_subtree( tree, '/oai:record/oai:metadata/...
python
{ "resource": "" }
q38470
LocalOAIRELoader.iter_grants
train
def iter_grants(self, as_json=True): """Fetch records from the SQLite database.""" self._connect() result = self.db_connection.cursor().execute( "SELECT data, format FROM grants" ) for data, data_format in result: if (not as_json) and data_format == 'json'...
python
{ "resource": "" }
q38471
RemoteOAIRELoader.iter_grants
train
def iter_grants(self, as_json=True): """Fetch grants from a remote OAI-PMH endpoint. Return the Sickle-provided generator object. """ records = self.client.ListRecords(metadataPrefix='oaf', set=self.setspec) for rec in records: ...
python
{ "resource": "" }
q38472
OAIREDumper.dump
train
def dump(self, as_json=True, commit_batch_size=100): """ Dump the grant information to a local storage. :param as_json: Convert XML to JSON before saving (default: True). """ connection = sqlite3.connect(self.destination) format_ = 'json' if as_json else 'xml' if...
python
{ "resource": "" }
q38473
BaseFundRefLoader.iter_funders
train
def iter_funders(self): """Get a converted list of Funders as JSON dict.""" root = self.doc_root funders = root.findall('./skos:Concept', namespaces=self.namespaces) for funder in funders: funder_json = self.fundrefxml2json(funder) yield funder_json
python
{ "resource": "" }
q38474
FundRefDOIResolver.resolve_by_oai_id
train
def resolve_by_oai_id(self, oai_id): """Resolve the funder from the OpenAIRE OAI record id. Hack for when funder is not provided in OpenAIRE. """ if oai_id.startswith('oai:dnet:'): oai_id = oai_id[len('oai:dnet:'):] prefix = oai_id.split("::")[0] suffix = pre...
python
{ "resource": "" }
q38475
predicates
train
def predicates(graph): """ Return a listing of all known predicates in the registered schemata, including the schema path they associate with, their name and allowed types. """ seen = set() def _traverse(binding): if binding.path in seen: return seen.add(binding.path) ...
python
{ "resource": "" }
q38476
passwordReset1to2
train
def passwordReset1to2(old): """ Power down and delete the item """ new = old.upgradeVersion(old.typeName, 1, 2, installedOn=None) for iface in new.store.interfacesFor(new): new.store.powerDown(new, iface) new.deleteFromStore()
python
{ "resource": "" }
q38477
ticket1to2
train
def ticket1to2(old): """ change Ticket to refer to Products and not benefactor factories. """ if isinstance(old.benefactor, Multifactor): types = list(chain(*[b.powerupNames for b in old.benefactor.benefactors('ascending')])) elif isinstance(old.benefactor, InitializerBenefac...
python
{ "resource": "" }
q38478
_getPublicSignupInfo
train
def _getPublicSignupInfo(siteStore): """ Get information about public web-based signup mechanisms. @param siteStore: a store with some signups installed on it (as indicated by _SignupTracker instances). @return: a generator which yields 2-tuples of (prompt, url) where 'prompt' is unicode brief...
python
{ "resource": "" }
q38479
PasswordResetResource.renderHTTP
train
def renderHTTP(self, ctx): """ Handle the password reset form. The following exchange describes the process: S: Render C{reset} C: POST C{username} or C{email} S: L{handleRequestForUser}, render C{reset-check-email} (User follows the emailed res...
python
{ "resource": "" }
q38480
PasswordResetResource._makeKey
train
def _makeKey(self, usern): """ Make a new, probably unique key. This key will be sent in an email to the user and is used to access the password change form. """ return unicode(hashlib.md5(str((usern, time.time(), random.random()))).hexdigest())
python
{ "resource": "" }
q38481
TicketBooth.issueViaEmail
train
def issueViaEmail(self, issuer, email, product, templateData, domainName, httpPort=80): """ Send a ticket via email to the supplied address, which, when claimed, will create an avatar and allow the given product to endow it with things. @param issuer: An ob...
python
{ "resource": "" }
q38482
UserInfoSignup.usernameAvailable
train
def usernameAvailable(self, username, domain): """ Check to see if a username is available for the user to select. """ if len(username) < 2: return [False, u"Username too short"] for char in u"[ ,:;<>@()!\"'%&\\|\t\b": if char in username: ...
python
{ "resource": "" }
q38483
SignupConfiguration.createSignup
train
def createSignup(self, creator, signupClass, signupConf, product, emailTemplate, prompt): """ Create a new signup facility in the site store's database. @param creator: a unicode string describing the creator of the new signup mechanism, for auditing purposes. ...
python
{ "resource": "" }
q38484
ProductFormMixin.makeProductPicker
train
def makeProductPicker(self): """ Make a LiveForm with radio buttons for each Product in the store. """ productPicker = liveform.LiveForm( self.coerceProduct, [liveform.Parameter( str(id(product)), liveform.FORM_INPUT, live...
python
{ "resource": "" }
q38485
SignupFragment._deleteTrackers
train
def _deleteTrackers(self, trackers): """ Delete the given signup trackers and their associated signup resources. @param trackers: sequence of L{_SignupTrackers} """ for tracker in trackers: if tracker.store is None: # we're not updating the list of l...
python
{ "resource": "" }
q38486
Image.fetch
train
def fetch(self): """ Fetch & return a new `Image` object representing the image's current state :rtype: Image :raises DOAPIError: if the API endpoint replies with an error (e.g., if the image no longer exists) """ api = self.doapi_manager retu...
python
{ "resource": "" }
q38487
Censusname.generate
train
def generate(self, nameformat=None, capitalize=None, formatters=None, **kwargs): '''Pick a random name form a specified list of name parts''' nameformat = nameformat or self.nameformat capitalize = capitalize or self.capitalize formatters = formatters or {} lines = self._get_li...
python
{ "resource": "" }
q38488
Censusname.pick_frequency_line
train
def pick_frequency_line(self, filename, frequency, cumulativefield='cumulative_frequency'): '''Given a numeric frequency, pick a line from a csv with a cumulative frequency field''' if resource_exists('censusname', filename): with closing(resource_stream('censusname', filename)) as b: ...
python
{ "resource": "" }
q38489
git_repo
train
def git_repo(): """ Returns the git repository root if the cwd is in a repo, else None """ try: reldir = subprocess.check_output( ["git", "rev-parse", "--git-dir"]) reldir = reldir.decode("utf-8") return os.path.basename(os.path.dirname(os.path.abspath(reldir))) e...
python
{ "resource": "" }
q38490
git_hash
train
def git_hash(): """returns the current git hash or unknown if not in git repo""" if git_repo() is None: return "unknown" git_hash = subprocess.check_output( ["git", "rev-parse", "HEAD"]) # git_hash is a byte string; we want a string. git_hash = git_hash.decode("utf-8") # git_hash...
python
{ "resource": "" }
q38491
git_pretty
train
def git_pretty(): """returns a pretty summary of the commit or unkown if not in git repo""" if git_repo() is None: return "unknown" pretty = subprocess.check_output( ["git", "log", "--pretty=format:%h %s", "-n", "1"]) pretty = pretty.decode("utf-8") pretty = pretty.strip() return...
python
{ "resource": "" }
q38492
invocation
train
def invocation(): """reconstructs the invocation for this python program""" cmdargs = [sys.executable] + sys.argv[:] invocation = " ".join(shlex.quote(s) for s in cmdargs) return invocation
python
{ "resource": "" }
q38493
serialize
train
def serialize(func): """ Falcon response serialization """ def wrapped(instance, req, resp, **kwargs): assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed" resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate"); r...
python
{ "resource": "" }
q38494
ExcelWrite.openSheet
train
def openSheet(self, name): ''' set a sheet to write ''' if name not in self.__sheetNameDict: sheet = self.__workbook.add_sheet(name) self.__sheetNameDict[name] = sheet self.__sheet = self.__sheetNameDict[name]
python
{ "resource": "" }
q38495
ExcelWrite.__getSheet
train
def __getSheet(self, name): ''' get a sheet by name ''' if not self.sheetExsit(name): raise UfException(Errors.SHEET_NAME_INVALID, "Can't find a sheet named %s" % name) return self.__sheetNameDict[name]
python
{ "resource": "" }
q38496
ExcelWrite.writeCell
train
def writeCell(self, row, col, value): ''' write a cell ''' if self.__sheet is None: self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET) self.__sheet.write(row, col, value)
python
{ "resource": "" }
q38497
ExcelWrite.writeRow
train
def writeRow(self, row, values): ''' write a row Not sure whether xlwt support write the same cell multiple times ''' if self.__sheet is None: self.openSheet(super(ExcelWrite, self).DEFAULT_SHEET) for index, value in enumerate(values): se...
python
{ "resource": "" }
q38498
ExcelRead.readCell
train
def readCell(self, row, col): ''' read a cell''' try: if self.__sheet is None: self.openSheet(super(ExcelRead, self).DEFAULT_SHEET) return self.__sheet.cell(row, col).value except BaseException as excp: raise UfException(Errors.UNKNOWN...
python
{ "resource": "" }
q38499
Cache.delete_url
train
def delete_url(self, url): """ Delete local files downloaded from given URL """ # file may exist locally in compressed and decompressed states # delete both for decompress in [False, True]: key = (url, decompress) if key in self._local_paths: ...
python
{ "resource": "" }