INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Launches a new menu. Wraps curses nicely so exceptions won t screw with the terminal too much. | def launch(title, items, selected=None):
"""
Launches a new menu. Wraps curses nicely so exceptions won't screw with
the terminal too much.
"""
resp = {"code": -1, "done": False}
curses.wrapper(Menu, title, items, selected, resp)
return resp |
Numerically solved trajectory function for initial conditons: math: q ( 0 ) = q_0 and: math: q ( 0 ) = 0. | def q(self, x, q0):
"""
Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.
"""
y1_0 = q0
y0_0 = 0
y0 = [y0_0, y1_0]
y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.at... |
Overridden method that handles that re - ranking of objects and the integrity of the rank field. | def save(self, *args, **kwargs):
"""Overridden method that handles that re-ranking of objects and the
integrity of the ``rank`` field.
:param rerank:
Added parameter, if True will rerank other objects based on the
change in this save. Defaults to True.
"""
... |
Removes any blank ranks in the order. | def repack(self):
"""Removes any blank ranks in the order."""
items = self.grouped_filter().order_by('rank').select_for_update()
for count, item in enumerate(items):
item.rank = count + 1
item.save(rerank=False) |
Queries the database for the same object that is passed in refetching its contents and runs select_for_update () to lock the corresponding row until the next commit. | def refetch_for_update(obj):
"""Queries the database for the same object that is passed in, refetching
its contents and runs ``select_for_update()`` to lock the corresponding
row until the next commit.
:param obj:
Object to refetch
:returns:
Refreshed version of the object
"""
... |
Returns the field names of a Django model object. | def get_field_names(obj, ignore_auto=True, ignore_relations=True,
exclude=[]):
"""Returns the field names of a Django model object.
:param obj: the Django model class or object instance to get the fields
from
:param ignore_auto: ignore any fields of type AutoField. Defaults to True
:pa... |
Works like getattr () but supports django s double underscore object dereference notation. | def get_obj_attr(obj, attr):
"""Works like getattr() but supports django's double underscore object
dereference notation.
Example usage:
.. code-block:: python
>>> get_obj_attr(book, 'writer__age')
42
>>> get_obj_attr(book, 'publisher__address')
<Address object at 105a... |
Returns a list of strings describing the full paths and patterns along with the name of the urls. Example: | def as_list(self):
"""Returns a list of strings describing the full paths and patterns
along with the name of the urls. Example:
.. code-block::python
>>> u = URLTree()
>>> u.as_list()
[
'admin/',
'admin/$, name=index',
... |
Register all HTTP error code error handlers | def register(
app):
"""
Register all HTTP error code error handlers
Currently, errors are handled by the JSON error handler.
"""
# Pick a handler based on the requested format. Currently we assume the
# caller wants JSON.
error_handler = json.http_exception_error_handler
@app... |
Plots but automatically resizes x axis. | def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to... |
Create a vector of values over an interval with a specified step size. | def linspacestep(start, stop, step=1):
"""
Create a vector of values over an interval with a specified step size.
Parameters
----------
start : float
The beginning of the interval.
stop : float
The end of the interval.
step : float
The step size.
Returns
--... |
Sets up logging to * filename *. debug. log * filename *. log and the terminal. * indent_offset * attempts to line up the lowest indent level to 0. Custom levels: | def mylogger(name=None, filename=None, indent_offset=7, level=_logging.DEBUG, stream_level=_logging.WARN, file_level=_logging.INFO):
"""
Sets up logging to *filename*.debug.log, *filename*.log, and the terminal. *indent_offset* attempts to line up the lowest indent level to 0. Custom levels:
* *level*: Par... |
Passes the selected course as the first argument to func. | def selected_course(func):
"""
Passes the selected course as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
course = Course.get_selected()
return func(course, *args, **kwargs)
return inner |
Passes the selected exercise as the first argument to func. | def selected_exercise(func):
"""
Passes the selected exercise as the first argument to func.
"""
@wraps(func)
def inner(*args, **kwargs):
exercise = Exercise.get_selected()
return func(exercise, *args, **kwargs)
return inner |
If func returns False the program exits immediately. | def false_exit(func):
"""
If func returns False the program exits immediately.
"""
@wraps(func)
def inner(*args, **kwargs):
ret = func(*args, **kwargs)
if ret is False:
if "TMC_TESTING" in os.environ:
raise TMCExit()
else:
sys.e... |
Configure tmc. py to use your account. | def configure(server=None, username=None, password=None, tid=None, auto=False):
"""
Configure tmc.py to use your account.
"""
if not server and not username and not password and not tid:
if Config.has():
if not yn_prompt("Override old configuration", False):
return Fa... |
Download the exercises from the server. | def download(course, tid=None, dl_all=False, force=False, upgradejava=False,
update=False):
"""
Download the exercises from the server.
"""
def dl(id):
download_exercise(Exercise.get(Exercise.tid == id),
force=force,
update_java=u... |
Go to the next exercise. | def skip(course, num=1):
"""
Go to the next exercise.
"""
sel = None
try:
sel = Exercise.get_selected()
if sel.course.tid != course.tid:
sel = None
except NoExerciseSelected:
pass
if sel is None:
sel = course.exercises.first()
else:
tr... |
Spawns a process with command path - of - exercise | def run(exercise, command):
"""
Spawns a process with `command path-of-exercise`
"""
Popen(['nohup', command, exercise.path()], stdout=DEVNULL, stderr=DEVNULL) |
Select a course or an exercise. | def select(course=False, tid=None, auto=False):
"""
Select a course or an exercise.
"""
if course:
update(course=True)
course = None
try:
course = Course.get_selected()
except NoCourseSelected:
pass
ret = {}
if not tid:
... |
Submit the selected exercise to the server. | def submit(course, tid=None, pastebin=False, review=False):
"""
Submit the selected exercise to the server.
"""
if tid is not None:
return submit_exercise(Exercise.byid(tid),
pastebin=pastebin,
request_review=review)
else:
... |
Sends the selected exercise to the TMC pastebin. | def paste(tid=None, review=False):
"""
Sends the selected exercise to the TMC pastebin.
"""
submit(pastebin=True, tid=tid, review=False) |
Lists all of the exercises in the current course. | def list_all(course, single=None):
"""
Lists all of the exercises in the current course.
"""
def bs(val):
return "●" if val else " "
def bc(val):
return as_success("✔") if val else as_error("✘")
def format_line(exercise):
return "{0} │ {1} │ {2} │ {3} │ {4}".format(exe... |
Update the data of courses and or exercises from server. | def update(course=False):
"""
Update the data of courses and or exercises from server.
"""
if course:
with Spinner.context(msg="Updated course metadata.",
waitmsg="Updating course metadata."):
for course in api.get_courses():
old = None
... |
Determine the type of x | def determine_type(x):
"""Determine the type of x"""
types = (int, float, str)
_type = filter(lambda a: is_type(a, x), types)[0]
return _type(x) |
map for a directory | def dmap(fn, record):
"""map for a directory"""
values = (fn(v) for k, v in record.items())
return dict(itertools.izip(record, values)) |
Apply the types on the elements of the line | def apply_types(use_types, guess_type, line):
"""Apply the types on the elements of the line"""
new_line = {}
for k, v in line.items():
if use_types.has_key(k):
new_line[k] = force_type(use_types[k], v)
elif guess_type:
new_line[k] = determine_type(v)
else:
... |
Read a CSV file Usage ----- >>> data = read_csv ( filename delimiter = delimiter skip = skip guess_type = guess_type has_header = True use_types = {} ) | def read_csv(filename, delimiter=",", skip=0, guess_type=True, has_header=True, use_types={}):
"""Read a CSV file
Usage
-----
>>> data = read_csv(filename, delimiter=delimiter, skip=skip,
guess_type=guess_type, has_header=True, use_types={})
# Use specific types
>>> types = {"... |
Write the data to the specified filename Usage ----- >>> write_csv ( filename header data mode = mode ) | def write_csv(filename, header, data=None, rows=None, mode="w"):
"""Write the data to the specified filename
Usage
-----
>>> write_csv(filename, header, data, mode=mode)
Parameters
----------
filename : str
The name of the file
header : list of strings
The names of... |
Convert a file to a. csv file | def format_to_csv(filename, skiprows=0, delimiter=""):
"""Convert a file to a .csv file"""
if not delimiter:
delimiter = "\t"
input_file = open(filename, "r")
if skiprows:
[input_file.readline() for _ in range(skiprows)]
new_filename = os.path.splitext(filename)[0] + ".csv"
o... |
Save the figure * fig * ( optional if not specified latest figure in focus ) to * filename * in the path * path * with extension * ext *. | def savefig(filename, path="figs", fig=None, ext='eps', verbose=False, **kwargs):
"""
Save the figure *fig* (optional, if not specified, latest figure in focus) to *filename* in the path *path* with extension *ext*.
*\*\*kwargs* is passed to :meth:`matplotlib.figure.Figure.savefig`.
"""
filename ... |
Returns a link to the django admin change list with a filter set to only the object given. | def admin_obj_link(obj, display=''):
"""Returns a link to the django admin change list with a filter set to
only the object given.
:param obj:
Object to create the admin change list display link for
:param display:
Text to display in the link. Defaults to string call of the object
... |
A safe version of: func: utils. get_obj_attr that returns and empty string in the case of an exception or an empty object | def admin_obj_attr(obj, attr):
"""A safe version of :func:``utils.get_obj_attr`` that returns and empty
string in the case of an exception or an empty object
"""
try:
field_obj = get_obj_attr(obj, attr)
if not field_obj:
return ''
except AttributeError:
return ''
... |
Returns string representation of an object either the default or based on the display template passed in. | def _obj_display(obj, display=''):
"""Returns string representation of an object, either the default or based
on the display template passed in.
"""
result = ''
if not display:
result = str(obj)
else:
template = Template(display)
context = Context({'obj':obj})
res... |
This method dynamically creates a mixin to be used with your: class: ModelAdmin classes. The mixin provides utility methods that can be referenced in side of the admin object s list_display and other similar attributes.: param name: Each usage of the mixin must be given a unique name for the mixin class being created: ... | def make_admin_obj_mixin(name):
"""This method dynamically creates a mixin to be used with your
:class:`ModelAdmin` classes. The mixin provides utility methods that can
be referenced in side of the admin object's ``list_display`` and other
similar attributes.
:param name:
Each usage o... |
Returns a new copy of a: class: FancyModelAdmin class ( a class not an instance! ). This can then be inherited from when declaring a model admin class. The: class: FancyModelAdmin class has additional methods for managing the list_display attribute. | def fancy_modeladmin(*args):
"""Returns a new copy of a :class:`FancyModelAdmin` class (a class, not
an instance!). This can then be inherited from when declaring a model
admin class. The :class:`FancyModelAdmin` class has additional methods
for managing the ``list_display`` attribute.
:param ``*ar... |
Adds a list_display property without any extra wrappers similar to: func: add_displays but can also change the title. | def add_display(cls, attr, title=''):
"""Adds a ``list_display`` property without any extra wrappers,
similar to :func:`add_displays`, but can also change the title.
:param attr:
Name of the attribute to add to the display
:param title:
Title for the column of t... |
Adds a list_display attribute that appears as a link to the django admin change page for the type of object being shown. Supports double underscore attribute name dereferencing. | def add_link(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute that appears as a link to the
django admin change page for the type of object being shown. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to deref... |
Adds a list_display attribute showing an object. Supports double underscore attribute name dereferencing. | def add_object(cls, attr, title='', display=''):
"""Adds a ``list_display`` attribute showing an object. Supports
double underscore attribute name dereferencing.
:param attr:
Name of the attribute to dereference from the corresponding
object, i.e. what will be lined to.... |
Adds a list_display attribute showing a field in the object using a python %formatted string. | def add_formatted_field(cls, field, format_string, title=''):
"""Adds a ``list_display`` attribute showing a field in the object
using a python %formatted string.
:param field:
Name of the field in the object.
:param format_string:
A old-style (to remain python ... |
View decorator that enforces that the method was called using POST. This decorator can be called with or without parameters. As it is expected to wrap a view the first argument of the method being wrapped is expected to be a request object. | def post_required(method_or_options=[]):
"""View decorator that enforces that the method was called using POST.
This decorator can be called with or without parameters. As it is
expected to wrap a view, the first argument of the method being wrapped is
expected to be a ``request`` object.
.. code-... |
View decorator that enforces that the method was called using POST and contains a field containing a JSON dictionary. This method should only be used to wrap views and assumes the first argument of the method being wrapped is a request object. | def json_post_required(*decorator_args):
"""View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code... |
Creates a histogram of data * x * with a * bins * * labels * =: code: [ title xlabel ylabel ]. | def hist(x, bins=10, labels=None, aspect="auto", plot=True, ax=None, range=None):
"""
Creates a histogram of data *x* with a *bins*, *labels* = :code:`[title, xlabel, ylabel]`.
"""
h, edge = _np.histogram(x, bins=bins, range=range)
mids = edge + (edge[1]-edge[0])/2
mids = mids[:-1]
if... |
Spot size of matched beam: math: \\ left ( \\ frac { 2 E \\ varepsilon_0 } { n_p e^2 } \\ right ) ^ { 1/ 4 } \\ sqrt { \\ epsilon } | def sigma(self):
"""
Spot size of matched beam :math:`\\left( \\frac{2 E \\varepsilon_0 }{ n_p e^2 } \\right)^{1/4} \\sqrt{\\epsilon}`
"""
return _np.power(2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.plasma.n_p * _np.power(_spc.elementary_charge, 2)) , 0.25) * _np.sqrt(self.emit) |
Divergence of matched beam | def sigma_prime(self):
"""
Divergence of matched beam
"""
return _np.sqrt(self.emit/self.beta(self.E)) |
The plasma density in SI units. | def n_p(self):
"""
The plasma density in SI units.
"""
return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2 |
The matched: class: Plasma. | def plasma(self, species=_pt.hydrogen):
"""
The matched :class:`Plasma`.
"""
return _Plasma(self.n_p, species=species) |
Semver tag triggered deployment helper | def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags from the upstream ...')
handler = TagHandler(git.list_tags())
print_information(handler, label)
tag = handler.yield_tag(target, label)
confirm(tag) |
Performs some environment checks prior to the program s execution | def check_environment(target, label):
"""
Performs some environment checks prior to the program's execution
"""
if not git.exists():
click.secho('You must have git installed to use yld.', fg='red')
sys.exit(1)
if not os.path.isdir('.git'):
click.secho('You must cd into a git... |
Prints latest tag s information | def print_information(handler, label):
"""
Prints latest tag's information
"""
click.echo('=> Latest stable: {tag}'.format(
tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if
handler.latest_stable else 'magenta')
))
if label is not None:
... |
Prompts user before proceeding | def confirm(tag):
"""
Prompts user before proceeding
"""
click.echo()
if click.confirm('Do you want to create the tag {tag}?'.format(
tag=click.style(str(tag), fg='yellow')),
default=True, abort=True):
git.create_tag(tag)
if click.confirm(
'Do you want to pus... |
Plots an array * X * such that the first coordinate is the * x * coordinate and the second coordinate is the * y * coordinate with the origin at the bottom left corner. | def imshow(X, ax=None, add_cbar=True, rescale_fig=True, **kwargs):
"""
Plots an array *X* such that the first coordinate is the *x* coordinate and the second coordinate is the *y* coordinate, with the origin at the bottom left corner.
Optional argument *ax* allows an existing axes to be used.
*\*\*kwa... |
Given an array * X * determine a good size for the figure to be by shrinking it to fit within * figsize *. If not specified shrinks to fit the figsize specified by the current: attr: matplotlib. rcParams. | def scaled_figsize(X, figsize=None, h_pad=None, v_pad=None):
"""
Given an array *X*, determine a good size for the figure to be by shrinking it to fit within *figsize*. If not specified, shrinks to fit the figsize specified by the current :attr:`matplotlib.rcParams`.
.. versionadded:: 1.3
"""
if fi... |
Gets an array from datasets. | def get(f, key, default=None):
"""
Gets an array from datasets.
.. versionadded:: 1.4
"""
if key in f.keys():
val = f[key].value
if default is None:
return val
else:
if _np.shape(val) == _np.shape(default):
return val
return def... |
Get the current directory state | def get_state(self):
"""Get the current directory state"""
return [os.path.join(dp, f)
for dp, _, fn in os.walk(self.dir)
for f in fn] |
Add one tick to progress bar | def tick(self):
"""Add one tick to progress bar"""
self.current += 1
if self.current == self.factor:
sys.stdout.write('+')
sys.stdout.flush()
self.current = 0 |
Push k to the top of the list | def push(self, k):
"""Push k to the top of the list
>>> l = DLL()
>>> l.push(1)
>>> l
[1]
>>> l.push(2)
>>> l
[2, 1]
>>> l.push(3)
>>> l
[3, 2, 1]
"""
if not self._first:
# first item
self._f... |
>>> l = DLL () >>> l. push ( 1 ) >>> l [ 1 ] >>> l. size () 1 >>> l. deletenode ( l. _first ) >>> l [] >>> l. size () 0 >>> l. _index {} >>> l. _first | def deletenode(self, node):
"""
>>> l = DLL()
>>> l.push(1)
>>> l
[1]
>>> l.size()
1
>>> l.deletenode(l._first)
>>> l
[]
>>> l.size()
0
>>> l._index
{}
>>> l._first
"""
if self._last =... |
>>> l = DLL () >>> l. push ( 1 ) >>> l. pop () 1 | def pop(self):
"""
>>> l = DLL()
>>> l.push(1)
>>> l.pop()
1
"""
k = self._last.value
self.deletenode(self._last)
return k |
Call this method to increment the named counter. This is atomic on the database. | def increment(cls, name):
"""Call this method to increment the named counter. This is atomic on
the database.
:param name:
Name for a previously created ``Counter`` object
"""
with transaction.atomic():
counter = Counter.objects.select_for_update().get(... |
Return axes: code: x y for * array * to be used with: func: matplotlib. pyplot. color. | def pcolor_axes(array, px_to_units=px_to_units):
"""
Return axes :code:`x, y` for *array* to be used with :func:`matplotlib.pyplot.color`.
*px_to_units* is a function to convert pixels to units. By default, returns pixels.
"""
# ======================================
# Coords need to be +1 larg... |
On - axis beam density: math: n_ { b 0 }. | def nb0(self):
"""
On-axis beam density :math:`n_{b,0}`.
"""
return self.N_e / ( (2*_np.pi)**(3/2) * self.sig_r**2 * self.sig_xi) |
The wavelength for large (: math: r_0 < \\ sigma_r ) oscillations. | def lambda_large(self, r0):
"""
The wavelength for large (:math:`r_0 < \\sigma_r`) oscillations.
"""
return 2*_np.sqrt(2*_np.pi/self.k)*r0 |
Approximate trajectory function for small (: math: r_0 < \\ sigma_r ) oscillations. | def r_small(self, x, r0):
"""
Approximate trajectory function for small (:math:`r_0 < \\sigma_r`) oscillations.
"""
return r0*_np.cos(_np.sqrt(self.k_small) * x) |
Approximate trajectory function for large (: math: r_0 > \\ sigma_r ) oscillations. | def r_large(self, x, r0):
"""
Approximate trajectory function for large (:math:`r_0 > \\sigma_r`) oscillations.
"""
return r0*_np.cos(x*self.omega_big(r0)) |
Driving force term:: math: r = - k \\ left ( \\ frac { 1 - e^ { - r^2/ 2 { \\ sigma_r } ^2 }} { r } \\ right ) | def k(self):
"""
Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)`
"""
try:
return self._k
except AttributeError:
self._k = e**2 * self.N_e / ( (2*_np.pi)**(5/2) * e0 * self.m * c**2 * self.sig_xi)
retur... |
print loading message on screen | def print_loading(self, wait, message):
"""
print loading message on screen
.. note::
loading message only write to `sys.stdout`
:param int wait: seconds to wait
:param str message: message to print
:return: None
"""
tags = ['\\', '|', '/',... |
print warn type message if file handle is sys. stdout print color message | def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."):
"""
print warn type message,
if file handle is `sys.stdout`, print color message
:param str message: message to print
:param file fh: file handle,default is `sys.stdout`
:param str prefix: message... |
print error type message if file handle is sys. stderr print color message | def error_message(self, message, fh=None, prefix="[error]:",
suffix="..."):
"""
print error type message
if file handle is `sys.stderr`, print color message
:param str message: message to print
:param file fh: file handle, default is `sys.stdout`
:p... |
a built - in wrapper make dry - run easier. you should use this instead use os. system | def system(self, cmd, fake_code=False):
"""
a built-in wrapper make dry-run easier.
you should use this instead use `os.system`
.. note::
to use it,you need add '--dry-run' option in
your argparser options
:param str cmd: command to execute
:pa... |
.. warning:: | def load_resource(path, root=''):
"""
.. warning::
Experiment feature.
BE CAREFUL! WE MAY REMOVE THIS FEATURE!
load resource file which in package.
this method is used to load file easier in different environment.
e.g:
consume we have a file ... |
.. warning:: | def load_description(name, root=''):
"""
.. warning::
Experiment feature.
BE CAREFUL! WE MAY REMOVE THIS FEATURE!
Load resource file as description,
if resource file not exist,will return empty string.
:param str path: name resource path
:para... |
Returns the name of the Firebase. If a Firebase instance points to https:// my_firebase. firebaseio. com/ users its name would be users | def name(self):
'''
Returns the name of the Firebase. If a Firebase instance points to
'https://my_firebase.firebaseio.com/users' its name would be 'users'
'''
i = self.__url.rfind('/')
if self.__url[:i] == 'https:/':
return "/"
return self.__url[i+1:] |
Returns a Corrected URL to be used for a Request as per the REST API. | def url_correct(self, point, auth=None, export=None):
'''
Returns a Corrected URL to be used for a Request
as per the REST API.
'''
newUrl = self.__url + point + '.json'
if auth or export:
newUrl += "?"
if auth:
newUrl += ("auth=" + auth)
... |
Reads a File with contents in correct JSON format. Returns the data as Python objects. path - ( string ) path to the file | def __read(path):
'''
Reads a File with contents in correct JSON format.
Returns the data as Python objects.
path - (string) path to the file
'''
try:
with open(path, 'r') as data_file:
data = data_file.read()
data = json.loads(... |
Writes to a File. Returns the data written. path - ( string ) path to the file to write to. data - ( json ) data from a request. mode - ( string ) mode to open the file in. Default to w. Overwrites. | def __write(path, data, mode="w"):
'''
Writes to a File. Returns the data written.
path - (string) path to the file to write to.
data - (json) data from a request.
mode - (string) mode to open the file in. Default to 'w'. Overwrites.
'''
with open(path, mode) as d... |
Requires the User to provide a certain parameter for the method to function properly. Else an Exception is raised. args - ( tuple ) arguments you are looking for. argv - ( dict ) arguments you have received and want to inspect. | def amust(self, args, argv):
'''
Requires the User to provide a certain parameter
for the method to function properly.
Else, an Exception is raised.
args - (tuple) arguments you are looking for.
argv - (dict) arguments you have received and want to inspect.
'''
... |
Checks for Errors in a Response. 401 or 403 - Security Rules Violation. 404 or 417 - Firebase NOT Found. response - ( Request. Response ) - response from a request. | def catch_error(response):
'''
Checks for Errors in a Response.
401 or 403 - Security Rules Violation.
404 or 417 - Firebase NOT Found.
response - (Request.Response) - response from a request.
'''
status = response.status_code
if status == 401 or status ==... |
GET: gets data from the Firebase. Requires the point parameter as a keyworded argument. | def get_sync(self, **kwargs):
'''
GET: gets data from the Firebase.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point",), kwargs)
response = requests.get(self.url_correct(kwargs["point"],
kwargs.get("auth", sel... |
PUT: puts data into the Firebase. Requires the point parameter as a keyworded argument. | def put_sync(self, **kwargs):
'''
PUT: puts data into the Firebase.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point", "data"), kwargs)
response = requests.put(self.url_correct(kwargs["point"],
kwargs.get("aut... |
POST: post data to a Firebase. Requires the point parameter as a keyworded argument. Note: Firebase will give it a randomized key and the data will be the value. Thus a key - value pair | def post_sync(self, **kwargs):
'''
POST: post data to a Firebase.
Requires the 'point' parameter as a keyworded argument.
Note: Firebase will give it a randomized "key"
and the data will be the "value". Thus a key-value pair
'''
self.amust(("point", "data"), kwar... |
UPDATE: updates data in the Firebase. Requires the point parameter as a keyworded argument. | def update_sync(self, **kwargs):
'''
UPDATE: updates data in the Firebase.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point", "data"), kwargs)
# Sending the 'PATCH' request
response = requests.patch(self.url_correct(
kwarg... |
DELETE: delete data in the Firebase. Requires the point parameter as a keyworded argument. | def delete_sync(self, **kwargs):
'''
DELETE: delete data in the Firebase.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point",), kwargs)
response = requests.delete(self.url_correct(
kwargs["point"],
kwargs.get("auth", se... |
EXPORT: exports data from the Firebase into a File if given. Requires the point parameter as a keyworded argument. | def export_sync(self, **kwargs):
'''
EXPORT: exports data from the Firebase into a File, if given.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point",), kwargs)
response = requests.get(self.url_correct(kwargs["point"],
... |
Provide. __super in python 2. x classes without having to specify the current class name each time super is used ( DRY principle ). | def superable(cls) :
'''Provide .__super in python 2.x classes without having to specify the current
class name each time super is used (DRY principle).'''
name = cls.__name__
super_name = '_%s__super' % (name,)
setattr(cls,super_name,super(cls))
return cls |
Main method. | def main():
"""
Main method.
This method holds what you want to execute when
the script is run on command line.
"""
args = get_arguments()
setup_logging(args)
version_path = os.path.abspath(os.path.join(
os.path.dirname(__file__),
'..',
'..',
'.VERSION'
... |
Validates a Firebase URL. A valid URL must exhibit: - Protocol must be HTTPS - Domain Must be firebaseio. com - firebasename can only contain: - hyphen small and capital letters - firebasename can not have leading and trailing hyphens - childnames can not contain: - period dollar sign square brackets pound - ASCII Cont... | def valid_url(name):
'''
Validates a Firebase URL. A valid URL must exhibit:
- Protocol must be HTTPS
- Domain Must be firebaseio.com
- firebasename can only contain:
- hyphen, small and capital letters
- firebasename can not have leading and trailing hyphens
- childnames can not c... |
Pickle and compress. | def pickle(obj, filepath):
"""Pickle and compress."""
arr = pkl.dumps(obj, -1)
with open(filepath, 'wb') as f:
s = 0
while s < len(arr):
e = min(s + blosc.MAX_BUFFERSIZE, len(arr))
carr = blosc.compress(arr[s:e], typesize=8)
f.write(carr)
s = e |
Decompress and unpickle. | def unpickle(filepath):
"""Decompress and unpickle."""
arr = []
with open(filepath, 'rb') as f:
carr = f.read(blosc.MAX_BUFFERSIZE)
while len(carr) > 0:
arr.append(blosc.decompress(carr))
carr = f.read(blosc.MAX_BUFFERSIZE)
return pkl.loads(b"".join(arr)) |
Displays the contact form and sends the email | def contact(request):
"""Displays the contact form and sends the email"""
form = ContactForm(request.POST or None)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_d... |
try use gitconfig info. author email etc. | def load_gitconfig(self):
"""
try use gitconfig info.
author,email etc.
"""
gitconfig_path = os.path.expanduser('~/.gitconfig')
if os.path.exists(gitconfig_path):
parser = Parser()
parser.read(gitconfig_path)
parser.sections()
... |
render template string to user string: param str match_string: template string syntax: ___VAR___: param str new_string: user string: return: | def render(self, match_string, new_string):
"""
render template string to user string
:param str match_string: template string,syntax: '___VAR___'
:param str new_string: user string
:return:
"""
current_dir = self.options.dir
# safe check,we don't allow ... |
Init project. | def add_arguments(cls):
"""
Init project.
"""
return [
(('--yes',), dict(action='store_true', help='clean .git repo')),
(('--variable', '-s'),
dict(nargs='+', help='set extra variable,format is name:value')),
(('--skip-builtin',),
... |
设置信号处理 | def set_signal(self):
"""
设置信号处理
默认直接中断,考虑到一些场景用户需要等待线程结束.
可在此自定义操作
:return:
"""
def signal_handle(signum, frame):
self.error("User interrupt.kill threads.")
sys.exit(-1)
pass
signal.signal(signal.SIGINT, signal_hand... |
检查是否是独占模式 | def check_exclusive_mode(self):
"""
检查是否是独占模式
参数顺序必须一致,也就是说如果参数顺序不一致,则判定为是两个不同的进程
这么设计是考虑到:
- 一般而言,排他模式的服务启动都是crontab等脚本来完成的,不存在顺序变更的可能
- 这在调试的时候可以帮助我们不需要结束原有进程就可以继续调试
:return:
"""
if self.options.exclusive_mode:
import psutil
... |
In general you don t need to overwrite this method. | def run(self, options):
"""
In general, you don't need to overwrite this method.
:param options:
:return:
"""
self.set_signal()
self.check_exclusive_mode()
slot = self.Handle(self)
# start thread
i = 0
while i < options.threads:... |
Returns ------- pandas. DataFrame Table of serial ports that match the USB vendor ID and product ID for the Teensy 3. 2 _ board. | def serial_ports():
'''
Returns
-------
pandas.DataFrame
Table of serial ports that match the USB vendor ID and product ID for
the `Teensy 3.2`_ board.
.. Teensy 3.2: https://www.pjrc.com/store/teensy32.html
'''
df_comports = sd.comports()
# Match COM ports with USB vend... |
Return a new filename to use as the combined file name for a bunch of files based on the SHA of their contents. A precondition is that they all have the same file extension | def combine_filenames(filenames, max_length=40):
"""Return a new filename to use as the combined file name for a
bunch of files, based on the SHA of their contents.
A precondition is that they all have the same file extension
Given that the list of files can have different paths, we aim to use the
... |
Extract the oritentation EXIF tag from the image which should be a PIL Image instance and if there is an orientation tag that would rotate the image apply that rotation to the Image instance given to do an in - place rotation. | def apply_orientation(im):
"""
Extract the oritentation EXIF tag from the image, which should be a PIL Image instance,
and if there is an orientation tag that would rotate the image, apply that rotation to
the Image instance given to do an in-place rotation.
:param Image im: Image instance to inspe... |
Start a new piece | def write():
"""Start a new piece"""
click.echo("Fantastic. Let's get started. ")
title = click.prompt("What's the title?")
# Make sure that title doesn't exist.
url = slugify(title)
url = click.prompt("What's the URL?", default=url)
# Make sure that title doesn't exist.
click.echo("Go... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.