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 streamify(self, state, frame):
"""Prepare frame for output as a COBS-encoded stream.""" |
# Get the encoding table
enc_tab = self._tables[1][:]
# Need the special un-trailed block length and code
untrail_len, untrail_code = enc_tab.pop(0)
# Set up a repository to receive the encoded blocks
result = []
# Break the frame into blocks
blocks = frame.split('\0')
# Now, walk the block list; done carefully because we need
# look-ahead in some cases
skip = False
for i in range(len(blocks)):
# Skip handled blocks
if skip:
skip = False
continue
blk = blocks[i]
# Encode un-trailed blocks
while len(blk) >= untrail_len - 1:
result.append(untrail_code + blk[:untrail_len - 1])
blk = blk[untrail_len - 1:]
# Do we care about look-ahead?
if (len(enc_tab) > 1 and i + 1 < len(blocks) and
blocks[i + 1] == '' and len(blk) <= 30):
# Use the second encoder table
tab = enc_tab[1]
# Skip the following empty block
skip = True
else:
# Use the regular encoder table
tab = enc_tab[0]
# Encode the block
result.append(tab[len(blk) + 1] + blk)
# Stitch together the result blocks
return ''.join(result) + '\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 parse_conf(self, keys=[]):
"""Parse configuration values from the database. The extension must have been previously initialized. If a key is not found in the database, it will be created with the default value specified. Arguments: keys (list[str]):
list of keys to parse. If the list is empty, then all the keys known to the application will be used. Returns: dict of the parsed config values. """ |
confs = self.app.config.get('WAFFLE_CONFS', {})
if not keys:
keys = confs.keys()
result = {}
for key in keys:
# Some things cannot be changed...
if key.startswith('WAFFLE_'):
continue
# No arbitrary keys
if key not in confs.keys():
continue
stored_conf = self.configstore.get(key)
if not stored_conf:
# Store new record in database
value = confs[key].get('default', '')
stored_conf = self.configstore.put(key, util.serialize(value))
self.configstore.commit()
else:
# Get stored value
value = util.deserialize(stored_conf.get_value())
result[stored_conf.get_key()] = value
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 update_db(self, new_values):
"""Update database values and application configuration. The provided keys must be defined in the ``WAFFLE_CONFS`` setting. Arguments: new_values (dict):
dict of configuration variables and their values The dict has the following structure: { 'MY_CONFIG_VAR' : <CONFIG_VAL>, 'MY_CONFIG_VAR1' : <CONFIG_VAL1> } """ |
confs = self.app.config.get('WAFFLE_CONFS', {})
to_update = {}
for key in new_values.keys():
# Some things cannot be changed...
if key.startswith('WAFFLE_'):
continue
# No arbitrary keys
if key not in confs.keys():
continue
value = new_values[key]
self.configstore.put(key, util.serialize(value))
self.configstore.commit()
to_update[key] = value
# Update config
if not to_update:
return
self.app.config.update(to_update)
# Notify other processes
if self.app.config.get('WAFFLE_MULTIPROC', False):
self.notify(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 update_conf(self):
"""Update configuration values from database. This method should be called when there is an update notification. """ |
parsed = self.parse_conf()
if not parsed:
return None
# Update app config
self.app.config.update(parsed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app, configstore):
"""Initialize the extension for the given application and store. Parse the configuration values stored in the database obtained from the ``WAFFLE_CONFS`` value of the configuration. Arguments: app: Flask application instance configstore (WaffleStore):
database store. """ |
if not hasattr(app, 'extensions'):
app.extensions = {}
self.state = _WaffleState(app, configstore)
app.extensions['waffleconf'] = self.state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isolcss(prefix, css):
""" Returns `css` with all selectors prefixed by `prefix`, or replacing "&" as SASS and LESS both do. Tries to parse strictly then falls back, with a warning, to forgiving parse if necessary. """ |
try:
# Attempt full strict parse, raise exception on failure.
all(True for m in matchiter(selrule_or_atom_re, css))
except ValueError as e:
logger.warning("Strict parse failed at char {}".format(e.args[0]))
splits = matchiter(selrule_or_any_re, css)
else:
splits = matchiter(selrule_or_atom_re, css)
css = []
for m in splits:
if not m.groupdict()['sels']:
css.extend(m.group(0))
continue
sels = matchall(sel_re, m.group('sels'))
# This should never happen because sel_re is a subpattern
# of the original match.
assert sels, "Failed to split selectors: {!r}".format(m.group('sels'))
for sel in sels:
atoms = matchall(atom_re, sel)
if '&' in atoms:
sel = ''.join((prefix if a == '&' else a) for a in atoms)
else:
sel = '%s %s' % (prefix, sel)
css.append(sel)
css.append(m.group('ruleset'))
return ''.join(css) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt_file(filename, set_env=True, override_env=False):
""" Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping the key names to encrypted secrets. This encrypted file can be created using `credkeep.encrypt_file` or the commandline utility. :param filename: filename of the JSON file :param set_env: If True, an environment variable representing the key is created. :param override_env: If True, an existing environment variable with the same key name will be overridden with the new decrypted value. If False, the environment variable will not be set. :return: Dict containing the decrypted keys """ |
data = json.load(open(filename))
results = {}
for key, v in data.iteritems():
v_decrypt = decrypt_secret(v)
results[key] = v_decrypt
if set_env:
if key in os.environ and not override_env:
break
os.environ[str(key)] = v_decrypt
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 decrypt_or_cache(filename, **kwargs):
""" Attempts to load a local version of decrypted secrets before making external api calls. This is useful as it allows credkeep secrets to be used offline. Options for decrypt_filename can be passed to this function. :param filename: filename of encrypted JSON file :return: Dict containing decrypted keys """ |
clear_fname = enc_to_clear_filename(filename)
if clear_fname:
return json.load(open(clear_fname))
return decrypt_file(filename, **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 list(self, filterfn=lambda x: True):
"""Return all direct descendands of directory `self` for which `filterfn` returns True. """ |
return [self / p for p in self.listdir() if filterfn(self / p)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist. """ |
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
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 chunked(l, n):
"""Chunk one big list into few small lists.""" |
return [l[i:i + n] for i in range(0, len(l), 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 getBids(self, auction_id):
"""Retrieve all bids in given auction.""" |
bids = {}
rc = self.__ask__('doGetBidItem2', itemId=auction_id)
if rc:
for i in rc:
i = i['bidsArray']
bids[long(i['item'][1])] = {
'price': Decimal(i['item'][6]),
'quantity': int(i['item'][5]),
'date_buy': i['item'][7]
}
return bids |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info.""" |
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id]))
rc = rc[0]['usersPostBuyData']['item'][0]['userData']
return {'allegro_aid': auction_id,
'allegro_uid': rc['userId'],
'allegro_login': magicDecode(rc['userLogin']),
'name': magicDecode(rc['userFirstName']),
'surname': magicDecode(rc['userLastName']),
'company': magicDecode(rc['userCompany']),
'postcode': magicDecode(rc['userPostcode']),
'city': magicDecode(rc['userCity']),
'address': magicDecode(rc['userAddress']),
'email': magicDecode(rc['userEmail']),
'phone': rc['userPhone']} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getOrders(self, auction_ids):
"""Return orders details.""" |
orders = {}
# chunk list (only 25 auction_ids per request)
for chunk in chunked(auction_ids, 25):
# auctions = [{'item': auction_id} for auction_id in chunk] # TODO?: is it needed?
auctions = self.ArrayOfLong(chunk)
rc = self.__ask__('doGetPostBuyData', itemsArray=auctions)
for auction in rc:
orders_auction = []
bids = self.getBids(auction['itemId'])
# get orders details
# for i in auction.get('usersPostBuyData', ()):
if not auction['usersPostBuyData']: # empty
continue
for i in auction['usersPostBuyData']['item']:
i = i['userData']
if i['userId'] not in bids: # temporary(?) webapi bug fix
continue
orders_auction.append({
'allegro_aid': auction['itemId'],
'allegro_uid': i['userId'],
'allegro_login': magicDecode(i['userLogin']),
'name': magicDecode(i['userFirstName']),
'surname': magicDecode(i['userLastName']),
'company': magicDecode(i['userCompany']),
'postcode': magicDecode(i['userPostcode']),
'city': magicDecode(i['userCity']),
'address': magicDecode(i['userAddress']),
'email': magicDecode(i['userEmail']),
'phone': i['userPhone'],
'price': bids[i['userId']]['price'],
'quantity': bids[i['userId']]['quantity'],
'date_buy': bids[i['userId']]['date_buy']
})
orders[auction['itemId']] = orders_auction
return orders |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getJournalDeals(self, start=None):
"""Return all journal events from start.""" |
# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA
if start is not None:
self.last_event_id = start
events = []
while self.getJournalDealsInfo(self.last_event_id) > 0:
rc = self.__ask__('doGetSiteJournalDeals', journalStart=self.last_event_id)
for i in rc:
events.append({
'allegro_did': i['dealId'],
'deal_status': i['dealEventType'],
'transaction_id': i['dealTransactionId'],
'time': i['dealEventTime'],
'event_id': i['dealEventId'],
'allegro_aid': i['dealItemId'],
'allegro_uid': i['dealBuyerId'],
# 'seller_id': i['dealSellerId '],
'quantity': i['dealQuantity']
})
self.last_event_id = rc[-1]['dealEventId']
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getWaitingFeedbacks(self):
"""Return all waiting feedbacks from buyers.""" |
# TODO: return sorted dictionary (negative/positive/neutral)
feedbacks = []
offset = 0
amount = self.__ask__('doGetWaitingFeedbacksCount')
while amount > 0:
rc = self.__ask__('doGetWaitingFeedbacks',
offset=offset, packageSize=200)
feedbacks.extend(rc['feWaitList'])
amount -= 200
offset += 1
return feedbacks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silent(cmd, **kwargs):
"""Calls the given shell command. Output will not be displayed. Returns the status code. **Examples**: :: auxly.shell.silent("ls") """ |
return call(cmd, shell=True, stdout=NULL, stderr=NULL, **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 has(cmd):
"""Returns true if the give shell command is available. **Examples**: :: auxly.shell.has("ls") # True """ |
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
for h in helps:
hcmd = "%s %s" % (cmd, h)
if 0 == silent(hcmd):
return True
if len(listout(hcmd)) > 0:
return True
if strerr(hcmd) != cmderr:
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 csvpretty(csvfile: csvfile=sys.stdin):
""" Pretty print a CSV file. """ |
shellish.tabulate(csv.reader(csvfile)) |
<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_key(self, path, geometry, filters, options):
"""Generates the thumbnail's key from it's arguments. If the arguments doesn't change the key will not change """ |
seed = u' '.join([
str(path),
str(geometry),
str(filters),
str(options),
]).encode('utf8')
return md5(seed).hexdigest() |
<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_source(self, path_or_url):
"""Returns the source image file descriptor. path_or_url: Path to the source image as an absolute path, a path relative to `self.base_path` or a URL beginning with `http[s]` """ |
if path_or_url.startswith(('http://', 'https://')):
try:
return urlopen(path_or_url)
except IOError:
return None
fullpath = path_or_url
if not os.path.isabs(path_or_url):
fullpath = os.path.join(self.base_path, path_or_url)
try:
return io.open(fullpath, 'rb')
except IOError:
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 get_thumb(self, path, key, format):
"""Get the stored thumbnail if exists. path: path of the source image key: key of the thumbnail format: thumbnail's file extension """ |
thumbpath = self.get_thumbpath(path, key, format)
fullpath = os.path.join(self.out_path, thumbpath)
if os.path.isfile(fullpath):
url = self.get_url(thumbpath)
return Thumb(url, key)
return 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 get_thumbpath(self, path, key, format):
"""Return the relative path of the thumbnail. path: path of the source image key: key of the thumbnail format: thumbnail file extension """ |
relpath = os.path.dirname(path)
thumbsdir = self.get_thumbsdir(path)
name, _ = os.path.splitext(os.path.basename(path))
name = '{}.{}.{}'.format(name, key, format.lower())
return os.path.join(relpath, thumbsdir, 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 save(self, path, key, format, data):
"""Save a newly generated thumbnail. path: path of the source image key: key of the thumbnail format: thumbnail's file extension data: thumbnail's binary data """ |
thumbpath = self.get_thumbpath(path, key, format)
fullpath = os.path.join(self.out_path, thumbpath)
self.save_thumb(fullpath, data)
url = self.get_url(thumbpath)
thumb = Thumb(url, key, fullpath)
return 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 add_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handler to the global logger.""" |
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatter = ColoredFormatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')
else:
formatter = logging.Formatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
g_logger.addHandler(handler)
return handler |
<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_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger.""" |
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename = os.path.basename(filename.replace('.py', '.log'))
filename = os.path.join('/tmp', filename)
if not os.path.exists(os.path.dirname(filename)):
os.mkdir(os.path.dirname(filename))
kwargs['filename'] = filename
# Choose the filehandler based on the passed arguments
if backup_count == 0: # Use FileHandler
cls = logging.FileHandler
kwargs['mode'] = mode
elif when is None: # Use RotatingFileHandler
cls = logging.handlers.RotatingFileHandler
kwargs['maxBytes'] = limit
kwargs['backupCount'] = backup_count
kwargs['mode'] = mode
else: # Use TimedRotatingFileHandler
cls = logging.handlers.TimedRotatingFileHandler
kwargs['when'] = when
kwargs['interval'] = limit
kwargs['backupCount'] = backup_count
return add_handler(cls, level, fmt, False, **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 init_logger(name=None):
"""Reload the global logger.""" |
global g_logger
if g_logger is None:
g_logger = logging.getLogger(name=name)
else:
logging.shutdown()
g_logger.handlers = []
g_logger.setLevel(logging.DEBUG) |
<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_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET', fmt= '%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelname)-7s] %(message)s', # fmt='[%(levelname)s] %(asctime)s %(message)s', backup_count=5, limit=20480, when=None, with_filehandler=True):
"""Configure the global logger.""" |
level = level.split(':')
if len(level) == 1: # Both set to the same level
s_level = f_level = level[0]
else:
s_level = level[0] # StreamHandler log level
f_level = level[1] # FileHandler log level
init_logger(name=name)
add_streamhandler(s_level, fmt)
if with_filehandler:
add_filehandler(f_level, fmt, filename, mode, backup_count, limit, when)
# Import the common log functions for convenient
import_log_funcs() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_log_funcs():
"""Import the common log functions from the global logger to the module.""" |
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def powerupIndirector(interface):
""" A decorator for a powerup indirector from a single interface to a single in-memory implementation. The in-memory implementation that is being indirected to must be created in the ``activate`` callback, and then assigned to ``self.indirected``, which is an ``inmemory`` attribute. """ |
def decorator(cls):
zi.implementer(iaxiom.IPowerupIndirector)(cls)
cls.powerupInterfaces = [interface]
cls.indirect = _indirect
return cls
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lint(self, dataset=None, col=None, no_header=False, ignore_nfd=False, ignore_ws=False, linewise=False, no_lines=False):
""" Returns a string containing all the issues found in the dataset defined by the given file path. """ |
reader = Reader(dataset, has_header=not no_header, ipa_col=col)
recog = Recogniser()
norm = Normaliser(nfc_chars=recog.get_nfc_chars())
for ipa_string, line_num in reader.gen_ipa_data():
ipa_string = norm.normalise(ipa_string, line_num)
recog.recognise(ipa_string, line_num)
rep = Reporter()
norm.report(rep, ignore_nfd, ignore_ws)
recog.report(rep)
return rep.get_report(linewise, no_lines) |
<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_rune_links(html: str) -> dict: """A function which parses the main Runeforge website into dict format. Parameters html : str The string representation of the html obtained via a GET request. Returns ------- dict The nested rune_links champ rune pages from runeforge. """ |
soup = BeautifulSoup(html, 'lxml')
# Champs with only a single runepage
single_page_raw = soup.find_all('li', class_='champion')
single_page = {re.split('\W+', x.a.div.div['style'])[-3].lower():
[x.a['href']] for x in single_page_raw if x.a is not None}
# Champs with two (or more) runepages
double_page_raw = soup.find_all('div', class_='champion-modal-open')
# This is JSON data which just needs to be decoded
double_page_decode = [json.loads(x['data-loadouts']) for x in double_page_raw]
# This lowers the champ name in the structure,
# and pulls out the champ links, after it's been decoded
double_page = {re.sub('[^A-Za-z0-9]+', '', x[0]['champion'].lower()):
[x[0]['link'], x[1]['link']] for x in double_page_decode}
# Combine the two dicts
champs_combined = {**single_page, **double_page}
return champs_combined |
<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_string(regex, s):
"""Find a string using a given regular expression. If the string cannot be found, returns None. The regex should contain one matching group, as only the result of the first group is returned. s - The string to search. regex - A string containing the regular expression. Returns a unicode string or None. """ |
m = re.search(regex, s)
if m is None:
return None
return m.groups()[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 clean_text(s):
"""Removes all cruft from the text.""" |
SPACES_RE = re.compile(r'\s+')
SPECIAL_CHARS_RE = re.compile(r'[^\w\s\.\-\(\)]')
s = SPACES_RE.sub(' ', s)
s = s.strip()
s = SPECIAL_CHARS_RE.sub('', s)
return s |
<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_immoweb_link(url):
"""Parses an Immoweb estate detail URL and returns the Immoweb estate id. Returns a string with the Immoweb estate id. """ |
IMMOWEB_ID_RE = re.compile(r'.*?IdBien=([0-9]+).*?')
return IMMOWEB_ID_RE.match(url).groups()[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 parse_number(d, key, regex, s):
"""Find a number using a given regular expression. If the number is found, sets it under the key in the given dictionary. d - The dictionary that will contain the data. key - The key into the dictionary. regex - A string containing the regular expression. s - The string to search. """ |
result = find_number(regex, s)
if result is not None:
d[key] = 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 make_category_filter(categories, blank=True):
'''
Generates a dict representing a Factual filter matching any of the categories
passed.
The resulting filter uses $bw "begins with" operators to return all matching
subcategories. Because of this, passing a top level category removes the need
to pass any of its subcategories.
Conversely, specifying subcategories will not restrict results as expected
if a prefix of those subcategories is also provided. For example:
make_category_filter(["Food & Beverage", "Food & Beverage > Cheese"])
is the same as
make_category_filter(["Food & Beverage"])
To minimize the size of the filters sent to Factual, make_category_filters
identifies redundant subcategories and removes them.
Note that because of this prefix matching, queries may return rows from unwanted
subcategories. It may be necessary for you to filter out these records after
the Factual request.
Specify blank=True to include items without a category set.
'''
categories = [category.strip() for category in categories]
# find shortest prefixes
categories.sort()
redundant_categories = set()
prefix_candidate = None
for category in categories:
if prefix_candidate != None \
and category.find(prefix_candidate) == 0:
# prefix_candidate is a prefix of the current category,
# so we can skip the current category
redundant_categories.add(category)
else:
prefix_candidate = category
categories = [category for category in categories if category not in redundant_categories]
filters = [ops.bw_("category", category) for category in categories]
if blank:
filters.append(ops.blank_("category"))
return ops.or_(*filters) |
<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_type(self, value, spec):
""" Some well-educated format guessing. """ |
data_type = spec.get('type', 'string').lower().strip()
if data_type in ['bool', 'boolean']:
return value.lower() in BOOL_TRUISH
elif data_type in ['int', 'integer']:
try:
return int(value)
except (ValueError, TypeError):
return None
elif data_type in ['float', 'decimal', 'real']:
try:
return float(value)
except (ValueError, TypeError):
return None
elif data_type in ['date', 'datetime', 'timestamp']:
if 'format' in spec:
format_list = self._get_date_format_list(spec.get('format'))
if format_list is None:
raise MappingException(
'%s format mapping is not valid: %r' %
(spec.get('column'), spec.get('format'))
)
for format, precision in format_list:
try:
return {'value': datetime.strptime(value, format),
'value_precision': precision}
except (ValueError, TypeError):
pass
return None
else:
try:
return parser.parse(value)
except (ValueError, TypeError):
return None
elif data_type == 'file':
try:
return self._get_file(value)
except:
raise
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 get_value(self, spec, row):
""" Returns the value or a dict with a 'value' entry plus extra fields. """ |
column = spec.get('column')
default = spec.get('default')
if column is None:
if default is not None:
return self.convert_type(default, spec)
return
value = row.get(column)
if is_empty(value):
if default is not None:
return self.convert_type(default, spec)
return None
return self.convert_type(value, spec) |
<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_source(self, spec, row):
""" Sources can be specified as plain strings or as a reference to a column. """ |
value = self.get_value({'column': spec.get('source_url_column')}, row)
if value is not None:
return value
return spec.get('source_url') |
<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(self, data):
""" Load a single row of data and convert it into entities and relations. """ |
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(self.loader, data, objs) |
<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_v3(vec1, m):
"""Return a new Vec3 containing the sum of our x, y, z, and arg. If argument is a float or vec, addt it to our x, y, and z. Otherwise, treat it as a Vec3 and add arg.x, arg.y, and arg.z from our own x, y, and z. """ |
if type(m) in NUMERIC_TYPES:
return Vec3(vec1.x + m, vec1.y + m, vec1.z + m)
else:
return Vec3(vec1.x + m.x, vec1.y + m.y, vec1.z + m.z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate_v3(vec, amount):
"""Return a new Vec3 that is translated version of vec.""" |
return Vec3(vec.x+amount, vec.y+amount, vec.z+amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale_v3(vec, amount):
"""Return a new Vec3 that is a scaled version of vec.""" |
return Vec3(vec.x*amount, vec.y*amount, vec.z*amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot_v3(v, w):
"""Return the dotproduct of two vectors.""" |
return sum([x * y for x, y in zip(v, w)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projection_as_vec_v3(v, w):
"""Return the signed length of the projection of vector v on vector w. Returns the full vector result of projection_v3(). """ |
proj_len = projection_v3(v, w)
return scale_v3(v, proj_len) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def point_to_line(point, segment_start, segment_end):
"""Given a point and a line segment, return the vector from the point to the closest point on the segment. """ |
# TODO: Needs unittests.
segment_vec = segment_end - segment_start
# t is distance along line
t = -(segment_start - point).dot(segment_vec) / (
segment_vec.length_squared())
closest_point = segment_start + scale_v3(segment_vec, t)
return point - closest_point |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b.""" |
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x * vec_b.z,
vec_a.x * vec_b.y - vec_a.y * vec_b.x) |
<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_around_vector_v3(v, angle_rad, norm_vec):
""" rotate v around norm_vec by angle_rad.""" |
cos_val = math.cos(angle_rad)
sin_val = math.sin(angle_rad)
## (v * cosVal) +
## ((normVec * v) * (1.0 - cosVal)) * normVec +
## (v ^ normVec) * sinVal)
#line1: scaleV3(v,cosVal)
#line2: dotV3( scaleV3( dotV3(normVec,v), 1.0-cosVal), normVec)
#line3: scaleV3( crossV3( v,normVec), sinVal)
#a = scaleV3(v,cosVal)
#b = scaleV3( normVec, dotV3(normVec,v) * (1.0-cosVal))
#c = scaleV3( crossV3( v,normVec), sinVal)
return add_v3(
add_v3(scale_v3(v, cos_val),
scale_v3(norm_vec, dot_v3(norm_vec, v) * (1.0 - cos_val))),
scale_v3(cross_v3(v, norm_vec), sin_val)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ave_list_v3(vec_list):
"""Return the average vector of a list of vectors.""" |
vec = Vec3(0, 0, 0)
for v in vec_list:
vec += v
num_vecs = float(len(vec_list))
vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)
return 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 _float_almost_equal(float1, float2, places=7):
"""Return True if two numbers are equal up to the specified number of "places" after the decimal point. """ |
if round(abs(float2 - float1), places) == 0:
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 almost_equal(self, v2, places=7):
"""When comparing for equality, compare floats up to a limited precision specified by "places". """ |
try:
return (
len(self) == len(v2) and
_float_almost_equal(self.x, v2.x, places) and
_float_almost_equal(self.y, v2.y, places) and
_float_almost_equal(self.z, v2.z, places))
except:
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 dot(self, w):
"""Return the dotproduct between self and another vector.""" |
return sum([x * y for x, y in zip(self, w)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cross(self, vec):
"""Return the crossproduct between self and vec.""" |
return Vec3(self.y * vec.z - self.z * vec.y,
self.z * vec.x - self.x * vec.z,
self.x * vec.y - self.y * vec.x) |
<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(self, x, y, z):
"""Set x, y, and z components. Also return self. """ |
self.x = x
self.y = y
self.z = z
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 neg(self):
"""Negative value of all components.""" |
self.x = -self.x
self.y = -self.y
self.z = -self.z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller is responsibile for closing the stream """ |
from io import IOBase
if not isinstance(rel_path, basestring):
rel_path = rel_path.cache_key
repo_path = os.path.join(self.cache_dir, rel_path.strip("/"))
if not os.path.isdir(os.path.dirname(repo_path)):
os.makedirs(os.path.dirname(repo_path))
if os.path.exists(repo_path):
os.remove(repo_path)
sink = open(repo_path, 'wb')
upstream = self.upstream
class flo(IOBase):
'''This File-Like-Object class ensures that the file is also
sent to the upstream after it is stored in the FSCache. '''
def __init__(self, sink, upstream, repo_path, rel_path):
self._sink = sink
self._upstream = upstream
self._repo_path = repo_path
self._rel_path = rel_path
@property
def rel_path(self):
return self._rel_path
def write(self, str_):
self._sink.write(str_)
def close(self):
if not self._sink.closed:
# print "Closing put_stream.flo {}
# is_closed={}!".format(self._repo_path, self._sink.closed)
self._sink.close()
if self._upstream and not self._upstream.readonly and not self._upstream.usreadonly:
self._upstream.put(
self._repo_path,
self._rel_path,
metadata=metadata)
def __enter__(self): # Can be used as a context!
return self
def __exit__(self, type_, value, traceback):
if type_:
return False
self.close()
self.put_metadata(rel_path, metadata)
return flo(sink, upstream, repo_path, rel_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 size(self):
'''Return the size of all of the files referenced in the database'''
c = self.database.cursor()
r = c.execute("SELECT sum(size) FROM files")
try:
size = int(r.fetchone()[0])
except TypeError:
size = 0
return 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 _free_up_space(self, size, this_rel_path=None):
'''If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it.
'''
# Amount of space we are over ( bytes ) for next put
space = self.size + size - self.maxsize
if space <= 0:
return
removes = []
for row in self.database.execute("SELECT path, size, time FROM files ORDER BY time ASC"):
if space > 0:
removes.append(row[0])
space -= row[1]
else:
break
for rel_path in removes:
if rel_path != this_rel_path:
global_logger.debug("Deleting {}".format(rel_path))
self.remove(rel_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 verify(self):
'''Check that the database accurately describes the state of the repository'''
c = self.database.cursor()
non_exist = set()
no_db_entry = set(os.listdir(self.cache_dir))
try:
no_db_entry.remove('file_database.db')
no_db_entry.remove('file_database.db-journal')
except:
pass
for row in c.execute("SELECT path FROM files"):
path = row[0]
repo_path = os.path.join(self.cache_dir, path)
if os.path.exists(repo_path):
no_db_entry.remove(path)
else:
non_exist.add(path)
if len(non_exist) > 0:
raise Exception(
"Found {} records in db for files that don't exist: {}" .format(
len(non_exist),
','.join(non_exist)))
if len(no_db_entry) > 0:
raise Exception("Found {} files that don't have db entries: {}"
.format(len(no_db_entry), ','.join(no_db_entry))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller is responsibile for closing the stream. Bad things happen if you dont close the stream """ |
class flo:
def __init__(self, this, sink, upstream, repo_path):
self.this = this
self.sink = sink
self.upstream = upstream
self.repo_path = repo_path
@property
def repo_path(self):
return self.repo_path
def write(self, d):
self.sink.write(d)
if self.upstream:
self.upstream.write(d)
def writelines(self, lines):
raise NotImplemented()
def close(self):
self.sink.close()
size = os.path.getsize(self.repo_path)
self.this.add_record(rel_path, size)
self.this._free_up_space(size, this_rel_path=rel_path)
if self.upstream:
self.upstream.close()
def __enter__(self): # Can be used as a context!
return self
def __exit__(self, type_, value, traceback):
if type_:
return False
if not isinstance(rel_path, basestring):
rel_path = rel_path.cache_key
repo_path = os.path.join(self.cache_dir, rel_path.strip('/'))
if not os.path.isdir(os.path.dirname(repo_path)):
os.makedirs(os.path.dirname(repo_path))
self.put_metadata(rel_path, metadata=metadata)
sink = open(repo_path, 'w+')
upstream = self.upstream.put_stream(
rel_path,
metadata=metadata) if self.upstream else None
return flo(self, sink, upstream, repo_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 create_proxy(self, this, message):
"""Create proxy for an actor. `message` has the form:: {'tag': 'create_proxy', } """ |
actor = message['actor']
proxy = self._create_proxy(this, actor)
message['customer'] << proxy |
<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_caselessly(dictionary, sought):
"""Find the sought key in the given dictionary regardless of case 9 """ |
try:
return dictionary[sought]
except KeyError:
caseless_keys = {k.lower(): k for k in dictionary.keys()}
real_key = caseless_keys[sought.lower()] # allow any KeyError here
return dictionary[real_key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_value(dictionary, key, item):
"""Append those items to the values for that key""" |
items = dictionary.get(key, [])
items.append(item)
dictionary[key] = 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 extend_values(dictionary, key, items):
"""Extend the values for that key with the items""" |
values = dictionary.get(key, [])
try:
values.extend(items)
except TypeError:
raise TypeError('Expected a list, got: %r' % items)
dictionary[key] = 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 run(self):
'''Fetch and dispatch jobs as long as the system is running.
This periodically checks the :class:`rejester.TaskMaster` mode
and asks it for more work. It will normally run forever in a
loop until the mode becomes
:attr:`~rejester.TaskMaster.TERMINATE`, at which point it
waits for all outstanding jobs to finish and exits.
This will :func:`~rejester.Worker.heartbeat` and check for new
work whenever a job finishes, or otherwise on a random
interval between 1 and 5 seconds.
'''
tm = self.task_master
num_workers = multiprocessing.cpu_count()
if 'tasks_per_cpu' in self.config:
num_workers *= self.config.get('tasks_per_cpu') or 1
if self.pool is None:
self.pool = multiprocessing.Pool(num_workers, maxtasksperchild=1)
## slots is a fixed-length list of [AsyncRsults, WorkUnit]
slots = [[None, None]] * num_workers
logger.info('MultiWorker starting with %s workers', num_workers)
min_loop_time = 2.0
lastFullPoll = time.time()
while True:
mode = self.heartbeat()
if mode != self._mode:
logger.info('worker {0} changed to mode {1}'
.format(self.worker_id, mode))
self._mode = mode
now = time.time()
should_update = (now - lastFullPoll) > min_loop_time
self._poll_slots(slots, mode=mode, do_update=should_update)
if should_update:
lastFullPoll = now
if mode == tm.TERMINATE:
num_waiting = sum(map(int, map(bool, map(itemgetter(0), slots))))
if num_waiting == 0:
logger.info('MultiWorker all children finished')
break
else:
logger.info('MultiWorker waiting for %d children to finish', num_waiting)
sleepsecs = random.uniform(1,5)
sleepstart = time.time()
try:
self._event_queue.get(block=True, timeout=sleepsecs)
logger.debug('woken by event looptime=%s sleeptime=%s', sleepstart - now, time.time() - sleepstart)
except Queue.Empty, empty:
logger.debug('queue timed out. be exhausting, looptime=%s sleeptime=%s', sleepstart - now, time.time() - sleepstart)
# it's cool, timed out, do the loop of checks and stuff.
logger.info('MultiWorker exiting') |
<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_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMINATE`.
:param set_title: if true, set the process's title with the
work unit name
:return: :const:`True` if there was a job (even if it failed)
'''
available_gb = MultiWorker.available_gb()
unit = self.task_master.get_work(self.worker_id, available_gb, work_spec_names=self.work_spec_names, max_jobs=self.max_jobs)
if not unit:
logger.info('No work to do; stopping.')
return False
if isinstance(unit, (list, tuple)):
ok = True
for xunit in unit:
if not ok:
try:
xunit.update(-1)
except LostLease as e:
pass
except Exception as bad:
# we're already quitting everything, but this is weirdly bad.
logger.error('failed to release lease on %r %r', xunit.work_spec_name, xunit.key, exc_info=True)
else:
ok = self._run_unit(xunit, set_title)
return ok
return self._run_unit(unit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def as_child(cls, global_config, parent=None):
'''Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did.
'''
try:
setproctitle('rejester worker')
random.seed() # otherwise everyone inherits the same seed
yakonfig.set_default_config([yakonfig, dblogger, rejester],
config=global_config)
worker = cls(yakonfig.get_global_config(rejester.config_name))
worker.register(parent=parent)
did_work = worker.run(set_title=True)
worker.unregister()
if did_work:
sys.exit(cls.EXIT_SUCCESS)
else:
sys.exit(cls.EXIT_BORED)
except Exception, e:
# There's some off chance we have logging.
# You will be here if redis is down, for instance,
# and the yakonfig dblogger setup runs but then
# the get_work call fails with an exception.
if len(logging.root.handlers) > 0:
logger.critical('failed to do any work', exc_info=e)
sys.exit(cls.EXIT_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 set_signal_handlers(self):
'''Set some signal handlers.
These react reasonably to shutdown requests, and keep the
logging child alive.
'''
def handler(f):
def wrapper(signum, backtrace):
return f()
return wrapper
self.old_sigabrt = signal.signal(signal.SIGABRT,
handler(self.scram))
self.old_sigint = signal.signal(signal.SIGINT,
handler(self.stop_gracefully))
self.old_sigpipe = signal.signal(signal.SIGPIPE,
handler(self.live_log_child))
signal.siginterrupt(signal.SIGPIPE, False)
self.old_sigterm = signal.signal(signal.SIGTERM,
handler(self.stop_gracefully)) |
<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, level, message):
'''Write a log message via the child process.
The child process must already exist; call :meth:`live_log_child`
to make sure. If it has died in a way we don't expect then
this will raise :const:`signal.SIGPIPE`.
'''
if self.log_fd is not None:
prefix = struct.pack('ii', level, len(message))
os.write(self.log_fd, prefix)
os.write(self.log_fd, 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 debug(self, group, message):
'''Maybe write a debug-level log message.
In particular, this gets written if the hidden `debug_worker`
option contains `group`.
'''
if group in self.debug_worker:
if 'stdout' in self.debug_worker:
print message
self.log(logging.DEBUG, 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 log_spewer(self, gconfig, fd):
'''Child process to manage logging.
This reads pairs of lines from `fd`, which are alternating
priority (Python integer) and message (unformatted string).
'''
setproctitle('rejester fork_worker log task')
yakonfig.set_default_config([yakonfig, dblogger], config=gconfig)
try:
while True:
prefix = os.read(fd, struct.calcsize('ii'))
level, msglen = struct.unpack('ii', prefix)
msg = os.read(fd, msglen)
logger.log(level, msg)
except Exception, e:
logger.critical('log writer failed', exc_info=e)
raise |
<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_log_child(self):
'''Start the logging child process.'''
self.stop_log_child()
gconfig = yakonfig.get_global_config()
read_end, write_end = os.pipe()
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
os.close(write_end)
yakonfig.clear_global_config()
self.log_spewer(gconfig, read_end)
sys.exit(0)
else:
# We are the parent
self.debug('children', 'new log child with pid {0}'.format(pid))
self.log_child = pid
os.close(read_end)
self.log_fd = write_end |
<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_log_child(self):
'''Stop the logging child process.'''
if self.log_fd:
os.close(self.log_fd)
self.log_fd = None
if self.log_child:
try:
self.debug('children', 'stopping log child with pid {0}'
.format(self.log_child))
os.kill(self.log_child, signal.SIGTERM)
os.waitpid(self.log_child, 0)
except OSError, e:
if e.errno == errno.ESRCH or e.errno == errno.ECHILD:
# already gone
pass
else:
raise
self.log_child = 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 live_log_child(self):
'''Start the logging child process if it died.'''
if not (self.log_child and self.pid_is_alive(self.log_child)):
self.start_log_child() |
<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_some_work(self, can_start_more):
'''Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one child.
:param bool can_start_more: Allowed to start a child?
:return: Time to wait before calling this function again
'''
any_happy_children = False
any_sad_children = False
any_bored_children = False
self.debug('loop', 'starting work loop, can_start_more={0!r}'
.format(can_start_more))
# See if anyone has died
while True:
try:
pid, status = os.waitpid(-1, os.WNOHANG)
except OSError, e:
if e.errno == errno.ECHILD:
# No children at all
pid = 0
else:
raise
if pid == 0:
break
elif pid == self.log_child:
self.debug('children',
'log child with pid {0} exited'.format(pid))
self.start_log_child()
elif pid in self.children:
self.children.remove(pid)
if os.WIFEXITED(status):
code = os.WEXITSTATUS(status)
self.debug('children',
'worker {0} exited with code {1}'
.format(pid, code))
if code == SingleWorker.EXIT_SUCCESS:
any_happy_children = True
elif code == SingleWorker.EXIT_EXCEPTION:
self.log(logging.WARNING,
'child {0} reported failure'.format(pid))
any_sad_children = True
elif code == SingleWorker.EXIT_BORED:
any_bored_children = True
else:
self.log(logging.WARNING,
'child {0} had odd exit code {1}'
.format(pid, code))
elif os.WIFSIGNALED(status):
self.log(logging.WARNING,
'child {0} exited with signal {1}'
.format(pid, os.WTERMSIG(status)))
any_sad_children = True
else:
self.log(logging.WARNING,
'child {0} went away with unknown status {1}'
.format(pid, status))
any_sad_children = True
else:
self.log(logging.WARNING,
'child {0} exited, but we don\'t recognize it'
.format(pid))
# ...what next?
# (Don't log anything here; either we logged a WARNING message
# above when things went badly, or we're in a very normal flow
# and don't want to spam the log)
if any_sad_children:
self.debug('loop', 'exit work loop with sad child')
return self.poll_interval
if any_bored_children:
self.debug('loop', 'exit work loop with no work')
return self.poll_interval
# This means we get to start a child, maybe.
if can_start_more and len(self.children) < self.num_workers:
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
if self.log_fd:
os.close(self.log_fd)
LoopWorker.as_child(yakonfig.get_global_config(),
parent=self.worker_id)
# This should never return, but just in case
sys.exit(SingleWorker.EXIT_EXCEPTION)
else:
# We are the parent
self.debug('children', 'new worker with pid {0}'.format(pid))
self.children.add(pid)
self.debug('loop', 'exit work loop with a new worker')
return self.spawn_interval
# Absolutely nothing is happening; which means we have all
# of our potential workers and they're doing work
self.debug('loop', 'exit work loop with full system')
return self.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 check_spinning_children(self):
'''Stop children that are working on overdue jobs.'''
child_jobs = self.task_master.get_child_work_units(self.worker_id)
# We will kill off any jobs that are due before "now". This
# isn't really now now, but now plus a grace period to make
# sure spinning jobs don't get retried.
now = time.time() + self.stop_jobs_early
for child, wul in child_jobs.iteritems():
if not isinstance(wul, (list, tuple)):
# Support old style get_child_work_units which returns
# single WorkUnit objects instead of list of them.
wul = [wul]
if not wul:
# This worker is idle, but oddly, still present; it should
# clean up after itself
continue
# filter on those actually assigned to the child worker
wul = filter(lambda wu: wu.worker_id == child, wul)
# check for any still active not-overdue job
if any(filter(lambda wu: wu.expires > now, wul)):
continue
# So either someone else is doing its work or it's just overdue
environment = self.task_master.get_heartbeat(child)
if not environment:
continue # derp
if 'pid' not in environment:
continue # derp
if environment['pid'] not in self.children:
continue # derp
os.kill(environment['pid'], signal.SIGTERM)
# This will cause the child to die, and do_some_work will
# reap it; but we'd also like the job to fail if possible
for wu in wul:
if wu.data is None:
logger.critical('how did wu.data become: %r' % wu.data)
else:
wu.data['traceback'] = 'job expired'
wu.fail(exc=Exception('job expired')) |
<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_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
'second shutdown request, shutting down now')
self.scram()
else:
self.log(logging.INFO, 'shutting down after current jobs finish')
self.shutting_down = 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 stop_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the log message before we kill it off. C'est la vie...
self.stop_log_child()
for pid in self.children:
try:
os.kill(pid, signal.SIGTERM)
os.waitpid(pid, 0)
except OSError, e:
if e.errno == errno.ESRCH or e.errno == errno.ECHILD:
# No such process
pass
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def scram(self):
'''Kill all workers and die ourselves.
This runs in response to SIGABRT, from a specific invocation
of the ``kill`` command. It also runs if
:meth:`stop_gracefully` is called more than once.
'''
self.stop_all_children()
signal.signal(signal.SIGTERM, signal.SIG_DFL)
sys.exit(2) |
<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(self):
'''Run the main loop.
This is fairly invasive: it sets a bunch of signal handlers
and spawns off a bunch of child processes.
'''
setproctitle('rejester fork_worker for namespace {0}'
.format(self.config.get('namespace', None)))
self.set_signal_handlers()
try:
self.start_log_child()
while True:
can_start_more = not self.shutting_down
if time.time() >= self.heartbeat_deadline:
mode = self.heartbeat()
if mode != self.last_mode:
self.log(logging.INFO,
'rejester global mode is {0!r}'.format(mode))
self.last_mode = mode
self.heartbeat_deadline = (time.time() +
self.heartbeat_interval)
self.check_spinning_children()
else:
mode = self.last_mode
if mode != self.task_master.RUN:
can_start_more = False
interval = self.do_some_work(can_start_more)
# Normal shutdown case
if len(self.children) == 0:
if mode == self.task_master.TERMINATE:
self.log(logging.INFO,
'stopping for rejester global shutdown')
break
if self.shutting_down:
self.log(logging.INFO,
'stopping in response to signal')
break
time.sleep(interval)
except Exception:
self.log(logging.CRITICAL,
'uncaught exception in worker: ' + traceback.format_exc())
finally:
# See the note in run_workers() above. clear_signal_handlers()
# calls signal.signal() which explicitly affects the current
# process, parent or child.
self.clear_signal_handlers() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance():
""" Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server with nginx + gunicorn """ |
# Record the starting time and print a starting message
start_time = time.time()
print(_green("Started..."))
# Use boto to create an EC2 instance
env.host_string = _create_ec2_instance()
print(_green("Waiting 30 seconds for server to boot..."))
time.sleep(30)
# Configure the instance that was just created
for item in tasks.configure_instance:
try:
print(_yellow(item['message']))
except KeyError:
pass
globals()["_" + item['action']](item['params'])
# Print out the final runtime and the public dns of the new instance
end_time = time.time()
print(_green("Runtime: %f minutes" % ((end_time - start_time) / 60)))
print(_green("\nPLEASE ADD ADDRESS THIS TO YOUR ")),
print(_yellow("project_conf.py")),
print(_green(" FILE UNDER ")),
print(_yellow("fabconf['EC2_INSTANCES'] : ")),
print(_green(env.host_string)) |
<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_task(task, start_message, finished_message):
""" Tasks a task from tasks.py and runs through the commands on the server """ |
# Get the hosts and record the start time
env.hosts = fabconf['EC2_INSTANCES']
start = time.time()
# Check if any hosts exist
if env.hosts == []:
print("There are EC2 instances defined in project_conf.py, please add some instances and try again")
print("or run 'fab spawn_instance' to create an instance")
return
# Print the starting message
print(_yellow(start_message))
# Run the task items
for item in task:
try:
print(_yellow(item['message']))
except KeyError:
pass
globals()["_" + item['action']](item['params'])
# Print the final message and the elapsed time
print(_yellow("%s in %.2fs" % (finished_message, time.time() - start))) |
<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, configurable, config=None, **kwargs):
'''Create a sub-object of this factory.
Instantiates the `configurable` object with the current saved
:attr:`config`. This essentially translates to
``configurable(**config)``, except services defined in the
parent and requested by `configurable` (by setting the
``services`` attribute) are injected. If a service is not
defined on this factory object, then a
:exc:`yakonfig.ProgrammerError` is raised.
If `config` is provided, it is a local configuration for
`configurable`, and it overrides the saved local configuration
(if any). If not provided, then :attr:`config` must already be
set, possibly by passing this object into the :mod:`yakonfig`
top-level setup sequence.
:param callable configurable: object to create
:param dict config: local configuration for `configurable`
:param kwargs: additional keyword parameters
:return: ``configurable(**config)``
'''
# If we got passed a string, find the thing to make.
if isinstance(configurable, string_types):
candidates = [ac for ac in self.sub_modules
if ac.config_name == configurable]
if len(candidates) == 0:
raise KeyError(configurable)
configurable = candidates[0]
# Regenerate the configuration if need be.
if not isinstance(configurable, AutoConfigured):
configurable = AutoConfigured.from_obj(configurable)
if config is None:
config = self.config.get(configurable.config_name, {})
# Iteratively build up the argument list. If you explicitly
# called this function with a config dictionary with extra
# parameters, those will be lost.
params = {}
for other, default in iteritems(configurable.default_config):
params[other] = kwargs.get(other, config.get(other, default))
for other in getattr(configurable, 'services', []):
# AutoConfigured.check_config() validates that this key
# wasn't in the global config, so this must have come from
# either our own config parameter, a keyword arg, or the
# caller setting factory.config; trust those paths.
if other == 'config':
params[other] = dict(config, **kwargs)
elif other in kwargs:
params[other] = kwargs[other]
elif other in config:
params[other] = config[other]
else:
# We're not catching an `AttributeError` exception
# here because it may case a net too wide which makes
# debugging underlying errors more difficult.
params[other] = getattr(self, other)
return configurable(**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 from_obj(cls, obj, any_configurable=False):
'''Create a proxy object from a callable.
If `any_configurable` is true, `obj` takes a parameter named
``config``, and `obj` smells like it implements
:class:`yakonfig.Configurable` (it has a
:attr:`~yakonfig.Configurable.config_name`), then return it
directly.
'''
discovered = cls.inspect_obj(obj)
if ((any_configurable and
'config' in discovered['required'] and
hasattr(obj, 'config_name'))):
return obj
return cls(obj, discovered['name'], discovered['required'],
discovered['defaults']) |
<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_config(self, config, name=''):
'''Check that the configuration for this object is valid.
This is a more restrictive check than for most :mod:`yakonfig`
objects. It will raise :exc:`yakonfig.ConfigurationError` if
`config` contains any keys that are not in the underlying
callable's parameter list (that is, extra unused configuration
options). This will also raise an exception if `config`
contains keys that duplicate parameters that should be
provided by the factory.
.. note:: This last behavior is subject to change; future
versions of the library may allow configuration to
provide local configuration for a factory-provided
object.
:param dict config: the parent configuration dictionary,
probably contains :attr:`config_name` as a key
:param str name: qualified name of this object in the configuration
:raise: :exc:`yakonfig.ConfigurationError` if excess parameters exist
'''
# This is assuming that `config` is the config dictionary of
# the *config parent*. That is, `config[self.config_name]`
# exists.
config = config.get(self.config_name, {})
# Complain about additional parameters, unless this is an
# older object that's expecting a config dictionary.
extras = set(config.keys()).difference(self.default_config)
if 'config' not in self.services and extras:
raise ConfigurationError(
'Unsupported config options for "%s": %s'
% (self.config_name, ', '.join(extras)))
# This only happens if you went out of your way to
# circumvent the configuration and delete a parameter.
missing = set(self.default_config).difference(config)
if missing:
raise ConfigurationError(
'Missing config options for "%s": %s'
% (self.config_name, ', '.join(missing)))
# Did caller try to provide parameter(s) that we also expect
# the factory to provide?
duplicates = set(config.keys()).intersection(set(self.services))
if duplicates:
# N.B. I don't think the parameter can come from the
# default config because Python will not let you have
# `arg` and `arg=val` in the same parameter
# list. (`discover_config`, below, guarantees that
# positional and named parameters are disjoint.)
raise ConfigurationError(
'Disallowed config options for "%s": %s'
% (self.config_name, ', '.join(duplicates))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inspect_obj(obj):
'''Learn what there is to be learned from our target.
Given an object at `obj`, which must be a function, method or
class, return a configuration *discovered* from the name of
the object and its parameter list. This function is
responsible for doing runtime reflection and providing
understandable failure modes.
The return value is a dictionary with three keys: ``name``,
``required`` and ``defaults``. ``name`` is the name of the
function/method/class. ``required`` is a list of parameters
*without* default values. ``defaults`` is a dictionary mapping
parameter names to default values. The sets of parameter names in
``required`` and ``defaults`` are disjoint.
When given a class, the parameters are taken from its ``__init__``
method.
Note that this function is purposefully conservative in the things
that is will auto-configure. All of the following things will result
in a :exc:`yakonfig.ProgrammerError` exception being raised:
1. A parameter list that contains tuple unpacking. (This is invalid
syntax in Python 3.)
2. A parameter list that contains variable arguments (``*args``) or
variable keyword words (``**kwargs``). This restriction forces
an auto-configurable to explicitly state all configuration.
Similarly, if given an object that isn't a function/method/class, a
:exc:`yakonfig.ProgrammerError` will be raised.
If reflection cannot be performed on ``obj``, then a ``TypeError``
is raised.
'''
skip_params = 0
if inspect.isfunction(obj):
name = obj.__name__
inspect_obj = obj
skip_params = 0
elif inspect.ismethod(obj):
name = obj.im_func.__name__
inspect_obj = obj
skip_params = 1 # self
elif inspect.isclass(obj):
inspect_obj = None
if hasattr(obj, '__dict__') and '__new__' in obj.__dict__:
inspect_obj = obj.__new__
elif hasattr(obj, '__init__'):
inspect_obj = obj.__init__
else:
raise ProgrammerError(
'Class "%s" does not have a "__new__" or "__init__" '
'method, so it cannot be auto configured.' % str(obj))
name = obj.__name__
if hasattr(obj, 'config_name'):
name = obj.config_name
if not inspect.ismethod(inspect_obj) \
and not inspect.isfunction(inspect_obj):
raise ProgrammerError(
'"%s.%s" is not a method/function (it is a "%s").'
% (str(obj), inspect_obj.__name__, type(inspect_obj)))
skip_params = 1 # self
else:
raise ProgrammerError(
'Expected a function, method or class to '
'automatically configure, but got a "%s" '
'(type: "%s").' % (repr(obj), type(obj)))
argspec = inspect.getargspec(inspect_obj)
if argspec.varargs is not None or argspec.keywords is not None:
raise ProgrammerError(
'The auto-configurable "%s" cannot contain '
'"*args" or "**kwargs" in its list of '
'parameters.' % repr(obj))
if not all(isinstance(arg, string_types) for arg in argspec.args):
raise ProgrammerError(
'Expected an auto-configurable with no nested '
'parameters, but "%s" seems to contain some '
'tuple unpacking: "%s"'
% (repr(obj), argspec.args))
defaults = argspec.defaults or []
# The index into `argspec.args` at which keyword arguments with default
# values starts.
i_defaults = len(argspec.args) - len(defaults)
return {
'name': name,
'required': argspec.args[skip_params:i_defaults],
'defaults': dict([(k, defaults[i])
for i, k in enumerate(argspec.args[i_defaults:])]),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modulepath(filename):
""" Find the relative path to its module of a python file if existing. filename string, name of a python file """ |
filepath = os.path.abspath(filename)
prepath = filepath[:filepath.rindex('/')]
postpath = '/'
if prepath.count('/') == 0 or not os.path.exists(prepath + '/__init__.py'):
flag = False
else:
flag = True
while True:
if prepath.endswith('/lib') or prepath.endswith('/bin') or prepath.endswith('/site-packages'):
break
elif flag and (prepath.count('/') == 0 or not os.path.exists(prepath + '/__init__.py')):
break
else:
for f in os.listdir(prepath):
if '.py' in f:
break
else:
break
postpath = prepath[prepath.rindex('/'):].split('-')[0].split('_')[0] + postpath
prepath = prepath[:prepath.rindex('/')]
return postpath.lstrip('/') + filename.split('/')[-1].replace('.pyc', '').replace('.py', '') + '/' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_message_type(message_type):
""" Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable version :rtype: str """ |
if message_type == MsgType.NOT_SET:
return "NOT_SET"
elif message_type == MsgType.ACK:
return "ACK"
elif message_type == MsgType.JOIN:
return "JOIN"
elif message_type == MsgType.UNJOIN:
return "UNJOIN"
elif message_type == MsgType.CONFIG:
return "CONFIG"
elif message_type == MsgType.UPDATE:
return "UPDATE"
elif message_type == MsgType.DATA:
return "DATA"
else:
return u"{}".format(message_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_data(data):
""" Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode """ |
if data is None:
return None
return u":".join([u"{:02x}".format(ord(c)) for c in 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 guess_message_type(message):
""" Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage :return: The corresponding message type (MsgType) or None if not found :rtype: None | int """ |
if isinstance(message, APPConfigMessage):
return MsgType.CONFIG
elif isinstance(message, APPJoinMessage):
return MsgType.JOIN
elif isinstance(message, APPDataMessage):
# All inheriting from this first !!
return MsgType.DATA
elif isinstance(message, APPUpdateMessage):
return MsgType.UPDATE
elif isinstance(message, APPUnjoinMessage):
return MsgType.UNJOIN
# APPMessage -> ACK?
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 timestamp_localize(value):
""" Save timestamp as utc :param value: Timestamp (in UTC or with tz_info) :type value: float | datetime.datetime :return: Localized timestamp :rtype: float """ |
if isinstance(value, datetime.datetime):
if not value.tzinfo:
value = pytz.UTC.localize(value)
else:
value = value.astimezone(pytz.UTC)
# Assumes utc (and add the microsecond part)
value = calendar.timegm(value.timetuple()) + \
value.microsecond / 1e6
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 set_timestamp_to_current(self):
""" Set timestamp to current time utc :rtype: None """ |
# Good form to add tzinfo
self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow()) |
<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, obj):
""" Set this instance up based on another instance :param obj: Instance to copy from :type obj: APPMessage :rtype: None """ |
if isinstance(obj, APPMessage):
self._header = obj._header
self._payload = obj._payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pack_people(people):
""" Pack people into a network transmittable format :param people: People to pack :type people: list[paps.people.People] :return: The packed people :rtype: str """ |
res = bytearray()
bits = bytearray([1])
for person in people:
bits.extend(person.to_bits())
aByte = 0
for i, bit in enumerate(bits[::-1]):
mod = i % 8
aByte |= bit << mod
if mod == 7 or i == len(bits) - 1:
res.append(aByte)
aByte = 0
return struct.pack(APPUpdateMessage.fmt.format(len(res)), *res[::-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_dynacRepr(cls, pynacRepr):
""" Construct a ``Quad`` instance from the Pynac lattice element """ |
L = float(pynacRepr[1][0][0])
B = float(pynacRepr[1][0][1])
aperRadius = float(pynacRepr[1][0][2])
return cls(L, B, aperRadius) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dynacRepresentation(self):
""" Return the Pynac representation of this quadrupole instance. """ |
return ['QUADRUPO', [[self.L.val, self.B.val, self.aperRadius.val]]] |
<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_dynacRepr(cls, pynacRepr):
""" Construct a ``CavityAnalytic`` instance from the Pynac lattice element """ |
cavID = int(pynacRepr[1][0][0])
xesln = float(pynacRepr[1][1][0])
phase = float(pynacRepr[1][1][1])
fieldReduction = float(pynacRepr[1][1][2])
isec = int(pynacRepr[1][1][3])
return cls(phase, fieldReduction, cavID, xesln, isec) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjustPhase(self, adjustment):
""" Adjust the accelerating phase of the cavity by the value of ``adjustment``. The adjustment is additive, so a value of ``scalingFactor = 0.0`` will result in no change of the phase. """ |
self.phase = self.phase._replace(val = self.phase.val + adjustment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scaleField(self, scalingFactor):
""" Adjust the accelerating field of the cavity by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field. """ |
oldField = self.fieldReduction.val
newField = 100.0 * (scalingFactor * (1.0 + oldField/100.0) - 1.0)
self.fieldReduction = self.fieldReduction._replace(val = newField) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.