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 contribute_to_class(self, cls, name):
""" Makes sure thumbnail gets set when image field initialized. """ |
super(SizedImageField, self).contribute_to_class(cls, name)
signals.post_init.connect(self._set_thumbnail, sender=cls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_save(self, model_instance, add):
""" Resizes, commits image to storage, and returns field's value just before saving. """ |
file = getattr(model_instance, self.attname)
if file and not file._committed:
file.name = self._clean_file_name(model_instance, file.name)
file.file = self._resize_image(model_instance, file)
file.save(file.name, file, save=False)
return file |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_file_name(self, model_instance, filename):
""" We need to make sure we know the full file name before we save the thumbnail so we can be sure the name doesn't change on save. This method gets the available filename and returns just the file part. """ |
available_name = self.storage.get_available_name(
self.generate_filename(model_instance, filename))
return os.path.basename(available_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 _create_thumbnail(self, model_instance, thumbnail, image_name):
""" Resizes and saves the thumbnail image """ |
thumbnail = self._do_resize(thumbnail, self.thumbnail_size)
full_image_name = self.generate_filename(model_instance, image_name)
thumbnail_filename = _get_thumbnail_filename(full_image_name)
thumb = self._get_simple_uploaded_file(thumbnail, thumbnail_filename)
self.storage.save(thumbnail_filename, thumb) |
<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_thumbnail(self, instance=None, **kwargs):
""" Sets a `thumbnail` attribute on the image field class. On thumbnail you can access name, url, path attributes """ |
image_field = getattr(instance, self.name)
if image_field:
thumbnail_filename = _get_thumbnail_filename(image_field.name)
thumbnail_field = ThumbnailField(thumbnail_filename, self.storage)
setattr(image_field, 'thumbnail', thumbnail_field) |
<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(self, **kwargs):
"""Create a new Application. Args: **kwargs: Arbitrary keyword arguments, including: name (str):
A name for the new Application. Returns: A round.Application object if successful. """ |
resource = self.resource.create(kwargs)
if 'admin_token' in kwargs:
resource.context.authorize('Gem-Application',
api_token=resource.api_token,
admin_token=kwargs['admin_token'])
app = self.wrap(resource)
return self.add(app) |
<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_mfa(self):
"""Return the currently-valid MFA token for this application.""" |
token = str(self.totp.now())
# PyOTP doesn't pre-pad tokens shorter than 6 characters
# ROTP does, so we have to.
while len(token) < 6:
token = '0{}'.format(token)
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self, *args):
"""Resets any of the tokens for this Application. Note that you may have to reauthenticate afterwards. Usage: application.reset('api_token') application.reset('api_token', 'totp_secret') Args: *args (list of str):
one or more of ['api_token', 'subscription_token', 'totp_secret'] Returns: The Application. """ |
self.resource = self.resource.reset(list(args))
return self |
<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_users(self, fetch=True):
"""Return this Applications's users object, populating it if fetch is True.""" |
return Users(self.resource.users, self.client, populate=fetch) |
<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_wallets(self, fetch=False):
"""Return this Applications's wallets object, populating it if fetch is True.""" |
return Wallets(
self.resource.wallets, self.client, populate=fetch, application=self) |
<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_netki_domains(self, fetch=False):
"""Return the Applications NetkiDomains object, populating it if fetch is True.""" |
return NetkiDomains(
self.resource.netki_domains, self.client, populate=fetch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def os_info():
"""Returns os data. """ |
return {
'uname': dict(platform.uname()._asdict()),
'path': os.environ.get('PATH', '').split(':'),
'shell': os.environ.get('SHELL', '/bin/sh'),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def network_info():
"""Returns hostname, ipv4 and ipv6. """ |
def extract(host, family):
return socket.getaddrinfo(host, None, family)[0][4][0]
host = socket.gethostname()
response = {
'hostname': host,
'ipv4': None,
'ipv6': None
}
with suppress(IndexError, socket.gaierror):
response['ipv4'] = extract(host, socket.AF_INET)
with suppress(IndexError, socket.gaierror):
response['ipv6'] = extract(host, socket.AF_INET6)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mac_addr_info():
"""Returns mac address. """ |
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2))
else:
value = None
return {'mac': 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 interfaces_info():
"""Returns interfaces data. """ |
def replace(value):
if value == netifaces.AF_LINK:
return 'link'
if value == netifaces.AF_INET:
return 'ipv4'
if value == netifaces.AF_INET6:
return 'ipv6'
return value
results = {}
for iface in netifaces.interfaces():
addrs = netifaces.ifaddresses(iface)
results[iface] = {replace(k): v for k, v in addrs.items()}
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gateways_info():
"""Returns gateways data. """ |
data = netifaces.gateways()
results = {'default': {}}
with suppress(KeyError):
results['ipv4'] = data[netifaces.AF_INET]
results['default']['ipv4'] = data['default'][netifaces.AF_INET]
with suppress(KeyError):
results['ipv6'] = data[netifaces.AF_INET6]
results['default']['ipv6'] = data['default'][netifaces.AF_INET6]
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def memory_data():
"""Returns memory data. """ |
vm = psutil.virtual_memory()
sw = psutil.swap_memory()
return {
'virtual': {
'total': mark(vm.total, 'bytes'),
'free': mark(vm.free, 'bytes'),
'percent': mark(vm.percent, 'percentage')
},
'swap': {
'total': mark(sw.total, 'bytes'),
'free': mark(sw.free, 'bytes'),
'percent': mark(sw.percent, 'percentage')
},
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def devices_data():
"""Returns devices data. """ |
response = {}
for part in psutil.disk_partitions():
device = part.device
response[device] = {
'device': device,
'mountpoint': part.mountpoint,
'fstype': part.fstype,
'opts': part.opts,
}
if part.mountpoint:
usage = psutil.disk_usage(part.mountpoint)
response[device]['usage'] = {
'size': mark(usage.total, 'bytes'),
'used': mark(usage.used, 'bytes'),
'free': mark(usage.free, 'bytes'),
'percent': mark(usage.percent, 'percentage')
}
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def integrator(integrand,xmin,xmax,n_points,factor=2):
'''
Creating theoretical curve for 2D model functions
integrator function
'''
integral_vector = np.empty([n_points+1])
dx = (xmax-xmin)/n_points
# integrate
for i in xrange(n_points+1):
xnow = xmin + i * dx
integral, error = integrate.quad(rotate(integrand,
xnow), xmin*factor, xmax*factor)
integral_vector[i] = integral
# normalize
normalization = np.average(integral_vector)*(xmax-xmin)
normalized_vector = integral_vector/normalization
return normalized_vector |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rotate(f,x,theta=0):
'''
Returns a function that takes as input the 1D vector along the angle
given a function that takes in 2D input
'''
f_R = lambda b: f(np.array([[x*np.cos(theta)-b*np.sin(theta)],
[x*np.sin(theta)+b*np.cos(theta)]]))
return f_R |
<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_failed_login(self):
""" 'Private method', check failed logins, it's used for wath_login decorator """ |
last_attempt = self.get_last_failed_access_attempt()
if not last_attempt:
# create a new entry
user_access = self._FailedAccessAttemptModel(ip_address=self.ip)
elif last_attempt:
user_access = last_attempt
if self.request.method == 'POST':
if self.username is None:
raise DobermanImproperlyConfigured(
"Bad username form field, if you are using a custom field please configure: "
"DOBERMAN_USERNAME_FORM_FIELD via settings."
)
if self.response.status_code != 302:
user_access.user_agent = self.request.META.get('HTTP_USER_AGENT', '<unknown user agent>')[:255]
user_access.username = self.username
user_access.failed_attempts += 1
user_access.params_get = self.request.GET
user_access.params_post = self.request.POST
if user_access.failed_attempts >= self.max_failed_attempts:
user_access.is_locked = True
user_access.save()
elif self.response.status_code == 302 and not user_access.is_locked:
user_access.is_expired = True
user_access.save()
return user_access |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optional_data_directories(self):
""" Data directories entries are somewhat wierd. First of all they have no direct type information in it, the type is assumed from the position inside the table. For this reason there are often "null" entries, with all fields set to zero. Here we parse all the entries, assign the correct type via position and then filter out the "null" ones. Even if the algorithm itself if quite simple, figuring it required a huge amount of time staring at PE/COFF specification with a 8O like expression thinking "WTF? WTF! WTF? WHY?!" """ |
base_offset = self.pe_header_offset +\
COFF_Header.get_size() +\
OptionalHeader_StandardFields.get_size() +\
OptionalHeader_WindowsFields.get_size()
for i in range(0, self.optional_windows_fields.NumberOfRvaAndSizes):
offset = base_offset + i*OptionalHeader_DataDirectory.get_size()
header = OptionalHeader_DataDirectory(self.stream, offset, i)
if not header.is_empty():
yield header |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_rva(self, rva):
""" RVAs are supposed to be used with the image of the file in memory. There's no direct algorithm to calculate the offset of an RVA in the file. What we do here is to find the section that contains the RVA and then we calculate the offset between the RVA of the section and the offset of the section in the file. With this offset, we can compute the position of the RVA in the file """ |
containing_section = self.get_section_of_rva(rva)
in_section_offset = containing_section.PointerToRawData -\
containing_section.VirtualAddress
return in_section_offset + rva |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dir_import_table(self):
""" import table is terminated by a all-null entry, so we have to check for that """ |
import_header = list(self.optional_data_directories)[1]
import_offset = self.resolve_rva(import_header.VirtualAddress)
i = 0
while True:
offset = import_offset + i*Import_DirectoryTable.get_size()
idt = Import_DirectoryTable(self.stream, offset, self)
if idt.is_empty():
break
else:
yield idt
i += 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 get_number(message, limit=4):
""" convert Chinese to pinyin and extract useful numbers attention: 1. only for integer 2. before apply this method, the message should be preprocessed input: message: the message you want to extract numbers from. limit: limit the length of number sequence """ |
words = pinyin.get_pinyin(message).split('-')
numbers = []
tmp = ''
count = 0
for w in words:
if re.search(r'\W', w, re.A):
for s in list(w):
if s in special_char.keys():
count += 1
tmp += special_char[s]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
elif w in pinyin2number.keys():
count += 1
tmp += pinyin2number[w]
else:
if count >= limit:
numbers.append(tmp)
count = 0
tmp = ''
if count >= limit:
numbers.append(tmp)
return numbers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def evalMetric(self, x, method=None):
'''Evaluates the density matching metric at a given design point.
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: metric_value - value of the metric evaluated at the design
point given by x
:rtype: float
*Example Usage*::
>>> def myFunc(x, u): return x[0]*x[1] + u
>>> u1 = UniformParameter()
>>> theDM = DensityMatching(myFunc, u)
>>> x0 = [1, 2]
>>> theDM.evalMetric(x0)
'''
return super(DensityMatching, self).evalMetric(x, method) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getPDF(self):
'''Function that gets vectors of the pdf and target at the last design
evaluated.
:return: tuple of q values, pdf values, target values
'''
if hasattr(self, '_qplot'):
return self._qplot, self._hplot, self._tplot
else:
raise ValueError('''The metric has not been evaluated at any
design point so the PDF cannot get obtained''') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def errorBand(x, yAvg, yStd, yDensity, plt, n_colors=None):
""" plot error-band around avg where colour equals to point density """ |
dmn = yDensity.min()
dmx = yDensity.max()
if n_colors is None:
n_colors = dmx - dmn + 1
print(n_colors)
cm = plt.cm.get_cmap('Blues', lut=n_colors)
# normalize (0...1):
relDensity = (yDensity - dmn) / (dmx - dmn)
# limit the number of densities to n_colors:
bins = np.linspace(0, 1, n_colors - 1)
inds = np.digitize(relDensity, bins)
i0 = 0
try:
while True:
# define area length as those of the same alpha value
v0 = inds[i0]
am = np.argmax(inds[i0:] != v0)
if am == 0:
i1 = len(inds)
else:
i1 = i0 + am
r = slice(i0, i1 + 1)
col = cm(v0)
# create polygon of color=density around average:
plt.fill_between(x[r], yAvg[r] - yStd[r], yAvg[r] + yStd[r],
alpha=1,
edgecolor=col, # '#3F7F4C',
facecolor=col, # '#7EFF99',
linewidth=1)
i0 = i1
except IndexError:
pass
plt.plot(x, yAvg, 'k', color='#3F7F4C')
# show colorbar in plot:
sm = plt.cm.ScalarMappable(cmap=cm, norm=plt.Normalize(vmin=dmn, vmax=dmx))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
plt.colorbar(sm)
plt.legend() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPage(url, contextFactory=None, *args, **kwargs):
"""Download a web page as a string. Download a page. Return a deferred, which will callback with a page (as a string) or errback with a description of the error. See HTTPClientFactory to see what extra args can be passed. """ |
scheme, host, port, path = client._parse(url)
factory = client.HTTPClientFactory(url, *args, **kwargs)
if scheme == 'https':
if contextFactory is None:
raise RuntimeError, 'must provide a contextFactory'
conn = reactor.connectSSL(host, port, factory, contextFactory)
else:
conn = reactor.connectTCP(host, port, factory)
return factory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Send(self, url, opname, pyobj, nsdict={}, soapaction=None, chain=None, **kw):
"""Returns a ProcessingChain which needs to be passed to Receive if Send is being called consecutively. """ |
url = url or self.url
cookies = None
if chain is not None:
cookies = chain.flow.cookies
d = {}
d.update(self.nsdict)
d.update(nsdict)
if soapaction is not None:
self.addHTTPHeader('SOAPAction', soapaction)
chain = self.factory.newInstance()
soapdata = chain.processRequest(pyobj, nsdict=nsdict,
soapaction=soapaction, **kw)
if self.trace:
print >>self.trace, "_" * 33, time.ctime(time.time()), "REQUEST:"
print >>self.trace, soapdata
f = getPage(str(url), contextFactory=self.contextFactory,
postdata=soapdata, agent=self.agent,
method='POST', headers=self.getHTTPHeaders(),
cookies=cookies)
if isinstance(f, Failure):
return f
chain.flow = f
self.chain = chain
return chain |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stream_array(self, generator):
'''Helper function to stream content as an array of JSON values.'''
def chunkify(generator):
log.debug('Data Stream STARTED')
yield '['.encode()
# In order to have commas only after the first value, we take the
# first value of the generator manually
try:
yield jsonify(next(generator)).encode()
except StopIteration:
pass
while True:
try:
bit = next(generator)
except StopIteration:
yield ']'.encode()
break
else:
yield ',\n'.encode()
yield jsonify(bit).encode()
log.debug('Data Stream ENDED')
return chunkify(generator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process_500(self, request, exception):
'''Internal server error.'''
id_ = str(uuid.uuid4())[:6].upper()
msg = 'Internal server error: 500. Unique error identifier is {}'
msg = msg.format(id_)
log.error('HTTP 500 [Message - {}]: {}'.format(id_, msg))
log.error('HTTP 500 [Arguments - {}]: {}'.format(id_, request.args))
log.exception('HTTP 500 [Traceback - {}]:'.format(id_))
return msg |
<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(self, name, network):
"""Create a new Account object and add it to this Accounts collection. Args: name (str):
Account name network (str):
Type of cryptocurrency. Can be one of, 'bitcoin', ' bitcoin_testnet', 'litecoin', 'dogecoin'. Returns: The new round.Account """ |
if not network in SUPPORTED_NETWORKS:
raise ValueError('Network not valid!')
account = self.wrap(self.resource.create(dict(name=name,
network=network)))
self.add(account)
return account |
<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(self, **kwargs):
"""Update the Account resource with specified content. Args: name (str):
Human-readable name for the account Returns: the updated Account object. """ |
return self.__class__(self.resource.update(kwargs),
self.client,
wallet=self.wallet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pay(self, payees, change_account=None, utxo_confirmations=6, mfa_token=None, redirect_uri=None):
"""Create, verify, and sign a new Transaction. If this Account is owned by a User object, the user must be redirected to a URL (`mfa_uri`) returned by this call to input their MFA token. After they complete that step, the Transaction will be approved and published to the bitcoin network. If a `redirect_uri` is provided in this call, the user will be redirected to that uri after they complete the MFA challenge so it's a good idea to have an endpoint in your app (or custom scheme on mobile) that can provide the user a seamless flow for returning to your application. If they have not configured a TOTP MFA application (e.g. Google Authenticator), then an SMS will be sent to their phone number with their token. If this Account is owned by an Application, the `mfa_token` can be included in this call and the Transaction will be automatically approved and published to the blockchain. Args: payees (list of dict):
list of outputs in the form: [{'amount': 10000(satoshis), change_account (str or Account):
if supplied, this account will be used to generate a change address in the event that a change output is required. This account must be owned by the same Wallet. utxo_confirmations (int, optional):
Required confirmations for UTXO selection ( > 0) mfa_token (str/function, optional):
TOTP token for the Application owning this Account's wallet OR a callable/function which will generate such a token. The latter is suggested (e.g. application.get_mfa) as otherwise, the token might be invalidated by the time tx.create and tx.update complete (before the tx.approve call which actually requires the mfa_token). redirect_uri (str, optional):
URI to redirect a user to after they input an mfa token on the page referenced by the `mfa_uri` returned by this function. Returns: An "unapproved" Transaction with an `mfa_uri` attribute to route the user to the MFA confirmation page -- if called with Gem-Device authentication. An "unconfirmed" Transaction -- if called with Gem-Application auth (and an `mfa_token` was supplied). """ |
# Check that wallet is unlocked
if self.wallet.is_locked():
raise DecryptionError("This wallet must be unlocked with "
"wallet.unlock(passphrase)")
# First create the unsigned tx.
content = dict(payees=payees,
utxo_confirmations=utxo_confirmations,
remainder_account=self.resource.attributes['key'],
network=self.network)
if change_account: content['change_account'] = \
self.wallet._get_account_attr(change_account)
try:
unsigned = self.resource.transactions().create(content)
except ResponseError as e:
if "cannot cover" in e.message:
raise BalanceError(e.message)
raise e
# Sign the tx with the primary private key.
coinoptx = CoinopTx(data=unsigned.attributes)
signatures = self.wallet.signatures(coinoptx)
# Update the tx with the signatures.
transaction = dict(signatures=dict(inputs=signatures,
transaction_hash=coinoptx.hash))
if redirect_uri:
transaction['redirect_uri'] = redirect_uri
signed = Transaction(unsigned.update(transaction), self.client)
# If this is an Application wallet, approve the transaction.
if mfa_token and self.wallet.application:
try:
return Transaction(signed.with_mfa(mfa_token).approve(),
self.client)
except Exception as e:
signed = signed.cancel()
logger.debug(e.message)
logger.debug("If you are having trouble with MFA tokens, make "
"sure your system time is accurate with `date -u`!")
# Otherwise return the unapproved tx (now redirect the user to the
# `mfa_uri` attribute to approve!)
return signed |
<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_addresses(self, fetch=False):
"""Return the Account's addresses object, populating it if fetch is True.""" |
return Addresses(self.resource.addresses, self.client, populate=fetch) |
<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_netki_names(self, fetch=False):
"""Return the Account's NetkiNames object, populating it if fetch is True.""" |
return NetkiNames(self.resource.netki_names, self.client, populate=fetch) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate_html(html, *args, **kwargs):
"""Truncates HTML string. :param html: The HTML string or parsed element tree (with :func:`html5lib.parse`). :param kwargs: Similar with :class:`.filters.TruncationFilter`. :return: The truncated HTML string. """ |
if hasattr(html, 'getchildren'):
etree = html
else:
etree = html5lib.parse(html)
walker = html5lib.getTreeWalker('etree')
stream = walker(etree)
stream = TruncationFilter(stream, *args, **kwargs)
serializer = html5lib.serializer.HTMLSerializer()
serialized = serializer.serialize(stream)
return u''.join(serialized).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 is_allowed(func):
"""Check user password, when is correct, then run decorated function. :returns: decorated function """ |
@wraps(func)
def _is_allowed(user, *args, **kwargs):
password = kwargs.pop('password', None)
if user.check_password(password):
return func(user, *args, **kwargs)
else:
raise NotAllowedError()
# add password parameter to function signature
sig = inspect.signature(func)
parms = list(sig.parameters.values())
parms.append(inspect.Parameter('password',
inspect.Parameter.KEYWORD_ONLY,
default=None))
_is_allowed.__signature__ = sig.replace(parameters=parms)
return _is_allowed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_get(self, args):
'''Get labels directly connected to a content item.'''
for label in self.label_store.directly_connected(args.content_id):
if args.value is None or label.value.value == args.value:
self.stdout.write('{0}\n'.format(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 do_connected(self, args):
'''Find a connected component from positive labels on an item.'''
connected = self.label_store.connected_component(args.content_id)
for label in connected:
self.stdout.write('{0}\n'.format(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 wait(self):
"""Waits for all submitted jobs to complete.""" |
logging.info("waiting for {} jobs to complete".format(len(self.submissions)))
while not self.shutdown:
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 download_dropped_files(self, sha256, environment_id, target_dir):
"""Downloads the dropped files for this sample into target_dir. Returns the list of files extracted.""" |
download_url = '{}/api/sample-dropped-files/{}?environmentId={}&apikey={}&secret={}'.format(
self.url,
sha256,
environment_id,
self.api_key,
self.secret)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
logging.info("downloading dropped files from {}".format(download_url))
result = requests.get(download_url, verify=False, headers=VXSTREAM_HEADERS, proxies=self.proxies) # XXX
if result.status_code != 200:
logging.error("got result {} from vxstream for {}: {}".format(result.status_code, download_url, result.reason))
return None
# put what we download into a temporary directory
temp_dir = tempfile.mkdtemp()
try:
# all dropped files come in a zip file
compressed_path = os.path.join(temp_dir, 'download.zip')
# write zip file to disk
with open(compressed_path, 'wb') as fp:
for block in result.iter_content(io.DEFAULT_BUFFER_SIZE):
fp.write(block)
# unzip without paths
p = Popen(['7z', 'e', '-y', '-o{}'.format(target_dir), compressed_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
try:
os.remove(compressed_path)
except Exception as e:
logging.error("unable to delete {}: {}".format(compressed_path, e))
# list gz files in drop_path
file_list = [os.path.join(target_dir, f) for f in os.listdir(target_dir) if f.endswith('.gz')]
result = []
for compressed_path in file_list:
# there are some other files in here sometimes that we'll ignore
# we just want the dropped file
if '.DROPPED.' not in compressed_path:
continue
DROPPED_FILE_REGEX = re.compile(r'^(.+?)\.[0-9]+\.DROPPED\.gz')
# the file paths look like this
# dropped/78QC7UOHAWCI47906LWH.temp.4212842214.DROPPED.gZ
m = DROPPED_FILE_REGEX.match(os.path.basename(compressed_path))
if not m:
logging.error("could not extract file name from {}".format(compressed_path))
continue
target_path = os.path.join(target_dir, m.group(1))
result.append(target_path)
with gzip.open(compressed_path) as fp:
logging.debug("decompressing {}".format(compressed_path))
with open(target_path, 'wb') as dest_fp:
while True:
data = fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
dest_fp.write(data)
os.remove(compressed_path)
return result
finally:
try:
if temp_dir:
shutil.rmtree(temp_dir)
except Exception as e:
logging.error("unable to delete temporary directory {}: {}".format(temp_dir, e)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_memory_dump(self, sha256, environment_id, dest_dir):
"""Downloads the given memory dump into the given directory. Returns a tuple of a list of files extracted from what was downloaded, and the path to the combined memory dump.""" |
dest_path = os.path.join(dest_dir, 'memory.zip')
if self.download(sha256, environment_id, VXSTREAM_DOWNLOAD_MEMORY, dest_path) is None:
return None
with open(dest_path, 'rb') as fp:
blob = fp.read(1024)
if b'No dump files available' in blob:
logging.debug("memory dump not available for {} env {}".format(sha256, environment_id))
return None
logging.debug("extracting memory dump {} into {}".format(dest_path, dest_dir))
p = Popen(['7z', 'x', '-y', '-o{}'.format(dest_dir), dest_path], stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
file_list = []
for file_path in [os.path.join(dest_dir, f) for f in os.listdir(dest_dir) if f != "memory.zip"]:
file_list.append(file_path)
# concatenate all these files into one file
dest_path = os.path.join(dest_dir, 'memory.combined.mdmp')
for file_path in file_list:
logging.debug("concatenating {}".format(file_path))
with open(file_path, 'rb') as input_fp:
with open(dest_path, 'ab') as output_fp:
while True:
data = input_fp.read(io.DEFAULT_BUFFER_SIZE)
if data == b'':
break
output_fp.write(data)
return file_list, dest_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 data(self):
'''email content for this message'''
# return data after any initial offset, plus content offset to
# skip header, up to the size of this message
return self.mmap[self.content_offset + self._offset: self._offset + self.size] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self, props=None, value=None):
""" Copy the Overlay possibly overriding props. """ |
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.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 match(self, props=None, rng=None, offset=None):
""" Provide any of the args and match or dont. :param props: Should be a subset of my props. :param rng: Exactly match my range. :param offset: I start after this offset. :returns: True if all the provided predicates match or are None """ |
if rng:
s, e = rng
else:
e = s = None
return ((e is None or self.end == e) and
(s is None or self.start == s)) and \
(props is None or props.issubset(self.props)) and \
(offset is None or self.start >= offset) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overlays_at(self, key):
""" Key may be a slice or a point. """ |
if isinstance(key, slice):
s, e, _ = key.indices(len(self.text))
else:
s = e = key
return [o for o in self.overlays if o.start in Rng(s, e)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def overlay(self, matchers, force=False):
""" Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c """ |
for m in matchers:
if m in self._ran_matchers:
continue
self._ran_matchers.append(m)
self.overlays += list(m.offset_overlays(self))
self.overlays.sort(key=lambda o: o.start, reverse=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 evil(expr, lookup, operators, cast, reducer, tokenizer):
"""evil evaluates an expression according to the eval description given. :param expr: An expression to evaluate. :param lookup: A callable which takes a single pattern argument and returns a set of results. The pattern can be anything that is not an operator token or round brackets. :param operators: A precedence-ordered dictionary of (function, side) tuples keyed on the operator token. :param reducer: A callable which takes a sequential list of values (from operations or lookups) and combines them into a result. Typical behaviour is that of the + operator. The return type should be the same as cast. :param cast: A callable which transforms the results of the lookup into the type expected by the operators and the type of the result. :param tokenizer: A callable which will break the query into tokens for evaluation per the lookup and operators. Defaults to setquery.query_tokenizer. :raises: SyntaxError :returns: """ |
operators = OrderedDict((op[0], op[1:]) for op in operators)
if "(" in operators or ")" in operators:
raise ValueError("( and ) are reserved operators")
operator_tokens = ["(", ")"] + operators.keys()
tokens = iter(tokenizer(expr, operator_tokens))
levels = [[]]
while True:
# Token evaluation and pattern lookups
expr = levels.pop() # The currently-constructed expression
new_level = False # We should step into a subexpression
first_token = len(expr) == 0 # The first (sub)exp. token
prev_op_side = None # The side of the last-seen operator
try:
# Try to get the side of the last operator from an expression
# which we are going to continue constructing.
prev_op_side = operators[expr[-1]][1]
except:
pass
for token in tokens:
if token == "(":
new_level = True
break
elif token == ")":
break
elif token in operators:
op_side = operators[token][1]
if first_token and op_side & OP_LEFT:
raise SyntaxError("Operators which act on expressions to "
"their left or both sides cannot be at "
"the beginning of an expression.")
if prev_op_side is not None:
if prev_op_side & OP_RIGHT and op_side & OP_LEFT:
raise SyntaxError("Operators cannot be beside one "
"another if they act on expressions "
"facing one-another.")
expr.append(token)
prev_op_side = op_side
continue
else:
expr.append(cast(lookup(token)))
prev_op_side = None
first_token = False
if new_level:
levels.append(expr)
levels.append([])
continue
elif prev_op_side is not None and prev_op_side & OP_RIGHT:
raise SyntaxError("Operators which act on expressions to their "
"right or both sides cannot be at the end of "
"an expression.")
# Operator evaluation
explen = len(expr)
for op, (op_eval, op_side) in operators.iteritems():
if op_side is OP_RIGHT:
# Apply right-sided operators. We loop from the end backward so
# that multiple such operators next to noe another are resolved
# in the correct order
t = explen - 1
while t >= 0:
if expr[t] == op:
expr[t] = op_eval(expr[t + 1])
del expr[t + 1]
explen -= 1
t -= 1
else:
# Apply left- and both-sided operators. We loop forward so that
# that multiple such operators next to one another are resolved
# in the correct order.
t = 0
while t < explen:
if expr[t] == op:
# Apply left- or both-sided operators
if op_side is OP_LEFT:
expr[t] = op_eval(expr[t - 1])
del expr[t - 1]
t -= 1
explen -= 1
elif op_side is OP_BOTH:
expr[t] = op_eval(expr[t - 1], expr[t + 1])
del expr[t + 1], expr[t - 1]
t -= 1
explen -= 2
t += 1
if len(levels) > 0:
levels[-1].append(reducer(expr))
else:
break
return reducer(expr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def op(token, func, left=False, right=False):
"""op provides a more verbose syntax for declaring operators. :param token: The string token of the operator. Usually a single character. :param func: A callable used to evaluate its arguments. Where the operator is both-sided the callable should accept two arguments. Where it is one-sided it should accept one argument. :param left: A boolean indicating whether the operator applies to the expression to the left of it. :param right: A boolean indicating whether the operator applies to the expression to the right of it. :returns: a tuple (token, func, side) where side is OP_BOTH if left and right (or neither) and OP_LEFT if left, otherwise OP_RIGHT. """ |
both = (left == right)
return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def globlookup(pattern, root):
"""globlookup finds filesystem objects whose relative path matches the given pattern. :param pattern: The pattern to wish to match relative filepaths to. :param root: The root director to search within. """ |
for subdir, dirnames, filenames in os.walk(root):
d = subdir[len(root) + 1:]
files = (os.path.join(d, f) for f in filenames)
for f in fnmatch.filter(files, pattern):
yield 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 on_get(self, req, resp, rid, related):
""" Find the related model & serialize it back If the parent resource of the related model doesn't exist then abort on a 404. """ |
signals.pre_req.send(self.model)
signals.pre_req_find.send(self.model)
if not hasattr(self.model, related):
abort(InvalidURL(**{
'detail': 'The "%s" resource does not have a related '
'resource named "%s". This is an error, check '
'your spelling & retry.' % (self.rtype, related)
}))
model = find(self.model, rid)
try:
model_related = getattr(model, related).load()
except AttributeError:
model_related = None
if isinstance(model_related, list):
props = to_rest_models(model_related, includes=req.includes)
elif model:
props = to_rest_model(model_related, includes=req.includes)
else:
props = model_related
resp.serialize(props)
signals.post_req.send(self.model)
signals.post_req_find.send(self.model) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recv_data(self):
""" Grab the next frame and put it on the matrix. """ |
data, addr = self.sock.recvfrom(self.packetsize)
matrix = map(ord, data.strip())
if len(matrix) == self.packetsize:
self.matrix = matrix[:-4] |
<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(self):
""" Generate the output from the matrix. """ |
pixels = len(self.matrix)
for x in range(self.width):
for y in range(self.height):
pixel = y * self.width * 3 + x * 3
#TODO: sometimes the matrix is not as big as it should
if pixel < pixels:
pygame.draw.circle(self.screen,
(self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]),
(x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 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 gameloop(self):
""" Loop through all the necessary stuff and end execution when Ctrl+C was hit. """ |
try:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
self.recv_data()
self.update()
self.render()
except KeyboardInterrupt:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getname(obj):
""" Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj`` """ |
for name_attribute in ('__qualname__', '__name__'):
try:
# an object always has a class, as per Python data model
return getattr(obj, name_attribute, getattr(obj.__class__, name_attribute))
except AttributeError:
pass
raise TypeError('object of type %r does not define a canonical name' % type(obj)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wraplet(cls, *cls_args, **cls_kwargs):
""" Create a factory to produce a Wrapper from a slave factory :param cls_args: positional arguments to provide to the Wrapper class :param cls_kwargs: keyword arguments to provide to the Wrapper class :return: .. code:: python cls_wrapper_factory = cls.wraplet(*cls_args, **cls_kwargs) link_factory = cls_wrapper_factory(slave_factory) slave_link = link_factory(*slave_args, **slave_kwargs) """ |
if cls.__init_slave__ in (None, WrapperMixin.__init_slave__):
raise TypeError('type %r does not implement the wraplet protocol' % getname(cls))
def wrapper_factory(slave_factory):
"""Factory to create a new class by wrapping ``slave_factory``"""
class Wraplet(cls): # pylint:disable=abstract-method
_slave_factory = staticmethod(slave_factory)
# Assign the wrapped attributes directly instead of
# using functools.wraps, as we may deal with arbitrarry
# class/callable combinations.
__doc__ = slave_factory.__doc__
# While the wrapped instance wraps the slave, the
# wrapper class wraps the slave factory. Any instance
# then just hides the class level attribute.
# Exposing __wrapped__ here allows introspection,such
# as inspect.signature, to pick up metadata.
__wrapped__ = slave_factory
# In Py3.X, objects without any annotations just provide an
# empty dict.
__annotations__ = getattr(slave_factory, '__annotations__', {})
def __init__(self, *slave_args, **slave_kwargs):
slave = self.__init_slave__(self._slave_factory, *slave_args, **slave_kwargs)
super(Wraplet, self).__init__(slave, *cls_args, **cls_kwargs)
__repr__ = cls.__wraplet_repr__
# swap places with our target so that both can be pickled/unpickled
Wraplet.__name__ = getname(slave_factory).split('.')[-1]
Wraplet.__qualname__ = getname(slave_factory)
Wraplet.__module__ = slave_factory.__module__
# this is enough for Py3.4+ to find the slave
slave_factory.__qualname__ = Wraplet.__qualname__ + '._slave_factory'
# ## This is an EVIL hack! Do not use use this at home unless you understand it! ##
# enable python2 lookup of the slave via its wrapper
# This allows to implicitly pickle slave objects which already support pickle,
# e.g. function and partial.
# python2 pickle performs the equivalent of getattr(sys.modules[obj.__module__, obj.__name__]
# which does not allow dotted name lookups. To work around this, we place the slave into the
# module, globally, using the qualified name *explicitly*. As qualified names are not valid identifiers,
# this will not create a collision unless someone tries to do the same trick.
if sys.version_info[:2] <= (3, 4):
# While 3.4 adds support for using __qualname__, that is *only* for protocol 4. Older
# protocols still require __name__. However, 3.4 *explicitly* disallows using dotted names,
# which defeats the obvious way of injecting the proper dotted name. Instead, an illegal name
# using : in place of . is used, which should also not conflict.
name_separator = '.' if sys.version_info[:2] != (3, 4) else ':'
# Make sure we actually register the correct entity
# Since we are only working with __name__, the slave could be defined
# in an inner scope. In this case, registering it in the global namespace
# may increase its lifetime, or replace an actual global slave of the
# same name.
# There are two cases we have to check here:
# slave = wraplet(slave)
# The slave already exists in the module namespace, with its __name__.
# The object with that name must be *identical* to the slave.
# @wraplet\ndef slave
# Neither slave nor Wrapper exist in the namespace yet (they are only bound *after*
# the wraplet returns). No object may exist with the same name.
if getattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory) is slave_factory:
slave_factory.__name__ += name_separator + '_slave_factory'
setattr(sys.modules[slave_factory.__module__], slave_factory.__name__, slave_factory)
return Wraplet
return wrapper_factory |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self, request):
""" Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `None`. """ |
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'basic':
return None
if len(auth) == 1:
msg = _('Invalid basic header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid basic header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
except (TypeError, UnicodeDecodeError):
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
raise exceptions.AuthenticationFailed(msg)
userid, password = auth_parts[0], auth_parts[2]
return self.authenticate_credentials(userid, password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate_credentials(self, userid, password):
""" Authenticate the userid and password against username and password. """ |
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password.'))
if not user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
return (user, 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 enforce_csrf(self, request):
""" Enforce CSRF validation for session based authentication. """ |
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) |
<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_enum(pred, enum):
""" Create a new enumeration containing only items filtered from another enumeration. Hidden enum items in the original enumeration are excluded. :type pred: ``Callable[[`EnumItem`], bool]`` :param pred: Predicate that will keep items for which the result is true. :type enum: Enum :param enum: Enumeration to filter. :rtype: Enum :return: New filtered enumeration. """ |
def _items():
for item in enum:
yield EnumItem(
item.value,
item.desc,
not pred(item),
**item._extra)
return Enum('Filtered from {!r}'.format(enum), list(_items())) |
<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_pairs(cls, doc, pairs):
""" Construct an enumeration from an iterable of pairs. :param doc: See `Enum.__init__`. :type pairs: ``Iterable[Tuple[unicode, unicode]]`` :param pairs: Iterable to construct the enumeration from. :rtype: Enum """ |
values = (EnumItem(value, desc) for value, desc in pairs)
return cls(doc=doc, values=values) |
<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, value):
""" Get an enumeration item for an enumeration value. :param unicode value: Enumeration value. :raise InvalidEnumItem: If ``value`` does not match any known enumeration value. :rtype: EnumItem """ |
_nothing = object()
item = self._values.get(value, _nothing)
if item is _nothing:
raise InvalidEnumItem(value)
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extra(self, value, extra_name, default=None):
""" Get the additional enumeration value for ``extra_name``. :param unicode value: Enumeration value. :param str extra_name: Extra name. :param default: Default value in the case ``extra_name`` doesn't exist. """ |
try:
return self.get(value).get(extra_name, default)
except InvalidEnumItem:
return default |
<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_all(self, **names):
""" Find all items with matching extra values. :param \*\*names: Extra values to match. :rtype: ``Iterable[`EnumItem`]`` """ |
values = names.items()
if len(values) != 1:
raise ValueError('Only one query is allowed at a time')
name, value = values[0]
for item in self:
if item.get(name) == value:
yield item |
<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_args(cmd_args):
"""split command args to args list returns a list of args :param cmd_args: command args, can be tuple, list or str """ |
if isinstance(cmd_args, (tuple, list)):
args_list = list(cmd_args)
else:
args_list = shlex.split(cmd_args)
return args_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 get_service(station: str) -> Service: """ Returns the preferred service for a given station """ |
for prefix in PREFERRED:
if station.startswith(prefix):
return PREFERRED[prefix] # type: ignore
return NOAA |
<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_err(self, body: str, key: str = 'report path') -> InvalidRequest: """ Returns an InvalidRequest exception with formatted error message """ |
msg = f'Could not find {key} in {self.__class__.__name__} response\n'
return InvalidRequest(msg + body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self, station: str) -> str: """ Fetches a report string from the service """ |
valid_station(station)
try:
resp = getattr(requests, self.method.lower())(self.url.format(self.rtype, station))
if resp.status_code != 200:
raise SourceError(f'{self.__class__.__name__} server returned {resp.status_code}')
except requests.exceptions.ConnectionError:
raise ConnectionError(f'Unable to connect to {self.__class__.__name__} server')
report = self._extract(resp.text, station)
# This split join replaces all *whitespace elements with a single space
return ' '.join(report.split()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract(self, raw: str, station: str = None) -> str: """ Extracts the raw_report element from XML response """ |
resp = parsexml(raw)
try:
report = resp['response']['data'][self.rtype.upper()]
except KeyError:
raise self.make_err(raw)
# Find report string
if isinstance(report, dict):
report = report['raw_text']
elif isinstance(report, list) and report:
report = report[0]['raw_text']
else:
raise self.make_err(raw, '"raw_text"')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
return report |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract(self, raw: str, station: str = None) -> str: """ Extracts the report message from XML response """ |
resp = parsexml(raw)
try:
report = resp['response']['body']['items']['item'][self.rtype.lower() + 'Msg']
except KeyError:
raise self.make_err(raw)
# Replace line breaks
report = report.replace('\n', '')
# Remove excess leading and trailing data
for item in (self.rtype.upper(), 'SPECI'):
if report.startswith(item + ' '):
report = report[len(item) + 1:]
report = report.rstrip('=')
# Make every element single-spaced and stripped
return ' '.join(report.split()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract(self, raw: str, station: str) -> str: # type: ignore """ Extracts the reports message using string finding """ |
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report |
<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_weather_from_metar( metar: typing.Union[Metar.Metar, str], in_file: typing.Union[str, Path], out_file: typing.Union[str, Path] = None ) -> typing.Tuple[typing.Union[str, None], typing.Union[str, None]]: """ Applies the weather from a METAR object to a MIZ file Args: metar: metar object in_file: path to MIZ file out_file: path to output MIZ file (will default to in_file) Returns: tuple of error, success """ |
error, metar = custom_metar.CustomMetar.get_metar(metar)
if error:
return error, None
if metar:
LOGGER.debug('METAR: %s', metar.code)
in_file = elib.path.ensure_file(in_file)
if out_file is None:
out_file = in_file
else:
out_file = elib.path.ensure_file(out_file, must_exist=False)
LOGGER.debug('applying metar: %s -> %s', in_file, out_file)
try:
LOGGER.debug('building MissionWeather')
_mission_weather = mission_weather.MissionWeather(metar)
with Miz(str(in_file)) as miz:
_mission_weather.apply_to_miz(miz)
miz.zip(str(out_file))
return None, f'successfully applied METAR to {in_file}'
except ValueError:
error = f'Unable to apply METAR string to the mission.\n' \
f'This is most likely due to a freak value, this feature is still experimental.\n' \
f'I will fix it ASAP !'
return error, 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 _pull_schedule_loop(self):
""" Called every 16 minutes to pull a new version of the schedule """ |
try:
self.pull_schedule()
delay = 16*60
except ScheduleError, e:
self.l.exception("ScheduleError while pulling schedule. "+
"Retrying in 5m")
delay = 5*60
if not self.running:
return
self.scheduler.plan(time.time() + delay, self._pull_schedule_loop) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jiggle_source_code(self):
# type: () ->int """ Updates version of central package """ |
changed = 0
for file_name in self.file_inventory.source_files:
to_write = []
# self.create_missing(file_name, file_name)
if not os.path.isfile(file_name):
continue
all_source = self.file_opener.read_this(file_name)
if "__version_info__" in all_source:
logger.warning("We have __version_info__ to sync up.")
# raise TypeError()
with self.file_opener.open_this(file_name, "r") as infile:
for line in infile:
leading_white = self.leading_whitespace(line)
version, version_token = dunder_version.find_in_line(line)
if version:
simplified_line = dunder_version.simplify_line(
line, keep_comma=True
)
if simplified_line.strip(" \t\n").endswith(","):
comma = ","
else:
comma = ""
if simplified_line.strip(" \t\n").startswith(","):
start_comma = ","
else:
start_comma = ""
to_write.append(
'{0}{1}{2} = "{3}"{4}{5}\n'.format(
start_comma,
leading_white,
version_token,
unicode(self.version_to_write()),
comma,
self.signature,
)
)
else:
to_write.append(line)
check(self.file_opener.open_this(file_name, "r").read(), "".join(to_write))
with open(file_name, "w") as outfile:
outfile.writelines(to_write)
changed += 1
return 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 jiggle_config_file(self):
# type: () ->int """ Update ini, cfg, conf """ |
changed = 0
# setup.py related. setup.py itself should read __init__.py or __version__.py
other_files = ["setup.cfg"]
for file_name in other_files:
filepath = os.path.join(self.SRC, file_name)
# only create setup.cfg if we have setup.py
if (
self.create_configs
and not os.path.isfile(filepath)
and os.path.isfile("setup.py")
):
logger.info("Creating " + unicode(filepath))
self.file_maker.create_setup_cfg(filepath)
if os.path.isfile(filepath):
config = configparser.ConfigParser()
config.read(filepath)
try:
version = config["metadata"]["version"]
except KeyError:
version = ""
if version:
with io.open(filepath, "w") as configfile: # save
config["metadata"]["version"] = unicode(self.version_to_write())
config.write(configfile)
changed += 1
return 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 _getConfiguration(self):
""" Load application configuration files. :return: <dict> """ |
configDirectoryPath = os.path.join("application", "config")
config = Config(configDirectoryPath)
configData = config.getData()
# setting application parameters
reactor.suggestThreadPoolSize(
int(configData["performance"]["threadPoolSize"])
)
return configData |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getInterfaces(self):
""" Load application communication interfaces. :return: <dict> """ |
interfaces = {}
interfacesPath = os.path.join("application", "interface")
interfaceList = os.listdir(interfacesPath)
for file in interfaceList:
interfaceDirectoryPath = os.path.join(interfacesPath, file)
if not os.path.isdir(interfaceDirectoryPath) or file.startswith("__") or file.startswith("."):
continue
interfaceName = ntpath.basename(interfaceDirectoryPath)
interfacePath = os.path.join(interfaceDirectoryPath, interfaceName) + ".py"
if not os.path.isfile(interfacePath):
continue
# importing interface
interfaceSpec = importlib.util.spec_from_file_location(
interfaceName,
interfacePath
)
interface = importlib.util.module_from_spec(interfaceSpec)
interfaceSpec.loader.exec_module(interface)
# checking if there is an interface in the file
if hasattr(interface, "Service"):
# initializing interface
interfaceInstance = interface.Service(self)
interfaces[interfaceName] = interfaceInstance
return interfaces |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getModules(self):
""" Import and load application modules. :return: <dict> """ |
modules = {}
modulesPath = os.path.join("application", "module")
moduleList = os.listdir(modulesPath)
for moduleName in moduleList:
modulePath = os.path.join(modulesPath, moduleName, "module.py")
if not os.path.isfile(modulePath):
continue
# importing module
moduleSpec = importlib.util.spec_from_file_location(
moduleName,
modulePath
)
module = importlib.util.module_from_spec(moduleSpec)
moduleSpec.loader.exec_module(module)
# initializing module
moduleInstance = module.Module(self)
modules[moduleName] = moduleInstance
return modules |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addModel(self, moduleName, modelName, model):
""" Add a model instance to the application model pool. :param moduleName: <str> module name in which the model is located :param modelName: <str> model name :param model: <object> model instance :return: <void> """ |
modelIdentifier = "{}.{}".format(moduleName, modelName)
if modelIdentifier not in self._models:
self._models[modelIdentifier] = model
else:
message = "Application - addModel() - " \
"A model with the identifier {} already exists." \
.format(modelIdentifier)
raise Exception(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getModel(self, modelIdentifier):
""" Return the requested model. :param modelIdentifier: <str> model identifier :return: <object> model instance """ |
if modelIdentifier in self._models:
return self._models[modelIdentifier]
else:
message = "Application - getModel() - " \
"Model with identifier {} does not exist." \
.format(modelIdentifier)
raise Exception(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadViperServices(self):
""" Load application bundled services. :return: <void> """ |
servicesPath = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"service"
)
for serviceFile in os.listdir(servicesPath):
if serviceFile.startswith("__") or serviceFile.startswith("."):
continue
serviceName = serviceFile.replace(".py", "")
servicePath = os.path.join(
servicesPath, serviceFile
)
if not os.path.isfile(servicePath):
continue
# importing service
serviceSpec = importlib.util.spec_from_file_location(
serviceName,
servicePath
)
service = importlib.util.module_from_spec(serviceSpec)
serviceSpec.loader.exec_module(service)
# initializing service
serviceInstance = service.Service(self)
self.addService("viper", serviceName, serviceInstance) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addService(self, moduleName, serviceName, service):
""" Add a service instance to the application service pool. :param moduleName: <str> module name in which the service is located :param serviceName: <str> service name :param service: <object> service instance :return: <void> """ |
serviceIdentifier = "{}.{}".format(moduleName, serviceName)
if serviceIdentifier not in self._services:
self._services[serviceIdentifier] = service
else:
message = "Application - addService() - " \
"A service with the identifier {} already exists." \
.format(serviceIdentifier)
raise Exception(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getService(self, serviceIdentifier):
""" Return the requested service instance. :param serviceIdentifier: <str> service identifier :return: <object> service instance """ |
if serviceIdentifier in self._services:
return self._services[serviceIdentifier]
else:
message = "Application - getService() - " \
"Service with identifier {} does not exist." \
.format(serviceIdentifier)
raise Exception(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, *number):
"""Adds all parameters interpreted as integers""" |
return self._format_result(sum(
# positional arguments are always strings
[int(n) for n in number])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subtract(self, number1, number2):
"""Subtracts number2 from number1""" |
return self._format_result(int(number1) - int(number2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def items(self):
"""Expose all grafts. """ |
accumulator = Accumulator()
for graft in load_grafts():
accumulator.spawn(graft())
response = await accumulator.join()
return response.items() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conf_merger(user_dict, variable):
""" Merge global configuration with user's personal configuration. Global configuration has always higher priority. """ |
if variable not in globals().keys():
raise NameError("Unknown variable '%s'." % variable)
if variable not in user_dict:
return globals()[variable]
return globals()[variable] and user_dict[variable] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def len(self, queue_name):
""" Returns the length of the queue. :param queue_name: The name of the queue. Usually handled by the ``Gator`` instance. :type queue_name: string :returns: The length of the queue :rtype: integer """ |
try:
stats = self.conn.stats_tube(queue_name)
except beanstalkc.CommandFailed as err:
if err[1] == 'NOT_FOUND':
return 0
raise
return stats.get('current-jobs-ready', 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 add_facets(engine_result, facet_features=None):
'''Adds facets to search results.
Construct a new result payload with `facets` added as a new
top-level property that carries a mapping from unicode strings to
lists of content_ids. The `facet_features` lists the names of
:class:`~dossier.fc.StringCounter` features in each result
:class:`~dossier.fc.FeatureCollection` to harvest phrases for the
facets list. If not specified, `facet_features` defaults to
`bowNP_sip`.
The remainder of the facet logic is handled in the UI.
'''
if facet_features is None:
facet_features = ['bowNP_sip']
phrases = collections.defaultdict(list)
for r in engine_result['results']:
cid = r[0]
fc = r[1]
for fname in facet_features:
for phrase in fc.get(u'bowNP_sip', []):
phrases[phrase].append(cid)
return dict(engine_result, **{'facets': dict(phrases)}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vectorizable_features(fcs):
'''Discovers the ordered set of vectorizable features in ``fcs``.
Returns a list of feature names, sorted lexicographically.
Feature names are only included if the corresponding
features are vectorizable (i.e., they are an instance of
:class:`collections.Mapping`).
'''
is_mapping = lambda obj: isinstance(obj, collections.Mapping)
return sorted(set([name for fc in fcs for name in fc if is_mapping(fc[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 dissimilarities(feature_names, fcs):
'''Computes the pairwise dissimilarity matrices.
This returns a dictionary mapping each name in ``feature_names``
to a pairwise dissimilarities matrix. The dissimilaritiy scores
correspond to ``1 - kernel`` between each feature of each
pair of feature collections in ``fcs``.
(The kernel used is currently fixed to ``cosine`` distance.)
'''
dis = {}
for count, name in enumerate(feature_names, 1):
logger.info('computing pairwise dissimilarity matrix '
'for %d of %d features (current feature: %s)',
count, len(feature_names), name)
# opportunity to use joblib is buried down inside call to
# pairwise_distances...
# And it's fixed to `n_jobs=1` because running multiprocessing
# inside py.test causes weird problems. It also doesn't seem like a
# good idea to do it inside a web server either. ---AG
dis[name] = 1 - pairwise_distances(
dict_vector().fit_transform([get_feat(fc, name) for fc in fcs]),
metric='cosine', n_jobs=1)
return dis |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def probabilities(self):
'''Trains a model and predicts recommendations.
If the query feature collection could not be found or if there
is insufficient training data, an empty list is returned.
Otherwise, a list of content objects (tuples of content
id and feature collection) and probabilities is returned.
The probability is generated from the model, and reflects
confidence of the model that the corresponding content object
is related to the query based on the ground truth data.
On a large database, random samples are used for training, so
this function is not deterministic.
:rtype: ``list`` of
((``content_id``, :class:`dossier.fc.FeatureCollection`),
probability)
'''
self.query_fc = self.store.get(self.query_content_id)
if self.query_fc is None:
logger.warning('Could not find FC for %s', self.query_content_id)
return []
# Try the canopy query before training, because if the canopy query
# gives us nothing, then there's no point in the additional work.
#
# Possible optimization: If the canopy query yields fewer than N
# results, then can we just return all of them? ---AG
#
# N.B Doing the canopy query first will cause things to be slower
# when there is insufficient training data.
candidates = self.canopy(limit=self.canopy_limit)
if len(candidates) == 0:
logger.info(
'Could not find any candidates in a canopy query by '
'scanning the following indexes: %s',
', '.join(self.store.index_names()))
return []
# Get labels from the database and translate them to the form
# `[{-1, 1}, i, j]` where `i, j` are indices into the list
# `content_objs`, which has type `[(content_id, FeatureCollection)]`.
logger.info('Fetching labels...')
labels = list(self.labels_from_query(limit=self.label_limit))
logger.info('Fetching FCs from labels...')
content_objs = self.content_objs_from_labels(labels)
indexed_labels = labels_to_indexed_coref_values(content_objs, labels)
logger.info('Training...')
model = self.train(content_objs, indexed_labels)
if model is None:
logger.info(
'Could not train model: insufficient training data. '
'(query content id: %s)', self.query_content_id)
raise InsufficientTrainingData
feature_names, classifier, transformer = model
return zip(candidates, self.classify(
feature_names, classifier, transformer, candidates)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def train(self, content_objs, idx_labels):
'''Trains and returns a model using sklearn.
If there are new labels to add, they can be added, returns an
sklearn model which can be used for prediction and getting
features.
This method may return ``None`` if there is insufficient
training data to produce a model.
:param labels: Ground truth data.
:type labels: list of ``({-1, 1}, index1, index2)``.
'''
# We have insufficient training data when there is only one or
# fewer classes of labels.
if len(set([lab[0] for lab in idx_labels])) <= 1:
return None
fcs = [fc for _, fc in content_objs]
feature_names = vectorizable_features(fcs)
dis = dissimilarities(feature_names, fcs)
phi_dicts, labels = [], [] # lists are in correspondence
for coref_value, i, j in idx_labels:
# i, j are indices into the list `fcs`
labels.append(coref_value) # either -1 or 1
phi_dict = dict([(name, dis[name][i,j]) for name in feature_names])
phi_dicts.append(phi_dict)
vec = dict_vector()
training_data = vec.fit_transform(phi_dicts)
model = LogisticRegression(class_weight='auto', penalty='l1')
model.fit(training_data, labels)
self.feature_weights = dict([(name, model.coef_[0][i])
for i, name in enumerate(feature_names)])
return feature_names, model, vec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def noun_phrases_as_tokens(text):
'''Generate a bag of lists of unnormalized tokens representing noun
phrases from ``text``.
This is built around python's nltk library for getting Noun
Phrases (NPs). This is all documented in the NLTK Book
http://www.nltk.org/book/ch03.html and blog posts that cite the
book.
:rtype: list of lists of strings
'''
## from NLTK Book:
sentence_re = r'''(?x) # set flag to allow verbose regexps
([A-Z])(\.[A-Z])+\.? # abbreviations, e.g. U.S.A.
| \w+(-\w+)* # words with optional internal hyphens
| \$?\d+(\.\d+)?%? # currency and percentages, e.g. $12.40, 82%
| \.\.\. # ellipsis
| [][.,;"'?():-_`] # these are separate tokens
'''
## From Su Nam Kim paper:
## http://www.comp.nus.edu.sg/~kanmy/papers/10.1007_s10579-012-9210-3.pdf
grammar = r'''
NBAR:
{<NN.*|JJ>*<NN.*>} # Nouns and Adjectives, terminated with Nouns
NP:
{<NBAR>}
{<NBAR><IN><NBAR>} # Above, connected with in/of/etc...
'''
if len(text.strip()) == 0:
return []
chunker = nltk.RegexpParser(grammar)
toks = nltk.regexp_tokenize(text, sentence_re)
postoks = nltk.tag.pos_tag(toks)
#print postoks
tree = chunker.parse(postoks)
stops = stopwords.words('english')
stops += dossier_stopwords()
## These next four functions are standard uses of NLTK illustrated by
## http://alexbowe.com/au-naturale/
## https://gist.github.com/alexbowe/879414
def leaves(tree):
'''Finds NP (nounphrase) leaf nodes of a chunk tree.'''
for subtree in tree.subtrees(filter = lambda t: t.label()=='NP'):
yield subtree.leaves()
def acceptable_word(word):
'''Checks conditions for acceptable word: length, stopword.'''
return 2 <= len(word) <= 40 and word.lower() not in stops
def get_terms(tree):
for leaf in leaves(tree):
yield [w for w,t in leaf if acceptable_word(w)]
return list(get_terms(tree)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def noun_phrases(text, included_unnormalized=False):
'''applies normalization to the terms found by noun_phrases_as_tokens
and joins on '_'.
:rtype: list of phrase strings with spaces replaced by ``_``.
'''
lemmatizer = nltk.WordNetLemmatizer()
stemmer = nltk.stem.porter.PorterStemmer()
def normalize(word):
'''Normalises words to lowercase and stems and lemmatizes it.'''
word = word.lower()
try:
word = stemmer.stem_word(word)
word = lemmatizer.lemmatize(word)
except:
pass
return word
normalizations = defaultdict(list)
for terms in noun_phrases_as_tokens(text):
key = u'_'.join(map(normalize, terms))
normalizations[key].append(u' '.join(terms))
if included_unnormalized:
return normalizations.keys(), normalizations
else:
return normalizations.keys() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _makeCertificate(key, email, _utcnow=datetime.utcnow):
"""Make the certificate for the client using the given key and e-mail address. """ |
# Create a certificate for this key.
cert = X509()
cert.set_pubkey(key)
# Set the subject.
subject = cert.get_subject()
subject.CN = u"Crypto 101 Client"
subject.emailAddress = email
# Expiration dates. Mandatory.
now = _utcnow()
start = now.replace(hour=0, minute=0, second=0)
cert.set_notBefore(start.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
end = start.replace(year=start.year + 5)
cert.set_notAfter(end.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
# Self-sign.
cert.set_issuer(cert.get_subject())
cert.sign(key, "sha512")
return cert |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def makeCredentials(path, email):
"""Make credentials for the client from given e-mail address and store them in the directory at path. """ |
key = _generateKey()
cert = _makeCertificate(key, email)
certPath = path.child("client.pem")
certPath.alwaysCreate = True
with certPath.open("wb") as pemFile:
pemFile.write(dump_privatekey(FILETYPE_PEM, key))
pemFile.write(dump_certificate(FILETYPE_PEM, cert)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getContextFactory(path):
"""Get a context factory for the client from keys already stored at path. Raises IOError if the credentials didn't exist. """ |
with path.child("client.pem").open() as pemFile:
cert = PrivateCertificate.loadPEM(pemFile.read())
certOptions = cert.options() # TODO: verify server cert (see #1)
certOptions.method = SSL.SSLv23_METHOD
ctxFactory = SecureCiphersContextFactory(certOptions)
return ctxFactory |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.