text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Make a single char from the string uppercase.
<END_TASK>
<USER_TASK:>
Description:
def _make_one_char_uppercase(string: str) -> str:
"""Make a single char from the string uppercase.""" |
if not isinstance(string, str):
raise TypeError('string must be a string')
if Aux.lowercase_count(string) > 0:
while True:
cindex = randbelow(len(string))
if string[cindex].islower():
aux = list(string)
aux[cindex] = aux[cindex].upper()
string = ''.join(aux)
break
return string |
<SYSTEM_TASK:>
Make uppercase some randomly selected characters.
<END_TASK>
<USER_TASK:>
Description:
def make_chars_uppercase(
lst: Union[list, tuple, str, set],
uppercase: int
) -> Union[list, tuple, str, set]:
"""Make uppercase some randomly selected characters.
The characters can be in a (mix of) string, list, tuple or set.
Keyword arguments:
lst -- the object to make all chars uppercase, which can be a (mix of)
list, tuple, string or set.
uppercase -- Number of characters to be set as uppercase.
""" |
if not isinstance(lst, (list, tuple, str, set)):
raise TypeError('lst must be a list, a tuple, a set or a string')
if not isinstance(uppercase, int):
raise TypeError('uppercase must be an integer')
if uppercase < 0:
raise ValueError('uppercase must be bigger than zero')
lowercase = Aux.lowercase_count(lst)
if uppercase == 0 or lowercase == 0:
return lst
elif uppercase >= lowercase:
# Make it all uppercase
return Aux.make_all_uppercase(lst)
arr = list(lst)
# Check if at least an element is supported
# This is required to avoid an infinite loop below
supported = False
for element in arr:
if isinstance(element, (list, tuple, str, set)):
supported = True
break
if supported:
# Pick a word at random, then make a character uppercase
count = 0
while count < uppercase:
windex = randbelow(len(arr))
element = arr[windex]
# Skip unsupported types or empty ones
if element:
aux = element
if isinstance(element, str):
aux = Aux._make_one_char_uppercase(element)
elif isinstance(element, (list, tuple, set)):
aux = Aux.make_chars_uppercase(element, 1)
if aux != element:
arr[windex] = aux
count += 1
if isinstance(lst, set):
return set(arr)
elif isinstance(lst, str):
return ''.join(arr)
elif isinstance(lst, tuple):
return tuple(arr)
return arr |
<SYSTEM_TASK:>
Check if the input filename with path is a file and is not empty.
<END_TASK>
<USER_TASK:>
Description:
def isfile_notempty(inputfile: str) -> bool:
"""Check if the input filename with path is a file and is not empty.""" |
try:
return isfile(inputfile) and getsize(inputfile) > 0
except TypeError:
raise TypeError('inputfile is not a valid type') |
<SYSTEM_TASK:>
Return the system's entropy bit count, or -1 if unknown.
<END_TASK>
<USER_TASK:>
Description:
def system_entropy():
"""Return the system's entropy bit count, or -1 if unknown.""" |
arg = ['cat', '/proc/sys/kernel/random/entropy_avail']
proc = Popen(arg, stdout=PIPE, stderr=DEVNULL)
response = proc.communicate()[0]
return int(response) if response else -1 |
<SYSTEM_TASK:>
Creates a transaction for issuing an asset.
<END_TASK>
<USER_TASK:>
Description:
def issue(self, issuance_spec, metadata, fees):
"""
Creates a transaction for issuing an asset.
:param TransferParameters issuance_spec: The parameters of the issuance.
:param bytes metadata: The metadata to be embedded in the transaction.
:param int fees: The fees to include in the transaction.
:return: An unsigned transaction for issuing an asset.
:rtype: CTransaction
""" |
inputs, total_amount = self._collect_uncolored_outputs(
issuance_spec.unspent_outputs, 2 * self._dust_amount + fees)
return bitcoin.core.CTransaction(
vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=[
self._get_colored_output(issuance_spec.to_script),
self._get_marker_output([issuance_spec.amount], metadata),
self._get_uncolored_output(issuance_spec.change_script, total_amount - self._dust_amount - fees)
]
) |
<SYSTEM_TASK:>
Creates a transaction for sending assets and bitcoins.
<END_TASK>
<USER_TASK:>
Description:
def transfer(self, asset_transfer_specs, btc_transfer_spec, fees):
"""
Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The second element is the parameters of the transfer.
:param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred.
:param int fees: The fees to include in the transaction.
:return: An unsigned transaction for sending assets and bitcoins.
:rtype: CTransaction
""" |
inputs = []
outputs = []
asset_quantities = []
for asset_id, transfer_spec in asset_transfer_specs:
colored_outputs, collected_amount = self._collect_colored_outputs(
transfer_spec.unspent_outputs, asset_id, transfer_spec.amount)
inputs.extend(colored_outputs)
outputs.append(self._get_colored_output(transfer_spec.to_script))
asset_quantities.append(transfer_spec.amount)
if collected_amount > transfer_spec.amount:
outputs.append(self._get_colored_output(transfer_spec.change_script))
asset_quantities.append(collected_amount - transfer_spec.amount)
btc_excess = sum([input.output.value for input in inputs]) - sum([output.nValue for output in outputs])
if btc_excess < btc_transfer_spec.amount + fees:
# Not enough bitcoin inputs
uncolored_outputs, total_amount = self._collect_uncolored_outputs(
btc_transfer_spec.unspent_outputs, btc_transfer_spec.amount + fees - btc_excess)
inputs.extend(uncolored_outputs)
btc_excess += total_amount
change = btc_excess - btc_transfer_spec.amount - fees
if change > 0:
# Too much bitcoin in input, send it back as change
outputs.append(self._get_uncolored_output(btc_transfer_spec.change_script, change))
if btc_transfer_spec.amount > 0:
outputs.append(self._get_uncolored_output(btc_transfer_spec.to_script, btc_transfer_spec.amount))
if asset_quantities:
outputs.insert(0, self._get_marker_output(asset_quantities, b''))
return bitcoin.core.CTransaction(
vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=outputs
) |
<SYSTEM_TASK:>
Creates a transaction for sending an asset.
<END_TASK>
<USER_TASK:>
Description:
def transfer_assets(self, asset_id, transfer_spec, btc_change_script, fees):
"""
Creates a transaction for sending an asset.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters transfer_spec: The parameters of the asset being transferred.
:param bytes btc_change_script: The script where to send bitcoin change, if any.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
""" |
return self.transfer(
[(asset_id, transfer_spec)],
TransferParameters(transfer_spec.unspent_outputs, None, btc_change_script, 0),
fees) |
<SYSTEM_TASK:>
Creates a transaction for swapping assets for bitcoins.
<END_TASK>
<USER_TASK:>
Description:
def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees):
"""
Creates a transaction for swapping assets for bitcoins.
:param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters asset_transfer_spec: The parameters of the asset being transferred.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
""" |
return self.transfer([(asset_id, asset_transfer_spec)], btc_transfer_spec, fees) |
<SYSTEM_TASK:>
Creates a transaction for swapping an asset for another asset.
<END_TASK>
<USER_TASK:>
Description:
def asset_asset_swap(
self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees):
"""
Creates a transaction for swapping an asset for another asset.
:param bytes asset1_id: The ID of the first asset.
:param TransferParameters asset1_transfer_spec: The parameters of the first asset being transferred.
It is also used for paying fees and/or receiving change if any.
:param bytes asset2_id: The ID of the second asset.
:param TransferDetails asset2_transfer_spec: The parameters of the second asset being transferred.
:param int fees: The fees to include in the transaction.
:return: The resulting unsigned transaction.
:rtype: CTransaction
""" |
btc_transfer_spec = TransferParameters(
asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0)
return self.transfer(
[(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees) |
<SYSTEM_TASK:>
Returns a list of uncolored outputs for the specified amount.
<END_TASK>
<USER_TASK:>
Description:
def _collect_uncolored_outputs(unspent_outputs, amount):
"""
Returns a list of uncolored outputs for the specified amount.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param int amount: The amount to collect.
:return: A list of outputs, and the total amount collected.
:rtype: (list[SpendableOutput], int)
""" |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id is None:
result.append(output)
total_amount += output.output.value
if total_amount >= amount:
return result, total_amount
raise InsufficientFundsError |
<SYSTEM_TASK:>
Returns a list of colored outputs for the specified quantity.
<END_TASK>
<USER_TASK:>
Description:
def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity):
"""
Returns a list of colored outputs for the specified quantity.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param bytes asset_id: The ID of the asset to collect.
:param int asset_quantity: The asset quantity to collect.
:return: A list of outputs, and the total asset quantity collected.
:rtype: (list[SpendableOutput], int)
""" |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id == asset_id:
result.append(output)
total_amount += output.output.asset_quantity
if total_amount >= asset_quantity:
return result, total_amount
raise InsufficientAssetQuantityError |
<SYSTEM_TASK:>
Creates an uncolored output.
<END_TASK>
<USER_TASK:>
Description:
def _get_uncolored_output(self, script, value):
"""
Creates an uncolored output.
:param bytes script: The output script.
:param int value: The satoshi value of the output.
:return: An object representing the uncolored output.
:rtype: TransactionOutput
""" |
if value < self._dust_amount:
raise DustOutputError
return bitcoin.core.CTxOut(value, bitcoin.core.CScript(script)) |
<SYSTEM_TASK:>
Creates a marker output.
<END_TASK>
<USER_TASK:>
Description:
def _get_marker_output(self, asset_quantities, metadata):
"""
Creates a marker output.
:param list[int] asset_quantities: The asset quantity list.
:param bytes metadata: The metadata contained in the output.
:return: An object representing the marker output.
:rtype: TransactionOutput
""" |
payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload()
script = openassets.protocol.MarkerOutput.build_script(payload)
return bitcoin.core.CTxOut(0, script) |
<SYSTEM_TASK:>
Create a verifier for an user authorized client
<END_TASK>
<USER_TASK:>
Description:
def authorized(self, request_token):
"""Create a verifier for an user authorized client""" |
verifier = generate_token(length=self.verifier_length[1])
self.save_verifier(request_token, verifier)
response = [
(u'oauth_token', request_token),
(u'oauth_verifier', verifier)
]
callback = self.get_callback(request_token)
return redirect(add_params_to_uri(callback, response)) |
<SYSTEM_TASK:>
Create an OAuth request token for a valid client request.
<END_TASK>
<USER_TASK:>
Description:
def request_token(self):
"""Create an OAuth request token for a valid client request.
Defaults to /request_token. Invoked by client applications.
""" |
client_key = request.oauth.client_key
realm = request.oauth.realm
# TODO: fallback on default realm?
callback = request.oauth.callback_uri
request_token = generate_token(length=self.request_token_length[1])
token_secret = generate_token(length=self.secret_length)
self.save_request_token(client_key, request_token, callback,
realm=realm, secret=token_secret)
return urlencode([(u'oauth_token', request_token),
(u'oauth_token_secret', token_secret),
(u'oauth_callback_confirmed', u'true')]) |
<SYSTEM_TASK:>
Create an OAuth access token for an authorized client.
<END_TASK>
<USER_TASK:>
Description:
def access_token(self):
"""Create an OAuth access token for an authorized client.
Defaults to /access_token. Invoked by client applications.
""" |
access_token = generate_token(length=self.access_token_length[1])
token_secret = generate_token(self.secret_length)
client_key = request.oauth.client_key
self.save_access_token(client_key, access_token,
request.oauth.resource_owner_key, secret=token_secret)
return urlencode([(u'oauth_token', access_token),
(u'oauth_token_secret', token_secret)]) |
<SYSTEM_TASK:>
Mark the view function f as a protected resource
<END_TASK>
<USER_TASK:>
Description:
def require_oauth(self, realm=None, require_resource_owner=True,
require_verifier=False, require_realm=False):
"""Mark the view function f as a protected resource""" |
def decorator(f):
@wraps(f)
def verify_request(*args, **kwargs):
"""Verify OAuth params before running view function f"""
try:
if request.form:
body = request.form.to_dict()
else:
body = request.data.decode("utf-8")
verify_result = self.verify_request(request.url.decode("utf-8"),
http_method=request.method.decode("utf-8"),
body=body,
headers=request.headers,
require_resource_owner=require_resource_owner,
require_verifier=require_verifier,
require_realm=require_realm or bool(realm),
required_realm=realm)
valid, oauth_request = verify_result
if valid:
request.oauth = self.collect_request_parameters(request)
# Request tokens are only valid when a verifier is too
token = {}
if require_verifier:
token[u'request_token'] = request.oauth.resource_owner_key
else:
token[u'access_token'] = request.oauth.resource_owner_key
# All nonce/timestamp pairs must be stored to prevent
# replay attacks, they may be connected to a specific
# client and token to decrease collision probability.
self.save_timestamp_and_nonce(request.oauth.client_key,
request.oauth.timestamp, request.oauth.nonce,
**token)
# By this point, the request is fully authorized
return f(*args, **kwargs)
else:
# Unauthorized requests should not diclose their cause
raise Unauthorized()
except ValueError as err:
# Caused by missing of or badly formatted parameters
raise BadRequest(err.message)
return verify_request
return decorator |
<SYSTEM_TASK:>
Collect parameters in an object for convenient access
<END_TASK>
<USER_TASK:>
Description:
def collect_request_parameters(self, request):
"""Collect parameters in an object for convenient access""" |
class OAuthParameters(object):
"""Used as a parameter container since plain object()s can't"""
pass
# Collect parameters
query = urlparse(request.url.decode("utf-8")).query
content_type = request.headers.get('Content-Type', '')
if request.form:
body = request.form.to_dict()
elif content_type == 'application/x-www-form-urlencoded':
body = request.data.decode("utf-8")
else:
body = ''
headers = dict(encode_params_utf8(request.headers.items()))
params = dict(collect_parameters(uri_query=query, body=body, headers=headers))
# Extract params and store for convenient and predictable access
oauth_params = OAuthParameters()
oauth_params.client_key = params.get(u'oauth_consumer_key')
oauth_params.resource_owner_key = params.get(u'oauth_token', None)
oauth_params.nonce = params.get(u'oauth_nonce')
oauth_params.timestamp = params.get(u'oauth_timestamp')
oauth_params.verifier = params.get(u'oauth_verifier', None)
oauth_params.callback_uri = params.get(u'oauth_callback', None)
oauth_params.realm = params.get(u'realm', None)
return oauth_params |
<SYSTEM_TASK:>
Get a resource size from the RSTB.
<END_TASK>
<USER_TASK:>
Description:
def get_size(self, name: str) -> int:
"""Get a resource size from the RSTB.""" |
crc32 = binascii.crc32(name.encode())
if crc32 in self.crc32_map:
return self.crc32_map[crc32]
if name in self.name_map:
return self.name_map[name]
return 0 |
<SYSTEM_TASK:>
Set the size of a resource in the RSTB.
<END_TASK>
<USER_TASK:>
Description:
def set_size(self, name: str, size: int):
"""Set the size of a resource in the RSTB.""" |
if self._needs_to_be_in_name_map(name):
if len(name) >= 128:
raise ValueError("Name is too long")
self.name_map[name] = size
else:
crc32 = binascii.crc32(name.encode())
self.crc32_map[crc32] = size |
<SYSTEM_TASK:>
Write the RSTB to the specified stream.
<END_TASK>
<USER_TASK:>
Description:
def write(self, stream: typing.BinaryIO, be: bool) -> None:
"""Write the RSTB to the specified stream.""" |
stream.write(b'RSTB')
stream.write(_to_u32(len(self.crc32_map), be))
stream.write(_to_u32(len(self.name_map), be))
# The CRC32 hashmap *must* be sorted because the game performs a binary search.
for crc32, size in sorted(self.crc32_map.items()):
stream.write(_to_u32(crc32, be))
stream.write(_to_u32(size, be))
# The name map does not have to be sorted, but Nintendo seems to do it, so let's sort too.
for name, size in sorted(self.name_map.items()):
stream.write(struct.pack('128s', name.encode()))
stream.write(_to_u32(size, be)) |
<SYSTEM_TASK:>
Generate an int with nbits random bits.
<END_TASK>
<USER_TASK:>
Description:
def randint(nbits: int) -> int:
"""Generate an int with nbits random bits.
Raises ValueError if nbits <= 0, and TypeError if it's not an integer.
>>> randint(16) #doctest:+SKIP
1871
""" |
if not isinstance(nbits, int):
raise TypeError('number of bits should be an integer')
if nbits <= 0:
raise ValueError('number of bits must be greater than zero')
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L676
nbytes = (nbits + 7) // 8 # bits / 8 and rounded up
num = int.from_bytes(randbytes(nbytes), 'big')
return num >> (nbytes * 8 - nbits) |
<SYSTEM_TASK:>
Return a randomly chosen element from the given sequence.
<END_TASK>
<USER_TASK:>
Description:
def randchoice(seq: Union[str, list, tuple, dict, set]) -> any:
"""Return a randomly chosen element from the given sequence.
Raises TypeError if *seq* is not str, list, tuple, dict, set and an
IndexError if it is empty.
>>> randchoice((1, 2, 'a', 'b')) #doctest:+SKIP
'a'
""" |
if not isinstance(seq, (str, list, tuple, dict, set)):
raise TypeError('seq must be str, list, tuple, dict or set')
if len(seq) <= 0:
raise IndexError('seq must have at least one element')
if isinstance(seq, set):
values = list(seq)
return randchoice(values)
elif isinstance(seq, dict):
indexes = list(seq)
index = randchoice(indexes)
else:
index = randbelow(len(seq))
return seq[index] |
<SYSTEM_TASK:>
Return a random int in the range [0,num).
<END_TASK>
<USER_TASK:>
Description:
def randbelow(num: int) -> int:
"""Return a random int in the range [0,num).
Raises ValueError if num <= 0, and TypeError if it's not an integer.
>>> randbelow(16) #doctest:+SKIP
13
""" |
if not isinstance(num, int):
raise TypeError('number must be an integer')
if num <= 0:
raise ValueError('number must be greater than zero')
if num == 1:
return 0
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L223
nbits = num.bit_length() # don't use (n-1) here because n can be 1
randnum = random_randint(nbits) # 0 <= randnum < 2**nbits
while randnum >= num:
randnum = random_randint(nbits)
return randnum |
<SYSTEM_TASK:>
Return a random text string of hexadecimal characters.
<END_TASK>
<USER_TASK:>
Description:
def randhex(ndigits: int) -> str:
"""Return a random text string of hexadecimal characters.
The string has *ndigits* random digits.
Raises ValueError if ndigits <= 0, and TypeError if it's not an integer.
>>> randhex(16) #doctest:+SKIP
'56054d728fc56f63'
""" |
if not isinstance(ndigits, int):
raise TypeError('number of digits must be an integer')
if ndigits <= 0:
raise ValueError('number of digits must be greater than zero')
nbytes = ceil(ndigits / 2)
rbytes = random_randbytes(nbytes)
hexstr = rbytes.hex()[:ndigits]
return hexstr |
<SYSTEM_TASK:>
Set the property _NET_MOVERESIZE_WINDOW to move or resize the given
<END_TASK>
<USER_TASK:>
Description:
def setMoveResizeWindow(self, win, gravity=0, x=None, y=None, w=None,
h=None):
"""
Set the property _NET_MOVERESIZE_WINDOW to move or resize the given
window. Flags are automatically calculated if x, y, w or h are defined.
:param win: the window object
:param gravity: gravity (one of the Xlib.X.*Gravity constant or 0)
:param x: int or None
:param y: int or None
:param w: int or None
:param h: int or None
""" |
# indicate source (application)
gravity_flags = gravity | 0b0000100000000000
if x is None:
x = 0
else:
gravity_flags = gravity_flags | 0b0000010000000000
if y is None:
y = 0
else:
gravity_flags = gravity_flags | 0b0000001000000000
if w is None:
w = 0
else:
gravity_flags = gravity_flags | 0b0000000100000000
if h is None:
h = 0
else:
gravity_flags = gravity_flags | 0b0000000010000000
self._setProperty('_NET_MOVERESIZE_WINDOW',
[gravity_flags, x, y, w, h], win) |
<SYSTEM_TASK:>
Send a ClientMessage event to the root window
<END_TASK>
<USER_TASK:>
Description:
def _setProperty(self, _type, data, win=None, mask=None):
"""
Send a ClientMessage event to the root window
""" |
if not win:
win = self.root
if type(data) is str:
dataSize = 8
else:
data = (data+[0]*(5-len(data)))[:5]
dataSize = 32
ev = protocol.event.ClientMessage(
window=win,
client_type=self.display.get_atom(_type), data=(dataSize, data))
if not mask:
mask = (X.SubstructureRedirectMask | X.SubstructureNotifyMask)
self.root.send_event(ev, event_mask=mask) |
<SYSTEM_TASK:>
Calculate the score at a given percentile of the input sequence.
<END_TASK>
<USER_TASK:>
Description:
def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
axis=None):
"""
Calculate the score at a given percentile of the input sequence.
For example, the score at `per=50` is the median. If the desired quantile
lies between two data points, we interpolate between them, according to
the value of `interpolation`. If the parameter `limit` is provided, it
should be a tuple (lower, upper) of two values.
Parameters
----------
a : array_like
A 1-D array of values from which to extract score.
per : array_like
Percentile(s) at which to extract score. Values should be in range
[0,100].
limit : tuple, optional
Tuple of two scalars, the lower and upper limits within which to
compute the percentile. Values of `a` outside
this (closed) interval will be ignored.
interpolation : {'fraction', 'lower', 'higher'}, optional
This optional parameter specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`
- fraction: ``i + (j - i) * fraction`` where ``fraction`` is the
fractional part of the index surrounded by ``i`` and ``j``.
- lower: ``i``.
- higher: ``j``.
axis : int, optional
Axis along which the percentiles are computed. The default (None)
is to compute the median along a flattened version of the array.
Returns
-------
score : float (or sequence of floats)
Score at percentile.
See Also
--------
percentileofscore
Examples
--------
>>> from scipy import stats
>>> a = np.arange(100)
>>> stats.scoreatpercentile(a, 50)
49.5
""" |
# adapted from NumPy's percentile function
a = np.asarray(a)
if limit:
a = a[(limit[0] <= a) & (a <= limit[1])]
if per == 0:
return a.min(axis=axis)
elif per == 100:
return a.max(axis=axis)
sorted = np.sort(a, axis=axis)
if axis is None:
axis = 0
return _compute_qth_percentile(sorted, per, interpolation_method, axis) |
<SYSTEM_TASK:>
Merge neighbors with same speaker.
<END_TASK>
<USER_TASK:>
Description:
def merge_equal_neighbors(self):
""" Merge neighbors with same speaker. """ |
IDX_LENGTH = 3
merged = self.segs.copy()
current_start = 0
j = 0
seg = self.segs.iloc[0]
for i in range(1, self.num_segments):
seg = self.segs.iloc[i]
last = self.segs.iloc[i - 1]
if seg.speaker == last.speaker:
merged.iat[j, IDX_LENGTH] = seg.start + seg.length - current_start
else:
j += 1
merged.iloc[j] = seg
current_start = seg.start
merged = merged.iloc[:(j+1)]
merged.sort_values('start', inplace = True)
return self.update_segs(merged) |
<SYSTEM_TASK:>
Converts a list of arguments from the command line into a list of
<END_TASK>
<USER_TASK:>
Description:
def format_arguments(*args):
"""
Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
Returns:
([positional_args], {kwargs})
""" |
positional_args = []
kwargs = {}
split_key = None
for arg in args:
if arg.startswith('--'):
arg = arg[2:]
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key.replace('-', '_')] = value
else:
split_key = arg.replace('-', '_')
elif split_key:
kwargs[split_key] = arg
split_key = None
else:
positional_args.append(arg)
return positional_args, kwargs |
<SYSTEM_TASK:>
Returns a `gocd_cli.settings.Settings` configured for settings file
<END_TASK>
<USER_TASK:>
Description:
def get_settings(section='gocd', settings_paths=('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')):
"""Returns a `gocd_cli.settings.Settings` configured for settings file
The settings will be read from environment variables first, then
it'll be read from the first config file found (if any).
Environment variables are expected to be in UPPERCASE and to be prefixed
with `GOCD_`.
Args:
section: The prefix to use for reading environment variables and the
name of the section in the config file. Default: gocd
settings_path: Possible paths for the configuration file.
Default: `('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')`
Returns:
`gocd_cli.settings.Settings` instance
""" |
if isinstance(settings_paths, basestring):
settings_paths = (settings_paths,)
config_file = next((path for path in settings_paths if is_file_readable(path)), None)
if config_file:
config_file = expand_user(config_file)
return Settings(prefix=section, section=section, filename=config_file) |
<SYSTEM_TASK:>
Returns a `gocd.Server` configured by the `settings`
<END_TASK>
<USER_TASK:>
Description:
def get_go_server(settings=None):
"""Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance
""" |
if not settings:
settings = get_settings()
return gocd.Server(
settings.get('server'),
user=settings.get('user'),
password=settings.get('password'),
) |
<SYSTEM_TASK:>
Require user to be logged in.
<END_TASK>
<USER_TASK:>
Description:
def require_openid(f):
"""Require user to be logged in.""" |
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
return redirect(next_url)
else:
return f(*args, **kwargs)
return decorator |
<SYSTEM_TASK:>
Does the login via OpenID. Has to call into `oid.try_login`
<END_TASK>
<USER_TASK:>
Description:
def login():
"""Does the login via OpenID. Has to call into `oid.try_login`
to start the OpenID machinery.
""" |
# if we are already logged in, go back to were we came from
if g.user is not None:
return redirect(oid.get_next_url())
if request.method == 'POST':
openid = request.form.get('openid')
if openid:
return oid.try_login(openid, ask_for=['email', 'fullname',
'nickname'])
return render_template('login.html', next=oid.get_next_url(),
error=oid.fetch_error()) |
<SYSTEM_TASK:>
Gets an output and information about its asset ID and asset quantity.
<END_TASK>
<USER_TASK:>
Description:
def get_output(self, transaction_hash, output_index):
"""
Gets an output and information about its asset ID and asset quantity.
:param bytes transaction_hash: The hash of the transaction containing the output.
:param int output_index: The index of the output.
:return: An object containing the output as well as its asset ID and asset quantity.
:rtype: Future[TransactionOutput]
""" |
cached_output = yield from self._cache.get(transaction_hash, output_index)
if cached_output is not None:
return cached_output
transaction = yield from self._transaction_provider(transaction_hash)
if transaction is None:
raise ValueError('Transaction {0} could not be retrieved'.format(bitcoin.core.b2lx(transaction_hash)))
colored_outputs = yield from self.color_transaction(transaction)
for index, output in enumerate(colored_outputs):
yield from self._cache.put(transaction_hash, index, output)
return colored_outputs[output_index] |
<SYSTEM_TASK:>
Computes the asset ID and asset quantity of every output in the transaction.
<END_TASK>
<USER_TASK:>
Description:
def color_transaction(self, transaction):
"""
Computes the asset ID and asset quantity of every output in the transaction.
:param CTransaction transaction: The transaction to color.
:return: A list containing all the colored outputs of the transaction.
:rtype: Future[list[TransactionOutput]]
""" |
# If the transaction is a coinbase transaction, the marker output is always invalid
if not transaction.is_coinbase():
for i, output in enumerate(transaction.vout):
# Parse the OP_RETURN script
marker_output_payload = MarkerOutput.parse_script(output.scriptPubKey)
if marker_output_payload is not None:
# Deserialize the payload as a marker output
marker_output = MarkerOutput.deserialize_payload(marker_output_payload)
if marker_output is not None:
# Fetch the colored outputs for previous transactions
inputs = []
for input in transaction.vin:
inputs.append((yield from asyncio.async(
self.get_output(input.prevout.hash, input.prevout.n), loop=self._loop)))
asset_ids = self._compute_asset_ids(
inputs,
i,
transaction.vout,
marker_output.asset_quantities)
if asset_ids is not None:
return asset_ids
# If no valid marker output was found in the transaction, all outputs are considered uncolored
return [
TransactionOutput(output.nValue, output.scriptPubKey, None, 0, OutputType.uncolored)
for output in transaction.vout] |
<SYSTEM_TASK:>
Computes the asset IDs of every output in a transaction.
<END_TASK>
<USER_TASK:>
Description:
def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities):
"""
Computes the asset IDs of every output in a transaction.
:param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction.
:param int marker_output_index: The position of the marker output in the transaction.
:param list[CTxOut] outputs: The outputs of the transaction.
:param list[int] asset_quantities: The list of asset quantities of the outputs.
:return: A list of outputs with asset ID and asset quantity information.
:rtype: list[TransactionOutput]
""" |
# If there are more items in the asset quantities list than outputs in the transaction (excluding the
# marker output), the marker output is deemed invalid
if len(asset_quantities) > len(outputs) - 1:
return None
# If there is no input in the transaction, the marker output is always invalid
if len(inputs) == 0:
return None
result = []
# Add the issuance outputs
issuance_asset_id = cls.hash_script(bytes(inputs[0].script))
for i in range(0, marker_output_index):
value, script = outputs[i].nValue, outputs[i].scriptPubKey
if i < len(asset_quantities) and asset_quantities[i] > 0:
output = TransactionOutput(value, script, issuance_asset_id, asset_quantities[i], OutputType.issuance)
else:
output = TransactionOutput(value, script, None, 0, OutputType.issuance)
result.append(output)
# Add the marker output
issuance_output = outputs[marker_output_index]
result.append(TransactionOutput(
issuance_output.nValue, issuance_output.scriptPubKey, None, 0, OutputType.marker_output))
# Add the transfer outputs
input_iterator = iter(inputs)
input_units_left = 0
for i in range(marker_output_index + 1, len(outputs)):
if i <= len(asset_quantities):
output_asset_quantity = asset_quantities[i - 1]
else:
output_asset_quantity = 0
output_units_left = output_asset_quantity
asset_id = None
while output_units_left > 0:
# Move to the next input if the current one is depleted
if input_units_left == 0:
current_input = next(input_iterator, None)
if current_input is None:
# There are less asset units available in the input than in the outputs:
# the marker output is considered invalid
return None
else:
input_units_left = current_input.asset_quantity
# If the current input is colored, assign its asset ID to the current output
if current_input.asset_id is not None:
progress = min(input_units_left, output_units_left)
output_units_left -= progress
input_units_left -= progress
if asset_id is None:
# This is the first input to map to this output
asset_id = current_input.asset_id
elif asset_id != current_input.asset_id:
# Another different asset ID has already been assigned to that output:
# the marker output is considered invalid
return None
result.append(TransactionOutput(
outputs[i].nValue, outputs[i].scriptPubKey, asset_id, output_asset_quantity, OutputType.transfer))
return result |
<SYSTEM_TASK:>
Hashes a script into an asset ID using SHA256 followed by RIPEMD160.
<END_TASK>
<USER_TASK:>
Description:
def hash_script(data):
"""
Hashes a script into an asset ID using SHA256 followed by RIPEMD160.
:param bytes data: The data to hash.
""" |
sha256 = hashlib.sha256()
ripemd = hashlib.new('ripemd160')
sha256.update(data)
ripemd.update(sha256.digest())
return ripemd.digest() |
<SYSTEM_TASK:>
Deserializes the marker output payload.
<END_TASK>
<USER_TASK:>
Description:
def deserialize_payload(cls, payload):
"""
Deserializes the marker output payload.
:param bytes payload: A buffer containing the marker output payload.
:return: The marker output object.
:rtype: MarkerOutput
""" |
with io.BytesIO(payload) as stream:
# The OAP marker and protocol version
oa_version = stream.read(4)
if oa_version != cls.OPEN_ASSETS_TAG:
return None
try:
# Deserialize the expected number of items in the asset quantity list
output_count = bitcoin.core.VarIntSerializer.stream_deserialize(stream)
# LEB128-encoded unsigned integers representing the asset quantity of every output in order
asset_quantities = []
for i in range(0, output_count):
asset_quantity = cls.leb128_decode(stream)
# If the LEB128-encoded asset quantity of any output exceeds 9 bytes,
# the marker output is deemed invalid
if asset_quantity > cls.MAX_ASSET_QUANTITY:
return None
asset_quantities.append(asset_quantity)
# The var-integer encoded length of the metadata field.
metadata_length = bitcoin.core.VarIntSerializer.stream_deserialize(stream)
# The actual metadata
metadata = stream.read(metadata_length)
# If the metadata string wasn't long enough, the marker output is malformed
if len(metadata) != metadata_length:
return None
# If there are bytes left to read, the marker output is malformed
last_byte = stream.read(1)
if len(last_byte) > 0:
return None
except bitcoin.core.SerializationTruncationError:
return None
return MarkerOutput(asset_quantities, metadata) |
<SYSTEM_TASK:>
Serializes the marker output data into a payload buffer.
<END_TASK>
<USER_TASK:>
Description:
def serialize_payload(self):
"""
Serializes the marker output data into a payload buffer.
:return: The serialized payload.
:rtype: bytes
""" |
with io.BytesIO() as stream:
stream.write(self.OPEN_ASSETS_TAG)
bitcoin.core.VarIntSerializer.stream_serialize(len(self.asset_quantities), stream)
for asset_quantity in self.asset_quantities:
stream.write(self.leb128_encode(asset_quantity))
bitcoin.core.VarIntSerializer.stream_serialize(len(self.metadata), stream)
stream.write(self.metadata)
return stream.getvalue() |
<SYSTEM_TASK:>
Parses an output and returns the payload if the output matches the right pattern for a marker output,
<END_TASK>
<USER_TASK:>
Description:
def parse_script(output_script):
"""
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes
""" |
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except bitcoin.core.script.CScriptTruncatedPushDataError:
return None
except bitcoin.core.script.CScriptInvalidError:
return None
if first_opcode == bitcoin.core.script.OP_RETURN and data is not None and remainder is None:
return data
else:
return None |
<SYSTEM_TASK:>
Creates an output script containing an OP_RETURN and a PUSHDATA.
<END_TASK>
<USER_TASK:>
Description:
def build_script(data):
"""
Creates an output script containing an OP_RETURN and a PUSHDATA.
:param bytes data: The content of the PUSHDATA.
:return: The final script.
:rtype: CScript
""" |
return bitcoin.core.script.CScript(
bytes([bitcoin.core.script.OP_RETURN]) + bitcoin.core.script.CScriptOp.encode_op_pushdata(data)) |
<SYSTEM_TASK:>
Decodes a LEB128-encoded unsigned integer.
<END_TASK>
<USER_TASK:>
Description:
def leb128_decode(data):
"""
Decodes a LEB128-encoded unsigned integer.
:param BufferedIOBase data: The buffer containing the LEB128-encoded integer to decode.
:return: The decoded integer.
:rtype: int
""" |
result = 0
shift = 0
while True:
character = data.read(1)
if len(character) == 0:
raise bitcoin.core.SerializationTruncationError('Invalid LEB128 integer')
b = ord(character)
result |= (b & 0x7f) << shift
if b & 0x80 == 0:
break
shift += 7
return result |
<SYSTEM_TASK:>
Encodes an integer using LEB128.
<END_TASK>
<USER_TASK:>
Description:
def leb128_encode(value):
"""
Encodes an integer using LEB128.
:param int value: The value to encode.
:return: The LEB128-encoded integer.
:rtype: bytes
""" |
if value == 0:
return b'\x00'
result = []
while value != 0:
byte = value & 0x7f
value >>= 7
if value != 0:
byte |= 0x80
result.append(byte)
return bytes(result) |
<SYSTEM_TASK:>
If this is the user's first login, the create_or_login function
<END_TASK>
<USER_TASK:>
Description:
def create_profile():
"""If this is the user's first login, the create_or_login function
will redirect here so that the user can set up his profile.
""" |
if g.user is not None or 'openid' not in session:
return redirect(url_for('index'))
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
if not name:
flash(u'Error: you have to provide a name')
elif '@' not in email:
flash(u'Error: you have to enter a valid email address')
else:
flash(u'Profile successfully created')
User.get_collection().insert(User(name, email, session['openid']))
return redirect(oid.get_next_url())
return render_template('create_profile.html', next_url=oid.get_next_url()) |
<SYSTEM_TASK:>
All purpose method to reduce an expression by applying
<END_TASK>
<USER_TASK:>
Description:
def replace(self, expression, replacements):
"""
All purpose method to reduce an expression by applying
successive replacement rules.
`expression` is either a SymPy expression
or a key in `scipy_data_fitting.Model.expressions`.
`replacements` can be any of the following,
or a list of any combination of the following:
- A replacement tuple as in `scipy_data_fitting.Model.replacements`.
- The name of a replacement in `scipy_data_fitting.Model.replacements`.
- The name of a replacement group in `scipy_data_fitting.Model.replacement_groups`.
Examples:
#!python
>>> model.replace(x + y, (x, z))
z + y
>>> model.replace('expression', (x, z))
>>> model.replace('expression', 'replacement')
>>> model.replace('expression', ['replacement_1', 'replacement_2'])
>>> model.replace('expression', ['replacement', 'group'])
""" |
# When expression is a string,
# get the expressions from self.expressions.
if isinstance(expression, str):
expression = self.expressions[expression]
# Allow for replacements to be empty.
if not replacements:
return expression
# Allow replacements to be a string.
if isinstance(replacements, str):
if replacements in self.replacements:
return self.replace(expression, self.replacements[replacements])
elif replacements in self.replacement_groups:
return self.replace(expression, self.replacement_groups[replacements])
# When replacements is a list of strings or tuples,
# Use reduce to make all the replacements.
if all(isinstance(item, str) for item in replacements) \
or all(isinstance(item, tuple) for item in replacements):
return functools.reduce(self.replace, replacements, expression)
# Otherwise make the replacement.
return expression.replace(*replacements) |
<SYSTEM_TASK:>
Advance to the next token.
<END_TASK>
<USER_TASK:>
Description:
def _forward(self):
"""Advance to the next token.
Internal methods, updates:
- self.current_token
- self.current_pos
Raises:
MissingTokensError: when trying to advance beyond the end of the
token flow.
""" |
try:
self.current_token = next(self.tokens)
except StopIteration:
raise MissingTokensError("Unexpected end of token stream at %d." %
self.current_pos)
self.current_pos += 1 |
<SYSTEM_TASK:>
Retrieve the current token, then advance the parser.
<END_TASK>
<USER_TASK:>
Description:
def consume(self, expect_class=None):
"""Retrieve the current token, then advance the parser.
If an expected class is provided, it will assert that the current token
matches that class (is an instance).
Note that when calling a token's nud() or led() functions, the "current"
token is the token following the token whose method has been called.
Returns:
Token: the previous current token.
Raises:
InvalidTokenError: If an expect_class is provided and the current
token doesn't match that class.
""" |
if expect_class and not isinstance(self.current_token, expect_class):
raise InvalidTokenError("Unexpected token at %d: got %r, expected %s" % (
self.current_pos, self.current_token, expect_class.__name__))
current_token = self.current_token
self._forward()
return current_token |
<SYSTEM_TASK:>
Extract an expression from the flow of tokens.
<END_TASK>
<USER_TASK:>
Description:
def expression(self, rbp=0):
"""Extract an expression from the flow of tokens.
Args:
rbp (int): the "right binding power" of the previous token.
This represents the (right) precedence of the previous token,
and will be compared to the (left) precedence of next tokens.
Returns:
Whatever the led/nud functions of tokens returned.
""" |
prev_token = self.consume()
# Retrieve the value from the previous token situated at the
# leftmost point in the expression
left = prev_token.nud(context=self)
while rbp < self.current_token.lbp:
# Read incoming tokens with a higher 'left binding power'.
# Those are tokens that prefer binding to the left of an expression
# than to the right of an expression.
prev_token = self.consume()
left = prev_token.led(left, context=self)
return left |
<SYSTEM_TASK:>
Parse the flow of tokens, and return their evaluation.
<END_TASK>
<USER_TASK:>
Description:
def parse(self):
"""Parse the flow of tokens, and return their evaluation.""" |
expr = self.expression()
if not isinstance(self.current_token, EndToken):
raise InvalidTokenError("Unconsumed trailing tokens.")
return expr |
<SYSTEM_TASK:>
Lowest level parsing function.
<END_TASK>
<USER_TASK:>
Description:
def keyword(self, token_stream, token, operators):
"""Lowest level parsing function.
A keyword consists of zero or more prefix operators (NOT, or
COMPARISON) followed by a TEXT, COLOR, or NUMBER block.
""" |
if token[0] == 'TEXT' or token[0] == 'COLOR':
return SearchKeyword(token[1], **operators)
elif token[0] == 'COMPARISON':
operators['comparison'] = token[1]
elif token[0] == 'NOT':
operators['boolean'] = 'not'
else:
if token[1] == None:
problem = 'end of input.'
else:
problem = 'token {0} in input'.format(token[1])
raise SyntaxError('Unexpected {0}'.format(problem))
token = next(token_stream)
return self.keyword(token_stream, token, operators) |
<SYSTEM_TASK:>
Parse the given text, return a list of Keywords.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, text):
"""Parse the given text, return a list of Keywords.""" |
token_stream = self.lexer.tokenize(text)
return self.expr(token_stream, next(token_stream)) |
<SYSTEM_TASK:>
Document custom properties added by the document author.
<END_TASK>
<USER_TASK:>
Description:
def customProperties(self):
"""Document custom properties added by the document author.
We canot convert the properties as indicated
with the http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes
namespace
:return: mapping of metadata
""" |
rval = {}
if len(self.content_types.getPathsForContentType(contenttypes.CT_CUSTOM_PROPS)) == 0:
# We may have no custom properties at all.
return rval
XPath = lxml.etree.XPath # Class shortcut
properties_xpath = XPath('custom-properties:property', namespaces=ns_map)
propname_xpath = XPath('@name')
propvalue_xpath = XPath('*/text()')
for tree in self.content_types.getTreesFor(self, contenttypes.CT_CUSTOM_PROPS):
for elt in properties_xpath(tree.getroot()):
rval[toUnicode(propname_xpath(elt)[0])] = u" ".join(propvalue_xpath(elt))
return rval |
<SYSTEM_TASK:>
Helper that merges core, extended and custom properties
<END_TASK>
<USER_TASK:>
Description:
def allProperties(self):
"""Helper that merges core, extended and custom properties
:return: mapping of all properties
""" |
rval = {}
rval.update(self.coreProperties)
rval.update(self.extendedProperties)
rval.update(self.customProperties)
return rval |
<SYSTEM_TASK:>
Words found in the various texts of the document.
<END_TASK>
<USER_TASK:>
Description:
def indexableText(self, include_properties=True):
"""Words found in the various texts of the document.
:param include_properties: Adds words from properties
:return: Space separated words of the document.
""" |
text = set()
for extractor in self._text_extractors:
if extractor.content_type in self.content_types.overrides:
for tree in self.content_types.getTreesFor(self, extractor.content_type):
words = extractor.indexableText(tree)
text |= words
if include_properties:
for prop_value in self.allProperties.values():
if prop_value is not None:
text.add(prop_value)
return u' '.join([word for word in text]) |
<SYSTEM_TASK:>
Check if we can process such file based on name
<END_TASK>
<USER_TASK:>
Description:
def canProcessFilename(cls, filename):
"""Check if we can process such file based on name
:param filename: File name as 'mydoc.docx'
:return: True if we can process such file
""" |
supported_patterns = cls._extpattern_to_mime.keys()
for pattern in supported_patterns:
if fnmatch.fnmatch(filename, pattern):
return True
return False |
<SYSTEM_TASK:>
Register a token.
<END_TASK>
<USER_TASK:>
Description:
def register(self, token, regexp):
"""Register a token.
Args:
token (Token): the token class to register
regexp (str): the regexp for that token
""" |
self._tokens.append((token, re.compile(regexp))) |
<SYSTEM_TASK:>
Retrieve all token definitions matching the beginning of a text.
<END_TASK>
<USER_TASK:>
Description:
def matching_tokens(self, text, start=0):
"""Retrieve all token definitions matching the beginning of a text.
Args:
text (str): the text to test
start (int): the position where matches should be searched in the
string (see re.match(rx, txt, pos))
Yields:
(token_class, re.Match): all token class whose regexp matches the
text, and the related re.Match object.
""" |
for token_class, regexp in self._tokens:
match = regexp.match(text, pos=start)
if match:
yield token_class, match |
<SYSTEM_TASK:>
Retrieve the next token from some text.
<END_TASK>
<USER_TASK:>
Description:
def get_token(self, text, start=0):
"""Retrieve the next token from some text.
Args:
text (str): the text from which tokens should be extracted
Returns:
(token_kind, token_text): the token kind and its content.
""" |
best_class = best_match = None
for token_class, match in self.matching_tokens(text):
if best_match and best_match.end() >= match.end():
continue
best_match = match
best_class = token_class
return best_class, best_match |
<SYSTEM_TASK:>
Register a token class.
<END_TASK>
<USER_TASK:>
Description:
def register_token(self, token_class, regexp=None):
"""Register a token class.
Args:
token_class (tdparser.Token): the token class to register
regexp (optional str): the regexp for elements of that token.
Defaults to the `regexp` attribute of the token class.
""" |
if regexp is None:
regexp = token_class.regexp
self.tokens.register(token_class, regexp) |
<SYSTEM_TASK:>
Split self.text into a list of tokens.
<END_TASK>
<USER_TASK:>
Description:
def lex(self, text):
"""Split self.text into a list of tokens.
Args:
text (str): text to parse
Yields:
Token: the tokens generated from the given text.
""" |
pos = 0
while text:
token_class, match = self.tokens.get_token(text)
if token_class is not None:
matched_text = text[match.start():match.end()]
yield token_class(matched_text)
text = text[match.end():]
pos += match.end()
elif text[0] in self.blank_chars:
text = text[1:]
pos += 1
else:
raise LexerError(
'Invalid character %s in %s' % (text[0], text),
position=pos)
yield self.end_token() |
<SYSTEM_TASK:>
Save fit result to a json file and a plot to an svg file.
<END_TASK>
<USER_TASK:>
Description:
def save_example_fit(fit):
"""
Save fit result to a json file and a plot to an svg file.
""" |
json_directory = os.path.join('examples', 'json')
plot_directory = os.path.join('examples', 'plots')
if not os.path.isdir(json_directory): os.makedirs(json_directory)
if not os.path.isdir(plot_directory): os.makedirs(plot_directory)
fit.to_json(os.path.join(json_directory, fit.name + '.json'), meta=fit.metadata)
plot = Plot(fit)
plot.save(os.path.join(plot_directory, fit.name + '.svg'))
plot.close() |
<SYSTEM_TASK:>
Remove `directory` if it exists, then create it if it doesn't exist.
<END_TASK>
<USER_TASK:>
Description:
def reset_directory(directory):
"""
Remove `directory` if it exists, then create it if it doesn't exist.
""" |
if os.path.isdir(directory): shutil.rmtree(directory)
if not os.path.isdir(directory): os.makedirs(directory) |
<SYSTEM_TASK:>
A dictionary of dictionaries.
<END_TASK>
<USER_TASK:>
Description:
def maps(self):
"""
A dictionary of dictionaries.
Each dictionary defines a map which is used to extend the metadata.
The precise way maps interact with the metadata is defined by `figure.fit._extend_meta`.
That method should be redefined or extended to suit specific use cases.
""" |
if not hasattr(self, '_maps'):
maps = {}
maps['tex_symbol'] = {}
maps['siunitx'] = {}
maps['value_transforms'] = {
'__default__': lambda x: round(x, 2),
}
self._maps = maps
return self._maps |
<SYSTEM_TASK:>
Provides all XML documents for that content type
<END_TASK>
<USER_TASK:>
Description:
def getTreesFor(self, document, content_type):
"""Provides all XML documents for that content type
@param document: a Document or subclass object
@param content_type: a MIME content type
@return: list of etree._ElementTree of that content type
""" |
# Relative path without potential leading path separator
# otherwise os.path.join doesn't work
for rel_path in self.overrides[content_type]:
if rel_path[0] in ('/', '\\'):
rel_path = rel_path[1:]
file_path = os.path.join(document._cache_dir, rel_path)
yield etree.parse(utils.xmlFile(file_path, 'rb'))
return |
<SYSTEM_TASK:>
Converts the string representation of a json number into its python object equivalent, an
<END_TASK>
<USER_TASK:>
Description:
def default_number_converter(number_str):
"""
Converts the string representation of a json number into its python object equivalent, an
int, long, float or whatever type suits.
""" |
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()
# FIXME: this handles a wider range of numbers than allowed by the json standard,
# etc.: float('nan') and float('inf'). But is this a problem?
return int(number_str) if is_int else float(number_str) |
<SYSTEM_TASK:>
Save the plot to the file at `path`.
<END_TASK>
<USER_TASK:>
Description:
def save(self, path, **kwargs):
"""
Save the plot to the file at `path`.
Any keyword arguments are passed to [`matplotlib.pyplot.savefig`][1].
[1]: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig
""" |
self.plot if not hasattr(self, '_plot') else None
self.figure.savefig(path, **kwargs) |
<SYSTEM_TASK:>
Remove all orphans in the site.
<END_TASK>
<USER_TASK:>
Description:
def orphans(dburl, sitedir):
"""Remove all orphans in the site.""" |
oldcwd = os.getcwd()
os.chdir(sitedir)
db = StrictRedis.from_url(dburl)
job = get_current_job(db)
job.meta.update({'out': '', 'return': None, 'status': None})
job.save()
returncode, out = orphans_single(default_exec=True)
job.meta.update({'out': out, 'return': returncode, 'status':
returncode == 0})
job.save()
os.chdir(oldcwd)
return returncode |
<SYSTEM_TASK:>
Build, in the single-user mode.
<END_TASK>
<USER_TASK:>
Description:
def build_single(mode):
"""Build, in the single-user mode.""" |
if mode == 'force':
amode = ['-a']
else:
amode = []
if executable.endswith('uwsgi'):
# hack, might fail in some environments!
_executable = executable[:-5] + 'python'
else:
_executable = executable
p = subprocess.Popen([_executable, '-m', 'nikola', 'build'] + amode,
stderr=subprocess.PIPE)
p.wait()
rl = p.stderr.readlines()
try:
out = ''.join(rl)
except TypeError:
out = ''.join(l.decode('utf-8') for l in rl)
return (p.returncode == 0), out |
<SYSTEM_TASK:>
Remove all orphans in the site, in the single user-mode.
<END_TASK>
<USER_TASK:>
Description:
def orphans_single(default_exec=False):
"""Remove all orphans in the site, in the single user-mode.""" |
if not default_exec and executable.endswith('uwsgi'):
# default_exec => rq => sys.executable is sane
_executable = executable[:-5] + 'python'
else:
_executable = executable
p = subprocess.Popen([_executable, '-m', 'nikola', 'orphans'],
stdout=subprocess.PIPE)
p.wait()
files = [l.strip().decode('utf-8') for l in p.stdout.readlines()]
for f in files:
if f:
os.unlink(f)
out = '\n'.join(files)
return p.returncode, out |
<SYSTEM_TASK:>
Add the data points to the plot.
<END_TASK>
<USER_TASK:>
Description:
def plot_data(self):
"""
Add the data points to the plot.
""" |
self.plt.plot(*self.fit.data, **self.options['data']) |
<SYSTEM_TASK:>
Add the fit to the plot.
<END_TASK>
<USER_TASK:>
Description:
def plot_fit(self):
"""
Add the fit to the plot.
""" |
self.plt.plot(*self.fit.fit, **self.options['fit']) |
<SYSTEM_TASK:>
Add a label to the x-axis.
<END_TASK>
<USER_TASK:>
Description:
def add_xlabel(self, text=None):
"""
Add a label to the x-axis.
""" |
x = self.fit.meta['independent']
if not text:
text = '$' + x['tex_symbol'] + r'$ $(\si{' + x['siunitx'] + r'})$'
self.plt.set_xlabel(text) |
<SYSTEM_TASK:>
Add a label to the y-axis.
<END_TASK>
<USER_TASK:>
Description:
def add_ylabel(self, text=None):
"""
Add a label to the y-axis.
""" |
y = self.fit.meta['dependent']
if not text:
text = '$' + y['tex_symbol'] + r'$ $(\si{' + y['siunitx'] + r'})$'
self.plt.set_ylabel(text) |
<SYSTEM_TASK:>
Add text to a plot in a grid fashion.
<END_TASK>
<USER_TASK:>
Description:
def add_text_table(self, rows, r0, dr, **kwargs):
"""
Add text to a plot in a grid fashion.
`rows` is a list of lists (the rows).
Each row contains the columns,
each column is text to add to the plot.
`r0` is a tuple `(x, y)` that positions the initial text.
`dr` is a tuple `(dx, dy)` that determines the column and row spacing.
Any keyword arguments will be passed to `matplotlib.pyplot.text`.
Example:
#!python
>>> rows = [ ['a', '=', '1'], ['b', '=', '2'] ]
>>> self.add_text_table(rows, (0.1, 0.9), (0.1, -0.1),
horizontalalignment='left',
verticalalignment='top')
[1]: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text
""" |
for m, row in enumerate(rows):
for n, column in enumerate(row):
self.plt.text(r0[0] + dr[0] * n, r0[1] + dr[1] * m, column,
transform=self.plt.axes.transAxes, **kwargs) |
<SYSTEM_TASK:>
Next gathered from session, then GET, then POST,
<END_TASK>
<USER_TASK:>
Description:
def _get_redirect_url(self, request):
"""
Next gathered from session, then GET, then POST,
then users absolute url.
""" |
if 'next' in request.session:
next_url = request.session['next']
del request.session['next']
elif 'next' in request.GET:
next_url = request.GET.get('next')
elif 'next' in request.POST:
next_url = request.POST.get('next')
else:
next_url = request.user.get_absolute_url()
if not next_url:
next_url = '/'
return next_url |
<SYSTEM_TASK:>
Provides the indexable - search engine oriented - raw text
<END_TASK>
<USER_TASK:>
Description:
def indexableText(self, tree):
"""Provides the indexable - search engine oriented - raw text
@param tree: an ElementTree
@return: set(["foo", "bar", ...])
""" |
rval = set()
root = tree.getroot()
for txp in self.text_elts_xpaths:
elts = txp(root)
texts = []
# Texts in element may be empty
for elt in elts:
text = self.text_extract_xpath(elt)
if len(text) > 0:
texts.append(text[0])
texts = self.separator.join(texts)
texts = [toUnicode(x) for x in self.wordssearch_rx.findall(texts)
if len(x) > 0]
rval |= set(texts)
return rval |
<SYSTEM_TASK:>
Recursively enter and extract text from all child
<END_TASK>
<USER_TASK:>
Description:
def _flatten(self, element):
"""Recursively enter and extract text from all child
elements.""" |
result = [(element.text or '')]
if element.attrib.get('alt'):
result.append(Symbol(element.attrib.get('alt')).textbox)
for sel in element:
result.append(self._flatten(sel))
result.append(sel.tail or '')
# prevent reminder text from getting too close to mana symbols
return ''.join(result).replace('}(', '} (') |
<SYSTEM_TASK:>
Hash the password, using bcrypt+sha256.
<END_TASK>
<USER_TASK:>
Description:
def password_hash(password):
"""Hash the password, using bcrypt+sha256.
.. versionchanged:: 1.1.0
:param str password: Password in plaintext
:return: password hash
:rtype: str
""" |
try:
return bcrypt_sha256.encrypt(password)
except TypeError:
return bcrypt_sha256.encrypt(password.decode('utf-8')) |
<SYSTEM_TASK:>
Get the UID of the post author.
<END_TASK>
<USER_TASK:>
Description:
def _author_uid_get(post):
"""Get the UID of the post author.
:param Post post: The post object to determine authorship of
:return: Author UID
:rtype: str
""" |
u = post.meta('author.uid')
return u if u else str(current_user.uid) |
<SYSTEM_TASK:>
Render a response using standard Nikola templates.
<END_TASK>
<USER_TASK:>
Description:
def render(template_name, context=None, code=200, headers=None):
"""Render a response using standard Nikola templates.
:param str template_name: Template name
:param dict context: Context (variables) to use in the template
:param int code: HTTP status code
:param headers: Headers to use for the response
:return: HTML fragment
:rtype: str
""" |
if context is None:
context = {}
if headers is None:
headers = {}
context['g'] = g
context['request'] = request
context['session'] = session
context['current_user'] = current_user
context['_author_get'] = _author_get
context['_author_uid_get'] = _author_uid_get
if app.config['COIL_URL'].startswith('https') and not request.url.startswith('https'):
# patch request URL for HTTPS proxy (eg. CloudFlare)
context['permalink'] = request.url.replace('http', 'https', 1)
else:
context['permalink'] = request.url
context['url_for'] = url_for
headers['Pragma'] = 'no-cache'
headers['Cache-Control'] = 'private, max-age=0, no-cache'
try:
mcp = current_user.must_change_password in (True, '1')
except AttributeError:
mcp = False
if mcp and not context.get('pwdchange_skip', False):
return redirect(url_for('acp_account') + '?status=pwdchange')
return _site.render_template(template_name, None, context), code, headers |
<SYSTEM_TASK:>
Get an user by the UID.
<END_TASK>
<USER_TASK:>
Description:
def get_user(uid):
"""Get an user by the UID.
:param str uid: UID to find
:return: the user
:rtype: User object
:raises ValueError: uid is not an integer
:raises KeyError: if user does not exist
""" |
if db is not None:
try:
uid = uid.decode('utf-8')
except AttributeError:
pass
d = db.hgetall('user:{0}'.format(uid))
if d:
nd = {}
# strings everywhere
for k in d:
try:
nd[k.decode('utf-8')] = d[k].decode('utf-8')
except AttributeError:
try:
nd[k.decode('utf-8')] = d[k]
except AttributeError:
nd[k] = d[k]
for p in PERMISSIONS:
nd[p] = nd.get(p) == '1'
return User(uid=uid, **nd)
else:
return None
else:
d = app.config['COIL_USERS'].get(uid)
if d:
return User(uid=uid, **d)
else:
return None |
<SYSTEM_TASK:>
Get an user by their username.
<END_TASK>
<USER_TASK:>
Description:
def find_user_by_name(username):
"""Get an user by their username.
:param str username: Username to find
:return: the user
:rtype: User object or None
""" |
if db is not None:
uid = db.hget('users', username)
if uid:
return get_user(uid)
else:
for uid, u in app.config['COIL_USERS'].items():
if u['username'] == username:
return get_user(uid) |
<SYSTEM_TASK:>
Write an user ot the database.
<END_TASK>
<USER_TASK:>
Description:
def write_user(user):
"""Write an user ot the database.
:param User user: User to write
""" |
udata = {}
for f in USER_FIELDS:
udata[f] = getattr(user, f)
for p in PERMISSIONS:
udata[p] = '1' if getattr(user, p) else '0'
db.hmset('user:{0}'.format(user.uid), udata) |
<SYSTEM_TASK:>
Handle user authentication.
<END_TASK>
<USER_TASK:>
Description:
def login():
"""Handle user authentication.
If requested over GET, present login page.
If requested over POST, log user in.
:param str status: Status of previous request/login attempt
""" |
alert = None
alert_status = 'danger'
code = 200
captcha = app.config['COIL_LOGIN_CAPTCHA']
form = LoginForm()
if request.method == 'POST':
if form.validate():
user = find_user_by_name(request.form['username'])
if not user:
alert = 'Invalid credentials.'
code = 401
if captcha['enabled']:
r = requests.post('https://www.google.com/recaptcha/api/siteverify',
data={'secret': captcha['secret_key'],
'response': request.form['g-recaptcha-response'],
'remoteip': request.remote_addr})
if r.status_code != 200:
alert = 'Cannot check CAPTCHA response.'
code = 500
else:
rj = r.json()
if not rj['success']:
alert = 'Invalid CAPTCHA response. Please try again.'
code = 401
if code == 200:
try:
pwd_ok = check_password(user.password,
request.form['password'])
except ValueError:
if user.password.startswith('$2a$12'):
# old bcrypt hash
pwd_ok = check_old_password(user.password,
request.form['password'])
if pwd_ok:
user.password = password_hash(
request.form['password'])
write_user(user)
else:
pwd_ok = False
if pwd_ok and user.is_active:
login_user(user, remember=('remember' in request.form))
return redirect(url_for('index'))
else:
alert = "Invalid credentials."
code = 401
else:
alert = 'Invalid credentials.'
code = 401
else:
if request.args.get('status') == 'unauthorized':
alert = 'Please log in to access this page.'
elif request.args.get('status') == 'logout':
alert = 'Logged out successfully.'
alert_status = 'success'
return render('coil_login.tmpl', {'title': 'Login', 'alert': alert, 'form':
form, 'alert_status': alert_status,
'pwdchange_skip': True,
'captcha': captcha},
code) |
<SYSTEM_TASK:>
Show the index with all posts.
<END_TASK>
<USER_TASK:>
Description:
def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
""" |
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}
n = request.args.get('all')
if n is None:
wants_now = None
else:
wants_now = n == '1'
if wants_now is None and current_user.wants_all_posts:
wants = True
else:
wants = wants_now
if current_user.can_edit_all_posts and wants:
posts = site.all_posts
pages = site.pages
else:
wants = False
posts = []
pages = []
for p in site.timeline:
if (p.meta('author.uid') and
p.meta('author.uid') != str(current_user.uid)):
continue
if p.is_post:
posts.append(p)
else:
pages.append(p)
context['posts'] = posts
context['pages'] = pages
context['title'] = 'Posts & Pages'
context['wants'] = wants
return render('coil_index.tmpl', context) |
<SYSTEM_TASK:>
Rebuild the site with a nice UI.
<END_TASK>
<USER_TASK:>
Description:
def rebuild(mode=''):
"""Rebuild the site with a nice UI.""" |
scan_site() # for good measure
if not current_user.can_rebuild_site:
return error('You are not permitted to rebuild the site.</p>'
'<p class="lead">Contact an administartor for '
'more information.', 401)
if db is not None:
db.set('site:needs_rebuild', '-1')
if not q.fetch_job('build') and not q.fetch_job('orphans'):
b = q.enqueue_call(func=coil.tasks.build,
args=(app.config['REDIS_URL'],
app.config['NIKOLA_ROOT'], mode),
job_id='build')
q.enqueue_call(func=coil.tasks.orphans,
args=(app.config['REDIS_URL'],
app.config['NIKOLA_ROOT']), job_id='orphans',
depends_on=b)
return render('coil_rebuild.tmpl', {'title': 'Rebuild'})
else:
status, outputb = coil.tasks.build_single(mode)
_, outputo = coil.tasks.orphans_single()
site.coil_needs_rebuild = '0'
return render('coil_rebuild_single.tmpl',
{'title': 'Rebuild', 'status': '1' if status else '0',
'outputb': outputb, 'outputo': outputo}) |
<SYSTEM_TASK:>
Serve bower components.
<END_TASK>
<USER_TASK:>
Description:
def serve_bower_components(path):
"""Serve bower components.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/bower_components/ => coil/data/bower_components
""" |
res = pkg_resources.resource_filename(
'coil', os.path.join('data', 'bower_components'))
return send_from_directory(res, path) |
<SYSTEM_TASK:>
Serve Coil assets.
<END_TASK>
<USER_TASK:>
Description:
def serve_coil_assets(path):
"""Serve Coil assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/coil_assets/ => coil/data/coil_assets
""" |
res = pkg_resources.resource_filename(
'coil', os.path.join('data', 'coil_assets'))
return send_from_directory(res, path) |
<SYSTEM_TASK:>
Serve Nikola assets.
<END_TASK>
<USER_TASK:>
Description:
def serve_assets(path):
"""Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
""" |
res = os.path.join(app.config['NIKOLA_ROOT'],
_site.config["OUTPUT_FOLDER"], 'assets')
return send_from_directory(res, path) |
<SYSTEM_TASK:>
Manage the user account of currently-logged-in users.
<END_TASK>
<USER_TASK:>
Description:
def acp_account():
"""Manage the user account of currently-logged-in users.
This does NOT accept admin-specific options.
""" |
if request.args.get('status') == 'pwdchange':
alert = 'You must change your password before proceeding.'
alert_status = 'danger'
pwdchange_skip = True
else:
alert = ''
alert_status = ''
pwdchange_skip = False
if db is None:
form = PwdHashForm()
return render('coil_account_single.tmpl',
context={'title': 'My account',
'form': form,
'alert': alert,
'alert_status': alert_status})
action = 'edit'
form = AccountForm()
if request.method == 'POST':
if int(current_user.uid) in app.config['COIL_USERS_PREVENT_EDITING']:
return error("Cannot edit data for this user.", 403)
if not form.validate():
return error("Bad Request", 400)
action = 'save'
data = request.form
if data['newpwd1']:
try:
pwd_ok = check_password(current_user.password, data['oldpwd'])
except ValueError:
if current_user.password.startswith('$2a$12'):
# old bcrypt hash
pwd_ok = check_old_password(current_user.password,
data['oldpwd'])
if data['newpwd1'] == data['newpwd2'] and pwd_ok:
current_user.password = password_hash(data['newpwd1'])
current_user.must_change_password = False
pwdchange_skip = True
else:
alert = 'Passwords don’t match.'
alert_status = 'danger'
action = 'save_fail'
current_user.realname = data['realname']
current_user.email = data['email']
current_user.wants_all_posts = 'wants_all_posts' in data
write_user(current_user)
return render('coil_account.tmpl',
context={'title': 'My account',
'action': action,
'alert': alert,
'alert_status': alert_status,
'form': form,
'pwdchange_skip': pwdchange_skip}) |
<SYSTEM_TASK:>
Edit an user account.
<END_TASK>
<USER_TASK:>
Description:
def acp_users_edit():
"""Edit an user account.""" |
global current_user
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
data = request.form
form = UserEditForm()
if not form.validate():
return error("Bad Request", 400)
action = data['action']
if action == 'new':
if not data['username']:
return error("No username to create specified.", 400)
uid = max(int(i) for i in db.hgetall('users').values()) + 1
pf = [False for p in PERMISSIONS]
pf[0] = True # active
pf[7] = True # must_change_password
user = User(uid, data['username'], '', '', '', *pf)
write_user(user)
db.hset('users', user.username, user.uid)
new = True
else:
user = get_user(data['uid'])
new = False
if not user:
return error("User does not exist.", 404)
alert = ''
alert_status = ''
if action == 'save':
if data['newpwd1']:
if data['newpwd1'] == data['newpwd2']:
user.password = password_hash(data['newpwd1'])
else:
alert = 'Passwords don’t match.'
alert_status = 'danger'
action = 'save_fail'
elif new:
alert = 'Must set a password.'
alert_status = 'danger'
action = 'save_fail'
if data['username'] != user.username:
db.hdel('users', user.username)
user.username = data['username']
db.hset('users', user.username, user.uid)
user.realname = data['realname']
user.email = data['email']
for p in PERMISSIONS:
setattr(user, p, p in data)
user.active = True
if user.uid == current_user.uid:
user.is_admin = True
user.must_change_password = False
current_user = user
write_user(user)
return render('coil_users_edit.tmpl',
context={'title': 'Edit user',
'user': user,
'new': new,
'action': action,
'alert': alert,
'alert_status': alert_status,
'form': form}) |
<SYSTEM_TASK:>
Import users from a TSV file.
<END_TASK>
<USER_TASK:>
Description:
def acp_users_import():
"""Import users from a TSV file.""" |
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserImportForm()
if not form.validate():
return error("Bad Request", 400)
fh = request.files['tsv'].stream
tsv = fh.read()
return tsv |
<SYSTEM_TASK:>
Delete or undelete an user account.
<END_TASK>
<USER_TASK:>
Description:
def acp_users_delete():
"""Delete or undelete an user account.""" |
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserDeleteForm()
if not form.validate():
return error("Bad Request", 400)
user = get_user(int(request.form['uid']))
direction = request.form['direction']
if not user:
return error("User does not exist.", 404)
else:
for p in PERMISSIONS:
setattr(user, p, False)
user.active = direction == 'undel'
write_user(user)
return redirect(url_for('acp_users') + '?status={_del}eted'.format(
_del=direction)) |
<SYSTEM_TASK:>
Returns whether the C extension is installed correctly.
<END_TASK>
<USER_TASK:>
Description:
def is_installed():
# type: () -> bool
"""
Returns whether the C extension is installed correctly.
""" |
try:
# noinspection PyUnresolvedReferences
from ccurl import Curl as CCurl
except ImportError:
return False
else:
# noinspection PyUnresolvedReferences
from iota.crypto import Curl
return issubclass(Curl, CCurl) |
<SYSTEM_TASK:>
Empty method to call to slurp up args and kwargs.
<END_TASK>
<USER_TASK:>
Description:
def mock_attr(self, *args, **kwargs):
"""
Empty method to call to slurp up args and kwargs.
`args` get pushed onto the url path.
`kwargs` are converted to a query string and appended to the URL.
""" |
self.path.extend(args)
self.qs.update(kwargs)
return self |
<SYSTEM_TASK:>
Returns the zero based column number based on the
<END_TASK>
<USER_TASK:>
Description:
def column(self):
""" Returns the zero based column number based on the
current position of the parser. """ |
for i in my_xrange(self._column_query_pos, self.pos):
if self.text[i] == '\t':
self._column += self.tab_size
self._column -= self._column % self.tab_size
else:
self._column += 1
self._column_query_pos = self.pos
return self._column |
<SYSTEM_TASK:>
Looking forward in the input text without actually stepping the current position.
<END_TASK>
<USER_TASK:>
Description:
def peek(self, offset=0):
""" Looking forward in the input text without actually stepping the current position.
returns None if the current position is at the end of the input. """ |
pos = self.pos + offset
if pos >= self.end:
return None
return self.text[pos] |
<SYSTEM_TASK:>
Reload the site from the database.
<END_TASK>
<USER_TASK:>
Description:
def reload_site(self):
"""Reload the site from the database.""" |
rev = int(self.db.get('site:rev'))
if rev != self.revision and self.db.exists('site:rev'):
timeline = self.db.lrange('site:timeline', 0, -1)
self._timeline = []
for data in timeline:
data = json.loads(data.decode('utf-8'))
self._timeline.append(Post(data[0], self.config, data[1],
data[2], data[3], self.messages,
self._site.compilers[data[4]]))
self._read_indexlist('posts')
self._read_indexlist('all_posts')
self._read_indexlist('pages')
self.revision = rev
self.logger.info("Site updated to revision {0}.".format(rev))
elif rev == self.revision and self.db.exists('site:rev'):
pass
else:
self.logger.warn("Site needs rescanning.") |
<SYSTEM_TASK:>
Read a list of indexes.
<END_TASK>
<USER_TASK:>
Description:
def _read_indexlist(self, name):
"""Read a list of indexes.""" |
setattr(self, '_' + name, [self._timeline[int(i)] for i in
self.db.lrange('site:{0}'.format(name), 0,
-1)]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.