code
stringlengths
1
18.2k
not None: headers['Content-Encoding'] = content_encoding m = md5() fp.seek(0) s = fp.read(BufferSize) while s: m.update(s) s = fp.read(BufferSize) self.size = fp.tell() fp.seek(0) self.md5 = m.hexdigest() headers['Content-MD5'] = base64.encodestring(m.digest()).rstrip('\n') headers['Content-Length'] = str(self.size) he...
%s'" % (k,v) for k,v in headers.items()), host, path )) def sender(http_conn, method, path, data, headers): http_conn.putrequest(method, path) for key in headers: http_conn.putheader(key, headers[key]) http_conn.endheaders() fp.seek(0) http_conn.set_debuglevel(0) ### XXX set to e.g. 4 to see what going on if cb: if num...
total_bytes = 0 cb(total_bytes, self.size) l = fp.read(BufferSize) while len(l) > 0: http_conn.send(l) if cb: total_bytes += len(l) i += 1 if i == cb_count or cb_count == -1: cb(total_bytes, self.size) i = 0 l = fp.read(BufferSize) if cb: cb(total_bytes, self.size) response = http_conn.getresponse() body = response.rea...
response elif response.status >= 200 and response.status <= 299: self.etag = response.getheader('etag') if self.etag != '"%s"' % self.md5: raise Exception('ETag from S3 did not match computed MD5') return response else: #raise provider.storage_response_error( # response.status, response.reason, body) raise Exception(re...
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.kkbox.com/v1.1/mood-stations' url += '?' + url_parse.urlencode({'ter...
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/reference#moodstations-station_id`. ''' url = 'https://api.kkbox.c...
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 ''' next_url = data['paging']['next'] if next_url != None: next_data = self....
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())
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 `https://docs-en.kkbox.codes/v1.1/reference#sharedplaylists-playl...
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 FirewallRule(**res['firewall_rule'])
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 [ FirewallRule(server=server_instance, **firewall_rule) for ...
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_instance(server) url = '/server/{0}/firewall_rule'.forma...
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)
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) for rule in firewall_rule_bodies ]
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: try: data = data.decode('utf-8') except Exception: data = data.decode('la...
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", "remote_addr", "remote_host", "remote_user", "request_met...
= header.replace("-", "_") header = "http_{header}".format( header=header) if header.lower() not in _wsgi_headers else header _transformed_headers.update({header.upper(): value}) return method, _transformed_headers
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}
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) # Add default content type. if "...
request factory to construct the request. _request_factory = BatchRequestFactory() _request_provider = getattr(_request_factory, method) secure = _settings.USE_HTTPS request = _request_provider(url, data=body, secure=secure, content_type=content_type, **x_headers) return request
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.python.org/dev/peps/pep-3333/#environ-variables environ = {...
'wsgi.url_scheme': str('http'), 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': True, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ
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/Forbidden HTTP method') url = '/' + self.api_v + endpoint...
timeout if timeout != -1 else self.timeout APIcall = getattr(requests, method.lower()) res = APIcall('https://api.upcloud.com' + url, data=json_body_or_None, headers=headers, timeout=call_timeout) if res.text: res_json = res.json() else: res_json = {} return self.__error_middleware(res, res_json)
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)
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=err_dict.get('error_code'), error_message=err_dict.get('e...
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))
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 or columns. See Jerom...
2:916-954, http://projecteuclid.org/download/pdfview_1/euclid.aoas/1223908046, s. 8.1. ARGUMENTS gbm should be a scikit-learn gradient-boosting model (instance of sklearn.ensemble.GradientBoostingClassifier or sklearn.ensemble.GradientBoostingRegressor) that has been fitted to array_or_frame (and a target, not used her...
columns of array_or_frame if array_or_frame is a NumPy array or a list of columns of array_or_frame if array_or_frame is a pandas data frame. If it is 'all', then all columns of array_or_frame are used. RETURNS The H statistic of the variables or NaN if the computation is spoiled by weak main effects and rounding error...
the stronger the evidence for an interaction among the variables. EXAMPLES Friedman and Popescu's (2008) formulas (44) and (46) correspond to h(F, x, [j, k]) and h(F, x, [j, k, l]) respectively. NOTES 1. Per Friedman and Popescu, only variables with strong main effects should be examined for interactions. Strengths of ...
Friedman and Popescu, collinearity among variables can lead to interactions in gbm that are not present in the target function. To forestall such spurious interactions, check for strong correlations among variables before fitting gbm. """ if indices_or_columns == 'all': if gbm.max_depth < array_or_frame.shape[1]: raise...
gbm.max_depth < len(indices_or_columns): raise \ Exception( "gbm.max_depth == {}, so indices_or_columns must contain at most {} {}." .format(gbm.max_depth, gbm.max_depth, "element" if gbm.max_depth == 1 else "elements") ) check_args_contd(array_or_frame, indices_or_columns) arr, model_inds = get_arr_and_model_inds(arra...
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 specified by the p...
ensembles", Ann. Appl. Stat. 2:916-954, http://projecteuclid.org/download/pdfview_1/euclid.aoas/1223908046, s. 8.1. ARGUMENTS gbm should be a scikit-learn gradient-boosting model (instance of sklearn.ensemble.GradientBoostingClassifier or sklearn.ensemble.GradientBoostingRegressor) that has been fitted to array_or_fram...
list of indices of columns of array_or_frame if array_or_frame is a NumPy array or a list of columns of array_or_frame if array_or_frame is a pandas data frame. If it is 'all', then all columns of array_or_frame are used. RETURNS A dict whose keys are pairs (2-tuples) of indices or columns and whose values are the H st...
if a computation is spoiled by weak main effects and rounding errors. H varies from 0 to 1. The larger H, the stronger the evidence for an interaction between a pair of variables. EXAMPLE Friedman and Popescu's (2008) formula (44) for every j and k corresponds to h_all_pairs(F, x) NOTES 1. Per Friedman and Popescu, onl...
for interactions. Strengths of main effects are available as gbm.feature_importances_ once gbm has been fitted. 2. Per Friedman and Popescu, collinearity among variables can lead to interactions in gbm that are not present in the target function. To forestall such spurious interactions, check for strong correlations am...
indices_or_columns) arr, model_inds = get_arr_and_model_inds(array_or_frame, indices_or_columns) width = arr.shape[1] f_vals = {} for n in [2, 1]: for inds in itertools.combinations(range(width), n): f_vals[inds] = compute_f_vals(gbm, model_inds, arr, inds) h_vals = {} for inds in itertools.combinations(range(width), 2...
for inds in h_vals.keys()} return h_vals
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(uri) return body['score']
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
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 labels in the specified bucket. ''' for n...
label
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 is a generator and will slow as ...
buckets = set() for name in self.z.namelist(): bucket, _ = self._nf(name) if bucket not in buckets: buckets.add(bucket) yield bucket
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' mode") elif self.exists(bucket, label): fn = self._zf(bu...
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 :return: a string URI - eg 'zip:file...
fn = self._zf(bucket, label) return "!/".join(root, fn) else: raise OFSFileNotFound
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 bytestring. :param params: update metadata...
self._zf(bucket, label) params['_creation_date'] = datetime.now().isoformat().split(".")[0] ## '2010-07-08T19:56:47' params['_label'] = label if self.exists(bucket, label) and replace==True: # Add then Replace? Let's see if that works... #z = ZipFile(self.zipfile, self.mode, self.compression, self.allowZip64) zinfo = s...
#z.close() params['_content_length'] = size if chksum: params['_checksum'] = chksum if add_md: params = self.update_metadata(bucket, label, params) return params
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(bucket, label): name = self._zf(bucket, label...
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 {} except OFSException as e: raise OFSException(e) if label in jsn: return jsn[label] else: return {} else: raise OF...
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) except OFSFileNotFound: # No MD found... create it payload = {} for l in self....
OFSException as e: raise OFSException(e) if not label in payload: payload[label] = {} payload[label].update(params) self.put_stream(bucket, MD_FILE, json.dumps(payload).encode('utf-8'), params={}, replace=True, add_md=False) return payload[label] else: raise OFSException("Cannot update MD in archive in 'r' mode")
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 OFSFileNotFound("Couldn't find a md file for %s bucket" % bucket) except OFSException as e: rais...
else: raise OFSException("Cannot update MD in archive in 'r' mode")
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({"request": wsgi_request}) # Let the view...
response into simple dict type. d_resp = {"status_code": resp.status_code, "reason_phrase": resp.reason_phrase, "headers": headers} try: d_resp.update({"body": resp.content}) except ContentNotRenderedError: resp.render() d_resp.update({"body": resp.content}) # Check if we need to send across the duration header. if _se...
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 type(requests) not in (list, tuple): r...
maximum of %d requests." % (_settings.MAX_LIMIT)) # We could mutate the current request with the respective parameters, but mutation is ghost in the dark, # so lets avoid. Construct the new WSGI request object for each request. def construct_wsgi_from_data(data): ''' Given the data in the format of url, method, body an...
data.get("method", None) if url is None or method is None: raise BadBatchRequest("Request definition should have url, method defined.") if method.lower() not in valid_http_methods: raise BadBatchRequest("Invalid request method.") body = data.get("body", "") headers = data.get("headers", {}) return get_wsgi_request_obje...
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: return HttpResponseBadRequest(content=brx....
resp.__setitem__(_settings.DURATION_HEADER_NAME, str((datetime.now() - batch_start_time).seconds)) return resp
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. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#sea...
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_address'])
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': [...]}} || {'ip_address': [...]} if 'ip_addresses' ...
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 # flatten { servers: { server: [] } } if 'server' in self.serve...
populated=False) for server in self.servers]
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' }) """ if not uri.startswith(self.remote): uri = '{}{}'.format(self...
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', { 'indicator': 'example.com' }) """ if not uri.startswith(self.remote):...
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 servers), returns populated Server in...
or strings returns servers that have at least one of the given tags - tags_has_all: list of Tag objects or strings returns servers that have all of the tags """ if tags_has_all and tags_has_one: raise Exception('only one of (tags_has_all, tags_has_one) is allowed.') request = '/server' if tags_has_all: tags_has_all = [...
[str(tag) for tag in tags_has_one] taglist = ','.join(tags_has_one) request = '/server/tag/{0}'.format(taglist) servers = self.get_request(request)['servers']['server'] server_list = list() for server in servers: server_list.append(Server(server, cloud_manager=self)) if populate: for server_instance in server_list: ser...
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, cloud_manager=self )
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'] return self.get_server(UUID)
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 to the REST API documentation for correct f...
"my.example.1", zone = ZONE.London, storage_devices = [ Storage(os = "Ubuntu 14.04", size=10, tier=maxiops, title='The OS drive'), Storage(size=10), Storage() title = "My Example Server" ]) manager.create_server(server1) One storage should contain an OS. Otherwise storage fields are optional. - size defaults to 10, - t...
- tier defaults to maxiops - valid operating systems are: "CentOS 6.5", "CentOS 7.0" "Debian 7.8" "Ubuntu 12.04", "Ubuntu 14.04" "Windows 2003","Windows 2008" ,"Windows 2012" """ if isinstance(server, Server): body = server.prepare_post_body() else: server = Server._create_server_obj(server, cloud_manager=self) body = ...
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: if arg not in Server.updateable_fields: Exception('{0} is not an updat...
= Storage._create_storage_objs(server.pop('storage_devices'), cloud_manager=self) return Server( server, ip_addresses=IPAddresses, storage_devices=storages, populated=True, cloud_manager=self )
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 IPAddresses = IPAddress._create_ip_address_objs(server.pop('ip_addresses'), ...
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') user, f = f.split('/') return Feed().show(user, f, limit=limit)
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 name must be formatted like: ' 'csirtgadge...
= f ret = Indicator(i).submit() return ret
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_convert(f) else: return _internal_convert(file)
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 = struct.unpack('>BBBB', inp.read(4)) except stru...
or mn[1] != 0: msg = ("Incorrect first two bytes of the magic number: " + "0x{0:02X} 0x{1:02X}".format(mn[0], mn[1])) raise FormatError(msg) # 3rd byte is the data type code. dtype_code = mn[2] if dtype_code not in _DATA_TYPES_IDX: msg = "Incorrect data type code: 0x{0:02X}".format(dtype_code) raise FormatError(msg) # ...
dtype_s, el_size = _DATA_TYPES_IDX[dtype_code] # 4-byte integer for length of each dimension. try: dims_sizes = struct.unpack('>' + 'I' * dims, inp.read(4 * dims)) except struct.error as e: raise FormatError('Dims sizes: {0}'.format(e)) # Full length of data. full_length = reduce(operator.mul, dims_sizes, 1) # Create a...
creating numpy array: {0}'.format(e)) # Check for superfluous data. if len(inp.read(1)) > 0: raise FormatError('Superfluous data detected.') return result_array
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: _internal_write(file, ndarr)
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()
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 KeyError: raise FormatError('numpy ndarray type n...
format cannot encode array with more than ' + str(_MAX_AXIS_LENGTH) + ' elements along any axis') # Write magic number out_stream.write(struct.pack('BBBB', 0, 0, type_byte, arr.ndim)) # Write array dimensions out_stream.write(struct.pack('>' + 'I' * arr.ndim, *arr.shape)) # Horrible hack to deal with horrible bug when ...
== 'uint8': arr_as_list = [int(i) for i in arr.reshape(-1)] out_stream.write(struct.pack('>' + struct_lib_type * arr.size, *arr_as_list)) else: # Write array contents - note that the limit to number of arguments # doesn't apply to unrolled arguments out_stream.write(struct.pack('>' + struct_lib_type * arr.size, *arr.re...
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 KKBOX such as public albums, playlists an...
a user. You have to let users to log-in into KKBOX and grant permissions for you to do so. You cannot use client credentials to do media playback either, since it requires a Premium Membership. :return: an access token :rtype: :class:`kkbox_sdk.KKBOXAccessToken` See `https://docs-en.kkbox.codes/docs/appendix-a`. ''' cl...
= {'Authorization': 'Basic ' + client_credentials, 'Content-type': 'application/x-www-form-urlencoded'} post_parameters = {'grant_type': 'client_credentials', 'scope': 'user_profile user_territory'} json_object = self.http._post_data(KKBOXOAuth.OAUTH_TOKEN_URL, post_parameters, headers) self.access_token = KKBOXAccessT...
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}$' if re.search(uuid_regexp, os): return os raise Exception(( ...