Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
346,100 | def transaction_start(self, name):
if not name:
raise ValueError("Transaction name cannot be empty")
self.transaction_count += 1
logger.debug("{}. Start transaction {}".format(self.transaction_count, name))
if self.transaction_count == 1:
se... | start a transaction
this will increment transaction semaphore and pass it to _transaction_start() |
346,101 | def flash(self, binary_location=None, forceflash=None):
if not Flash:
self.logger.error("Mbed-flasher not installed!")
raise ImportError("Mbed-flasher not installed!")
try:
self.build = Build.init(binary_location)
except NotImplementedEr... | Flash a binary to the target device using mbed-flasher.
:param binary_location: Binary to flash to device.
:param forceflash: Not used.
:return: False if an unknown error was encountered during flashing.
True if flasher retcode == 0
:raises: ImportError if mbed-flasher not insta... |
346,102 | def _create_retry_request(self):
req_manager = _ReadRowsRequestManager(
self.request, self.last_scanned_row_key, self._counter
)
return req_manager.build_updated_request() | Helper for :meth:`__iter__`. |
346,103 | def get_section_by_name(self, section_name):
sections = self.unravel_sections(self.get_sections())
for section in sections:
if section[] == section_name:
return section[], section
return None, None | Get a section by its name.
Get a list of sections for a given gradebook,
specified by a gradebookid.
Args:
section_name (str): The section's name.
Raises:
requests.RequestException: Exception connection error
ValueError: Unable to decode response co... |
346,104 | def render_impl(self, template, context, **options):
ropts = dict((k, v) for k, v in options.items() if k != "safe")
tmpl = anytemplate.engines.base.fallback_render(template, {}, **ropts)
return self.renders_impl(tmpl, context, **options) | Inherited class must implement this!
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param options: Same options as :meth:`renders_impl`
- at_paths: Template search paths (common option)
- at... |
346,105 | def heat_wave_max_length(tasmin, tasmax, thresh_tasmin=, thresh_tasmax=,
window=3, freq=):
r
thresh_tasmax = utils.convert_units_to(thresh_tasmax, tasmax)
thresh_tasmin = utils.convert_units_to(thresh_tasmin, tasmin)
cond = (tasmin > thresh_tasmin) & (tasmax > thresh_tasma... | r"""Heat wave max length
Maximum length of heat waves over a given period. A heat wave is defined as an event
where the minimum and maximum daily temperature both exceeds specific thresholds
over a minimum number of days.
By definition heat_wave_max_length must be >= window.
Parameters
------... |
346,106 | def to_match(self):
self.validate()
def visitor_fn(expression):
if isinstance(expression, TernaryConditional):
raise ValueError(u
u
u.format(expression... | Return a unicode object with the MATCH representation of this TernaryConditional. |
346,107 | def _GetDirectory(self):
if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY:
return None
return OSDirectory(self._file_system, self.path_spec) | Retrieves a directory.
Returns:
OSDirectory: a directory object or None if not available. |
346,108 | def yield_typed(obj_or_cls):
if not isinstance(obj_or_cls, type):
obj_or_cls = type(obj_or_cls)
for attrname in dir(obj_or_cls):
if hasattr(obj_or_cls, attrname):
attr = getattr(obj_or_cls, attrname)
if (isinstance(attr, property) and isinstance(attr.__d... | Generator that yields typed object names of the class (or object's class).
Args:
obj_or_cls (object): Class object or instance of class
Returns:
name (array): Names of class attributes that are strongly typed |
346,109 | def add_cluster_interface_on_master_engine(self, interface_id, macaddress,
nodes, zone_ref=None, vlan_id=None, comment=None):
_interface = {: interface_id, : macaddress,
: [{: nodes if nodes else [], : vlan_id}],
: zone_ref, : comment}
try:
... | Add a cluster address specific to a master engine. Master engine
clusters will not use "CVI" interfaces like normal layer 3 FW clusters,
instead each node has a unique address and share a common macaddress.
Adding multiple addresses to an interface is not supported with this
method.
... |
346,110 | def cleanup(logger, *args):
for obj in args:
if obj is not None and hasattr(obj, ):
try:
obj.cleanup()
except NotImplementedError:
pass
except Exception:
logger.exception("Unable to cleanup %s object", obj) | Environment's cleanup routine. |
346,111 | def init_model(engine):
if meta.Session is None:
sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm) | Call me before using any of the tables or classes in the model |
346,112 | def token(self):
tok = None
if self.next_token is not None:
tok = lex.LexToken()
tok.value =
tok.lineno = self.lex.lineno
tok.lexpos = self.lex.lexpos
tok.type = self.next_token
self.next_token = None
while self.l... | Returns a token from the current input. If tok is None
from the current input, it means we are at end of current input
(e.g. at end of include file). If so, closes the current input
and discards it; then pops the previous input and lexer from
the input stack, and gets another token.
... |
346,113 | def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
... | Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
346,114 | def print_signals_and_slots(self):
for i in xrange(self.metaObject().methodCount()):
m = self.metaObject().method(i)
if m.methodType() == QMetaMethod.MethodType.Signal:
print("SIGNAL: sig=", m.signature(), "hooked to nslots=", self.receivers(SIGNAL(m.signature... | List all active Slots and Signal.
Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging |
346,115 | def set_fallback_resolution(self, x_pixels_per_inch, y_pixels_per_inch):
cairo.cairo_surface_set_fallback_resolution(
self._pointer, x_pixels_per_inch, y_pixels_per_inch)
self._check_status() | Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend,
cairo will fallback by rendering operations to an image
and then overlaying that image onto the output.
For backends that are natively vector-oriented,
... |
346,116 | def dimension_values(self, dimension, expanded=True, flat=True):
values = []
found = False
for el in self:
if dimension in el.dimensions(label=True):
values.append(el.dimension_values(dimension))
found = True
if not found:
... | Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
on the type of data:
* Colum... |
346,117 | def bitfield_update(w, range_start, range_end, newvalue, truncating=False):
from .corecircuits import concat_list
w = as_wires(w)
idxs = list(range(len(w)))
idxs_lower = idxs[0:range_start]
idxs_middle = idxs[range_start:range_end]
idxs_upper = idxs[range_end:]
if len(idxs_middle) =... | Return wirevector w but with some of the bits overwritten by newvalue.
:param w: a wirevector to use as the starting point for the update
:param range_start: the start of the range of bits to be updated
:param range_end: the end of the range of bits to be updated
:param newvalue: the value to be writte... |
346,118 | def sqs_put_item(queue_url,
item,
delay_seconds=0,
client=None,
raiseonfail=False):
if not client:
client = boto3.client()
try:
json_msg = json.dumps(item)
resp = client.send_message(
QueueUrl=queue_... | This pushes a dict serialized to JSON to the specified SQS queue.
Parameters
----------
queue_url : str
The SQS URL of the queue to push the object to.
item : dict
The dict passed in here will be serialized to JSON.
delay_seconds : int
The amount of time in seconds the pu... |
346,119 | def get_declared_envs(ini):
tox_section_name = if ini.path.endswith() else
tox_section = ini.sections.get(tox_section_name, {})
envlist = split_env(tox_section.get(, []))
section_envs = [
section[8:] for section in sorted(ini.sections, key=ini.lineof)
if section.startswith()... | Get the full list of envs from the tox ini.
This notably also includes envs that aren't in the envlist,
but are declared by having their own testenv:envname section.
The envs are expected in a particular order. First the ones
declared in the envlist, then the other testenvs in order. |
346,120 | def _parse_menu_entry(line_iter, cur_line, conf):
menu = []
conf[].append(menu)
n, entry = _parse_line("menuentry", cur_line)
entry_name, v = _parse_line("{", entry)
if not entry_name:
raise Exception("Cannot parse menuentry line: {0}".format(cur_line))
menu.append((, entry_name))... | Parse each `menuentry` that the grub v2 configuration contains
* Uses "_parse_script" to eliminate bash scripts |
346,121 | def run_gui():
try:
from gi.repository import Gtk
except ImportError as ie:
pass
except RuntimeError as e:
sys.stderr.write(GUI_MESSAGE)
sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e)))
sys.stderr.flush()
sys.exit(1)
... | Function for running DevAssistant GUI |
346,122 | def validate(self, value, model=None, context=None):
from boiler.user.services import role_service
self_id = None
if model:
if isinstance(model, dict):
self_id = model.get()
else:
self_id = getattr(model, )
found = role_s... | Perform validation |
346,123 | def parse_station_table(root):
stations = [parse_xml_station(elem) for elem in root.findall()]
return {st.id: st for st in stations} | Parse station list XML file. |
346,124 | def _FlowObjectFromRow(self, row):
flow, fs, cci, pt, nr, pd, po, ps, uct, sct, nbs, nrs, ts, lut = row
flow_obj = rdf_flow_objects.Flow.FromSerializedString(flow)
if fs not in [None, rdf_flow_objects.Flow.FlowState.UNSET]:
flow_obj.flow_state = fs
if cci is not None:
cc_cls = rdf_cli... | Generates a flow object from a database row. |
346,125 | def user_timeline(request):
user = request.user.twitterprofile
twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
user.oauth_token, user.oauth_secret)
user_tweets = twitter.get_home_timeline()
return render_to_response(, {: user_tweets}) | An example view with Twython/OAuth hooks/calls to fetch data about the user in question. |
346,126 | def get_labels(node=None, apiserver_url=None):
**
node = _guess_node_id(node)
apiserver_url = _guess_apiserver(apiserver_url)
if apiserver_url is None:
return False
ret = _get_labels(node, apiserver_url)
return {"labels": ret} | .. versionadded:: 2016.3.0
Get labels from the current node
CLI Example:
.. code-block:: bash
salt '*' k8s.get_labels
salt '*' k8s.get_labels kube-node.cluster.local http://kube-master.cluster.local |
346,127 | def _compute_first(self):
for terminal in self.terminals:
self._first[terminal].add(terminal)
self._first[END_OF_INPUT].add(END_OF_INPUT)
while True:
changed = False
for nonterminal, productions in self.nonterminals.items():
for prod... | Computes the FIRST set for every symbol in the grammar.
Tenatively based on _compute_first in PLY. |
346,128 | def validate(self):
properties = (
getattr(self.__class__, prop)
for prop in self._property_list
if hasattr(self.__class__, prop)
)
all_valid = True
for prop in properties:
if hasattr(prop, "validate"):
... | Validate all inputs. Highlight invalid inputs. |
346,129 | def from_file(cls, filename, name=):
"Imports a mass table from a file"
df = pd.read_csv(filename, header=0, delim_whitespace=True, index_col=[0, 1])[]
df.name = name
return cls(df=df, name=name) | Imports a mass table from a file |
346,130 | def drvr_initialize(self, cfg):
cnt = 0
for ip in self.obj_dict:
cfg_dict = {}
drvr_obj = self.obj_dict.get(ip).get()
cfg_dict[] = ip
if self.user_list is not None:
cfg_dict[] = self.user_list[cnt]
if self.pwd_list is n... | Initialize the driver routines. |
346,131 | def tf_step(self, time, variables, **kwargs):
deltas = self.optimizer.step(time=time, variables=variables, **kwargs)
with tf.control_dependencies(control_inputs=deltas):
clipped_deltas = list()
exceeding_deltas = list()
for delta in deltas:
c... | Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional arguments passed on to the internal optimizer.
Returns:
List of delta tensors corresponding to ... |
346,132 | def delete_object(
request, model, post_delete_redirect, object_id=None,
slug=None, slug_field=, template_name=None,
template_loader=loader, extra_context=None, login_required=False,
context_processors=None, template_object_name=):
if extra_context is None:
extra_context... | Generic object-delete function.
The given template will be used to confirm deletetion if this view is
fetched using GET; for safty, deletion will only be performed if this
view is POSTed.
Templates: ``<app_label>/<model_name>_confirm_delete.html``
Context:
object
the original o... |
346,133 | def command(self, *args, **kwargs):
def decorator(f):
cmd = command(*args, **kwargs)(f)
self.add_command(cmd)
return cmd
return decorator | A shortcut decorator for declaring and attaching a command to
the group. This takes the same arguments as :func:`command` but
immediately registers the created command with this instance by
calling into :meth:`add_command`. |
346,134 | def _is_request_in_include_path(self, request):
if self._include_paths:
for path in self._include_paths:
if request.path.startswith(path):
return True
return False
else:
return True | Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths. |
346,135 | def RV_com1(self):
return self.RV * (self.M2 / (self.M1 + self.M2)) | RVs of star 1 relative to center-of-mass |
346,136 | def pretty_print_config_to_json(self, services, hostname=None):
descriptor = self.get_config_dict(services, hostname)
return json.dumps(descriptor, sort_keys=True, indent=2,
separators=(, )) | JSON string description of a protorpc.remote.Service in API format.
Args:
services: Either a single protorpc.remote.Service or a list of them
that implements an api/version.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
R... |
346,137 | def _bam_coverage(name, bam_input, data):
cmd = ("{bam_coverage} -b {bam_input} -o {bw_output} "
"--binSize 20 --effectiveGenomeSize {size} "
"--smoothLength 60 --extendReads 150 --centerReads -p {cores}")
size = bam.fasta.total_sequence_length(dd.get_ref_file(data))
cores = dd.get_... | Run bamCoverage from deeptools |
346,138 | def enforce_epsilon_and_compute_hash(dataset_batch_dir, adv_dir, output_dir,
epsilon):
dataset_images = [f for f in os.listdir(dataset_batch_dir)
if f.endswith()]
image_hashes = {}
resize_warning = False
for img_name in dataset_images:
if not os.pa... | Enforces size of perturbation on images, and compute hashes for all images.
Args:
dataset_batch_dir: directory with the images of specific dataset batch
adv_dir: directory with generated adversarial images
output_dir: directory where to copy result
epsilon: size of perturbation
Returns:
dictio... |
346,139 | def book_room(self, item, start, end, fname, lname, email, nickname, custom={}, test=False):
data = {
"start": start,
"fname": fname,
"lname": lname,
"email": email,
"nickname": nickname,
"bookings": [
{
... | Books a room given the required information.
:param item:
The ID of the room to book.
:type item: int
:param start:
The start time range of when to book the room, in the format returned by the LibCal API.
:type start: str
:param end:
The end t... |
346,140 | async def write(self, towrite: bytes, await_blocking=False):
await self._write(towrite)
if await_blocking:
return await self.flush() | Appends towrite to the write queue
>>> await test.write(b"HELLO")
# Returns without wait time
>>> await test.write(b"HELLO", await_blocking = True)
# Returns when the bufer is flushed
:param towrite: Write buffer
:param await_blocking: wait for everything to be wr... |
346,141 | def Get_RpRs(d, **kwargs):
if ps is None:
raise Exception("Unable to import `pysyzygy`.")
def Depth(RpRs, **kwargs):
return 1 - ps.Transit(RpRs=RpRs, **kwargs)([kwargs.get(, 0.)])
def DiffSq(r):
return 1.e10 * (d - Depth(r, **kwargs)) ** 2
return fmin(DiffSq, [np.sqrt... | Returns the value of the planet radius over the stellar radius
for a given depth :py:obj:`d`, given
the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`. |
346,142 | def get_attachment_formset(self, formset_class):
if (
self.request.forum_permission_handler.can_attach_files(
self.get_forum(), self.request.user,
)
):
return formset_class(**self.get_attachment_formset_kwargs()) | Returns an instance of the attachment formset to be used in the view. |
346,143 | def template_to_base_path(template, google_songs):
if template == os.getcwd() or template == :
base_path = os.getcwd()
else:
template = os.path.abspath(template)
song_paths = [template_to_filepath(template, song) for song in google_songs]
base_path = os.path.dirname(os.path.commonprefix(song_paths))
retu... | Get base output path for a list of songs for download. |
346,144 | def wiki_download(url):
DOWNLOAD_TMPL =
freq_range = url[url.rindex()+1:]
tmp_path = DOWNLOAD_TMPL % freq_range
if os.path.exists(tmp_path):
print(, url)
with codecs.open(tmp_path, , ) as f:
return f.read(), True
with codecs.open(tmp_path, , ) as f:
print(,... | scrape friendly: sleep 20 seconds between each request, cache each result. |
346,145 | def delif(self, iface):
if type(iface) == ifconfig.Interface:
devindex = iface.index
else:
devindex = ifconfig.Interface(iface).index
ifreq = struct.pack(, self.name, devindex)
fcntl.ioctl(ifconfig.sockfd, SIOCBRDELIF, ifreq)
return self | Remove the interface with the given name from this bridge.
Equivalent to brctl delif [bridge] [interface] |
346,146 | def significance_fdr(p, alpha):
i = np.argsort(p, axis=None)
m = i.size - np.sum(np.isnan(p))
j = np.empty(p.shape, int)
j.flat[i] = np.arange(1, i.size + 1)
mask = p <= alpha * j / m
if np.sum(mask) == 0:
return mask
k = np.max(j[mask])
s = j <= k
return... | Calculate significance by controlling for the false discovery rate.
This function determines which of the p-values in `p` can be considered
significant. Correction for multiple comparisons is performed by
controlling the false discovery rate (FDR). The FDR is the maximum fraction
of p-values that are w... |
346,147 | def monte_carlo_csiszar_f_divergence(
f,
p_log_prob,
q,
num_draws,
use_reparametrization=None,
seed=None,
name=None):
reparameterization_types = tf.nest.flatten(q.reparameterization_type)
with tf.compat.v1.name_scope(name, "monte_carlo_csiszar_f_divergence",
... | Monte-Carlo approximation of the Csiszar f-Divergence.
A Csiszar-function is a member of,
```none
F = { f:R_+ to R : f convex }.
```
The Csiszar f-Divergence for Csiszar-function f is given by:
```none
D_f[p(X), q(X)] := E_{q(X)}[ f( p(X) / q(X) ) ]
~= m**-1 sum_j^m f( p(x_j) / q(x_j... |
346,148 | def format_failure(failure):
return "Line {}, Column {} -
failure.getLine(),
failure.getColumn(),
failure.getErrorId(),
failure.getMessage(),
failure.getCategoryAsString(),
failure.getSeverity()
) | Format how an error or warning should be displayed. |
346,149 | def pitch_contour(times, frequencies, fs, amplitudes=None, function=np.sin,
length=None, kind=):
fs = float(fs)
if length is None:
length = int(times.max() * fs)
frequencies = np.maximum(frequencies, 0.0)
f_interp = interp1d(times * fs, 2 * np.pi * frequ... | Sonify a pitch contour.
Parameters
----------
times : np.ndarray
time indices for each frequency measurement, in seconds
frequencies : np.ndarray
frequency measurements, in Hz.
Non-positive measurements will be interpreted as un-voiced samples.
fs : int
desired sam... |
346,150 | def collapse_equivalencies_by_namespace(graph: BELGraph, victim_namespace: Strings, survivor_namespace: str) -> None:
_collapse_edge_by_namespace(graph, victim_namespace, survivor_namespace, EQUIVALENT_TO) | Collapse pairs of nodes with the given namespaces that have equivalence relationships.
:param graph: A BEL graph
:param victim_namespace: The namespace(s) of the node to collapse
:param survivor_namespace: The namespace of the node to keep
To convert all ChEBI names to InChI keys, assuming there a... |
346,151 | def vmstat(stat):
out = subprocess.check_output(["vmstat", "-s"])
stat = stat.encode("ascii")
for line in out.split(b"\n"):
line = line.strip()
if stat in line:
return int(line.split(b" ")[0])
raise ValueError("Canvmstat' output.".format(stat)) | Run vmstat and get a particular statistic.
Args:
stat: The statistic that we are interested in retrieving.
Returns:
The parsed output. |
346,152 | def connect(cls, resource):
import boto
return boto.s3.connect_to_region(cls.get_region(resource)) | Connect to this Region's endpoint.
Returns a connection object pointing to the endpoint associated
to the received resource. |
346,153 | def get_api_envs():
client_id = os.environ.get()
user_id = os.environ.get()
if not client_id or not user_id:
raise ValueError()
return client_id, user_id | Get required API keys from environment variables. |
346,154 | def get_activities_by_ids(self, activity_ids=None):
if activity_ids is None:
raise NullArgument()
activities = []
for i in activity_ids:
activity = None
url_path = construct_url(,
bank_id=self._catalog_idstr,
... | Gets an ActivityList corresponding to the given IdList.
In plenary mode, the returned list contains all of the
activities 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 inaccessible. Otherwise,
... |
346,155 | def _adj_for_assc(self):
if self.gene2gos:
gos_assoc = set(get_b2aset(self.gene2gos).keys())
if not in self.kws:
self.kws[] = {go: for go in gos_assoc}
if not in self.kws:
gosubdag = GoSubDag(gos_assoc, self.gosubdag.go2obj,
... | Print only GO IDs from associations and their ancestors. |
346,156 | def _GetHeader(self):
header = []
for value in self.values:
try:
header.append(value.Header())
except SkipValue:
continue
return header | Returns header. |
346,157 | def _collect_grades_data(self, enterprise_enrollment, course_details):
if self.grades_api is None:
self.grades_api = GradesApiClient(self.user)
course_id = enterprise_enrollment.course_id
username = enterprise_enrollment.enterprise_customer_user.user.username
try:
... | Collect the learner completion data from the Grades API.
Used for self-paced courses.
Args:
enterprise_enrollment (EnterpriseCourseEnrollment): the enterprise enrollment record for which we need to
collect completion/grade data
course_details (dict): the course deta... |
346,158 | def _draw_contour(self, img):
if self.mask is None or self.contour_width == 0:
return img
mask = self._get_bolean_mask(self.mask) * 255
contour = Image.fromarray(mask.astype(np.uint8))
contour = contour.resize(img.size)
contour = contour.filter(ImageFilter.F... | Draw mask contour on a pillow image. |
346,159 | def _get_earliest_valid_timestamp(self, symbol, interval):
kline = self.get_klines(
symbol=symbol,
interval=interval,
limit=1,
startTime=0,
endTime=None
)
return kline[0][0] | Get earliest valid open timestamp from Binance
:param symbol: Name of symbol pair e.g BNBBTC
:type symbol: str
:param interval: Binance Kline interval
:type interval: str
:return: first valid timestamp |
346,160 | def get_field_template(self, bound_field, template_name=None):
if template_name:
return template_name
templates = self.field_template_overrides or {}
template_name = templates.get(bound_field.name, None)
if template_name:
return template_name
t... | Returns the field template to use when rendering a form field to HTML.
Preference of template selection:
1. Provided method argument `template_name`
2. Template from `field_template_overrides` selected by field name
3. Template from `field_template_overrides` selected by field class
... |
346,161 | def map(self, mols, nproc=None, nmols=None, quiet=False, ipynb=False, id=-1):
r
if nproc is None:
nproc = cpu_count()
if hasattr(mols, "__len__"):
nmols = len(mols)
if nproc == 1:
return self._serial(mols, nmols=nmols, quiet=quiet, ipynb=ipynb, id=id... | r"""Calculate descriptors over mols.
Parameters:
mols(Iterable[rdkit.Mol]): moleculars
nproc(int): number of process to use. default: multiprocessing.cpu_count()
nmols(int): number of all mols to use in progress-bar. default: mols.__len__()
quiet(bool): don't ... |
346,162 | def to_internal_value(self, data):
ret = super(DynamicDocumentSerializer, self).to_internal_value(data)
dynamic_data = self._get_dynamic_data(ret)
ret.update(dynamic_data)
return ret | Updates _validated_data with dynamic data, i.e. data,
not listed in fields. |
346,163 | def set_random_state(state):
randgen.state_set = True
randgen.setstate(state)
faker.generator.random.setstate(state) | Force-set the state of factory.fuzzy's random generator. |
346,164 | def printfile(aFileName):
print("\nMission file: %s" % aFileName)
with open(aFileName) as f:
for line in f:
print( % line.strip()) | Print a mission file to demonstrate "round trip" |
346,165 | def convert_PDF_to_plaintext(fpath, keep_layout=False):
if not os.path.isfile(CFG_PATH_PDFTOTEXT):
raise IOError()
if keep_layout:
layout_option = "-layout"
else:
layout_option = "-raw"
doclines = []
p_break_in_line = re.compile(ur, re.UNICODE)
... | Convert PDF to txt using pdftotext
Take the path to a PDF file and run pdftotext for this file, capturing
the output.
@param fpath: (string) path to the PDF file
@return: (list) of unicode strings (contents of the PDF file translated
into plaintext; each string is a line in the document.) |
346,166 | def _take_lease(self, lease, uuid_path, safe=True):
if safe:
lease_taken_by = self._lease_valid(lease)
if lease_taken_by and lease_taken_by != uuid_path:
raise LagoSubnetLeaseTakenException(
lease.subnet, lease_taken_by
)
... | Persist the given lease to the store and make the prefix in uuid_path
his owner
Args:
lease(lago.subnet_lease.Lease): Object representation of the lease
uuid_path (str): Path to the prefix uuid
safe (bool): If true (the default), validate the the lease
... |
346,167 | def comment_user(self, user_id, amount=None):
if not self.check_user(user_id, filter_closed_acc=True):
return False
self.logger.info("Going to comment user_%s's feed:" % user_id)
user_id = self.convert_to_user_id(user_id)
medias = self.get_user_medias(user_id, is_comment=True)
if not me... | Comments last user_id's medias |
346,168 | def parse(type: Type):
def decorator(parser):
EnvVar.parsers[type] = parser
return parser
return decorator | Register a parser for a attribute type.
Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.
Args:
type: the type the decorated function will be responsible
for parsing a environment variable to. |
346,169 | def get_filter_kwargs(self):
if self.is_valid():
filter_kwargs = {}
for field in self.get_filter_fields():
empty_values = EMPTY_VALUES
if hasattr(self.fields[field], ):
empty_values = self.fields[field].empty_values
... | Translates the cleaned data into a dictionary
that can used to generate the filter removing
blank values. |
346,170 | def get_item_string(items_list):
if not items_list:
return
string_list = []
for item in items_list:
try:
name = item.name
string_list.append(name)
except AttributeError:
pass
return ":".join(string_list) | take in a list of pmag_objects
return a colon-delimited list of the findable names |
346,171 | def draw_hist(self, metric, title=""):
rows = 1
cols = 1
limit = 10
ax = self.figure.add_subplot(self.gs, projection="3d")
ax.view_init(30, -80)
verts = []
area_colors = []
edge_colors = []
for i, s... | Draw a series of histograms of the selected keys over different
training steps. |
346,172 | def add(self, key, val, time = 0, min_compress_len = 0):
t already exist.
@return: Nonzero on success.
@rtype: int
'
return self._set("add", key, val, time, min_compress_len) | Add new key with value.
Like L{set}, but only stores in memcache if the key doesn't already exist.
@return: Nonzero on success.
@rtype: int |
346,173 | def plot_seebeck_temp(self, doping=, output=):
import matplotlib.pyplot as plt
if output == :
sbk = self._bz.get_seebeck(output=)
elif output == :
sbk = self._bz.get_seebeck(output=)
plt.figure(figsize=(22, 14))
tlist = sorted(sbk[].keys())
... | Plot the Seebeck coefficient in function of temperature for different
doping levels.
Args:
dopings: the default 'all' plots all the doping levels in the analyzer.
Specify a list of doping levels if you want to plot only some.
output: with 'average' you get ... |
346,174 | def min_length_discard(records, min_length):
logging.info(
, min_length)
for record in records:
if len(record) < min_length:
logging.debug(,
record.id, len(record))
else:
yield record | Discard any records that are shorter than min_length. |
346,175 | def dragMoveEvent( self, event ):
filt = self.dragDropFilter()
if ( filt and filt(self, event) ):
return
super(XTableWidget, self).dragMoveEvent(event) | Processes the drag drop event using the filter set by the \
setDragDropFilter
:param event | <QDragEvent> |
346,176 | def versus_summaries(turns=2, sims_to_average=2, async_results_q=None):
board, player, opponent, extra_actions = _state_investigator.get_versus()
if extra_actions: extra_actions = 1
if board is None:
return tuple()
averaged_summaries = list()
advisors = list()
for i in rang... | Return summaries of the likely resutls of each available action..
Arguments:
- turns: how many turns to simulate.
- in 2013, 1 is fast (seconds), 2 is slow (seconds), 3 who knows
- sims_to_average: how many times to run the simulation
to get more representative average results of each actio... |
346,177 | def create_element_tree(elem_or_name=None, text=None, **attribute_kwargs):
if elem_or_name is None:
return ElementTree()
is_elem = isinstance(elem_or_name, ElementType)
element = elem_or_name if is_elem else Element(elem_or_name)
if text is not None:
element.text = text
elem... | Creates an ElementTree from elem_or_name, updated it with text and attributes.
If elem_or_name is None, a permanently empty ElementTree is returned.
:param elem_or_name: an Element or the name of the root element tag
:param text: optional text with which to update the root element
:param attribute_kwarg... |
346,178 | def _scoring(self, net, X_test, y_test):
scorer = check_scoring(net, self.scoring_)
scores = _score(
estimator=net,
X_test=X_test,
y_test=y_test,
scorer=scorer,
is_multimetric=False,
)
return scores | Resolve scoring and apply it to data. Use cached prediction
instead of running inference again, if available. |
346,179 | def get_message_from_call(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], dict):
self.logger.debug()
result = kwargs
else:
self.logger.error(
,
args, kwargs
)
... | \
Get message object from a call.
:raises: :py:exc:`TypeError` (if the format is not what we expect)
This is where arguments to nodes are turned into Messages. Arguments
are parsed in the following order:
- A single positional argument (a :py:class:`dict`)
- No posit... |
346,180 | def getDigitalActionData(self, action, unActionDataSize, ulRestrictToDevice):
fn = self.function_table.getDigitalActionData
pActionData = InputDigitalActionData_t()
result = fn(action, byref(pActionData), unActionDataSize, ulRestrictToDevice)
return result, pActionData | Reads the state of a digital action given its handle. This will return VRInputError_WrongType if the type of
action is something other than digital |
346,181 | def cited_names_from_aux_file(stream):
cited = set()
for line in stream:
if not line.startswith(r):
continue
line = line.rstrip()
if line[-1] != :
continue
entries = line[10:-1]
for name in entries.split():
name = name.strip()... | Parse a LaTeX ".aux" file and generate a list of names cited according to
LaTeX ``\\citation`` commands. Repeated names are generated only once. The
argument should be a opened I/O stream. |
346,182 | def match(self, request):
for test in self.filters:
if not test(request, self):
return False
for mapper in self.mappers:
request = mapper(request, self)
if not request:
raise ValueError()
ma... | Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
Arguments:
request (pook.Request): Request contract to match.
Raises:
pook.PookNoMatches: if networking is disabled and no mock mat... |
346,183 | def append_position_to_token_list(token_list):
return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)] | Converts a list of Token into a list of Token, asuming size == 1 |
346,184 | def SLH_to_qutip(slh, full_space=None, time_symbol=None,
convert_as=):
if full_space:
if not full_space >= slh.space:
raise AlgebraError("full_space="+str(full_space)+" needs to "
"at least include slh.space = "+str(slh.space))
else:
... | Generate and return QuTiP representation matrices for the Hamiltonian
and the collapse operators. Any inhomogeneities in the Lindblad operators
(resulting from coherent drives) will be moved into the Hamiltonian, cf.
:func:`~qnet.algebra.circuit_algebra.move_drive_to_H`.
Args:
slh (SLH): The SL... |
346,185 | def get_resource_attribute(collection, key, attribute):
resource = retrieve_resource(collection, key)
_validate(endpoint_class(collection), request.method, resource)
value = getattr(resource, attribute)
if isinstance(value, Model):
return resource_response(value)
else:
return at... | Return the appropriate *Response* for retrieving an attribute of
a single resource.
:param string collection: a :class:`sandman.model.Model` endpoint
:param string key: the primary key for the :class:`sandman.model.Model`
:rtype: :class:`flask.Response` |
346,186 | def metadata(self, **kwargs):
r
self._check_geo_param(kwargs)
kwargs[] = self.token
return self._get_response(, kwargs) | r""" Returns the metadata for a station or stations. Users must specify at least one geographic search parameter
('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to obtain
observation data. Other parameters may also be included. See below for optional ... |
346,187 | def requests_for_variant(self, request, variant_id=None):
requests = ProductRequest.objects.filter(variant__id=variant_id)
serializer = self.serializer_class(requests, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK) | Get all the requests for a single variant |
346,188 | def check_version(dstore):
ds_version = dstore.hdf5.attrs[]
if ds_version != __version__:
return (
% (ds_version, __version__))
else:
return | :param dstore: a DataStore instance
:returns:
a message if the stored version is different from the current version |
346,189 | def bool_env(key, default=False):
try:
return os.environ[key].lower() in TRUE
except KeyError:
return default | Parse an environment variable as a boolean switch
`True` is returned if the variable value matches one of the following:
- ``'1'``
- ``'y'``
- ``'yes'``
- ``'true'``
The match is case-insensitive (so ``'Yes'`` will match as `True`)
Parameters
----------
key : `str`
the na... |
346,190 | def check(text):
err = "consistency.spacing"
msg = "Inconsistent spacing after period (1 vs. 2 spaces)."
regex = ["[\.\?!] [A-Z]", "[\.\?!] [A-Z]"]
return consistency_check(text, [regex], err, msg) | Check the text. |
346,191 | def store_value(self, name, value):
self.spine.send_command("storeSetting", self.group, name, value) | Store a value to DB |
346,192 | def get_statistics(self):
return {
: self.get_cumulative_elapsed_time(),
: self.get_percentage(),
: self.get_n_splits(),
: self.get_mean_per_split(),
} | Get all statistics as a dictionary.
Returns
-------
statistics : Dict[str, List] |
346,193 | def calculate_bin_centers(edges):
edges = np.asanyarray(edges, dtype=np.float)
if edges.ndim != 1:
raise ValueError()
if edges.size < 2:
raise ValueError()
centers = np.empty(edges.size - 1, dtype=np.float)
centers[0] = edges[:2].mean()
for i in range(1, centers.size):
... | Calculate the centers of wavelengths bins given their edges.
Parameters
----------
edges : array_like
Sequence of bin edges. Must be 1D and have at least two values.
Returns
-------
centers : ndarray
Array of bin centers. Will be 1D and have one less value than ``edges``. |
346,194 | def cast(source, target):
import ibis.expr.operations as ops
out_type = target.type().scalar_type()
return out_type(op) | Currently Literal to *Scalar implicit casts are allowed |
346,195 | def connect_bitcoind_impl( bitcoind_opts ):
if not in bitcoind_opts.keys() or bitcoind_opts[] is None:
log.error("No port given")
raise ValueError("No RPC port given (bitcoind_port)")
if not in bitcoind_opts.keys() or bitcoind_opts[] is None:
bitcoind_opts[] = 300
... | Create a connection to bitcoind, using a dict of config options. |
346,196 | def gen_keys(keydir, keyname, keysize, user=None, passphrase=None):
masterminion
base = os.path.join(keydir, keyname)
priv = .format(base)
pub = .format(base)
if HAS_M2:
gen = RSA.gen_key(keysize, 65537, lambda: None)
else:
salt.utils.crypt.reinit_crypto()
gen = RSA.gene... | Generate a RSA public keypair for use with salt
:param str keydir: The directory to write the keypair to
:param str keyname: The type of salt server for whom this key should be written. (i.e. 'master' or 'minion')
:param int keysize: The number of bits in the key
:param str user: The user on the system... |
346,197 | def anomaly(self, test_data, per_feature=False):
return {model.model_id: model.anomaly(test_data, per_feature) for model in self.models} | Obtain the reconstruction error for the input test_data.
:param H2OFrame test_data: The dataset upon which the reconstruction error is computed.
:param bool per_feature: Whether to return the square reconstruction error per feature. Otherwise, return
the mean square error.
:returns:... |
346,198 | def _to_json(self, resp):
try:
json = resp.json()
except ValueError as e:
reason = "TMC Server did not send valid JSON: {0}"
raise APIError(reason.format(repr(e)))
return json | Extract json from a response.
Assumes response is valid otherwise.
Internal use only. |
346,199 | def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1,
log=False):
alphabeta
opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size,
numItermax, lr)
pi = (np.exp((opt_alpha[:, None] + opt_be... | Compute the transportation matrix to solve the regularized discrete measures
optimal transport dual problem
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.