text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unique_groups(input_list):
"""Function to get a unique list of groups.""" |
out_list = []
for item in input_list:
if item not in out_list:
out_list.append(item)
return out_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_to_dict(self):
"""Convert the group object to an appropriate DICT""" |
out_dict = {}
out_dict["groupName"] = self.group_name
out_dict["atomNameList"] = self.atom_name_list
out_dict["elementList"] = self.element_list
out_dict["bondOrderList"] = self.bond_order_list
out_dict["bondAtomList"] = self.bond_atom_list
out_dict["formalChargeList"] = self.charge_list
out_dict["singleLetterCode"] = self.single_letter_code
out_dict["chemCompType"] = self.group_type
return out_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_data(self):
"""Encode the data back into a dict.""" |
output_data = {}
output_data["groupTypeList"] = encode_array(self.group_type_list, 4, 0)
output_data["xCoordList"] = encode_array(self.x_coord_list, 10, 1000)
output_data["yCoordList"] = encode_array(self.y_coord_list, 10, 1000)
output_data["zCoordList"] = encode_array(self.z_coord_list, 10, 1000)
output_data["bFactorList"] = encode_array(self.b_factor_list, 10, 100)
output_data["occupancyList"] = encode_array(self.occupancy_list, 9, 100)
output_data["atomIdList"] = encode_array(self.atom_id_list, 8, 0)
output_data["altLocList"] = encode_array(self.alt_loc_list, 6, 0)
output_data["insCodeList"] = encode_array(self.ins_code_list, 6, 0)
output_data["groupIdList"] = encode_array(self.group_id_list, 8, 0)
output_data["groupList"] = self.group_list
output_data["sequenceIndexList"] = encode_array(self.sequence_index_list, 8, 0)
output_data["chainNameList"] = encode_array(self.chain_name_list, 5, 4)
output_data["chainIdList"] = encode_array(self.chain_id_list, 5, 4)
output_data["bondAtomList"] = encode_array(self.bond_atom_list, 4, 0)
output_data["bondOrderList"] = encode_array(self.bond_order_list, 2, 0)
output_data["secStructList"] = encode_array(self.sec_struct_list, 2, 0)
output_data["chainsPerModel"] = self.chains_per_model
output_data["groupsPerChain"] = self.groups_per_chain
output_data["spaceGroup"] = self.space_group
output_data["mmtfVersion"] = self.mmtf_version
output_data["mmtfProducer"] = self.mmtf_producer
output_data["structureId"] = self.structure_id
output_data["entityList"] = self.entity_list
output_data["bioAssemblyList"] = self.bio_assembly
output_data["rFree"] = self.r_free
output_data["rWork"] = self.r_work
output_data["resolution"] = self.resolution
output_data["title"] = self.title
output_data["experimentalMethods"] = self.experimental_methods
output_data["depositionDate"] = self.deposition_date
output_data["releaseDate"] = self.release_date
output_data["unitCell"] = self.unit_cell
output_data["numBonds"] = self.num_bonds
output_data["numChains"] = self.num_chains
output_data["numModels"] = self.num_models
output_data["numAtoms"] = self.num_atoms
output_data["numGroups"] = self.num_groups
return output_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def finalize_structure(self):
"""Any functions needed to cleanup the structure.""" |
self.group_list.append(self.current_group)
group_set = get_unique_groups(self.group_list)
for item in self.group_list:
self.group_type_list.append(group_set.index(item))
self.group_list = [x.convert_to_dict() for x in group_set] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_array(input_array):
"""Parse the header of an input byte array and then decode using the input array, the codec and the appropirate parameter. :param input_array: the array to be decoded :return the decoded array""" |
codec, length, param, input_array = parse_header(input_array)
return codec_dict[codec].decode(input_array, param) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_array(input_array, codec, param):
"""Encode the array using the method and then add the header to this array. :param input_array: the array to be encoded :param codec: the integer index of the codec to use :param param: the integer parameter to use in the function :return an array with the header added to the fornt""" |
return add_header(codec_dict[codec].encode(input_array, param), codec, len(input_array), param) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer is defined by num :param in_bytes: the input bytes :param num: the number of bytes per int :return the integer array""" |
dt = numpy.dtype('>i' + str(num))
return numpy.frombuffer(in_bytes, dt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recursive_index_decode(int_array, max=32767, min=-32768):
"""Unpack an array of integers using recursive indexing. :param int_array: the input array of integers :param max: the maximum integer size :param min: the minimum integer size :return the array of integers after recursive index decoding""" |
out_arr = []
decoded_val = 0
for item in int_array.tolist():
if item==max or item==min:
decoded_val += item
else:
decoded_val += item
out_arr.append(decoded_val)
decoded_val = 0
return numpy.asarray(out_arr,dtype=numpy.int32) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_coords(self):
"""Utility function to get the coordinates as a single list of tuples.""" |
out_list = []
for i in range(len(self.x_coord_list)):
out_list.append((self.x_coord_list[i],self.y_coord_list[i],self.z_coord_list[i],))
return out_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_data_on(self, data_setters):
"""Write the data from the getters to the setters. :param data_setters: a series of functions that can fill a chemical data structure :type data_setters: DataTransferInterface """ |
data_setters.init_structure(self.num_bonds, len(self.x_coord_list), len(self.group_type_list),
len(self.chain_id_list), len(self.chains_per_model), self.structure_id)
decoder_utils.add_entity_info(self, data_setters)
decoder_utils.add_atomic_information(self, data_setters)
decoder_utils.add_header_info(self, data_setters)
decoder_utils.add_xtalographic_info(self, data_setters)
decoder_utils.generate_bio_assembly(self, data_setters)
decoder_utils.add_inter_group_bonds(self, data_setters)
data_setters.finalize_structure() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_mmtf(file_path, input_data, input_function):
"""API function to write data as MMTF to a file :param file_path the path of the file to write :param input_data the input data in any user format :param input_function a function to converte input_data to an output format. Must contain all methods in TemplateEncoder """ |
mmtf_encoder = MMTFEncoder()
pass_data_on(input_data, input_function, mmtf_encoder)
mmtf_encoder.write_file(file_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_raw_data_from_url(pdb_id, reduced=False):
"""" Get the msgpack unpacked data given a PDB id. :param pdb_id: the input PDB id :return the unpacked data (a dict) """ |
url = get_url(pdb_id,reduced)
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
data = ungzip_data(response.read())
else:
data = response.read()
return _unpack(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(file_path):
"""Return a decoded API to the data from a file path. :param file_path: the input file path. Data is not entropy compressed (e.g. gzip) :return an API to decoded data """ |
newDecoder = MMTFDecoder()
with open(file_path, "rb") as fh:
newDecoder.decode_data(_unpack(fh))
return newDecoder |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ungzip_data(input_data):
"""Return a string of data after gzip decoding :param the input gziped data :return the gzip decoded data""" |
buf = StringIO(input_data)
f = gzip.GzipFile(fileobj=buf)
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_ints_to_bytes(in_ints, num):
"""Convert an integer array into a byte arrays. The number of bytes forming an integer is defined by num :param in_ints: the input integers :param num: the number of bytes per int :return the integer array""" |
out_bytes= b""
for val in in_ints:
out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val)
return out_bytes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_chain_list(in_strings):
"""Convert a list of strings to a list of byte arrays. :param in_strings: the input strings :return the encoded list of byte arrays""" |
out_bytes = b""
for in_s in in_strings:
out_bytes+=in_s.encode('ascii')
for i in range(mmtf.utils.constants.CHAIN_LEN -len(in_s)):
out_bytes+= mmtf.utils.constants.NULL_BYTE.encode('ascii')
return out_bytes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recursive_index_encode(int_array, max=32767, min=-32768):
"""Pack an integer array using recursive indexing. :param int_array: the input array of integers :param max: the maximum integer size :param min: the minimum integer size :return the array of integers after recursive index encoding""" |
out_arr = []
for curr in int_array:
if curr >= 0 :
while curr >= max:
out_arr.append(max)
curr -= max
else:
while curr <= min:
out_arr.append(min)
curr += int(math.fabs(min))
out_arr.append(curr)
return out_arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build(algo, init):
'''Build and return an optimizer for the rosenbrock function.
In downhill, an optimizer can be constructed using the build() top-level
function. This function requires several Theano quantities such as the loss
being optimized and the parameters to update during optimization.
'''
x = theano.shared(np.array(init, FLOAT), name='x')
n = 0.1 * RandomStreams().normal((len(init) - 1, ))
monitors = []
if len(init) == 2:
# this gives us access to the x and y locations during optimization.
monitors.extend([('x', x[:-1].sum()), ('y', x[1:].sum())])
return downhill.build(
algo,
loss=(n + 100 * (x[1:] - x[:-1] ** 2) ** 2 + (1 - x[:-1]) ** 2).sum(),
params=[x],
monitors=monitors,
monitor_gradients=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_and_trace(algo, init, limit=100, **kwargs):
'''Run an optimizer on the rosenbrock function. Return xs, ys, and losses.
In downhill, optimization algorithms can be iterated over to progressively
minimize the loss. At each iteration, the optimizer yields a dictionary of
monitor values that were computed during that iteration. Here we build an
optimizer and then run it for a fixed number of iterations.
'''
kw = dict(min_improvement=0, patience=0, max_gradient_norm=100)
kw.update(kwargs)
xs, ys, loss = [], [], []
for tm, _ in build(algo, init).iterate([[]], **kw):
if len(init) == 2:
xs.append(tm['x'])
ys.append(tm['y'])
loss.append(tm['loss'])
if len(loss) == limit:
break
# Return the optimization up to any failure of patience.
return xs[:-9], ys[:-9], loss[-9] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def minimize(loss, train, valid=None, params=None, inputs=None, algo='rmsprop',
updates=(), monitors=(), monitor_gradients=False, batch_size=32,
train_batches=None, valid_batches=None, **kwargs):
'''Minimize a loss function with respect to some symbolic parameters.
Additional keyword arguments are passed to the underlying :class:`Optimizer
<downhill.base.Optimizer>` instance.
Parameters
----------
loss : Theano expression
Loss function to minimize. This must be a scalar-valued expression.
train : :class:`Dataset <downhill.dataset.Dataset>`, ndarray, or callable
Dataset to use for computing gradient updates.
valid : :class:`Dataset <downhill.dataset.Dataset>`, ndarray, or callable, optional
Dataset to use for validating the minimization process. The training
dataset is used if this is not provided.
params : list of Theano variables, optional
Symbolic variables to adjust to minimize the loss. If not given, these
will be computed automatically by walking the computation graph.
inputs : list of Theano variables, optional
Symbolic variables required to compute the loss. If not given, these
will be computed automatically by walking the computation graph.
algo : str, optional
Name of the minimization algorithm to use. Must be one of the strings
that can be passed to :func:`build`. Defaults to ``'rmsprop'``.
updates : list of update pairs, optional
A list of pairs providing updates for the internal of the loss
computation. Normally this is empty, but it can be provided if the loss,
for example, requires an update to an internal random number generator.
monitors : dict or sequence of (str, Theano expression) tuples, optional
Additional values to monitor during optimization. These must be provided
as either a sequence of (name, expression) tuples, or as a dictionary
mapping string names to Theano expressions.
monitor_gradients : bool, optional
If True, add monitors to log the norms of the parameter gradients during
optimization. Defaults to False.
batch_size : int, optional
Size of batches provided by datasets. Defaults to 32.
train_batches : int, optional
Number of batches of training data to iterate over during one pass of
optimization. Defaults to None, which uses the entire training dataset.
valid_batches : int, optional
Number of batches of validation data to iterate over during one pass of
validation. Defaults to None, which uses the entire validation dataset.
Returns
-------
train_monitors : dict
A dictionary mapping monitor names to monitor values. This dictionary
will always contain the ``'loss'`` key, giving the value of the loss
evaluated on the training dataset.
valid_monitors : dict
A dictionary mapping monitor names to monitor values, evaluated on the
validation dataset. This dictionary will always contain the ``'loss'``
key, giving the value of the loss function. Because validation is not
always computed after every optimization update, these monitor values
may be "stale"; however, they will always contain the most recently
computed values.
'''
if not isinstance(train, Dataset):
train = Dataset(
train,
name='train',
batch_size=batch_size,
iteration_size=train_batches,
)
if valid is not None and not isinstance(valid, Dataset):
valid = Dataset(
valid,
name='valid',
batch_size=batch_size,
iteration_size=valid_batches,
)
return build(
algo,
loss=loss,
params=params,
inputs=inputs,
updates=updates,
monitors=monitors,
monitor_gradients=monitor_gradients,
).minimize(train, valid, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_label(loss, key):
'''Create a legend label for an optimization run.'''
algo, rate, mu, half, reg = key
slots, args = ['{:.3f}', '{}', 'm={:.3f}'], [loss, algo, mu]
if algo in 'SGD NAG RMSProp Adam ESGD'.split():
slots.append('lr={:.2e}')
args.append(rate)
if algo in 'RMSProp ADADELTA ESGD'.split():
slots.append('rmsh={}')
args.append(half)
slots.append('rmsr={:.2e}')
args.append(reg)
return ' '.join(slots).format(*args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def iterate(self, shuffle=True):
'''Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration reaches the end
of the batch list. Defaults to True.
Yields
------
batches : data batches
A sequence of batches---often from a training, validation, or test
dataset.
'''
for _ in range(self.iteration_size):
if self._callable is not None:
yield self._callable()
else:
yield self._next_batch(shuffle) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def shared_like(param, suffix, init=0):
'''Create a Theano shared variable like an existing parameter.
Parameters
----------
param : Theano variable
Theano variable to use for shape information.
suffix : str
Suffix to append to the parameter's name for the new variable.
init : float or ndarray, optional
Initial value of the shared variable. Defaults to 0.
Returns
-------
shared : Theano shared variable
A new shared variable with the same shape and data type as ``param``.
'''
return theano.shared(np.zeros_like(param.get_value()) + init,
name='{}_{}'.format(param.name, suffix),
broadcastable=param.broadcastable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find_inputs_and_params(node):
'''Walk a computation graph and extract root variables.
Parameters
----------
node : Theano expression
A symbolic Theano expression to walk.
Returns
-------
inputs : list Theano variables
A list of candidate inputs for this graph. Inputs are nodes in the graph
with no parents that are not shared and are not constants.
params : list of Theano shared variables
A list of candidate parameters for this graph. Parameters are nodes in
the graph that are shared variables.
'''
queue, seen, inputs, params = [node], set(), set(), set()
while queue:
node = queue.pop()
seen.add(node)
queue.extend(p for p in node.get_parents() if p not in seen)
if not node.get_parents():
if isinstance(node, theano.compile.SharedVariable):
params.add(node)
elif not isinstance(node, TT.Constant):
inputs.add(node)
return list(inputs), list(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def log(msg, *args, **kwargs):
'''Log a message to the console.
Parameters
----------
msg : str
A string to display on the console. This can contain {}-style
formatting commands; the remaining positional and keyword arguments
will be used to fill them in.
'''
now = datetime.datetime.now()
module = 'downhill'
if _detailed_callsite:
caller = inspect.stack()[1]
parts = caller.filename.replace('.py', '').split('/')
module = '{}:{}'.format(
'.'.join(parts[parts.index('downhill')+1:]), caller.lineno)
click.echo(' '.join((
click.style(now.strftime('%Y%m%d'), fg='blue'),
click.style(now.strftime('%H%M%S'), fg='cyan'),
click.style(module, fg='magenta'),
msg.format(*args, **kwargs),
))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def log_param(name, value):
'''Log a parameter value to the console.
Parameters
----------
name : str
Name of the parameter being logged.
value : any
Value of the parameter being logged.
'''
log('setting {} = {}', click.style(str(name)),
click.style(str(value), fg='yellow')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def load_mnist():
'''Load the MNIST digits dataset.'''
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
train_images = arr('train_images', np.float32) / 128 - 1
train_labels = arr('train_labels', np.uint8)
return ((train_images[:50000], train_labels[:50000, 0]),
(train_images[50000:], train_labels[50000:, 0])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build(algo, loss, params=None, inputs=None, updates=(), monitors=(),
monitor_gradients=False):
'''Construct an optimizer by name.
Parameters
----------
algo : str
The name of the optimization algorithm to build.
loss : Theano expression
Loss function to minimize. This must be a scalar-valued expression.
params : list of Theano variables, optional
Symbolic variables to adjust to minimize the loss. If not given, these
will be computed automatically by walking the computation graph.
inputs : list of Theano variables, optional
Symbolic variables required to compute the loss. If not given, these
will be computed automatically by walking the computation graph.
updates : list of update pairs, optional
A list of pairs providing updates for the internal of the loss
computation. Normally this is empty, but it can be provided if the loss,
for example, requires an update to an internal random number generator.
monitors : dict or sequence of (str, Theano expression) tuples, optional
Additional values to monitor during optimization. These must be provided
as either a sequence of (name, expression) tuples, or as a dictionary
mapping string names to Theano expressions.
monitor_gradients : bool, optional
If True, add monitors to log the norms of the parameter gradients during
optimization. Defaults to False.
Returns
-------
optimizer : :class:`Optimizer`
An optimizer instance.
'''
return Optimizer.build(algo, loss, params, inputs,
updates=updates, monitors=monitors,
monitor_gradients=monitor_gradients) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _compile(self, **kwargs):
'''Compile the Theano functions for evaluating and updating our model.
'''
util.log('compiling evaluation function')
self.f_eval = theano.function(self._inputs,
self._monitor_exprs,
updates=self._updates,
name='evaluation')
label = self.__class__.__name__
util.log('compiling {} optimizer'.format(click.style(label, fg='red')))
updates = list(self._updates) + list(self.get_updates(**kwargs))
self.f_step = theano.function(self._inputs,
self._monitor_exprs,
updates=updates,
name=label) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_updates(self, **kwargs):
'''Get parameter update expressions for performing optimization.
Keyword arguments can be applied here to set any of the global
optimizer attributes.
Yields
------
updates : (parameter, expression) tuples
A sequence of parameter updates to be applied during optimization.
'''
self._prepare(**kwargs)
for param, grad in self._differentiate():
for var, update in self._get_updates_for(param, grad):
# For auxiliary variables, updates are meant to replace the
# existing variable value.
if var != param:
yield var, update
continue
# If momentum is disabled, just apply the parameter delta.
if self.momentum == 0:
yield var, param - update
continue
# Momentum is enabled, so we keep track of velocity here.
vel_tm1 = util.shared_like(param, 'vel')
vel_t = util.as_float(self.momentum) * vel_tm1 - update
if self.nesterov:
# see http://arxiv.org/pdf/1212.0901v2.pdf (eq 7) and
# https://github.com/lisa-lab/pylearn2/pull/136#issuecomment-10381617
mom_sqr = util.as_float(self.momentum ** 2)
mom_inc = util.as_float(1 + self.momentum)
vel_t = mom_sqr * vel_tm1 - mom_inc * update
yield vel_tm1, vel_t
yield param, param + vel_t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _differentiate(self, params=None):
'''Return a sequence of gradients for our parameters.
If this optimizer has been configured with a gradient norm limit, or
with elementwise gradient clipping, this method applies the appropriate
rescaling and clipping operations before returning the gradient.
Parameters
----------
params : list of Theano variables, optional
Return the gradient with respect to these parameters. Defaults to
all parameters that the optimizer knows about.
Yields
------
pairs : (param, grad) tuples
Generates a sequence of tuples representing each of the parameters
requested and the corresponding Theano gradient expressions.
'''
if params is None:
params = self._params
for param, grad in zip(params, TT.grad(self._loss, params)):
if self.max_gradient_elem > 0:
limit = util.as_float(self.max_gradient_elem)
yield param, TT.clip(grad, -limit, limit)
elif self.max_gradient_norm > 0:
norm = TT.sqrt((grad * grad).sum())
limit = util.as_float(self.max_gradient_norm)
yield param, grad * TT.minimum(1, limit / norm)
else:
yield param, grad |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def set_params(self, targets=None):
'''Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters for this optimizer will be
used.
'''
if not isinstance(targets, (list, tuple)):
targets = self._best_params
for param, target in zip(self._params, targets):
param.set_value(target) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _log(self, monitors, iteration, label='', suffix=''):
'''Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
iteration : int
Optimization iteration that we are logging.
label : str, optional
A label for the name of the optimizer creating the log line.
Defaults to the name of the current class.
suffix : str, optional
A suffix to add to the end of the log line, if any.
'''
label = label or self.__class__.__name__
fields = (('{}={:.6f}').format(k, v) for k, v in monitors.items())
util.log('{} {} {}{}'.format(label, iteration, ' '.join(fields), suffix)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evaluate(self, dataset):
'''Evaluate the current model parameters on a dataset.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A set of data to use for evaluating the model.
Returns
-------
monitors : OrderedDict
A dictionary mapping monitor names to values. Monitors are
quantities of interest during optimization---for example, loss
function, accuracy, or whatever the optimization task requires.
'''
if dataset is None:
values = [self.f_eval()]
else:
values = [self.f_eval(*x) for x in dataset]
monitors = zip(self._monitor_names, np.mean(values, axis=0))
return collections.OrderedDict(monitors) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _prepare(self, **kwargs):
'''Set up properties for optimization.
This method can be overridden by base classes to provide parameters that
are specific to a particular optimization technique (e.g., setting up a
learning rate value).
'''
self.learning_rate = util.as_float(kwargs.pop('learning_rate', 1e-4))
self.momentum = kwargs.pop('momentum', 0)
self.nesterov = kwargs.pop('nesterov', False)
self.patience = kwargs.get('patience', 5)
self.validate_every = kwargs.pop('validate_every', 10)
self.min_improvement = kwargs.pop('min_improvement', 0)
self.max_gradient_norm = kwargs.pop('max_gradient_norm', 0)
self.max_gradient_elem = kwargs.pop('max_gradient_elem', 0)
util.log_param('patience', self.patience)
util.log_param('validate_every', self.validate_every)
util.log_param('min_improvement', self.min_improvement)
util.log_param('max_gradient_norm', self.max_gradient_norm)
util.log_param('max_gradient_elem', self.max_gradient_elem)
util.log_param('learning_rate', self.learning_rate)
util.log_param('momentum', self.momentum)
util.log_param('nesterov', self.nesterov) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def iterate(self, train=None, valid=None, max_updates=None, **kwargs):
r'''Optimize a loss iteratively using a training and validation dataset.
This method yields a series of monitor values to the caller. After every
optimization epoch, a pair of monitor dictionaries is generated: one
evaluated on the training dataset during the epoch, and another
evaluated on the validation dataset at the most recent validation epoch.
The validation monitors might not be updated during every optimization
iteration; in this case, the most recent validation monitors will be
yielded along with the training monitors.
Additional keyword arguments supplied here will set the global
optimizer attributes.
Parameters
----------
train : sequence or :class:`Dataset <downhill.dataset.Dataset>`
A set of training data for computing updates to model parameters.
valid : sequence or :class:`Dataset <downhill.dataset.Dataset>`
A set of validation data for computing monitor values and
determining when the loss has stopped improving. Defaults to the
training data.
max_updates : int, optional
If specified, halt optimization after this many gradient updates
have been processed. If not provided, uses early stopping to decide
when to halt.
Yields
------
train_monitors : dict
A dictionary mapping monitor names to values, evaluated on the
training dataset.
valid_monitors : dict
A dictionary containing monitor values evaluated on the validation
dataset.
'''
self._compile(**kwargs)
if valid is None:
valid = train
iteration = 0
training = validation = None
while max_updates is None or iteration < max_updates:
if not iteration % self.validate_every:
try:
validation = self.evaluate(valid)
except KeyboardInterrupt:
util.log('interrupted!')
break
if self._test_patience(validation):
util.log('patience elapsed!')
break
try:
training = self._step(train)
except KeyboardInterrupt:
util.log('interrupted!')
break
iteration += 1
self._log(training, iteration)
yield training, validation
self.set_params('best') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def minimize(self, *args, **kwargs):
'''Optimize our loss exhaustively.
This method is a thin wrapper over the :func:`iterate` method. It simply
exhausts the iterative optimization process and returns the final
monitor values.
Returns
-------
train_monitors : dict
A dictionary mapping monitor names to values, evaluated on the
training dataset.
valid_monitors : dict
A dictionary containing monitor values evaluated on the validation
dataset.
'''
monitors = None
for monitors in self.iterate(*args, **kwargs):
pass
return monitors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _step(self, dataset):
'''Advance the state of the optimizer by one step.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A dataset for optimizing the model.
Returns
-------
train_monitors : dict
A dictionary mapping monitor names to values.
'''
if dataset is None:
values = [self.f_step()]
else:
values = [self.f_step(*x) for x in dataset]
return collections.OrderedDict(
zip(self._monitor_names, np.mean(values, axis=0))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accept_arguments(method, number_of_arguments=1):
"""Returns True if the given method will accept the given number of arguments method: the method to perform introspection on number_of_arguments: the number_of_arguments """ |
if 'method' in method.__class__.__name__:
number_of_arguments += 1
func = getattr(method, 'im_func', getattr(method, '__func__'))
func_defaults = getattr(func, 'func_defaults', getattr(func, '__defaults__'))
number_of_defaults = func_defaults and len(func_defaults) or 0
elif method.__class__.__name__ == 'function':
func_defaults = getattr(method, 'func_defaults', getattr(method, '__defaults__'))
number_of_defaults = func_defaults and len(func_defaults) or 0
coArgCount = getattr(method, 'func_code', getattr(method, '__code__')).co_argcount
if(coArgCount >= number_of_arguments and coArgCount - number_of_defaults <= number_of_arguments):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, signal, slot, transform=None, condition=None):
"""Defines a connection between this objects signal and another objects slot signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be called slot: the slot method to call transform: an optional value override to pass into the slot method as the first variable condition: only call the slot if the value emitted matches the required value or calling required returns True """ |
if not signal in self.signals:
print("WARNING: {0} is trying to connect a slot to an undefined signal: {1}".format(self.__class__.__name__,
str(signal)))
return
if not hasattr(self, 'connections'):
self.connections = {}
connection = self.connections.setdefault(signal, {})
connection = connection.setdefault(condition, {})
connection[slot] = transform |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key):
""" Returns context data for a given app, can be an ID or a case insensitive name """ |
keystr = str(key)
res = None
try:
res = self.ctx[keystr]
except KeyError:
for k, v in self.ctx.items():
if "name" in v and v["name"].lower() == keystr.lower():
res = v
break
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_name(self):
""" The URL-friendly identifier for the item. Generates its own approximation if one isn't available """ |
name = self._item.get("market_hash_name")
if not name:
name = "{0.appid}-{0.name}".format(self)
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quality(self):
""" Can't really trust presence of a schema here, but there is an ID sometimes """ |
try:
qid = int((self.tool_metadata or {}).get("quality", 0))
except:
qid = 0
# We might be able to get the quality strings from the item's tags
internal_name, name = "normal", "Normal"
if self.tags:
tags = {x.get('category'): x for x in self.tags}
if 'Quality' in tags:
internal_name, name = tags['Quality'].get('internal_name'), tags['Quality'].get('name')
return qid, internal_name, name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls):
"""Get the current API key. if one has not been given via 'set' the env var STEAMODD_API_KEY will be checked instead. """ |
apikey = cls.__api_key or cls.__api_key_env_var
if apikey:
return apikey
else:
raise APIKeyMissingError("API key not set") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self):
""" Make the API call again and fetch fresh data. """ |
data = self._downloader.download()
# Only try to pass errors arg if supported
if sys.version >= "2.7":
data = data.decode("utf-8", errors="ignore")
else:
data = data.decode("utf-8")
self.update(json.loads(data))
self._fetched = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute ID, can be the name or the integer ID """ |
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
except KeyError:
attr_names = self._schema["attribute_names"]
attrdef = attrs.get(attr_names.get(str(attrid).lower()))
if not attrdef:
return None
else:
return dict(attrdef) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _quality_definition(self, qid):
""" Returns the ID and localized name of the given quality, can be either ID type """ |
qualities = self._schema["qualities"]
try:
return qualities[qid]
except KeyError:
qid = self._schema["quality_names"].get(str(qid).lower(), 0)
return qualities.get(qid, (qid, "normal", "Normal")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attributes(self):
""" Returns all attributes in the schema """ |
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def origin_id_to_name(self, origin):
""" Returns a localized origin name for a given ID """ |
try:
oid = int(origin)
except (ValueError, TypeError):
return None
return self.origins.get(oid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attributes(self):
""" Returns a list of attributes """ |
overridden_attrs = self._attributes
sortmap = {"neutral": 1, "positive": 2,
"negative": 3}
sortedattrs = list(overridden_attrs.values())
sortedattrs.sort(key=operator.itemgetter("defindex"))
sortedattrs.sort(key=lambda t: sortmap.get(t.get("effect_type",
"neutral"), 99))
return [item_attribute(theattr) for theattr in sortedattrs] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equipped(self):
""" Returns a dict of classes that have the item equipped and in what slot """ |
equipped = self._item.get("equipped", [])
# WORKAROUND: 0 is probably an off-by-one error
# WORKAROUND: 65535 actually serves a purpose (according to Valve)
return dict([(eq["class"], eq["slot"]) for eq in equipped if eq["class"] != 0 and eq["slot"] != 65535]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def equipable_classes(self):
""" Returns a list of classes that _can_ use the item. """ |
sitem = self._schema_item
return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contents(self):
""" Returns the item in the container, if there is one. This will be a standard item object. """ |
rawitem = self._item.get("contained_item")
if rawitem:
return self.__class__(rawitem, self._schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def full_name(self):
""" The full name of the item, generated depending on things such as its quality, rank, the schema language, and so on. """ |
qid, quality_str, pretty_quality_str = self.quality
custom_name = self.custom_name
item_name = self.name
english = (self._language == "en_US")
rank = self.rank
prefixed = self._schema_item.get("proper_name", False)
prefix = ''
suffix = ''
pfinal = ''
if item_name.startswith("The ") and prefixed:
item_name = item_name[4:]
if quality_str != "unique" and quality_str != "normal":
pfinal = pretty_quality_str
if english:
if prefixed:
if quality_str == "unique":
pfinal = "The"
elif quality_str == "unique":
pfinal = ''
if rank and quality_str == "strange":
pfinal = rank["name"]
if english:
prefix = pfinal
elif pfinal:
suffix = '(' + pfinal + ') ' + suffix
return (prefix + " " + item_name + " " + suffix).strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def available_styles(self):
""" Returns a list of all styles defined for the item """ |
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatted_value(self):
""" Returns a formatted value as a string""" |
# TODO: Cleanup all of this, it's just weird and unnatural maths
val = self.value
pval = val
ftype = self.value_type
if ftype == "percentage":
pval = int(round(val * 100))
if self.type == "negative":
pval = 0 - (100 - pval)
else:
pval -= 100
elif ftype == "additive_percentage":
pval = int(round(val * 100))
elif ftype == "inverted_percentage":
pval = 100 - int(round(val * 100))
# Can't remember what workaround this was, is it needed?
if self.type == "negative":
if self.value > 1:
pval = 0 - pval
elif ftype == "additive" or ftype == "particle_index" or ftype == "account_id":
if int(val) == val:
pval = int(val)
elif ftype == "date":
d = time.gmtime(int(val))
pval = time.strftime("%Y-%m-%d %H:%M:%S", d)
return u"{0}".format(pval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def account_info(self):
""" Certain attributes have a user's account information associated with it such as a gifted or crafted item. A dict with two keys: 'persona' and 'id64'. None if the attribute has no account information attached to it. """ |
account_info = self._attribute.get("account_info")
if account_info:
return {"persona": account_info.get("personaname", ""),
"id64": account_info["steamid"]}
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tags(self):
""" Returns a dict containing tags and their localized labels as values """ |
return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vanity(self):
""" Returns the user's vanity url if it exists, None otherwise """ |
purl = self.profile_url.strip('/')
if purl.find("/id/") != -1:
return os.path.basename(purl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def creation_date(self):
""" Returns the account creation date as a localtime time.struct_time struct if public""" |
timestamp = self._prof.get("timecreated")
if timestamp:
return time.localtime(timestamp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def level(self):
""" Returns the the user's profile level, note that this runs a separate request because the profile level data isn't in the standard player summary output even though it should be. Which is also why it's not implemented as a separate class. You won't need this output and not the profile output """ |
level_key = "player_level"
if level_key in self._api["response"]:
return self._api["response"][level_key]
try:
lvl = api.interface("IPlayerService").GetSteamLevel(steamid=self.id64)["response"][level_key]
self._api["response"][level_key] = lvl
return lvl
except:
return -1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_def(cls, obj):
""" Builds a profile object from a raw player summary object """ |
prof = cls(obj["steamid"])
prof._cache = obj
return prof |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_status_withheld(self, status_id, user_id, countries):
"""Called when a status is withheld""" |
logger.info('Status %s withheld for user %s', status_id, user_id)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_disconnect(self, code, stream_name, reason):
"""Called when a disconnect is received""" |
logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_error(self, status_code):
"""Called when a non-200 status code is returned""" |
logger.error('Twitter returned error code %s', status_code)
self.error = status_code
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_exception(self, exception):
"""An exception occurred in the streaming thread""" |
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self):
""" Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. """ |
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_terms:
logging.debug("Some tracking terms removed")
terms_changed = True
# any added terms?
elif self._tracking_terms_set < new_tracking_terms:
logging.debug("Some tracking terms added")
terms_changed = True
# Go ahead and store for later
self._tracking_terms_set = new_tracking_terms
# If the terms changed, we need to restart the stream
return terms_changed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_tracking_terms(self):
""" Terms must be one-per-line. Blank lines will be skipped. """ |
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set of terms
new_terms = set()
for line in lines:
line = line.strip()
if len(line):
new_terms.add(line)
return set(new_terms) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal""" |
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT""" |
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_tweepy_auth(twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret):
"""Make a tweepy auth object""" |
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token, twitter_access_token_secret)
return auth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_listener(outfile=None):
"""Create the listener that prints tweets""" |
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def begin_stream_loop(stream, poll_interval):
|
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in 1 second.", exc_info=True)
time.sleep(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(track_file, twitter_api_key, twitter_api_secret, twitter_access_token, twitter_access_token_secret, poll_interval=15, unfiltered=False, languages=None, debug=False, outfile=None):
"""Start the stream.""" |
listener = construct_listener(outfile)
checker = BasicFileTermChecker(track_file, listener)
auth = get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret)
stream = DynamicTwitterStream(auth, listener, checker, unfiltered=unfiltered, languages=languages)
set_terminate_listeners(stream)
if debug:
set_debug_listener(stream)
begin_stream_loop(stream, poll_interval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_status(self, status):
"""Print out some tweets""" |
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_status(self):
"""Print out the current tweet rate and reset the counter""" |
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / diff) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_polling(self, interval):
""" Start polling for term updates and streaming. """ |
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for changes to the track list")
while self.polling:
loop_start = time()
self.update_stream()
self.handle_exceptions()
# wait for the interval unless interrupted, compensating for time elapsed in the loop
elapsed = time() - loop_start
sleep(max(0.1, interval - elapsed))
logger.warning("Term poll ceased!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_stream(self):
""" Restarts the stream with the current list of tracking terms. """ |
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.running:
logger.warning("Stream exists but isn't running")
self.listener.error = False
self.listener.streaming_exception = None
need_to_restart = True
# Check if the tracking list has changed
if self.term_checker.check():
logger.info("Terms have changed")
need_to_restart = True
# If we aren't running and we are allowing unfiltered streams
if self.stream is None and self.unfiltered:
need_to_restart = True
if not need_to_restart:
return
logger.info("Restarting stream...")
# Stop any old stream
self.stop_stream()
# Start a new stream
self.start_stream() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_stream(self):
"""Starts a stream with teh current tracking terms""" |
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.listener,
stall_warnings=True,
timeout=90,
retry_count=self.retry_count)
if len(tracking_terms) > 0:
logger.info("Starting new twitter stream with %s terms:", len(tracking_terms))
logger.info(" %s", repr(tracking_terms))
# Launch it in a new thread
self.stream.filter(track=tracking_terms, async=True, languages=self.languages)
else:
logger.info("Starting new unfiltered stream")
self.stream.sample(async=True, languages=self.languages) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_stream(self):
""" Stops the current stream. Blocks until this is done. """ |
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
# wait a few seconds to allow the streaming to actually stop
sleep(self.STOP_TIMEOUT) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data.""" |
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=timezone.utc)
else:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y')
return tweet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag. Should be used before urlize_tweet """ |
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
text=tweet['retweeted_status']['text'])
urls = tweet['retweeted_status']['entities']['urls']
else:
text = tweet['text']
urls = tweet['entities']['urls']
for url in urls:
text = text.replace(url['url'], '<a href="%s">%s</a>' % (url['expanded_url'], url['display_url']))
tweet['html'] = text
return tweet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rabin_miller(p):
""" Performs a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime """ |
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 and p & 1 == 0:
return False
s = p - 1
while s & 1 == 0:
s >>= 1
for x in range(10):
a = random.randrange(p - 1) + 1
temp = s
mod = pow(a, temp, p)
while temp != p - 1 and mod != 1 and mod != p - 1:
mod = (mod * mod) % p
temp = temp * 2
if mod != p - 1 and temp % 2 == 0:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zero_width_split(pattern, string):
""" Split a string on a regex that only matches zero-width strings :param pattern: Regex pattern that matches zero-width strings :param string: String to split on. :return: Split array """ |
splits = list((m.start(), m.end()) for m in regex.finditer(pattern, string, regex.VERBOSE))
starts = [0] + [i[1] for i in splits]
ends = [i[0] for i in splits] + [len(string)]
return [string[start:end] for start, end in zip(starts, ends)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roll_group(group):
""" Rolls a group of dice in 2d6, 3d10, d12, etc. format :param group: String of dice group :return: Array of results """ |
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2])
assert num_of_dice > 0
result = []
for i in range(num_of_dice):
result.append(random.randint(1, type_of_dice))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def num_equal(result, operator, comparator):
""" Returns the number of elements in a list that pass a comparison :param result: The list of results of a dice roll :param operator: Operator in string to perform comparison on: Either '+', '-', or '*' :param comparator: The value to compare :return: """ |
if operator == '<':
return len([x for x in result if x < comparator])
elif operator == '>':
return len([x for x in result if x > comparator])
elif operator == '=':
return len([x for x in result if x == comparator])
else:
raise ValueError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eval(self, expr):
""" Evaluates an expression :param expr: Expression to evaluate :return: Result of expression """ |
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.parse(expr.strip()).body[0].value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eval(self, node):
""" Evaluate a node :param node: Node to eval :return: Result of node """ |
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__name__))
return handler(node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eval_num(self, node):
""" Evaluate a numerical node :param node: Node to eval :return: Result of node """ |
if self.floats:
return node.n
else:
return int(node.n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _eval_call(self, node):
""" Evaluate a function call :param node: Node to eval :return: Result of node """ |
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(self._eval(a) for a in node.args),
**dict(self._eval(k) for k in node.keywords)
)
if value is True:
return 1
elif value is False:
return 0
else:
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roll_dice(self):
# Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ |
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._last_explanation = roll[1]
return self.last_roll, self.last_explanation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def roll(self, value):
""" Setter for roll, verifies the roll is valid :param value: Roll :return: None """ |
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dice(value) # Make sure dice roll parses as a valid roll and not an error
except Exception as e:
raise ValueError('Dice roll specified was not a valid diceroll.\n%s\n' % str(e))
else:
self._roll = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checks():
""" An iterator of valid checks that are in the installed checkers package. yields check name, check module """ |
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = importlib.import_module("checkers.{0}".format(name))
# Does the module have a "run" function
if isinstance(getattr(mod, 'run', None), types.FunctionType):
# has a run method, yield it
yield getattr(mod, 'CHECK_NAME', name), mod |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files_to_check(commit_only):
""" Validate the commit diff. Make copies of the staged changes for analysis. """ |
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
yield files
finally:
shutil.rmtree(safe_directory) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(commit_only=True):
""" Run the configured code checks. Return system exit code. 1 - reject commit 0 - accept commit """ |
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod in checks():
default = getattr(mod, 'DEFAULT', 'off')
if hook_checks.is_enabled(name, default=default):
if hasattr(mod, 'REQUIRED_FILES'):
for filename in mod.REQUIRED_FILES:
if os.path.isfile(filename):
try:
shutil.copy(filename, TEMP_FOLDER)
except shutil.Error:
# Copied over by a previous check
continue
args = hook_checks.arguments(name)
tmp_files = [os.path.join(TEMP_FOLDER, f) for f in files]
if args:
errors = mod.run(tmp_files, TEMP_FOLDER, args)
else:
errors = mod.run(tmp_files, TEMP_FOLDER)
if errors:
title_print("Checking {0}".format(name))
print((errors.replace(TEMP_FOLDER + "/", '')))
print("")
exit_code = 1
if exit_code == 1:
title_print("Rejecting commit")
return exit_code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash(
"git ls-tree --name-only --full-tree -r HEAD"
).value().strip()
if real_files:
return create_fake_copies(real_files.split('\n'), copy_dest)
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_fake_copies(files, destination):
""" Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files. """ |
dest_files = []
for filename in files:
leaf_dest_folder = os.path.join(destination, os.path.dirname(filename))
if not os.path.exists(leaf_dest_folder):
os.makedirs(leaf_dest_folder)
dest_file = os.path.join(destination, filename)
bash("git show :{filename} > {dest_file}".format(
filename=filename,
dest_file=dest_file)
)
dest_files.append(os.path.realpath(dest_file))
return dest_files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if extension:
if extension == '.py':
py_files.append(f)
elif 'python' in open(f, 'r').readline():
py_files.append(f)
elif 'python script' in bash('file {}'.format(f)).value().lower():
py_files.append(f)
return py_files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configuration(self, plugin):
""" Get plugin configuration. Return a tuple of (on|off|default, args) """ |
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.