code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def buildpack(self, url):
cmd = ["heroku", "buildpacks:add", url, "--app", self.name]
self._run(cmd) | Add a buildpack by URL. |
def route(self):
dst = self.dst
if isinstance(dst, Gen):
dst = next(iter(dst))
return conf.route6.route(dst) | Used to select the L2 address |
def _handle_tag_removeobject(self):
obj = _make_object("RemoveObject")
obj.CharacterId = unpack_ui16(self._src)
obj.Depth = unpack_ui16(self._src)
return obj | Handle the RemoveObject tag. |
def __get_nondirect_init(self, init):
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
crc |= self.MSB_Mask
return crc & self.Mask | return the non-direct init if the direct algorithm has been selected. |
def call(exe, *argv):
exes = which(exe)
if not exes:
returnValue(None)
stdout, stderr, value = yield getProcessOutputAndValue(
exes[0], argv, env=os.environ.copy()
)
if value:
returnValue(None)
returnValue(stdout.decode('utf-8').rstrip('\n')) | Run a command, returning its output, or None if it fails. |
def replace_in_files(search, replace, depth=0, paths=None, confirm=True):
if paths==None:
paths = _s.dialogs.MultipleFiles('DIS AND DAT|*.*')
if paths == []: return
for path in paths:
lines = read_lines(path)
if depth: N=min(len(lines),depth)
else: N=len(lines)
fo... | Does a line-by-line search and replace, but only up to the "depth" line. |
def update_repository_configuration(id, external_repository=None, prebuild_sync=None):
to_update_id = id
rc_to_update = pnc_api.repositories.get_specific(id=to_update_id).content
if external_repository is None:
external_repository = rc_to_update.external_url
else:
rc_to_update.external_u... | Update an existing RepositoryConfiguration with new information |
def dump_raw(self, text, stream=None):
encrypted = self.vault.encrypt(text)
if stream:
stream.write(encrypted)
else:
return encrypted | Encrypt raw data and write to stream. |
def makeProductPicker(self):
productPicker = liveform.LiveForm(
self.coerceProduct,
[liveform.Parameter(
str(id(product)),
liveform.FORM_INPUT,
liveform.LiveForm(
lambda selectedProduct, product=product: selectedProduct and product,... | Make a LiveForm with radio buttons for each Product in the store. |
def reset(self):
for alternative in self.alternatives:
alternative.reset()
self.reset_winner()
self.increment_version() | Delete all data for this experiment. |
def stop_trial(self, trial_id):
response = requests.put(
urljoin(self._path, "trials/{}".format(trial_id)))
return self._deserialize(response) | Requests to stop trial by trial_id. |
def train_position_scales(self, layout, layers):
_layout = layout.layout
panel_scales_x = layout.panel_scales_x
panel_scales_y = layout.panel_scales_y
for layer in layers:
data = layer.data
match_id = match(data['PANEL'], _layout['PANEL'])
if panel_sca... | Compute ranges for the x and y scales |
def start(self):
self._configs = self._client.config_get('slow-*')
self._client.config_set('slowlog-max-len', 100000)
self._client.config_set('slowlog-log-slower-than', 0)
self._client.execute_command('slowlog', 'reset') | Get ready for a profiling run |
def _pretty_type(s, offset=0):
tc = s[offset]
if tc == "V":
return "void"
elif tc == "Z":
return "boolean"
elif tc == "C":
return "char"
elif tc == "B":
return "byte"
elif tc == "S":
return "short"
elif tc == "I":
return "int"
elif tc == "J... | returns the pretty version of a type code |
def trunk(self, unique=True):
unique = False
res = []
if self.children:
if self.name is not None:
res.append(self)
for child in self.children:
for sub_child in child.trunk(unique=unique):
if not unique or sub_child not i... | Get the trunk of the tree starting at this root. |
def should_be_hidden_as_cause(exc):
from valid8.validation_lib.types import HasWrongType, IsWrongType
return isinstance(exc, (HasWrongType, IsWrongType)) | Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error |
def _flatten_mesh(self, Xs, term):
n = Xs[0].size
if self.terms[term].istensor:
terms = self.terms[term]
else:
terms = [self.terms[term]]
X = np.zeros((n, self.statistics_['m_features']))
for term_, x in zip(terms, Xs):
X[:, term_.feature] = x.... | flatten the mesh and distribute into a feature matrix |
def _fuzzdb_integers(limit=0):
'Helper to grab some integers from fuzzdb'
path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt')
stream = _open_fuzzdb_file(path)
for line in _limit_helper(stream, limit):
yield int(line.decode('utf-8'), 0) | Helper to grab some integers from fuzzdb |
def generate(env):
global TeXLaTeXAction
if TeXLaTeXAction is None:
TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction,
strfunction=TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
generate_common(env)
from . import dvi
dvi.ge... | Add Builders and construction variables for TeX to an Environment. |
def flipHorizontal(self):
self.flipH = not self.flipH
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) | flips an image object horizontally |
def part(self, channels, message=""):
self.send_items('PART', ','.join(always_iterable(channels)), message) | Send a PART command. |
def _query(event=None,
method='GET',
args=None,
header_dict=None,
data=None):
secret_key = __salt__['config.get']('ifttt.secret_key') or \
__salt__['config.get']('ifttt:secret_key')
path = 'https://maker.ifttt.com/trigger/{0}/with/key/{1}'.format(event, secret... | Make a web call to IFTTT. |
def _set_from_ini(self, namespace, ini_file):
global_vars = dict((key, val)
for key, val in namespace.items()
if isinstance(val, basestring)
)
for section in ini_file.sections():
if section == "GLOBAL":
raw_vars = global_vars
else:
... | Copy values from loaded INI file to namespace. |
def Put(self, key, obj):
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
node = Node(key=key, data=obj)
self._hash[key] = node
self._age.AppendNode(node)
self.Expire()
return key | Add the object to the cache. |
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if valid_pct==0.: return self.split_none()
if seed is not None: np.random.seed(seed)
rand_idx = np.random.... | Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed. |
def clean_cache(self, request):
treenav.delete_cache()
self.message_user(request, _('Cache menuitem cache cleaned successfully.'))
info = self.model._meta.app_label, self.model._meta.model_name
changelist_url = reverse('admin:%s_%s_changelist' % info, current_app=self.admin_site.name)
... | Remove all MenuItems from Cache. |
def propget(self, prop, rev, path=None):
rev, prefix = self._maprev(rev)
if path is None:
return self._propget(prop, str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._propget(prop, str(rev), path) | Get Subversion property value of the path |
def table_top_abs(self):
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | Returns the absolute position of table top |
def call_fdel(self, obj) -> None:
self.fdel(obj)
try:
del vars(obj)[self.name]
except KeyError:
pass | Remove the predefined custom value and call the delete function. |
def read_header(self):
format = '!HHHHHH'
length = struct.calcsize(format)
info = struct.unpack(format,
self.data[self.offset:self.offset + length])
self.offset += length
self.id = info[0]
self.flags = info[1]
self.num_questions = info[2]
s... | Reads header portion of packet |
def run_deferred(self, deferred):
for handler, scope, offset in deferred:
self.scope_stack = scope
self.offset = offset
handler() | Run the callables in deferred using their associated scope stack. |
def checkout(self, ref, cb=None):
if self.is_api:
return self._checkout_api(ref, cb=cb)
else:
return self._checkout_fs(ref, cb=cb) | Checkout a bundle from the remote. Returns a file-like object |
def gridOn(self):
return (self._gridOn and (self._has_default_loc()
or transforms.interval_contains(self.get_view_interval(), self.get_loc()))) | Control whether the gridline is drawn for this tick. |
def _syscall(self, command, input=None, env=None, *params):
return Popen([command] + list(params), stdout=PIPE, stdin=PIPE, stderr=STDOUT,
env=env or os.environ).communicate(input=input) | Call an external system command. |
def element_not_focused(step, id):
elem = world.browser.find_element_by_xpath(str('id("{id}")'.format(id=id)))
focused = world.browser.switch_to_active_element()
assert_false(step, elem == focused) | Check if the element is not focused |
def send_stop_audio(self):
assert self._session_id != VoiceService.SESSION_ID_INVALID
self._pebble.send_packet(AudioStream(session_id=self._session_id, data=StopTransfer())) | Stop an audio streaming session |
def _square_segment(radius, origin):
return np.array(((origin[0] - radius, origin[1] - radius),
(origin[0] - radius, origin[1] + radius),
(origin[0] + radius, origin[1] + radius),
(origin[0] + radius, origin[1] - radius))) | Vertices for a square |
async def _cleanup_subprocess(self, process):
if process.returncode is None:
try:
process.kill()
return await asyncio.wait_for(process.wait(), 1)
except concurrent.futures.TimeoutError:
self._log.debug('Waiting for process to close failed, ... | Kill the given process and properly closes any pipes connected to it. |
def std_byte(self):
try:
return self.std_name[self.pos]
except IndexError:
self.failed = 1
return ord('?') | Copy byte from 8-bit representation. |
def iso8601_to_dt(iso8601):
parser = DateTimeParser()
try:
arrow_dt = arrow.Arrow.fromdatetime(parser.parse_iso(iso8601))
return arrow_dt.to('utc').datetime
except ParserError as pe:
raise ValueError("Provided was not a valid ISO8601 string: %r" % pe) | Given an ISO8601 string as returned by Device Cloud, convert to a datetime object |
def shared_dataset_ids(self):
shared_ids = set(self.scenes[0].keys())
for scene in self.scenes[1:]:
shared_ids &= set(scene.keys())
return shared_ids | Dataset IDs shared by all children. |
def _group_matching(tlist, cls):
opens = []
tidx_offset = 0
for idx, token in enumerate(list(tlist)):
tidx = idx - tidx_offset
if token.is_whitespace:
continue
if token.is_group and not isinstance(token, cls):
_group_matching(token, cls)
continue
... | Groups Tokens that have beginning and end. |
def add_module(self, module):
if module in self._modules:
raise KeyError("module already added to this engine")
ffi.lib.LLVMPY_AddModule(self, module)
module._owned = True
self._modules.add(module) | Ownership of module is transferred to the execution engine |
def create(self, fname, lname, group, type, group_api):
self.__username(fname, lname)
self.client.add(
self.__distinguished_name(type, fname=fname, lname=lname),
API.__object_class(),
self.__ldap_attr(fname, lname, type, group, group_api)) | Create an LDAP User. |
def potcar_symbols(self):
elements = self.poscar.site_symbols
potcar_symbols = []
settings = self._config_dict["POTCAR"]
if isinstance(settings[elements[-1]], dict):
for el in elements:
potcar_symbols.append(settings[el]['symbol']
... | List of POTCAR symbols. |
def convert_to_timestamp(time):
if time == -1:
return None
time = int(time*1000)
hour = time//1000//3600
minute = (time//1000//60) % 60
second = (time//1000) % 60
return str(hour).zfill(2)+":"+str(minute).zfill(2)+":"+str(second).zfill(2) | Convert int to timestamp string. |
def prod():
common_conf()
env.user = settings.LOGIN_USER_PROD
env.machine = 'prod'
env.host_string = settings.HOST_PROD
env.hosts = [env.host_string, ] | Option to do something on the production server. |
def count_waiting_jobs(cls, names):
return sum([queue.waiting.llen() for queue in cls.get_all(names)]) | Return the number of all jobs waiting in queues with the given names |
def new_tmp(self):
self.tmp_idx += 1
return p.join(self.tmp_dir, 'tmp_' + str(self.tmp_idx)) | Create a new temp file allocation |
def filename(self):
if self._filename is None:
if os.path.splitext(self.destination)[1]:
target_file = self.destination
else:
target_file = os.path.join(self.destination,
self.build_filename(self.binary))
... | Return the local filename of the build. |
def from_hostname(cls, hostname):
result = cls.list({'items_per_page': 500})
paas_hosts = {}
for host in result:
paas_hosts[host['name']] = host['id']
return paas_hosts.get(hostname) | Retrieve paas instance id associated to a host. |
def update_contact(self, um_from_user, um_to_user, message):
contact, created = self.get_or_create(um_from_user,
um_to_user,
message)
if not created:
contact.latest_message = message
conta... | Get or update a contacts information |
def _release(self):
if self._in_use is None:
return
if not self._in_use.done():
self._in_use.set_result(None)
self._in_use = None
if self._proxy is not None:
self._proxy._detach()
self._proxy = None
self._pool._queue.put_nowait(self... | Release this connection holder. |
def model_function(self, model_name, version, func_name):
assert func_name in ('serializer', 'loader', 'invalidator')
name = "%s_%s_%s" % (model_name.lower(), version, func_name)
return getattr(self, name) | Return the model-specific caching function. |
def find_cygwin_executables(cls):
exe_paths = glob.glob(cls.cygwin_path + r'\*.exe')
for c in exe_paths:
exe = c.split('\\')
name = exe[1].split('.')[0]
cls.command['windows'][name] = c | find the executables in cygwin |
async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
packets_captured = 0
self._log.debug('Starting to go through packets')
psml_struct, data = await self._get_psml_struct(fd)
while True:
try:
packet, data = await self._get_pack... | A coroutine which goes through a stream and calls a given callback for each XML packet seen in it. |
def _connect(self):
"Connects a socket to the server using options defined in `config`."
self.socket = socket.socket()
self.socket.connect((self.config['host'], self.config['port']))
self.cmd("NICK %s" % self.config['nick'])
self.cmd("USER %s %s bla :%s" %
(self.c... | Connects a socket to the server using options defined in `config`. |
def to_wav(mediafile):
if mediafile.endswith(".wav"):
yield mediafile
else:
wavfile = tempfile.mktemp(__name__) + ".wav"
try:
extract_wav(mediafile, wavfile)
yield wavfile
finally:
if os.path.exists(wavfile):
os.remove(wavfile) | Context manager providing a temporary WAV file created from the given media file. |
def _WritePartial(self, data):
chunk = self.offset // self.chunksize
chunk_offset = self.offset % self.chunksize
data = utils.SmartStr(data)
available_to_write = min(len(data), self.chunksize - chunk_offset)
fd = self._GetChunkForWriting(chunk)
fd.seek(chunk_offset)
fd.write(data[:available_... | Writes at most one chunk of data. |
def list_from_json(source_list_json):
result = []
if source_list_json == [] or source_list_json == None:
return result
for list_item in source_list_json:
item = json.loads(list_item)
try:
if item['class_name'] == 'Departure':
temp = Departure()
... | Deserialise all the items in source_list from json |
def _cluster(param, tom, imtls, gsims, grp_ids, pmap):
pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims))
for grp_id in grp_ids})
first = True
for nocc in range(0, 50):
ocr = tom.occurrence_rate
prob_n_occ = tom.get_probability_n_occurrences(oc... | Computes the probability map in case of a cluster group |
def _parseSections(self, data, imageDosHeader, imageNtHeaders, parse_header_only=False):
sections = []
optional_header_offset = imageDosHeader.header.e_lfanew + 4 + sizeof(IMAGE_FILE_HEADER)
offset = optional_header_offset + imageNtHeaders.header.FileHeader.SizeOfOptionalHeader
image_sec... | Parses the sections in the memory and returns a list of them |
def display_multiple_ropes(self, rope, ax, y, linewidth, rope_var):
vals = dict(rope[rope_var][0])["rope"]
ax.plot(
vals,
(y + 0.05, y + 0.05),
lw=linewidth * 2,
color="C2",
solid_capstyle="round",
zorder=0,
alpha=0.7,
... | Display ROPE when more than one interval is provided. |
def tenant_exists(self, keystone, tenant):
self.log.debug('Checking if tenant exists ({})...'.format(tenant))
return tenant in [t.name for t in keystone.tenants.list()] | Return True if tenant exists. |
def _formatSequence(tokens, categories, seqID, uniqueID):
record = {"_category":categories,
"_sequenceId":seqID}
data = []
reset = 1
for t in tokens:
tokenRecord = record.copy()
tokenRecord["_token"] = t
tokenRecord["_reset"] = reset
tokenRecord["ID"] = uniqueID
... | Write the sequence of data records for this sample. |
def image_upload_to(self, filename):
now = timezone.now()
filename, extension = os.path.splitext(filename)
return os.path.join(
UPLOAD_TO,
now.strftime('%Y'),
now.strftime('%m'),
now.strftime('%d'),
'%s%s' % (slugify(filename), extensio... | Compute the upload path for the image field. |
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 rdy(self, count):
self.ready = count
self.last_ready_sent = count
return self.send(constants.RDY + ' ' + str(count)) | Indicate that you're ready to receive |
def simple_generate_batch(klass, create, size, **kwargs):
return make_factory(klass, **kwargs).simple_generate_batch(create, size) | Create a factory for the given class, and simple_generate instances. |
def _on_throttle(self, conn, command, kwargs, response, capacity, seconds):
LOG.info(
"Throughput limit exceeded during %s. " "Sleeping for %d second%s",
command,
seconds,
plural(seconds),
) | Print out a message when the query is throttled |
def handle_routine(self, que, opts, host, target, mine=False):
opts = copy.deepcopy(opts)
single = Single(
opts,
opts['argv'],
host,
mods=self.mods,
fsclient=self.fsclient,
thin=self.thin,
min... | Run the routine in a "Thread", put a dict on the queue |
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs):
if time_offset is not None:
time = times.apply_time_offset(da[TIME_STR], **time_offset)
da[TIME_STR] = time
return da | Apply specified time shift to DataArray |
def advance_to_checkpoint(self, checkpoint):
if checkpoint in self._checkpoints:
for cp in self._checkpoints:
self.insert(cp)
if cp == checkpoint:
return cp
else:
raise InvalidCheckpointError(checkpoint) | Advance to the specified checkpoint, passing all preceding checkpoints including the specified checkpoint. |
def project_job_trigger_path(cls, project, job_trigger):
return google.api_core.path_template.expand(
"projects/{project}/jobTriggers/{job_trigger}",
project=project,
job_trigger=job_trigger,
) | Return a fully-qualified project_job_trigger string. |
def detach_all_classes(self):
classes = list(self._observers.keys())
for cls in classes:
self.detach_class(cls) | Detach from all tracked classes. |
def remove_duplicates(errors):
passed = defaultdict(list)
for error in errors:
key = error.linter, error.number
if key in DUPLICATES:
if key in passed[error.lnum]:
continue
passed[error.lnum] = DUPLICATES[key]
yield error | Filter duplicates from given error's list. |
def _serialize(self, value, attr, obj):
try:
return super(DateString, self)._serialize(
arrow.get(value).date(), attr, obj)
except ParserError:
return missing | Serialize an ISO8601-formatted date. |
def method_name(self):
if isinstance(self.view_func, str):
return self.view_func
return self.view_func.__name__ | The string name of this route's view function. |
def tokenize(self, s):
s = tf.compat.as_text(s)
if self.reserved_tokens:
substrs = self._reserved_tokens_re.split(s)
else:
substrs = [s]
toks = []
for substr in substrs:
if substr in self.reserved_tokens:
toks.append(substr)
else:
toks.extend(self._alphanum_re... | Splits a string into tokens. |
def convert(value):
s0 = "Sbp" + value if value in COLLISIONS else value
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s0)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + "_t" | Converts to a C language appropriate identifier format. |
def _check(self):
super(Spectrum, self)._check()
err_str = None
has_data = self._KEYS.DATA in self
has_wave = self._KEYS.WAVELENGTHS in self
has_flux = self._KEYS.FLUXES in self
has_filename = self._KEYS.FILENAME in self
if not has_data:
if (not has_wa... | Check that spectrum has legal combination of attributes. |
def name_insert_prefix(records, prefix):
logging.info('Applying _name_insert_prefix generator: '
'Inserting prefix ' + prefix + ' for all '
'sequence IDs.')
for record in records:
new_id = prefix + record.id
_update_id(record, new_id)
yield record | Given a set of sequences, insert a prefix for each sequence's name. |
def main():
input_tif = "../tests/data/Jamaica_dem.tif"
output_tif = "../tests/data/tmp_results/log_dem.tif"
rst = RasterUtilClass.read_raster(input_tif)
rst_valid = rst.validValues
output_data = np.log(rst_valid)
RasterUtilClass.write_gtiff_file(output_tif, rst.nRows, rst.nCols, output_data, rs... | Read GeoTiff raster data and perform log transformation. |
def generate_password(self) -> list:
characterset = self._get_password_characters()
if (
self.passwordlen is None
or not characterset
):
raise ValueError("Can't generate password: character set is "
"empty or passwordlen is... | Generate a list of random characters. |
def _parse_scale(scale_exp):
m = re.search("(\w+?)\{(.*?)\}", scale_exp)
if m is None:
raise InvalidFormat('Unable to parse the given time period.')
scale = m.group(1)
range = m.group(2)
if scale not in SCALES:
raise InvalidFormat('%s is not a valid scale.' % scale)
ranges = re.s... | Parses a scale expression and returns the scale, and a list of ranges. |
def generate_entities_doc(ctx, out_path, package):
from canari.commands.generate_entities_doc import generate_entities_doc
generate_entities_doc(ctx.project, out_path, package) | Create entities documentation from Canari python classes file. |
async def connect_service(bus_name, object_path, interface):
proxy = await proxy_new_for_bus(
Gio.BusType.SYSTEM,
Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES |
Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
info=None,
name=bus_name,
object_path=object_path,
interfac... | Connect to the service object on DBus, return InterfaceProxy. |
def _initialize_with_array(self, data, rowBased=True):
if rowBased:
self.matrix = []
if len(data) != self._rows:
raise ValueError("Size of Matrix does not match")
for col in xrange(self._columns):
self.matrix.append([])
for row ... | Set the matrix values from a two dimensional list. |
def default_link_tag(item):
text = item["value"]
target_url = item["href"]
if not item["href"] or item["type"] in ("span", "current_page"):
if item["attrs"]:
text = make_html_tag("span", **item["attrs"]) + text + "</span>"
return text
return make_h... | Create an A-HREF tag that points to another page. |
def save(self):
with open(self._filename, "w") as f:
self.config.write(f) | save current config to the file |
def download_files(file_list):
for _, source_data_file in file_list:
sql_gz_name = source_data_file['name'].split('/')[-1]
msg = 'Downloading: %s' % (sql_gz_name)
log.debug(msg)
new_data = objectstore.get_object(
handelsregister_conn, source_data_file, 'handelsregister')
... | Download the latest data. |
def previous(self, type=None):
i = self.start - 1
s = self.sentence
while i > 0:
if s[i].chunk is not None and type in (s[i].chunk.type, None):
return s[i].chunk
i -= 1 | Returns the next previous chunk in the sentence with the given type. |
def _to_number(cls, string):
try:
if float(string) - int(string) == 0:
return int(string)
return float(string)
except ValueError:
try:
return float(string)
except ValueError:
return string | Convert string to int or float. |
def send(self, message):
if isinstance(message, bytes):
message = message.decode("utf8")
with self.send_lock:
try:
self.ws.send(message)
except socket.error:
chat_backend.unsubscribe(self) | Send a single message to the websocket. |
def output_shape(self):
if self._output_shape is None:
self._ensure_is_connected()
if callable(self._output_shape):
self._output_shape = tuple(self._output_shape())
return self._output_shape | Returns the output shape. |
def merge(self, from_email, source_incidents):
if from_email is None or not isinstance(from_email, six.string_types):
raise MissingFromEmail(from_email)
add_headers = {'from': from_email, }
endpoint = '/'.join((self.endpoint, self.id, 'merge'))
incident_ids = [entity['id'] if... | Merge other incidents into this incident. |
def _get_metadap_dap(name, version=''):
m = metadap(name)
if not m:
raise DapiCommError('DAP {dap} not found.'.format(dap=name))
if not version:
d = m['latest_stable'] or m['latest']
if d:
d = data(d)
else:
d = dap(name, version)
if not d:
... | Return data for dap of given or latest version. |
def send_login():
form_class = _security.passwordless_login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class()
if form.validate_on_submit():
send_login_instructions(form.user)
if not request.is_json:
do_flash(*g... | View function that sends login instructions for passwordless login |
def finish(self):
self.unset_env()
self.cov.stop()
self.cov.combine()
self.cov.save()
node_desc = self.get_node_desc(sys.platform, sys.version_info)
self.node_descs.add(node_desc) | Stop coverage, save data to file and set the list of coverage objects to report on. |
def setup_manifest(datadir):
manifest_dir = os.path.join(datadir, "manifest")
if not os.path.exists(manifest_dir):
os.makedirs(manifest_dir) | Create barebones manifest to be filled in during update |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.