Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def getSkeletalSummaryData(self, action):
fn = self.function_table.getSkeletalSummaryData
pSkeletalSummaryData = VRSkeletalSummaryData_t()
result = fn(action, byref(pSkeletalSummaryData))
return result, pSkeletalSummaryData | [
"Reads summary information about the current pose of the skeleton associated with the given action."
] |
Please provide a description of the function:def getSkeletalBoneDataCompressed(self, action, eMotionRange, pvCompressedData, unCompressedSize):
fn = self.function_table.getSkeletalBoneDataCompressed
punRequiredCompressedSize = c_uint32()
result = fn(action, eMotionRange, pvCompressedDa... | [
"\n Reads the state of the skeletal bone data in a compressed form that is suitable for\n sending over the network. The required buffer size will never exceed ( sizeof(VR_BoneTransform_t)*boneCount + 2).\n Usually the size will be much smaller.\n "
] |
Please provide a description of the function:def decompressSkeletalBoneData(self, pvCompressedBuffer, unCompressedBufferSize, eTransformSpace, unTransformArrayCount):
fn = self.function_table.decompressSkeletalBoneData
pTransformArray = VRBoneTransform_t()
result = fn(pvCompressedBuffe... | [
"Turns a compressed buffer from GetSkeletalBoneDataCompressed and turns it back into a bone transform array."
] |
Please provide a description of the function:def triggerHapticVibrationAction(self, action, fStartSecondsFromNow, fDurationSeconds, fFrequency, fAmplitude, ulRestrictToDevice):
fn = self.function_table.triggerHapticVibrationAction
result = fn(action, fStartSecondsFromNow, fDurationSeconds, fFr... | [
"Triggers a haptic event as described by the specified action"
] |
Please provide a description of the function:def getActionOrigins(self, actionSetHandle, digitalActionHandle, originOutCount):
fn = self.function_table.getActionOrigins
originsOut = VRInputValueHandle_t()
result = fn(actionSetHandle, digitalActionHandle, byref(originsOut), originOutCou... | [
"Retrieve origin handles for an action"
] |
Please provide a description of the function:def getOriginLocalizedName(self, origin, pchNameArray, unNameArraySize, unStringSectionsToInclude):
fn = self.function_table.getOriginLocalizedName
result = fn(origin, pchNameArray, unNameArraySize, unStringSectionsToInclude)
return result | [
"\n Retrieves the name of the origin in the current language. unStringSectionsToInclude is a bitfield of values in EVRInputStringBits that allows the \n application to specify which parts of the origin's information it wants a string for.\n "
] |
Please provide a description of the function:def getOriginTrackedDeviceInfo(self, origin, unOriginInfoSize):
fn = self.function_table.getOriginTrackedDeviceInfo
pOriginInfo = InputOriginInfo_t()
result = fn(origin, byref(pOriginInfo), unOriginInfoSize)
return result, pOriginInf... | [
"Retrieves useful information for the origin of this action"
] |
Please provide a description of the function:def showActionOrigins(self, actionSetHandle, ulActionHandle):
fn = self.function_table.showActionOrigins
result = fn(actionSetHandle, ulActionHandle)
return result | [
"Shows the current binding for the action in-headset"
] |
Please provide a description of the function:def showBindingsForActionSet(self, unSizeOfVRSelectedActionSet_t, unSetCount, originToHighlight):
fn = self.function_table.showBindingsForActionSet
pSets = VRActiveActionSet_t()
result = fn(byref(pSets), unSizeOfVRSelectedActionSet_t, unSetC... | [
"Shows the current binding all the actions in the specified action sets"
] |
Please provide a description of the function:def open(self, pchPath, mode, unElementSize, unElements):
fn = self.function_table.open
pulBuffer = IOBufferHandle_t()
result = fn(pchPath, mode, unElementSize, unElements, byref(pulBuffer))
return result, pulBuffer | [
"opens an existing or creates a new IOBuffer of unSize bytes"
] |
Please provide a description of the function:def close(self, ulBuffer):
fn = self.function_table.close
result = fn(ulBuffer)
return result | [
"closes a previously opened or created buffer"
] |
Please provide a description of the function:def read(self, ulBuffer, pDst, unBytes):
fn = self.function_table.read
punRead = c_uint32()
result = fn(ulBuffer, pDst, unBytes, byref(punRead))
return result, punRead.value | [
"reads up to unBytes from buffer into *pDst, returning number of bytes read in *punRead"
] |
Please provide a description of the function:def write(self, ulBuffer, pSrc, unBytes):
fn = self.function_table.write
result = fn(ulBuffer, pSrc, unBytes)
return result | [
"writes unBytes of data from *pSrc into a buffer."
] |
Please provide a description of the function:def propertyContainer(self, ulBuffer):
fn = self.function_table.propertyContainer
result = fn(ulBuffer)
return result | [
"retrieves the property container of an buffer."
] |
Please provide a description of the function:def hasReaders(self, ulBuffer):
fn = self.function_table.hasReaders
result = fn(ulBuffer)
return result | [
"inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes."
] |
Please provide a description of the function:def createSpatialAnchorFromDescriptor(self, pchDescriptor):
fn = self.function_table.createSpatialAnchorFromDescriptor
pHandleOut = SpatialAnchorHandle_t()
result = fn(pchDescriptor, byref(pHandleOut))
return result, pHandleOut | [
"\n Returns a handle for an spatial anchor described by \"descriptor\". On success, pHandle\n will contain a handle valid for this session. Caller can wait for an event or occasionally\n poll GetSpatialAnchorPose() to find the virtual coordinate associated with this anchor.\n "
] |
Please provide a description of the function:def createSpatialAnchorFromPose(self, unDeviceIndex, eOrigin):
fn = self.function_table.createSpatialAnchorFromPose
pPose = SpatialAnchorPose_t()
pHandleOut = SpatialAnchorHandle_t()
result = fn(unDeviceIndex, eOrigin, byref(pPose), ... | [
"\n Returns a handle for an new spatial anchor at pPose. On success, pHandle\n will contain a handle valid for this session. Caller can wait for an event or occasionally\n poll GetSpatialAnchorDescriptor() to find the permanent descriptor for this pose.\n The result of GetSpatialAnchor... |
Please provide a description of the function:def getSpatialAnchorPose(self, unHandle, eOrigin):
fn = self.function_table.getSpatialAnchorPose
pPoseOut = SpatialAnchorPose_t()
result = fn(unHandle, eOrigin, byref(pPoseOut))
return result, pPoseOut | [
"\n Get the pose for a given handle. This is intended to be cheap enough to call every frame (or fairly often)\n so that the driver can refine this position when it has more information available.\n "
] |
Please provide a description of the function:def getSpatialAnchorDescriptor(self, unHandle, pchDescriptorOut):
fn = self.function_table.getSpatialAnchorDescriptor
punDescriptorBufferLenInOut = c_uint32()
result = fn(unHandle, pchDescriptorOut, byref(punDescriptorBufferLenInOut))
... | [
"\n Get the descriptor for a given handle. This will be empty for handles where the driver has not\n yet built a descriptor. It will be the application-supplied descriptor for previously saved anchors\n that the application is requesting poses for. If the driver has called UpdateSpatialAncho... |
Please provide a description of the function:def render_scene(self):
"render scene one time"
self.canvas.SetCurrent ( self.context )
self.renderer.render_scene()
# Done rendering
# self.canvas.SwapBuffers()
if self.canvas.IsDoubleBuffered():
self.canvas.SwapBuffers()
print ("double buffered") ... | [] |
Please provide a description of the function:async def close(self):
if self._conn is None:
return
await self._run_operation(self._impl.close)
self._conn = None | [
"Close the cursor now (rather than whenever __del__ is called).\n\n The cursor will be unusable from this point forward; an Error\n (or subclass) exception will be raised if any operation is attempted\n with the cursor.\n "
] |
Please provide a description of the function:async def execute(self, sql, *params):
if self._echo:
logger.info(sql)
logger.info("%r", sql)
await self._run_operation(self._impl.execute, sql, *params)
return self | [
"Executes the given operation substituting any markers with\n the given parameters.\n\n :param sql: the SQL statement to execute with optional ? parameter\n markers. Note that pyodbc never modifies the SQL statement.\n :param params: optional parameters for the markers in the SQL. Th... |
Please provide a description of the function:def executemany(self, sql, *params):
fut = self._run_operation(self._impl.executemany, sql, *params)
return fut | [
"Prepare a database query or command and then execute it against\n all parameter sequences found in the sequence seq_of_params.\n\n :param sql: the SQL statement to execute with optional ? parameters\n :param params: sequence parameters for the markers in the SQL.\n "
] |
Please provide a description of the function:def fetchmany(self, size):
fut = self._run_operation(self._impl.fetchmany, size)
return fut | [
"Returns a list of remaining rows, containing no more than size\n rows, used to process results in chunks. The list will be empty when\n there are no more rows.\n\n The default for cursor.arraysize is 1 which is no different than\n calling fetchone().\n\n A ProgrammingError except... |
Please provide a description of the function:def tables(self, **kw):
fut = self._run_operation(self._impl.tables, **kw)
return fut | [
"Creates a result set of tables in the database that match the\n given criteria.\n\n :param table: the table tname\n :param catalog: the catalog name\n :param schema: the schmea name\n :param tableType: one of TABLE, VIEW, SYSTEM TABLE ...\n "
] |
Please provide a description of the function:def columns(self, **kw):
fut = self._run_operation(self._impl.columns, **kw)
return fut | [
"Creates a results set of column names in specified tables by\n executing the ODBC SQLColumns function. Each row fetched has the\n following columns.\n\n :param table: the table tname\n :param catalog: the catalog name\n :param schema: the schmea name\n :param column: strin... |
Please provide a description of the function:def statistics(self, catalog=None, schema=None, unique=False, quick=True):
fut = self._run_operation(self._impl.statistics, catalog=catalog,
schema=schema, unique=unique, quick=quick)
return fut | [
"Creates a results set of statistics about a single table and\n the indexes associated with the table by executing SQLStatistics.\n\n :param catalog: the catalog name\n :param schema: the schmea name\n :param unique: if True, only unique indexes are retured. Otherwise\n all in... |
Please provide a description of the function:def rowIdColumns(self, table, catalog=None, schema=None, # nopep8
nullable=True):
fut = self._run_operation(self._impl.rowIdColumns, table,
catalog=catalog, schema=schema,
... | [
"Executes SQLSpecialColumns with SQL_BEST_ROWID which creates a\n result set of columns that uniquely identify a row\n "
] |
Please provide a description of the function:def primaryKeys(self, table, catalog=None, schema=None): # nopep8
fut = self._run_operation(self._impl.primaryKeys, table,
catalog=catalog, schema=schema)
return fut | [
"Creates a result set of column names that make up the primary key\n for a table by executing the SQLPrimaryKeys function."
] |
Please provide a description of the function:def foreignKeys(self, *a, **kw): # nopep8
fut = self._run_operation(self._impl.foreignKeys, *a, **kw)
return fut | [
"Executes the SQLForeignKeys function and creates a result set\n of column names that are foreign keys in the specified table (columns\n in the specified table that refer to primary keys in other tables)\n or foreign keys in other tables that refer to the primary key in\n the specified t... |
Please provide a description of the function:def getTypeInfo(self, sql_type): # nopep8
fut = self._run_operation(self._impl.getTypeInfo, sql_type)
return fut | [
"Executes SQLGetTypeInfo a creates a result set with information\n about the specified data type or all data types supported by the\n ODBC driver if not specified.\n "
] |
Please provide a description of the function:def procedures(self, *a, **kw):
fut = self._run_operation(self._impl.procedures, *a, **kw)
return fut | [
"Executes SQLProcedures and creates a result set of information\n about the procedures in the data source.\n "
] |
Please provide a description of the function:async def dataSources(loop=None, executor=None):
loop = loop or asyncio.get_event_loop()
sources = await loop.run_in_executor(executor, _dataSources)
return sources | [
"Returns a dictionary mapping available DSNs to their descriptions.\n\n :param loop: asyncio compatible event loop\n :param executor: instance of custom ThreadPoolExecutor, if not supplied\n default executor will be used\n :return dict: mapping of dsn to driver description\n "
] |
Please provide a description of the function:async def clear(self):
with (await self._cond):
while self._free:
conn = self._free.popleft()
await conn.close()
self._cond.notify() | [
"Close all free connections in pool."
] |
Please provide a description of the function:async def release(self, conn):
assert conn in self._used, (conn, self._used)
self._used.remove(conn)
if not conn.closed:
if self._closing:
await conn.close()
else:
self._free.append(conn... | [
"Release free connection back to the connection pool.\n "
] |
Please provide a description of the function:def connect(*, dsn, autocommit=False, ansi=False, timeout=0, loop=None,
executor=None, echo=False, after_created=None, **kwargs):
return _ContextManager(_connect(dsn=dsn, autocommit=autocommit,
ansi=ansi, timeout=timeout, loop=... | [
"Accepts an ODBC connection string and returns a new Connection object.\n\n The connection string can be passed as the string `str`, as a list of\n keywords,or a combination of the two. Any keywords except autocommit,\n ansi, and timeout are simply added to the connection string.\n\n :param autocommit ... |
Please provide a description of the function:async def close(self):
if not self._conn:
return
c = await self._execute(self._conn.close)
self._conn = None
return c | [
"Close pyodbc connection"
] |
Please provide a description of the function:async def execute(self, sql, *args):
_cursor = await self._execute(self._conn.execute, sql, *args)
connection = self
cursor = Cursor(_cursor, connection, echo=self._echo)
return cursor | [
"Create a new Cursor object, call its execute method, and return it.\n\n See Cursor.execute for more details.This is a convenience method\n that is not part of the DB API. Since a new Cursor is allocated\n by each call, this should not be used if more than one SQL\n statement needs to b... |
Please provide a description of the function:def getinfo(self, type_):
fut = self._execute(self._conn.getinfo, type_)
return fut | [
"Returns general information about the driver and data source\n associated with a connection by calling SQLGetInfo and returning its\n results. See Microsoft's SQLGetInfo documentation for the types of\n information available.\n\n :param type_: int, pyodbc.SQL_* constant\n "
] |
Please provide a description of the function:def add_output_converter(self, sqltype, func):
fut = self._execute(self._conn.add_output_converter, sqltype, func)
return fut | [
"Register an output converter function that will be called whenever\n a value with the given SQL type is read from the database.\n\n :param sqltype: the integer SQL type value to convert, which can\n be one of the defined standard constants (pyodbc.SQL_VARCHAR)\n or a database-sp... |
Please provide a description of the function:def set_attr(self, attr_id, value):
fut = self._execute(self._conn.set_attr, attr_id, value)
return fut | [
"Calls SQLSetConnectAttr with the given values.\n\n :param attr_id: the attribute ID (integer) to set. These are ODBC or\n driver constants.\n :parm value: the connection attribute value to set. At this time\n only integer values are supported.\n "
] |
Please provide a description of the function:def _request_get(self, path, params=None, json=True, url=BASE_URL):
url = urljoin(url, path)
headers = self._get_request_headers()
response = requests.get(url, params=params, headers=headers)
if response.status_code >= 500:
... | [
"Perform a HTTP GET request."
] |
Please provide a description of the function:def _request_post(self, path, data=None, params=None, url=BASE_URL):
url = urljoin(url, path)
headers = self._get_request_headers()
response = requests.post(
url, json=data, params=params, headers=headers,
timeout=DE... | [
"Perform a HTTP POST request.."
] |
Please provide a description of the function:def _request_delete(self, path, params=None, url=BASE_URL):
url = urljoin(url, path)
headers = self._get_request_headers()
response = requests.delete(
url, params=params, headers=headers, timeout=DEFAULT_TIMEOUT)
respons... | [
"Perform a HTTP DELETE request."
] |
Please provide a description of the function:def download_vod(self, video_id):
vod_id = video_id[1:]
token = self._request_get(
'vods/{}/access_token'.format(vod_id), url='https://api.twitch.tv/api/')
params = {
'nauthsig': token['sig'],
'nauth': toke... | [
"\n This will return a byte string of the M3U8 playlist data\n (which contains more links to segments of the vod)\n "
] |
Please provide a description of the function:def parse(cls, signed_request, application_secret_key):
def decode(encoded):
padding = '=' * (len(encoded) % 4)
return base64.urlsafe_b64decode(encoded + padding)
try:
encoded_signature, encoded_payload = (str(str... | [
"Parse a signed request, returning a dictionary describing its payload."
] |
Please provide a description of the function:def generate(self):
payload = {
'algorithm': 'HMAC-SHA256'
}
if self.data:
payload['app_data'] = self.data
if self.page:
payload['page'] = {}
if self.page.id:
payload[... | [
"Generate a signed request from this instance."
] |
Please provide a description of the function:def for_application(self, id, secret_key, api_version=None):
from facepy.utils import get_application_access_token
access_token = get_application_access_token(id, secret_key, api_version=api_version)
return GraphAPI(access_token, version=api... | [
"\n Initialize GraphAPI with an OAuth access token for an application.\n\n :param id: An integer describing a Facebook application.\n :param secret_key: A String describing the Facebook application's secret key.\n "
] |
Please provide a description of the function:def get(self, path='', page=False, retry=3, **options):
response = self._query(
method='GET',
path=path,
data=options,
page=page,
retry=retry
)
if response is False:
rai... | [
"\n Get an item from the Graph API.\n\n :param path: A string describing the path to the item.\n :param page: A boolean describing whether to return a generator that\n iterates over each page of results.\n :param retry: An integer describing how many times the request... |
Please provide a description of the function:def post(self, path='', retry=0, **data):
response = self._query(
method='POST',
path=path,
data=data,
retry=retry
)
if response is False:
raise FacebookError('Could not post to "%s... | [
"\n Post an item to the Graph API.\n\n :param path: A string describing the path to the item.\n :param retry: An integer describing how many times the request may be retried.\n :param data: Graph API parameters such as 'message' or 'source'.\n\n See `Facebook's Graph API documenta... |
Please provide a description of the function:def search(self, term, type='place', page=False, retry=3, **options):
if type != 'place':
raise ValueError('Unsupported type "%s". The only supported type is "place" since Graph API 2.0.' % type)
options = dict({
'q': term,
... | [
"\n Search for an item in the Graph API.\n\n :param term: A string describing the search term.\n :param type: A string describing the type of items to search for.\n :param page: A boolean describing whether to return a generator that\n iterates over each page of resul... |
Please provide a description of the function:def batch(self, requests):
for request in requests:
if 'body' in request:
request['body'] = urlencode(request['body'])
def _grouper(complete_list, n=1):
for i in range(0, len(complete_list), n):... | [
"\n Make a batch request.\n\n :param requests: A list of dictionaries with keys 'method', 'relative_url' and optionally 'body'.\n\n Yields a list of responses and/or exceptions.\n ",
"\n Batches a list into constant size chunks.\n\n :param complete_list: A input l... |
Please provide a description of the function:def _query(self, method, path, data=None, page=False, retry=0):
if(data):
data = dict(
(k.replace('_sqbro_', '['), v) for k, v in data.items())
data = dict(
(k.replace('_sqbrc_', ']'), v) for k, v in d... | [
"\n Fetch an object from the Graph API and parse the output, returning a tuple where the first item\n is the object yielded by the Graph API and the second is the URL for the next page of results, or\n ``None`` if results have been exhausted.\n\n :param method: A string describing the HT... |
Please provide a description of the function:def _parse(self, data):
if type(data) == type(bytes()):
try:
data = data.decode('utf-8')
except UnicodeDecodeError:
return data
try:
data = json.loads(data, parse_float=Decimal)
... | [
"\n Parse the response from Facebook's Graph API.\n\n :param data: A string describing the Graph API's response.\n "
] |
Please provide a description of the function:def _generate_appsecret_proof(self):
if six.PY2:
key = self.appsecret
message = self.oauth_token
else:
key = bytes(self.appsecret, 'utf-8')
message = bytes(self.oauth_token, 'utf-8')
return hma... | [
"\n Returns a SHA256 of the oauth_token signed by appsecret.\n https://developers.facebook.com/docs/graph-api/securing-requests/\n "
] |
Please provide a description of the function:def get_extended_access_token(access_token, application_id, application_secret_key, api_version=None):
graph = GraphAPI(version=api_version)
response = graph.get(
path='oauth/access_token',
client_id=application_id,
client_secret=applica... | [
"\n Get an extended OAuth access token.\n\n :param access_token: A string describing an OAuth access token.\n :param application_id: An integer describing the Facebook application's ID.\n :param application_secret_key: A string describing the Facebook application's secret key.\n\n Returns a tuple wit... |
Please provide a description of the function:def get_application_access_token(application_id, application_secret_key, api_version=None):
graph = GraphAPI(version=api_version)
response = graph.get(
path='oauth/access_token',
client_id=application_id,
client_secret=application_secret... | [
"\n Get an OAuth access token for the given application.\n\n :param application_id: An integer describing a Facebook application's ID.\n :param application_secret_key: A string describing a Facebook application's secret key.\n "
] |
Please provide a description of the function:def locked_get_or_set(self, key, value_creator, version=None,
expire=None, id=None, lock_key=None,
timeout=DEFAULT_TIMEOUT):
if lock_key is None:
lock_key = 'get_or_set:' + key
val = se... | [
"\n Fetch a given key from the cache. If the key does not exist, the key is added and\n set to the value returned when calling `value_creator`. The creator function\n is invoked inside of a lock.\n "
] |
Please provide a description of the function:def _eval_script(redis, script_id, *keys, **kwargs):
args = kwargs.pop('args', ())
if kwargs:
raise TypeError("Unexpected keyword arguments %s" % kwargs.keys())
try:
return redis.evalsha(SCRIPTS[script_id], len(keys), *keys + args)
except... | [
"Tries to call ``EVALSHA`` with the `hash` and then, if it fails, calls\n regular ``EVAL`` with the `script`.\n "
] |
Please provide a description of the function:def reset(self):
_eval_script(self._client, RESET, self._name, self._signal)
self._delete_signal() | [
"\n Forcibly deletes the lock. Use this with care.\n "
] |
Please provide a description of the function:def acquire(self, blocking=True, timeout=None):
logger.debug("Getting %r ...", self._name)
if self._held:
raise AlreadyAcquired("Already acquired from this Lock instance.")
if not blocking and timeout is not None:
ra... | [
"\n :param blocking:\n Boolean value specifying whether lock should be blocking or not.\n :param timeout:\n An integer value specifying the maximum number of seconds to block.\n "
] |
Please provide a description of the function:def extend(self, expire=None):
if expire is None:
if self._expire is not None:
expire = self._expire
else:
raise TypeError(
"To extend a lock 'expire' must be provided as an "
... | [
"Extends expiration time of the lock.\n\n :param expire:\n New expiration time. If ``None`` - `expire` provided during\n lock initialization will be taken.\n "
] |
Please provide a description of the function:def _lock_renewer(lockref, interval, stop):
log = getLogger("%s.lock_refresher" % __name__)
while not stop.wait(timeout=interval):
log.debug("Refreshing lock")
lock = lockref()
if lock is None:
log.... | [
"\n Renew the lock key in redis every `interval` seconds for as long\n as `self._lock_renewal_thread.should_exit` is False.\n "
] |
Please provide a description of the function:def _start_lock_renewer(self):
if self._lock_renewal_thread is not None:
raise AlreadyStarted("Lock refresh thread already started")
logger.debug(
"Starting thread to refresh lock every %s seconds",
self._lock_ren... | [
"\n Starts the lock refresher thread.\n "
] |
Please provide a description of the function:def _stop_lock_renewer(self):
if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive():
return
logger.debug("Signalling the lock refresher to stop")
self._lock_renewal_stop.set()
self._lock_renewal_... | [
"\n Stop the lock renewer.\n\n This signals the renewal thread and waits for its exit.\n "
] |
Please provide a description of the function:def release(self):
if self._lock_renewal_thread is not None:
self._stop_lock_renewer()
logger.debug("Releasing %r.", self._name)
error = _eval_script(self._client, UNLOCK, self._name, self._signal, args=(self._id,))
if err... | [
"Releases the lock, that was acquired with the same object.\n\n .. note::\n\n If you want to release a lock that you acquired in a different place you have two choices:\n\n * Use ``Lock(\"name\", id=id_from_other_place).release()``\n * Use ``Lock(\"name\").reset()``\n ... |
Please provide a description of the function:def bunchify(x):
if isinstance(x, dict):
return Bunch( (k, bunchify(v)) for k,v in iteritems(x) )
elif isinstance(x, (list, tuple)):
return type(x)( bunchify(v) for v in x )
else:
return x | [
" Recursively transforms a dictionary into a Bunch via copy.\n \n >>> b = bunchify({'urmom': {'sez': {'what': 'what'}}})\n >>> b.urmom.sez.what\n 'what'\n \n bunchify can handle intermediary dicts, lists and tuples (as well as \n their subclasses), but ymmv on custom... |
Please provide a description of the function:def unbunchify(x):
if isinstance(x, dict):
return dict( (k, unbunchify(v)) for k,v in iteritems(x) )
elif isinstance(x, (list, tuple)):
return type(x)( unbunchify(v) for v in x )
else:
return x | [
" Recursively converts a Bunch into a dictionary.\n \n >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')\n >>> unbunchify(b)\n {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42}\n \n unbunchify will handle intermediary dicts, lists and tuples (as ... |
Please provide a description of the function:def get_detail(self, course_id):
# the request is done in behalf of the current logged in user
resp = self._requester.get(
urljoin(
self._base_url,
'/api/courses/v1/courses/{course_key}/'.format(course_key=... | [
"\n Fetches course details.\n\n Args:\n course_id (str): An edx course id.\n\n Returns:\n CourseDetail\n "
] |
Please provide a description of the function:def get_user_info(self):
# the request is done in behalf of the current logged in user
resp = self.requester.get(
urljoin(
self.base_url,
'/api/mobile/v0.5/my_user_info'
)
)
res... | [
"\n Returns a UserInfo object for the logged in user.\n\n Returns:\n UserInfo: object representing the student current grades\n "
] |
Please provide a description of the function:def course_blocks(self, course_id, username):
resp = self.requester.get(
urljoin(self.base_url, '/api/courses/v1/blocks/'),
params={
"depth": "all",
"username": username,
"course_id": co... | [
"\n Fetches course blocks.\n\n Args:\n course_id (str): An edx course id.\n username (str): username of the user to query for (can reveal hidden\n modules)\n\n Returns:\n Structure\n "
] |
Please provide a description of the function:def get_student_current_grade(self, username, course_id):
# the request is done in behalf of the current logged in user
resp = self.requester.get(
urljoin(
self.base_url,
'/api/grades/v1/courses/{course_key... | [
"\n Returns an CurrentGrade object for the user in a course\n\n Args:\n username (str): an edx user's username\n course_id (str): an edX course id.\n\n Returns:\n CurrentGrade: object representing the student current grade for a course\n "
] |
Please provide a description of the function:def get_student_current_grades(self, username, course_ids=None):
# if no course ids are provided, let's get the user enrollments
if course_ids is None:
enrollments_client = CourseEnrollments(self.requester, self.base_url)
enro... | [
"\n Returns a CurrentGradesByUser object with the user current grades.\n\n Args:\n username (str): an edx user's username\n course_ids (list): a list of edX course ids.\n\n Returns:\n CurrentGradesByUser: object representing the student current grades\n "... |
Please provide a description of the function:def get_course_current_grades(self, course_id):
resp = self.requester.get(
urljoin(
self.base_url,
'/api/grades/v1/courses/{course_key}/'.format(course_key=course_id)
)
)
resp.raise_for_... | [
"\n Returns a CurrentGradesByCourse object for all users in the specified course.\n\n Args:\n course_id (str): an edX course ids.\n\n Returns:\n CurrentGradesByCourse: object representing the student current grades\n\n Authorization:\n The authenticated u... |
Please provide a description of the function:def get_requester(self):
# TODO(abrahms): Perhaps pull this out into a factory function for
# generating an EdxApi instance with the proper requester & credentials.
session = requests.session()
session.headers.update({
'Au... | [
"\n Returns an object to make authenticated requests. See python `requests` for the API.\n ",
"\n adds timeout param to session.request\n "
] |
Please provide a description of the function:def create(self, master_course_id, coach_email, max_students_allowed, title, modules=None):
payload = {
'master_course_id': master_course_id,
'coach_email': coach_email,
'max_students_allowed': max_students_allowed,
... | [
"\n Creates a CCX\n\n Args:\n master_course_id (str): edx course id of the master course\n coach_email (str): email of the user to make a coach. This user must exist on edx.\n max_students_allowed (int): Maximum number of students to allow in this ccx.\n tit... |
Please provide a description of the function:def _get_enrollments_list_page(self, params=None):
req_url = urljoin(self.base_url, self.enrollment_list_url)
resp = self.requester.get(req_url, params=params)
resp.raise_for_status()
resp_json = resp.json()
results = resp_jso... | [
"\n Submit request to retrieve enrollments list.\n\n Args:\n params (dict): Query parameters to use in the request. Valid parameters are:\n * course_id: Filters the result to course enrollments for the course\n corresponding to the given course ID. The valu... |
Please provide a description of the function:def get_enrollments(self, course_id=None, usernames=None):
params = {}
if course_id is not None:
params['course_id'] = course_id
if usernames is not None and isinstance(usernames, list):
params['username'] = ','.join(u... | [
"\n List all course enrollments.\n\n Args:\n course_id (str, optional): If used enrollments will be filtered to the specified\n course id.\n usernames (list, optional): List of usernames to filter enrollments.\n\n Notes:\n - This method returns an... |
Please provide a description of the function:def get_student_enrollments(self):
# the request is done in behalf of the current logged in user
resp = self.requester.get(
urljoin(self.base_url, self.enrollment_url))
resp.raise_for_status()
return Enrollments(resp.json(... | [
"\n Returns an Enrollments object with the user enrollments\n\n Returns:\n Enrollments: object representing the student enrollments\n "
] |
Please provide a description of the function:def create_audit_student_enrollment(self, course_id):
audit_enrollment = {
"mode": "audit",
"course_details": {"course_id": course_id}
}
# the request is done in behalf of the current logged in user
resp = self... | [
"\n Creates an audit enrollment for the user in a given course\n\n Args:\n course_id (str): an edX course id\n\n Returns:\n Enrollment: object representing the student enrollment in the provided course\n "
] |
Please provide a description of the function:def get_student_certificate(self, username, course_id):
# the request is done in behalf of the current logged in user
resp = self.requester.get(
urljoin(
self.base_url,
'/api/certificates/v0/certificates/{u... | [
"\n Returns an Certificate object with the user certificates\n\n Args:\n username (str): an edx user's username\n course_id (str): an edX course id.\n\n Returns:\n Certificate: object representing the student certificate for a course\n "
] |
Please provide a description of the function:def get_student_certificates(self, username, course_ids=None):
# if no course ids are provided, let's get the user enrollments
if course_ids is None:
enrollments_client = CourseEnrollments(self.requester, self.base_url)
enroll... | [
"\n Returns an Certificates object with the user certificates\n\n Args:\n username (str): an edx user's username\n course_ids (list): a list of edX course ids.\n\n Returns:\n Certificates: object representing the student certificates for a course\n "
] |
Please provide a description of the function:def get_colors(img):
w, h = img.size
return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)] | [
"\n Returns a list of all the image's colors.\n "
] |
Please provide a description of the function:def clamp(color, min_v, max_v):
h, s, v = rgb_to_hsv(*map(down_scale, color))
min_v, max_v = map(down_scale, (min_v, max_v))
v = min(max(min_v, v), max_v)
return tuple(map(up_scale, hsv_to_rgb(h, s, v))) | [
"\n Clamps a color such that the value is between min_v and max_v.\n "
] |
Please provide a description of the function:def order_by_hue(colors):
hsvs = [rgb_to_hsv(*map(down_scale, color)) for color in colors]
hsvs.sort(key=lambda t: t[0])
return [tuple(map(up_scale, hsv_to_rgb(*hsv))) for hsv in hsvs] | [
"\n Orders colors by hue.\n "
] |
Please provide a description of the function:def brighten(color, brightness):
h, s, v = rgb_to_hsv(*map(down_scale, color))
return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness)))) | [
"\n Adds or subtracts value to a color.\n "
] |
Please provide a description of the function:def colorz(fd, n=DEFAULT_NUM_COLORS, min_v=DEFAULT_MINV, max_v=DEFAULT_MAXV,
bold_add=DEFAULT_BOLD_ADD, order_colors=True):
img = Image.open(fd)
img.thumbnail(THUMB_SIZE)
obs = get_colors(img)
clamped = [clamp(color, min_v, max_v) for color i... | [
"\n Get the n most dominant colors of an image.\n Clamps value to between min_v and max_v.\n\n Creates bold colors using bold_add.\n Total number of colors returned is 2*n, optionally ordered by hue.\n Returns as a list of pairs of RGB triples.\n\n For terminal colors, the hue order is:\n red, ... |
Please provide a description of the function:def html_preview(colors, font_size=DEFAULT_FONT_SIZE,
bg_color=DEFAULT_BG_COLOR, bg_img=None,
fd=None):
fd = fd or NamedTemporaryFile(mode='wt', suffix='.html', delete=False)
# Initial CSS styling is empty
style = ""
... | [
"\n Creates an HTML preview of each color.\n\n Returns the Python file object for the HTML file.\n ",
"\n <div class=\"color\" style=\"color: {color}\">\n <div>█ {color}</div>\n <div style=\"color: {color_bold}\">\n <strong>█ {color_bold}</strong>\n ... |
Please provide a description of the function:def long_description(*paths):
'''Returns a RST formated string.
'''
result = ''
# attempt to import pandoc
try:
import pypandoc
except (ImportError, OSError) as e:
print("Unable to import pypandoc - %s" % e)
return result
... | [] |
Please provide a description of the function:def memory_full():
current_process = psutil.Process(os.getpid())
return (current_process.memory_percent() >
config.MAXIMUM_CACHE_MEMORY_PERCENTAGE) | [
"Check if the memory is too full for further caching."
] |
Please provide a description of the function:def cache(cache={}, maxmem=config.MAXIMUM_CACHE_MEMORY_PERCENTAGE,
typed=False):
# Constants shared by all lru cache instances:
# Unique object used to signal cache misses.
sentinel = object()
# Build a key from the function arguments.
make... | [
"Memory-limited cache decorator.\n\n ``maxmem`` is a float between 0 and 100, inclusive, specifying the maximum\n percentage of physical memory that the cache can use.\n\n If ``typed`` is ``True``, arguments of different types will be cached\n separately. For example, f(3.0) and f(3) will be treated as ... |
Please provide a description of the function:def MICECache(subsystem, parent_cache=None):
if config.REDIS_CACHE:
cls = RedisMICECache
else:
cls = DictMICECache
return cls(subsystem, parent_cache=parent_cache) | [
"Construct a |MICE| cache.\n\n Uses either a Redis-backed cache or a local dict cache on the object.\n\n Args:\n subsystem (Subsystem): The subsystem that this is a cache for.\n\n Kwargs:\n parent_cache (MICECache): The cache generated by the uncut\n version of ``subsystem``. Any c... |
Please provide a description of the function:def method(cache_name, key_prefix=None):
def decorator(func):
if (func.__name__ in ['cause_repertoire', 'effect_repertoire'] and
not config.CACHE_REPERTOIRES):
return func
@wraps(func)
def wrapper(obj, *args, **kw... | [
"Caching decorator for object-level method caches.\n\n Cache key generation is delegated to the cache.\n\n Args:\n cache_name (str): The name of the (already-instantiated) cache\n on the decorated object which should be used to store results\n of this method.\n *key_prefix:... |
Please provide a description of the function:def get(self, key):
if key in self.cache:
self.hits += 1
return self.cache[key]
self.misses += 1
return None | [
"Get a value out of the cache.\n\n Returns None if the key is not in the cache. Updates cache\n statistics.\n "
] |
Please provide a description of the function:def key(self, *args, _prefix=None, **kwargs):
if kwargs:
raise NotImplementedError(
'kwarg cache keys not implemented')
return (_prefix,) + tuple(args) | [
"Get the cache key for the given function args.\n\n Kwargs:\n prefix: A constant to prefix to the key.\n "
] |
Please provide a description of the function:def info(self):
info = redis_conn.info()
return _CacheInfo(info['keyspace_hits'],
info['keyspace_misses'],
self.size()) | [
"Return cache information.\n\n .. note:: This is not the cache info for the entire Redis key space.\n "
] |
Please provide a description of the function:def get(self, key):
value = redis_conn.get(key)
if value is not None:
value = pickle.loads(value)
return value | [
"Get a value from the cache.\n\n Returns None if the key is not in the cache.\n "
] |
Please provide a description of the function:def set(self, key, value):
value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL)
redis_conn.set(key, value) | [
"Set a value in the cache."
] |
Please provide a description of the function:def get(self, key):
mice = super().get(key)
if mice is not None: # Hit
return mice
# Try and get the key from the parent cache.
if self.parent_subsystem_hash:
parent_key = key.replace(str(self.subsystem_hash... | [
"Get a value from the cache.\n\n If the |MICE| cannot be found in this cache, try and find it in the\n parent cache.\n "
] |
Please provide a description of the function:def set(self, key, value):
if not self.subsystem.is_cut:
super().set(key, value) | [
"Only need to set if the subsystem is uncut.\n\n Caches are only inherited from uncut subsystems.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.