code stringlengths 1 18.2k |
|---|
def load(self, filepath=None): """ Load settings file from given path and optionnal filepath. During path resolving, the ``projectdir`` is updated to the file path directory. Keyword Arguments: filepath (str): Filepath to the settings file. Returns: boussole.conf.model.Settings: Settings object with loaded options. """... |
async def withdraw_bulk(self, *args, **kwargs): """ Withdraw funds requests to user wallet Accepts: - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) - address [string] withdrawal address (in hex for tokens) - amount [int] withdrawal amount multiplied by decimals_k (10**8) Returns dictionary with following ... |
async def withdraw(self, *args, **kwargs): """ Withdraw funds to user wallet Accepts: - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) - address [string] withdrawal address (in hex for tokens) - amount [int] withdrawal amount multiplied by decimals_k (10**8) Returns dictionary with following fields: - txid... |
self.db.available_tokens.find_one({'_id': coinid}) if token is None: return WithdrawValidator.error_500('Unsupported coinid') elif token['blockchain'] in ('QTUM', 'QTUMTEST'): connection = self.connections[coinid] address = Bip32Addresses.address_to_hex(address) handler = Qrc20.from_connection( connection, token['contr... |
async def withdraw_custom_token(self, *args, **kwargs): """ Withdraw custom token to user wallet Accepts: - address [hex string] (withdrawal address in hex form) - amount [int] withdrawal amount multiplied by decimals_k (10**8) - blockchain [string] token's blockchain (QTUMTEST, ETH) - contract_address [hex string] tok... |
address = Web3.toChecksumAddress(address) contract_address = Web3.toChecksumAddress(contract_address) handler = Erc20.from_connection(connection, contract_address, erc20_abi) handler.set_send_params({ 'gasLimit': transfer_settings[blockchain]['gasLimit'], 'gasPrice': transfer_settings[blockchain]['gasPrice'], 'sender':... |
def relative_root_dir(self): """Build the relative root dir path for the bundle version.""" return Path(self.bundle.name) / str(self.created_at.date()) |
def full_path(self): """Return the full path to the file.""" if Path(self.path).is_absolute(): return self.path else: return str(self.app_root / self.path) |
def multiline_repr(text, special_chars=('\n', '"')): """Get string representation for triple quoted context. Make string representation as normal except do not transform "special characters" into an escaped representation to support use of the representation in a triple quoted multi-line string context (to avoid escapi... |
def _dedent(text): """Remove common indentation from each line in a text block. When text block is a single line, return text block. Otherwise determine common indentation from last line, strip common indentation from each line, and return text block consisting of inner lines (don't include first and last lines since t... |
len(lines[-1]) if any(line[:indent].strip() for line in lines): raise ValueError( 'indents must equal or exceed indent in last line') lines = [line[indent:] for line in lines][1:-1] return indent, '\n'.join(lines) |
def z__update(self): """Triple quoted baseline representation. Return string with multiple triple quoted baseline strings when baseline had been compared multiple times against varying strings. :returns: source file baseline replacement text :rtype: str """ updates = [] for text in self._updates: if self._AVOID_RAW_FOR... |
multi-line or when text ends with # characters that would otherwise result in a syntax error in # the formatted representation. multiline = self._indent or ('\n' in text) if multiline or text.endswith('\\') or text.endswith(quotes[0]): update = raw_char + quotes + '\n' + text_repr + '\n' + quotes else: update = raw_cha... |
def _atexit_callback(cls): """Create Python script copies with updated baselines. For any baseline that had a miscompare, make a copy of the source file which contained the baseline and update the baseline with the new string value. :returns: record of every Python file update (key=path, value=script instance) :rtype: ... |
def bundle(context, name): """Add a new bundle.""" if context.obj['db'].bundle(name): click.echo(click.style('bundle name already exists', fg='yellow')) context.abort() new_bundle = context.obj['db'].new_bundle(name) context.obj['db'].add_commit(new_bundle) # add default version new_version = context.obj['db'].new_vers... |
def file_cmd(context, tags, archive, bundle_name, path): """Add a file to a bundle.""" bundle_obj = context.obj['db'].bundle(bundle_name) if bundle_obj is None: click.echo(click.style(f"unknown bundle: {bundle_name}", fg='red')) context.abort() version_obj = bundle_obj.versions[0] new_file = context.obj['db'].new_file(... |
def tag(context: click.Context, file_id: int, tags: List[str]): """Add tags to an existing file.""" file_obj = context.obj['db'].file_(file_id) if file_obj is None: print(click.style('unable to find file', fg='red')) context.abort() for tag_name in tags: tag_obj = context.obj['db'].tag(tag_name) if tag_obj is None: tag... |
def include_version(global_root: str, version_obj: models.Version, hardlink:bool=True): """Include files in existing bundle version.""" global_root_dir = Path(global_root) if version_obj.included_at: raise VersionIncludedError(f"version included on {version_obj.included_at}") # generate root directory version_root_dir ... |
def checksum(path): """Calculcate checksum for a file.""" hasher = hashlib.sha1() with open(path, 'rb') as stream: buf = stream.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = stream.read(BLOCKSIZE) return hasher.hexdigest() |
def kwargs_only(func): """ Make a function only accept keyword arguments. This can be dropped in Python 3 in lieu of: def foo(*, bar=default): """ if hasattr(inspect, 'signature'): # pragma: no cover # Python 3 signature = inspect.signature(func) first_arg_name = list(signature.parameters.keys())[0] else: # pragma: no ... |
def get_prep_lookup(self, lookup_name, rhs): """ Perform preliminary non-db specific lookup checks and conversions """ if lookup_name == 'exact': if not isinstance(rhs, Model): raise FilteredGenericForeignKeyFilteringException( "For exact lookup, please pass a single Model instance.") elif lookup_name in ['in', 'in_raw... |
async def getaccountbywallet(**params): """Receives account by wallet Accepts: - public key hex or checksum format """ if params.get("message"): params = json.loads(params.get("message")) for coinid in coin_ids: database = client[coinid] wallet_collection = database[settings.WALLET] wallet = await wallet_collection.fin... |
async def create_account(self, **params): """Describes, validates data. """ logging.debug("\n\n[+] -- Create account debugging. ") model = { "unique": ["email", "public_key"], "required": ("public_key",), "default": {"count":len(settings.AVAILABLE_COIN_ID), "level":2, "news_count":0, "email":None}, "optional": ("phone"... |
coinid in coin_ids: database = client[coinid] wallet_collection = database[settings.WALLET] wallet = await wallet_collection.insert_one({ "account_id": account["id"], "wallet": self.account.validator[coinid](account["public_key"]) }) return account |
async def find_recent_news(self, **params): """Looking up recent news for account. Accepts: - public_key Returns: - list with dicts or empty """ # Check if params is not empty if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"... |
0}}) return news |
async def insert_news(self, **params): """Inserts news for account Accepts: - event_type - cid - access_string (of buyer) - buyer_pubkey - buyer address - owner address - price - offer type - coin ID Returns: - dict with result """ logging.debug("\n\n [+] -- Setting news debugging. ") if params.get("message"): params =... |
self.account.blockchain.ownerbycid(cid=cid) # Get sellers account seller = await getaccountbywallet(wallet=owneraddr) if "error" in seller.keys(): return seller # Connect to news table news_collection = self.database[settings.NEWS] # Get sellers price self.account.blockchain.setendpoint(settings.bridges[coinid]) if off... |
async def insert_offer(self, **params): """Inserts new offer to database (related to buyers account) Accepts: - cid - buyer address - price - access type - transaction id - owner public key - owner address - coin ID """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"e... |
async def get_offer(self, **params): """Receives offer data if exists Accepts: - cid - buyer address - coin ID """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = int(params.get("cid... |
found"} else: offer["coinid"] = coinid return {i:offer[i] for i in offer if i != "_id"} |
async def get_offers(self, **params): """Receives all users input (by cid) or output offers Accepts: - public key - cid (optional) - coinid (optional) """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = params.get("c... |
async def remove_offer(self, **params): """Receives offfer after have deal Accepts: - cid - buyer address - coin ID """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = int(params.get... |
async def update_offer(self, **params): """Updates offer after transaction confirmation Accepts: - transaction id - coinid - confirmed (boolean flag) """ logging.debug("\n\n -- Update offer. ") if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Misse... |
async def mailed_confirm(self, **params): """Sends mail to user after offer receiveing Accepts: - cid - buyer address - price - offer_type - point - coinid """ if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists cid = params.get("cid") buyer_address = params.get("buy... |
# "to": seller["email"], # "subject": "Robin8 support", # "optional": "You`ve got a new offer from %s" % seller["public_key"] # # } # await client_email.request(method_name="sendmail", **emaildata) # Send news for seller buyer = await getaccountbywallet(wallet=buyer_address) if "error" in buyer.keys(): buyer["public_ke... |
async def get_contents(self, **params): """Retrieves all users content Accepts: -public key """ logging.debug("[+] -- Get contents") if params.get("message"): params = json.loads(params.get("message", "{}")) if not params or not params.get("public_key"): return {"error":400, "reason":"Missed required fields"} # Try to ... |
async def set_contents(self, **params): """Writes users content to database Accepts: - public key (required) - content (required) - description - price - address """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} txid = p... |
async def update_contents(self, **params): """Updates users content row Accepts: - txid - cid - description - write_price - read_price - confirmed - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} txid = params.... |
async def set_access_string(self, **params): """Writes content access string to database """ if params.get("message"): params = json.loads(params.get("message", "{}")) cid = int(params.get("cid", "0")) seller_access_string = params.get("seller_access_string") seller_pubkey = params.get("seller_pubkey") coinid = params.... |
async def get_reviews(self, **params): """Receives all reviews by cid Accepts: - cid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = params.get("cid", 0) coinid = params.get("coinid") if not cid and not ... |
async def set_review(self, **params): """Writes review for content Accepts: - cid - review - public_key - rating - txid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = int(params.get("cid", 0)) txid = pa... |
async def update_review(self, **params): """Update review after transaction confirmation Accepts: - txid - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Check if required fields exists txid = params.get("txi... |
async def write_deal(self, **params): """Writes deal to database Accepts: - cid - access_type - buyer public key - seller public key - price - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} cid = int(params.get... |
async def update_description(self, **params): """Set description to unconfirmed status after updating by user. Accepts: - cid - description - transaction id - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Ch... |
# Get updated offer updated = await collection.find_one({"cid":int(cid)}) return {i:updated[i] for i in updated if i != "_id"} |
async def get_deals(self, **params): """Receives all users deals Accepts: - buyer public key """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} buyer = params.get("buyer") if not buyer: return {"error":400, "reason":"Miss... |
async def log_source(self, **params): """ Logging users request sources """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} # Insert new source if does not exists the one database = client[settings.DBNAME] source_collectio... |
async def log_transaction(self, **params): """Writing transaction to database """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} coinid = params.get("coinid") if not coinid in ["QTUM", "PUT"]: return {"error":400, "reason... |
def _check_node_list(path, sample, template, start_enumerate=0): """Check a list of nodes, e.g. function body""" if len(sample) != len(template): raise ASTNodeListMismatch(path, sample, template) for i, (sample_node, template_node) in enumerate(zip(sample, template), start=start_enumerate): if callable(template_node): ... |
def assert_ast_like(sample, template, _path=None): """Check that the sample AST matches the template. Raises a suitable subclass of :exc:`ASTMismatch` if a difference is detected. The ``_path`` parameter is used for recursion; you shouldn't normally pass it. """ if _path is None: _path = ['tree'] if callable(template):... |
sample_field != template_field: raise ASTPlainObjMismatch(field_path, sample_field, template_field) |
async def get(self): """ Accepts: without parameters Returns: list of dictionaries with following fields: - "description" - str - "read_access" - int - "write_access" - int - "cid" - int - "owneraddr" - str - "coinid" - str Verified: False """ logging.debug("\n\n All Content debugging --- ") page = self.get_query_argum... |
async def get(self, cid, coinid): """Receives content by content id and coin id Accepts: Query string arguments: - "cid" - int - "coinid" - str Returns: return dict with following fields: - "description" - str - "read_access" - int - "write_access" - int - "content" - str - "cid" - int - "owneraddr" - str - "owner" - s... |
= await self.account.getuserscontent(public_key=public_key) deals = await self.account.getdeals(buyer=public_key) if int(content["cid"]) in [i[0] for i in cids.get(coinid,[])]: content["access_type"] = "write_access" elif int(content["cid"]) in [i[0] for i in deals.get(coinid,[])]: content["access_type"] = "read_access... |
async def post(self, public_key, coinid): """Writes content to blockchain Accepts: Query string args: - "public_key" - str - "coin id" - str Request body arguments: - message (signed dict as json): - "cus" (content) - str - "description" - str - "read_access" (price for read access) - int - "write_access" (price for wr... |
account exists account = await self.account.getaccountdata(public_key=public_key) logging.debug("\n Users account ") logging.debug(account) if "error" in account.keys(): self.set_status(account["error"]) self.write(account) raise tornado.web.Finish # Get message from request try: data = json.loads(self.request.body) ex... |
await self.account.setuserscontent(public_key=public_key,hash=response["cus_hash"], coinid=coinid, txid=response["result"]["txid"],access="content") logging.debug("\n Database content") logging.debug(db_content) response = {i:data[i] for i in data if i != "cus"} self.write(response) |
async def put(self, cid): """Update description for content Accepts: Query string args: - "cid" - int Request body parameters: - message (signed dict): - "description" - str - "coinid" - str Returns: dict with following fields: - "confirmed": None - "txid" - str - "description" - str - "content" - str - "read_access" -... |
settings.bridges.keys(): self.set_status(400) self.write({"error":400, "reason":"Unknown coin id"}) raise tornado.web.Finish # Check if all required data exists if not all([public_key, descr, coinid]): self.set_status(400) self.write({"error":400, "reason":"Missed required fields"}) raise tornado.web.Finish owneraddr =... |
async def put(self, cid): """Update price of current content Accepts: Query string args: - "cid" - int Request body params: - "access_type" - str - "price" - int - "coinid" - str Returns: dict with following fields: - "confirmed": None - "txid" - str - "description" - str - "content" - str - "read_access" - int - "writ... |
# Check if required fields exists if not any([price, access_type, coinid]): self.set_status(400) self.write({"error":400, "reason":"Missed price and access type for content"}) # Set bridges url if coinid in settings.bridges.keys(): self.account.blockchain.setendpoint(settings.bridges[coinid]) else: self.set_status(400)... |
Fee fee = await billing.set_price_fee(cid=cid, price=price, owneraddr=owneraddr) if "error" in fee.keys(): self.set_status(fee["error"]) self.write(fee) raise tornado.web.Finish self.write(response) |
async def put(self, public_key): """Reject offer and unfreeze balance Accepts: - cid - buyer public key - buyer address """ if settings.SIGNATURE_VERIFICATION: super().verify() # Check if message contains required data try: body = json.loads(self.request.body) except: self.set_status(400) self.write({"error":400, "reas... |
buyer_address != hex_ and owneraddr != hex_: # Avoid rejecting offer self.set_status(403) self.write({"error": 403, "reason":"Forbidden. Offer does not belong to user."}) # Reject offer response = await self.account.blockchain.rejectoffer(coinid=coinid, cid=cid, buyer_address=buyer_address) if "error" in response.keys(... |
async def post(self, public_key=None): """Creates new offer Accepts: - buyer public key - cid - buyer access string Returns: - offer parameters as dictionary """ if settings.SIGNATURE_VERIFICATION: super().verify() try: body = json.loads(self.request.body) except: self.set_status(400) self.write({"error":400, "reason":... |
# If account does not exist self.set_status(account["error"]) self.write(account) raise tornado.web.Finish #Get sellers balance balances = await self.account.balance.get_wallets(coinid=coinid, uid=account["id"]) # Check if current content does not belong to current user if owneraddr == buyer_address: self.set_status(40... |
"error" in seller.keys(): self.set_status(seller["error"]) self.write(seller) raise tornado.web.Finish if seller.get("email"): emaildata = { "to": seller["email"], "subject": "Robin8 support", "optional": "You`ve got an offer for content %s." % cid } await self.account.mailer.sendmail(**emaildata) # Freeze price at bal... |
async def post(self, public_key): """Accepting offer by buyer Function accepts: - cid - buyer access string - buyer public key - seller public key """ logging.debug("[+] -- Deal debugging. ") if settings.SIGNATURE_VERIFICATION: super().verify() # Check if message contains required data try: body = json.loads(self.reque... |
= await self.account.getaccountdata(public_key=public_key) logging.debug("\n Seller account") logging.debug(seller_account) try: error_code = seller_account["error"] except: pass else: self.set_status(error_code) self.write(seller_account) raise tornado.web.Finish buyer_account = await self.account.getaccountdata(publi... |
logging.debug("\n Write access") # Fee fee = await billing.change_owner_fee(cid=cid, new_owner=buyer_pubkey) if "error" in fee.keys(): self.set_status(fee["error"]) self.write(fee) raise tornado.web.Finish # Change content owner chownerdata = { "cid":cid, "new_owner": buyer_address, "access_string": buyer_access_string... |
= await self.account.balance.sub_active(uid=buyer_account["id"], coinid=coinid, amount=price) logging.debug("\n Sub active") logging.debug(sub_active) add_frozen = await self.account.balance.add_frozen(uid=seller_account["id"], amount=price, coinid=coinid) logging.debug("\n Add frozen") logging.debug(add_frozen) # Writ... |
async def get(self, cid, coinid): """Receives all contents reviews """ if settings.SIGNATURE_VERIFICATION: super().verify() if coinid in settings.bridges.keys(): self.account.blockchain.setendpoint(settings.bridges[coinid]) reviews = await self.account.blockchain.getreviews(cid=cid) if isinstance(reviews, dict): if "er... |
async def post(self, public_key): """Writes contents review """ if settings.SIGNATURE_VERIFICATION: super().verify() try: body = json.loads(self.request.body) except: self.set_status(400) self.write({"error":400, "reason":"Unexpected data format. JSON required"}) raise tornado.web.Finish if isinstance(body["message"], ... |
def sendmail(array): """function for read data in db and send mail """ username = 'root@robin8.io' FROM = username TO = [array["to"]] SUBJECT = array["subject"] # check on correct data in optional if type(array["optional"]) == str and array["optional"]: TEXT = array["optional"] else: return "Error: missed argument" # m... |
async def post(self): """Creates new account Accepts: - message (signed dict): - "device_id" - str - "email" - str - "phone" - str - "public_key" - str - "signature" - str Returns: dictionary with following fields: - "device_id" - str - "phone" - str - "public_key" - str - "count" - int ( wallets amount ) - "level" - i... |
logging.debug("\n\n [+] -- New account debugging.") logging.debug(new_account["id"]) if "error" in new_account.keys(): # Raise error if the one does exist self.set_status(new_account["error"]) self.write(new_account) raise tornado.web.Finish # Receive balance from balance host wallets = await self.account.balance.get_w... |
async def get(self, public_key): """ Receive account data Accepts: Query string: - "public_key" - str Query string params: - message ( signed dictionary ): - "timestamp" - str Returns: - "device_id" - str - "phone" - str - "public_key" - str - "count" - int ( wallets amount ) - "level" - int (2 by default) - "news_coun... |
self.write(response) raise tornado.web.Finish # Receive balances from balance host wallets = await self.account.balance.get_wallets(uid=response["id"]) if isinstance(wallets, dict): if "error" in wallets.keys(): self.set_status(wallets["error"]) self.write(wallets) raise tornado.web.Finish # Filter wallets response.upd... |
async def get(self, public_key): """Receives public key, looking up document at storage, sends document id to the balance server """ if settings.SIGNATURE_VERIFICATION: super().verify() response = await self.account.getnews(public_key=public_key) # If we`ve got a empty or list with news if isinstance(response, list): s... |
async def get(self, public_key): """Retrieves all users input and output offers Accepts: - public key """ # Sign-verifying functional #super().verify() # Get coinid account = await self.account.getaccountdata(public_key=public_key) if "error" in account.keys(): self.set_status(account["error"]) self.write(account) rais... |
async def get(self, public_key): """Retrieves all users input and output offers Accepts: - public key """ # Sign-verifying functional if settings.SIGNATURE_VERIFICATION: super().verify() logging.debug("\n\n -- Input offers debugging") message = json.loads(self.get_argument("message")) cid = message.get("cid") coinid = ... |
async def get(self, public_key): """Retrieves all users contents Accepts: - public key """ # Sign-verifying functional if settings.SIGNATURE_VERIFICATION: super().verify() page = self.get_query_argument("page", 1) cids = await self.account.getuserscontent(public_key=public_key) logging.debug("\n\n Users cids") logging.... |
async def post(self): """ Funds from account to given address. 1. Verify signature 2. Freeze senders amount. 3. Request to withdraw server. 4. Call balances sub_frozen method. Accepts: - message [dict]: - coinid [string] - amount [integer] - address [string] - timestamp [float] - recvWindow [float] - public_key - signa... |
message.get("address") timestamp = message.get("timestamp") recvWindow = message.get("recvWindow") # if not all([coinid, amount, address, public_key, signature, timestamp, recvWindow]): data.update({"error":400, "reason":"Missed required fields. "}) self.set_status(400) self.write(data) raise tornado.web.Finish logging... |
#if "error" in add_active.keys(): # await self.account.balance.unfreeze(uid=account["id"], coinid=coinid, # amount=amount + fee) # data.update(add_active) # self.set_status(add_active["error"]) # self.write(data) # raise tornado.web.Finish # Submit amount from frozen balance sub_frozen = await self.account.balance.sub_... |
async def upload_content_fee(*args, **kwargs): """Estimating uploading content """ cus = kwargs.get("cus") owneraddr = kwargs.get("owneraddr") description = kwargs.get("description") coinid = kwargs.get("coinid", "PUT") #Check if required fields exists if not all([cus, owneraddr, description]): return {"error":400, "re... |
if "error" in decbalance.keys(): return decbalance else: return {"result":"ok"} |
def __get_supervisor(self): """ Return the supervisor proxy object Should probably use this more rather than supervisorctl directly """ options = supervisorctl.ClientOptions() options.realize(args=['-c', self.supervisord_conf_path]) return supervisorctl.Controller(options).get_supervisor() |
def update(self): """ Add newly defined servers, remove any that are no longer present """ configs, meta_changes = self.config_manager.determine_config_changes() self._process_config_changes(configs, meta_changes) self.supervisorctl('update') |
def receive_data(self): # pragma: no cover; no covered since qt event loop ''' Infinite loop via QObject.moveToThread(), does not block event loop ''' while(not self._stop_readout.wait(0.01)): # use wait(), do not block if self._send_data: if self.socket_type != zmq.DEALER: raise RuntimeError('You send data without a b... |
def parse_object(self, data): """ Look for datetime looking strings. """ for key, value in data.items(): if isinstance(value, (str, type(u''))) and \ self.strict_iso_match.match(value): data[key] = dateutil.parser.parse(value) return data |
def getPiLambert(n): """Returns a list containing first n digits of Pi """ mypi = piGenLambert() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result |
def extract(self, destination): """Extracts the contents of the archive to the specifed directory. Args: destination (str): Path to an empty directory to extract the files to. """ if os.path.exists(destination): raise OSError(20, 'Destination exists', destination) self.__extract_directory( '.', self.files['files'], des... |
def __extract_directory(self, path, files, destination): """Extracts a single directory to the specified directory on disk. Args: path (str): Relative (to the root of the archive) path of the directory to extract. files (dict): A dictionary of files from a *.asar file header. destination (str): The path to extract the ... |
def __extract_file(self, path, fileinfo, destination): """Extracts the specified file to the specified destination. Args: path (str): Relative (to the root of the archive) path of the file to extract. fileinfo (dict): Dictionary containing the offset and size of the file (Extracted from the header). destination (str): ... |
def __copy_extracted(self, path, destination): """Copies a file that was already extracted to the destination directory. Args: path (str): Relative (to the root of the archive) of the file to copy. destination (str): Directory to extract the archive to. """ unpacked_dir = self.filename + '.unpacked' if not os.path.isdi... |
def open(cls, filename): """Opens a *.asar file and constructs a new :see AsarArchive instance. Args: filename (str): Path to the *.asar file to open for reading. Returns (AsarArchive): An insance of of the :AsarArchive class or None if reading failed. """ asarfile = open(filename, 'rb') # uses google's pickle format, ... |
of pickle padding asarfile.seek(asarfile.tell() + 8) header = asarfile.read(header_size).decode('utf-8') files = json.loads(header) return cls(filename, asarfile, files, asarfile.tell()) |
def value_from_datadict(self, data, files, name): """Ensure the payload is a list of values. In the case of a sub form, we need to ensure the data is returned as a list and not a dictionary. When a dict is found in the given data, we need to ensure the data is converted to a list perseving the field order. """ if name ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.