code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Takes a block_representation and returns the nonce ''' return get_block_overview(block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
def get_nonce(block_representation, coin_symbol='btc', api_key=None)
Takes a block_representation and returns the nonce
6.032659
5.152444
1.170834
''' Takes a block_representation and returns the previous block hash ''' return get_block_overview(block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['prev_block']
def get_prev_block_hash(block_representation, coin_symbol='btc', api_key=None)
Takes a block_representation and returns the previous block hash
4.887414
4.054458
1.205442
''' Takes a block_height and returns the block_hash ''' return get_block_overview(block_representation=block_height, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['hash']
def get_block_hash(block_height, coin_symbol='btc', api_key=None)
Takes a block_height and returns the block_hash
6.433332
5.447356
1.181001
''' Takes a block_hash and returns the block_height ''' return get_block_overview(block_representation=block_hash, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['height']
def get_block_height(block_hash, coin_symbol='btc', api_key=None)
Takes a block_hash and returns the block_height
6.402682
5.397964
1.186129
assert is_valid_coin_symbol(coin_symbol) block_overview = get_block_overview( block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=txn_limit, txn_offset=txn_offset, api_key=api_key, ) if 'error' in block...
def get_block_details(block_representation, coin_symbol='btc', txn_limit=None, txn_offset=None, in_out_limit=None, api_key=None)
Takes a block_representation, coin_symbol and txn_limit and 1) Gets the block overview 2) Makes a separate API call to get specific data on txn_limit transactions Note: block_representation may be the block number or block hash WARNING: using a high txn_limit will make this *extremely* slow.
2.47925
2.510521
0.987544
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key) return { 'high_fee_per_kb': overview['high_fee_per_kb'], 'medium_fee_per_kb': overview['medium_fee_per_kb'], 'low_fee_per_kb': overview['low_fee_per_kb'], }
def get_blockchain_fee_estimates(coin_symbol='btc', api_key=None)
Returns high, medium, and low fee estimates for a given blockchain.
1.995458
1.80701
1.104287
assert is_valid_coin_symbol(coin_symbol) assert api_key, 'api_key required' url = make_url(coin_symbol, 'payments') logger.info(url) params = {'token': api_key} data = { 'destination': destination_address, } if callback_url: data['callback_url'] = cal...
def get_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc')
Give a destination address and return the details of the input address that will automatically forward to the destination address Note: a blockcypher api_key is required for this method
2.952558
3.064298
0.963535
assert api_key, 'api_key required' resp_dict = get_forwarding_address_details( destination_address=destination_address, api_key=api_key, callback_url=callback_url, coin_symbol=coin_symbol ) return resp_dict['input_address']
def get_forwarding_address(destination_address, api_key, callback_url=None, coin_symbol='btc')
Give a destination address and return an input address that will automatically forward to the destination address. See get_forwarding_address_details if you also need the forwarding address ID. Note: a blockcypher api_key is required for this method
3.152981
2.762541
1.141334
''' List the forwarding addresses for a certain api key (and on a specific blockchain) ''' assert is_valid_coin_symbol(coin_symbol) assert api_key url = make_url(coin_symbol, 'payments') params = {'token': api_key} if offset: params['start'] = offset r = requests.get...
def list_forwarding_addresses(api_key, offset=None, coin_symbol='btc')
List the forwarding addresses for a certain api key (and on a specific blockchain)
4.842745
3.334597
1.452273
''' Delete a forwarding address on a specific blockchain, using its payment id ''' assert payment_id, 'payment_id required' assert is_valid_coin_symbol(coin_symbol) assert api_key, 'api_key required' params = {'token': api_key} url = make_url(**dict(payments=payment_id)) r = ...
def delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None)
Delete a forwarding address on a specific blockchain, using its payment id
4.637092
3.70587
1.251283
''' Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription ''' assert is_valid_coin_symbol(coin_symbol) assert is_valid_address_for_coinsymbol(subscription_address, coin_symbol)...
def subscribe_to_address_webhook(callback_url, subscription_address, event='tx-confirmation', confirmations=0, confidence=0.00, coin_symbol='btc', api_key=None)
Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription
3.433387
2.435581
1.409678
''' Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription ''' assert is_valid_coin_symbol(coin_symbol) assert is_valid_wallet_name(wallet_name), wallet_name assert api_key,...
def subscribe_to_wallet_webhook(callback_url, wallet_name, event='tx-confirmation', coin_symbol='btc', api_key=None)
Subscribe to transaction webhooks on a given address. Webhooks for transaction broadcast and each confirmation (up to 6). Returns the blockcypher ID of the subscription
3.935147
2.455993
1.602263
''' Send yourself test coins on the bitcoin or blockcypher testnet You can see your balance info at: - https://live.blockcypher.com/bcy/ for BCY - https://live.blockcypher.com/btc-testnet/ for BTC Testnet ''' assert coin_symbol in ('bcy', 'btc-testnet') assert is_valid_address_for_coins...
def send_faucet_coins(address_to_fund, satoshis, api_key, coin_symbol='bcy')
Send yourself test coins on the bitcoin or blockcypher testnet You can see your balance info at: - https://live.blockcypher.com/bcy/ for BCY - https://live.blockcypher.com/btc-testnet/ for BTC Testnet
3.588143
2.305287
1.556484
''' Takes a signed transaction hex binary (and coin_symbol) and broadcasts it to the bitcoin network. ''' assert is_valid_coin_symbol(coin_symbol) assert api_key, 'api_key required' url = _get_pushtx_url(coin_symbol=coin_symbol) logger.info(url) data = {'tx': tx_hex} params = {'...
def pushtx(tx_hex, coin_symbol='btc', api_key=None)
Takes a signed transaction hex binary (and coin_symbol) and broadcasts it to the bitcoin network.
3.804459
2.790054
1.363579
''' Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON. Does NOT broadcast the transaction to the bitcoin network. Especially useful for testing/debugging and sanity checking ''' assert is_valid_coin_symbol(coin_symbol) assert api_key, 'api_key required' ur...
def decodetx(tx_hex, coin_symbol='btc', api_key=None)
Takes a signed transaction hex binary (and coin_symbol) and decodes it to JSON. Does NOT broadcast the transaction to the bitcoin network. Especially useful for testing/debugging and sanity checking
5.063103
2.826936
1.791021
''' Get all the wallets belonging to an API key ''' assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key params = {'token': api_key} kwargs = dict(wallets='hd' if is_hd_wallet else '') url = make_url(coin_symbol, **kwargs) r = requests.get(url, params=params, verify=True, ...
def list_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc')
Get all the wallets belonging to an API key
4.459505
4.283279
1.041143
''' Create a new wallet with one address You can add addresses with the add_address_to_wallet method below You can delete the wallet with the delete_wallet method below ''' assert is_valid_address_for_coinsymbol(address, coin_symbol) assert api_key assert is_valid_wallet_name(wallet_nam...
def create_wallet_from_address(wallet_name, address, api_key, coin_symbol='btc')
Create a new wallet with one address You can add addresses with the add_address_to_wallet method below You can delete the wallet with the delete_wallet method below
3.865485
2.845682
1.358369
''' Create a new wallet from an extended pubkey (xpub... for BTC) You can delete the wallet with the delete_wallet method below ''' inferred_coin_symbol = coin_symbol_from_mkey(mkey=xpubkey) if inferred_coin_symbol: assert inferred_coin_symbol == coin_symbol assert api_key, 'api_key...
def create_hd_wallet(wallet_name, xpubkey, api_key, subchain_indices=[], coin_symbol='btc')
Create a new wallet from an extended pubkey (xpub... for BTC) You can delete the wallet with the delete_wallet method below
4.689094
3.452906
1.358014
''' Returns a list of wallet addresses as well as some meta-data ''' assert is_valid_coin_symbol(coin_symbol) assert api_key assert len(wallet_name) <= 25, wallet_name assert zero_balance in (None, True, False) assert used in (None, True, False) assert isinstance(omit_addresses, bool...
def get_wallet_addresses(wallet_name, api_key, is_hd_wallet=False, zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc')
Returns a list of wallet addresses as well as some meta-data
2.716808
2.553667
1.063885
''' This is particularly useful over get_wallet_transactions and get_wallet_addresses in cases where you have lots of addresses/transactions. Much less data to return. ''' assert is_valid_coin_symbol(coin_symbol) assert api_key assert len(wallet_name) <= 25, wallet_name assert isinst...
def get_wallet_balance(wallet_name, api_key, omit_addresses=False, coin_symbol='btc')
This is particularly useful over get_wallet_transactions and get_wallet_addresses in cases where you have lots of addresses/transactions. Much less data to return.
4.428653
2.660682
1.66448
''' Takes an unsigned transaction and what was used to build it (in create_unsigned_tx) and verifies that tosign_tx matches what is being signed and what was requestsed to be signed. Returns if valid: (True, '') Returns if invalid: (False, 'err_msg') Specifically, this chec...
def verify_unsigned_tx(unsigned_tx, outputs, inputs=None, sweep_funds=False, change_address=None, coin_symbol='btc')
Takes an unsigned transaction and what was used to build it (in create_unsigned_tx) and verifies that tosign_tx matches what is being signed and what was requestsed to be signed. Returns if valid: (True, '') Returns if invalid: (False, 'err_msg') Specifically, this checks that the ...
4.993584
3.183407
1.568629
assert len(privkey_list) == len(pubkey_list) == len(txs_to_sign) # in the event of multiple inputs using the same pub/privkey, # that privkey should be included multiple times signatures = [] for cnt, tx_to_sign in enumerate(txs_to_sign): sig = der_encode_sig(*ecdsa_raw_sign(tx_to_sign...
def make_tx_signatures(txs_to_sign, privkey_list, pubkey_list)
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list Not sure what privkeys and pubkeys to supply? Use get_input_addresses() to return a list of addresses. Matching those addresses to keys is up to you and how you store your private keys. A future version of this library ma...
3.182087
3.246699
0.980099
''' Broadcasts the transaction from create_unsigned_tx ''' assert 'errors' not in unsigned_tx, unsigned_tx assert api_key, 'api_key required' url = make_url(coin_symbol, **dict(txs='send')) data = unsigned_tx.copy() data['signatures'] = signatures data['pubkeys'] = pubkeys pa...
def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol='btc', api_key=None)
Broadcasts the transaction from create_unsigned_tx
3.895345
3.413553
1.141141
''' Get metadata using blockcypher's API. This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain. ''' assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key or not private, 'Cannot see private metadata without an API key' kwarg = get_val...
def get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc')
Get metadata using blockcypher's API. This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
4.725395
3.136583
1.506543
''' Embed metadata using blockcypher's API. This is not embedded into the bitcoin (or other) blockchain, and is only stored on blockcypher's servers. ''' assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key assert metadata_dict and isinstance(metadata_dict, dict), metada...
def put_metadata(metadata_dict, address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc')
Embed metadata using blockcypher's API. This is not embedded into the bitcoin (or other) blockchain, and is only stored on blockcypher's servers.
4.079915
2.702139
1.509883
''' Only available for metadata that was embedded privately. ''' assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key, 'api_key required' kwarg = get_valid_metadata_identifier( coin_symbol=coin_symbol, address=address, tx_hash=tx_hash, block_hash=...
def delete_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, coin_symbol='btc')
Only available for metadata that was embedded privately.
4.214725
3.263544
1.291456
''' convert to satoshis, no rounding ''' assert input_type in UNIT_CHOICES, input_type # convert to satoshis if input_type in ('btc', 'mbtc', 'bit'): satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per']) elif input_type == 'satoshi': satoshis = input_qu...
def to_satoshis(input_quantity, input_type)
convert to satoshis, no rounding
3.231972
3.113619
1.038011
''' Safe trimming means the following: 1.0010000 -> 1.001 1.0 -> 1.0 (no change) 1.0000001 -> 1.0000001 (no change) ''' qty_formatted = qty_as_string if '.' in qty_as_string: # only affect numbers with decimals while True: if qty_formatted[-1] == '...
def safe_trim(qty_as_string)
Safe trimming means the following: 1.0010000 -> 1.001 1.0 -> 1.0 (no change) 1.0000001 -> 1.0000001 (no change)
3.222228
1.99059
1.61873
''' Take an input like 11002343 satoshis and convert it to another unit (e.g. BTC) and format it with appropriate units if coin_symbol is supplied and print_cs == True then the units will be added (e.g. BTC or satoshis) Smart trimming gets rid of trailing 0s in the decimal place, except for satoshis (...
def format_crypto_units(input_quantity, input_type, output_type, coin_symbol=None, print_cs=False, safe_trimming=False, round_digits=0)
Take an input like 11002343 satoshis and convert it to another unit (e.g. BTC) and format it with appropriate units if coin_symbol is supplied and print_cs == True then the units will be added (e.g. BTC or satoshis) Smart trimming gets rid of trailing 0s in the decimal place, except for satoshis (irrelevant) ...
4.624944
1.945679
2.377034
''' Used to verify a transaction hex does what's expected of it. Must supply a list of output addresses so that the library can try to convert from script to address using both pubkey and script. Returns a list of the following form: [{'value': 12345, 'address': '1abc...'}, ...] Uses ...
def get_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol)
Used to verify a transaction hex does what's expected of it. Must supply a list of output addresses so that the library can try to convert from script to address using both pubkey and script. Returns a list of the following form: [{'value': 12345, 'address': '1abc...'}, ...] Uses @vbuterin's ...
4.016279
2.569279
1.563193
''' Take a list of txn ouputs (from get_txn_outputs output of pybitcointools) and compress it to the sum of satoshis sent to each address in a dictionary. Returns a dict of the following form: {'1abc...': 12345, '1def': 54321, ...} ''' result_dict = {} outputs = (output for output i...
def compress_txn_outputs(txn_outputs)
Take a list of txn ouputs (from get_txn_outputs output of pybitcointools) and compress it to the sum of satoshis sent to each address in a dictionary. Returns a dict of the following form: {'1abc...': 12345, '1def': 54321, ...}
3.474239
1.594452
2.178955
''' Blockcypher limits wallet names to 25 chars. Hash the master pubkey (with subchain indexes) and take the first 25 chars. Hackey determinstic method for naming. ''' # http://stackoverflow.com/a/19877309/1754586 mpub = mpub.encode('utf-8') if subchain_indices: mpub += ','....
def get_blockcypher_walletname_from_mpub(mpub, subchain_indices=[])
Blockcypher limits wallet names to 25 chars. Hash the master pubkey (with subchain indexes) and take the first 25 chars. Hackey determinstic method for naming.
6.061759
2.882118
2.103231
''' Flattens a response from querying a list of address (or wallet) transactions If nesting==True then it will return an ordered dictionary where the keys are tranasaction hashes, otherwise it will be a list of dicts. (nesting==False is good for django templates) ''' nested_cleaned_txs = Ordere...
def flatten_txns_by_hash(tx_list, nesting=True)
Flattens a response from querying a list of address (or wallet) transactions If nesting==True then it will return an ordered dictionary where the keys are tranasaction hashes, otherwise it will be a list of dicts. (nesting==False is good for django templates)
2.577787
1.890454
1.363581
if byteorder == 'little': indexes = range(length) else: indexes = reversed(range(length)) return bytearray((n >> i * 8) & 0xff for i in indexes)
def _long_to_bytes(n, length, byteorder)
Convert a long to a bytestring For use in python version prior to 3.2 Source: http://bugs.python.org/issue16580#msg177208
2.564467
2.804566
0.91439
''' Is an address both valid *and* start with the correct character for its coin symbol (chain/network) ''' assert is_valid_coin_symbol(coin_symbol) if b58_address[0] in COIN_SYMBOL_MAPPINGS[coin_symbol]['address_first_char_list']: if is_valid_address(b58_address): return Tr...
def is_valid_address_for_coinsymbol(b58_address, coin_symbol)
Is an address both valid *and* start with the correct character for its coin symbol (chain/network)
5.611725
2.591873
2.165124
start = datetime.now() - timedelta(days=1) return start.replace(hour=0, minute=0, second=0, microsecond=0)
def default_validity_start()
Sets validity_start field to 1 day before the current date (avoids "certificate not valid yet" edge case). In some cases, because of timezone differences, when certificates were just created they were considered valid in a timezone (eg: Europe) but not yet valid in another timezone (eg: US). This ...
2.478956
2.756308
0.899375
now = timezone.now() return self.cert_set.filter(revoked=True, validity_start__lte=now, validity_end__gte=now)
def get_revoked_certs(self)
Returns revoked certificates of this CA (does not include expired certificates)
3.864435
3.419842
1.130004
revoked_certs = self.get_revoked_certs() crl = crypto.CRL() now_str = timezone.now().strftime(generalized_time) for cert in revoked_certs: revoked = crypto.Revoked() revoked.set_serial(bytes_compat(cert.serial_number)) revoked.set_reason(b'uns...
def crl(self)
Returns up to date CRL of this CA
3.48236
3.356411
1.037525
now = timezone.now() self.revoked = True self.revoked_at = now self.save()
def revoke(self)
* flag certificate as revoked * fill in revoked_at DateTimeField
4.183501
3.263391
1.281949
authenticated = request.user.is_authenticated authenticated = authenticated() if callable(authenticated) else authenticated if app_settings.CRL_PROTECTED and not authenticated: return HttpResponse(_('Forbidden'), status=403, content_type='...
def crl(request, pk)
returns CRL of a CA
3.609699
3.369629
1.071245
small_font = [] medium_font = [] large_font = [] xlarge_font = [] fonts = set(font_map.keys()) - set(RANDOM_FILTERED_FONTS) for font in fonts: length = max(map(len, font_map[font][0].values())) if length <= FONT_SMALL_THRESHOLD: small_font.append(font) el...
def font_size_splitter(font_map)
Split fonts to 4 category (small,medium,large,xlarge) by maximum length of letter in each font. :param font_map: input fontmap :type font_map : dict :return: splitted fonts as dict
1.998098
1.924521
1.038232
fonts = set(FONT_MAP.keys()) if test: fonts = fonts - set(TEST_FILTERED_FONTS) for item in sorted(list(fonts)): print(str(item) + " : ") text_temp = text try: tprint(text_temp, str(item)) except Exception: print(FONT_ENVIRONMENT_WARNING)
def font_list(text="test", test=False)
Print all fonts. :param text : input text :type text : str :param test: test flag :type test: bool :return: None
6.143719
7.233702
0.849319
for i in sorted(list(art_dic.keys())): try: if test: raise Exception print(i) aprint(i) line() except Exception: print(ART_ENVIRONMENT_WARNING) line() if test: break
def art_list(test=False)
Print all 1-Line arts. :param test : exception test flag :type test : bool :return: None
7.458127
7.955682
0.937459
tprint("art") tprint("v" + VERSION) print(DESCRIPTION + "\n") print("Webpage : http://art.shaghighi.ir\n") print("Help : \n") print(" - list --> (list of arts)\n") print(" - fonts --> (list of fonts)\n") print(" - test --> (run tests)\n") print(" - text 'yourtext...
def help_func()
Print help page. :return: None
5.236255
5.422133
0.965719
print(art(artname=artname, number=number, text=text))
def aprint(artname, number=1, text="")
Print 1-line art. :param artname: artname :type artname : str :return: None
3.765962
5.615166
0.670677
if isinstance(artname, str) is False: raise artError(ART_TYPE_ERROR) artname = artname.lower() arts = sorted(art_dic.keys()) if artname == "random" or artname == "rand" or artname == "rnd": filtered_arts = list(set(arts) - set(RANDOM_FILTERED_ARTS)) artname = random.choice(f...
def art(artname, number=1, text="")
Return 1-line art. :param artname: artname :type artname : str :return: ascii art as str
2.505733
2.562607
0.977806
r result = text2art(text, font=font, chr_ignore=chr_ignore) print(result)
def tprint(text, font=DEFAULT_FONT, chr_ignore=True)
r""" Print art text (support \n). :param text: input text :type text:str :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :return: None
7.040537
6.901722
1.020113
r try: if isinstance(text, str) is False: raise Exception(TEXT_TYPE_ERROR) files_list = os.listdir(os.getcwd()) extension = ".txt" splitted_filename = filename.split(".") name = splitted_filename[0] if len(splitted_filename) > 1: extension ...
def tsave( text, font=DEFAULT_FONT, filename="art", chr_ignore=True, print_status=True)
r""" Save ascii art (support \n). :param text: input text :param font: input font :type font:str :type text:str :param filename: output file name :type filename:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :param print_status : save message print f...
2.538614
2.568591
0.988329
if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2 + 1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append( ...
def distance_calc(s1, s2)
Calculate Levenshtein distance between two words. :param s1: first word :type s1 : str :param s2: second word :type s2 : str :return: distance between two word References : 1- https://stackoverflow.com/questions/2460177/edit-distance-in-python 2- https://en.wikipedia.org/wiki/Levenshte...
1.30107
1.306021
0.996209
text_length = len(text) if text_length <= TEXT_XLARGE_THRESHOLD: font = random.choice(XLARGE_WIZARD_FONT) elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD: font = random.choice(LARGE_WIZARD_FONT) elif text_length > TEXT_LARGE_THRESHOLD and text_length...
def wizard_font(text)
Check input text length for wizard mode. :param text: input text :type text:str :return: font as str
1.888946
1.889684
0.999609
if font == "rnd-small" or font == "random-small" or font == "rand-small": font = random.choice(RND_SIZE_DICT["small_list"]) return font if font == "rnd-medium" or font == "random-medium" or font == "rand-medium": font = random.choice(RND_SIZE_DICT["medium_list"]) return font...
def indirect_font(font, fonts, text)
Check input font for indirect modes. :param font: input font :type font : str :param fonts: fonts list :type fonts : list :param text: input text :type text:str :return: font as str
2.063862
2.076214
0.994051
split_list = [] result_list = [] splitter = "\n" for i in word: if (ord(i) == 9) or (ord(i) == 32 and font == "block"): continue if (i not in letters.keys()): if (chr_ignore): continue else: raise artError(str(i) + ...
def __word2art(word, font, chr_ignore, letters)
Return art word. :param word: input word :type word: str :param font: input font :type font: str :param chr_ignore: ignore not supported character :type chr_ignore: bool :param letters: font letters table :type letters: dict :return: ascii art as str
3.10078
3.013554
1.028945
r letters = standard_dic text_temp = text if isinstance(text, str) is False: raise artError(TEXT_TYPE_ERROR) if isinstance(font, str) is False: raise artError(FONT_TYPE_ERROR) font = font.lower() fonts = sorted(FONT_MAP.keys()) font = indirect_font(font, fonts, text) ...
def text2art(text, font=DEFAULT_FONT, chr_ignore=True)
r""" Return art text (support \n). :param text: input text :type text:str :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :return: ascii art text as str
3.768334
3.694114
1.020091
if isinstance(font, str) is False: raise artError(FONT_TYPE_ERROR) if isinstance(chr_ignore, bool) is False: raise artError(CHR_IGNORE_TYPE_ERROR) if isinstance(filename, str) is False: raise artError(FILE_TYPE_ERROR) if isinstance(print_status, bool) is False: raise...
def set_default(font=DEFAULT_FONT, chr_ignore=True, filename="art", print_status=True)
Change text2art, tprint and tsave default values. :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :param filename: output file name (only tsave) :type filename:str :param print_status : save message print flag (only tsave) :...
2.225178
1.919119
1.159479
if not name and not callable(fn): name = fn fn = None def inner(fn): if isinstance(fn, Predicate): return fn p = Predicate(fn, name, **options) update_wrapper(p, fn) return p if fn: return inner(fn) else: return inner
def predicate(fn=None, name=None, **options)
Decorator that constructs a ``Predicate`` instance from any function:: >>> @predicate ... def is_book_author(user, book): ... return user == book.author ... >>> @predicate(bind=True) ... def is_book_author(self, user, book): ... if self.context.args: ...
2.571451
3.878065
0.663076
def _getter(request, *view_args, **view_kwargs): if attr_name not in view_kwargs: raise ImproperlyConfigured( 'Argument {0} is not available. Given arguments: [{1}]' .format(attr_name, ', '.join(view_kwargs.keys()))) try: return get_object...
def objectgetter(model, attr_name='pk', field_name='pk')
Helper that returns a function suitable for use as the ``fn`` argument to the ``permission_required`` decorator. Internally uses ``get_object_or_404``, so keep in mind that this may raise ``Http404``. ``model`` can be a model class, manager or queryset. ``attr_name`` is the name of the view attribute....
2.469774
2.622897
0.941621
def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): # Normalize to a list of permissions if isinstance(perm, six.string_types): perms = (perm,) else: per...
def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME)
View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules.contrib.views import permission_required from posts.models import Post def get_post_by_pk(request, post_id): ...
2.300847
2.230581
1.031501
if not isinstance(self, BaseCreateView): # We do NOT want to call get_object in a BaseCreateView, see issue #85 if hasattr(self, 'get_object') and callable(self.get_object): # Requires SingleObjectMixin or equivalent ``get_object`` method return s...
def get_permission_object(self)
Override this method to provide the object to check for permission against. By default uses ``self.get_object()`` as provided by ``SingleObjectMixin``. Returns None if there's no ``get_object`` method.
7.283558
5.823723
1.25067
self._base_dir = base_dir self.icon_cache.set_base_dir(base_dir)
def set_base_dir(self, base_dir)
Set the base directory to be used for all relative filenames.
4.284178
3.965572
1.080343
align_flags = None for qt_align in alignment.split('|'): _, qt_align = qt_align.split('::') align = getattr(QtCore.Qt, qt_align) if align_flags is None: align_flags = align else: align_flags |= align return align_flags
def _parse_alignment(alignment)
Convert a C++ alignment to the corresponding flags.
4.087697
3.071755
1.330737
row = elem.attrib.get('row') column = elem.attrib.get('column') alignment = elem.attrib.get('alignment') # See if it is a box layout. if row is None or column is None: if alignment is None: return () return (0, _parse_alignment(alignment)) # It must be a grid...
def _layout_position(elem)
Return either (), (0, alignment), (row, column, rowspan, colspan) or (row, column, rowspan, colspan, alignment) depending on the type of layout and its configuration. The result will be suitable to use as arguments to the layout.
2.478734
2.076705
1.19359
try: suffix = self.name_suffixes[name] except KeyError: self.name_suffixes[name] = 0 return name suffix += 1 self.name_suffixes[name] = suffix return "%s%i" % (name, suffix)
def uniqueName(self, name)
UIParser.uniqueName(string) -> string Create a unique name from a string. >>> p = UIParser(QtCore, QtGui, QtWidgets) >>> p.uniqueName("foo") 'foo' >>> p.uniqueName("foo") 'foo1'
2.510848
3.302101
0.760379
for a in args: if a is not None and not isinstance(a, str): return True return False
def any_i18n(*args)
Return True if any argument appears to be an i18n string.
5.19179
4.085352
1.27083
item = self.factory.createQObject(item_type, "item", (), False) props = self.wprops # Note that not all types of widget items support the full set of # properties. text = props.getProperty(elem, 'text') status_tip = props.getProperty(elem, 'statusTip') ...
def createWidgetItem(self, item_type, elem, getter, *getter_args)
Create a specific type of widget item.
2.09281
2.050578
1.020595
try: iterator = getattr(elem, 'iter') except AttributeError: iterator = getattr(elem, 'getiterator') for include in iterator("include"): loc = include.attrib.get("location") # Apply the convention for naming the Python files generated by...
def readResources(self, elem)
Read a "resources" tag and add the module to import to the parser's list of them.
5.912518
5.424584
1.089949
import os # Compile a single .ui file. def compile_ui(ui_dir, ui_file): # Ignore if it doesn't seem to be a .ui file. if ui_file.endswith('.ui'): py_dir = ui_dir py_file = ui_file[:-3] + '.py' # Allow the caller to change the name of the .py file o...
def compileUiDir(dir, recurse=False, map=None, **compileUi_args)
compileUiDir(dir, recurse=False, map=None, **compileUi_args) Creates Python modules from Qt Designer .ui files in a directory or directory tree. dir is the name of the directory to scan for files whose name ends with '.ui'. By default the generated Python module is created in the same directory e...
2.02144
1.945166
1.039212
from PyQt5.QtCore import PYQT_VERSION_STR try: uifname = uifile.name except AttributeError: uifname = uifile indenter.indentwidth = indent pyfile.write(_header % (uifname, PYQT_VERSION_STR)) winfo = compiler.UICompiler().compileUi(uifile, pyfile, from_imports, resource_...
def compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.')
compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file name or file-like object containing the .ui file. pyfile is the file-like object to which the Python code will be written...
4.572394
4.503559
1.015285
import sys from PyQt5 import QtWidgets if sys.hexversion >= 0x03000000: from .port_v3.string_io import StringIO else: from .port_v2.string_io import StringIO code_string = StringIO() winfo = compiler.UICompiler().compileUi(uifile, code_string, from_imports, resource_suff...
def loadUiType(uifile, from_imports=False, resource_suffix='_rc', import_from='.')
loadUiType(uifile, from_imports=False, resource_suffix='_rc', import_from='.') -> (form class, base class) Load a Qt Designer .ui file and return the generated form class and the Qt base class. uifile is a file name or file-like object containing the .ui file. from_imports is optionally set to generat...
4.507427
4.025684
1.119667
from .Loader.loader import DynamicUILoader return DynamicUILoader(package).loadUi(uifile, baseinstance, resource_suffix)
def loadUi(uifile, baseinstance=None, package='', resource_suffix='_rc')
loadUi(uifile, baseinstance=None, package='') -> widget Load a Qt Designer .ui file and return an instance of the user interface. uifile is a file name or file-like object containing the .ui file. baseinstance is an optional instance of the Qt base class. If specified then the user interface is creat...
6.221137
7.475561
0.832197
# Handle a themed icon. theme = iconset.attrib.get('theme') if theme is not None: return self._object_factory.createQObject("QIcon.fromTheme", 'icon', (self._object_factory.asString(theme), ), is_attribute=False) # Handle an ...
def get_icon(self, iconset)
Return an icon described by the given iconset tag.
4.289914
4.121219
1.040933
fname = fname.replace("\\", "\\\\") if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname): fname = os.path.join(base_dir, fname) return fname
def _file_name(fname, base_dir)
Convert a relative filename if we have a base directory.
3.054353
2.630696
1.161044
if self._use_fallback: icon.addFile(self._fallback) else: for role, pixmap in self._roles.items(): if role.endswith("off"): mode = role[:-3] state = qtgui_module.QIcon.Off elif role.endswith("on"): ...
def set_icon(self, icon, qtgui_module)
Save the icon and set its attributes.
2.715182
2.660449
1.020573
template = import PyQt5 exedir = os.path.dirname(sys.executable) qtpath = os.path.join(exedir, "qt.conf") pyqt5path = os.path.abspath(PyQt5.__file__) binpath = os.path.dirname(pyqt5path).replace("\\", "/") try: with open(qtpath, "w") as f: f.write(template.forma...
def createqtconf()
Create a qt.conf file next to the current executable
3.345931
3.145069
1.063866
package_data = dict() package_data['PyQt5'] = list() for subdir in ("doc/", "examples/", "include/", "mkspecs/", "plugins/", "qml/", "qsci/", "sip/", "translations/", "uic/"): abspath = os.path.abspath("PyQt5/" + subdir) for root, dirs, files in os...
def get_package_data()
Include all files from all sub-directories
3.392227
3.364073
1.008369
from PyQt5 import QtWidgets app = QtWidgets.QApplication([self._ui_file]) widget = loadUi(self._ui_file) widget.show() return app.exec_()
def _preview(self)
Preview the .ui file. Return the exit status to be passed back to the parent process.
5.472799
3.758075
1.456277
needs_close = False if sys.hexversion >= 0x03000000: if self._opts.output == '-': from io import TextIOWrapper pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8') else: pyfile = open(self._opts.output, 'wt', encod...
def _generate(self)
Generate the Python code.
2.626161
2.521477
1.041517
sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename))
def on_IOError(self, e)
Handle an IOError exception.
4.414742
4.291137
1.028805
if logging.getLogger(self.LOGGER_NAME).level == logging.DEBUG: import traceback traceback.print_exception(*sys.exc_info()) else: from PyQt5 import QtCore sys.stderr.write( % QtCore.PYQT_VERSION_STR)
def on_Exception(self, e)
Handle a generic exception.
5.807506
5.537076
1.04884
plugin = open(filename, 'rU') try: exec(plugin.read(), plugin_globals, plugin_locals) except ImportError: return False except Exception as e: raise WidgetPluginError("%s: %s" % (e.__class__, str(e))) finally: plugin.close...
def load_plugin(filename, plugin_globals, plugin_locals)
Load the plugin from the given file. Return True if the plugin was loaded, or False if it wanted to be ignored. Raise an exception if there was an error.
3.258442
3.118954
1.044723
'''Parse an RFC822, RFC1123, RFC2822, or asctime-style date''' data = dateString.split() if data[0][-1] in (',', '.') or data[0].lower() in _daynames: del data[0] if len(data) == 4: s = data[3] s = s.split('+', 1) if len(s) == 2: data[3:] = s else: ...
def _parse_date_rfc822(dateString)
Parse an RFC822, RFC1123, RFC2822, or asctime-style date
2.865268
2.615721
1.095403
# build am and pm lists to contain # original case, lowercase, first-char and dotted # versions of the meridian text ptc.am = ['', ''] ptc.pm = ['', ''] for idx, xm in enumerate(ptc.locale.meridian[:2]): # 0: am # 1: pm target = ['am', 'pm'][idx] setattr(ptc,...
def _initSymbols(ptc)
Initialize symbols and single character constants.
6.356412
6.428304
0.988816
word_list, a, b = re.split(r"[,\s-]+", unitText), 0, 0 for word in word_list: x = self.ptc.small.get(word) if x is not None: a += x elif word == "hundred": a *= 100 else: x = self.ptc.magnitude.get(w...
def _convertUnitAsWords(self, unitText)
Converts text units into their number value. @type unitText: string @param unitText: number text to convert @rtype: integer @return: numerical value of unitText
3.518877
4.164695
0.84493
ctx = self.currentContext debug and log.debug('_buildTime: [%s][%s][%s]', quantity, modifier, units) if source is None: source = time.localtime() if quantity is None: quantity = '' else: quantity = quantit...
def _buildTime(self, source, quantity, modifier, units)
Take C{quantity}, C{modifier} and C{unit} strings and convert them into values. After converting, calcuate the time and return the adjusted sourceTime. @type source: time @param source: time to use as the base (or source) @type quantity: string @param quantity: qua...
4.30586
4.270281
1.008332
if sourceTime is None: yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime() else: yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime # values pulled from regex's will be stored here and later # assigned to mth, dy, yr based on information from th...
def parseDate(self, dateString, sourceTime=None)
Parse short-form date strings:: '05/28/2006' or '04.21' @type dateString: string @param dateString: text to convert to a C{datetime} @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: struct_time @ret...
3.307811
3.384393
0.977372
if sourceTime is None: yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime() else: yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime currentMth = mth currentDy = dy accuracy = [] debug and log.debug('parseDateText currentMth %s c...
def parseDateText(self, dateString, sourceTime=None)
Parse long-form date strings:: 'May 31st, 2006' 'Jan 1st' 'July 2006' @type dateString: string @param dateString: text to convert to a datetime @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base ...
3.225503
3.247357
0.99327
diffBase = wkdy - wd origOffset = offset if offset == 2: # no modifier is present. # i.e. string to be parsed is just DOW if wkdy * style > wd * style or \ currentDayStyle and wkdy == wd: # wkdy located in current ...
def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle)
Based on the C{style} and C{currentDayStyle} determine what day-of-week value is to be returned. @type wd: integer @param wd: day-of-week value for the current day @type wkdy: integer @param wkdy: day-of-week value for the parsed...
4.718913
4.829866
0.977028
if not quantity: return 1.0 try: return float(quantity.replace(',', '.')) except ValueError: pass try: return float(self.ptc.numbers[quantity]) except KeyError: pass return 0.0
def _quantityToReal(self, quantity)
Convert a quantity, either spelled-out or numeric, to a float @type quantity: string @param quantity: quantity to parse to float @rtype: int @return: the quantity as an float, defaulting to 0.0
3.934641
4.536309
0.867366
ctx = self.currentContext s = datetimeString.strip() # Given string date is a RFC822 date if sourceTime is None: sourceTime = _parse_date_rfc822(s) debug and log.debug( 'attempt to parse as rfc822 - %s', str(sourceTime)) if s...
def _evalDT(self, datetimeString, sourceTime)
Calculate the datetime from known format like RFC822 or W3CDTF Examples handled:: RFC822, W3CDTF formatted dates HH:MM[:SS][ am/pm] MM/DD/YYYY DD MMMM YYYY @type datetimeString: string @param datetimeString: text to try and parse as more "tradit...
2.829082
2.728643
1.036809
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a time string with units like "5 hrs 30 min" modifier = '' # TODO m = self.ptc.CRE_UNITS.search(s) if m is not None: units = m.group('units') ...
def _evalUnits(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseUnits()}
6.793437
6.512847
1.043082
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a time string with single char units like "5 h 30 m" modifier = '' # TODO m = self.ptc.CRE_QUNITS.search(s) if m is not None: units = m.group('qunits...
def _evalQUnits(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseQUnits()}
7.973969
7.471058
1.067315
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format "May 23rd, 2005" debug and log.debug('checking for MMM DD YYYY') return self.parseDateText(s, sourceTime)
def _evalDateStr(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseDateStr()}
10.733618
10.146678
1.057846
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format 07/21/2006 return self.parseDate(s, sourceTime)
def _evalDateStd(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseDateStd()}
7.935272
7.285056
1.089253
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a natural language date string like today, tomorrow.. (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = sourceTime try: offset = self.ptc.dayOffsets[s] exce...
def _evalDayStr(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseDaystr()}
5.052091
5.051237
1.000169
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a weekday yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime start = datetime.datetime(yr, mth, dy, hr, mn, sec) wkdy = self.ptc.WeekdayOffsets[s] if w...
def _evalWeekday(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseWeekday()}
4.973117
4.964939
1.001647
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) if s in self.ptc.re_values['now']: self.currentContext.updateAccuracy(pdtContext.ACU_NOW) else: # Given string is a natural language time string like # lunch, mi...
def _evalTimeStr(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseTimeStr()}
8.889673
8.830701
1.006678
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format HH:MM(:SS)(am/pm) yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime m = self.ptc.CRE_TIMEHMS2.search(s) if m is not None: dt = s[:m.s...
def _evalMeridian(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseMeridian()}
3.857597
3.822075
1.009294
s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format HH:MM(:SS) yr, mth, dy, hr, mn, sec, wd, yd, isdst = sourceTime m = self.ptc.CRE_TIMEHMS.search(s) if m is not None: hr, mn, sec = _extr...
def _evalTimeStd(self, datetimeString, sourceTime)
Evaluate text passed by L{_partialParseTimeStd()}
5.038966
4.943992
1.01921
parseStr = None chunk1 = chunk2 = '' # Modifier like next/prev/from/after/prior.. m = self.ptc.CRE_MODIFIER.search(s) if m is not None: if m.group() != s: # capture remaining string parseStr = m.group() chunk1 ...
def _partialParseModifier(self, s, sourceTime)
test if giving C{s} matched CRE_MODIFIER, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: tuple @return: tuple of remained date/...
5.090938
5.303475
0.959925
parseStr = None chunk1 = chunk2 = '' # Quantity + Units m = self.ptc.CRE_UNITS.search(s) if m is not None: debug and log.debug('CRE_UNITS matched') if self._UnitsTrapped(s, m, 'units'): debug and log.debug('day suffix trapped by u...
def _partialParseUnits(self, s, sourceTime)
test if giving C{s} matched CRE_UNITS, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: tuple @return: tuple of remained date/tim...
4.601281
4.605581
0.999066
parseStr = None chunk1 = chunk2 = '' # Quantity + Units m = self.ptc.CRE_QUNITS.search(s) if m is not None: debug and log.debug('CRE_QUNITS matched') if self._UnitsTrapped(s, m, 'qunits'): debug and log.debug( ...
def _partialParseQUnits(self, s, sourceTime)
test if giving C{s} matched CRE_QUNITS, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: tuple @return: tuple of remained date/ti...
4.6389
4.607861
1.006736