code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def _add_auth(self):
if not self.auth:
return
if self.auth and not self.definition_body:
raise InvalidResourceException(self.logical_id,
"Auth works only with inline Swagger specified in "
"'Def... | Add Auth configuration to the Swagger file, if necessary |
def run(self):
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 100)
socket.bind('ipc://' + self.timer_sock)
count = 0
log.debug('ConCache-Timer started')
while not self.stopped.wait(1):
socket.send(self.serial.dum... | main loop that fires the event every second |
def load(file):
with open(file, 'r') as f:
contents = f.read()
lambder.load_events(contents) | Load events from a json file |
def push_to_server(self, data):
output = add_profile(self.customer.pk, data, data)
output['response'].raise_if_error()
self.profile_id = output['profile_id']
self.payment_profile_ids = output['payment_profile_ids'] | Create customer profile for given ``customer`` on Authorize.NET |
def xml(self, value):
self._xml = value
self._root = s2t(value) | Set new XML string |
def _process_json_resp_data(resp, no_custom_fields=False):
bridge_users = []
while True:
resp_data = json.loads(resp)
link_url = None
if "meta" in resp_data and\
"next" in resp_data["meta"]:
link_url = resp_data["meta"]["next"]
bridge_users = _process_... | process the response and return a list of BridgeUser |
def project_data_source_path(cls, project, data_source):
return google.api_core.path_template.expand(
"projects/{project}/dataSources/{data_source}",
project=project,
data_source=data_source,
) | Return a fully-qualified project_data_source string. |
def revision_number(self):
revision = self.revision
if revision is None:
return 0
revision_str = revision.text
try:
revision = int(revision_str)
except ValueError:
revision = 0
if revision < 0:
revision = 0
return re... | Integer value of revision property. |
def _nodedev_event_update_cb(conn, dev, opaque):
_salt_send_event(opaque, conn, {
'nodedev': {
'name': dev.name()
},
'event': opaque['event']
}) | Node device update events handler |
def name(self):
if self.chosen_name:
return self.chosen_name
else:
name = self.process.get_name()
if name:
return os.path.basename(name)
return '' | The name for the window as displayed in the title bar and status bar. |
def listener(self):
channels = ['ql:w:' + self.client.worker_name]
listener = Listener(self.client.redis, channels)
thread = threading.Thread(target=self.listen, args=(listener,))
thread.start()
try:
yield
finally:
listener.unlisten()
t... | Listen for pubsub messages relevant to this worker in a thread |
def _findLocation(self, reference_name, start, end):
try:
return self._locationMap['hg19'][reference_name][start][end]
except:
return None | return a location key form the locationMap |
def figure_buffer(figs):
assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?'
buffers = []
w, h = figs[0].canvas.get_width_height()
for f in figs:
wf, hf = f.canvas.get_width_height()
assert wf == w and hf == h, 'All canvas objects need to have same size'
... | Extract raw image buffer from matplotlib figure shaped as 1xHxWx3. |
def stdout_display():
if sys.version_info[0] == 2:
yield SmartBuffer(sys.stdout)
else:
yield SmartBuffer(sys.stdout.buffer) | Print results straight to stdout |
def item(self):
url = self._contentURL
return Item(url=self._contentURL,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initalize=True) | returns the Item class of an Item |
def run_has_samplesheet(fc_dir, config, require_single=True):
fc_name, _ = flowcell.parse_dirname(fc_dir)
sheet_dirs = config.get("samplesheet_directories", [])
fcid_sheet = {}
for ss_dir in (s for s in sheet_dirs if os.path.exists(s)):
with utils.chdir(ss_dir):
for ss in glob.glob("... | Checks if there's a suitable SampleSheet.csv present for the run |
def read(self):
resp = self.sqs_client.receive_message(
QueueUrl=self.queue_url,
MaxNumberOfMessages=1,
AttributeNames=('SentTimestamp',),
WaitTimeSeconds=self.recv_wait_time_seconds,
)
if resp['ResponseMetadata']['HTTPStatusCode'] != 200:
... | read a single message from the queue |
def remove_nopairs(in_bam, out_dir, config):
runner = broad.runner_from_config(config)
out_bam = os.path.join(out_dir, "{}-safepair{}".format(*os.path.splitext(os.path.basename(in_bam))))
if not utils.file_exists(out_bam):
read_counts = collections.defaultdict(int)
with pysam.Samfile(in_bam,... | Remove any reads without both pairs present in the file. |
def captures_directory(self):
path = os.path.join(self._path, "project-files", "captures")
os.makedirs(path, exist_ok=True)
return path | Location of the captures files |
def make_sudo_cmd(sudo_user, executable, cmd):
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_F... | helper function for connection plugins to create sudo commands |
def tseitin(self, auxvarname='aux'):
if self.is_cnf():
return self
_, constraints = _tseitin(self.to_nnf(), auxvarname)
fst = constraints[-1][1]
rst = [Equal(v, ex).to_cnf() for v, ex in constraints[:-1]]
return And(fst, *rst) | Convert the expression to Tseitin's encoding. |
def accel_move_tab_right(self, *args):
pos = self.get_notebook().get_current_page()
if pos != self.get_notebook().get_n_pages() - 1:
self.move_tab(pos, pos + 1)
return True | Callback to move a tab to the right |
def add_dependency(id=None, name=None, dependency_id=None, dependency_name=None):
data = add_dependency_raw(id, name, dependency_id, dependency_name)
if data:
return utils.format_json_list(data) | Add an existing BuildConfiguration as a dependency to another BuildConfiguration. |
def cells(self) -> Generator[Tuple[int, int], None, None]:
yield from itertools.product(
range(self.row_start, self.row_end),
range(self.column_start, self.column_end)
) | Generate cells in span. |
def _copy_replace(src, dst, replacements):
with src.open() as infile, dst.open('w') as outfile:
outfile.write(re.sub(
'|'.join(re.escape(k) for k in replacements),
lambda m: str(replacements[m.group(0)]),
infile.read()
)) | Copies the src file into dst applying the replacements dict |
def list_cubes(self):
for file_name in os.listdir(self.directory):
if '.' in file_name:
name, ext = file_name.rsplit('.', 1)
if ext.lower() == 'json':
yield name | List all available JSON files. |
def save_relationship(self, relationship_form, *args, **kwargs):
if relationship_form.is_for_update():
return self.update_relationship(relationship_form, *args, **kwargs)
else:
return self.create_relationship(relationship_form, *args, **kwargs) | Pass through to provider RelationshipAdminSession.update_relationship |
def stationary_distribution(P, C=None, mincount_connectivity=0):
from msmtools.analysis.dense.stationary_vector import stationary_distribution as msmstatdist
if C is None:
if is_connected(P, strong=True):
return msmstatdist(P)
else:
raise ValueError('Computing stationary ... | Simple estimator for stationary distribution for multiple strongly connected sets |
def applyIndex(self, lst, right):
if len(right) != 1:
raise exceptions.EvaluationError('%r can only be applied to one argument, got %r' % (self.left, self.right))
right = right[0]
if isinstance(right, int):
return lst[right]
raise exceptions.EvaluationError("Can't apply %r to argument (%r): ... | Apply a list to something else. |
def stream(self):
if not hasattr(self, '_stream'):
self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop)
return self._stream | Return the current zmqstream, creating one if necessary |
def from_country(cls, country):
result = cls.list({'sort_by': 'id ASC'})
dc_countries = {}
for dc in result:
if dc['country'] not in dc_countries:
dc_countries[dc['country']] = dc['id']
return dc_countries.get(country) | Retrieve the first datacenter id associated to a country. |
def package_has_version_file(package_name):
version_file_path = helpers.package_file_path('_version.py', package_name)
return os.path.isfile(version_file_path) | Check to make sure _version.py is contained in the package |
def Printer(open_file=sys.stdout, closing=False):
try:
while True:
logstr = (yield)
open_file.write(logstr)
open_file.write('\n')
except GeneratorExit:
if closing:
try: open_file.close()
except: pass | Prints items with a timestamp. |
def unpack_rgb_image(plane):
assert plane.bits_per_pixel == 24, "{} != 24".format(plane.bits_per_pixel)
size = point.Point.build(plane.size)
data = np.frombuffer(plane.data, dtype=np.uint8)
return data.reshape(size.y, size.x, 3) | Return a correctly shaped numpy array given the image bytes. |
def timelines(fig, y, xstart, xstop, color='b'):
fig.hlines(y, xstart, xstop, color, lw=4)
fig.vlines(xstart, y+0.03, y-0.03, color, lw=2)
fig.vlines(xstop, y+0.03, y-0.03, color, lw=2) | Plot timelines at y from xstart to xstop with given color. |
def read(self, start_position: int, size: int) -> memoryview:
return memoryview(self._bytes)[start_position:start_position + size] | Return a view into the memory |
def die(msg, errlvl=1, prefix="Error: "):
stderr("%s%s\n" % (prefix, msg))
sys.exit(errlvl) | Convenience function to write short message to stderr and quit. |
def _traverse_report(data):
if 'items' not in data:
return {}
out = {}
for item in data['items']:
skip = (item['severity'] == 'NonDisplay' or
item['itemKey'] == 'categoryDesc' or
item['value'] in [None, 'Null', 'N/A', 'NULL'])
if skip:
cont... | Recursively traverse vehicle health report. |
def clipper(self):
for sample in self.runmetadata:
replacementresults = dict()
try:
if self.analysistype != 'sixteens_full' and self.analysistype != 'resfinder':
for gene in sample[self.analysistype].faidict:
try:
... | Filter out results based on the presence of cigar features such as internal soft-clipping |
def fromints(cls, ints):
return cls.frombitsets(map(cls.BitSet.fromint, ints)) | Series from integer rank arguments. |
def _build_row(self, row, parent, align, border):
tr = etree.SubElement(parent, 'tr')
tag = 'td'
if parent.tag == 'thead':
tag = 'th'
cells = self._split_row(row, border)
for i, a in enumerate(align):
c = etree.SubElement(tr, tag)
try:
... | Given a row of text, build table cells. |
def addPort(n: LNode, intf: Interface):
d = PortTypeFromDir(intf._direction)
ext_p = LayoutExternalPort(
n, name=intf._name, direction=d, node2lnode=n._node2lnode)
ext_p.originObj = originObjOfPort(intf)
n.children.append(ext_p)
addPortToLNode(ext_p, intf, reverseDirection=True)
return e... | Add LayoutExternalPort for interface |
def total_volume_per_neurite(neurites, neurite_type=NeuriteType.all):
return list(sum(s.volume for s in n.iter_sections())
for n in iter_neurites(neurites, filt=is_type(neurite_type))) | Get the volume per neurite in a collection |
def _parse_summary_frames(self, file_obj):
for _ in range(self.n_summary_frames):
dom_id = unpack('<i', file_obj.read(4))[0]
dq_status = file_obj.read(4)
dom_status = unpack('<iiii', file_obj.read(16))
raw_rates = unpack('b' * 31, file_obj.read(31))
pm... | Iterate through the byte data and fill the summary_frames |
def neighbors(self, distance=2.0):
dgrid = self.distance_grid.reshape(self.num_neurons, self.num_neurons)
for x, y in zip(*np.nonzero(dgrid <= distance)):
if x != y:
yield x, y | Get all neighbors for all neurons. |
def set(self, shape):
self.bottom, self.left = shape.bottom, shape.left
self.width, self.height = shape.width, shape.height
return self | Fill this rectangle with the dimensions of the given shape. |
def extract_causal_relations(self):
relations = [e for e in self.doc.extractions if
'DirectedRelation' in e['labels'] and
'Causal' in e['labels']]
for relation in relations:
stmt = self.get_causal_relation(relation)
if stmt is not None:
... | Extract causal relations as Statements. |
def cli(yamlfile, directory, out, classname, format):
DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out) | Generate graphviz representations of the biolink model |
def read_only_s3_bucket_policy_statements(buckets, folder="*"):
list_buckets = [s3_arn(b) for b in buckets]
object_buckets = [s3_objects_arn(b, folder) for b in buckets]
bucket_resources = list_buckets + object_buckets
return [
Statement(
Effect=Allow,
Resource=[s3_arn("*... | Read only policy an s3 bucket. |
def build_default_filepath(self):
return os.path.join(
self.app_config.name,
'scripts',
self.template_relpath + '.js',
) | Called when 'filepath' is not defined in the settings |
def to_dict(cls, acl):
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.id
}
} | transform an ACL to a dict |
def asyncStarCmap(asyncCallable, iterable):
results = []
yield coopStar(asyncCallable, results.append, iterable)
returnValue(results) | itertools.starmap for deferred callables using cooperative multitasking |
def team_accessLogs(self, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call("team.accessLogs", http_verb="GET", params=kwargs) | Gets the access logs for the current team. |
def Query(self, sql_query):
results = {}
try:
self._connection = sqlite.connect(self.name)
self._connection.execute("PRAGMA journal_mode=%s" % self.journal_mode)
self._cursor = self._connection.cursor()
results = self._cursor.execute(sql_query).fetchall()
except sqlite.Error as error... | Query the database file. |
def translate(self):
varnames = set()
ident = self.ident
funcnames = set([ident])
arg_exprs = []
for arg in self.args:
subexprs, subvars, subfuncs = arg.translate()
varnames.update(subvars)
funcnames.update(subfuncs)
arg_exprs.appen... | Compile the function call. |
def install_toolset(self, toolset):
info = toolset_info[toolset]
if sys.platform.startswith('linux'):
os.chdir(self.work_dir)
if 'ppa' in info:
for ppa in info['ppa']:
utils.check_call(
'sudo','add-apt-repository','--yes... | Installs specific toolset on CI system. |
def _get_default_router(self, routers, router_name=None):
if router_name is None:
for router in routers:
if router['id'] is not None:
return router['id']
else:
for router in routers:
if router['hostname'] == router_name:
... | Returns the default router for ordering a dedicated host. |
def isInside(self, point, tol=0.0001):
poly = self.polydata(True)
points = vtk.vtkPoints()
points.InsertNextPoint(point)
pointsPolydata = vtk.vtkPolyData()
pointsPolydata.SetPoints(points)
sep = vtk.vtkSelectEnclosedPoints()
sep.SetTolerance(tol)
sep.Check... | Return True if point is inside a polydata closed surface. |
def _create_table_xml_file(self, data, fname=None):
content = self._xml_pretty_print(data)
if not fname:
fname = self.name
with open(fname+".xml", 'w') as f:
f.write(content) | Creates a xml file of the table |
def _include_term_list(self, termlist):
ref_needed = False
for term in termlist:
ref_needed = ref_needed or self._include_term(term)
return ref_needed | Add terms from a TermList to the ontology. |
def setup_apiv2():
if sys.version_info[0] == 2:
logging.getLogger(__name__).debug(
'setting up SIP API to version 2')
import sip
try:
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
except ValueError:
logging.getLogger(__name__).crit... | Setup apiv2 when using PyQt4 and Python2. |
def move_up(self):
self.at(ardrone.at.pcmd, True, 0, 0, self.speed, 0) | Make the drone rise upwards. |
def config(self):
if self.__config is None:
config_path = self.locate_config()
if config_path:
self.__config = self.read_file(config_path)
self.__config_path = config_path
return self.__config | Read config automatically if required |
def _update_wikidata(self):
claims = self.data['claims']
for ent in claims:
plabel = self.data['labels'].get(ent)
if plabel:
plabel = "%s (%s)" % (plabel, ent)
claim = []
for item in claims[ent]:
ilabel = item
... | set wikidata from claims and labels |
def callback(self):
try:
return self._callback()
except:
s = straceback()
self.exceptions.append(s)
self.shutdown(msg="Exception raised in callback!\n" + s) | The function that will be executed by the scheduler. |
def start(self):
if self.mode == MODE_PRIMARY:
i = self._start()
else:
i = self._connect()
self.manager = i | Starts or connects to the manager. |
def sync_sources(self, force=False):
from ambry.orm.file import File
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SOURCES]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer or force:
self.log('Syncing {}'.format(bsf... | Sync in only the sources.csv file |
def _init_lazy_fields(self):
self.gtf_path = None
self._protein_sequences = None
self._transcript_sequences = None
self._db = None
self.protein_fasta_paths = None
self.transcript_fasta_paths = None
self._genes = {}
self._transcripts = {}
self._exon... | Member data that gets loaded or constructed on demand |
def create_app_from_yml(path):
try:
with open(path, "rt", encoding="UTF-8") as f:
try:
interpolated = io.StringIO(f.read() % {
"here": os.path.abspath(os.path.dirname(path))})
interpolated.name = f.name
conf = yaml.safe_load(int... | Return an application instance created from YAML. |
def freeze(obj):
if isinstance(obj, dict):
return ImmutableDict(obj)
if isinstance(obj, list):
return ImmutableList(obj)
if isinstance(obj, set):
return ImmutableSet(obj)
return obj | Freeze python types by turning them into immutable structures. |
def _notify_subnet_create(resource, event, trigger, **kwargs):
context = kwargs['context']
subnet = kwargs['subnet']
l3plugin = bc.get_plugin(L3_ROUTER_NAT)
for router in l3plugin.get_routers(context):
if (router['external_gateway_info'] and
(router['external_gateway_info']['netw... | Called when a new subnet is created in the external network |
def _get_tags_and_content(self, content: str) -> typing.Tuple[str, str]:
content_lines = content.split('\n')
tag_lines = []
if content_lines[0] != '---':
return '', content
content_lines.pop(0)
for line in content_lines:
if line in ('---', '...'):
... | Splits content into two string - tags part and another content. |
def copy_attr(f1, f2):
copyit = lambda x: not hasattr(f2, x) and x[:10] == 'PACKAGING_'
if f1._tags:
pattrs = [tag for tag in f1._tags if copyit(tag)]
for attr in pattrs:
f2.Tag(attr, f1.GetTag(attr)) | copies the special packaging file attributes from f1 to f2. |
async def _receive(self, stream_id, pp_id, data):
await self._data_channel_receive(stream_id, pp_id, data) | Receive data stream -> ULP. |
def exec_then_eval(code, namespace=None):
namespace = namespace or {}
block = ast.parse(code, mode='exec')
last = ast.Expression(block.body.pop().value)
exec(compile(block, '<string>', mode='exec'), namespace)
return eval(compile(last, '<string>', mode='eval'), namespace) | Exec a code block & return evaluation of the last line |
def generate_words(numberofwords, wordlist, secure=None):
if not secure:
chooser = random.choice
else:
chooser = random.SystemRandom().choice
return [chooser(wordlist) for _ in range(numberofwords)] | Generate a list of random words from wordlist. |
def standardize(score):
score = asarray_ndim(score, 1)
return (score - np.nanmean(score)) / np.nanstd(score) | Centre and scale to unit variance. |
def addUnderlineAnnot(self, rect):
CheckParent(self)
val = _fitz.Page_addUnderlineAnnot(self, rect)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val | Underline content in a rectangle or quadrilateral. |
def _import_module(module_path, classnames):
try:
imported_module = __import__(module_path, fromlist=classnames)
return imported_module
except ImportError:
__, __, exc_traceback = sys.exc_info()
frames = traceback.extract_tb(exc_traceback)
if len(frames) > 1:
... | Tries to import the given Python module path. |
def use_isolated_book_view(self):
self._book_view = ISOLATED
for session in self._get_provider_sessions():
try:
session.use_isolated_book_view()
except AttributeError:
pass | Pass through to provider CommentLookupSession.use_isolated_book_view |
def _pre_delete_hook(cls, key):
if cls.searching_enabled:
doc_id = cls.search_get_document_id(key)
index = cls.search_get_index()
index.delete(doc_id) | Removes instance from index. |
def disassociate_public_ip(self, public_ip_id):
floating_ip = self.client.floating_ips.get(public_ip_id)
floating_ip = floating_ip.to_dict()
instance_id = floating_ip.get('instance_id')
address = floating_ip.get('ip')
self.client.servers.remove_floating_ip(instance_id, address)
... | Disassociate a external IP |
def save(self, *args, **kwargs):
valid = map(str, settings.RATINGS_RANGE)
if str(self.value) not in valid:
raise ValueError("Invalid rating. %s is not in %s" % (self.value,
", ".join(valid)))
super(Rating, self).save(*args, **kwargs) | Validate that the rating falls between the min and max values. |
def _config(self):
config = 0
if self.mode == MODE_NORMAL:
config += (self._t_standby << 5)
if self._iir_filter:
config += (self._iir_filter << 2)
return config | Value to be written to the device's config register |
def delete_issue_link_type(self, issue_link_type_id):
url = 'rest/api/2/issueLinkType/{issueLinkTypeId}'.format(issueLinkTypeId=issue_link_type_id)
return self.delete(url) | Delete the specified issue link type. |
def check_file(self):
try:
image_type = ".{0}".format(self.image.split(".")[1])
if image_type not in self.file_format:
print("Format: '{0}' not recognized. Use one of "
"them:\n{1}".format(self.image.split(".")[1],
... | Check for file format and type |
def loadFile(self, fileName):
self.file = QtCore.QFile(fileName)
if self.file.exists():
self.qteText.append(open(fileName).read())
else:
msg = "File <b>{}</b> does not exist".format(self.qteAppletID())
self.qteLogger.info(msg) | Display the file associated with the appletID. |
def relative_path(self, absolute_path, output_filename):
absolute_path = posixpath.join(settings.PIPELINE_ROOT, absolute_path)
output_path = posixpath.join(settings.PIPELINE_ROOT, posixpath.dirname(output_filename))
return relpath(absolute_path, output_path) | Rewrite paths relative to the output stylesheet path |
def extract_bits(self, val):
thisval = self.high >> 4
thisval = thisval ^ val
self.high = (self.high << 4) | (self.low >> 4)
self.high = self.high & constants.BYTEMASK
self.low = self.low << 4
self.low = self.low & constants.BYTEMASK
self.high = self.high ^ s... | Extras the 4 bits, XORS the message data, and does table lookups. |
def interface(iface):
iface_info, error = _get_iface_info(iface)
if error is False:
return iface_info.get(iface, {}).get('inet', '')
else:
return error | Return the details of `iface` or an error if it does not exist |
def enable_reporting(self):
self.reporting = True
msg = bytearray([REPORT_DIGITAL + self.port_number, 1])
self.board.sp.write(msg)
for pin in self.pins:
if pin.mode == INPUT:
pin.reporting = True | Enable reporting of values for the whole port. |
def htmlCreateMemoryParserCtxt(buffer, size):
ret = libxml2mod.htmlCreateMemoryParserCtxt(buffer, size)
if ret is None:raise parserError('htmlCreateMemoryParserCtxt() failed')
return parserCtxt(_obj=ret) | Create a parser context for an HTML in-memory document. |
def pid(self):
try:
os.remove(self.pidfile)
except IOError:
if not os.path.isfile(self.pidfile):
return None
LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
sys.exit(exit.PIDFILE_INACCESSIBLE) | Stop managing the current pid. |
def add_metadata_to_archive(self, metadata, meta_path):
archive_path = self.get_full_archive_path(meta_path.lstrip('/'))
write_data_to_file(metadata, archive_path) | Add metadata to archive |
def render_secretfile(opt):
LOG.debug("Using Secretfile %s", opt.secretfile)
secretfile_path = abspath(opt.secretfile)
obj = load_vars(opt)
return render(secretfile_path, obj) | Renders and returns the Secretfile construct |
def delete_edge_by_nodes(self, node_a, node_b):
node = self.get_node(node_a)
edge_ids = []
for e_id in node['edges']:
edge = self.get_edge(e_id)
if edge['vertices'][1] == node_b:
edge_ids.append(e_id)
for e in edge_ids:
self.delete_edge... | Removes all the edges from node_a to node_b from the graph. |
def publish(self, topic, payload, qos=0, retain=False):
return self._client.publish(topic, payload, qos, retain) | Publishes an MQTT message |
def clean(self):
super().clean()
if self.poster is None and self.anonymous_key is None:
raise ValidationError(
_('A user id or an anonymous key must be associated with a post.'),
)
if self.poster and self.anonymous_key:
raise ValidationError(
... | Validates the post instance. |
def from_dict(raw_data):
url = None
width = None
height = None
try:
url = raw_data['url']
width = raw_data['width']
height = raw_data['height']
except KeyError:
raise ValueError('Unexpected image json structure')
except Type... | Create Image from raw dictionary data. |
def find_info(name=None):
if not name:
return list(servers.keys())
name = name.lower()
if name in servers:
info = servers[name]
else:
raise CityNotFound("Could not find the specified city: %s" % name)
return info | Find the needed city server information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.