_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q275500
SynoStorage.volumes
test
def volumes(self): """Returns all available volumes""" if self._data is not None: volumes = []
python
{ "resource": "" }
q275501
SynoStorage._get_volume
test
def _get_volume(self, volume_id): """Returns a specific volume""" if self._data is not None: for volume in
python
{ "resource": "" }
q275502
SynoStorage.volume_size_total
test
def volume_size_total(self, volume, human_readable=True): """Total size of volume""" volume = self._get_volume(volume) if volume is not None: return_data = int(volume["size"]["total"]) if human_readable:
python
{ "resource": "" }
q275503
SynoStorage.volume_percentage_used
test
def volume_percentage_used(self, volume): """Total used size in percentage for volume""" volume = self._get_volume(volume) if volume is not None: total = int(volume["size"]["total"]) used = int(volume["size"]["used"])
python
{ "resource": "" }
q275504
SynoStorage.volume_disk_temp_avg
test
def volume_disk_temp_avg(self, volume): """Average temperature of all disks making up the volume""" volume = self._get_volume(volume) if volume is not None: vol_disks = volume["disks"] if vol_disks is not None: total_temp = 0 total_disks = 0 for vol_disk in vol_disks: disk_temp = self.disk_temp(vol_disk)
python
{ "resource": "" }
q275505
SynoStorage.volume_disk_temp_max
test
def volume_disk_temp_max(self, volume): """Maximum temperature of all disks making up the volume""" volume = self._get_volume(volume) if volume is not None: vol_disks = volume["disks"] if vol_disks is not None: max_temp = 0 for vol_disk in vol_disks:
python
{ "resource": "" }
q275506
SynoStorage._get_disk
test
def _get_disk(self, disk_id): """Returns a specific disk""" if self._data is not None: for disk in
python
{ "resource": "" }
q275507
SynologyDSM._login
test
def _login(self): """Build and execute login request""" api_path = "%s/auth.cgi?api=SYNO.API.Auth&version=2" % ( self.base_url, ) login_path = "method=login&%s" % (self._encode_credentials()) url = "%s&%s&session=Core&format=cookie" % ( api_path, login_path) result = self._execute_get_url(url, False) # Parse Result if valid if result is not None:
python
{ "resource": "" }
q275508
SynologyDSM._get_url
test
def _get_url(self, url, retry_on_error=True): """Function to handle sessions for a GET request""" # Check if we failed to request the url or need to login if self.access_token is None or \ self._session is None or \ self._session_error: # Clear Access Token en reset session error self.access_token = None self._session_error = False # First Reset the session if self._session is not None: self._session = None self._debuglog("Creating New Session") self._session = requests.Session() # disable SSL certificate verification if self._use_https: self._session.verify = False # We Created a new Session so login if self._login() is False:
python
{ "resource": "" }
q275509
SynologyDSM._execute_get_url
test
def _execute_get_url(self, request_url, append_sid=True): """Function to execute and handle a GET request""" # Prepare Request self._debuglog("Requesting URL: '" + request_url + "'") if append_sid: self._debuglog("Appending access_token (SID: " + self.access_token + ") to url") request_url = "%s&_sid=%s" % ( request_url, self.access_token) # Execute Request try: resp = self._session.get(request_url) self._debuglog("Request executed: " + str(resp.status_code)) if resp.status_code == 200: # We got a response json_data = json.loads(resp.text) if json_data["success"]: self._debuglog("Succesfull returning data") self._debuglog(str(json_data)) return json_data
python
{ "resource": "" }
q275510
SynologyDSM.update
test
def update(self): """Updates the various instanced modules""" if self._utilisation is not None: api = "SYNO.Core.System.Utilization" url = "%s/entry.cgi?api=%s&version=1&method=get&_sid=%s" % ( self.base_url, api, self.access_token) self._utilisation.update(self._get_url(url)) if self._storage is not None: api = "SYNO.Storage.CGI.Storage"
python
{ "resource": "" }
q275511
SynologyDSM.utilisation
test
def utilisation(self): """Getter for various Utilisation variables""" if self._utilisation is None: api = "SYNO.Core.System.Utilization" url = "%s/entry.cgi?api=%s&version=1&method=get" % ( self.base_url,
python
{ "resource": "" }
q275512
SynologyDSM.storage
test
def storage(self): """Getter for various Storage variables""" if self._storage is None: api = "SYNO.Storage.CGI.Storage"
python
{ "resource": "" }
q275513
Context.for_request
test
def for_request(request, body=None): """Creates the context for a specific request.""" tenant, jwt_data = Tenant.objects.for_request(request, body) webhook_sender_id = jwt_data.get('sub') sender_data = None if body and 'item' in body: if 'sender' in body['item']: sender_data = body['item']['sender'] elif 'message' in body['item'] and 'from' in body['item']['message']: sender_data = body['item']['message']['from'] if sender_data is None: if webhook_sender_id is None: raise BadTenantError('Cannot identify sender in tenant')
python
{ "resource": "" }
q275514
Context.tenant_token
test
def tenant_token(self): """The cached token of the current tenant.""" rv = getattr(self, '_tenant_token', None) if rv is None:
python
{ "resource": "" }
q275515
WidgetWrapperMixin.build_attrs
test
def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary."
python
{ "resource": "" }
q275516
with_apps
test
def with_apps(*apps): """ Class decorator that makes sure the passed apps are present in INSTALLED_APPS.
python
{ "resource": "" }
q275517
without_apps
test
def without_apps(*apps): """ Class decorator that makes sure the passed apps are not present in INSTALLED_APPS. """ apps_list = [a for
python
{ "resource": "" }
q275518
override_settings.get_global_settings
test
def get_global_settings(self): """ Return a dictionary of all global_settings values. """ return
python
{ "resource": "" }
q275519
OAuth2UtilRequestHandler.do_GET
test
def do_GET(self): """ Handle the retrieval of the code """ parsed_url = urlparse(self.path) if parsed_url[2] == "/" + SERVER_REDIRECT_PATH: # 2 = Path parsed_query = parse_qs(parsed_url[4]) # 4 = Query if "code" not in parsed_query: self.send_response(200) self.send_header("Content-Type", "text/plain") self.end_headers() self.wfile.write("No code found, try again!".encode("utf-8")) return self.server.response_code = parsed_query["code"][0] self.send_response(200) self.send_header("Content-Type", "text/plain") self.end_headers() self.wfile.write( "Thank you for using OAuth2Util. The authorization was successful, " "you
python
{ "resource": "" }
q275520
OAuth2Util._get_value
test
def _get_value(self, key, func=None, split_val=None, as_boolean=False, exception_default=None): """ Helper method to get a value from the config """ try: if as_boolean: return self.config.getboolean(key[0], key[1]) value = self.config.get(key[0], key[1]) if split_val is not None: value = value.split(split_val) if func is not None: return func(value)
python
{ "resource": "" }
q275521
OAuth2Util._change_value
test
def _change_value(self, key, value): """ Change the value of the given key in the given file to the given value """ if not self.config.has_section(key[0]): self.config.add_section(key[0])
python
{ "resource": "" }
q275522
OAuth2Util._migrate_config
test
def _migrate_config(self, oldname=DEFAULT_CONFIG, newname=DEFAULT_CONFIG): """ Migrates the old config file format to the new one """ self._log("Your OAuth2Util config file is in an old format and needs " "to be changed. I
python
{ "resource": "" }
q275523
OAuth2Util._start_webserver
test
def _start_webserver(self, authorize_url=None): """ Start the webserver that will receive the code """ server_address = (SERVER_URL, SERVER_PORT) self.server = HTTPServer(server_address, OAuth2UtilRequestHandler) self.server.response_code
python
{ "resource": "" }
q275524
OAuth2Util._wait_for_response
test
def _wait_for_response(self): """ Wait until the user accepted or rejected the request """ while not
python
{ "resource": "" }
q275525
OAuth2Util._get_new_access_information
test
def _get_new_access_information(self): """ Request new access information from reddit using the built in webserver """ if not self.r.has_oauth_app_info: self._log('Cannot obtain authorize url from PRAW. Please check your configuration.', logging.ERROR) raise AttributeError('Reddit Session invalid, please check your designated config file.') url = self.r.get_authorize_url('UsingOAuth2Util', self._get_value(CONFIGKEY_SCOPE, set, split_val=','), self._get_value(CONFIGKEY_REFRESHABLE, as_boolean=True)) self._start_webserver(url) if not self._get_value(CONFIGKEY_SERVER_MODE, as_boolean=True): webbrowser.open(url) else: print("Webserver is waiting for you :D. Please open {0}:{1}/{2} " "in
python
{ "resource": "" }
q275526
OAuth2Util._check_token_present
test
def _check_token_present(self): """ Check whether the tokens are set and request new ones if not """ try: self._get_value(CONFIGKEY_TOKEN)
python
{ "resource": "" }
q275527
OAuth2Util.set_access_credentials
test
def set_access_credentials(self, _retry=0): """ Set the token on the Reddit Object again """ if _retry >= 5: raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.') self._check_token_present() try: self.r.set_access_credentials(self._get_value(CONFIGKEY_SCOPE, set, split_val=","),
python
{ "resource": "" }
q275528
OAuth2Util.refresh
test
def refresh(self, force=False, _retry=0): """ Check if the token is still valid and requests a new if it is not valid anymore Call this method before a call to praw if there might have passed more than one hour force: if true, a new token will be retrieved no matter what """ if _retry >= 5: raise ConnectionAbortedError('Reddit is not accessible right now, cannot refresh OAuth2 tokens.') self._check_token_present() # We check whether another instance already refreshed the token if time.time() > self._get_value(CONFIGKEY_VALID_UNTIL, float, exception_default=0) - REFRESH_MARGIN: self.config.read(self.configfile) if time.time() < self._get_value(CONFIGKEY_VALID_UNTIL, float, exception_default=0) - REFRESH_MARGIN: self._log("Found new token") self.set_access_credentials() if force or time.time() >
python
{ "resource": "" }
q275529
create_manifest_table
test
def create_manifest_table(dynamodb_client, table_name): """Create DynamoDB table for run manifests Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name """ try: dynamodb_client.create_table( AttributeDefinitions=[ { 'AttributeName': DYNAMODB_RUNID_ATTRIBUTE, 'AttributeType': 'S' }, ], TableName=table_name, KeySchema=[ { 'AttributeName': DYNAMODB_RUNID_ATTRIBUTE, 'KeyType': 'HASH' },
python
{ "resource": "" }
q275530
split_full_path
test
def split_full_path(path): """Return pair of bucket without protocol and path Arguments: path - valid S3 path, such as s3://somebucket/events >>> split_full_path('s3://mybucket/path-to-events') ('mybucket', 'path-to-events/') >>> split_full_path('s3://mybucket') ('mybucket', None) >>> split_full_path('s3n://snowplow-bucket/some/prefix/') ('snowplow-bucket', 'some/prefix/') """ if path.startswith('s3://'): path = path[5:] elif path.startswith('s3n://'):
python
{ "resource": "" }
q275531
is_glacier
test
def is_glacier(s3_client, bucket, prefix): """Check if prefix is archived in Glacier, by checking storage class of first object inside that prefix Arguments: s3_client - boto3 S3 client (not service) bucket - valid extracted bucket (without protocol and prefix) example: sowplow-events-data prefix - valid S3 prefix (usually, run_id) example: snowplow-archive/enriched/archive/ """ response = s3_client.list_objects_v2(Bucket=bucket,
python
{ "resource": "" }
q275532
extract_run_id
test
def extract_run_id(key): """Extract date part from run id Arguments: key - full key name, such as shredded-archive/run=2012-12-11-01-31-33/ (trailing slash is required) >>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33/') 'shredded-archive/run=2012-12-11-01-11-33/' >>> extract_run_id('shredded-archive/run=2012-12-11-01-11-33') >>> extract_run_id('shredded-archive/run=2012-13-11-01-11-33/') """
python
{ "resource": "" }
q275533
clean_dict
test
def clean_dict(dict): """Remove all keys with Nones as values >>> clean_dict({'key': None}) {} >>> clean_dict({'empty_s': ''})
python
{ "resource": "" }
q275534
add_to_manifest
test
def add_to_manifest(dynamodb_client, table_name, run_id): """Add run_id into DynamoDB manifest table Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string representing run_id to store
python
{ "resource": "" }
q275535
is_in_manifest
test
def is_in_manifest(dynamodb_client, table_name, run_id): """Check if run_id is stored in DynamoDB table. Return True if run_id is stored or False otherwise. Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string representing run_id to store """ response = dynamodb_client.get_item(
python
{ "resource": "" }
q275536
extract_schema
test
def extract_schema(uri): """ Extracts Schema information from Iglu URI >>> extract_schema("iglu:com.acme-corporation_underscore/event_name-dash/jsonschema/1-10-1")['vendor'] 'com.acme-corporation_underscore' """ match = re.match(SCHEMA_URI_REGEX, uri)
python
{ "resource": "" }
q275537
fix_schema
test
def fix_schema(prefix, schema): """ Create an Elasticsearch field name from a schema string """ schema_dict = extract_schema(schema) snake_case_organization = schema_dict['vendor'].replace('.', '_').lower() snake_case_name = re.sub('([^A-Z_])([A-Z])', '\g<1>_\g<2>',
python
{ "resource": "" }
q275538
parse_contexts
test
def parse_contexts(contexts): """ Convert a contexts JSON to an Elasticsearch-compatible list of key-value pairs For example, the JSON { "data": [ { "data": { "unique": true }, "schema": "iglu:com.acme/unduplicated/jsonschema/1-0-0" }, { "data": { "value": 1 }, "schema": "iglu:com.acme/duplicated/jsonschema/1-0-0" }, { "data": { "value": 2 }, "schema": "iglu:com.acme/duplicated/jsonschema/1-0-0" } ], "schema": "iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0" } would become [ ("context_com_acme_duplicated_1", [{"value": 1}, {"value": 2}]), ("context_com_acme_unduplicated_1", [{"unique": true}]) ] """
python
{ "resource": "" }
q275539
parse_unstruct
test
def parse_unstruct(unstruct): """ Convert an unstructured event JSON to a list containing one Elasticsearch-compatible key-value pair For example, the JSON { "data": { "data": { "key": "value" }, "schema": "iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1" }, "schema": "iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0" } would become [ ( "unstruct_com_snowplowanalytics_snowplow_link_click_1", { "key": "value" } ) ] """
python
{ "resource": "" }
q275540
transform
test
def transform(line, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True): """ Convert a Snowplow enriched event TSV into a JSON """
python
{ "resource": "" }
q275541
jsonify_good_event
test
def jsonify_good_event(event, known_fields=ENRICHED_EVENT_FIELD_TYPES, add_geolocation_data=True): """ Convert a Snowplow enriched event in the form of an array of fields into a JSON """ if len(event) != len(known_fields): raise SnowplowEventTransformationException( ["Expected {} fields, received {} fields.".format(len(known_fields), len(event))] ) else: output = {} errors = [] if add_geolocation_data and event[LATITUDE_INDEX] != '' and event[LONGITUDE_INDEX] != '': output['geo_location'] = event[LATITUDE_INDEX] + ',' + event[LONGITUDE_INDEX] for i in range(len(event)): key = known_fields[i][0] if event[i] != '': try: kvpairs = known_fields[i][1](key, event[i]) for kvpair in kvpairs: output[kvpair[0]] = kvpair[1]
python
{ "resource": "" }
q275542
get_used_template
test
def get_used_template(response): """ Get the template used in a TemplateResponse. This returns a tuple of "active choice, all choices" """ if not hasattr(response, 'template_name'): return None, None template = response.template_name if template is None: return None, None if isinstance(template, (list, tuple)): # See which template name was really used. if len(template) == 1: return template[0], None else: used_name = _get_used_template_name(template) return used_name,
python
{ "resource": "" }
q275543
PrintNode.print_context
test
def print_context(self, context): """ Print the entire template context """ text = [CONTEXT_TITLE] for i, context_scope in enumerate(context): dump1 = linebreaksbr(pformat_django_context_html(context_scope)) dump2 = pformat_dict_summary_html(context_scope)
python
{ "resource": "" }
q275544
PrintNode.print_variables
test
def print_variables(self, context): """ Print a set of variables """ text = [] for name, expr in self.variables: # Some extended resolving, to handle unknown variables data = '' try: if isinstance(expr.var, Variable): data = expr.var.resolve(context) else: data = expr.resolve(context) # could return TEMPLATE_STRING_IF_INVALID except VariableDoesNotExist as e: # Failed to resolve, display exception inline keys = [] for scope in context: keys += scope.keys() keys = sorted(set(keys)) # Remove duplicates, e.g. csrf_token return ERROR_TYPE_BLOCK.format(style=PRE_ALERT_STYLE, error=escape(u"Variable '{0}' not found! Available context variables are:\n\n{1}".format(expr, u', '.join(keys)))) else: # Regular format
python
{ "resource": "" }
q275545
pformat_sql_html
test
def pformat_sql_html(sql): """ Highlight common SQL words in a string. """
python
{ "resource": "" }
q275546
pformat_django_context_html
test
def pformat_django_context_html(object): """ Dump a variable to a HTML string with sensible output for template context fields. It filters out all fields which are not usable in a template context. """ if isinstance(object, QuerySet): text = '' lineno = 0 for item in object.all()[:21]: lineno += 1 if lineno >= 21: text += u' (remaining items truncated...)' break text += u' {0}\n'.format(escape(repr(item))) return text elif isinstance(object, Manager): return mark_safe(u' (use <kbd>.all</kbd> to read it)') elif isinstance(object, six.string_types): return escape(repr(object)) elif isinstance(object, Promise): # lazy() object
python
{ "resource": "" }
q275547
pformat_dict_summary_html
test
def pformat_dict_summary_html(dict): """ Briefly print the dictionary keys. """ if not dict: return ' {}' html = [] for key, value in sorted(six.iteritems(dict)): if not isinstance(value, DICT_EXPANDED_TYPES):
python
{ "resource": "" }
q275548
_style_text
test
def _style_text(text): """ Apply some HTML highlighting to the contents. This can't be done in the """ # Escape text and apply some formatting. # To have really good highlighting, pprint would have to be re-implemented. text = escape(text) text = text.replace(' &lt;iterator object&gt;', " <small>&lt;<var>this object can be used in a 'for' loop</var>&gt;</small>") text = text.replace(' &lt;dynamic item&gt;', ' <small>&lt;<var>this object may have extra field names</var>&gt;</small>') text = text.replace(' &lt;dynamic attribute&gt;', ' <small>&lt;<var>this object may have extra field names</var>&gt;</small>') text = RE_PROXY.sub('\g<1><small>&lt;<var>proxy object</var>&gt;</small>', text) text = RE_FUNCTION.sub('\g<1><small>&lt;<var>object method</var>&gt;</small>', text) text = RE_GENERATOR.sub("\g<1><small>&lt;<var>generator, use 'for' to traverse it</var>&gt;</small>", text) text
python
{ "resource": "" }
q275549
DebugPrettyPrinter.format
test
def format(self, object, context, maxlevels, level): """ Format an item in the result. Could be a dictionary key, value, etc..
python
{ "resource": "" }
q275550
DebugPrettyPrinter._format
test
def _format(self, object, stream, indent, allowance, context, level): """ Recursive part of the formatting """ try:
python
{ "resource": "" }
q275551
get_token
test
def get_token(s, pos, brackets_are_chars=True, environments=True, **parse_flags): """ Parse the next token in the stream. Returns a `LatexToken`. Raises `LatexWalkerEndOfStream` if end of stream reached. .. deprecated:: 1.0 Please use :py:meth:`LatexWalker.get_token()` instead. """ return LatexWalker(s, **parse_flags).get_token(pos=pos,
python
{ "resource": "" }
q275552
get_latex_nodes
test
def get_latex_nodes(s, pos=0, stop_upon_closing_brace=None, stop_upon_end_environment=None, stop_upon_closing_mathmode=None, **parse_flags): """ Parses latex content `s`. Returns a tuple `(nodelist, pos, len)` where nodelist is a list of `LatexNode` 's. If `stop_upon_closing_brace` is given, then `len` includes the closing brace, but the closing brace is not included in any of the nodes in the `nodelist`. .. deprecated:: 1.0
python
{ "resource": "" }
q275553
latex2text
test
def latex2text(content, tolerant_parsing=False, keep_inline_math=False, keep_comments=False): """ Extracts text from `content` meant for database indexing. `content` is some LaTeX code. .. deprecated:: 1.0 Please use :py:class:`LatexNodes2Text` instead. """ (nodelist, tpos, tlen) = latexwalker.get_latex_nodes(content, keep_inline_math=keep_inline_math,
python
{ "resource": "" }
q275554
LatexNodes2Text.set_tex_input_directory
test
def set_tex_input_directory(self, tex_input_directory, latex_walker_init_args=None, strict_input=True): """ Set where to look for input files when encountering the ``\\input`` or ``\\include`` macro. Alternatively, you may also override :py:meth:`read_input_file()` to implement a custom file lookup mechanism. The argument `tex_input_directory` is the directory relative to which to search for input files. If `strict_input` is set to `True`, then we always check that the referenced file lies within the subtree of `tex_input_directory`, prohibiting for instance hacks with '..' in filenames or using symbolic links to refer to files out of the directory tree. The argument `latex_walker_init_args` allows you to specify the parse flags passed to the constructor of :py:class:`pylatexenc.latexwalker.LatexWalker` when parsing the input
python
{ "resource": "" }
q275555
LatexNodes2Text.read_input_file
test
def read_input_file(self, fn): """ This method may be overridden to implement a custom lookup mechanism when encountering ``\\input`` or ``\\include`` directives. The default implementation looks for a file of the given name relative to the directory set by :py:meth:`set_tex_input_directory()`. If `strict_input=True` was set, we ensure strictly that the file resides in a subtree of the reference input directory (after canonicalizing the paths and resolving all symlinks). You may override this method to obtain the input data in however way you see fit. (In that case, a call to `set_tex_input_directory()` may not be needed as that function simply sets properties which are used by the default implementation of `read_input_file()`.) This function accepts the referred filename as argument (the argument to the ``\\input`` macro), and should return a string with the file contents (or generate a warning or raise an error). """ fnfull = os.path.realpath(os.path.join(self.tex_input_directory, fn)) if self.strict_input: # make sure that the input file is strictly within dirfull, and didn't escape with # '../..' tricks or via symlinks. dirfull = os.path.realpath(self.tex_input_directory) if not fnfull.startswith(dirfull):
python
{ "resource": "" }
q275556
LatexNodes2Text.latex_to_text
test
def latex_to_text(self, latex, **parse_flags): """ Parses the given `latex` code and returns its textual representation. The `parse_flags` are the flags to give on to the :py:class:`pylatexenc.latexwalker.LatexWalker` constructor.
python
{ "resource": "" }
q275557
utf8tolatex
test
def utf8tolatex(s, non_ascii_only=False, brackets=True, substitute_bad_chars=False, fail_bad_chars=False): u""" Encode a UTF-8 string to a LaTeX snippet. If `non_ascii_only` is set to `True`, then usual (ascii) characters such as ``#``, ``{``, ``}`` etc. will not be escaped. If set to `False` (the default), they are escaped to their respective LaTeX escape sequences. If `brackets` is set to `True` (the default), then LaTeX macros are enclosed in brackets. For example, ``sant\N{LATIN SMALL LETTER E WITH ACUTE}`` is replaced by ``sant{\\'e}`` if `brackets=True` and by ``sant\\'e`` if `brackets=False`. .. warning:: Using `brackets=False` might give you an invalid LaTeX string, so avoid it! (for instance, ``ma\N{LATIN SMALL LETTER I WITH CIRCUMFLEX}tre`` will be replaced incorrectly by ``ma\\^\\itre`` resulting in an unknown macro ``\\itre``). If `substitute_bad_chars=True`, then any non-ascii character for which no LaTeX escape sequence is known is replaced by a question mark in boldface. Otherwise (by default), the character is left as it
python
{ "resource": "" }
q275558
_unascii
test
def _unascii(s): """Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8 This method takes the output of the JSONEncoder and expands any \\uNNNN escapes it finds (except for \\u0000 to \\u001F, which are converted to \\xNN escapes). For performance, it assumes that the input is valid JSON, and performs few sanity checks. """ # make the fast path fast: if there are no matches in the string, the # whole thing is ascii. On python 2, that means we're done. On python 3, # we have to turn it into a bytes, which is quickest with encode('utf-8') m = _U_ESCAPE.search(s) if not m: return s if PY2 else s.encode('utf-8') # appending to a string (or a bytes) is slooow, so we accumulate sections # of string result in 'chunks', and join them all together later. # (It doesn't seem to make much difference whether we accumulate # utf8-encoded bytes, or strings which we utf-8 encode after rejoining) # chunks = [] # 'pos' tracks the index in 's' that we have processed into 'chunks' so # far. pos = 0 while m: start = m.start() end = m.end() g = m.group(1) if g is None: # escaped backslash: pass it through along with anything before the # match chunks.append(s[pos:end]) else: # \uNNNN, but we have to watch out for surrogate pairs. # # On python 2, str.encode("utf-8") will decode utf-16 surrogates # before re-encoding, so it's fine for us to pass the surrogates # through. (Indeed we must, to deal with UCS-2 python builds, per # https://github.com/matrix-org/python-canonicaljson/issues/12). # # On python 3, str.encode("utf-8") complains about surrogates, so # we have to unpack them.
python
{ "resource": "" }
q275559
Organisation.get_organisation_information
test
def get_organisation_information(self, query_params=None): ''' Get information fot this organisation. Returns a dictionary of values. '''
python
{ "resource": "" }
q275560
Organisation.get_boards
test
def get_boards(self, **query_params): ''' Get all the boards for this organisation. Returns a list of Board s. Returns: list(Board): The boards attached to
python
{ "resource": "" }
q275561
Organisation.get_members
test
def get_members(self, **query_params): ''' Get all members attached to this organisation. Returns a list of Member objects Returns: list(Member): The members attached to this organisation
python
{ "resource": "" }
q275562
Organisation.update_organisation
test
def update_organisation(self, query_params=None): ''' Update this organisations information. Returns a new organisation object. ''' organisation_json = self.fetch_json( uri_path=self.base_uri,
python
{ "resource": "" }
q275563
Organisation.remove_member
test
def remove_member(self, member_id): ''' Remove a member from the organisation.Returns JSON of all members if successful or raises
python
{ "resource": "" }
q275564
Organisation.add_member_by_id
test
def add_member_by_id(self, member_id, membership_type='normal'): ''' Add a member to the board using the id. Membership type can be normal or admin. Returns JSON of all members if successful or raises an Unauthorised exception if not. ''' return self.fetch_json(
python
{ "resource": "" }
q275565
Organisation.add_member
test
def add_member(self, email, fullname, membership_type='normal'): ''' Add a member to the board. Membership type can be normal or admin. Returns JSON of all members if successful or raises an Unauthorised exception if not. ''' return self.fetch_json(
python
{ "resource": "" }
q275566
List.get_list_information
test
def get_list_information(self, query_params=None): ''' Get information for this list. Returns a dictionary
python
{ "resource": "" }
q275567
List.add_card
test
def add_card(self, query_params=None): ''' Create a card for this list. Returns a Card object. ''' card_json = self.fetch_json( uri_path=self.base_uri + '/cards',
python
{ "resource": "" }
q275568
Label.get_label_information
test
def get_label_information(self, query_params=None): ''' Get all information for this Label. Returns a dictionary
python
{ "resource": "" }
q275569
Label.get_items
test
def get_items(self, query_params=None): ''' Get all the items for this label. Returns a list of dictionaries. Each dictionary has the values for an item. ''' return self.fetch_json(
python
{ "resource": "" }
q275570
Label._update_label_name
test
def _update_label_name(self, name): ''' Update the current label's name. Returns a new Label object. '''
python
{ "resource": "" }
q275571
Label._update_label_dict
test
def _update_label_dict(self, query_params={}): ''' Update the current label. Returns a new Label object. ''' label_json = self.fetch_json( uri_path=self.base_uri,
python
{ "resource": "" }
q275572
Authorise.get_authorisation_url
test
def get_authorisation_url(self, application_name, token_expire='1day'): ''' Returns a URL that needs to be opened in a browser to retrieve an access token. ''' query_params = { 'name': application_name, 'expiration': token_expire, 'response_type': 'token', 'scope': 'read,write' } authorisation_url = self.build_uri( path='/authorize',
python
{ "resource": "" }
q275573
Card.get_card_information
test
def get_card_information(self, query_params=None): ''' Get information for this card. Returns a dictionary
python
{ "resource": "" }
q275574
Card.get_board
test
def get_board(self, **query_params): ''' Get board information for this card. Returns a Board object. Returns: Board: The board this card is attached to '''
python
{ "resource": "" }
q275575
Card.get_list
test
def get_list(self, **query_params): ''' Get list information for this card. Returns a List object. Returns: List: The list this card is attached to '''
python
{ "resource": "" }
q275576
Card.get_checklists
test
def get_checklists(self, **query_params): ''' Get the checklists for this card. Returns a list of Checklist objects. Returns: list(Checklist): The checklists attached to this card ''' checklists = self.get_checklist_json(self.base_uri, query_params=query_params)
python
{ "resource": "" }
q275577
Card.add_comment
test
def add_comment(self, comment_text): ''' Adds a comment to this card by the current user. ''' return self.fetch_json(
python
{ "resource": "" }
q275578
Card.add_attachment
test
def add_attachment(self, filename, open_file): ''' Adds an attachment to this card. ''' fields = { 'api_key': self.client.api_key, 'token': self.client.user_auth_token } content_type, body
python
{ "resource": "" }
q275579
Card.add_checklist
test
def add_checklist(self, query_params=None): ''' Add a checklist to this card. Returns a Checklist object. ''' checklist_json = self.fetch_json( uri_path=self.base_uri + '/checklists',
python
{ "resource": "" }
q275580
Card._add_label_from_dict
test
def _add_label_from_dict(self, query_params=None): ''' Add a label to this card, from a dictionary.
python
{ "resource": "" }
q275581
Card._add_label_from_class
test
def _add_label_from_class(self, label=None): ''' Add an existing label to this card. ''' return self.fetch_json(
python
{ "resource": "" }
q275582
Card.add_member
test
def add_member(self, member_id): ''' Add a member to this card. Returns a list of Member objects. ''' members = self.fetch_json( uri_path=self.base_uri + '/idMembers', http_method='POST', query_params={'value': member_id}
python
{ "resource": "" }
q275583
Member.get_member_information
test
def get_member_information(self, query_params=None): ''' Get Information for a member. Returns a dictionary of values. Returns: dict '''
python
{ "resource": "" }
q275584
Member.get_cards
test
def get_cards(self, **query_params): ''' Get all cards this member is attached to. Return a list of Card objects. Returns: list(Card): Return all cards
python
{ "resource": "" }
q275585
Member.get_organisations
test
def get_organisations(self, **query_params): ''' Get all organisations this member is attached to. Return a list of Organisation objects. Returns: list(Organisation): Return all organisations this member is attached to ''' organisations = self.get_organisations_json(self.base_uri,
python
{ "resource": "" }
q275586
Member.create_new_board
test
def create_new_board(self, query_params=None): ''' Create a new board. name is required in query_params. Returns a Board object. Returns: Board: Returns the created board ''' board_json = self.fetch_json(
python
{ "resource": "" }
q275587
singledispatchmethod
test
def singledispatchmethod(method): ''' Enable singledispatch for class methods. See http://stackoverflow.com/a/24602374/274318 ''' dispatcher = singledispatch(method) def wrapper(*args, **kw): return
python
{ "resource": "" }
q275588
Board.get_board_information
test
def get_board_information(self, query_params=None): ''' Get all information for this board. Returns a dictionary
python
{ "resource": "" }
q275589
Board.get_lists
test
def get_lists(self, **query_params): ''' Get the lists attached to this board. Returns a list of List objects. Returns: list(List): The lists attached to
python
{ "resource": "" }
q275590
Board.get_labels
test
def get_labels(self, **query_params): ''' Get the labels attached to this board. Returns a label of Label objects. Returns: list(Label): The labels attached
python
{ "resource": "" }
q275591
Board.get_card
test
def get_card(self, card_id, **query_params): ''' Get a Card for a given card id. Returns a Card object. Returns: Card: The card with the given card_id ''' card_json
python
{ "resource": "" }
q275592
Board.get_checklists
test
def get_checklists( self ): """ Get the checklists for this board. Returns a list of Checklist objects. """ checklists = self.getChecklistsJson( self.base_uri ) checklists_list = []
python
{ "resource": "" }
q275593
Board.get_organisation
test
def get_organisation(self, **query_params): ''' Get the Organisation for this board. Returns Organisation object. Returns: list(Organisation): The organisation attached to this board '''
python
{ "resource": "" }
q275594
Board.update_board
test
def update_board(self, query_params=None): ''' Update this board's information. Returns a new board. '''
python
{ "resource": "" }
q275595
Board.add_list
test
def add_list(self, query_params=None): ''' Create a list for a board. Returns a new List object. ''' list_json = self.fetch_json( uri_path=self.base_uri + '/lists',
python
{ "resource": "" }
q275596
Board.add_label
test
def add_label(self, query_params=None): ''' Create a label for a board. Returns a new Label object. ''' list_json = self.fetch_json( uri_path=self.base_uri + '/labels',
python
{ "resource": "" }
q275597
Checklist.get_checklist_information
test
def get_checklist_information(self, query_params=None): ''' Get all information for this Checklist. Returns a dictionary of values. ''' # We don't use trelloobject.TrelloObject.get_checklist_json, because # that
python
{ "resource": "" }
q275598
Checklist.get_card
test
def get_card(self): ''' Get card this checklist is on. '''
python
{ "resource": "" }
q275599
Checklist.get_item_objects
test
def get_item_objects(self, query_params=None): """ Get the items for this checklist. Returns a list of ChecklistItem objects. """ card = self.get_card() checklistitems_list = [] for checklistitem_json in self.get_items(query_params):
python
{ "resource": "" }