Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
13,100 | def pre_save(self, instance, add: bool):
if not isinstance(instance, AtomicSlugRetryMixin):
raise ImproperlyConfigured((
%s\
) % type(instance).__name__)
slugs = LocalizedValue()
for lang_code, value in self._get_populate_value... | Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or an update.
Returns:
The locali... |
13,101 | def getFullFMAtIndex(self, index):
if index == self.totalSize:
return np.cumsum(self.totalCounts)
binID = index >> self.bitPower
bwtIndex = self.refFM[binID]
ret = np.copy(self.partialFM[binID])
trueIndex = np.sum(ret)-self... | This function creates a complete FM-index for a specific position in the BWT. Example using the above example:
BWT Full FM-index
$ A C G T
C 0 1 2 4 4
$ 0 1 3 4 4
C 1 1 3 4 4
A 1 1 4 4 4
1 2 4 4 4
@return -... |
13,102 | def list(self, page=1, per_page=50):
data = {"page": page,
"per_page": per_page}
return self.get(self.base_url, data=data) | Lists Jobs.
https://app.zencoder.com/docs/api/jobs/list |
13,103 | def _get_create_table_sql(self, table_name, columns, options=None):
options = options or {}
column_list_sql = self.get_column_declaration_list_sql(columns)
if options.get("unique_constraints"):
for name, definition in options["unique_constraints"].items():
... | Returns the SQL used to create a table.
:param table_name: The name of the table to create
:type table_name: str
:param columns: The table columns
:type columns: dict
:param options: The options
:type options: dict
:rtype: str |
13,104 | def new_pic(cls, id_, name, desc, rId, left, top, width, height):
xml = cls._pic_tmpl() % (
id_, name, desc, rId, left, top, width, height
)
pic = parse_xml(xml)
return pic | Return a new ``<p:pic>`` element tree configured with the supplied
parameters. |
13,105 | def _try_larger_image(self, roi, cur_text, cur_mrz, filter_order=3):
if roi.shape[1] <= 700:
scale_by = int(1050.0 / roi.shape[1] + 0.5)
roi_lg = transform.rescale(roi, scale_by, order=filter_order, mode=, multichannel=False,
anti_aliasing=... | Attempts to improve the OCR result by scaling the image. If the new mrz is better, returns it, otherwise returns
the old mrz. |
13,106 | def _get_symbol_index(stroke_id_needle, segmentation):
for symbol_index, symbol in enumerate(segmentation):
if stroke_id_needle in symbol:
return symbol_index
return None | Parameters
----------
stroke_id_needle : int
Identifier for the stroke of which the symbol should get found.
segmentation : list of lists of integers
An ordered segmentation of strokes to symbols.
Returns
-------
The symbol index in which stroke_id_needle occurs
Examples
... |
13,107 | def connect_attenuator(self, connect=True):
if connect:
try:
pa5 = win32com.client.Dispatch("PA5.x")
success = pa5.ConnectPA5(, 1)
if success == 1:
print
pass
else:
p... | Establish a connection to the TDT PA5 attenuator |
13,108 | def select_python_parser(parser=None):
if parser == or os.environ.get():
PythonFile.Class = RedbaronPythonFile
else:
PythonFile.Class = ParsoPythonFile | Select default parser for loading and refactoring steps. Passing `redbaron` as argument
will select the old paring engine from v0.3.3
Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our
best to make sure there is no user impact on users. However, there may ... |
13,109 | def get_authorizations_by_ids(self, authorization_ids):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
object_id_list = []
for i in authorization_ids:
... | Gets an ``AuthorizationList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the
authorizations specified in the ``Id`` list, in the order of the
list, including duplicates, or an error results if an ``Id`` in
the supplied list is not found or ... |
13,110 | def json_encoder_default(obj):
if np is not None and hasattr(obj, ) and hasattr(obj, ):
if obj.size == 1:
if np.issubdtype(obj.dtype, np.integer):
return int(obj)
elif np.issubdtype(obj.dtype, np.floating):
return float(obj)
if isinstance(obj... | Handle more data types than the default JSON encoder.
Specifically, it treats a `set` and a `numpy.array` like a `list`.
Example usage: ``json.dumps(obj, default=json_encoder_default)`` |
13,111 | def _merge_results(self, results):
self.results[] += results[]
for key, value in results[].items():
self.results[][key] += value | Combine results of test run with exisiting dict. |
13,112 | def hsl_to_rgb(h, s=None, l=None):
if type(h) in [list,tuple]:
h, s, l = h
if s==0: return (l, l, l)
if l<0.5: n2 = l * (1.0 + s)
else: n2 = l+s - (l*s)
n1 = (2.0 * l) - n2
h /= 60.0
hueToRgb = _hue_to_rgb
r = hueToRgb(n1, n2, h + 2)
g = hueToRgb(n1, n2, h)
b = hueToRgb(n1, n2, h - 2)
... | Convert the color from HSL coordinates to RGB.
Parameters:
:h:
The Hue component value [0...1]
:s:
The Saturation component value [0...1]
:l:
The Lightness component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
>... |
13,113 | def weld_iloc_int(array, index):
obj_id, weld_obj = create_weld_object(array)
weld_template =
weld_obj.weld_code = weld_template.format(array=obj_id,
index=index)
return weld_obj | Retrieves the value at index.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data. Assumed to be bool data.
index : int
The array index from which to retrieve value.
Returns
-------
WeldObject
Representation of this computation. |
13,114 | def port(self, value):
if value is not None:
assert type(value) is int, " attribute: type is not !".format(
"port", value)
assert type(value) >= 0 and type(value) >= 65535, \
" attribute: value must be in 0-65535 range!".format("port", value)
... | Setter for **self.__port** attribute.
:param value: Attribute value.
:type value: int |
13,115 | def approve(self):
url = self.reddit_session.config[]
data = {: self.fullname}
response = self.reddit_session.request_json(url, data=data)
urls = [self.reddit_session.config[x] for x in [, ]]
if isinstance(self, Submission):
urls += self.subreddit._listing_ur... | Approve object.
This reverts a removal, resets the report counter, marks it with a
green check mark (only visible to other moderators) on the website view
and sets the approved_by attribute to the logged in user.
:returns: The json response from the server. |
13,116 | def _add_request_data(data, request):
try:
request_data = _build_request_data(request)
except Exception as e:
log.exception("Exception while building request_data for Rollbar payload: %r", e)
else:
if request_data:
_filter_ip(request_data, SETTINGS[])
dat... | Attempts to build request data; if successful, sets the 'request' key on `data`. |
13,117 | def createTileUrl(self, x, y, z):
return self.tileTemplate.replace(, str(x)).replace(, str(
y)).replace(, str(z)) | returns new tile url based on template |
13,118 | def run_apidoc(_):
import os
dirname = os.path.dirname(__file__)
ignore_paths = [os.path.join(dirname, ),]
argv = [
,
,
,
,
,
os.path.join(dirname, ),
os.path.join(dirname, ),
] + ignore_paths
from sphinx.ext import apidoc
a... | This method is required by the setup method below. |
13,119 | def validate_args(self):
def validate_name():
allowed_re =
assert isinstance(self.params[], basestring), (
% repr(self.params[]))
assert re.match(allowed_re, self.params[]), (
% (
repr(self.params[]), repr(allowe... | Input validation! |
13,120 | def get_change_values(change):
action, rrset = change
if action == :
values[key] = getattr(rrset, key)
return values
else:
return rrset._initial_vals | In the case of deletions, we pull the change values for the XML request
from the ResourceRecordSet._initial_vals dict, since we want the original
values. For creations, we pull from the attributes on ResourceRecordSet.
Since we're dealing with attributes vs. dict key/vals, we'll abstract
this part away... |
13,121 | def count(args):
from jcvi.graphics.histogram import stem_leaf_plot
from jcvi.utils.cbook import SummaryStats
p = OptionParser(count.__doc__)
p.add_option("--csv", help="Write depth per contig to file")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help()... | %prog count cdhit.consensus.fasta
Scan the headers for the consensus clusters and count the number of reads. |
13,122 | def volume(self) -> float:
m = self._matrix
return float(abs(dot(np.cross(m[0], m[1]), m[2]))) | Volume of the unit cell. |
13,123 | def expand_file_names(path, files_root):
if not any(wildcard in path for wildcard in ):
return [path]
else:
dir_path, filename = os.path.split(path)
return [os.path.join(dir_path, f) for f in fnmatch.filter(os.listdir(os.path.join(files_root, dir_path)), filename)] | Expands paths (e.g. css/*.css in files_root /actual/path/to/css/files/) |
13,124 | def get_annotations(self):
try:
obj_list = self.__dict__[]
return [Annotation(i) for i in obj_list]
except KeyError:
self._lazy_load()
obj_list = self.__dict__[]
return [Annotation(i) for i in obj_list] | Fetch the annotations field if it does not exist. |
13,125 | def posted_data_dict(self):
if not self.query:
return None
from django.http import QueryDict
roughdecode = dict(item.split(, 1) for item in self.query.split())
encoding = roughdecode.get(, None)
if encoding is None:
encoding = DEFAULT_ENCODING
... | All the data that PayPal posted to us, as a correctly parsed dictionary of values. |
13,126 | def delete_pool_member(hostname, username, password, name, member):
ret = {: name, : {}, : False, : }
if __opts__[]:
return _test_output(ret, , params={
: hostname,
: username,
: password,
: name,
: member
}
)
e... | Delete an existing pool member.
hostname
The host/address of the bigip device
username
The iControl REST username
password
The iControl REST password
name
The name of the pool to be modified
member
The name of the member to delete from the pool |
13,127 | def render(template, namespace, app=None):
app = app or state.app
return app.render(template, namespace) | Render the specified template using the Pecan rendering framework
with the specified template namespace as a dictionary. Useful in a
controller where you have no template specified in the ``@expose``.
:param template: The path to your template, as you would specify in
``@expose``.
... |
13,128 | def follow(user, obj, send_action=True, actor_only=True, flag=, **kwargs):
check(obj)
instance, created = apps.get_model(, ).objects.get_or_create(
user=user, object_id=obj.pk, flag=flag,
content_type=ContentType.objects.get_for_model(obj),
actor_only=actor_only
)
if send_ac... | Creates a relationship allowing the object's activities to appear in the
user's stream.
Returns the created ``Follow`` instance.
If ``send_action`` is ``True`` (the default) then a
``<user> started following <object>`` action signal is sent.
Extra keyword arguments are passed to the action.send ca... |
13,129 | def make_mixture_prior(latent_size, mixture_components):
if mixture_components == 1:
return tfd.MultivariateNormalDiag(
loc=tf.zeros([latent_size]),
scale_identity_multiplier=1.0)
loc = tf.compat.v1.get_variable(
name="loc", shape=[mixture_components, latent_size])
raw_scale_dia... | Creates the mixture of Gaussians prior distribution.
Args:
latent_size: The dimensionality of the latent representation.
mixture_components: Number of elements of the mixture.
Returns:
random_prior: A `tfd.Distribution` instance representing the distribution
over encodings in the absence of any ... |
13,130 | def unpack_thin(thin_path):
tfile = tarfile.TarFile.gzopen(thin_path)
old_umask = os.umask(0o077)
tfile.extractall(path=OPTIONS.saltdir)
tfile.close()
os.umask(old_umask)
try:
os.unlink(thin_path)
except OSError:
pass
reset_time(OPTIONS.saltdir) | Unpack the Salt thin archive. |
13,131 | def _iter_module_files():
for module in list(sys.modules.values()):
if module is None:
continue
filename = getattr(module, "__file__", None)
if filename:
if os.path.isdir(filename) and os.path.exists(
os.path.join(filename, "__init__.py"... | This iterates over all relevant Python files. It goes through all
loaded files from modules, all files in folders of already loaded modules
as well as all files reachable through a package. |
13,132 | def smooth(x, window_len=7, window=):
if len(x) < window_len:
raise ValueError("Input vector length must be >= window length.")
if window_len < 3:
raise ValueError("Window length must be at least 3.")
if not window_len % 2:
window_len += 1
print("Window length reset ... | Smooth the data in x using convolution with a window of requested
size and type.
Parameters
----------
x : array_like(float)
A flat NumPy array containing the data to smooth
window_len : scalar(int), optional
An odd integer giving the length of the window. Defaults to 7.
window... |
13,133 | def search(name,
jail=None,
chroot=None,
root=None,
exact=False,
glob=False,
regex=False,
pcre=False,
comment=False,
desc=False,
full=False,
depends=False,
size=False,
quiet=Fal... | Searches in remote package repositories
CLI Example:
.. code-block:: bash
salt '*' pkg.search pattern
jail
Perform the search using the ``pkg.conf(5)`` from the specified jail
CLI Example:
.. code-block:: bash
salt '*' pkg.search pattern jail=<jail name or ... |
13,134 | def _cloglog_transform_deriv_v(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
output_array=None,
*args, **kwargs):
exp_neg_v = np.exp(-1 * syste... | Parameters
----------
systematic_utilities : 1D ndarray.
All elements should be ints, floats, or longs. Should contain the
systematic utilities of each observation per available alternative.
Note that this vector is formed by the dot product of the design matrix
with the vector o... |
13,135 | def dashboard(request):
"Counts, aggregations and more!"
end_time = now()
start_time = end_time - timedelta(days=7)
defaults = {: start_time, : end_time}
form = DashboardForm(data=request.GET or defaults)
if form.is_valid():
start_time = form.cleaned_data[]
end_time = form.clean... | Counts, aggregations and more! |
13,136 | def get(cls, resource_type):
if isinstance(resource_type, str):
obj = getattr(db, cls.__name__).find_one(cls.resource_type == resource_type)
elif isinstance(resource_type, int):
obj = getattr(db, cls.__name__).find_one(cls.resource_type_id == resource_type)
eli... | Returns the ResourceType object for `resource_type`. If no existing object was found, a new type will
be created in the database and returned
Args:
resource_type (str): Resource type name
Returns:
:obj:`ResourceType` |
13,137 | def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)):
subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId))
if subPattern:
return PatternConstructors[patternId](pattern=subPattern) | Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)). |
13,138 | def transform_folder(args):
command, (transform, src, dest) = args
try:
print(progress.value, "remaining")
data = []
data_dir = os.path.join(src, command)
for filename in os.listdir(data_dir):
path = os.path.join(data_dir, filename)
data.append(transform({: path}))
pic... | Transform all the files in the source dataset for the given command and save
the results as a single pickle file in the destination dataset
:param args: tuple with the following arguments:
- the command name: 'zero', 'one', 'two', ...
- transforms to apply to wav file
- ... |
13,139 | def zadd(self, key, score, member, *pairs, exist=None):
if not isinstance(score, (int, float)):
raise TypeError("score argument must be int or float")
if len(pairs) % 2 != 0:
raise TypeError("length of pairs must be even number")
scores = (item for i, item in en... | Add one or more members to a sorted set or update its score.
:raises TypeError: score not int or float
:raises TypeError: length of pairs is not even number |
13,140 | def _set_channels(self):
logger.debug("=====================")
logger.debug("Setting main channels")
logger.debug("=====================")
for i, p in enumerate(self.processes):
logger.debug("[{}] Setting main channels with pid: {}".format(
... | Sets the main channels for the pipeline
This method will parse de the :attr:`~Process.processes` attribute
and perform the following tasks for each process:
- Sets the input/output channels and main input forks and adds
them to the process's
:attr:`flowcraft.pro... |
13,141 | def last_first_initial(self):
return ("{}{} ".format(self.last_name, ", " + self.first_name[:1] + "." if self.first_name else "") + ("({}) ".format(self.nickname)
if self.nickname else "")) | Return a name in the format of:
Lastname, F [(Nickname)] |
13,142 | def get_state_actions(self, state, **kwargs):
if state.base_state == State.ABSENT:
if state.config_id.config_type == ItemType.IMAGE:
return [ItemAction(state, ImageAction.PULL)]
actions = [ItemAction(state, Action.CREATE, extra_data=kwargs)]
if state.... | Creates all missing containers, networks, and volumes.
:param state: Configuration state.
:type state: dockermap.map.state.ConfigState
:param kwargs: Additional keyword arguments.
:return: Actions on the client, map, and configurations.
:rtype: list[dockermap.map.action.ItemActi... |
13,143 | def getfield(self, pkt, s):
ext = pkt.get_field(self.length_of)
tmp_len = ext.length_from(pkt)
if tmp_len is None or tmp_len <= 0:
v = pkt.tls_session.tls_version
if v is None or v < 0x0304:
return s, None
return super(_ExtensionsLenField,... | We try to compute a length, usually from a msglen parsed earlier.
If this length is 0, we consider 'selection_present' (from RFC 5246)
to be False. This means that there should not be any length field.
However, with TLS 1.3, zero lengths are always explicit. |
13,144 | def edit(i):
o=i.get(,)
ruoa=i.get(,)
muoa=i.get(,)
duoa=i.get(,)
iu=i.get(,)
if iu==: iu=
ed=i.get(,)
sk=i.get(,)
if sk==: sk=
ii={:,
:ruoa,
:muoa,
:duoa,
:}
r=access(ii)
if r[]>0: return r
desc=r.get(,{})
meta=r[]
... | Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
(ignore_update) - (default==yes) if 'yes', do not add info about update
(sort_keys) - (default==yes) if 'yes', sort k... |
13,145 | def get_subscription_by_channel_id_and_endpoint_id(
self, channel_id, endpoint_id):
subscriptions = self.search_subscriptions(
channel_id=channel_id, endpoint_id=endpoint_id)
try:
return subscriptions[0]
except IndexError:
raise DataFailu... | Search for subscription by a given channel and endpoint |
13,146 | def search_reports(self, search_term=None,
enclave_ids=None,
from_time=None,
to_time=None,
tags=None,
excluded_tags=None):
return Page.get_generator(page_generator=self._search_reports_pa... | Uses the |search_reports_page| method to create a generator that returns each successive report.
:param str search_term: The term to search for. If empty, no search term will be applied. Otherwise, must
be at least 3 characters.
:param list(str) enclave_ids: list of enclave ids used to re... |
13,147 | def main(device_type):
args = create_agent_parser(device_type=device_type).parse_args()
util.setup_logging(verbosity=args.verbose, filename=args.log_file)
public_keys = None
filename = None
if args.identity.startswith():
filename = args.identity
contents = open(filename, ).read... | Run ssh-agent using given hardware client factory. |
13,148 | def send(self, stream, retry=16, timeout=60, quiet=0, callback=None):
/etc/issuerb
try:
packet_size = dict(
xmodem = 128,
xmodem1k = 1024,
)[self.mode]
except AttributeError:
raise ValueError("An invalid mode was s... | Send a stream via the XMODEM protocol.
>>> stream = file('/etc/issue', 'rb')
>>> print modem.send(stream)
True
Returns ``True`` upon succesful transmission or ``False`` in case of
failure.
:param stream: The stream object to send data from.
:type st... |
13,149 | def update_widget(self, idx=None):
if idx is None:
for w in self._widgets:
idx = self._get_idx_from_widget(w)
self._write_widget(self._read_property(idx), idx)
pass
else: self._write_widget(self._read_property(idx), idx)
return | Forces the widget at given index to be updated from the
property value. If index is not given, all controlled
widgets will be updated. This method should be called
directly by the user when the property is not observable, or
in very unusual conditions. |
13,150 | def delete(config, username, type):
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | Delete an LDAP user. |
13,151 | def parse_user_params(user_params):
if user_params:
params = {}
try:
for param in options.params.split():
param_key, param_value = param.split(, 1)
params[param_key] = param_value
except ValueError as e:
sys.stdout.write("Invalid p... | Parse the user params (-p/--params) and them as a dict. |
13,152 | def detach(self):
from . import _ndarray_cls
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayDetach(self.handle, ctypes.byref(hdl)))
return _ndarray_cls(hdl) | Returns a new NDArray, detached from the current graph. |
13,153 | def add_relation(app_f, app_t, weight=1):
recs = TabRel.select().where(
(TabRel.post_f_id == app_f) & (TabRel.post_t_id == app_t)
)
if recs.count() > 1:
for record in recs:
MRelation.delete(record.uid)
if recs.count() == 0:
ui... | Adding relation between two posts. |
13,154 | def add_sources_from_roi(self, names, roi, free=False, **kwargs):
for name in names:
self.add_source(name, roi[name].data, free=free, **kwargs) | Add multiple sources to the current ROI model copied from another ROI model.
Parameters
----------
names : list
List of str source names to add.
roi : `~fermipy.roi_model.ROIModel` object
The roi model from which to add sources.
free : bool
... |
13,155 | def yaml2tree(cls, yamltree):
if not cls.YAML_setup:
cls.setup_yaml()
cls.YAML_setup = True
if os.path.isfile(yamltree):
with open(yamltree) as fh:
yaml_data = fh.read()
else:
yaml_data = yamltree
list_of_nodes = y... | Class method that creates a tree from YAML.
| # Example yamltree data:
| - !Node &root
| name: "root node"
| parent: null
| data:
| testpara: 111
| - !Node &child1
| name: "child node"
| parent: *root
| - !Node &gc1
|... |
13,156 | def get_ser_val_alt(lat: float, lon: float,
da_alt_x: xr.DataArray,
da_alt: xr.DataArray, da_val: xr.DataArray)->pd.Series:
alt_t_1d = da_alt.sel(
latitude=lat, longitude=lon, method=)
val_t_1d = da_val.sel(
latitude=lat, longitude=lon, method=)
... | interpolate atmospheric variable to a specified altitude
Parameters
----------
lat : float
latitude of specified site
lon : float
longitude of specified site
da_alt_x : xr.DataArray
desired altitude to interpolate variable at
da_alt : xr.DataArray
altitude associ... |
13,157 | def transform(self, X):
self._check_fitted()
M = self.smoothness
dim = self.dim_
inds = self.inds_
do_check = self.do_bounds_check
X = as_features(X)
if X.dim != dim:
msg = "model fit for dimension {} but got dim {}"
raise ValueEr... | Transform a list of bag features into its projection series
representation.
Parameters
----------
X : :class:`skl_groups.features.Features` or list of bag feature arrays
New data to transform. The data should all lie in [0, 1];
use :class:`skl_groups.preprocessin... |
13,158 | def open(self):
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)
if self.device is not None:
print "Serial printer enabled"
else:
... | Setup serial port and set is as escpos device |
13,159 | def get_free_sphere_params(structure, rad_dict=None, probe_rad=0.1):
with ScratchDir():
name = "temp_zeo1"
zeo_inp_filename = name + ".cssr"
ZeoCssr(structure).write_file(zeo_inp_filename)
rad_file = None
rad_flag = False
if rad_dict:
rad_file = nam... | Analyze the void space in the input structure using voronoi decomposition
Calls Zeo++ for Voronoi decomposition.
Args:
structure: pymatgen.core.structure.Structure
rad_dict (optional): Dictionary of radii of elements in structure.
If not given, Zeo++ default values are used.
... |
13,160 | def generate_files(engine, crypto_factory, min_dt=None, max_dt=None,
logger=None):
return _generate_notebooks(files, files.c.created_at,
engine, crypto_factory, min_dt, max_dt, logger) | Create a generator of decrypted files.
Files are yielded in ascending order of their timestamp.
This function selects all current notebooks (optionally, falling within a
datetime range), decrypts them, and returns a generator yielding dicts,
each containing a decoded notebook and metadata including th... |
13,161 | def nv_tuple_list_replace(l, v):
_found = False
for i, x in enumerate(l):
if x[0] == v[0]:
l[i] = v
_found = True
if not _found:
l.append(v) | replace a tuple in a tuple list |
13,162 | def _hybrid_select_metrics(self, dup_bam, bait_file, target_file):
metrics = self._check_metrics_file(dup_bam, "hs_metrics")
if not file_exists(metrics):
with bed_to_interval(bait_file, dup_bam) as ready_bait:
with bed_to_interval(target_file, dup_bam) as ready_targe... | Generate metrics for hybrid selection efficiency. |
13,163 | def deleted(message):
def deleted(value, _context, **_params):
return Deleted(value, message)
return deleted | Create a Deleted response builder with specified message. |
13,164 | def get_software_package_compilation_timestamp(cls,calc,**kwargs):
from dateutil.parser import parse
try:
date = calc.out.job_info.get_dict()[]
return parse(date.replace(, )).isoformat()
except Exception:
return None | Returns the timestamp of package/program compilation in ISO 8601
format. |
13,165 | def update_features(self, poly):
for feature in self.features:
feature.wavelength = poly(feature.xpos) | Evaluate wavelength at xpos using the provided polynomial. |
13,166 | def error_and_result(f):
@wraps(f)
def error_and_result_decorator(*args, **kwargs):
return error_and_result_decorator_inner_fn(f, False, *args, **kwargs)
return error_and_result_decorator | Format task result into json dictionary `{'data': task return value}` if no
exception was raised during the task execution. If there was raised an
exception during task execution, formats task result into dictionary
`{'error': exception message with traceback}`. |
13,167 | def dict_from_prefix(cls, prefix, dictionary):
o_dictionary = OrderedDict()
for key, val in dictionary.items():
if key.startswith(prefix):
o_dictionary[key[len(prefix):].strip()] = val
dictionary = o_dictionary
if len(dictionary) == 0:
re... | >>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od["problem[q0][a]"]=1
>>> od["problem[q0][b][c]"]=2
>>> od["problem[q1][first]"]=1
>>> od["problem[q1][second]"]=2
>>> AdminCourseEditTask.dict_from_prefix("problem",od)
... |
13,168 | def OnPasteFormat(self, event):
with undo.group(_("Paste format")):
self.grid.actions.paste_format()
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
self.grid.actions.zoom() | Paste format event handler |
13,169 | def iteritems(self, indices=None):
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | Iterate through items in the ``indices`` (defaults to all indices) |
13,170 | def gen_cartesian_product(*args):
if not args:
return []
elif len(args) == 1:
return args[0]
product_list = []
for product_item_tuple in itertools.product(*args):
product_item_dict = {}
for item in product_item_tuple:
product_item_dict.update(item)
... | generate cartesian product for lists
Args:
args (list of list): lists to be generated with cartesian product
Returns:
list: cartesian product in list
Examples:
>>> arg1 = [{"a": 1}, {"a": 2}]
>>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}]
>>> args = [arg1... |
13,171 | def AddContract(self, contract):
super(UserWallet, self).AddContract(contract)
try:
db_contract = Contract.get(ScriptHash=contract.ScriptHash.ToBytes())
db_contract.delete_instance()
except Exception as e:
logger.debug("contract does not exist yet")
... | Add a contract to the database.
Args:
contract(neo.SmartContract.Contract): a Contract instance. |
13,172 | def load_conf(cfg_path):
global config
try:
cfg = open(cfg_path, )
except Exception as ex:
if verbose:
print("Unable to open {0}".format(cfg_path))
print(str(ex))
return False
cfg_json = cfg.read()
cfg.close()
try:
con... | Try to load the given conf file. |
13,173 | def add_keywords_from_list(self, keyword_list):
if not isinstance(keyword_list, list):
raise AttributeError("keyword_list should be a list")
for keyword in keyword_list:
self.add_keyword(keyword) | To add keywords from a list
Args:
keyword_list (list(str)): List of keywords to add
Examples:
>>> keyword_processor.add_keywords_from_list(["java", "python"]})
Raises:
AttributeError: If `keyword_list` is not a list. |
13,174 | def start_adc_comparator(self, channel, high_threshold, low_threshold,
gain=1, data_rate=None, active_low=True,
traditional=True, latching=False, num_readings=1):
assert 0 <= channel <= 3,
return self._read_comparator(... | Start continuous ADC conversions on the specified channel (0-3) with
the comparator enabled. When enabled the comparator to will check if
the ADC value is within the high_threshold & low_threshold value (both
should be signed 16-bit integers) and trigger the ALERT pin. The
behavior can... |
13,175 | def po_to_ods(languages, locale_root, po_files_path, temp_file_path):
title_row = [, , ]
title_row += map(lambda s: s + , languages)
ods = ODS()
_prepare_ods_columns(ods, title_row)
po_files = _get_all_po_filenames(locale_root, languages[0], po_files_path)
i = 1
for po_filename in p... | Converts po file to csv GDocs spreadsheet readable format.
:param languages: list of language codes
:param locale_root: path to locale root folder containing directories
with languages
:param po_files_path: path from lang directory to po file
:param temp_file_path: path where tem... |
13,176 | def ParseOptions(cls, options, analysis_plugin):
if not isinstance(analysis_plugin, viper.ViperAnalysisPlugin):
raise errors.BadConfigObject(
)
lookup_hash = cls._ParseStringOption(
options, , default_value=cls._DEFAULT_HASH)
analysis_plugin.SetLookupHash(lookup_hash)
host... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance. |
13,177 | def to_string(value, ctx):
if isinstance(value, bool):
return "TRUE" if value else "FALSE"
elif isinstance(value, int):
return str(value)
elif isinstance(value, Decimal):
return format_decimal(value)
elif isinstance(value, str):
return value
elif type(value) == d... | Tries conversion of any value to a string |
13,178 | def start(self, historics_id):
return self.request.post(, data=dict(id=historics_id)) | Start the historics job with the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart
:param historics_id: hash of the job to start
:type historics_id: str
:return: dict of REST API output with headers attached
... |
13,179 | def authorize():
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
url = auth.get_authorization_url()
print(.format(url))
webbrowser.open(url)
pin = input().strip()
token_key, token_secret = auth.get_access_token(verifier=pin)
return OAuthToken(token_key, token_secret) | Authorize to twitter.
Use PIN authentification.
:returns: Token for authentificate with Twitter.
:rtype: :class:`autotweet.twitter.OAuthToken` |
13,180 | def install_extensions(extensions, **connection_parameters):
from postpy.connections import connect
conn = connect(**connection_parameters)
conn.autocommit = True
for extension in extensions:
install_extension(conn, extension) | Install Postgres extension if available.
Notes
-----
- superuser is generally required for installing extensions.
- Currently does not support specific schema. |
13,181 | def _compile(cls, lines):
m = cls.RE_FOR.match(lines.current)
if m is None:
raise DefineBlockError(
.format(lines.pos, lines.current))
return m.group(1), m.group(2).replace(, ) | Return both variable names used in the #for loop in the
current line. |
13,182 | def get_loader(vm_, **kwargs):
*
conn = __get_conn(**kwargs)
loader = _get_loader(_get_domain(conn, vm_))
conn.close()
return loader | Returns the information on the loader for a given vm
:param vm_: name of the domain
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defaults
CLI Example:
.. code... |
13,183 | def get_default_config(self):
config = super(MonitCollector, self).get_default_config()
config.update({
: ,
: 2812,
: ,
: ,
: ,
: [],
: False,
})
return ... | Returns the default collector settings |
13,184 | def _epd_residual(coeffs, mags, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd):
f = _epd_function(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, iha, izd)
residual = mags - f
return residual | This is the residual function to minimize using scipy.optimize.leastsq. |
13,185 | def add(self, post_id):
post_data = self.get_post_data()
post_data[] = self.userinfo.user_name
post_data[] = self.userinfo.uid
post_data[] = post_id
replyid = MReply.create_reply(post_data)
if replyid:
out_dic = {: post_data[],
... | Adding reply to a post. |
13,186 | def add_bias(self, name, b, input_name, output_name, shape_bias = [1]):
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_... | Add bias layer to the model.
Parameters
----------
name: str
The name of this layer.
b: int | numpy.array
Bias to add to the input.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of... |
13,187 | def receive_request(self, transaction):
if transaction.request.observe == 0:
host, port = transaction.request.source
key_token = hash(str(host) + str(port) + str(transaction.request.token))
non_counter = 0
if key_token in self._relations:
... | Manage the observe option in the request end eventually initialize the client for adding to
the list of observers or remove from the list.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:rtype : Transaction
:return: the modified transact... |
13,188 | def get_route_shape_segments(cur, route_id):
cur.execute(, (route_id,))
shape_points = [dict(seq=row[0], lat=row[1], lon=row[2]) for row in cur]
return shape_points | Given a route_id, return its stop-sequence.
Parameters
----------
cur: sqlite3.Cursor
cursor to a GTFS database
route_id: str
id of the route
Returns
-------
shape_points: list
elements are dictionaries containing the 'seq', 'lat', and 'lon' of the shape |
13,189 | def info(path):
output, err = cli_syncthing_adapter.info(folder=path)
if err:
click.echo(output, err=err)
else:
stat = output[]
click.echo("State: %s" % stat[])
click.echo("\nTotal Files: %s" % stat[])
click.echo("Files Needed: %s" % stat[])
click.echo("\nTotal Bytes: %s" % stat[])
... | Display synchronization information. |
13,190 | def parse_response(self, connection, command_name, **options):
response = connection.read_response()
if command_name in self.response_callbacks and len(response):
status = nativestr(response[0])
if status == RES_STATUS.OK:
return self.response_callbacks[c... | Parses a response from the ssdb server |
13,191 | def send_media_group(
self,
media: str,
disable_notification: bool = False,
reply_to_message_id: int = None,
**options
):
return self.bot.api_call(
"sendMediaGroup",
chat_id=str(self.id),
media=media,
disable_n... | Send a group of photos or videos as an album
:param media: A JSON-serialized array describing photos and videos
to be sent, must include 2–10 items
:param disable_notification: Sends the messages silently. Users will
receive a notification with no sound.
:param reply_to_message_... |
13,192 | def displayEmptyInputWarningBox(display=True, parent=None):
if sys.version_info[0] >= 3:
from tkinter.messagebox import showwarning
else:
from tkMessageBox import showwarning
if display:
msg = +\
showwarning(parent=parent,message=msg, title="No valid inputs!")
... | Displays a warning box for the 'input' parameter. |
13,193 | def _main(args):
if not args.apikey:
print("\nPlease provide TinyPNG API key")
print("To obtain key visit https://api.tinypng.com/developers\n")
sys.exit(1)
input_dir = realpath(args.input)
if not args.output:
output_dir = input_dir + "-output"
else:
outpu... | Batch compression.
args contains:
* input - path to input directory
* output - path to output directory or None
* apikey - TinyPNG API key
* overwrite - boolean flag |
13,194 | def setup_ui(self, ):
grid = QtGui.QGridLayout(self)
grid.setContentsMargins(0, 0, 0, 0)
self.setLayout(grid) | Create the layouts and set some attributes of the ui
:returns: None
:rtype: None
:raises: None |
13,195 | def construct_mail(self):
canonical_format = self.body.encode()
textpart = MIMEText(canonical_format, , )
if self.attachments:
inner_msg = MIMEMultipart()
inner_msg.attach(textpart)
for a in self.attachments:
... | compiles the information contained in this envelope into a
:class:`email.Message`. |
13,196 | def dict_merge(a, b, dict_boundary):
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.iteritems():
exploded_k = k.split(dict_boundary)
if len(exploded_k) > 1:
new_dict = None
for key in reversed(exploded_k):
... | Recursively merges dicts. not just simple a['key'] = b['key'], if
both a and b have a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
Also, if keys contain `self._dict_boundary`, they will be split into
sub dictionaries.
:param a... |
13,197 | def init_common(app):
if app.config[]:
security_ext = app.extensions[]
security_ext.confirm_register_form = confirm_register_form_factory(
security_ext.confirm_register_form)
security_ext.register_form = register_form_factory(
security_ext.register_form) | Post initialization. |
13,198 | def _attribute_iterator(self, mapped_class, key):
for attr in \
itervalues_(self.__get_attribute_map(mapped_class, key, 0)):
if self.is_pruning:
do_ignore = attr.should_ignore(key)
else:
do_ignore = False
if not do_ignore:
... | Returns an iterator over the attributes in this mapping for the
given mapped class and attribute key.
If this is a pruning mapping, attributes that are ignored because
of a custom configuration or because of the default ignore rules
are skipped. |
13,199 | def __prepare_dataset_parameter(self, dataset):
if not isinstance(dataset, _SFrame):
def raise_dataset_type_exception():
raise TypeError("The dataset parameter must be either an SFrame, "
"or a dictionary of (str : list) or (str : va... | Processes the dataset parameter for type correctness.
Returns it as an SFrame. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.