code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def _parse_data(self, data, charset):
builder = TreeBuilder(numbermode=self._numbermode)
if isinstance(data,basestring):
xml.sax.parseString(data, builder)
else:
xml.sax.parse(data, builder)
return builder.root[self._root_element_name()] | Parse the xml data into dictionary. |
def showPopup(self):
nav = self.navigator()
nav.move(self.mapToGlobal(QPoint(0, self.height())))
nav.resize(400, 250)
nav.show() | Displays the popup associated with this navigator. |
def detect_hooks():
flog.debug('Detecting hooks ...')
present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path])
if present:
flog.debug('Detected.')
else:
flog.debug('Not detected.')
return present | Returns True if the import hooks are installed, False if not. |
def insertAnnouncement(self, announcement):
url = announcement.get('url', None)
try:
peers.Peer(url)
except:
raise exceptions.BadUrlException(url)
try:
models.Announcement.create(
url=announcement.get('url'),
attributes=... | Adds an announcement to the registry for later analysis. |
def add(self, defn):
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | Adds the given Packet Definition to this Telemetry Dictionary. |
def ExpireObject(self, key):
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
self.KillObject(node.data)
return node.data | Expire a specific object from cache. |
def _validate(self, writing=False):
box_ids = [box.box_id for box in self.box]
if len(box_ids) != 1 or box_ids[0] != 'flst':
msg = ("Fragment table boxes must have a single fragment list "
"box as a child box.")
self._dispatch_validation_error(msg, writing=writ... | Self-validate the box before writing. |
def binary_op(data, op, other, blen=None, storage=None, create='array',
**kwargs):
if hasattr(other, 'shape') and len(other.shape) == 0:
other = other[()]
if np.isscalar(other):
def f(block):
return op(block, other)
return map_blocks(data, f, blen=blen, storage=... | Compute a binary operation block-wise over `data`. |
def load(data_path):
with open(data_path, "r") as data_file:
raw_data = data_file.read()
data_file.close()
return raw_data | Extract data from provided file and return it as a string. |
def _read_config(conf_file=None):
if conf_file is None:
paths = ('/etc/supervisor/supervisord.conf', '/etc/supervisord.conf')
for path in paths:
if os.path.exists(path):
conf_file = path
break
if conf_file is None:
raise CommandExecutionError('... | Reads the config file using configparser |
def wherenotin(self, fieldname, value):
return self.wherein(fieldname, value, negate=True) | Logical opposite of `wherein`. |
def storage(self):
annotation = get_portal_annotation()
if annotation.get(NUMBER_STORAGE) is None:
annotation[NUMBER_STORAGE] = OIBTree()
return annotation[NUMBER_STORAGE] | get the counter storage |
def inMicrolensRegion_main(args=None):
import argparse
parser = argparse.ArgumentParser(
description="Check if a celestial coordinate is "
"inside the K2C9 microlensing superstamp.")
parser.add_argument('ra', nargs=1, type=float,
he... | Exposes K2visible to the command line. |
def add_matplotlib_cmap(cm, name=None):
global cmaps
cmap = matplotlib_to_ginga_cmap(cm, name=name)
cmaps[cmap.name] = cmap | Add a matplotlib colormap. |
def _tuple_requested(self, namespace_tuple):
if not isinstance(namespace_tuple[0], unicode):
encoded_db = unicode(namespace_tuple[0])
else:
encoded_db = namespace_tuple[0]
if not isinstance(namespace_tuple[1], unicode):
encoded_coll = unicode(namespace_tuple[1... | Helper for _namespace_requested. Supports limited wildcards |
def reset_term_stats(set_id, term_id, client_id, user_id, access_token):
found_sets = [user_set for user_set in get_user_sets(client_id, user_id)
if user_set.set_id == set_id]
if len(found_sets) != 1:
raise ValueError('{} set(s) found with id {}'.format(len(found_sets), set_id))
fo... | Reset the stats of a term by deleting and re-creating it. |
def addPeer(self):
self._openRepo()
try:
peer = peers.Peer(
self._args.url, json.loads(self._args.attributes))
except exceptions.BadUrlException:
raise exceptions.RepoManagerException("The URL for the peer was "
... | Adds a new peer into this repo |
def _initGP(self):
if self._inference=='GP2KronSum':
signalPos = sp.where(sp.arange(self.n_randEffs)!=self.noisPos)[0][0]
gp = GP2KronSum(Y=self.Y, F=self.sample_designs, A=self.trait_designs,
Cg=self.trait_covars[signalPos], Cn=self.trait_covars[self.noisPos... | Internal method for initialization of the GP inference objetct |
def trunc(x):
if isinstance(x, UncertainFunction):
mcpts = np.trunc(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.trunc(x) | Truncate the values to the integer value without rounding |
def h5features_convert(self, infile):
with h5py.File(infile, 'r') as f:
groups = list(f.keys())
for group in groups:
self._writer.write(
Reader(infile, group).read(),
self.groupname, append=True) | Convert a h5features file to the latest h5features version. |
def _propagate_packages(self):
for item in self.data:
if isinstance(item, LatexObject):
if isinstance(item, Container):
item._propagate_packages()
for p in item.packages:
self.packages.add(p) | Make sure packages get propagated. |
def __get_doc_block_lines(self):
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
if re.match(r'\s*\*/', line):
line2 = i
if self._is_start_of_stored_... | Returns the start and end line of the DOcBlock of the stored routine code. |
def render_payment_form(self):
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) | Display the DirectPayment for entering payment information. |
def scale_values(numbers, num_lines=1, minimum=None, maximum=None):
"Scale input numbers to appropriate range."
filtered = [n for n in numbers if n is not None]
min_ = min(filtered) if minimum is None else minimum
max_ = max(filtered) if maximum is None else maximum
dv = max_ - min_
numbers = [m... | Scale input numbers to appropriate range. |
def value_text(self):
search = self._selected.get()
for item in self._rbuttons:
if item.value == search:
return item.text
return "" | Sets or returns the option selected in a ButtonGroup by its text value. |
def init_index(self, app=None):
elasticindexes = self._get_indexes()
for index, settings in elasticindexes.items():
es = settings['resource']
if not es.indices.exists(index):
self.create_index(index, settings.get('index_settings'), es)
continue
... | Create indexes and put mapping. |
async def wait_and_quit(loop):
from pylp.lib.tasks import running
if running:
await asyncio.wait(map(lambda runner: runner.future, running)) | Wait until all task are executed. |
def _execute(self):
data = self.seed_fn()
for transform in self.transforms:
data = transform(data)
return list(data) | Run the query, generating data from the `seed_fn` and performing transforms on the results. |
def _validate_all_tags_are_used(metadata):
tag_names = set([tag_name for tag_name, _ in metadata.tags])
filter_arg_names = set()
for location, _ in metadata.registered_locations:
for filter_info in metadata.get_filter_infos(location):
for filter_arg in filter_info.args:
i... | Ensure all tags are used in some filter. |
def read_remote_origin(repo_dir):
conf = ConfigParser()
conf.read(os.path.join(repo_dir, '.git/config'))
return conf.get('remote "origin"', 'url') | Read the remote origin URL from the given git repo, or None if unset. |
def disable_requiretty_on_sudoers(log=False):
if log:
bookshelf2.logging_helpers.log_green(
'disabling requiretty on sudo calls')
comment_line('/etc/sudoers',
'^Defaults.*requiretty', use_sudo=True)
return True | allow sudo calls through ssh without a tty |
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interrogator = self._getUE4BuildInterrogator()
return interrogator.interrogate(self.getPlatformIdentifier(), configuration, libs, sel... | Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries |
def _deserialize(self, value, attr, data):
return super(DateString, self)._deserialize(value, attr,
data).isoformat() | Deserialize an ISO8601-formatted date. |
def build_and_install_wheel(python):
dist_type = "bdist_wheel" if not SDIST else "sdist"
return_code = run_command("{} setup.py {}".format(python, dist_type))
if return_code != 0:
print("Building and installing wheel failed.")
exit(return_code)
assert check_wheel_existence()
print("W... | Build a binary distribution wheel and install it |
def unordered(x, y):
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_unordered_p(x, y) | Return True if x or y is a NaN and False otherwise. |
def RV_1(self):
return self.orbpop_long.RV * (self.orbpop_long.M2 / (self.orbpop_long.M1 + self.orbpop_long.M2)) | Instantaneous RV of star 1 with respect to system center-of-mass |
async def _send_generic_template(self, request: Request, stack: Stack):
gt = stack.get_layer(GenericTemplate)
payload = await gt.serialize(request)
msg = {
'attachment': {
'type': 'template',
'payload': payload
}
}
await sel... | Generates and send a generic template. |
def qual_name(self) -> QualName:
p, s, loc = self._key.partition(":")
return (loc, p) if s else (p, self.namespace) | Return the receiver's qualified name. |
def get(geo_coord, mode=2, verbose=True):
if not isinstance(geo_coord, tuple) or not isinstance(geo_coord[0], float):
raise TypeError('Expecting a tuple')
_rg = RGeocoder(mode=mode, verbose=verbose)
return _rg.query([geo_coord])[0] | Function to query for a single coordinate |
def on_message(msg, server):
text = msg.get("text", "")
match = re.findall(r"!gif (.*)", text)
if not match:
return
res = gif(match[0])
if not res:
return
attachment = {
"fallback": match[0],
"title": match[0],
"title_link": res,
"image_url": res
... | handle a message and return an gif |
def get(self):
key = self.get_key_from_request()
result = self.get_storage().get(key)
return result if result else None | Get the item from redis. |
def infer_compression(url):
compression_indicator = url[-2:]
mapping = dict(
gz='z',
bz='j',
xz='J',
)
return mapping.get(compression_indicator, 'z') | Given a URL or filename, infer the compression code for tar. |
def _tofloat(obj):
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | Convert to float if object is a float string. |
def status(self):
data = self._read()
self._status = YubiKeyUSBHIDStatus(data)
return self._status | Poll YubiKey for status. |
def file_id(self):
if self.type.lower() == "directory":
return None
if self.file_uuid is None:
raise exceptions.MetsError(
"No FILEID: File %s does not have file_uuid set" % self.path
)
if self.is_aip:
return os.path.splitext(os.pat... | Returns the fptr @FILEID if this is not a Directory. |
def from_learner(cls, learn: Learner, ds_type:DatasetType=DatasetType.Valid):
"Create an instance of `ClassificationInterpretation`"
preds = learn.get_preds(ds_type=ds_type, with_loss=True)
return cls(learn, *preds) | Create an instance of `ClassificationInterpretation` |
def cnvkit_background(background_cnns, out_file, items, target_bed=None, antitarget_bed=None):
if not utils.file_exists(out_file):
with file_transaction(items[0], out_file) as tx_out_file:
cmd = [_get_cmd(), "reference", "-f", dd.get_ref_file(items[0]), "-o", tx_out_file]
gender = _g... | Calculate background reference, handling flat case with no normal sample. |
def _wrap_extraction(self, date_object: datetime.datetime,
original_text: str,
start_char: int,
end_char: int
) -> Extraction or None:
try:
resolution = self._settings[MIN_RESOLUTION] \
... | wrap the final result as an Extraction and return |
def raster_field(self):
for field in self.model._meta.fields:
if isinstance(field, models.FileField):
return field
return False | Returns the raster FileField instance on the model. |
def load_object(s):
try:
m_path, o_name = s.rsplit('.', 1)
except ValueError:
raise ImportError('Cant import backend from path: {}'.format(s))
module = import_module(m_path)
return getattr(module, o_name) | Load backend by dotted path. |
def stripext (cmd, archive, verbosity, extension=""):
if verbosity >= 0:
print(util.stripext(archive)+extension)
return None | Print the name without suffix. |
def create_node(self, network, participant):
return self.models.MCMCPAgent(network=network, participant=participant) | Create a node for a participant. |
def log(self, level, *msg_elements):
self.report.log(self._threadlocal.current_workunit, level, *msg_elements) | Log a message against the current workunit. |
def file_renamed(self, editor, new_filename):
if editor is None:
return
editor_id = editor.get_id()
if editor_id in list(self.editor_ids.values()):
root_item = self.editor_items[editor_id]
root_item.set_path(new_filename, fullpath=self.show_fullpath)
... | File was renamed, updating outline explorer tree |
def _connect_su(spec):
return {
'method': 'su',
'enable_lru': True,
'kwargs': {
'username': spec.become_user(),
'password': spec.become_pass(),
'python_path': spec.python_path(),
'su_path': spec.become_exe(),
'connect_timeout': spec... | Return ContextService arguments for su as a become method. |
def from_api_response(cls, reddit_session, json_dict):
json_dict['subreddits'] = [Subreddit(reddit_session, item['name'])
for item in json_dict['subreddits']]
return cls(reddit_session, None, None, json_dict) | Return an instance of the appropriate class from the json dict. |
def _add_pos1(token):
result = token.copy()
result['pos1'] = _POSMAP[token['pos'].split("(")[0]]
return result | Adds a 'pos1' element to a frog token. |
def create_firewall_rule(self, protocol, action, **kwargs):
body = {'protocol': protocol, 'action': action}
if 'tenant_id' in kwargs:
body['tenant_id'] = kwargs['tenant_id']
if 'name' in kwargs:
body['name'] = kwargs['name']
if 'description' in kwargs:
... | Create a new firlwall rule |
def hr_avg(self):
hr_data = self.hr_values()
return int(sum(hr_data) / len(hr_data)) | Average heart rate of the workout |
def to_xarray(self) -> "xarray.Dataset":
import xarray as xr
data_vars = {
"frequencies": xr.DataArray(self.frequencies, dims="bin"),
"errors2": xr.DataArray(self.errors2, dims="bin"),
"bins": xr.DataArray(self.bins, dims=("bin", "x01"))
}
coords = {}
... | Convert to xarray.Dataset |
def start(self):
self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id)
if self.socket is not None:
raise Exception("Socket already established for %s." % self)
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock... | Creates a TCP connection to Device Cloud and sends a ConnectionRequest message |
async def open(self):
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self.publish(message) | Register with the publisher. |
def http_methods(self, urls=None, **route_data):
def decorator(class_definition):
instance = class_definition
if isinstance(class_definition, type):
instance = class_definition()
router = self.urls(urls if urls else "/{0}".format(instance.__class__.__name__.lo... | Creates routes from a class, where the class method names should line up to HTTP METHOD types |
def _is_custom_manager_attribute(node):
attrname = node.attrname
if not name_is_from_qs(attrname):
return False
for attr in node.get_children():
inferred = safe_infer(attr)
funcdef = getattr(inferred, '_proxied', None)
if _is_custom_qs_manager(funcdef):
return Tru... | Checks if the attribute is a valid attribute for a queryset manager. |
def validate_json(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
if request.get_json() is None:
ret_dict = instance._create_ret_object(instance.FAILURE,
None, True,
... | Validate that the call is JSON. |
def print_row_perc_table(table, row_labels, col_labels):
r1c1, r1c2, r2c1, r2c2 = map(float, table)
row1 = r1c1 + r1c2
row2 = r2c1 + r2c2
blocks = [
(r1c1, row1),
(r1c2, row1),
(r2c1, row2),
(r2c2, row2)]
new_table = []
for cell, row in blocks:
try:
... | given a table, print the percentages rather than the totals |
def hosting_devices_removed(self, context, payload):
try:
if payload['hosting_data']:
if payload['hosting_data'].keys():
self.process_services(removed_devices_info=payload)
except KeyError as e:
LOG.error("Invalid payload format for received RP... | Deal with hosting device removed RPC message. |
def flavor_extra_delete(request, flavor_id, keys):
flavor = _nova.novaclient(request).flavors.get(flavor_id)
return flavor.unset_keys(keys) | Unset the flavor extra spec keys. |
def query(self, query, *parameters, **kwargs):
cursor = self._cursor()
try:
self._execute(cursor, query, parameters or None, kwargs)
if cursor.description:
column_names = [column.name for column in cursor.description]
res = [Row(zip(column_names, r... | Returns a row list for the given query and parameters. |
def update(self, user, **kwargs):
yield self.get_parent()
if not self.parent.editable:
err = 'Cannot update child of {} resource'.format(self.parent.state.name)
raise exceptions.Unauthorized(err)
yield super(SubResource, self).update(user, **kwargs) | If parent resource is not an editable state, should not be able to update |
def _print_header(self):
header = " Iter Dir "
if self.constraints is not None:
header += ' SC CC'
header += " Function"
if self.convergence_condition is not None:
header += self.convergence_condition.get_header()
header += " Time"
se... | Print the header for screen logging |
def wrap(string, length, indent):
newline = "\n" + " " * indent
return newline.join((string[i : i + length] for i in range(0, len(string), length))) | Wrap a string at a line length |
def unpack_variable(var):
if var.dataType == stream.STRUCTURE:
return None, struct_to_dtype(var), 'Structure'
elif var.dataType == stream.SEQUENCE:
log.warning('Sequence support not implemented!')
dt = data_type_to_numpy(var.dataType, var.unsigned)
if var.dataType == stream.OPAQUE:
... | Unpack an NCStream Variable into information we can use. |
def write_bit(self, b):
if b:
b = 1
else:
b = 0
shift = self.bitcount % 8
if shift == 0:
self.bits.append(0)
self.bits[-1] |= (b << shift)
self.bitcount += 1 | Write a boolean value. |
def _handle_response(response, command, id_xpath='./id', **kwargs):
_response_switch = {
'insert': ModifyResponse,
'replace': ModifyResponse,
'partial-replace': ModifyResponse,
'update': ModifyResponse,
'delete': ModifyResponse,
'search-delete': SearchDeleteResponse,
... | Initialize the corect Response object from the response string based on the API command type. |
def scatter_group(ax, key, imask, adata, Y, projection='2d', size=3, alpha=None):
mask = adata.obs[key].cat.categories[imask] == adata.obs[key].values
color = adata.uns[key + '_colors'][imask]
if not isinstance(color[0], str):
from matplotlib.colors import rgb2hex
color = rgb2hex(adata.uns[k... | Scatter of group using representation of data Y. |
def precondition(self):
return self.tlang.nplurals == self.slang.nplurals and \
super(PrintfValidator, self).precondition() | Check if the number of plurals in the two languages is the same. |
def disable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native):
starttime = time.time()
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, True, False)
s... | Disable a VLAN on a trunk interface. |
def find_state_op_colocation_error(graph, reported_tags=None):
state_op_types = list_registered_stateful_ops_without_inputs()
state_op_map = {op.name: op for op in graph.get_operations()
if op.type in state_op_types}
for op in state_op_map.values():
for colocation_group in op.colocation_grou... | Returns error message for colocation of state ops, or None if ok. |
def broadcast(self, command, *args, **kwargs):
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL)
for index, user in items(self.users()):
if criterion(user, command, *args, **kwargs):
self.notify(user, command, *args, **kwargs) | Notifies each user with a specified command. |
def _get_resources(self, resource, obj, params=None, map=None, **kwargs):
r = self._http_resource('GET', resource, params=params)
d_items = self._resource_deserialize(r.content.decode("utf-8"))
items = [obj.new_from_dict(item, h=self, **kwargs) for item in d_items]
if map is None:
... | Returns a list of mapped objects from an HTTP resource. |
def _changeMs(self, line):
try:
last_space_pos = line.rindex(' ')
except ValueError:
return line
else:
end_str = line[last_space_pos:]
new_string = line
if end_str[-2:] == 'ms' and int(end_str[:-2]) >= 1000:
ms = int(end... | Change the ms part in the string if needed. |
def to_function(var_instance, lineno=None):
assert isinstance(var_instance, SymbolVAR)
from symbols import FUNCTION
var_instance.__class__ = FUNCTION
var_instance.class_ = CLASS.function
var_instance.reset(lineno=lineno)
return var_instance | Converts a var_instance to a function one |
def det_n(x):
assert x.ndim == 3
assert x.shape[1] == x.shape[2]
if x.shape[1] == 1:
return x[:,0,0]
result = np.zeros(x.shape[0])
for permutation in permutations(np.arange(x.shape[1])):
sign = parity(permutation)
result += np.prod([x[:, i, permutation[i]]
... | given N matrices, return N determinants |
def connect(self):
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_args)
else:
self.common_args += ["-... | connect to the remote host |
def requirements():
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list | Build the requirements list for this project |
def create_dataset_file(root_dir, data):
file_path = os.path.join(root_dir, '{dataset_type}', '{dataset_name}.py')
context = (
_HEADER + _DATASET_DEFAULT_IMPORTS + _CITATION
+ _DESCRIPTION + _DATASET_DEFAULTS
)
with gfile.GFile(file_path.format(**data), 'w') as f:
f.write(context.format(**data)) | Create a new dataset from a template. |
def _return_samples(return_type, samples):
if return_type.lower() == "dataframe":
if HAS_PANDAS:
return pandas.DataFrame.from_records(samples)
else:
warn("Pandas installation not found. Returning numpy.recarray object")
return samples
else:
return samp... | A utility function to return samples according to type |
def mset_list(item, index, value):
'set mulitple items via index of int, slice or list'
if isinstance(index, (int, slice)):
item[index] = value
else:
map(item.__setitem__, index, value) | set mulitple items via index of int, slice or list |
def coinbase_tx(cls, public_key_sec, coin_value, coinbase_bytes=b'', version=1, lock_time=0):
tx_in = cls.TxIn.coinbase_tx_in(script=coinbase_bytes)
COINBASE_SCRIPT_OUT = "%s OP_CHECKSIG"
script_text = COINBASE_SCRIPT_OUT % b2h(public_key_sec)
script_bin = BitcoinScriptTools.compile(scri... | Create the special "first in block" transaction that includes the mining fees. |
def loads(self, string):
"Decompress the passed-in compact script and return the result."
script_class = self.get_script_class()
script = self._load(BytesIO(string), self._protocol, self._version)
return script_class(script) | Decompress the passed-in compact script and return the result. |
def __update_keyboard(self, milliseconds):
if Ragnarok.get_world().Keyboard.is_clicked(self.move_up_button):
self.move_up()
elif Ragnarok.get_world().Keyboard.is_clicked(self.move_down_button):
self.move_down()
elif Ragnarok.get_world().Keyboard.is_clicked(self.select_but... | Use the keyboard to control selection of the buttons. |
def timesteps(self, horizon: int) -> tf.Tensor:
start, limit, delta = horizon - 1, -1, -1
timesteps_range = tf.range(start, limit, delta, dtype=tf.float32)
timesteps_range = tf.expand_dims(timesteps_range, -1)
batch_timesteps = tf.stack([timesteps_range] * self.batch_size)
return... | Returns the input tensor for the given `horizon`. |
def RetrieveIP4Info(self, ip):
if ip.is_private:
return (IPInfo.INTERNAL, "Internal IP address.")
try:
res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)
return (IPInfo.EXTERNAL, res[0])
except (socket.error, socket.herror, socket.gaierror):
return (IPInfo.EXTERNAL, "Unknown ... | Retrieves information for an IP4 address. |
def remove_phenotype(self, ind_obj, phenotypes=None):
if phenotypes is None:
logger.info("delete all phenotypes related to %s", ind_obj.ind_id)
self.query(PhenotypeTerm).filter_by(ind_id=ind_obj.id).delete()
else:
for term in ind_obj.phenotypes:
if ter... | Remove multiple phenotypes from an individual. |
def wp_loop(self):
loader = self.wploader
if loader.count() < 2:
print("Not enough waypoints (%u)" % loader.count())
return
wp = loader.wp(loader.count()-2)
if wp.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
print("Mission is already looped")
... | close the loop on a mission |
def stream(self, sha):
hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(sha))
return OStream(hex_to_bin(hexsha), typename, size, stream) | For now, all lookup is done by git itself |
def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
if devices.filter(registration_id=canonical_id, active=True).exists():
devices.filter(registration_id=current_id).update(active=False)
else:
devices.filter(registration_id=current_... | Handle situation when FCM server response contains canonical ID |
def authenticate(self, username=None, password=None, **kwargs):
try:
user = get_user_model().objects.filter(Q(username=username)|Q(email=username))[0]
if check_password(password, user.password):
return user
else:
return None
except Exce... | Allow users to log in with their email address or username. |
def read(self):
assert os.path.isfile(self.file_path), 'No such file exists: ' + str(self.file_path)
with open(self.file_path, 'r') as f:
reader = csv_builtin.reader(f)
loaded_data = list(reader)
return juggle_types(loaded_data) | Reads CSV file and returns list of contents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.