code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def block_header_verify( block_data, prev_hash, block_hash ):
serialized_header = block_header_to_hex( block_data, prev_hash )
candidate_hash_bin_reversed = hashing.bin_double_sha256(binascii.unhexlify(serialized_header))
candidate_hash = binascii.hexlify( candidate_hash_bin_reversed[::-1] )
retur... | Verify whether or not bitcoind's block header matches the hash we expect. |
def block_verify( block_data ):
# verify block data txs
m = merkle.MerkleTree( block_data['tx'] )
root_hash = str(m.root())
return root_hash == str(block_data['merkleroot']) | Given block data (a dict with 'merkleroot' hex string and 'tx' list of hex strings--i.e.
a block compatible with bitcoind's getblock JSON RPC method), verify that the
transactions are consistent.
Return True on success
Return False if not. |
def btc_tx_output_parse_script( scriptpubkey ):
script_type = None
reqSigs = None
addresses = []
script_type = btc_script_classify(scriptpubkey)
script_tokens = btc_script_deserialize(scriptpubkey)
if script_type in ['p2pkh']:
script_type = "pubkeyhash"
reqSigs = 1... | Given the hex representation of a script,
turn it into a nice, easy-to-read dict.
The dict will have:
* asm: the disassembled script as a string
* hex: the raw hex (given as an argument)
* type: the type of script
Optionally, it will have:
* addresses: a list of addresses the script represe... |
def convert_code_to_value(M_c, cidx, code):
if M_c['column_metadata'][cidx]['modeltype'] == 'normal_inverse_gamma':
return float(code)
else:
try:
return M_c['column_metadata'][cidx]['value_to_code'][int(code)]
except KeyError:
return M_c['column_metadata'][ci... | For a column with categorical data, this function takes the 'code':
the integer used to represent a specific value, and returns the corresponding
raw value (e.g. 'Joe' or 234.23409), which is always encoded as a string.
Note that the underlying store 'value_to_code' is unfortunately named backwards.
TO... |
def convert_value_to_code(M_c, cidx, value):
if M_c['column_metadata'][cidx]['modeltype'] == 'normal_inverse_gamma':
return float(value)
else:
return M_c['column_metadata'][cidx]['code_to_value'][str(value)] | For a column with categorical data, this function takes the raw value
(e.g. 'Joe' or 234.23409), which is always encoded as a string, and returns the
'code': the integer used to represent that value in the underlying representation.
Note that the underlying store 'code_to_value' is unfortunately named back... |
def save(self, force=False):
if (not self._success) and (not force):
raise ConfigError((
'The config file appears to be corrupted:\n\n'
' {fname}\n\n'
'Before attempting to save the configuration, please either '
'fix the co... | Saves the configuration to a JSON, in the standard config location.
Args:
force (Optional[:obj:`bool`]): Continue writing, even if the original
config file was not loaded properly. This is dangerous, because
it could cause the previous configuration options to be los... |
def reset(self):
self._options = {}
self.save(force=True)
self._success = True | Resets the configuration, and overwrites the existing configuration
file. |
def get_sys_info():
"Returns system information as a dict"
blob = []
# commit = cc._git_hash
# blob.append(('commit', commit))
try:
(sysname, nodename, release, version,
machine, processor) = platform.uname()
blob.extend([
("python", "%d.%d.%d.%s.%s" % sys.ver... | Returns system information as a dict |
def get_block_info(self):
if not self.finished:
raise Exception("Not finished downloading")
ret = []
for (block_hash, block_data) in self.block_info.items():
ret.append( (block_data['height'], block_data['txns']) )
return ret | Get the retrieved block information.
Return [(height, [txs])] on success, ordered on height
Raise if not finished downloading |
def run( self ):
log.debug("Segwit support: {}".format(get_features('segwit')))
self.begin()
try:
self.loop()
except socket.error, se:
if not self.finished:
# unexpected
log.exception(se)
return F... | Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
The order of operations is:
* send version
* receive version
* send verack
* send getdata
* receive blocks
* for each block:
* for each transa... |
def have_all_block_data(self):
if not (self.num_blocks_received == self.num_blocks_requested):
log.debug("num blocks received = %s, num requested = %s" % (self.num_blocks_received, self.num_blocks_requested))
return False
return True | Have we received all block data? |
def block_data_sanity_checks(self):
assert self.have_all_block_data(), "Still missing block data"
assert self.num_txs_received == len(self.sender_info.keys()), "Num TXs received: %s; num TXs requested: %s" % (self.num_txs_received, len(self.sender_info.keys()))
for (block_hash, block_i... | Verify that the data we received makes sense.
Return True on success
Raise on error |
def begin(self):
log.debug("handshake (version %s)" % PROTOCOL_VERSION)
version = Version()
version.services = 0 # can't send blocks
log.debug("send Version")
self.send_message(version) | This method will implement the handshake of the
Bitcoin protocol. It will send the Version message,
and block until it receives a VerAck.
Once we receive the version, we'll send the verack,
and begin downloading. |
def handle_version(self, message_header, message):
log.debug("handle version")
verack = VerAck()
log.debug("send VerAck")
self.send_message(verack)
self.verack = True
start_block_height = sorted(self.blocks.keys())[0]
if start_block_height < 1:
... | This method will handle the Version message and
will send a VerAck message when it receives the
Version message.
:param message_header: The Version message header
:param message: The Version message |
def handle_inv(self, message_header, inv_packet ):
log.debug("handle inv of %s item(s)" % len(inv_packet.inventory))
reply_inv = []
for inv_info in inv_packet.inventory:
inv_hash = "%064x" % inv_info.inv_hash
if inv_info.inv_type == INVENTORY_TYPE["MSG_BLOCK"]:... | Get the data we just requested.
Shouldn't happen with newer servers, since they use
getheaders/headers followed by getdata/blocks
(older peers use getblocks/inv/getdata/inv exchanges) |
def add_sender_info( self, sender_txhash, nulldata_vin_outpoint, sender_out_data ):
assert sender_txhash in self.sender_info.keys(), "Missing sender info for %s" % sender_txhash
assert nulldata_vin_outpoint in self.sender_info[sender_txhash], "Missing outpoint %s for sender %s" % (nulldata_vin_... | Record sender information in our block info.
@sender_txhash: txid of the sender
@nulldata_vin_outpoint: the 'vout' index from the nulldata tx input that this transaction funded |
def parse_tx( self, txn, block_header, block_hash, txindex ):
txn_serializer = TxSerializer()
tx_bin = txn_serializer.serialize(txn)
txdata = {
"version": txn.version,
"locktime": txn.lock_time,
"hex": binascii.hexlify( tx_bin ),
"txid":... | Given a transaction message and its index in the block,
go and create a "verbose" transaction structure
containing all the information in a nice, easy-to-read
dict (i.e. like what bitcoind would give us).
Does not work on coinbase transactions.
Does not include segwit witnesses |
def make_sender_info( self, block_hash, txn, i, block_height ):
inp = txn['ins'][i]
ret = {
# to be filled in...
'scriptPubKey': None,
'addresses': None,
# for matching the input and sender funded
"txindex": txn['txindex'],
... | Make sender information bundle for a particular input of
a nulldata transaction.
We'll use it to go find the transaction output that
funded the ith input of the given tx. |
def check_config(config):
'''
Check the executor config file for consistency.
'''
# Check server URL
url = config.get("Server", "url")
try:
urlopen(url)
except Exception as e:
logger.error(
"The configured OpenSubmit server URL ({0}) seems to be invalid: {1}".... | Check the executor config file for consistency. |
def has_config(config_fname):
'''
Determine if the given config file exists.
'''
config = RawConfigParser()
try:
config.readfp(open(config_fname))
return True
except IOError:
return Falsf has_config(config_fname):
'''
Determine if the given config file exists.
... | Determine if the given config file exists. |
def create_config(config_fname, override_url=None):
'''
Create the config file from the defaults under the given name.
'''
config_path = os.path.dirname(config_fname)
os.makedirs(config_path, exist_ok=True)
# Consider override URL. Only used by test suite runs
settings = DEFAULT_SETTINGS_FL... | Create the config file from the defaults under the given name. |
def make_student(user):
'''
Makes the given user a student.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = False
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.remove(user)
tutor_group.save(f ... | Makes the given user a student. |
def make_tutor(user):
'''
Makes the given user a tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.remove(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save(f make_tut... | Makes the given user a tutor. |
def make_owner(user):
'''
Makes the given user a owner and tutor.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = False
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save(f m... | Makes the given user a owner and tutor. |
def make_admin(user):
'''
Makes the given user an admin.
'''
tutor_group, owner_group = _get_user_groups()
user.is_staff = True
user.is_superuser = True
user.save()
owner_group.user_set.add(user)
owner_group.save()
tutor_group.user_set.add(user)
tutor_group.save(f make_admin(... | Makes the given user an admin. |
def _get_username_hostname():
'''Best attempt to get username and hostname, returns "na" if problem.'''
user = 'na'
host = 'na'
try:
user = getpass.getuser()
except Exception:
pass
try:
host = socket.gethostname()
except Exception:
pass
return user, hosf _... | Best attempt to get username and hostname, returns "na" if problem. |
def sort_dict(key_counts, by_key=False):
'''Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values.
If by_key=True, sorts by dict key.'''
sort_key = lambda x: (-1 * x[1], x[0])
if by_key:
sort_key = lambda x: x[0]
return sorted(key_counts.items(), k... | Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values.
If by_key=True, sorts by dict key. |
def filter(self, base_collection):
'''Yields subset of base_collection/generator based on filters.'''
for item in base_collection:
excluded = []
for (name, exclude) in self._filters:
if exclude(item):
excluded.append(name)
if exclud... | Yields subset of base_collection/generator based on filters. |
def get_user_details(self, response):
data = {}
# None of them is mandatory
data['id'] = response.get('user_id', None)
data['username'] = response.get('custom_username', None)
if not data['username']:
data['username'] = response.get('ext_user_username', None)... | Complete with additional information from original LTI POST data, as available. |
def user_unicode(self):
'''
Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations.
'''
if self.ema... | Monkey patch for getting better user name stringification,
user proxies did not make the job.
Django's custom user model feature would have needed to be introduced
before the first syncdb, which does not work for existing installations. |
def move_user_data(primary, secondary):
'''
Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys.
'''
# Update all submission authorships of the secondary to the primary
submissions = Submission... | Moves all submissions and other data linked to the secondary user into the primary user.
Nothing is deleted here, we just modify foreign user keys. |
def add_course_safe(self, id):
'''
Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception.
'''
course = get_object_or_404(Course, pk=int(id), active=True)
if course not in self.courses.all():
... | Adds a course for the user after conducting a set of sanity checks.
Return the title of the course or an exception. |
def tutor_courses(self):
'''
Returns the list of courses this user is tutor or owner for.
'''
tutoring = self.user.courses_tutoring.all().filter(active__exact=True)
owning = self.user.courses.all().filter(active__exact=True)
result = (tutoring | owning).distinct()
... | Returns the list of courses this user is tutor or owner for. |
def user_courses(self):
'''
Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership.
'''
registered = self.courses.filter(active__exact=True).distin... | Returns the list of courses this user is subscribed for,
or owning, or tutoring.
This leads to the fact that tutors and owners don't need
course membership. |
def gone_assignments(self):
'''
Returns the list of past assignments the user did not submit for
before the hard deadline.
'''
# Include only assignments with past hard deadline
qs = Assignment.objects.filter(hard_deadline__lt=timezone.now())
# Include onl... | Returns the list of past assignments the user did not submit for
before the hard deadline. |
def _build_message(self, to, text, subject=None, mtype=None, unsubscribe_url=None):
# TODO Maybe file attachments handling through `files` message_model context var.
if subject is None:
subject = u'%s' % _('No Subject')
if mtype == 'html':
msg = self.mime_multi... | Constructs a MIME message from message and dispatch models. |
def _social_auth_login(self, request, **kwargs):
'''
View function that redirects to social auth login,
in case the user is not logged in.
'''
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
else... | View function that redirects to social auth login,
in case the user is not logged in. |
def get_queryset(self, request):
''' Restrict the listed courses for the current user.'''
qs = super(CourseAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).dist... | Restrict the listed courses for the current user. |
def _rank_tags(tagged_paired_aligns):
'''Return the list of tags ranked from most to least popular.'''
tag_count_dict = defaultdict(int)
for paired_align in tagged_paired_aligns:
tag_count_dict[paired_align.umt] += 1
tags_by_count = utils.sort_dict(tag_count_dict)
ranked_tags = [tag_count[0]... | Return the list of tags ranked from most to least popular. |
def schedule_email(message, to, subject=None, sender=None, priority=None):
if SHORTCUT_EMAIL_MESSAGE_TYPE:
message_cls = get_registered_message_type(SHORTCUT_EMAIL_MESSAGE_TYPE)
else:
if isinstance(message, dict):
message_cls = EmailHtmlMessage
else:
messa... | Schedules an email message for delivery.
:param dict, str message: str or dict: use str for simple text email;
dict - to compile email from a template (default: `sitemessage/messages/email_html__smtp.html`).
:param list|str|unicode to: recipients addresses or Django User model heir instances
:param... |
def schedule_jabber_message(message, to, sender=None, priority=None):
schedule_messages(message, recipients('xmppsleek', to), sender=sender, priority=priority) | Schedules Jabber XMPP message for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `email` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overri... |
def schedule_tweet(message, to='', sender=None, priority=None):
schedule_messages(message, recipients('twitter', to), sender=sender, priority=priority) | Schedules a Tweet for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes.
If supplied tweets will be @-replies.
:param User sender: User model heir instance
:param int priority: number descr... |
def schedule_telegram_message(message, to, sender=None, priority=None):
schedule_messages(message, recipients('telegram', to), sender=sender, priority=priority) | Schedules Telegram message for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overri... |
def schedule_facebook_message(message, sender=None, priority=None):
schedule_messages(message, recipients('fb', ''), sender=sender, priority=priority) | Schedules Facebook wall message for delivery.
:param str message: text or URL to publish.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overrides priority provided with message type. |
def schedule_vkontakte_message(message, to, sender=None, priority=None):
schedule_messages(message, recipients('vk', to), sender=sender, priority=priority) | Schedules VKontakte message for delivery.
:param str message: text or URL to publish on wall.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `vk` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. ... |
def get_alias(cls):
if cls.alias is None:
cls.alias = cls.__name__
return cls.alias | Returns messenger alias.
:return: str
:rtype: str |
def before_after_send_handling(self):
self._init_delivery_statuses_dict()
self.before_send()
try:
yield
finally:
self.after_send()
self._update_dispatches() | Context manager that allows to execute send wrapped
in before_send() and after_send(). |
def _structure_recipients_data(cls, recipients):
try: # That's all due Django 1.7 apps loading.
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
except ImportError:
# Django 1.4 fallback.
from django.contrib.auth.model... | Converts recipients data into a list of Recipient objects.
:param list recipients: list of objects
:return: list of Recipient
:rtype: list |
def mark_error(self, dispatch, error_log, message_cls):
if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:
self.mark_failed(dispatch, error_log)
else:
dispatch.error_log = error_log
self._st['error'].ap... | Marks a dispatch as having error or consequently as failed
if send retry limit for that message type is exhausted.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: error message
:param MessageBase message_cls: MessageBase heir |
def mark_failed(self, dispatch, error_log):
dispatch.error_log = error_log
self._st['failed'].append(dispatch) | Marks a dispatch as failed.
Sitemessage won't try to deliver already failed messages.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: str - error message |
def _process_messages(self, messages, ignore_unknown_message_types=False):
with self.before_after_send_handling():
for message_id, message_data in messages.items():
message_model, dispatch_models = message_data
try:
message_cls = get_regis... | Performs message processing.
:param dict messages: indexed by message id dict with messages data
:param bool ignore_unknown_message_types: whether to silence exceptions
:raises UnknownMessageTypeError: |
def _update_dispatches(self):
Dispatch.log_dispatches_errors(self._st['error'] + self._st['failed'])
Dispatch.set_dispatches_statuses(**self._st)
self._init_delivery_statuses_dict() | Updates dispatched data in DB according to information gather by `mark_*` methods, |
def setup(self, app):
'''
Make sure that other installed plugins don't affect the same keyword argument.
'''
for other in app.plugins:
if not isinstance(other, MySQLPlugin):
continue
if other.keyword == self.keyword:
raise PluginErr... | Make sure that other installed plugins don't affect the same keyword argument. |
def assign_role(backend, user, response, *args, **kwargs):
'''
Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group.
'''
if backend.name is 'passthrough' and settings.DEMO is True and 'role' in kwargs['request'].session[passthrough.SESSION_VAR]:
... | Part of the Python Social Auth Pipeline.
Checks if the created demo user should be pushed into some group. |
def fetch(url, fullpath):
'''
Fetch data from an URL and save it under the given target name.
'''
logger.debug("Fetching %s from %s" % (fullpath, url))
try:
tmpfile, headers = urlretrieve(url)
if os.path.exists(fullpath):
os.remove(fullpath)
shutil.move(tmpfile, ... | Fetch data from an URL and save it under the given target name. |
def send_post(config, urlpath, post_data):
'''
Send POST data to an OpenSubmit server url path,
according to the configuration.
'''
server = config.get("Server", "url")
logger.debug("Sending executor payload to " + server)
post_data = urlencode(post_data)
post_data = post_data.encode("ut... | Send POST data to an OpenSubmit server url path,
according to the configuration. |
def send_hostinfo(config):
'''
Register this host on OpenSubmit test machine.
'''
info = all_host_infos()
logger.debug("Sending host information: " + str(info))
post_data = [("Config", json.dumps(info)),
("Action", "get_config"),
("UUID", config.get("Server", "u... | Register this host on OpenSubmit test machine. |
def compatible_api_version(server_version):
'''
Check if this server API version is compatible to us.
'''
try:
semver = server_version.split('.')
if semver[0] != '1':
logger.error(
'Server API version (%s) is too new for us. Please update the executor installa... | Check if this server API version is compatible to us. |
def run_configure(self, mandatory=True):
if not has_file(self.working_dir, 'configure'):
if mandatory:
raise FileNotFoundError(
"Could not find a configure script for execution.")
else:
return
try:
prog = Ru... | Runs the 'configure' program in the working directory.
Args:
mandatory (bool): Throw exception if 'configure' fails or a
'configure' file is missing. |
def run_compiler(self, compiler=GCC, inputs=None, output=None):
# Let exceptions travel through
prog = RunningProgram(self, *compiler_cmdline(compiler=compiler,
inputs=inputs,
output=outp... | Runs a compiler in the working directory.
Args:
compiler (tuple): The compiler program and its command-line arguments,
including placeholders for output and input files.
inputs (tuple): The list of input files for the compiler.
output (str): ... |
def run_build(self, compiler=GCC, inputs=None, output=None):
logger.info("Running build steps ...")
self.run_configure(mandatory=False)
self.run_make(mandatory=False)
self.run_compiler(compiler=compiler,
inputs=inputs,
output=o... | Combined call of 'configure', 'make' and the compiler.
The success of 'configure' and 'make' is optional.
The arguments are the same as for run_compiler. |
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
logger.debug("Spawning program for interaction ...")
if exclusive:
kill_longrunning(self.config)
return RunningProgram(self, name, arguments, timeout) | Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the progra... |
def run_program(self, name, arguments=[], timeout=30, exclusive=False):
logger.debug("Running program ...")
if exclusive:
kill_longrunning(self.config)
prog = RunningProgram(self, name, arguments, timeout)
return prog.expect_end() | Runs a program in the working directory to completion.
Args:
name (str): The name of the program to be executed.
arguments (tuple): Command-line arguments for the program.
timeout (int): The timeout for execution.
exclusive (bool): Prevent parallel va... |
def grep(self, regex):
matches = []
logger.debug("Searching student files for '{0}'".format(regex))
for fname in self.student_files:
if os.path.isfile(self.working_dir + fname):
for line in open(self.working_dir + fname, 'br'):
if re.searc... | Scans the student files for text patterns.
Args:
regex (str): Regular expression used for scanning inside the files.
Returns:
tuple: Names of the matching files in the working directory. |
def ensure_files(self, filenames):
logger.debug("Testing {0} for the following files: {1}".format(
self.working_dir, filenames))
dircontent = os.listdir(self.working_dir)
for fname in filenames:
if fname not in dircontent:
return False
ret... | Checks the student submission for specific files.
Args:
filenames (tuple): The list of file names to be cjecked for.
Returns:
bool: Indicator if all files are found in the student archive. |
def live_chat_banner(context):
context = copy(context)
# Find any upcoming or current live chat. The Chat date must be less than 5
# days away, or currently in progress.
oldchat = LiveChat.chat_finder.get_last_live_chat()
if oldchat:
context['last_live_chat'] = {
'title':... | Display any available live chats as advertisements. |
def get_exitstatus(self):
logger.debug("Exit status is {0}".format(self._spawn.exitstatus))
return self._spawn.exitstatus | Get the exit status of the program execution.
Returns:
int: Exit status as reported by the operating system,
or None if it is not available. |
def expect_output(self, pattern, timeout=-1):
logger.debug("Expecting output '{0}' from '{1}'".format(pattern, self.name))
try:
return self._spawn.expect(pattern, timeout)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
... | Wait until the running program performs some given output, or terminates.
Args:
pattern: The pattern the output should be checked for.
timeout (int): How many seconds should be waited for the output.
The pattern argument may be a string, a compiled regular expression,
... |
def sendline(self, text):
logger.debug("Sending input '{0}' to '{1}'".format(text, self.name))
try:
return self._spawn.sendline(text)
except pexpect.exceptions.EOF as e:
logger.debug("Raising termination exception.")
raise TerminationException(instanc... | Sends an input line to the running program, including os.linesep.
Args:
text (str): The input text to be send.
Raises:
TerminationException: The program terminated before / while / after sending the input.
NestedException: An internal problem occured while waiting ... |
def expect_end(self):
logger.debug("Waiting for termination of '{0}'".format(self.name))
try:
# Make sure we fetch the last output bytes.
# Recommendation from the pexpect docs.
self._spawn.expect(pexpect.EOF)
self._spawn.wait()
dircon... | Wait for the running program to finish.
Returns:
A tuple with the exit code, as reported by the operating system, and the output produced. |
def expect_exitstatus(self, exit_status):
self.expect_end()
logger.debug("Checking exit status of '{0}', output so far: {1}".format(
self.name, self.get_output()))
if self._spawn.exitstatus is None:
raise WrongExitStatusException(
instance=self, e... | Wait for the running program to finish and expect some exit status.
Args:
exit_status (int): The expected exit status.
Raises:
WrongExitStatusException: The produced exit status is not the expected one. |
def unsubscribe(request, message_id, dispatch_id, hashed, redirect_to=None):
return _generic_view(
'handle_unsubscribe_request', sig_unsubscribe_failed,
request, message_id, dispatch_id, hashed, redirect_to=redirect_to
) | Handles unsubscribe request.
:param Request request:
:param int message_id:
:param int dispatch_id:
:param str hashed:
:param str redirect_to:
:return: |
def mark_read(request, message_id, dispatch_id, hashed, redirect_to=None):
if redirect_to is None:
redirect_to = get_static_url('img/sitemessage/blank.png')
return _generic_view(
'handle_mark_read_request', sig_mark_read_failed,
request, message_id, dispatch_id, hashed, redirect_to... | Handles mark message as read request.
:param Request request:
:param int message_id:
:param int dispatch_id:
:param str hashed:
:param str redirect_to:
:return: |
def schedule_messages(messages, recipients=None, sender=None, priority=None):
if not is_iterable(messages):
messages = (messages,)
results = []
for message in messages:
if isinstance(message, six.string_types):
message = PlainTextMessage(message)
resulting_priority... | Schedules a message or messages.
:param MessageBase|str|list messages: str or MessageBase heir or list - use str to create PlainTextMessage.
:param list|None recipients: recipients addresses or Django User model heir instances
If `None` Dispatches should be created before send using `prepare_dispatches... |
def send_scheduled_messages(priority=None, ignore_unknown_messengers=False, ignore_unknown_message_types=False):
dispatches_by_messengers = Dispatch.group_by_messengers(Dispatch.get_unsent(priority=priority))
for messenger_id, messages in dispatches_by_messengers.items():
try:
messenge... | Sends scheduled messages.
:param int, None priority: number to limit sending message by this priority.
:param bool ignore_unknown_messengers: to silence UnknownMessengerError
:param bool ignore_unknown_message_types: to silence UnknownMessageTypeError
:raises UnknownMessengerError:
:raises UnknownM... |
def check_undelivered(to=None):
failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()
if failed_count:
from sitemessage.shortcuts import schedule_email
from sitemessage.messages.email import EmailTextMessage
if to is None:
admi... | Sends a notification email if any undelivered dispatches.
Returns undelivered (failed) dispatches count.
:param str|unicode to: Recipient address. If not set Django ADMINS setting is used.
:rtype: int |
def cleanup_sent_messages(ago=None, dispatches_only=False):
filter_kwargs = {
'dispatch_status': Dispatch.DISPATCH_STATUS_SENT,
}
objects = Dispatch.objects
if ago:
filter_kwargs['time_dispatched__lte'] = timezone.now() - timedelta(days=int(ago))
dispatch_map = dict(objects.f... | Cleans up DB : removes delivered dispatches (and messages).
:param int ago: Days. Allows cleanup messages sent X days ago. Defaults to None (cleanup all sent).
:param bool dispatches_only: Remove dispatches only (messages objects will stay intact). |
def prepare_dispatches():
dispatches = []
target_messages = Message.get_without_dispatches()
cache = {}
for message_model in target_messages:
if message_model.cls not in cache:
message_cls = get_registered_message_type(message_model.cls)
subscribers = message_cls.... | Automatically creates dispatches for messages without them.
:return: list of Dispatch
:rtype: list |
def set_user_preferences_from_request(request):
prefs = []
for pref in request.POST.getlist(_PREF_POST_KEY):
message_alias, messenger_alias = pref.split(_ALIAS_SEP)
try:
get_registered_message_type(message_alias)
get_registered_messenger_object(messenger_alias)
... | Sets user subscription preferences using data from a request.
Expects data sent by form built with `sitemessage_prefs_table` template tag.
:param request:
:rtype: bool
:return: Flag, whether prefs were found in the request. |
def get_sitemessage_urls():
url_unsubscribe = url(
r'^messages/unsubscribe/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<hashed>[^/]+)/$',
unsubscribe,
name='sitemessage_unsubscribe'
)
url_mark_read = url(
r'^messages/ping/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<has... | Returns sitemessage urlpatterns, that can be attached to urlpatterns of a project:
# Example from urls.py.
from sitemessage.toolbox import get_sitemessage_urls
urlpatterns = patterns('',
# Your URL Patterns belongs here.
) + get_sitemessage_urls() # Now attaching additio... |
def gradings(gradingScheme):
''' Determine the list of gradings in this scheme as rendered string.
TODO: Use nice little icons instead of (p) / (f) marking.
'''
result = []
for grading in gradingScheme.gradings.all():
if grading.means_passed:
result.append(str(grading) + " (p... | Determine the list of gradings in this scheme as rendered string.
TODO: Use nice little icons instead of (p) / (f) marking. |
def formfield_for_dbfield(self, db_field, **kwargs):
''' Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all.'''
if db_field.name == "gradings":
request=kwargs['request']
try:
#TODO: MockRequst object fro... | Offer only gradings that are not used by other schemes, which means they are used by this scheme or not at all. |
def store_report_link(backend, user, response, *args, **kwargs):
'''
Part of the Python Social Auth Pipeline.
Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later.
'''
if backend.name is 'lti':
assignment_pk = response.get('assignment_pk', None)
... | Part of the Python Social Auth Pipeline.
Stores the result service URL reported by the LMS / LTI tool consumer so that we can use it later. |
def current_livechat(request):
result = {}
livechat = LiveChat.chat_finder.get_current_live_chat()
if livechat:
result['live_chat'] = {}
result['live_chat']['current_live_chat'] = livechat
can_comment, reason_code = livechat.can_comment(request)
result['live_chat']['can_... | Checks if a live chat is currently on the go, and add it to the request
context.
This is to allow the AskMAMA URL in the top-navigation to be redirected to
the live chat object view consistently, and to make it available to the
views and tags that depends on it. |
def upload_path(instance, filename):
'''
Sanitize the user-provided file name, add timestamp for uniqness.
'''
filename = filename.replace(" ", "_")
filename = unicodedata.normalize('NFKD', filename).lower()
return os.path.join(str(timezone.now().date().isoformat()), filenamef upload_path(i... | Sanitize the user-provided file name, add timestamp for uniqness. |
def is_archive(self):
'''
Determines if the attachment is an archive.
'''
try:
if zipfile.is_zipfile(self.attachment.path) or tarfile.is_tarfile(self.attachment.path):
return True
except Exception:
pass
return Falsf is_archive(s... | Determines if the attachment is an archive. |
def auth_complete(self, *args, **kwargs):
if SESSION_VAR not in self.strategy.request.session:
# This is the only protection layer when people
# go directly to the passthrough login view.
logger.warn("Auth data for passthrough provider not found in session. Raising 4... | Completes loging process, must return user instance |
def get_user_details(self, response):
result = {
'id': response['id'],
'username': response.get('username', None),
'email': response.get('email', None),
'first_name': response.get('first_name', None),
'last_name': response.get('last_name', Non... | Complete with additional information from session, as available. |
def paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
... | Given a BAM file, return a generator that yields filtered, paired reads |
def total_align_count(bam_filepath):
'''Returns count of all mapped alignments in input BAM (based on index)'''
count = 0
for line in idxstats(bam_filepath):
if line:
chrom, _, mapped, unmapped = line.strip().split('\t')
if chrom != '*':
count += int(mapped) +... | Returns count of all mapped alignments in input BAM (based on index) |
def _balanced_strand_gen(base_aligns, limit):
'''given collection of random {aligns}, returns alternating forward/reverse
strands up to {total_aligns}; will return smaller of forward/reverse
collection if less than total_aligns'''
predicate=lambda align: align.is_reverse
gen1, gen2 = itertools.tee((... | given collection of random {aligns}, returns alternating forward/reverse
strands up to {total_aligns}; will return smaller of forward/reverse
collection if less than total_aligns |
def ipaddress():
'''
Determine our own IP adress.
This seems to be far more complicated than you would think:
'''
try:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("gmail.com", 80))
result = s.getsockname()[0]
s.close()
... | Determine our own IP adress.
This seems to be far more complicated than you would think: |
def opencl():
'''
Determine some system information about the installed OpenCL device.
'''
result = []
try:
import pyopencl as ocl
for plt in ocl.get_platforms():
result.append("Platform: " + platform.name)
for device in plt.get_devices():
... | Determine some system information about the installed OpenCL device. |
def all_host_infos():
'''
Summarize all host information.
'''
output = []
output.append(["Operating system", os()])
output.append(["CPUID information", cpu()])
output.append(["CC information", compiler()])
output.append(["JDK information", from_cmd("java -version")])
output.appen... | Summarize all host information. |
def _completed_families(self, reference_name, rightmost_boundary):
'''returns one or more families whose end < rightmost boundary'''
in_progress = self._right_coords_in_progress[reference_name]
while len(in_progress):
right_coord = in_progress[0]
if right_coord < rightmos... | returns one or more families whose end < rightmost boundary |
def build_usage_logger(self, log):
'''Return a method that logs progress/mem usage.'''
def _log_usage():
log.debug("{}mb peak memory", peak_memory())
log.debug("{} pending alignment pairs; {} peak pairs",
self.pending_pair_count,
self.p... | Return a method that logs progress/mem usage. |
def graded_submissions(self):
'''
Queryset for the graded submissions, which are worth closing.
'''
qs = self._valid_submissions().filter(state__in=[Submission.GRADED])
return qf graded_submissions(self):
'''
Queryset for the graded submissions, which are ... | Queryset for the graded submissions, which are worth closing. |
def authors(self):
'''
Queryset for all distinct authors this course had so far. Important for statistics.
Note that this may be different from the list of people being registered for the course,
f.e. when they submit something and the leave the course.
'''
qs... | Queryset for all distinct authors this course had so far. Important for statistics.
Note that this may be different from the list of people being registered for the course,
f.e. when they submit something and the leave the course. |
def _init_groups(self, string):
taf_group_pattern = """
(?:FM|(?:PROB(?:\d{1,2})\s*(?:TEMPO)?)|TEMPO|BECMG|[\S\s])[A-Z0-9\+\-/\s$]+?(?=FM|PROB|TEMPO|BECMG|$)
"""
group_list = []
groups = re.findall(taf_group_pattern, string, re.VERBOSE)
if not groups:
... | Extracts weather groups (FM, PROB etc.) and populates group list
Args:
TAF report string
Raises:
MalformedTAF: Group decoding error |
def post_user_login(sender, request, user, **kwargs):
logger.debug("Running post-processing for user login.")
# Users created by social login or admins have no profile.
# We fix that during their first login.
try:
with transaction.atomic():
profile, created = UserProfile.objects... | Create a profile for the user, when missing.
Make sure that all neccessary user groups exist and have the right permissions.
We need that automatism for people not calling the configure tool,
admin rights for admins after the first login, and similar cases. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.