_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q31200 | normalize | train | def normalize(dt, tz):
"""
Given a object with a timezone return a datetime object
normalized to the proper timezone.
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone. | python | {
"resource": ""
} |
q31201 | Delorean.shift | train | def shift(self, timezone):
"""
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorea... | python | {
"resource": ""
} |
q31202 | Delorean.epoch | train | def epoch(self):
"""
Returns the total seconds since epoch associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. | python | {
"resource": ""
} |
q31203 | Delorean.replace | train | def replace(self, **kwargs):
"""
Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
| python | {
"resource": ""
} |
q31204 | Delorean.format_datetime | train | def format_datetime(self, format='medium', locale='en_US'):
"""
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
| python | {
"resource": ""
} |
q31205 | mask_phone_number | train | def mask_phone_number(number):
"""
Masks a phone number, only first 3 and last 2 digits visible.
Examples:
* `+31 * ******58`
:param number: str or phonenumber object
:return: str
| python | {
"resource": ""
} |
q31206 | PhoneDevice.generate_challenge | train | def generate_challenge(self):
# local import to avoid circular import
from two_factor.utils import totp_digits
"""
Sends the current TOTP token to `self.number` using `self.method`. | python | {
"resource": ""
} |
q31207 | AdminSiteOTPRequiredMixin.login | train | def login(self, request, extra_context=None):
"""
Redirects to the site login page for the given HttpRequest.
"""
redirect_to = request.POST.get(REDIRECT_FIELD_NAME, request.GET.get(REDIRECT_FIELD_NAME)) | python | {
"resource": ""
} |
q31208 | class_view_decorator | train | def class_view_decorator(function_decorator):
"""
Converts a function based decorator into a class based decorator usable
on class based Views.
Can't subclass the `View` as it breaks inheritance (super in particular),
so we monkey-patch instead.
| python | {
"resource": ""
} |
q31209 | IdempotentSessionWizardView.is_step_visible | train | def is_step_visible(self, step):
"""
Returns whether the given `step` should be included in the wizard; it
is included | python | {
"resource": ""
} |
q31210 | IdempotentSessionWizardView.post | train | def post(self, *args, **kwargs):
"""
Check if the current step is still available. It might not be if
conditions have changed.
"""
if self.steps.current not in self.steps.all:
logger.warning("Current step '%s' is no longer valid, returning "
... | python | {
"resource": ""
} |
q31211 | IdempotentSessionWizardView.process_step | train | def process_step(self, form):
"""
Stores the validated data for `form` and cleans out validated forms
for next steps, as those might be affected by the current step. Note
that this behaviour is relied upon by the `LoginView` to prevent users
from bypassing the `TokenForm` by goin... | python | {
"resource": ""
} |
q31212 | download | train | def download(query, num_results):
"""
downloads HTML after google search
"""
# https://stackoverflow.com/questions/11818362/how-to-deal-with-unicode-string-in-url-in-python3
name = quote(query)
name = name.replace(' ','+')
url = 'http://www.google.com/search?q=' + name
if num_results != 10:
url += '&num=' +... | python | {
"resource": ""
} |
q31213 | convert_unicode | train | def convert_unicode(text):
"""
converts unicode HTML to real Unicode
"""
if isPython2:
h = HTMLParser()
s = h.unescape(text)
else:
try:
s = unescape(text)
except Exception:
| python | {
"resource": ""
} |
q31214 | permission_required | train | def permission_required(perm, login_url=None):
"""Replacement for django.contrib.auth.decorators.permission_required that
returns 403 Forbidden if the user is already logged in.
| python | {
"resource": ""
} |
q31215 | CASBackend.authenticate | train | def authenticate(self, request, ticket, service):
"""Verifies CAS ticket and gets or creates User object"""
client = get_cas_client(service_url=service, request=request)
username, attributes, pgtiou = client.verify_ticket(ticket)
if attributes and request:
request.session['at... | python | {
"resource": ""
} |
q31216 | CASBackend.get_user_id | train | def get_user_id(self, attributes):
"""
For use when CAS_CREATE_USER_WITH_ID is True. Will raise ImproperlyConfigured
exceptions when a user_id cannot be accessed. This is important because we
shouldn't create Users with automatically assigned ids if we are trying to
keep User pri... | python | {
"resource": ""
} |
q31217 | CASBackend.clean_username | train | def clean_username(self, username):
"""
Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, changes the username case according to
`settings.CAS_FORCE_CHANGE_USERNAME_CASE`.
"""
| python | {
"resource": ""
} |
q31218 | get_service_url | train | def get_service_url(request, redirect_to=None):
"""Generates application django service URL for CAS"""
if hasattr(django_settings, 'CAS_ROOT_PROXIED_AS'):
service = django_settings.CAS_ROOT_PROXIED_AS + request.path
else:
protocol = get_protocol(request)
| python | {
"resource": ""
} |
q31219 | ProxyGrantingTicket.retrieve_pt | train | def retrieve_pt(cls, request, service):
"""`request` should be the current HttpRequest object
`service` a string representing the service for witch we want to
retrieve a ticket.
The function return a Proxy Ticket or raise `ProxyError`
"""
try:
pgt = cls.object... | python | {
"resource": ""
} |
q31220 | DummyStateMachine.reset | train | def reset(self, document, parent, level):
"""Reset the state of state machine.
After reset, self and self.state can be used to
passed to docutils.parsers.rst.Directive.run
Parameters
----------
document: docutils document
Current document of the node.
... | python | {
"resource": ""
} |
q31221 | DummyStateMachine.run_directive | train | def run_directive(self, name,
arguments=None,
options=None,
content=None):
"""Generate directive node given arguments.
Parameters
----------
name : str
name of directive.
arguments : list
l... | python | {
"resource": ""
} |
q31222 | DummyStateMachine.run_role | train | def run_role(self, name,
options=None,
content=None):
"""Generate a role node.
options : dict
key value arguments.
content : content
content of the directive
Returns
-------
node : docutil Node
Node g... | python | {
"resource": ""
} |
q31223 | CommonMarkParser.default_depart | train | def default_depart(self, mdnode):
"""Default node depart handler
If there is a matching ``visit_<type>`` method for a container node,
then we should make sure to back up to it's parent element when the node
is exited.
"""
if mdnode.is_container():
| python | {
"resource": ""
} |
q31224 | CommonMarkParser.depart_heading | train | def depart_heading(self, _):
"""Finish establishing section
Wrap up title node, but stick in the section node. Add the section names
based on all the text nodes added to the title.
"""
assert isinstance(self.current_node, nodes.title)
# The title node has a tree of text ... | python | {
"resource": ""
} |
q31225 | AutoStructify.parse_ref | train | def parse_ref(self, ref):
"""Analyze the ref block, and return the information needed.
Parameters
----------
ref : nodes.reference
Returns
-------
result : tuple of (str, str, str)
The returned result is tuple of (title, uri, docpath).
ti... | python | {
"resource": ""
} |
q31226 | AutoStructify.auto_toc_tree | train | def auto_toc_tree(self, node): # pylint: disable=too-many-branches
"""Try to convert a list block to toctree in rst.
This function detects if the matches the condition and return
a converted toc tree node. The matching condition:
The list only contains one level, and only contains refe... | python | {
"resource": ""
} |
q31227 | AutoStructify.auto_inline_code | train | def auto_inline_code(self, node):
"""Try to automatically generate nodes for inline literals.
Parameters
----------
node : nodes.literal
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None if co... | python | {
"resource": ""
} |
q31228 | AutoStructify.auto_code_block | train | def auto_code_block(self, node):
"""Try to automatically generate nodes for codeblock syntax.
Parameters
----------
node : nodes.literal_block
Original codeblock node
Returns
-------
tocnode: docutils node
The converted toc tree node, None... | python | {
"resource": ""
} |
q31229 | AutoStructify.find_replace | train | def find_replace(self, node):
"""Try to find replace node for current node.
Parameters
----------
node : docutil node
Node to find replacement for.
Returns
-------
nodes : node or list of node
The replacement nodes of current node.
... | python | {
"resource": ""
} |
q31230 | AutoStructify.apply | train | def apply(self):
"""Apply the transformation by configuration."""
source = self.document['source']
self.reporter.info('AutoStructify: %s' % source)
# only transform markdowns
if not source.endswith(tuple(self.config['commonmark_suffixes'])):
return
self.url... | python | {
"resource": ""
} |
q31231 | correction | train | def correction(sentence, pos):
"Most probable spelling correction for word."
word = sentence[pos]
cands = candidates(word)
if not cands:
cands = candidates(word, False)
if not cands:
return word
cands = | python | {
"resource": ""
} |
q31232 | graph_from_dot_file | train | def graph_from_dot_file(path, encoding=None):
"""Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
| python | {
"resource": ""
} |
q31233 | Node.to_string | train | def to_string(self):
"""Return string representation of node in DOT language."""
# RMF: special case defaults for node, edge and graph properties.
#
node = quote_if_necessary(self.obj_dict['name'])
node_attr = list()
for attr in sorted(self.obj_dict['attributes']):
... | python | {
"resource": ""
} |
q31234 | Graph.add_node | train | def add_node(self, graph_node):
"""Adds a node object to the graph.
It takes a node object as its only argument and returns
None.
"""
if not isinstance(graph_node, Node):
raise TypeError(
'add_node() received ' +
'a non node class obj... | python | {
"resource": ""
} |
q31235 | Graph.del_node | train | def del_node(self, name, index=None):
"""Delete a node from the graph.
Given a node's name all node(s) with that same name
will be deleted if 'index' is not specified or set
to None.
If there are several nodes with that same name and
'index' is given, only the node in th... | python | {
"resource": ""
} |
q31236 | Graph.get_edge | train | def get_edge(self, src_or_list, dst=None):
"""Retrieved an edge from the graph.
Given an edge's source and destination the corresponding
Edge instance(s) will be returned.
If one or more edges exist with that source and destination
a list of Edge instances is returned.
... | python | {
"resource": ""
} |
q31237 | Graph.get_subgraph | train | def get_subgraph(self, name):
"""Retrieved a subgraph from the graph.
Given a subgraph's name the corresponding
Subgraph instance will be returned.
If one or more subgraphs exist with the same name, a list of
Subgraph instances is returned.
An empty list is returned oth... | python | {
"resource": ""
} |
q31238 | Graph.get_subgraph_list | train | def get_subgraph_list(self):
"""Get the list of Subgraph instances.
This method returns the list of Subgraph instances
in the graph.
"""
sgraph_objs = list()
for sgraph in self.obj_dict['subgraphs']:
obj_dict_list = self.obj_dict['subgraphs'][sgraph]
| python | {
"resource": ""
} |
q31239 | Dot.create | train | def create(self, prog=None, format='ps', encoding=None):
"""Creates and returns a binary image for the graph.
create will write the graph to a temporary dot file in the
encoding specified by `encoding` and process it with the
program given by 'prog' (which defaults to 'twopi'), reading
... | python | {
"resource": ""
} |
q31240 | SchemaError.code | train | def code(self):
"""
Removes duplicates values in auto and error list.
parameters.
"""
def uniq(seq):
"""
Utility function that removes duplicate.
"""
seen = set()
seen_add = seen.add | python | {
"resource": ""
} |
q31241 | Schema._dict_key_priority | train | def _dict_key_priority(s):
"""Return priority for a given key object."""
if isinstance(s, Hook):
return _priority(s._schema) - 0.5
| python | {
"resource": ""
} |
q31242 | Schema._prepend_schema_name | train | def _prepend_schema_name(self, message):
"""
If a custom schema name has been defined, prepends it to the error
| python | {
"resource": ""
} |
q31243 | Schema.json_schema | train | def json_schema(self, schema_id=None, is_main_schema=True):
"""Generate a draft-07 JSON schema dict representing the Schema.
This method can only be called when the Schema's value is a dict.
This method must be called with a schema_id. Calling it without one
is used in a recursive contex... | python | {
"resource": ""
} |
q31244 | Files.put | train | def put(self, filename, data):
"""Create or update the specified file with the provided data.
"""
# Open the file for writing on the board and write chunks of data.
self._pyboard.enter_raw_repl()
self._pyboard.exec_("f = open('{0}', 'wb')".format(filename))
size = len(dat... | python | {
"resource": ""
} |
q31245 | cli | train | def cli(port, baud, delay):
"""ampy - Adafruit MicroPython Tool
Ampy is a tool to control MicroPython boards over a serial connection. Using
ampy you can manipulate files on the board's internal filesystem and even run
scripts.
"""
global _board
# On Windows fix the COM port path name for ... | python | {
"resource": ""
} |
q31246 | get | train | def get(remote_file, local_file):
"""
Retrieve a file from the board.
Get will download a file from the board and print its contents or save it
locally. You must pass at least one argument which is the path to the file
to download from the board. If you don't specify a second argument then
th... | python | {
"resource": ""
} |
q31247 | mkdir | train | def mkdir(directory, exists_okay):
"""
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument is
required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with one
mkdir command, instea... | python | {
"resource": ""
} |
q31248 | ls | train | def ls(directory, long_format, recursive):
"""List contents of a directory on the board.
Can pass an optional argument which is the path to the directory. The
default is to list the contents of the root, /, path.
For example to list the contents of the root run:
ampy --port /board/serial/port ... | python | {
"resource": ""
} |
q31249 | put | train | def put(local, remote):
"""Put a file or folder and its contents on the board.
Put will upload a local file or folder to the board. If the file already
exists on the board it will be overwritten with no warning! You must pass
at least one argument which is the path to the local file/folder to
up... | python | {
"resource": ""
} |
q31250 | rmdir | train | def rmdir(remote_folder, missing_okay):
"""Forcefully remove a folder and all its children from the board.
Remove the specified folder from the board's filesystem. Must specify one
argument which is the path to the folder to delete. This will delete the
directory and ALL of its children recursively, ... | python | {
"resource": ""
} |
q31251 | run | train | def run(local_file, no_output):
"""Run a script and print its output.
Run will send the specified file to the board and execute it immediately.
Any output from the board will be printed to the console (note that this is
not a 'shell' and you can't send input to the program).
Note that if your code... | python | {
"resource": ""
} |
q31252 | GenericESCPOS.kick_drawer | train | def kick_drawer(self, port=0, **kwargs):
"""Kick drawer connected to the given port.
In this implementation, cash drawers are identified according to the
port in which they are connected. This relation between drawers and
ports does not exists in the ESC/POS specification and it is just... | python | {
"resource": ""
} |
q31253 | get_baudrates | train | def get_baudrates():
"""
Returns supported baud rates in a Django-like choices tuples.
"""
baudrates = []
s = pyserial.Serial()
for name, value in | python | {
"resource": ""
} |
q31254 | get_databits | train | def get_databits():
"""
Returns supported byte sizes in a Django-like choices tuples.
"""
databits = []
s = pyserial.Serial()
for name, value | python | {
"resource": ""
} |
q31255 | get_stopbits | train | def get_stopbits():
"""
Returns supported stop bit lengths in a Django-like choices tuples.
"""
stopbits = []
s = pyserial.Serial()
| python | {
"resource": ""
} |
q31256 | get_parities | train | def get_parities():
"""
Returns supported parities in a Django-like choices tuples.
"""
parities = []
s = pyserial.Serial()
for name, value in | python | {
"resource": ""
} |
q31257 | SerialSettings.get_connection | train | def get_connection(self, **kwargs):
"""Return a serial connection implementation suitable for the specified
protocol. Raises ``RuntimeError`` if there is no implementation for
the given protocol.
.. warn::
This may be a little bit confusing since there is | python | {
"resource": ""
} |
q31258 | SerialConnection.write | train | def write(self, data):
"""Write data to serial port."""
for chunk in chunks(data, 512):
self.wait_to_write()
| python | {
"resource": ""
} |
q31259 | SerialConnection.read | train | def read(self):
"""Read data from serial port and returns a ``bytearray``."""
data = bytearray()
while True:
incoming_bytes = self.comport.inWaiting()
if incoming_bytes == 0:
break
| python | {
"resource": ""
} |
q31260 | FileConnection.write | train | def write(self, data):
"""Print any command sent in raw format.
:param bytes data: arbitrary code to be printed.
"""
| python | {
"resource": ""
} |
q31261 | is_value_in | train | def is_value_in(constants_group, value):
"""
Checks whether value can be found in the given constants group, which in
turn, should be a Django-like choices tuple.
"""
| python | {
"resource": ""
} |
q31262 | run_interactive | train | def run_interactive(query, editor=None, just_count=False, default_no=False):
"""
Asks the user about each patch suggested by the result of the query.
@param query An instance of the Query class.
@param editor Name of editor to use for manual intervention, e.g.
'vim'... | python | {
"resource": ""
} |
q31263 | Query.get_all_patches | train | def get_all_patches(self, dont_use_cache=False):
"""
Computes a list of all patches matching this query, though ignoreing
self.start_position and self.end_position.
@param dont_use_cache If False, and get_all_patches has been called
before, compute the ... | python | {
"resource": ""
} |
q31264 | Query.compute_percentile | train | def compute_percentile(self, percentage):
"""
Returns a Position object that represents percentage%-far-of-the-way
through the larger task, as specified by this query.
@param percentage a number between 0 and 100.
"""
| python | {
"resource": ""
} |
q31265 | Query.generate_patches | train | def generate_patches(self):
"""
Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor.
"""
start_pos = self.start_posit... | python | {
"resource": ""
} |
q31266 | Query._walk_directory | train | def _walk_directory(root_directory):
"""
Generates the paths of all files that are ancestors
of `root_directory`.
"""
paths = [os.path.join(root, name)
| python | {
"resource": ""
} |
q31267 | matches_extension | train | def matches_extension(path, extension):
"""
Returns True if path has the given extension, or if
the last path component matches the extension. Supports
Unix glob matching.
>>> matches_extension("./www/profile.php", "php")
True
>>> matches_extension("./scripts/menu.js", "html")
| python | {
"resource": ""
} |
q31268 | path_filter | train | def path_filter(extensions, exclude_paths=None):
"""
Returns a function that returns True if a filepath is acceptable.
@param extensions An array of strings. Specifies what file
extensions should be accepted by the
filter. If None, we default to the U... | python | {
"resource": ""
} |
q31269 | _terminal_use_capability | train | def _terminal_use_capability(capability_name):
"""
If the terminal supports the given capability, output it. Return whether
it was output.
"""
curses.setupterm()
| python | {
"resource": ""
} |
q31270 | Countries.get_option | train | def get_option(self, option):
"""
Get a configuration option, trying the options attribute first and
falling back to a Django project setting.
"""
value = getattr(self, option, None)
if value | python | {
"resource": ""
} |
q31271 | Countries.countries | train | def countries(self):
"""
Return the a dictionary of countries, modified by any overriding
options.
The result is cached so future lookups are less work intensive.
"""
if not hasattr(self, "_countries"):
only = self.get_option("only")
if only:
... | python | {
"resource": ""
} |
q31272 | Countries.translate_pair | train | def translate_pair(self, code):
"""
Force a country to the current activated translation.
:returns: ``CountryTuple(code, translated_country_name)`` namedtuple
"""
name = self.countries[code]
if code in self.OLD_NAMES:
# Check if there's an older translation a... | python | {
"resource": ""
} |
q31273 | Countries.alpha2 | train | def alpha2(self, code):
"""
Return the two letter country code when passed any type of ISO 3166-1
country code.
If no match is found, returns an empty string.
"""
code = force_text(code).upper()
if code.isdigit():
lookup_code = int(code)
... | python | {
"resource": ""
} |
q31274 | Countries.name | train | def name(self, code):
"""
Return the name of a country, based on the code.
If no match is found, returns an | python | {
"resource": ""
} |
q31275 | Countries.by_name | train | def by_name(self, country, language="en"):
"""
Fetch a country's ISO3166-1 two letter country code from its name.
An optional language parameter is also available.
Warning: This depends on the quality of the available translations.
If no match is found, returns an empty string.... | python | {
"resource": ""
} |
q31276 | Countries.alpha3 | train | def alpha3(self, code):
"""
Return the ISO 3166-1 three letter country code matching the provided
country code.
If no match is found, returns an empty string.
"""
code | python | {
"resource": ""
} |
q31277 | Countries.numeric | train | def numeric(self, code, padded=False):
"""
Return the ISO 3166-1 numeric country code matching the provided
country code.
If no match is found, returns ``None``.
:param padded: Pass ``True`` to return a 0-padded three character
string, otherwise an integer will be r... | python | {
"resource": ""
} |
q31278 | LazyChoicesMixin.choices | train | def choices(self):
"""
When it's time to get the choices, if it was a lazy then figure it out
now and memoize the result.
| python | {
"resource": ""
} |
q31279 | check_ioc_countries | train | def check_ioc_countries(verbosity=1):
"""
Check if all IOC codes map to ISO codes correctly
"""
from django_countries.data import COUNTRIES
if verbosity: # pragma: no cover
print("Checking if all IOC codes map correctly")
for key in ISO_TO_IOC:
| python | {
"resource": ""
} |
q31280 | self_generate | train | def self_generate(output_filename, filename="iso3166-1.csv"): # pragma: no cover
"""
The following code can be used for self-generation of this file.
It requires a UTF-8 CSV file containing the short ISO name and two letter
country code as the first two columns.
"""
import csv
import re
... | python | {
"resource": ""
} |
q31281 | LazyChoicesMixin._set_choices | train | def _set_choices(self, value):
"""
Also update the widget's choices.
"""
super(LazyChoicesMixin, | python | {
"resource": ""
} |
q31282 | CountryField.deconstruct | train | def deconstruct(self):
"""
Remove choices from deconstructed field, as this is the country list
and not user editable.
Not including the ``blank_label`` property, as this isn't database
related.
"""
name, path, args, kwargs = super(CountryField, self).deconstruct... | python | {
"resource": ""
} |
q31283 | CountryField.validate | train | def validate(self, value, model_instance):
"""
Use custom validation for when using a multiple countries field.
"""
if not self.multiple:
return super(CountryField, self).validate(value, model_instance)
if not self.editable:
# Skip validation for non-edit... | python | {
"resource": ""
} |
q31284 | CountryField.value_to_string | train | def value_to_string(self, obj):
"""
Ensure data is serialized correctly.
"""
| python | {
"resource": ""
} |
q31285 | _pquery | train | def _pquery(scheduler, data, ndata, ndim, leafsize,
x, nx, d, i, k, eps, p, dub, ierr):
"""
Function that parallelly queries the K-D tree based on chunks of data returned by the scheduler
"""
try:
_data = shmem_as_nparray(data).reshape((ndata, ndim))
_x = shmem_as_nparray(x).... | python | {
"resource": ""
} |
q31286 | cKDTree_MP.pquery | train | def pquery(self, x_list, k=1, eps=0, p=2,
distance_upper_bound=np.inf):
"""
Function to parallelly query the K-D Tree
"""
x = np.array(x_list)
nx, mx = x.shape
shmem_x = mp.Array(ctypes.c_double, nx*mx)
shmem_d = mp.Array(ctypes.c_double, nx*k)
... | python | {
"resource": ""
} |
q31287 | singleton | train | def singleton(cls):
"""
Function to get single instance of the RGeocoder class
"""
instances = {}
def getinstance(**kwargs):
"""
Creates a new RGeocoder instance if not created already
"""
| python | {
"resource": ""
} |
q31288 | rel_path | train | def rel_path(filename):
"""
Function that gets relative path to the filename
"""
| python | {
"resource": ""
} |
q31289 | get | train | def get(geo_coord, mode=2, verbose=True):
"""
Function to query for a single coordinate
"""
if not isinstance(geo_coord, tuple) | python | {
"resource": ""
} |
q31290 | search | train | def search(geo_coords, mode=2, verbose=True):
"""
Function to query for a list of coordinates
"""
if not isinstance(geo_coords, tuple) and not isinstance(geo_coords, list):
raise TypeError('Expecting a tuple or a tuple/list of tuples') | python | {
"resource": ""
} |
q31291 | Printer.art_msg | train | def art_msg(self, arttag, colorname, file=sys.stdout):
"""Wrapper for easy emission of the calendar borders"""
| python | {
"resource": ""
} |
q31292 | GoogleCalendarInterface._cal_monday | train | def _cal_monday(self, day_num):
"""Shift the day number if we're doing cal monday, or cal_weekend is
false, since that also means we're starting on day 1
"""
| python | {
"resource": ""
} |
q31293 | GoogleCalendarInterface.QuickAddEvent | train | def QuickAddEvent(self, event_text, reminders=None):
"""Wrapper around Google Calendar API's quickAdd"""
if not event_text:
raise GcalcliError('event_text is required for a quickAdd')
if len(self.cals) != 1:
# TODO: get a better name for this exception class
... | python | {
"resource": ""
} |
q31294 | GoogleCalendarInterface.Remind | train | def Remind(self, minutes, command, use_reminders=False):
"""
Check for events between now and now+minutes.
If use_reminders then only remind if now >= event['start'] - reminder
"""
# perform a date query for now + minutes + slip
start = self.now
end = (start + t... | python | {
"resource": ""
} |
q31295 | color_validator | train | def color_validator(input_str):
"""
A filter allowing only the particular colors used by the Google Calendar
API
Raises ValidationError otherwise.
"""
try:
assert input_str in VALID_OVERRIDE_COLORS + ['']
return input_str
except AssertionError:
raise ValidationError(... | python | {
"resource": ""
} |
q31296 | reminder_validator | train | def reminder_validator(input_str):
"""
Allows a string that matches utils.REMINDER_REGEX.
Raises ValidationError otherwise.
"""
match = re.match(REMINDER_REGEX, input_str)
| python | {
"resource": ""
} |
q31297 | BaseAPI.registration_id_chunks | train | def registration_id_chunks(self, registration_ids):
"""
Splits registration ids in several lists of max 1000 registration ids per list
Args:
registration_ids (list): FCM device registration ID
Yields:
generator: list including lists with registration ids
... | python | {
"resource": ""
} |
q31298 | BaseAPI.json_dumps | train | def json_dumps(self, data):
"""
Standardized json.dumps function with separators and sorted keys set
Args:
data (dict or list): data to be dumped
| python | {
"resource": ""
} |
q31299 | BaseAPI.registration_info_request | train | def registration_info_request(self, registration_id):
"""
Makes a request for registration info and returns the response object
Args:
registration_id: id to be checked
Returns:
response of registration info request
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.