Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def parseWord(word):
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
value = int(value)
except ValueError:
value = mapping.get(value, value)
return (key, value) | [
"\n Split given attribute word to key, value pair.\n\n Values are casted to python equivalents.\n\n :param word: API word.\n :returns: Key, value pair.\n "
] |
Please provide a description of the function:def composeWord(key, value):
mapping = {True: 'yes', False: 'no'}
# this is necesary because 1 == True, 0 == False
if type(value) == int:
value = str(value)
else:
value = mapping.get(value, str(value))
return '={}={}'.format(key, valu... | [
"\n Create a attribute word from key, value pair.\n Values are casted to api equivalents.\n "
] |
Please provide a description of the function:def login_token(api, username, password):
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded})) | [
"Login using pre routeros 6.43 authorization method."
] |
Please provide a description of the function:def check_relations(self, relations):
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
raise Valu... | [
"Recursive function which checks if a relation is valid."
] |
Please provide a description of the function:def format_json_api_response(self, data, many):
ret = self.format_items(data, many)
ret = self.wrap_response(ret, many)
ret = self.render_included_data(ret)
ret = self.render_meta_document(ret)
return ret | [
"Post-dump hook that formats serialized data as a top-level JSON API object.\n\n See: http://jsonapi.org/format/#document-top-level\n "
] |
Please provide a description of the function:def on_bind_field(self, field_name, field_obj):
if _MARSHMALLOW_VERSION_INFO[0] < 3:
if not field_obj.load_from:
field_obj.load_from = self.inflect(field_name)
else:
if not field_obj.data_key:
f... | [
"Schema hook override. When binding fields, set ``data_key`` (on marshmallow 3) or\n load_from (on marshmallow 2) to the inflected form of field_name.\n "
] |
Please provide a description of the function:def _do_load(self, data, many=None, **kwargs):
many = self.many if many is None else bool(many)
# Store this on the instance so we have access to the included data
# when processing relationships (``included`` is outside of the
# ``d... | [
"Override `marshmallow.Schema._do_load` for custom JSON API handling.\n\n Specifically, we do this to format errors as JSON API Error objects,\n and to support loading of included data.\n "
] |
Please provide a description of the function:def _extract_from_included(self, data):
return (item for item in self.included_data
if item['type'] == data['type'] and
str(item['id']) == str(data['id'])) | [
"Extract included data matching the items in ``data``.\n\n For each item in ``data``, extract the full data from the included\n data.\n "
] |
Please provide a description of the function:def inflect(self, text):
return self.opts.inflect(text) if self.opts.inflect else text | [
"Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise\n do nothing.\n "
] |
Please provide a description of the function:def format_errors(self, errors, many):
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems(errors)... | [
"Format validation errors as JSON Error objects."
] |
Please provide a description of the function:def format_error(self, field_name, message, index=None):
pointer = ['/data']
if index is not None:
pointer.append(str(index))
relationship = isinstance(
self.declared_fields.get(field_name), BaseRelationship,
... | [
"Override-able hook to format a single error message as an Error object.\n\n See: http://jsonapi.org/format/#error-objects\n "
] |
Please provide a description of the function:def format_item(self, item):
# http://jsonapi.org/format/#document-top-level
# Primary data MUST be either... a single resource object, a single resource
# identifier object, or null, for requests that target single resources
if not i... | [
"Format a single datum as a Resource object.\n\n See: http://jsonapi.org/format/#document-resource-objects\n "
] |
Please provide a description of the function:def format_items(self, data, many):
if many:
return [self.format_item(item) for item in data]
else:
return self.format_item(data) | [
"Format data as a Resource object or list of Resource objects.\n\n See: http://jsonapi.org/format/#document-resource-objects\n "
] |
Please provide a description of the function:def get_top_level_links(self, data, many):
self_link = None
if many:
if self.opts.self_url_many:
self_link = self.generate_url(self.opts.self_url_many)
else:
if self.opts.self_url:
self... | [
"Hook for adding links to the root of the response data."
] |
Please provide a description of the function:def get_resource_links(self, item):
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
re... | [
"Hook for adding links to a resource object."
] |
Please provide a description of the function:def wrap_response(self, data, many):
ret = {'data': data}
# self_url_many is still valid when there isn't any data, but self_url
# may only be included if there is data in the ret
if many or data:
top_level_links = self.ge... | [
"Wrap data and links according to the JSON API "
] |
Please provide a description of the function:def extract_value(self, data):
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self.type_:
... | [
"Extract the id key and validate the request structure."
] |
Please provide a description of the function:def deserialize(self, value, attr=None, data=None):
if value is missing_:
return super(Relationship, self).deserialize(value, attr, data)
if not isinstance(value, dict) or 'data' not in value:
# a relationships object does not... | [
"Deserialize ``value``.\n\n :raise ValidationError: If the value is not type `dict`, if the\n value does not contain a `data` key, and if the value is\n required but unspecified.\n "
] |
Please provide a description of the function:def J(*args, **kwargs):
response = jsonify(*args, **kwargs)
response.mimetype = 'application/vnd.api+json'
return response | [
"Wrapper around jsonify that sets the Content-Type of the response to\n application/vnd.api+json.\n "
] |
Please provide a description of the function:def resolve_params(obj, params, default=missing):
param_values = {}
for name, attr_tpl in iteritems(params):
attr_name = tpl(str(attr_tpl))
if attr_name:
attribute_value = get_value(obj, attr_name, default=default)
if attr... | [
"Given a dictionary of keyword arguments, return the same dictionary except with\n values enclosed in `< >` resolved to attributes on `obj`.\n "
] |
Please provide a description of the function:def fill_package_digests(generated_project: Project) -> Project:
for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages):
if package_version.hashes:
# Already filled from the last run.
... | [
"Temporary fill package digests stated in Pipfile.lock."
] |
Please provide a description of the function:def fetch_digests(self, package_name: str, package_version: str) -> dict:
report = {}
for source in self._sources:
try:
report[source.url] = source.get_package_hashes(package_name, package_version)
except NotF... | [
"Fetch digests for the given package in specified version from the given package index."
] |
Please provide a description of the function:def random_passphrase_from_wordlist(phrase_length, wordlist):
passphrase_words = []
numbytes_of_entropy = phrase_length * 2
entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True))
bytes_per_word = int(ceil(log(len(wordlis... | [
" An extremely entropy efficient passphrase generator.\n\n This function:\n -Pulls entropy from the safer alternative to /dev/urandom: /dev/random\n -Doesn't rely on random.seed (words are selected right from the entropy)\n -Only requires 2 entropy bytes/word for word lists of up to 6553... |
Please provide a description of the function:def bin_hash160(s, hex_format=False):
if hex_format and is_hex(s):
s = unhexlify(s)
return hashlib.new('ripemd160', bin_sha256(s)).digest() | [
" s is in hex or binary format\n "
] |
Please provide a description of the function:def hex_hash160(s, hex_format=False):
if hex_format and is_hex(s):
s = unhexlify(s)
return hexlify(bin_hash160(s)) | [
" s is in hex or binary format\n "
] |
Please provide a description of the function:def reverse_hash(hash, hex_format=True):
if not hex_format:
hash = hexlify(hash)
return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)])) | [
" hash is in hex or binary format\n "
] |
Please provide a description of the function:def get_wordlist(language, word_source):
try:
wordlist_string = eval(language + '_words_' + word_source)
except NameError:
raise Exception("No wordlist could be found for the word source and language provided.")
wordlist = wordlist_string.spl... | [
" Takes in a language and a word source and returns a matching wordlist,\n if it exists.\n Valid languages: ['english']\n Valid word sources: ['bip39', 'wiktionary', 'google']\n "
] |
Please provide a description of the function:def get_num_words_with_entropy(bits_of_entropy, wordlist):
entropy_per_word = math.log(len(wordlist))/math.log(2)
num_words = int(math.ceil(bits_of_entropy/entropy_per_word))
return num_words | [
" Gets the number of words randomly selected from a given wordlist that\n would result in the number of bits of entropy specified.\n "
] |
Please provide a description of the function:def create_passphrase(bits_of_entropy=None, num_words=None,
language='english', word_source='wiktionary'):
wordlist = get_wordlist(language, word_source)
if not num_words:
if not bits_of_entropy:
bits_of_entropy = 80
... | [
" Creates a passphrase that has a certain number of bits of entropy OR\n a certain number of words.\n "
] |
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockchainInfoClient()):
if not isinstance(blockchain_client, BlockchainInfoClient):
raise Exception('A BlockchainInfoClient object is required')
url = BLOCKCHAIN_API_BASE_URL + "/unspent?format=json&active=" ... | [
" Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n "
] |
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client=BlockchainInfoClient()):
url = BLOCKCHAIN_API_BASE_URL + '/pushtx'
payload = {'tx': hex_tx}
r = requests.post(url, data=payload, auth=blockchain_client.auth)
if 'submitted' in r.text.lower():
... | [
" Dispatch a raw transaction to the network.\n "
] |
Please provide a description of the function:def serialize_input(input, signature_script_hex=''):
if not (isinstance(input, dict) and 'transaction_hash' in input \
and 'output_index' in input):
raise Exception('Required parameters: transaction_hash, output_index')
if is_hex(str(input['... | [
" Serializes a transaction input.\n "
] |
Please provide a description of the function:def serialize_output(output):
if not ('value' in output and 'script_hex' in output):
raise Exception('Invalid output')
return ''.join([
hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
hexlify(variable_length_int(len(outp... | [
" Serializes a transaction output.\n "
] |
Please provide a description of the function:def serialize_transaction(inputs, outputs, lock_time=0, version=1):
# add in the inputs
serialized_inputs = ''.join([serialize_input(input) for input in inputs])
# add in the outputs
serialized_outputs = ''.join([serialize_output(output) for output in ... | [
" Serializes a transaction.\n "
] |
Please provide a description of the function:def deserialize_transaction(tx_hex):
tx = bitcoin.deserialize(str(tx_hex))
inputs = tx["ins"]
outputs = tx["outs"]
ret_inputs = []
ret_outputs = []
for inp in inputs:
ret_inp = {
"transaction_hash": inp["outpoint"]["hash"]... | [
"\n Given a serialized transaction, return its inputs, outputs,\n locktime, and version\n\n Each input will have:\n * transaction_hash: string\n * output_index: int\n * [optional] sequence: int\n * [optional] script_sig: string\n\n Each output will have:\n ... |
Please provide a description of the function:def pending_transactions(server):
namecoind = NamecoindClient(server, NAMECOIND_PORT,
NAMECOIND_USER, NAMECOIND_PASSWD)
reply = namecoind.listtransactions("", 10000)
counter = 0
for i in reply:
if i['confirmat... | [
" get the no. of pending transactions (0 confirmations) on a server\n "
] |
Please provide a description of the function:def get_server(key, server=MAIN_SERVER, servers=LOAD_SERVERS):
namecoind = NamecoindClient(NAMECOIND_SERVER, NAMECOIND_PORT,
NAMECOIND_USER, NAMECOIND_PASSWD)
info = namecoind.name_show(key)
if 'address' in info:
r... | [
" given a key, get the IP address of the server that has the pvt key that\n owns the name/key\n "
] |
Please provide a description of the function:def keypair(self, i, keypair_class):
# Make sure keypair_class is a valid cryptocurrency keypair
if not is_cryptocurrency_keypair_class(keypair_class):
raise Exception(_messages["INVALID_KEYPAIR_CLASS"])
currency_name = keypair_... | [
" Return the keypair that corresponds to the provided sequence number\n and keypair class (BitcoinKeypair, etc.).\n "
] |
Please provide a description of the function:def get_unspents(self, address):
addresses = []
addresses.append(str(address))
min_confirmations = 0
max_confirmation = 2000000000 # just a very large number for max
unspents = self.obj.listunspent(min_confirmations, max_co... | [
" Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n\n NOTE: this will only return unspents if the address provided is\n present in the bitcoind server. Use the chain, blockchain,\n or blockcypher API to grab the unspents for ar... |
Please provide a description of the function:def broadcast_transaction(self, hex_tx):
resp = self.obj.sendrawtransaction(hex_tx)
if len(resp) > 0:
return {'transaction_hash': resp, 'success': True}
else:
return error_reply('Invalid response from bitcoind.') | [
" Dispatch a raw transaction to the network.\n "
] |
Please provide a description of the function:def from_passphrase(cls, passphrase=None):
if not passphrase:
# run a rejection sampling algorithm to ensure the private key is
# less than the curve order
while True:
passphrase = create_passphrase(bits_of... | [
" Create keypair from a passphrase input (a brain wallet keypair)."
] |
Please provide a description of the function:def name_transfer(self, key, new_address, value=None):
key_details = self.name_show(key)
if 'code' in key_details and key_details.get('code') == -4:
return error_reply("Key does not exist")
# get new 'value' if given, otherwise... | [
" Check if this name exists and if it does, find the value field\n note that update command needs an arg of <new value>.\n in case we're simply transferring, need to obtain old value first\n "
] |
Please provide a description of the function:def variable_length_int(i):
if not isinstance(i, (int,long)):
raise Exception('i must be an integer')
if i < (2**8-3):
return chr(i) # pack the integer into one byte
elif i < (2**16):
return chr(253) + struct.pack('<H', i) # pack int... | [
" Encodes integers into variable length integers, which are used in\n Bitcoin in order to save space.\n "
] |
Please provide a description of the function:def script_to_hex(script):
hex_script = ''
parts = script.split(' ')
for part in parts:
if part[0:3] == 'OP_':
try:
hex_script += '%0.2x' % eval(part)
except:
raise Exception('Invalid opcode: %s... | [
" Parse the string representation of a script and return the hex version.\n Example: \"OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG\"\n "
] |
Please provide a description of the function:def make_pay_to_address_script(address):
hash160 = hexlify(b58check_decode(address))
script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160
return script_to_hex(script_string) | [
" Takes in an address and returns the script \n "
] |
Please provide a description of the function:def make_op_return_script(data, format='bin'):
if format == 'hex':
assert(is_hex(data))
hex_data = data
elif format == 'bin':
hex_data = hexlify(data)
else:
raise Exception("Format must be either 'hex' or 'bin'")
num_byte... | [
" Takes in raw ascii data to be embedded and returns a script.\n "
] |
Please provide a description of the function:def create_bitcoind_service_proxy(
rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False):
protocol = 'https' if use_https else 'http'
uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password,
server, port)
return Aut... | [
" create a bitcoind service proxy\n "
] |
Please provide a description of the function:def get_unspents(address, blockchain_client):
if isinstance(blockchain_client, BitcoindClient):
bitcoind = blockchain_client.bitcoind
version_byte = blockchain_client.version_byte
elif isinstance(blockchain_client, AuthServiceProxy):
bitc... | [
" Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n\n NOTE: this will only return unspents if the address provided is present\n in the bitcoind server. Use the chain, blockchain, or blockcypher API\n to grab the unspents for arbitrary addresse... |
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client):
if isinstance(blockchain_client, BitcoindClient):
bitcoind = blockchain_client.bitcoind
elif isinstance(blockchain_client, AuthServiceProxy):
bitcoind = blockchain_client
else:
rai... | [
" Dispatch a raw transaction to the network.\n "
] |
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockchainInfoClient()):
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return... | [
" Gets the unspent outputs for a given address.\n "
] |
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client):
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return blockc... | [
" Dispatches a raw hex transaction to the network.\n "
] |
Please provide a description of the function:def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inp... | [
" Builds and signs a \"send to address\" transaction.\n "
] |
Please provide a description of the function:def make_op_return_tx(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyz... | [
" Builds and signs an OP_RETURN transaction.\n "
] |
Please provide a description of the function:def send_to_address(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
# build and sign the tx
signed_tx = make_send_to_address_tx(recipient_address, amount,
private_k... | [
" Builds, signs, and dispatches a \"send to address\" transaction.\n "
] |
Please provide a description of the function:def embed_data_in_blockchain(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
# build and sign the tx
signed_tx = make_op_return_tx(data, private_key, blockchain_client,
f... | [
" Builds, signs, and dispatches an OP_RETURN transaction.\n "
] |
Please provide a description of the function:def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex):
inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex)
tx_hex = unsigned_tx_hex
for index in xrange(0, len(inputs)):
if len(inputs[index]['script_sig']) == 0:
... | [
"\n Sign a serialized transaction's unsigned inputs\n\n @hex_privkey: private key that should sign inputs\n @unsigned_tx_hex: hex transaction with unsigned inputs\n\n Returns: signed hex transaction\n "
] |
Please provide a description of the function:def random_secret_exponent(curve_order):
# run a rejection sampling algorithm to ensure the random int is less
# than the curve order
while True:
# generate a random 256 bit hex string
random_hex = hexlify(dev_random_entropy(32))
rand... | [
" Generates a random secret exponent. "
] |
Please provide a description of the function:def get_unspents(address, blockchain_client=ChainComClient()):
if not isinstance(blockchain_client, ChainComClient):
raise Exception('A ChainComClient object is required')
url = CHAIN_API_BASE_URL + '/bitcoin/addresses/' + address + '/unspents'
aut... | [
" Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n "
] |
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client):
if not isinstance(blockchain_client, ChainComClient):
raise Exception('A ChainComClient object is required')
auth = blockchain_client.auth
if not auth or len(auth) != 2:
raise Exception('... | [
" Dispatch a raw hex transaction to the network.\n "
] |
Please provide a description of the function:def get_unspents(address, blockchain_client=BlockcypherClient()):
if not isinstance(blockchain_client, BlockcypherClient):
raise Exception('A BlockcypherClient object is required')
url = '%s/addrs/%s?unspentOnly=true&includeScript=true' % (
BL... | [
" Get the spendable transaction outputs, also known as UTXOs or\n unspent transaction outputs.\n "
] |
Please provide a description of the function:def broadcast_transaction(hex_tx, blockchain_client):
if not isinstance(blockchain_client, BlockcypherClient):
raise Exception('A BlockcypherClient object is required')
url = '%s/txs/push' % (BLOCKCYPHER_BASE_URL)
payload = json.dumps({'tx': hex_tx}... | [
" Dispatch a raw hex transaction to the network.\n "
] |
Please provide a description of the function:def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
# keep moving up the merkle tree, constructing one row at a time
while len(hashe... | [
" takes in a list of binary hashes, returns a binary hash\n "
] |
Please provide a description of the function:def b58check_encode(bin_s, version_byte=0):
# append the version byte to the beginning
bin_s = chr(int(version_byte)) + bin_s
# calculate the number of leading zeros
num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0))
# add in the checksum a... | [
" Takes in a binary string and converts it to a base 58 check string. "
] |
Please provide a description of the function:def b58check_unpack(b58_s):
num_leading_zeros = len(re.match(r'^1*', b58_s).group(0))
# convert from b58 to b16
hex_s = change_charset(b58_s, B58_KEYSPACE, HEX_KEYSPACE)
# if an odd number of hex characters are present, add a zero to the front
if len... | [
" Takes in a base 58 check string and returns: the version byte, the\n original encoded binary string, and the checksum.\n "
] |
Please provide a description of the function:def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
fee=STANDARD_FEE):
return [
# main output
{ "script_hex": make_pay_to_address_script(to_address), "value": send_amount },
# chang... | [
" Builds the outputs for a \"pay to address\" transaction.\n "
] |
Please provide a description of the function:def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amount },
# ... | [
" Builds the outputs for an OP_RETURN transaction.\n "
] |
Please provide a description of the function:def add_timezone(value, tz=None):
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
except AttributeError: # 'datetime.date' object has no attribute 'tzinfo'
dt = d... | [
"If the value is naive, then the timezone is added to it.\n\n If no timezone is given, timezone.get_current_timezone() is used.\n "
] |
Please provide a description of the function:def get_active_entry(user, select_for_update=False):
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not entries.exist... | [
"Returns the user's currently-active entry, or None."
] |
Please provide a description of the function:def get_month_start(day=None):
day = add_timezone(day or datetime.date.today())
return day.replace(day=1) | [
"Returns the first day of the given month."
] |
Please provide a description of the function:def get_setting(name, **kwargs):
if hasattr(settings, name): # Try user-defined settings first.
return getattr(settings, name)
if 'default' in kwargs: # Fall back to a specified default value.
return kwargs['default']
if hasattr(defaults, n... | [
"Returns the user-defined value for the setting, or a default value."
] |
Please provide a description of the function:def get_week_start(day=None):
day = add_timezone(day or datetime.date.today())
days_since_monday = day.weekday()
if days_since_monday != 0:
day = day - relativedelta(days=days_since_monday)
return day | [
"Returns the Monday of the given week."
] |
Please provide a description of the function:def get_year_start(day=None):
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1) | [
"Returns January 1 of the given year."
] |
Please provide a description of the function:def to_datetime(date):
return datetime.datetime(date.year, date.month, date.day) | [
"Transforms a date or datetime object into a date object."
] |
Please provide a description of the function:def report_estimation_accuracy(request):
contracts = ProjectContract.objects.filter(
status=ProjectContract.STATUS_COMPLETE,
type=ProjectContract.PROJECT_FIXED
)
data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')]
for c in contracts:... | [
"\n Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.\n "
] |
Please provide a description of the function:def get_context_data(self, **kwargs):
context = super(ReportMixin, self).get_context_data(**kwargs)
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
start, end = form.save()
entryQ = sel... | [
"Processes form data to get relevant entries & date_headers."
] |
Please provide a description of the function:def get_entry_query(self, start, end, data):
# Entry types.
incl_billable = data.get('billable', True)
incl_nonbillable = data.get('non_billable', True)
incl_leave = data.get('paid_leave', True)
# If no types are selected, sh... | [
"Builds Entry query from form data."
] |
Please provide a description of the function:def get_headers(self, date_headers, from_date, to_date, trunc):
date_headers = list(date_headers)
# Earliest date should be no earlier than from_date.
if date_headers and date_headers[0] < from_date:
date_headers[0] = from_date
... | [
"Adjust date headers & get range headers."
] |
Please provide a description of the function:def get_previous_month(self):
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end | [
"Returns date range for the previous full month."
] |
Please provide a description of the function:def convert_context_to_csv(self, context):
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
content.ap... | [
"Convert the context dictionary into a CSV file."
] |
Please provide a description of the function:def defaults(self):
# Set default date span to previous week.
(start, end) = get_week_window(timezone.now() - relativedelta(days=7))
return {
'from_date': start,
'to_date': end,
'billable': True,
... | [
"Default filter form data when no GET data is provided."
] |
Please provide a description of the function:def get_hours_data(self, entries, date_headers):
project_totals = get_project_totals(
entries, date_headers, total_column=False) if entries else []
data_map = {}
for rows, totals in project_totals:
for user, user_id, ... | [
"Sum billable and non-billable hours across all users."
] |
Please provide a description of the function:def add_parameters(url, parameters):
if parameters:
sep = '&' if '?' in url else '?'
return '{0}{1}{2}'.format(url, sep, urlencode(parameters))
return url | [
"\n Appends URL-encoded parameters to the base URL. It appends after '&' if\n '?' is found in the URL; otherwise it appends using '?'. Keep in mind that\n this tag does not take into account the value of existing params; it is\n therefore possible to add another value for a pre-existing parameter.\n\n ... |
Please provide a description of the function:def get_max_hours(context):
progress = context['project_progress']
return max([0] + [max(p['worked'], p['assigned']) for p in progress]) | [
"Return the largest number of hours worked or assigned on any project."
] |
Please provide a description of the function:def get_uninvoiced_hours(entries, billable=None):
statuses = ('invoiced', 'not-invoiced')
if billable is not None:
billable = (billable.lower() == u'billable')
entries = [e for e in entries if e.activity.billable == billable]
hours = sum([e.h... | [
"Given an iterable of entries, return the total hours that have\n not been invoiced. If billable is passed as 'billable' or 'nonbillable',\n limit to the corresponding entries.\n "
] |
Please provide a description of the function:def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
seconds = int(float(total_hours) * 3600)
return humanize_seconds(seconds, frmt, negative_frmt) | [
"Given time in hours, return a string representing the time."
] |
Please provide a description of the function:def humanize_seconds(total_seconds,
frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
negative_frmt=None):
if negative_frmt is None:
negative_frmt = '<span class="negative-time">-{0}</span>'.format(frmt)
seconds = ... | [
"Given time in int(seconds), return a string representing the time.\n\n If negative_frmt is not given, a negative sign is prepended to frmt\n and the result is wrapped in a <span> with the \"negative-time\" class.\n "
] |
Please provide a description of the function:def project_hours_for_contract(contract, project, billable=None):
hours = contract.entries.filter(project=project)
if billable is not None:
if billable in (u'billable', u'nonbillable'):
billable = (billable.lower() == u'billable')
... | [
"Total billable hours worked on project for contract.\n If billable is passed as 'billable' or 'nonbillable', limits to\n the corresponding hours. (Must pass a variable name first, of course.)\n "
] |
Please provide a description of the function:def _timesheet_url(url_name, pk, date=None):
url = reverse(url_name, args=(pk,))
if date:
params = {'month': date.month, 'year': date.year}
return '?'.join((url, urlencode(params)))
return url | [
"Utility to create a time sheet URL with optional date parameters."
] |
Please provide a description of the function:def reject_user_timesheet(request, user_id):
form = YearMonthForm(request.GET or request.POST)
user = User.objects.get(pk=user_id)
if form.is_valid():
from_date, to_date = form.save()
entries = Entry.no_join.filter(
status=Entry.V... | [
"\n This allows admins to reject all entries, instead of just one\n "
] |
Please provide a description of the function:def _is_requirement(line):
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#")) | [
"Returns whether the line is a valid package requirement."
] |
Please provide a description of the function:def render_to_response(self, context):
if self.redirect_if_one_result:
if self.object_list.count() == 1 and self.form.is_bound:
return redirect(self.object_list.get().get_absolute_url())
return super(SearchMixin, self).ren... | [
"\n When the user makes a search and there is only one result, redirect\n to the result's detail page rather than rendering the list.\n "
] |
Please provide a description of the function:def clean_start_time(self):
start = self.cleaned_data.get('start_time')
if not start:
return start
active_entries = self.user.timepiece_entries.filter(
start_time__gte=start, end_time__isnull=True)
for entry in... | [
"\n Make sure that the start time doesn't come before the active entry\n "
] |
Please provide a description of the function:def clean(self):
active = utils.get_active_entry(self.user)
start_time = self.cleaned_data.get('start_time', None)
end_time = self.cleaned_data.get('end_time', None)
if active and active.pk != self.instance.pk:
if (start_... | [
"\n If we're not editing the active entry, ensure that this entry doesn't\n conflict with or come after the active entry.\n "
] |
Please provide a description of the function:def timespan(self, from_date, to_date=None, span=None, current=False):
if span and not to_date:
diff = None
if span == 'month':
diff = relativedelta(months=1)
elif span == 'week':
diff = rel... | [
"\n Takes a beginning date a filters entries. An optional to_date can be\n specified, or a span, which is one of ('month', 'week', 'day').\n N.B. - If given a to_date, it does not include that date, only before.\n "
] |
Please provide a description of the function:def clock_in(request):
user = request.user
# Lock the active entry for the duration of this transaction, to prevent
# creating multiple active entries.
active_entry = utils.get_active_entry(user, select_for_update=True)
initial = dict([(k, v) for k,... | [
"For clocking the user into a project."
] |
Please provide a description of the function:def toggle_pause(request):
entry = utils.get_active_entry(request.user)
if not entry:
raise Http404
# toggle the paused state
entry.toggle_paused()
entry.save()
# create a message that can be displayed to the user
action = 'paused' ... | [
"Allow the user to pause and unpause the active entry."
] |
Please provide a description of the function:def reject_entry(request, entry_id):
return_url = request.GET.get('next', reverse('dashboard'))
try:
entry = Entry.no_join.get(pk=entry_id)
except:
message = 'No such log entry.'
messages.error(request, message)
return redirec... | [
"\n Admins can reject an entry that has been verified or approved but not\n invoiced to set its status to 'unverified' for the user to fix.\n "
] |
Please provide a description of the function:def delete_entry(request, entry_id):
try:
entry = Entry.no_join.get(pk=entry_id, user=request.user)
except Entry.DoesNotExist:
message = 'No such entry found.'
messages.info(request, message)
url = request.GET.get('next', reverse(... | [
"\n Give the user the ability to delete a log entry, with a confirmation\n beforehand. If this method is invoked via a GET request, a form asking\n for a confirmation of intent will be presented to the user. If this method\n is invoked via a POST request, the entry will be deleted.\n "
] |
Please provide a description of the function:def get_hours_per_week(self, user=None):
try:
profile = UserProfile.objects.get(user=user or self.user)
except UserProfile.DoesNotExist:
profile = None
return profile.hours_per_week if profile else Decimal('40.00') | [
"Retrieves the number of hours the user should work per week."
] |
Please provide a description of the function:def process_progress(self, entries, assignments):
# Determine all projects either worked or assigned.
project_q = Q(id__in=assignments.values_list('project__id', flat=True))
project_q |= Q(id__in=entries.values_list('project__id', flat=True))... | [
"\n Returns a list of progress summary data (pk, name, hours worked, and\n hours assigned) for each project either worked or assigned.\n The list is ordered by project name.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.