text stringlengths 81 112k |
|---|
Send a dweet to dweet.io for a thing with a known name
def dweet_for(thing_name, payload, key=None, session=None):
"""Send a dweet to dweet.io for a thing with a known name
"""
if key is not None:
params = {'key': key}
else:
params = None
return _send_dweet(payload, '/dweet/for/{0}'... |
Read all the dweets for a dweeter
def get_dweets_for(thing_name, key=None, session=None):
"""Read all the dweets for a dweeter
"""
if key is not None:
params = {'key': key}
else:
params = None
return _request('get', '/get/dweets/for/{0}'.format(thing_name), params=params, session=No... |
Remove a lock (no matter what it's connected to).
def remove_lock(lock, key, session=None):
"""Remove a lock (no matter what it's connected to).
"""
return _request('get', '/remove/lock/{0}'.format(lock), params={'key': key}, session=session) |
Lock a thing (prevents unauthed dweets for the locked thing)
def lock(thing_name, lock, key, session=None):
"""Lock a thing (prevents unauthed dweets for the locked thing)
"""
return _request('get', '/lock/{0}'.format(thing_name), params={'key': key, 'lock': lock}, session=session) |
Unlock a thing
def unlock(thing_name, key, session=None):
"""Unlock a thing
"""
return _request('get', '/unlock/{0}'.format(thing_name), params={'key': key}, session=session) |
Set an alert on a thing with the given condition
def set_alert(thing_name, who, condition, key, session=None):
"""Set an alert on a thing with the given condition
"""
return _request('get', '/alert/{0}/when/{1}/{2}'.format(
','.join(who),
thing_name,
quote(condition),
), params=... |
Set an alert on a thing with the given condition
def get_alert(thing_name, key, session=None):
"""Set an alert on a thing with the given condition
"""
return _request('get', '/get/alert/for/{0}'.format(thing_name), params={'key': key}, session=session) |
Remove an alert for the given thing
def remove_alert(thing_name, key, session=None):
"""Remove an alert for the given thing
"""
return _request('get', '/remove/alert/for/{0}'.format(thing_name), params={'key': key}, session=session) |
list all product sets for current user
def get_product_sets(self):
"""
list all product sets for current user
"""
# ensure we are using api url without a specific product set id
api_url = super(ProductSetAPI, self).base_url
return self.client.get(api_url) |
BE NOTICED: this will delete all product sets for current user
def delete_all_product_sets(self):
"""
BE NOTICED: this will delete all product sets for current user
"""
# ensure we are using api url without a specific product set id
api_url = super(ProductSetAPI, self).base_url
... |
This function (and backend API) is being obsoleted. Don't use it anymore.
def get_products(self, product_ids):
"""
This function (and backend API) is being obsoleted. Don't use it anymore.
"""
if self.product_set_id is None:
raise ValueError('product_set_id must be specified... |
Check if the timeout has been reached and raise a `StopIteration` if so.
def _check_stream_timeout(started, timeout):
"""Check if the timeout has been reached and raise a `StopIteration` if so.
"""
if timeout:
elapsed = datetime.datetime.utcnow() - started
if elapsed.seconds > timeout:
... |
Yields dweets as received from dweet.io's streaming API
def _listen_for_dweets_from_response(response):
"""Yields dweets as received from dweet.io's streaming API
"""
streambuffer = ''
for byte in response.iter_content():
if byte:
streambuffer += byte.decode('ascii')
try... |
Create a real-time subscription to dweets
def listen_for_dweets_from(thing_name, timeout=900, key=None, session=None):
"""Create a real-time subscription to dweets
"""
url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name)
session = session or requests.Session()
if key is not None:
... |
curl -X POST \
-H 'x-ca-version: 1.0' \
-H 'x-ca-accesskeyid: YourAccessId' \
-d "service_id=p4dkh2sg&request_id=c13ed5aa-d6d2-11e8-ba11-02420a582a05&description=blahlblah" \
https://api.productai.cn/bad_cases/_0000204
def add(self, service_id, request_id, description=No... |
Executes a `packer build`
:param bool parallel: Run builders in parallel
:param bool debug: Run in debug mode
:param bool force: Force artifact output even if exists
:param bool machine_readable: Make output machine-readable
def build(self, parallel=True, debug=False, force=False,
... |
Implements the `packer fix` function
:param string to_file: File to output fixed template to
def fix(self, to_file=None):
"""Implements the `packer fix` function
:param string to_file: File to output fixed template to
"""
self.packer_cmd = self.packer.fix
self._add_op... |
Inspects a Packer Templates file (`packer inspect -machine-readable`)
To return the output in a readable form, the `-machine-readable` flag
is appended automatically, afterwhich the output is parsed and returned
as a dict of the following format:
"variables": [
{
... |
Implmenets the `packer push` function
UNTESTED! Must be used alongside an Atlas account
def push(self, create=True, token=False):
"""Implmenets the `packer push` function
UNTESTED! Must be used alongside an Atlas account
"""
self.packer_cmd = self.packer.push
self._ad... |
Validates a Packer Template file (`packer validate`)
If the validation failed, an `sh` exception will be raised.
:param bool syntax_only: Whether to validate the syntax only
without validating the configuration itself.
def validate(self, syntax_only=False):
"""Validates a Packer Templa... |
Appends base arguments to packer commands.
-except, -only, -var and -var-file are appeneded to almost
all subcommands in packer. As such this can be called to add
these flags to the subcommand.
def _append_base_arguments(self):
"""Appends base arguments to packer commands.
-ex... |
Parses the machine-readable output `packer inspect` provides.
See the inspect method for more info.
This has been tested vs. Packer v0.7.5
def _parse_inspection_output(self, output):
"""Parses the machine-readable output `packer inspect` provides.
See the inspect method for more info.... |
Perform an HTTP POST request for a given url.
Returns the response object.
def post(self, url, data, headers=None):
"""
Perform an HTTP POST request for a given url.
Returns the response object.
"""
return self._request('POST', url, data, headers=headers) |
Perform an HTTP PUT request for a given url.
Returns the response object.
def put(self, url, data, headers=None):
"""
Perform an HTTP PUT request for a given url.
Returns the response object.
"""
return self._request('PUT', url, data, headers=headers) |
Query a fulltext index by key and query or just a plain Lucene query,
i1 = gdb.nodes.indexes.get('people',type='fulltext', provider='lucene')
i1.query('name','do*')
i1.query('name:do*')
In this example, the last two line are equivalent.
def query(self, *args):
"""
Quer... |
Return a HTML representation for a particular QuerySequence.
Mainly for IPython Notebook.
def _plot_graph(self, graph, title=None, width=None, height=None):
"""
Return a HTML representation for a particular QuerySequence.
Mainly for IPython Notebook.
"""
if not self._ele... |
Send an HTTP request to the REST API.
:param string path: A URL
:param string method: The HTTP method (GET, POST, etc.) to use
in the request.
:param string body: A string representing any data to be sent in the
body of the HTTP request.
:param dictionary headers... |
Wrapper around http.do_call that transforms some HTTPError into
our own exceptions
def _call(self, path, method, body=None, headers=None):
"""
Wrapper around http.do_call that transforms some HTTPError into
our own exceptions
"""
try:
resp = self.http.do_call... |
Uses the aliveness-test API call to determine if the
server is alive and the vhost is active. The broker (not this code)
creates a queue and then sends/consumes a message from it.
:param string vhost: There should be no real reason to ever change
this from the default value, but it'... |
A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user name
* auth_backend: backend ... |
A convenience function for getting back only the vhost names instead of
the larger vhost dicts.
:returns list vhost_names: A list of just the vhost names.
def get_vhost_names(self):
"""
A convenience function for getting back only the vhost names instead of
the larger vhost dic... |
Returns the attributes of a single named vhost in a dict.
:param string vname: Name of the vhost to get.
:returns dict vhost: Attribute dict for the named vhost
def get_vhost(self, vname):
"""
Returns the attributes of a single named vhost in a dict.
:param string vname: Name ... |
Creates a vhost on the server to house exchanges.
:param string vname: The name to give to the vhost on the server
:returns: boolean
def create_vhost(self, vname):
"""
Creates a vhost on the server to house exchanges.
:param string vname: The name to give to the vhost on the s... |
Deletes a vhost from the server. Note that this also deletes any
exchanges or queues that belong to this vhost.
:param string vname: Name of the vhost to delete from the server.
def delete_vhost(self, vname):
"""
Deletes a vhost from the server. Note that this also deletes any
... |
:returns: list of dicts, or an empty list if there are no permissions.
def get_permissions(self):
"""
:returns: list of dicts, or an empty list if there are no permissions.
"""
path = Client.urls['all_permissions']
conns = self._call(path, 'GET')
return conns |
:returns: list of dicts, or an empty list if there are no permissions.
:param string vname: Name of the vhost to set perms on.
def get_vhost_permissions(self, vname):
"""
:returns: list of dicts, or an empty list if there are no permissions.
:param string vname: Name of the vhost to s... |
:returns: list of dicts, or an empty list if there are no permissions.
:param string username: User to set permissions for.
def get_user_permissions(self, username):
"""
:returns: list of dicts, or an empty list if there are no permissions.
:param string username: User to set permissi... |
Set permissions for a given username on a given vhost. Both
must already exist.
:param string vname: Name of the vhost to set perms on.
:param string username: User to set permissions for.
:param string config: Permission pattern for configuration operations
for this user in... |
Delete permission for a given username on a given vhost. Both
must already exist.
:param string vname: Name of the vhost to set perms on.
:param string username: User to set permissions for.
def delete_permission(self, vname, username):
"""
Delete permission for a given usernam... |
:returns: A list of dicts
:param string vhost: A vhost to query for exchanges, or None (default),
which triggers a query for all exchanges in all vhosts.
def get_exchanges(self, vhost=None):
"""
:returns: A list of dicts
:param string vhost: A vhost to query for exchanges, o... |
Gets a single exchange which requires a vhost and name.
:param string vhost: The vhost containing the target exchange
:param string name: The name of the exchange
:returns: dict
def get_exchange(self, vhost, name):
"""
Gets a single exchange which requires a vhost and name.
... |
Creates an exchange in the given vhost with the given name. As per the
RabbitMQ API documentation, a JSON body also needs to be included that
"looks something like this":
{"type":"direct",
"auto_delete":false,
"durable":true,
"internal":false,
"arguments":[]}
... |
Publish a message to an exchange.
:param string vhost: vhost housing the target exchange
:param string xname: name of the target exchange
:param string rt_key: routing key for message
:param string payload: the message body for publishing
:param string payload_enc: encoding of t... |
Delete the named exchange from the named vhost. The API returns a 204
on success, in which case this method returns True, otherwise the
error is raised.
:param string vhost: Vhost where target exchange was created
:param string name: The name of the exchange to delete.
:returns ... |
Get all queues, or all queues in a vhost if vhost is not None.
Returns a list.
:param string vhost: The virtual host to list queues for. If This is
None (the default), all queues for the broker instance
are returned.
:returns: A list of dicts, each repres... |
Get a single queue, which requires both vhost and name.
:param string vhost: The virtual host for the queue being requested.
If the vhost is '/', note that it will be translated to '%2F' to
conform to URL encoding requirements.
:param string name: The name of the queue being req... |
Get the number of messages currently in a queue. This is a convenience
function that just calls :meth:`Client.get_queue` and pulls
out/returns the 'messages' field from the dictionary it returns.
:param string vhost: The vhost of the queue being queried.
:param string name: The name o... |
Get the number of messages currently sitting in either the queue
names listed in 'names', or all queues in 'vhost' if no 'names' are
given.
:param str vhost: Vhost where queues in 'names' live.
:param list names: OPTIONAL - Specific queues to show depths for. If
None, sh... |
Purge all messages from one or more queues.
:param list queues: A list of ('qname', 'vhost') tuples.
:returns: True on success
def purge_queues(self, queues):
"""
Purge all messages from one or more queues.
:param list queues: A list of ('qname', 'vhost') tuples.
:retu... |
Purge all messages from a single queue. This is a convenience method
so you aren't forced to supply a list containing a single tuple to
the purge_queues method.
:param string vhost: The vhost of the queue being purged.
:param string name: The name of the queue being purged.
:rty... |
Create a queue. The API documentation specifies that all of the body
elements are optional, so this method only requires arguments needed
to form the URI
:param string vhost: The vhost to create the queue in.
:param string name: The name of the queue
More on these operations ca... |
Deletes the named queue from the named vhost.
:param string vhost: Vhost housing the queue to be deleted.
:param string qname: Name of the queue to delete.
Note that if you just want to delete the messages from a queue, you
should use purge_queue instead of deleting/recreating a queue.... |
Gets <count> messages from the queue.
:param string vhost: Name of vhost containing the queue
:param string qname: Name of the queue to consume from
:param int count: Number of messages to get.
:param bool requeue: Whether to requeue the message after getting it.
This will c... |
:returns: list of dicts, or an empty list if there are no connections.
def get_connections(self):
"""
:returns: list of dicts, or an empty list if there are no connections.
"""
path = Client.urls['all_connections']
conns = self._call(path, 'GET')
return conns |
Get a connection by name. To get the names, use get_connections.
:param string name: Name of connection to get
:returns dict conn: A connection attribute dictionary.
def get_connection(self, name):
"""
Get a connection by name. To get the names, use get_connections.
:param str... |
Close the named connection. The API returns a 204 on success,
in which case this method returns True, otherwise the
error is raised.
:param string name: The name of the connection to delete.
:returns bool: True on success.
def delete_connection(self, name):
"""
Close th... |
Return a list of dicts containing details about broker connections.
:returns: list of dicts
def get_channels(self):
"""
Return a list of dicts containing details about broker connections.
:returns: list of dicts
"""
path = Client.urls['all_channels']
chans = self... |
Get a channel by name. To get the names, use get_channels.
:param string name: Name of channel to get
:returns dict conn: A channel attribute dictionary.
def get_channel(self, name):
"""
Get a channel by name. To get the names, use get_channels.
:param string name: Name of cha... |
:returns: list of dicts
def get_bindings(self):
"""
:returns: list of dicts
"""
path = Client.urls['all_bindings']
bindings = self._call(path, 'GET')
return bindings |
Return a list of dicts, one dict per binding. The dict format coming
from RabbitMQ for queue named 'testq' is:
{"source":"sourceExch","vhost":"/","destination":"testq",
"destination_type":"queue","routing_key":"*.*","arguments":{},
"properties_key":"%2A.%2A"}
def get_queue_bindings(s... |
Creates a binding between an exchange and a queue on a given vhost.
:param string vhost: vhost housing the exchange/queue to bind
:param string exchange: the target exchange of the binding
:param string queue: the queue to bind to the exchange
:param string rt_key: the routing key to us... |
Deletes a binding between an exchange and a queue on a given vhost.
:param string vhost: vhost housing the exchange/queue to bind
:param string exchange: the target exchange of the binding
:param string queue: the queue to bind to the exchange
:param string rt_key: the routing key to us... |
Creates a user.
:param string username: The name to give to the new user
:param string password: Password for the new user
:param string tags: Comma-separated list of tags for the user
:returns: boolean
def create_user(self, username, password, tags=""):
"""
Creates a u... |
Deletes a user from the server.
:param string username: Name of the user to delete from the server.
def delete_user(self, username):
"""
Deletes a user from the server.
:param string username: Name of the user to delete from the server.
"""
path = Client.urls['users_by... |
Redirects to the default wiki index name.
def index(request):
"""
Redirects to the default wiki index name.
"""
kwargs = {'slug': getattr(settings, 'WAKAWAKA_DEFAULT_INDEX', 'WikiIndex')}
redirect_to = reverse('wakawaka_page', kwargs=kwargs)
return HttpResponseRedirect(redirect_to) |
Displays a wiki page. Redirects to the edit view if the page doesn't exist.
def page(
request,
slug,
rev_id=None,
template_name='wakawaka/page.html',
extra_context=None,
):
"""
Displays a wiki page. Redirects to the edit view if the page doesn't exist.
"""
try:
queryset = Wi... |
Displays the form for editing and deleting a page.
def edit(
request,
slug,
rev_id=None,
template_name='wakawaka/edit.html',
extra_context=None,
wiki_page_form=WikiPageForm,
wiki_delete_form=DeleteWikiPageForm,
):
"""
Displays the form for editing and deleting a page.
"""
# ... |
Displays the list of all revisions for a specific WikiPage
def revisions(
request, slug, template_name='wakawaka/revisions.html', extra_context=None
):
"""
Displays the list of all revisions for a specific WikiPage
"""
queryset = WikiPage.objects.all()
page = get_object_or_404(queryset, slug=sl... |
Displays the changes between two revisions.
def changes(
request, slug, template_name='wakawaka/changes.html', extra_context=None
):
"""
Displays the changes between two revisions.
"""
rev_a_id = request.GET.get('a', None)
rev_b_id = request.GET.get('b', None)
# Some stinky fingers manipul... |
Displays a list of all recent revisions.
def revision_list(
request, template_name='wakawaka/revision_list.html', extra_context=None
):
"""
Displays a list of all recent revisions.
"""
revision_list = Revision.objects.all()
template_context = {'revision_list': revision_list}
template_contex... |
Displays all Pages
def page_list(
request, template_name='wakawaka/page_list.html', extra_context=None
):
"""
Displays all Pages
"""
page_list = WikiPage.objects.all()
page_list = page_list.order_by('slug')
template_context = {
'page_list': page_list,
'index_slug': getattr(... |
Deletes the page with all revisions or the revision, based on the
users choice.
Returns a HttpResponseRedirect.
def delete_wiki(self, request, page, rev):
"""
Deletes the page with all revisions or the revision, based on the
users choice.
Returns a HttpResponseRedirect... |
Get the real field from a model given its name.
Handle nested models recursively (aka. ``__`` lookups)
def get_real_field(model, field_name):
'''
Get the real field from a model given its name.
Handle nested models recursively (aka. ``__`` lookups)
'''
parts = field_name.split('__')
field... |
Test if a given field supports regex lookups
def can_regex(self, field):
'''Test if a given field supports regex lookups'''
from django.conf import settings
if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'):
return not isinstance(get_real_field(self.model, field), UNSUP... |
Get ordering fields for ``QuerySet.order_by``
def get_orders(self):
'''Get ordering fields for ``QuerySet.order_by``'''
orders = []
iSortingCols = self.dt_data['iSortingCols']
dt_orders = [(self.dt_data['iSortCol_%s' % i], self.dt_data['sSortDir_%s' % i]) for i in xrange(iSortingCols)]
... |
Filter a queryset with global search
def global_search(self, queryset):
'''Filter a queryset with global search'''
search = self.dt_data['sSearch']
if search:
if self.dt_data['bRegex']:
criterions = [
Q(**{'%s__iregex' % field: search})
... |
Filter a queryset with column search
def column_search(self, queryset):
'''Filter a queryset with column search'''
for idx in xrange(self.dt_data['iColumns']):
search = self.dt_data['sSearch_%s' % idx]
if search:
if hasattr(self, 'search_col_%s' % idx):
... |
Apply Datatables sort and search criterion to QuerySet
def get_queryset(self):
'''Apply Datatables sort and search criterion to QuerySet'''
qs = super(DatatablesView, self).get_queryset()
# Perform global search
qs = self.global_search(qs)
# Perform column search
qs = se... |
Get the requested page
def get_page(self, form):
'''Get the requested page'''
page_size = form.cleaned_data['iDisplayLength']
start_index = form.cleaned_data['iDisplayStart']
paginator = Paginator(self.object_list, page_size)
num_page = (start_index / page_size) + 1
retu... |
Format a single row (if necessary)
def get_row(self, row):
'''Format a single row (if necessary)'''
if isinstance(self.fields, dict):
return dict([
(key, text_type(value).format(**row) if RE_FORMATTED.match(value) else row[value])
for key, value in self.fiel... |
Render Datatables expected JSON format
def render_to_response(self, form, **kwargs):
'''Render Datatables expected JSON format'''
page = self.get_page(form)
data = {
'iTotalRecords': page.paginator.count,
'iTotalDisplayRecords': page.paginator.count,
'sEcho':... |
Grant types:
- token:
An authorization is requested to the end-user by redirecting it to an authorization page hosted
on Dailymotion. Once authorized, a refresh token is requested by the API client to the token
server and stored in the end-user's cookie (or other storage tec... |
Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token
def authenticated(func):
"""
Decorator to check if Smappee's access token has expired.
If it has, use the refresh token to request a new access token
"""
@wraps(func)
def... |
Join terms together with forward slashes
Parameters
----------
parts
Returns
-------
str
def urljoin(*parts):
"""
Join terms together with forward slashes
Parameters
----------
parts
Returns
-------
str
"""
# first strip extra forward slashes (except ... |
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
access token is saved in self.access_token
refre... |
Saves the token expiration time by adding the 'expires in' parameter
to the current datetime (in utc).
Parameters
----------
expires_in : int
number of seconds from the time of the request until expiration
Returns
-------
nothing
saves ex... |
Request service locations
Returns
-------
dict
def get_service_locations(self):
"""
Request service locations
Returns
-------
dict
"""
url = URLS['servicelocation']
headers = {"Authorization": "Bearer {}".format(self.access_token... |
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_locatio... |
Request Elektricity consumption and Solar production
for a given service location.
Parameters
----------
service_location_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
... |
Request consumption for a given sensor in a given service location
Parameters
----------
service_location_id : int
sensor_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
... |
Request for both the get_consumption and
get_sensor_consumption methods.
Parameters
----------
url : str
start : dt.datetime
end : dt.datetime
aggregation : int
Returns
-------
dict
def _get_consumption(self, url, start, end, aggregation... |
Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pan... |
Turn actuator on
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
un... |
Turn actuator off
Parameters
----------
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any other value results in turning on for an
u... |
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any o... |
Extends get_consumption() AND get_sensor_consumption(),
parses the results in a Pandas DataFrame
Parameters
----------
service_location_id : int
start : dt.datetime | int
end : dt.datetime | int
timezone-naive datetimes are assumed to be in UTC
ep... |
Converts a datetime-like object to epoch, in milliseconds
Timezone-naive datetime objects are assumed to be in UTC
Parameters
----------
time : dt.datetime | pd.Timestamp | int
Returns
-------
int
epoch milliseconds
def _to_milliseconds(self, time):... |
Because basically every post request is the same
Parameters
----------
url : str
data : str, optional
Returns
-------
requests.Response
def _basic_post(self, url, data=None):
"""
Because basically every post request is the same
Paramete... |
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
def logon(self, password='admin'):
"""
Parameters
----------
password : str
default 'admin'
Returns
-------
dict
""... |
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.