INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Read and return up to n bytes. If the argument is omitted None or negative data is read and returned until EOF is reached..
def read(self, n=-1): """Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached.. """ buf = b'' while n < 0 or n is None or n > len(buf): data = self.read1(n) if len(data) == 0: ...
Read in the table of contents for the ZIP file.
def _RealGetContents(self): """Read in the table of contents for the ZIP file.""" fp = self.fp endrec = _EndRecData(fp) if not endrec: raise BadZipfile("File is not a zip file") if self.debug > 1: print(endrec) size_cd = endrec[_ECD_SIZE] ...
Return file - like object for name.
def open(self, name, mode="r", pwd=None): """Return file-like object for 'name'.""" if mode not in ("r", "U", "rU"): raise RuntimeError('open() requires mode "r", "U", or "rU"') if not self.fp: raise RuntimeError( "Attempt to read ZIP archive that was alre...
Remove a member from the archive.
def remove(self, member): """Remove a member from the archive.""" # Make sure we have an info object if isinstance(member, ZipInfo): # 'member' is already an info object zinfo = member else: # Get info object for name zinfo = self.getinfo(m...
Return ( filename archivename ) for the path.
def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ ...
Imports the class for the given class name.
def import_class(class_path): ''' Imports the class for the given class name. ''' module_name, class_name = class_path.rsplit(".", 1) module = import_module(module_name) claz = getattr(module, class_name) return claz
Creating an ExecutorPool is a costly operation. Executor needs to be instantiated only once.
def _executor(self): ''' Creating an ExecutorPool is a costly operation. Executor needs to be instantiated only once. ''' if self.EXECUTE_PARALLEL is False: executor_path = "batch_requests.concurrent.executor.SequentialExecutor" executor_class = import_class(e...
this borrows too much from the internals of ofs maybe expose different parts of the api?
def make_label(self, path): """ this borrows too much from the internals of ofs maybe expose different parts of the api? """ from datetime import datetime from StringIO import StringIO path = path.lstrip("/") bucket, label = path.split("/", 1) buc...
stub. this really needs to be a call to the remote restful interface to get the appropriate host and headers to use for this upload
def get_proxy_config(self, headers, path): """ stub. this really needs to be a call to the remote restful interface to get the appropriate host and headers to use for this upload """ self.ofs.conn.add_aws_auth_header(headers, 'PUT', path) from pprint import pprint...
This is the main function that uploads. We assume the bucket and key ( == path ) exists. What we do here is simple. Calculate the headers we will need ( e. g. md5 content - type etc ). Then we ask the self. get_proxy_config method to fill in the authentication information and tell us which remote host we should talk to...
def proxy_upload(self, path, filename, content_type=None, content_encoding=None, cb=None, num_cb=None): """ This is the main function that uploads. We assume the bucket and key (== path) exists. What we do here is simple. Calculate the headers we will need, (e.g. md5...
Fetches all mood stations.
def fetch_all_mood_stations(self, terr=KKBOXTerritory.TAIWAN): ''' Fetches all mood stations. :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#moodstations`. ''' url = 'https://api.kk...
Fetches a mood station by given ID.
def fetch_mood_station(self, station_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a mood station by given ID. :param station_id: the station ID :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/referenc...
Fetches next page based on previously fetched data. Will get the next page url from data [ paging ] [ next ].
def fetch_next_page(self, data): ''' Fetches next page based on previously fetched data. Will get the next page url from data['paging']['next']. :param data: previously fetched API response. :type data: dict :return: API response. :rtype: dict '''...
Fetches data from specific url.
def fetch_data(self, url): ''' Fetches data from specific url. :return: The response. :rtype: dict ''' return self.http._post_data(url, None, self.http._headers_with_access_token())
Fetches a shared playlist by given ID.
def fetch_shared_playlist(self, playlist_id, terr=KKBOXTerritory.TAIWAN): ''' Fetches a shared playlist by given ID. :param playlist_id: the playlist ID. :type playlist_id: str :param terr: the current territory. :return: API response. :rtype: dictcd See...
Return a FirewallRule object based on server uuid and rule position.
def get_firewall_rule(self, server_uuid, firewall_rule_position, server_instance=None): """ Return a FirewallRule object based on server uuid and rule position. """ url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position) res = self.get_request(url) ...
Return all FirewallRule objects based on a server instance or uuid.
def get_firewall_rules(self, server): """ Return all FirewallRule objects based on a server instance or uuid. """ server_uuid, server_instance = uuid_and_instance(server) url = '/server/{0}/firewall_rule'.format(server_uuid) res = self.get_request(url) return [ ...
Create a new firewall rule for a given server uuid.
def create_firewall_rule(self, server, firewall_rule_body): """ Create a new firewall rule for a given server uuid. The rule can begiven as a dict or with FirewallRule.prepare_post_body(). Returns a FirewallRule object. """ server_uuid, server_instance = uuid_and_instanc...
Delete a firewall rule based on a server uuid and rule position.
def delete_firewall_rule(self, server_uuid, firewall_rule_position): """ Delete a firewall rule based on a server uuid and rule position. """ url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position) return self.request('DELETE', url)
Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies.
def configure_firewall(self, server, firewall_rule_bodies): """ Helper for calling create_firewall_rule in series for a list of firewall_rule_bodies. """ server_uuid, server_instance = uuid_and_instance(server) return [ self.create_firewall_rule(server_uuid, rule) ...
POSTs a raw SMTP message to the Sinkhole API
def post(self, data): """ POSTs a raw SMTP message to the Sinkhole API :param data: raw content to be submitted [STRING] :return: { list of predictions } """ uri = '{}/sinkhole'.format(self.client.remote) self.logger.debug(uri) if PYVERSION == 2: ...
Returns the lowered method. Capitalize headers prepend HTTP_ and change - to _.
def pre_process_method_headers(method, headers): ''' Returns the lowered method. Capitalize headers, prepend HTTP_ and change - to _. ''' method = method.lower() # Standard WSGI supported headers _wsgi_headers = ["content_length", "content_type", "query_string", ...
Define headers that needs to be included from the current request.
def headers_to_include_from_request(curr_request): ''' Define headers that needs to be included from the current request. ''' return { h: v for h, v in curr_request.META.items() if h in _settings.HEADERS_TO_INCLUDE}
Based on the given request parameters constructs and returns the WSGI request object.
def get_wsgi_request_object(curr_request, method, url, headers, body): ''' Based on the given request parameters, constructs and returns the WSGI request object. ''' x_headers = headers_to_include_from_request(curr_request) method, t_headers = pre_process_method_headers(method, headers) # A...
Override the default values for the wsgi environment variables.
def _base_environ(self, **request): ''' Override the default values for the wsgi environment variables. ''' # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www...
Perform a request with a given body to a given endpoint in UpCloud s API.
def request(self, method, endpoint, body=None, timeout=-1): """ Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __error_middleware. """ if method not in set(['GET', 'POST', 'PUT', 'DELETE']): raise Exception('Invalid/Forb...
Perform a POST request to a given endpoint in UpCloud s API.
def post_request(self, endpoint, body=None, timeout=-1): """ Perform a POST request to a given endpoint in UpCloud's API. """ return self.request('POST', endpoint, body, timeout)
Middleware that raises an exception when HTTP statuscode is an error code.
def __error_middleware(self, res, res_json): """ Middleware that raises an exception when HTTP statuscode is an error code. """ if(res.status_code in [400, 401, 402, 403, 404, 405, 406, 409]): err_dict = res_json.get('error', {}) raise UpCloudAPIError(error_code=e...
Create a new file to swift object storage.
def put_stream(self, bucket, label, stream_object, params={}): ''' Create a new file to swift object storage. ''' self.claim_bucket(bucket) self.connection.put_object(bucket, label, stream_object, headers=self._convert_to_meta(params))
PURPOSE
def h(gbm, array_or_frame, indices_or_columns = 'all'): """ PURPOSE Compute Friedman and Popescu's H statistic, in order to look for an interaction in the passed gradient-boosting model among the variables represented by the elements of the passed array or frame and specified by the passed indices ...
PURPOSE
def h_all_pairs(gbm, array_or_frame, indices_or_columns = 'all'): """ PURPOSE Compute Friedman and Popescu's two-variable H statistic, in order to look for an interaction in the passed gradient- boosting model between each pair of variables represented by the elements of the passed array or frame and s...
Performs a search against the predict endpoint
def get(self, q, limit=None): """ Performs a search against the predict endpoint :param q: query to be searched for [STRING] :return: { score: [0|1] } """ uri = '{}/predict?q={}'.format(self.client.remote, q) self.logger.debug(uri) body = self.client.get...
Whether a given bucket: label object already exists.
def exists(self, bucket, label): '''Whether a given bucket:label object already exists.''' fn = self._zf(bucket, label) try: self.z.getinfo(fn) return True except KeyError: return False
List labels for the given bucket. Due to zipfiles inherent arbitrary ordering this is an expensive operation as it walks the entire archive searching for individual buckets
def list_labels(self, bucket): '''List labels for the given bucket. Due to zipfiles inherent arbitrary ordering, this is an expensive operation, as it walks the entire archive searching for individual 'buckets' :param bucket: bucket to list labels for. :return: iterator for the ...
List all buckets managed by this OFS instance. Like list_labels this also walks the entire archive yielding the bucketnames. A local set is retained so that duplicates aren t returned so this will temporarily pull the entire list into memory even though this is a generator and will slow as more buckets are added to the...
def list_buckets(self): '''List all buckets managed by this OFS instance. Like list_labels, this also walks the entire archive, yielding the bucketnames. A local set is retained so that duplicates aren't returned so this will temporarily pull the entire list into memory even though this ...
Get a bitstream for the given bucket: label combination.
def get_stream(self, bucket, label, as_stream=True): '''Get a bitstream for the given bucket:label combination. :param bucket: the bucket to use. :return: bitstream as a file-like object ''' if self.mode == "w": raise OFSException("Cannot read from archive in 'w' mod...
Get a URL that should point at the bucket: labelled resource. Aimed to aid web apps by allowing them to redirect to an open resource rather than proxy the bitstream.
def get_url(self, bucket, label): '''Get a URL that should point at the bucket:labelled resource. Aimed to aid web apps by allowing them to redirect to an open resource, rather than proxy the bitstream. :param bucket: the bucket to use. :param label: the label of the resource to get :re...
Put a bitstream ( stream_object ) for the specified bucket: label identifier.
def put_stream(self, bucket, label, stream_object, params=None, replace=True, add_md=True): '''Put a bitstream (stream_object) for the specified bucket:label identifier. :param bucket: as standard :param label: as standard :param stream_object: file-like object to read from or bytestrin...
Delete a bitstream. This needs more testing - file deletion in a zipfile is problematic. Alternate method is to create second zipfile without the files in question which is not a nice method for large zip archives.
def del_stream(self, bucket, label): '''Delete a bitstream. This needs more testing - file deletion in a zipfile is problematic. Alternate method is to create second zipfile without the files in question, which is not a nice method for large zip archives. ''' if self.exists(bucke...
Get the metadata for this bucket: label identifier.
def get_metadata(self, bucket, label): '''Get the metadata for this bucket:label identifier. ''' if self.mode !="w": try: jsn = self._get_bucket_md(bucket) except OFSFileNotFound: # No MD found... return {} excep...
Update the metadata with the provided dictionary of params.
def update_metadata(self, bucket, label, params): '''Update the metadata with the provided dictionary of params. :param parmams: dictionary of key values (json serializable). ''' if self.mode !="r": try: payload = self._get_bucket_md(bucket) excep...
Delete the metadata corresponding to the specified keys.
def del_metadata_keys(self, bucket, label, keys): '''Delete the metadata corresponding to the specified keys. ''' if self.mode !="r": try: payload = self._get_bucket_md(bucket) except OFSFileNotFound: # No MD found... raise ...
Given a WSGI request makes a call to a corresponding view function and returns the response.
def get_response(wsgi_request): ''' Given a WSGI request, makes a call to a corresponding view function and returns the response. ''' service_start_time = datetime.now() # Get the view / handler for this request view, args, kwargs = resolve(wsgi_request.path_info) kwargs.update(...
For the given batch request extract the individual requests and create WSGIRequest object for each.
def get_wsgi_requests(request): ''' For the given batch request, extract the individual requests and create WSGIRequest object for each. ''' valid_http_methods = ["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace"] requests = json.loads(request.body) if t...
A view function to handle the overall processing of batch requests.
def handle_batch_requests(request, *args, **kwargs): ''' A view function to handle the overall processing of batch requests. ''' batch_start_time = datetime.now() try: # Get the Individual WSGI requests. wsgi_requests = get_wsgi_requests(request) except BadBatchRequest as brx...
Searches within KKBOX s database.
def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN): ''' Searches within KKBOX's database. :param keyword: the keyword. :type keyword: str :param types: the search types. :return: list :param terr: the current territory. :return: API response....
IPAddress can only change its PTR record. Saves the current state PUT/ ip_address/ uuid.
def save(self): """ IPAddress can only change its PTR record. Saves the current state, PUT /ip_address/uuid. """ body = {'ip_address': {'ptr_record': self.ptr_record}} data = self.cloud_manager.request('PUT', '/ip_address/' + self.address, body) self._reset(**data['ip_add...
Create IPAddress objects from API response data. Also associates CloudManager with the objects.
def _create_ip_address_objs(ip_addresses, cloud_manager): """ Create IPAddress objects from API response data. Also associates CloudManager with the objects. """ # ip-addresses might be provided as a flat array or as a following dict: # {'ip_addresses': {'ip_address': [.....
Reset the objects attributes.
def _reset(self, **kwargs): """ Reset the objects attributes. Accepts servers as either unflattened or flattened UUID strings or Server objects. """ super(Tag, self)._reset(**kwargs) # backup name for changing it (look: Tag.save) self._api_name = self.name ...
HTTP GET function
def _get(self, uri, params={}): """ HTTP GET function :param uri: REST endpoint :param params: optional HTTP params to pass to the endpoint :return: list of results (usually a list of dicts) Example: ret = cli.get('/search', params={ 'q': 'example.org' }) ...
HTTP POST function
def _post(self, uri, data): """ HTTP POST function :param uri: REST endpoint to POST to :param data: list of dicts to be passed to the endpoint :return: list of dicts, usually will be a list of objects or id's Example: ret = cli.post('/indicators', { 'indica...
Return a list of ( populated or unpopulated ) Server instances.
def get_servers(self, populate=False, tags_has_one=None, tags_has_all=None): """ Return a list of (populated or unpopulated) Server instances. - populate = False (default) => 1 API request, returns unpopulated Server instances. - populate = True => Does 1 + n API requests (n = # of serv...
Return a ( populated ) Server instance.
def get_server(self, UUID): """ Return a (populated) Server instance. """ server, IPAddresses, storages = self.get_server_data(UUID) return Server( server, ip_addresses=IPAddresses, storage_devices=storages, populated=True, ...
Return a ( populated ) Server instance by its IP.
def get_server_by_ip(self, ip_address): """ Return a (populated) Server instance by its IP. Uses GET '/ip_address/x.x.x.x' to retrieve machine UUID using IP-address. """ data = self.get_request('/ip_address/{0}'.format(ip_address)) UUID = data['ip_address']['server'] ...
Create a server and its storages based on a ( locally created ) Server object.
def create_server(self, server): """ Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer t...
modify_server allows updating the server s updateable_fields.
def modify_server(self, UUID, **kwargs): """ modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods. """ body = dict() body['server'] = {} for arg in kwargs: i...
Return/ server/ uuid data in Python dict.
def get_server_data(self, UUID): """ Return '/server/uuid' data in Python dict. Creates object representations of any IP-address and Storage. """ data = self.get_request('/server/{0}'.format(UUID)) server = data['server'] # Populate subobjects IPAddresse...
Pull a feed: param f: feed name ( eg: csirtgadgetes/ correlated ): param limit: return value limit ( default 25 ): return: Feed dict
def feed(f, limit=25): """ Pull a feed :param f: feed name (eg: csirtgadgetes/correlated) :param limit: return value limit (default 25) :return: Feed dict """ if '/' not in f: raise ValueError('feed name must be formatted like: ' 'csirtgadgets/scanners') ...
Create an indicator in a feed: param f: feed name ( eg: wes/ test ): param i: indicator dict ( eg: { indicator: example. com tags: [ ssh ] description: this is a test } ): return: dict of indicator
def indicator_create(f, i): """ Create an indicator in a feed :param f: feed name (eg: wes/test) :param i: indicator dict (eg: {'indicator': 'example.com', 'tags': ['ssh'], 'description': 'this is a test'}) :return: dict of indicator """ if '/' not in f: raise ValueError('feed na...
Reads the content of file in IDX format converts it into numpy. ndarray and returns it. file is a file - like object ( with read () method ) or a file name.
def convert_from_file(file): """ Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'rb') as f: return _internal_con...
Converts file in IDX format provided by file - like input into numpy. ndarray and returns it.
def _internal_convert(inp): """ Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. """ ''' Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. ''' # Read the "magic number" - 4 bytes. try: mn ...
Writes the contents of the numpy. ndarray ndarr to file in IDX format. file is a file - like object ( with write () method ) or a file name.
def convert_to_file(file, ndarr): """ Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'wb') as fp: _internal_write(fp, ndarr) else...
Writes the contents of the numpy. ndarray ndarr to bytes in IDX format and returns it.
def convert_to_string(ndarr): """ Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. """ with contextlib.closing(BytesIO()) as bytesio: _internal_write(bytesio, ndarr) return bytesio.getvalue()
Writes numpy. ndarray arr to a file - like object ( with write () method ) in IDX format.
def _internal_write(out_stream, arr): """ Writes numpy.ndarray arr to a file-like object (with write() method) in IDX format. """ if arr.size == 0: raise FormatError('Cannot encode empty array.') try: type_byte, struct_lib_type = _DATA_TYPES_NUMPY[str(arr.dtype)] except Key...
There are three ways to let you start using KKBOX s Open/ Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums playlists and so on.
def fetch_access_token_by_client_credentials(self): ''' There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from K...
Validate Storage OS and its UUID.
def get_OS_UUID(cls, os): """ Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates. """ if os in cls.templates: return cls.templates[os] uuid_regexp = '^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}...
Calls the resp_generator for all the requests in parallel in an asynchronous way.
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in parallel in an asynchronous way. ''' result_futures = [self.executor_pool.submit(resp_generator, req, *args, **kwargs) for req in requests] resp = [res_future.re...
Calls the resp_generator for all the requests in sequential order.
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in sequential order. ''' return [resp_generator(request) for request in requests]
Sets up basic logging
def setup_logging(args): """ Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally """ loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG console = logging.StreamHandl...
Get an IPAddress object with the IP address ( string ) from the API.
def get_ip(self, address): """ Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') """ res = self.get_request('/ip_address/' + address) return IPAddress(cloud_manager=self, **res['ip_address'])
Get all IPAddress objects from the API.
def get_ips(self): """ Get all IPAddress objects from the API. """ res = self.get_request('/ip_address') IPs = IPAddress._create_ip_address_objs(res['ip_addresses'], cloud_manager=self) return IPs
Attach a new ( random ) IPAddress to the given server ( object or UUID ).
def attach_ip(self, server, family='IPv4'): """ Attach a new (random) IPAddress to the given server (object or UUID). """ body = { 'ip_address': { 'server': str(server), 'family': family } } res = self.request('POST...
Modify an IP address ptr - record ( Reverse DNS ).
def modify_ip(self, ip_addr, ptr_record): """ Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). """ body = { 'ip_address': { 'ptr_record': ptr_record } } res = ...
Creates a new Feed object
def new(self, user, name, description=None): """ Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description :return: dict """ uri = self.client.remote + '/users/{0}/feeds'.format(user) data = ...
Removes a feed
def delete(self, user, name): """ Removes a feed :param user: feed username :param name: feed name :return: true/false """ uri = self.client.remote + '/users/{}/feeds/{}'.format(user, name) resp = self.client.session.delete(uri) return resp.stat...
Returns a list of Feeds from the API
def index(self, user): """ Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets') """ uri = self.client.remote + '/users/{0}/feeds'.format(user) return self.client.get(uri)
Returns a specific Feed from the API
def show(self, user, name, limit=None, lasttime=None): """ Returns a specific Feed from the API :param user: feed username :param name: feed name :param limit: limit the results :param lasttime: only show >= lasttime :return: dict Example: re...
Codenerix CONTEXT
def codenerix(request): ''' Codenerix CONTEXT ''' # Get values DEBUG = getattr(settings, 'DEBUG', False) VERSION = getattr(settings, 'VERSION', _('WARNING: No version set to this code, add VERSION contant to your configuration')) # Set environment return { 'DEBUG': DEBUG, ...
Override django - bakery to skip profiles that raise 404
def build_object(self, obj): """Override django-bakery to skip profiles that raise 404""" try: build_path = self.get_build_path(obj) self.request = self.create_request(build_path) self.request.user = AnonymousUser() self.set_kwargs(obj) self.bu...
Create a row for the schedule table.
def make_schedule_row(schedule_day, slot, seen_items): """Create a row for the schedule table.""" row = ScheduleRow(schedule_day, slot) skip = {} expanding = {} all_items = list(slot.scheduleitem_set .select_related('talk', 'page', 'venue') .all()) for ...
Helper function which creates an ordered list of schedule days
def generate_schedule(today=None): """Helper function which creates an ordered list of schedule days""" # We create a list of slots and schedule items schedule_days = {} seen_items = {} for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'): day = slot.get_day() if ...
Allow adding a render_description parameter
def get_context_data(self, **kwargs): """Allow adding a 'render_description' parameter""" context = super(ScheduleXmlView, self).get_context_data(**kwargs) if self.request.GET.get('render_description', None) == '1': context['render_description'] = True else: conte...
Create a iCal file from the schedule
def get(self, request): """Create a iCal file from the schedule""" # Heavily inspired by https://djangosnippets.org/snippets/2223/ and # the icalendar documentation calendar = Calendar() site = get_current_site(request) calendar.add('prodid', '-//%s Schedule//%s//' % (sit...
Look up a page by url ( which is a tree of slugs )
def slug(request, url): """Look up a page by url (which is a tree of slugs)""" page = None if url: for slug in url.split('/'): if not slug: continue try: page = Page.objects.get(slug=slug, parent=page) except Page.DoesNotExist: ...
Override django - bakery to skip pages marked exclude_from_static
def build_object(self, obj): """Override django-bakery to skip pages marked exclude_from_static""" if not obj.exclude_from_static: super(ShowPage, self).build_object(obj)
Override django - bakery to skip talks that raise 403
def build_object(self, obj): """Override django-bakery to skip talks that raise 403""" try: super(TalkView, self).build_object(obj) except PermissionDenied: # We cleanup the directory created self.unbuild_object(obj)
Only talk owners can see talks unless they ve been accepted
def get_object(self, *args, **kwargs): '''Only talk owners can see talks, unless they've been accepted''' object_ = super(TalkView, self).get_object(*args, **kwargs) if not object_.can_view(self.request.user): raise PermissionDenied return object_
Canonicalize the URL if the slug changed
def render_to_response(self, *args, **kwargs): '''Canonicalize the URL if the slug changed''' if self.request.path != self.object.get_absolute_url(): return HttpResponseRedirect(self.object.get_absolute_url()) return super(TalkView, self).render_to_response(*args, **kwargs)
Override delete to only withdraw
def delete(self, request, *args, **kwargs): """Override delete to only withdraw""" talk = self.get_object() talk.status = WITHDRAWN talk.save() revisions.set_user(self.request.user) revisions.set_comment("Talk Withdrawn") return HttpResponseRedirect(self.success_u...
A decorator that applies an ordering to the QuerySet returned by a function.
def order_results_by(*fields): """A decorator that applies an ordering to the QuerySet returned by a function. """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kw): result = f(*args, **kw) return result.order_by(*fields) return wrapper ...
A decorator for caching the result of a function.
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if...
Override django - bakery s build logic to fake pagination.
def build_queryset(self): """Override django-bakery's build logic to fake pagination.""" paths = [(os.path.join(self.build_prefix, 'index.html'), {})] self.request = None queryset = self.get_queryset() paginator = self.get_paginator(queryset, self.get_paginate_by(queryset)) ...
< --------------------------------------- 12 columns ------------------------------------ > < --- 6 columns --- > < --- 6 columns --- > ------------------------------------------ ------------------------------------------ | Info | | Personal | | ========================================== | | ===========================...
def get_groups(self, gs=None, processed=[], initial=True): ''' <--------------------------------------- 12 columns ------------------------------------> <--- 6 columns ---> <--- 6 columns ---> ------------------------------------------ -----------...
Expose the site s info to templates
def site_info(request): '''Expose the site's info to templates''' site = get_current_site(request) context = { 'WAFER_CONFERENCE_NAME': site.name, 'WAFER_CONFERENCE_DOMAIN': site.domain, } return context
Expose whether to display the navigation header and footer
def navigation_info(request): '''Expose whether to display the navigation header and footer''' if request.GET.get('wafer_hide_navigation') == "1": nav_class = "wafer-invisible" else: nav_class = "wafer-visible" context = { 'WAFER_NAVIGATION_VISIBILITY': nav_class, } retur...
Expose selected settings to templates
def registration_settings(request): '''Expose selected settings to templates''' context = {} for setting in ( 'WAFER_SSO', 'WAFER_HIDE_LOGIN', 'WAFER_REGISTRATION_OPEN', 'WAFER_REGISTRATION_MODE', 'WAFER_TALKS_OPEN', 'WAFER_VIDEO_LICENS...
return the rolls this people is related with
def profiles(self): ''' return the rolls this people is related with ''' limit = [] if self.is_admin(): limit.append(_("Administrator")) limit.sort() return limit
r Matern covariance function of arbitrary dimension for use with: py: class: ArbitraryKernel. The Matern kernel has the following hyperparameters always referenced in the order listed: = ===== ==================================== 0 sigma prefactor 1 nu order of kernel 2 l1 length scale for the first dimension 3 l2... a...
def matern_function(Xi, Xj, *args): r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`. The Matern kernel has the following hyperparameters, always referenced in the order listed: = ===== ==================================== 0 sigma prefactor ...
r Evaluate the kernel directly at the given values of tau. Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. Returns ------- k:: py: class: Array ( M ): math: k ( \ tau ) ( less the: math: \ sigma^2 prefactor ).
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) ...
r Covert tau to: math: y = 2 \ nu \ sum_i ( \ tau_i^2/ l_i^2 ). Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. return_r2l2: bool optional Set to True to return a tuple of ( y r2l2 ). Default is False ( only return y ). Returns ------- y:: py: class: Array ( M ) Inner argument of functi...
def _compute_y(self, tau, return_r2l2=False): r"""Covert tau to :math:`y=2\nu\sum_i(\tau_i^2/l_i^2)`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. return_r2l2 : bool, optional Set to True to return a tu...