code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def _stop(self):
engine = self.current_engine()
if "vm" in self._controller.computes:
yield from self._controller.delete_compute("vm")
if engine.running:
log.info("Stop the GNS3 VM")
yield from engine.stop() | Stop the GNS3 VM |
def create_new_csv(samples, args):
out_fn = os.path.splitext(args.csv)[0] + "-merged.csv"
logger.info("Preparing new csv: %s" % out_fn)
with file_transaction(out_fn) as tx_out:
with open(tx_out, 'w') as handle:
handle.write(_header(args.csv))
for s in samples:
... | create csv file that can be use with bcbio -w template |
def update_cost_model(self, x, cost_x):
if self.cost_type == 'evaluation_time':
cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T)
if self.num_updates == 0:
X_all = x
costs_all = cost_evals
else:
X_all = np.vstack((self.co... | Updates the GP used to handle the cost.
param x: input of the GP for the cost model.
param x_cost: values of the time cost at the input locations. |
def get_class(view_model_name):
from . import models; models
from .plotting import Figure; Figure
d = MetaModel.model_class_reverse_map
if view_model_name in d:
return d[view_model_name]
else:
raise KeyError("View model name '%s' not found" % view_model_name) | Look up a Bokeh model class, given its view model name.
Args:
view_model_name (str) :
A view model name for a Bokeh model to look up
Returns:
Model: the model class corresponding to ``view_model_name``
Raises:
KeyError, if the model cannot be found
Example:
... |
def write_config(cfg):
cfg_path = '/usr/local/etc/freelan'
cfg_file = 'freelan_TEST.cfg'
cfg_lines = []
if not isinstance(cfg, FreelanCFG):
if not isinstance(cfg, (list, tuple)):
print("Freelan write input can not be processed.")
return
cfg_lines = cfg
else:
... | try writing config file to a default directory |
def pick_action_todo():
for ndx, todo in enumerate(things_to_do):
if roll_dice(todo["chance"]):
cur_act = actions[get_action_by_name(todo["name"])]
if todo["WHERE_COL"] == "energy" and my_char["energy"] > todo["WHERE_VAL"]:
return cur_act
if todo["WHERE_CO... | only for testing and AI - user will usually choose an action
Sort of works |
def transformByDistance(wV, subModel, alphabetSize=4):
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | transform wV by given substitution matrix |
def intersect(self, other):
intersection = Rect()
if lib.SDL_IntersectRect(self._ptr, self._ptr, intersection._ptr):
return intersection
else:
return None | Calculate the intersection of this rectangle and another rectangle.
Args:
other (Rect): The other rectangle.
Returns:
Rect: The intersection of this rectangle and the given other rectangle, or None if there is no such
intersection. |
def get_branch(self, i):
branch = MerkleBranch(self.order)
j = i + 2 ** self.order - 1
for k in range(0, self.order):
if (self.is_left(j)):
branch.set_row(k, (self.nodes[j], self.nodes[j + 1]))
else:
branch.set_row(k, (self.nodes[j - 1], se... | Gets a branch associated with leaf i. This will trace the tree
from the leaves down to the root, constructing a list of tuples that
represent the pairs of nodes all the way from leaf i to the root.
:param i: the leaf identifying the branch to retrieve |
def _output_dir(
self,
ext,
is_instance=False,
interpolatable=False,
autohinted=False,
is_variable=False,
):
assert not (is_variable and any([is_instance, interpolatable]))
if is_variable:
dir_prefix = "variable_"
elif is_instance:
... | Generate an output directory.
Args:
ext: extension string.
is_instance: The output is instance font or not.
interpolatable: The output is interpolatable or not.
autohinted: The output is autohinted or not.
is_variable: The outp... |
def inverse_transform(self, maps):
out = {}
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
out[parameters.mchirp] = conversions.mchirp_from_mass1_mass2(m1, m2)
out[parameters.q] = m1 / m2
return self.format_output(maps, out) | This function transforms from component masses to chirp mass and
mass ratio.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
>>> import numpy
>>> from pycbc import transforms
>>> t = transfo... |
def mount_iso_image(self, image, image_name, ins_file_name):
query_parms_str = '?image-name={}&ins-file-name={}'. \
format(quote(image_name, safe=''), quote(ins_file_name, safe=''))
self.manager.session.post(
self.uri + '/operations/mount-iso-image' + query_parms_str,
... | Upload an ISO image and associate it to this Partition
using the HMC operation 'Mount ISO Image'.
When the partition already has an ISO image associated,
the newly uploaded image replaces the current one.
Authorization requirements:
* Object-access permission to this Partition... |
def getsystemhooks(self, page=1, per_page=20):
data = {'page': page, 'per_page': per_page}
request = requests.get(
self.hook_url, params=data, headers=self.headers,
verify=self.verify_ssl, auth=self.auth, timeout=self.timeout)
if request.status_code == 200:
re... | Get all system hooks
:param page: Page number
:param per_page: Records per page
:return: list of hooks |
def fragment(self, message):
if message.message_type in [Types.CALL_RES,
Types.CALL_REQ,
Types.CALL_REQ_CONTINUE,
Types.CALL_RES_CONTINUE]:
rw = RW[message.message_type]
payload_sp... | Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
payload size |
def net_recv(ws, conn):
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | Read pending data from network into websocket. |
def decode(self, integers):
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode(integers) | List of ints to str. |
def reset(self):
logger.debug('StackInABox({0}): Resetting...'
.format(self.__id))
for k, v in six.iteritems(self.services):
matcher, service = v
logger.debug('StackInABox({0}): Resetting Service {1}'
.format(self.__id, service.name))... | Reset StackInABox to a like-new state. |
def _get_opt(config, key, option, opt_type):
for opt_key in [option, option.replace('-', '_')]:
if not config.has_option(key, opt_key):
continue
if opt_type == bool:
return config.getbool(key, opt_key)
if opt_type == int:
return config.getint(key, opt_key)... | Get an option from a configparser with the given type. |
def swap_across(idx, idy, mat_a, mat_r, perm):
size = mat_a.shape[0]
perm_new = numpy.eye(size, dtype=int)
perm_row = 1.0*perm[:, idx]
perm[:, idx] = perm[:, idy]
perm[:, idy] = perm_row
row_p = 1.0 * perm_new[idx]
perm_new[idx] = perm_new[idy]
perm_new[idy] = row_p
mat_a = numpy.dot... | Interchange row and column idy and idx. |
def xgettext(self, template):
cmd = 'xgettext -d django -L Python --keyword=gettext_noop \
--keyword=gettext_lazy --keyword=ngettext_lazy:1,2 --from-code=UTF-8 \
--output=- -'
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=... | Extracts to be translated strings from template and turns it into po format. |
def create(self, query, **kwargs):
if kwargs.get("exec_mode", None) == "oneshot":
raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.")
response = self.post(search=query, **kwargs)
sid = _load_sid(response)
return Job(self.service, sid) | Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Search job parameters
<http://dev.spl... |
def FxTools(self):
pi = self.pi
si = self.si
if self.vc_ver <= 10.0:
include32 = True
include64 = not pi.target_is_x86() and not pi.current_is_x86()
else:
include32 = pi.target_is_x86() or pi.current_is_x86()
include64 = pi.current_cpu == '... | Microsoft .NET Framework Tools |
def angular_distance_fast(ra1, dec1, ra2, dec2):
lon1 = np.deg2rad(ra1)
lat1 = np.deg2rad(dec1)
lon2 = np.deg2rad(ra2)
lat2 = np.deg2rad(dec2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon /2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
... | Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lon1:
:param lat1:
:param lon2:
:param lat2:
:r... |
def computeNormals(self):
poly = self.polydata(False)
pnormals = poly.GetPointData().GetNormals()
cnormals = poly.GetCellData().GetNormals()
if pnormals and cnormals:
return self
pdnorm = vtk.vtkPolyDataNormals()
pdnorm.SetInputData(poly)
pdnorm.Comput... | Compute cell and vertex normals for the actor's mesh.
.. warning:: Mesh gets modified, can have a different nr. of vertices. |
def get_panels(self):
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group)
return all_panels | Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included. |
def add_album_art(file_name, album_art):
img = requests.get(album_art, stream=True)
img = img.raw
audio = EasyMP3(file_name, ID3=ID3)
try:
audio.add_tags()
except _util.error:
pass
audio.tags.add(
APIC(
encoding=3,
mime='image/png',
typ... | Add album_art in .mp3's tags |
def send(self, message):
for event in message.events:
self.events.append(event)
reply = riemann_client.riemann_pb2.Msg()
reply.ok = True
return reply | Adds a message to the list, returning a fake 'ok' response
:returns: A response message with ``ok = True`` |
def paused_partitions(self):
return set(partition for partition in self.assignment
if self.is_paused(partition)) | Return current set of paused TopicPartitions. |
def gnpool(name, start, room, lenout=_default_len_out):
name = stypes.stringToCharP(name)
start = ctypes.c_int(start)
kvars = stypes.emptyCharArray(yLen=room, xLen=lenout)
room = ctypes.c_int(room)
lenout = ctypes.c_int(lenout)
n = ctypes.c_int()
found = ctypes.c_int()
libspice.gnpool_c(... | Return names of kernel variables matching a specified template.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gnpool_c.html
:param name: Template that names should match.
:type name: str
:param start: Index of first matching name to retrieve.
:type start: int
:param room: The largest... |
def command(self):
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) | Manually import an OFX into a nYNAB budget |
def handle(self, object, *args, **kw):
if not bool(self):
if not self.spec or self.spec == SPEC_ALL:
raise ValueError('No plugins available in group %r' % (self.group,))
raise ValueError(
'No plugins in group %r matched %r' % (self.group, self.spec))
for plugin in self.plugins:
... | Calls each plugin in this PluginSet with the specified object,
arguments, and keywords in the standard group plugin order. The
return value from each successive invoked plugin is passed as the
first parameter to the next plugin. The final return value is the
object returned from the last plugin.
If... |
def load_fn_matches_ext(file_path, file_type):
correct_ext = False
curr_ext = os.path.splitext(file_path)[1]
exts = [curr_ext, file_type]
try:
if ".xlsx" in exts and ".xls" in exts:
correct_ext = True
elif curr_ext == file_type:
correct_ext = True
else:
... | Check that the file extension matches the target extension given.
:param str file_path: Path to be checked
:param str file_type: Target extension
:return bool correct_ext: Extension match or does not match |
def _isdictclass(obj):
c = getattr(obj, '__class__', None)
return c and c.__name__ in _dict_classes.get(c.__module__, ()) | Return True for known dict objects. |
def make_float(s, default='', ignore_commas=True):
r
if ignore_commas and isinstance(s, basestring):
s = s.replace(',', '')
try:
return float(s)
except (IndexError, ValueError, AttributeError, TypeError):
try:
return float(str(s))
except ValueError:
... | r"""Coerce a string into a float
>>> make_float('12,345')
12345.0
>>> make_float('12.345')
12.345
>>> make_float('1+2')
3.0
>>> make_float('+42.0')
42.0
>>> make_float('\r\n-42?\r\n')
-42.0
>>> make_float('$42.42')
42.42
>>> make_float('B-52')
-52.0
>>> make_... |
def clone_schema(self, base_schema_name, new_schema_name):
connection.set_schema_to_public()
cursor = connection.cursor()
try:
cursor.execute("SELECT 'clone_schema'::regproc")
except ProgrammingError:
self._create_clone_schema_function()
transaction.co... | Creates a new schema `new_schema_name` as a clone of an existing schema
`old_schema_name`. |
def prepare_notebook_context(request, notebook_context):
if not notebook_context:
notebook_context = {}
if "extra_template_paths" not in notebook_context:
notebook_context["extra_template_paths"] = [os.path.join(os.path.dirname(__file__), "server", "templates")]
assert type(notebook_context[... | Fill in notebook context with default values. |
def transform(self, fseries, **kwargs):
weight = 1 + numpy.log10(self.qrange[1]/self.qrange[0]) / numpy.sqrt(2)
nind, nplanes, peak, result = (0, 0, 0, None)
for plane in self:
nplanes += 1
nind += sum([1 + row.ntiles * row.deltam for row in plane])
result = p... | Compute the time-frequency plane at fixed Q with the most
significant tile
Parameters
----------
fseries : `~gwpy.timeseries.FrequencySeries`
the complex FFT of a time-series data set
**kwargs
other keyword arguments to pass to `QPlane.transform`
... |
def delete_by_ids(self, ids):
ids = utils.coerce_to_list(ids)
uri = "/%s?ids=%s" % (self.uri_base, ",".join(ids))
return self.api.method_delete(uri) | Deletes the messages whose IDs are passed in from this queue. |
def has_duplicate_keys(config_data, base_conf, raise_error):
duplicate_keys = set(base_conf) & set(config_data)
if not duplicate_keys:
return
msg = "Duplicate keys in config: %s" % duplicate_keys
if raise_error:
raise errors.ConfigurationError(msg)
log.info(msg)
return True | Compare two dictionaries for duplicate keys. if raise_error is True
then raise on exception, otherwise log return True. |
def maybe_obj(str_or_obj):
if not isinstance(str_or_obj, six.string_types):
return str_or_obj
parts = str_or_obj.split(".")
mod, modname = None, None
for p in parts:
modname = p if modname is None else "%s.%s" % (modname, p)
try:
mod = __import__(modname)
exce... | If argument is not a string, return it.
Otherwise import the dotted name and return that. |
def signature(array):
length = len(array)
index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length
return array[:index] | Returns the first 262 bytes of the given bytearray
as part of the file header signature.
Args:
array: bytearray to extract the header signature.
Returns:
First 262 bytes of the file content as bytearray type. |
def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()):
idlst = [funcID(e) for e in lst]
idlst.sort()
classes = [idlst[0]]
classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0] - t[1]) > 50]
lst = [(funcID(x), funcpres(x)) for x in lst]
lst.sort()
print("... | Identify IP id values classes in a list of packets
lst: a list of packets
funcID: a function that returns IP id values
funcpres: a function used to summarize packets |
def _transform_to_dict(result):
result_dict = {}
property_list = result.item
for item in property_list:
result_dict[item.key[0]] = item.value[0]
return result_dict | Transform the array from Ideone into a Python dictionary. |
def _create_dictionary_of_marshall(
self,
marshallQuery,
marshallTable):
self.log.debug(
'starting the ``_create_dictionary_of_marshall`` method')
dictList = []
tableName = self.dbTableName
rows = readquery(
log=self.log,
... | create a list of dictionaries containing all the rows in the marshall stream
**Key Arguments:**
- ``marshallQuery`` -- the query used to lift the required data from the marshall database.
- ``marshallTable`` -- the name of the marshall table we are lifting the data from.
**Retu... |
def CompileFilter(self, filter_expression):
filter_parser = pfilter.BaseParser(filter_expression).Parse()
matcher = filter_parser.Compile(pfilter.PlasoAttributeFilterImplementation)
self._filter_expression = filter_expression
self._matcher = matcher | Compiles the filter expression.
The filter expression contains an object filter expression.
Args:
filter_expression (str): filter expression.
Raises:
ParseError: if the filter expression cannot be parsed. |
def add_rollback_panels(self):
from wagtailplus.utils.edit_handlers import add_panel_to_edit_handler
from wagtailplus.wagtailrollbacks.edit_handlers import HistoryPanel
for model in self.applicable_models:
add_panel_to_edit_handler(model, HistoryPanel, _(u'History')) | Adds rollback panel to applicable model class's edit handlers. |
def vb_stop_vm(name=None, timeout=10000, **kwargs):
vbox = vb_get_box()
machine = vbox.findMachine(name)
log.info('Stopping machine %s', name)
session = _virtualboxManager.openMachineSession(machine)
try:
console = session.console
progress = console.powerDown()
progress.waitF... | Tells Virtualbox to stop a VM.
This is a blocking function!
@param name:
@type name: str
@param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely
@type timeout: int
@return untreated dict of stopped VM |
def RemoveClass(self, class_name):
if class_name not in self._class_mapping:
raise problems.NonexistentMapping(class_name)
del self._class_mapping[class_name] | Removes an entry from the list of known classes.
Args:
class_name: A string with the class name that is to be removed.
Raises:
NonexistentMapping if there is no class with the specified class_name. |
def path(*components):
_path = os.path.join(*components)
_path = os.path.expanduser(_path)
return _path | Get a file path.
Concatenate all components into a path. |
def _get_vswitch_name(self, network_type, physical_network):
if network_type != constants.TYPE_LOCAL:
vswitch_name = self._get_vswitch_for_physical_network(
physical_network)
else:
vswitch_name = self._local_network_vswitch
if vswitch_name:
ret... | Get the vswitch name for the received network information. |
def DeviceReadThread(hid_device):
hid_device.run_loop_ref = cf.CFRunLoopGetCurrent()
if not hid_device.run_loop_ref:
logger.error('Failed to get current run loop')
return
iokit.IOHIDDeviceScheduleWithRunLoop(hid_device.device_handle,
hid_device.run_loop_ref,
... | Binds a device to the thread's run loop, then starts the run loop.
Args:
hid_device: The MacOsHidDevice object
The HID manager requires a run loop to handle Report reads. This thread
function serves that purpose. |
def _score_clusters(self, X, y=None):
stype = self.scoring.lower()
if stype == "membership":
return np.bincount(self.estimator.labels_)
raise YellowbrickValueError("unknown scoring method '{}'".format(stype)) | Determines the "scores" of the cluster, the metric that determines the
size of the cluster visualized on the visualization. |
def extract_declarations(map_el, dirs, scale=1, user_styles=[]):
styles = []
for stylesheet in map_el.findall('Stylesheet'):
map_el.remove(stylesheet)
content, mss_href = fetch_embedded_or_remote_src(stylesheet, dirs)
if content:
styles.append((content, mss_href))
for sty... | Given a Map element and directories object, remove and return a complete
list of style declarations from any Stylesheet elements found within. |
def up(force=True, env=None, **kwargs):
"Starts a new experiment"
inventory = os.path.join(os.getcwd(), "hosts")
conf = Configuration.from_dictionnary(provider_conf)
provider = Enos_vagrant(conf)
roles, networks = provider.init()
check_networks(roles, networks)
env["roles"] = roles
env["... | Starts a new experiment |
def create_bare(self):
self.instances = []
for ip in self.settings['NODES']:
new_instance = Instance.new(settings=self.settings, cluster=self)
new_instance.ip = ip
self.instances.append(new_instance) | Create instances for the Bare provider |
def getNamedActionValue(self, name):
actions = self._actions
if (type (actions) is list):
for a in actions:
if a.get('name', 'NoValue') == name:
dict =a
else:
dict = actions
return dict.get('value', 'NoValue') | Get the value of the named Tropo action. |
def clean(self):
if self.pst_arg is None:
self.logger.statement("linear_analysis.clean(): not pst object")
return
if not self.pst.estimation and self.pst.nprior > 0:
self.drop_prior_information() | drop regularization and prior information observation from the jco |
def check_str(obj):
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | Returns a string for various input types |
def from_internal(self, attribute_profile, internal_dict):
external_dict = {}
for internal_attribute_name in internal_dict:
try:
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
except KeyError:
logger.debug("no attribute ... | Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute valu... |
def to_python(self, value):
value = super(TimeZoneField, self).to_python(value)
if not value:
return value
try:
return pytz.timezone(str(value))
except pytz.UnknownTimeZoneError:
raise ValidationError(
message=self.error_messages['inval... | Returns a datetime.tzinfo instance for the value. |
def __cond_from_desc(desc):
for code, [condition, detailed, exact, exact_nl] in __BRCONDITIONS.items():
if exact_nl == desc:
return {CONDCODE: code,
CONDITION: condition,
DETAILED: detailed,
EXACT: exact,
EXACTNL: ex... | Get the condition name from the condition description. |
def safe_kill(pid, signum):
assert(isinstance(pid, IntegerForPid))
assert(isinstance(signum, int))
try:
os.kill(pid, signum)
except (IOError, OSError) as e:
if e.errno in [errno.ESRCH, errno.EPERM]:
pass
elif e.errno == errno.EINVAL:
raise ValueError("Invalid signal number {}: {}"
... | Kill a process with the specified signal, catching nonfatal errors. |
def _on_event(self, event):
if self.has_option(event):
on_event = self.get_option(event).upper()
if on_event not in ["NO ACTION", "RESTRICT"]:
return on_event
return False | Returns the referential action for a given database operation
on the referenced table the foreign key constraint is associated with.
:param event: Name of the database operation/event to return the referential action for.
:type event: str
:rtype: str or None |
def retrieve_diaspora_host_meta(host):
document, code, exception = fetch_document(host=host, path="/.well-known/host-meta")
if exception:
return None
xrd = XRD.parse_xrd(document)
return xrd | Retrieve a remote Diaspora host-meta document.
:arg host: Host to retrieve from
:returns: ``XRD`` instance |
def devices(self):
response = self._call(
mc_calls.DeviceManagementInfo
)
registered_devices = response.body.get('data', {}).get('items', [])
return registered_devices | Get a listing of devices registered to the Google Music account. |
def download_previews(self, savedir=None):
for obsid in self.obsids:
pm = io.PathManager(obsid.img_id, savedir=savedir)
pm.basepath.mkdir(exist_ok=True)
basename = Path(obsid.medium_img_url).name
print("Downloading", basename)
urlretrieve(obsid.medium_... | Download preview files for the previously found and stored Opus obsids.
Parameters
==========
savedir: str or pathlib.Path, optional
If the database root folder as defined by the config.ini should not be used,
provide a different savedir here. It will be handed to PathMa... |
def loss_l2(self, l2=0):
if isinstance(l2, (int, float)):
D = l2 * torch.eye(self.d)
else:
D = torch.diag(torch.from_numpy(l2))
return torch.norm(D @ (self.mu - self.mu_init)) ** 2 | L2 loss centered around mu_init, scaled optionally per-source.
In other words, diagonal Tikhonov regularization,
||D(\mu-\mu_{init})||_2^2
where D is diagonal.
Args:
- l2: A float or np.array representing the per-source regularization
strengths to use |
def detect_suicidal_func(func):
if func.is_constructor:
return False
if func.visibility != 'public':
return False
calls = [c.name for c in func.internal_calls]
if not ('suicide(address)' in calls or 'selfdestruct(address)' in calls):
return False
... | Detect if the function is suicidal
Detect the public functions calling suicide/selfdestruct without protection
Returns:
(bool): True if the function is suicidal |
def _Start_refresh_timer(self):
if self._refreshPeriod > 60:
interval = self._refreshPeriod - 60
else:
interval = 60
self._refreshTimer = Timer(self._refreshPeriod, self.Refresh)
self._refreshTimer.setDaemon(True)
self._refreshTimer.start() | Internal method to support auto-refresh functionality. |
def as_fn(self, *binding_order):
if len(binding_order) != len(self.unbound_vars):
raise ValueError('All vars must be specified.')
for arg in binding_order:
if arg not in self.unbound_vars:
raise ValueError('Unknown binding: %s' % arg)
def func(*args, **kwargs):
if len(binding_order... | Creates a function by binding the arguments in the given order.
Args:
*binding_order: The unbound variables. This must include all values.
Returns:
A function that takes the arguments of binding_order.
Raises:
ValueError: If the bindings are missing values or include unknown values. |
def _postprocess_output(self, output):
if self.vowel_style == CIRCUMFLEX_STYLE:
try:
output = output.translate(vowels_to_circumflexes)
except TypeError:
pass
if self.uppercase:
output = output.upper()
return output | Performs the last modifications before the output is returned. |
def lazy_load(name):
def wrapper(load_fn):
@_memoize
def load_once(self):
if load_once.loading:
raise ImportError("Circular import when resolving LazyModule %r" % name)
load_once.loading = True
try:
module = load_fn()
finally:
load_once.loading = False
sel... | Decorator to define a function that lazily loads the module 'name'.
This can be used to defer importing troublesome dependencies - e.g. ones that
are large and infrequently used, or that cause a dependency cycle -
until they are actually used.
Args:
name: the fully-qualified name of the module; typically ... |
def make_permalink(img_id):
profile, filename = img_id.split(':', 1)
new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename)
urls = get_files_by_img_id(img_id)
if urls is None:
return urls
move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))}
for var... | Removes tmp prefix from filename and rename main and variant files.
Returns img_id without tmp prefix. |
def update_sandbox_site(comment_text):
file_to_deliver = NamedTemporaryFile(delete=False)
file_text = "Deployed at: {} <br /> Comment: {}".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text))
file_to_deliver.write(file_text)
file_to_deliver.close()
put(file_to_deliver.name, '/var... | put's a text file on the server |
def parse_data_port_mappings(mappings, default_bridge='br-data'):
_mappings = parse_mappings(mappings, key_rvalue=True)
if not _mappings or list(_mappings.values()) == ['']:
if not mappings:
return {}
_mappings = {mappings.split()[0]: default_bridge}
ports = _mappings.keys()
... | Parse data port mappings.
Mappings must be a space-delimited list of bridge:port.
Returns dict of the form {port:bridge} where ports may be mac addresses or
interface names. |
def fill(h1: Histogram1D, ax: Axes, **kwargs):
show_stats = kwargs.pop("show_stats", False)
density = kwargs.pop("density", False)
cumulative = kwargs.pop("cumulative", False)
kwargs["label"] = kwargs.get("label", h1.name)
data = get_data(h1, cumulative=cumulative, density=density)
_apply_xy_lim... | Fill plot of 1D histogram. |
def readpipe(self, chunk=None):
read = []
while True:
l = sys.stdin.readline()
if not l:
if read:
yield read
return
return
if not chunk:
yield l
else:
r... | Return iterator that iterates over STDIN line by line
If ``chunk`` is set to a positive non-zero integer value, then the
reads are performed in chunks of that many lines, and returned as a
list. Otherwise the lines are returned one by one. |
def resume(self, trigger_duration=0):
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False | Resumes pulse capture after an optional trigger pulse. |
def stylize(txt, bold=False, underline=False):
setting = ''
setting += _SET_BOLD if bold is True else ''
setting += _SET_UNDERLINE if underline is True else ''
return setting + str(txt) + _STYLE_RESET | Changes style of the text. |
def GetSchema(component):
parent = component
while not isinstance(parent, XMLSchema):
parent = parent._parent()
return parent | convience function for finding the parent XMLSchema instance. |
def db_dict(c):
db_d = {}
c.execute('SELECT * FROM library_spectra')
db_d['library_spectra'] = [list(row) for row in c]
c.execute('SELECT * FROM library_spectra_meta')
db_d['library_spectra_meta'] = [list(row) for row in c]
c.execute('SELECT * FROM library_spectra_annotation')
db_d['library_... | Get a dictionary of the library spectra from a database
Example:
>>> from msp2db.db import get_connection
>>> conn = get_connection('sqlite', 'library.db')
>>> test_db_d = db_dict(conn.cursor())
If using a large database the resulting dictionary will be very large!
Args:
c... |
def verified_funds(pronac, dt):
dataframe = data.planilha_comprovacao
project = dataframe.loc[dataframe['PRONAC'] == pronac]
segment_id = project.iloc[0]["idSegmento"]
pronac_funds = project[
["idPlanilhaAprovacao", "PRONAC", "vlComprovacao", "idSegmento"]
]
funds_grp = pronac_funds.drop... | Responsable for detecting anomalies in projects total verified funds. |
def ping(destination, source=None, ttl=None, timeout=None, size=None, count=None, vrf=None, **kwargs):
return salt.utils.napalm.call(
napalm_device,
'ping',
**{
'destination': destination,
'source': source,
'ttl': ttl,
'timeout': timeout,
... | Executes a ping on the network device and returns a dictionary as a result.
destination
Hostname or IP address of remote host
source
Source address of echo request
ttl
IP time-to-live value (IPv6 hop-limit value) (1..255 hops)
timeout
Maximum wait time after sending f... |
def _run_markdownlint(matched_filenames, show_lint_files):
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdo... | Run markdownlint on matched_filenames. |
def run_cufflinks(data):
if "cufflinks" in dd.get_tools_off(data):
return [[data]]
work_bam = dd.get_work_bam(data)
ref_file = dd.get_sam_ref(data)
out_dir, fpkm_file, fpkm_isoform_file = cufflinks.run(work_bam, ref_file, data)
data = dd.set_cufflinks_dir(data, out_dir)
data = dd.set_fpk... | Quantitate transcript expression with Cufflinks |
def minimum_needs_section_header_element(feature, parent):
_ = feature, parent
header = minimum_needs_section_header['string_format']
return header.capitalize() | Retrieve minimum needs section header string from definitions. |
def show_syspath(self, syspath):
if syspath is not None:
editor = CollectionsEditor(self)
editor.setup(syspath, title="sys.path contents", readonly=True,
width=600, icon=ima.icon('syspath'))
self.dialog_manager.show(editor)
else:
... | Show sys.path contents. |
def update_standings(semester=None, pool_hours=None, moment=None):
if semester is None:
try:
semester = Semester.objects.get(current=True)
except (Semester.DoesNotExist, Semester.MultipleObjectsReturned):
return []
if moment is None:
moment = localtime(now())
... | This function acts to update a list of PoolHours objects to adjust their
current standing based on the time in the semester.
Parameters
----------
semester : workshift.models.Semester, optional
pool_hours : list of workshift.models.PoolHours, optional
If None, runs on all pool hours for sem... |
def get_events(self, service_location_id, appliance_id, start, end,
max_number=None):
start = self._to_milliseconds(start)
end = self._to_milliseconds(end)
url = urljoin(URLS['servicelocation'], service_location_id, "events")
headers = {"Authorization": "Bearer {}".for... | Request events for a given appliance
Parameters
----------
service_location_id : int
appliance_id : int
start : int | dt.datetime | pd.Timestamp
end : int | dt.datetime | pd.Timestamp
start and end support epoch (in milliseconds),
datetime and Pan... |
def exists(self, target, path, path_sep="/"):
if path.endswith(path_sep):
path = path[:-len(path_sep)]
par_dir, filename = path.rsplit(path_sep, 1)
file_list = self.list_files(target, par_dir)
out_dict = {}
for device_id, device_data in six.iteritems(file_list):
... | Check if path refers to an existing path on the device
:param target: The device(s) to be targeted with this request
:type target: :class:`devicecloud.sci.TargetABC` or list of :class:`devicecloud.sci.TargetABC` instances
:param path: The path on the target to check for existence.
:para... |
def clone(self, substitutions, **kwargs):
dag = self.explain(**kwargs)
dag.substitutions.update(substitutions)
cloned_dag = dag.clone(ignore=self.ignore)
return self.update_nodes(self.add_edges(cloned_dag)) | Clone a DAG. |
def _did_receive_response(self, response):
try:
data = response.json()
except:
data = None
self._response = NURESTResponse(status_code=response.status_code, headers=response.headers, data=data, reason=response.reason)
level = logging.WARNING if self._response.stat... | Called when a response is received |
def remove_locations(node):
def fix(node):
if 'lineno' in node._attributes and hasattr(node, 'lineno'):
del node.lineno
if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):
del node.col_offset
for child in iter_child_nodes(node):
fix(child)... | Removes locations from the given AST tree completely |
def delete(self, key):
super(DirectoryTreeDatastore, self).delete(key)
str_key = str(key)
if str_key == '/':
return
dir_key = key.parent.instance('directory')
directory = self.directory(dir_key)
if directory and str_key in directory:
directory.remove(str_key)
if len(directory) ... | Removes the object named by `key`.
DirectoryTreeDatastore removes the directory entry. |
def get_listener_instance(self, cls):
with self._lock:
for listener in self._listeners:
if isinstance(listener, cls):
return listener | If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener` |
def writeInfo(self, stream):
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size) | Write information about diffs into a file stream for use later. |
def related(self, *, exclude_self=False):
manager = type(self)._default_manager
queryset = manager.related_to(self)
if exclude_self:
queryset = queryset.exclude(id=self.id)
return queryset | Get a QuerySet for all trigger log objects for the same connected model.
Args:
exclude_self (bool): Whether to exclude this log object from the result list |
def _maintain_LC(self, obj, slice_id, last_slice=False, begin_slice=True,
shard_ctx=None, slice_ctx=None):
if obj is None or not isinstance(obj, shard_life_cycle._ShardLifeCycle):
return
shard_context = shard_ctx or self.shard_context
slice_context = slice_ctx or self.slice_context
... | Makes sure shard life cycle interface are respected.
Args:
obj: the obj that may have implemented _ShardLifeCycle.
slice_id: current slice_id
last_slice: whether this is the last slice.
begin_slice: whether this is the beginning or the end of a slice.
shard_ctx: shard ctx for dependen... |
def series_expand(
self, param: Symbol, about, order: int) -> tuple:
r
expansion = self._series_expand(param, about, order)
res = []
for v in expansion:
if v == 0 or v.is_zero:
v = self._zero
elif v == 1:
v = self._one
... | r"""Expand the expression as a truncated power series in a
scalar parameter.
When expanding an expr for a parameter $x$ about the point $x_0$ up to
order $N$, the resulting coefficients $(c_1, \dots, c_N)$ fulfill
.. math::
\text{expr} = \sum_{n=0}^{N} c_n (x - x_0)^n + O(... |
def _clean_filepath(self, filepath):
if (os.path.isdir(filepath) and
os.path.isfile(os.path.join(filepath, '__init__.py'))):
filepath = os.path.join(filepath, '__init__.py')
if (not filepath.endswith('.py') and
os.path.isfile(filepath + '.py')):
fi... | processes the filepath by checking if it is a directory or not
and adding `.py` if not present. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.