Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
355,400 | def from_start_and_end(cls, start, end, sequence, helix_type=,
phos_3_prime=False):
start = numpy.array(start)
end = numpy.array(end)
instance = cls(sequence, helix_type=helix_type,
phos_3_prime=phos_3_prime)
instance.move_to(sta... | Generates a helical `Polynucleotide` that is built along an axis.
Parameters
----------
start: [float, float, float]
Start of the build axis.
end: [float, float, float]
End of build axis.
sequence: str
The nucleotide sequence of the nucleic ac... |
355,401 | def listen(self):
while self._listen:
key = u
key = self.term.inkey(timeout=0.2)
try:
if key.code == KEY_ENTER:
self.on_enter(key=key)
elif key.code in (KEY_DOWN, KEY_UP):
self.on_key_arrow(key=k... | Blocking call on widgets. |
355,402 | def get_keyboard_mapping(conn):
mn, mx = get_min_max_keycode(conn)
return conn.core.GetKeyboardMapping(mn, mx - mn + 1) | Return a keyboard mapping cookie that can be used to fetch the table of
keysyms in the current X environment.
:rtype: xcb.xproto.GetKeyboardMappingCookie |
355,403 | def takes_kwargs(obj) -> bool:
if inspect.isclass(obj):
signature = inspect.signature(obj.__init__)
elif inspect.ismethod(obj) or inspect.isfunction(obj):
signature = inspect.signature(obj)
else:
raise ConfigurationError(f"object {obj} is not callable")
return bool(any([p.ki... | Checks whether a provided object takes in any positional arguments.
Similar to takes_arg, we do this for both the __init__ function of
the class or a function / method
Otherwise, we raise an error |
355,404 | def makeLogic(self):
self.filemenu.exit. triggered.connect(self.exit_slot)
self.filemenu.save_window_layout. triggered.connect(
self.save_window_layout_slot)
self.filemenu.load_wi... | self.configmenu.manage_cameras. triggered.connect(
self.manage_cameras_slot)
self.configmenu.memory_usage. triggered.connect(
self.memory_usage_slot) |
355,405 | def bake(self):
self.unbake()
for key in self.dct:
self.get_absolute_time(key)
self.is_baked = True | Find absolute times for all keys.
Absolute time is stored in the KeyFrame dictionary as the variable
__abs_time__. |
355,406 | def un_priority(op,val):
"unary expression order-of-operations helper"
if isinstance(val,BinX) and val.op < op: return bin_priority(val.op,UnX(op,val.left),val.right)
else: return UnX(op,val) | unary expression order-of-operations helper |
355,407 | def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict:
intersection = {
: dfa_1[].intersection(dfa_2[]),
: {(dfa_1[], dfa_2[])},
: (dfa_1[], dfa_2[]),
: set(),
: dict()
}
boundary = set()
boundary.add(intersection[])
while boundary:
(state_dfa_1... | Returns a DFA accepting the intersection of the DFAs in
input.
Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and
:math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs.
Then there is a DFA :math:`A_∧` that runs simultaneously both
:math:`A_1` and :math:`A_2` on the input word and
accepts w... |
355,408 | def set_locale(request):
return request.query.get(, app.ps.babel.select_locale_by_request(request)) | Return locale from GET lang param or automatically. |
355,409 | def compute_performance(SC, verbose=True, output=):
counts = SC._counts
tp_rate = float(counts[]) / counts[] * 100
cl_rate = float(counts[]) / counts[] * 100
fn_rate = float(counts[]) / counts[] * 100
fp_st1 = float(counts[]) / counts[] * 100
fp_st2 = float(counts[]) / counts[] * 100
... | Return some performance value for comparison.
Parameters
-------
SC: SortingComparison instance
The SortingComparison
verbose: bool
Display on console or not
output: dict or pandas
Returns
----------
performance: dict or pandas.Serie depending output param |
355,410 | def eth_getBlockByHash(self, bhash, tx_objects=True):
result = yield from self.rpc_call(,
[bhash, tx_objects])
return result | https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbyhash
:param bhash: Block hash
:type bhash: str
:param tx_objects: Return txs full object (optional)
:type tx_objects: bool
:return: block
:rtype: dict or None |
355,411 | def get_kline(self, symbol, period, size=150):
params = {: symbol, : period, : size}
url = u.MARKET_URL +
def _wrapper(_func):
@wraps(_func)
def handle():
_func(http_get_request(url, params))
return handle
return _wrapper | 获取K线
:param symbol
:param period: 可选值:{1min, 5min, 15min, 30min, 60min, 1day, 1mon, 1week, 1year }
:param size: 可选值: [1,2000]
:return: |
355,412 | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
return self._persist_uncles(self.db, uncles) | Persists the list of uncles to the database.
Returns the uncles hash. |
355,413 | def update_ip_address(context, id, ip_address):
LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))
ports = []
if not in ip_address:
raise n_exc.BadRequest(resource="ip_addresses",
msg="Invalid request body.")
with context.session.begin()... | Due to NCP-1592 ensure that address_type cannot change after update. |
355,414 | def template_global(self, name: Optional[str]=None) -> Callable:
def decorator(func: Callable) -> Callable:
self.add_template_global(func, name=name)
return func
return decorator | Add a template global.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.template_global('name')
def five():
return 5
Arguments:
name: The global name (defaults to function name). |
355,415 | def validate_tenant_data(self, expected, actual):
self.log.debug()
self.log.debug(.format(repr(actual)))
for e in expected:
found = False
for act in actual:
a = {: act.enabled, : act.description,
: act.name, : act.id}
... | Validate tenant data.
Validate a list of actual tenant data vs list of expected tenant
data. |
355,416 | def unregisterHandler(self, fh):
try:
self.fds.remove(fh)
except KeyError:
pass
self.lock.acquire()
try:
self.data.rollover()
finally:
self.lock.release()
if self.closing and not self.fds:
self.d... | Unregister a file descriptor. Clean data, if such operation has been scheduled.
Parameters
----------
fh : int
File descriptor. |
355,417 | def _sample_template(sample, out_dir):
bam_fn = dd.get_work_bam(sample)
genome = dd.get_genome_build(sample)
if genome in supported:
peaks = sample.get("peaks_files", []).get("main")
if peaks:
r_code = ("library(ChIPQC);\n"
"sample = ChIPQCsample(\"{bam... | R code to get QC for one sample |
355,418 | def parse_args():
parser = argparse.ArgumentParser(description = "Validate secrets using YubiHSM",
add_help=True,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(, ,
... | Parse the command line arguments |
355,419 | def sort_stats(stats,
sortedby=,
sortedby_secondary=,
reverse=True):
if sortedby is None and sortedby_secondary is None:
return stats
sort_lambda = _sort_lambda(sortedby=sortedby,
sortedby_secondary=sortedby_... | Return the stats (dict) sorted by (sortedby).
Reverse the sort if reverse is True. |
355,420 | def update_or_append_line(filename, prefix, new_line, keep_backup=True,
append=True):
filenameprefixnew_lineprefixnew_line
result = None
if env.host_string == :
result = update_or_append_local(filename, prefix, new_line,
keep_backup, ... | Search in file 'filename' for a line starting with 'prefix' and replace
the line by 'new_line'.
If a line starting with 'prefix' not exists 'new_line' will be appended.
If the file not exists, it will be created.
Return False if new_line was appended, else True (i.e. if the prefix was
found within... |
355,421 | def elide(self, line: str, regexp: str, quantity: int = 1, offset: int = 0) -> str:
matcher = re.compile(regexp)
positions = matcher.finditer(line)
new_line = line
for match in positions:
(start, end) = match.span()
if (start > 0) and new_line[start - 1... | Erase a section of a line, matching on a regex, pushing in a quantity of blank spaces,
and jumping forward with an offset if necessary.
If the elided vowel was strong, the vowel merged with takes on the stress.
:param line:
:param regexp:
:param quantity:
:param offset:
... |
355,422 | def record2marcxml(record):
schema_name = _get_schema_name(record)
if schema_name == :
marcjson = hep2marc.do(record)
elif schema_name == :
marcjson = hepnames2marc.do(record)
else:
raise NotImplementedError(u.format(schema_name))
record = RECORD()
for key, values... | Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from the record. |
355,423 | def cache_from_names(self):
cache_from = self.cache_from()
if not cache_from or cache_from is NotSpecified:
return
if cache_from is True:
yield self.image_name
return
for thing in cache_from:
if not isinstance(thing, six.string_... | Yield the image names to do --cache-from from |
355,424 | def addparentstofks(rels, fks):
for j in rels:
son = index(fks, j[1])
parent = index(fks, j[0])
fks[son][2] = fks[son][2].replace("models.Model", parent)
if parent not in fks[son][0]:
fks[son][0].append(parent) | Get a list of relations, between parents and sons and a dict of
clases named in dia, and modifies the fks to add the parent as fk to get
order on the output of classes and replaces the base class of the son, to
put the class parent name. |
355,425 | def _disambiguate_star_fusion_junctions(star_junction_file, contamination_bam, disambig_out_file, data):
out_file = disambig_out_file
fusiondict = {}
with open(star_junction_file, "r") as in_handle:
for my_line in in_handle:
my_line_split = my_line.strip().split("\t")
if... | Disambiguate detected fusions based on alignments to another species. |
355,426 | def entry_point(entry_point_name):
def wrap(f):
ENTRY_POINT_TABLE[entry_point_name] = f
@wraps(f)
def wrapped_f(*args, **kwargs):
return f(*args, **kwargs)
return wrapped_f
return wrap | Use this to decorate a DNAnexus execution environment entry point.
Example:
.. code-block:: python
@dxpy.entry_point('main')
def hello(i):
pass |
355,427 | def instantiate_config(config):
configpythonpathsetup_modules
make_absolute_paths(config)
pipeline_config = config[]
pipeline_config[] = make_hash(config)
pipeline_config[] = json.dumps(config)
logger.debug(
.format(pipeline_config[], config))
die = False
f... | setup the config and load external modules
This updates 'config' as follows:
* All paths are replaced with absolute paths
* A hash and JSON dump of the config are stored in the config
* If 'pythonpath' is in the config, it is added to sys.path
* If 'setup_modules' is in the config, all modules nam... |
355,428 | def _signed_sub_overflow(state, a, b):
sub = Operators.SEXTEND(a, 256, 512) - Operators.SEXTEND(b, 256, 512)
cond = Operators.OR(sub < -(1 << 255), sub >= (1 << 255))
return cond | Sign extend the value to 512 bits and check the result can be represented
in 256. Following there is a 32 bit excerpt of this condition:
a - b -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff
+80000000 False False False False True True True
... |
355,429 | def insert(self, index, child):
if child not in (None, self):
if isinstance(child, String):
child_parent = child._parent
if self._parent is child:
child.remove(self)
if... | Insert ``child`` into the list of :attr:`children` at ``index``.
:param index: The index (positive integer) where to insert ``child``.
:param child: String, bytes or another :class:`String`.
If it is an :class:`.String`, this instance will be set as
its :attr:`parent`.
... |
355,430 | def read_raw(self, params=None):
path_type = self._meta.get(, )
return client.get(
self.path(path_type),
params=params,
**self._server_config.get_client_kwargs()
) | Get information about the current entity.
Make an HTTP GET call to ``self.path('self')``. Return the response.
:return: A ``requests.response`` object. |
355,431 | def main():
parser = argparse.ArgumentParser(description = ,
parents = [XMPPSettings.get_arg_parser()])
parser.add_argument(, metavar = ,
help = )
parser.add_argument(,
action = , dest = ,
... | Parse the command-line arguments and run the bot. |
355,432 | def make_even_size(x):
x_shape = x.get_shape().as_list()
assert len(x_shape) > 2, "Only 3+-dimensional tensors supported."
shape = [dim if dim is not None else -1 for dim in x_shape]
new_shape = x_shape
if x_shape[1] is not None:
new_shape[1] = 2 * int(math.ceil(x_shape[1] * 0.5))
if x_shape[2] is ... | Pad x to be even-sized on axis 1 and 2, but only if necessary. |
355,433 | def create_system(self):
return System(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of Api System Variables services facade. |
355,434 | def jd_corr(jd,
ra, dec,
obslon=None,
obslat=None,
obsalt=None,
jd_type=):
bjdhjdbjdhjd
if not HAVEKERNEL:
LOGERROR(t continue!utcjdutcjd%.5fd%.5fdbjdhjd':
pos_sun = jplkernel[0,10].compute(t.tdb.jd)
... | Returns BJD_TDB or HJD_TDB for input JD_UTC.
The equation used is::
BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay
where:
- JD_to_TDB_corr is the difference between UTC and TDB JDs
- romer_delay is the delay caused by finite speed of light from Earth-Sun
This is based on the code at:
... |
355,435 | def read_csv_with_errors(cls,
url,
delimiter=,
header=True,
comment_char=,
escape_char=,
double_quote=True,
quote_cha... | Constructs an SFrame from a CSV file or a path to multiple CSVs, and
returns a pair containing the SFrame and a dict of filenames to SArrays
indicating for each file, what are the incorrectly parsed lines
encountered.
Parameters
----------
url : string
Locati... |
355,436 | def update(self, auth_payload=values.unset):
data = values.of({: auth_payload, })
payload = self._version.update(
,
self._uri,
data=data,
)
return ChallengeInstance(
self._version,
payload,
service_sid=sel... | Update the ChallengeInstance
:param unicode auth_payload: Optional payload to verify the Challenge
:returns: Updated ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance |
355,437 | def build_plane_arrays(x, y, qlist):
if type(qlist) is not list:
return_list = False
qlist = [qlist]
else:
return_list = True
xv = x[np.where(y==y[0])[0]]
yv = y[np.where(x==x[0])[0]]
qlistp = []
for n in range(len(qlist)):
qlistp.append(np.zeros((... | Build a 2-D array out of data taken in the same plane, for contour
plotting. |
355,438 | def merge_links_from(self, other_node, merge_same_value_targets=False):
for other_link in other_node.link_list:
for existing_link in self.link_list:
if merge_same_value_targets:
if other_link.target.value == existing_link.target.value:
... | Merge links from another node with ``self.link_list``.
Copy links from another node, merging when copied links point to a
node which this already links to.
Args:
other_node (Node): The node to merge links from
merge_same_value_targets (bool): Whether or not to merge lin... |
355,439 | def comment(self, issue, body):
url = issue.comments_url
data = {: body}
response = self.session.post(url, json.dumps(data))
assert response.status_code == 201
return json.loads(response.content) | Comment on existing issue on Github.
For JSON data returned by Github refer:
https://developer.github.com/v3/issues/comments/#create-a-comment
:param issue: object of exisiting issue
:param body: body of the comment
:returns: dict of JSON data returned by Github of the new comme... |
355,440 | def insert_data(self, travel_impedance_measure_name, data):
f = float
data_tuple = [(int(x["from_stop_I"]), int(x["to_stop_I"]), f(x["min"]), f(x["max"]), f(x["median"]), f(x["mean"])) for
x in data]
insert_stmt = + travel_impedance_measure_name +
self.co... | Parameters
----------
travel_impedance_measure_name: str
data: list[dict]
Each list element must contain keys:
"from_stop_I", "to_stop_I", "min", "max", "median" and "mean" |
355,441 | def span_path(cls, project, trace, span):
return google.api_core.path_template.expand(
"projects/{project}/traces/{trace}/spans/{span}",
project=project,
trace=trace,
span=span,
) | Return a fully-qualified span string. |
355,442 | def _handle_output(self, channel, output):
augmented = Sentinel.augment_items(output, channel=channel, secret=False)
for message in augmented:
self.out(message.channel, message, not message.secret) | Given an initial channel and a sequence of messages or sentinels,
output the messages. |
355,443 | def to_range(obj, score=None, id=None, strand=None):
from jcvi.utils.range import Range
if score or id:
_score = score if score else obj.score
_id = id if id else obj.id
return Range(seqid=obj.seqid, start=obj.start, end=obj.end, \
score=_score, id=_id)
elif strand:... | Given a gffutils object, convert it to a range object |
355,444 | def get_metadata(self, obj, prefix=None):
uri = "/%s/%s" % (self.uri_base, utils.get_name(obj))
resp, resp_body = self.api.method_head(uri)
ret = {}
if prefix is None:
prefix = OBJECT_META_PREFIX
low_prefix = prefix.lower()
for hkey, hval in ... | Returns the metadata for the specified object as a dict. |
355,445 | def importProteinDatabase(filePath, proteindb=None, decoyTag=,
contaminationTag=, headerParser=None, forceId=False,
cleavageRule=, minLength=5, maxLength=40, missedCleavage=2,
ignoreIsoleucine=False, removeNtermM=True):
proteindb = ProteinDatabase() if proteindb is None else proteindb
... | Generates a :class:`ProteinDatabase` by in silico digestion of proteins
from a fasta file.
:param filePath: File path
:param proteindb: optional an existing :class:`ProteinDatabase` can be
specified, otherwise a new instance is generated and returned
:param decoyTag: If a fasta file contains de... |
355,446 | def request(self, method, url, body=None, content_type=):
headers = self.make_auth_headers(content_type)
connection = http_client.HTTPSConnection(self.apibase)
connection.request(method, url, body, headers=headers)
response = connection.getresponse()
data = response.read... | Send http request. |
355,447 | def predict_log_proba(self, X):
Xt, _, _ = self._transform(X)
return self._final_estimator.predict_log_proba(Xt) | Apply transforms, and predict_log_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_score : array-like, shape = [n_samples, n_class... |
355,448 | def stop(self):
with self._status_lock:
if self._running:
assert self._observer is not None
self._observer.stop()
self._running = False
self._origin_mapped_data = dict() | Stops monitoring the predefined directory. |
355,449 | def PopupGetFolder(message, title=None, default_path=, no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folde... | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
... |
355,450 | def get_check_point(self, project, logstore, consumer_group, shard=-1):
request = ConsumerGroupGetCheckPointRequest(project, logstore, consumer_group, shard)
params = request.get_params()
headers = {}
resource = "/logstores/" + logstore + "/consumergroups/" + consumer_group... | Get check point
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
:param consumer_group: consumer group name
:type shard: int
:param shard: shard id
... |
355,451 | def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False):
current_1, queue_1 = __formatXpath__(xpath1)
if xpath2 is None:
result_1, loop = performXpath(parent, current_1)
if loop is True:
queue_1 = xpath1
central = Non... | Loop over passages to construct and increment new tree given a parent and XPaths
:param parent: Parent on which to perform xpath
:param new_tree: Parent on which to add nodes
:param xpath1: List of xpath elements
:type xpath1: [str]
:param xpath2: List of xpath elements
:type xpath2: [str]
... |
355,452 | def refine_peak(tsmap, pix):
nx = tsmap.shape[1]
ny = tsmap.shape[0]
if pix[0] == 0 or pix[0] == (nx - 1):
xval = float(pix[0])
xerr = -1
else:
x_arr = tsmap[pix[1], pix[0] - 1:pix[0] + 2]
xval, xerr = estimate_pos_and_err_parabolic(x_arr)
xval += float... | Solve for the position and uncertainty of source assuming that you
are near the maximum and the errors are parabolic
Parameters
----------
tsmap : `~numpy.ndarray`
Array with the TS data.
Returns
-------
The position and uncertainty of the source, in pixel units
w.r.t. the cente... |
355,453 | def isxmap(xmethod, opt):
if xmethod == :
isx = {: , : ,
: }
else:
isx = {: , : ,
: , : , : }
if not opt[]:
isx.update(evlmap(True))
return isx | Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser. |
355,454 | def get_overlay_spec(o, k, v):
k = wrap_tuple(k)
return ((type(v).__name__, v.group, v.label) + k if len(o.kdims) else
(type(v).__name__,) + k) | Gets the type.group.label + key spec from an Element in an Overlay. |
355,455 | def all_other_enabled_satchels(self):
return dict(
(name, satchel)
for name, satchel in self.all_satchels.items()
if name != self.name.upper() and name.lower() in map(str.lower, self.genv.services)
) | Returns a dictionary of satchels used in the current configuration, excluding ourselves. |
355,456 | def json_response(obj):
return Response(
response=json.dumps(
obj, indent=4, cls=AirflowJsonEncoder),
status=200,
mimetype="application/json") | returns a json response from a json serializable python object |
355,457 | def attention_lm_moe_24b_diet():
hparams = attention_lm_moe_large_diet()
hparams.moe_hidden_sizes = "12288"
hparams.moe_num_experts = 1024
hparams.batch_size = 4096
return hparams | Unnecessarily large model with 24B params - because we can. |
355,458 | def name(self):
names = (criterion.name() for criterion in self._criteria)
return .join(sorted(names)) | Concatenates the names of the given criteria in alphabetical order.
If a sub-criterion is itself a combined criterion, its name is
first split into the individual names and the names of the
sub-sub criteria is used instead of the name of the sub-criterion.
This is done recursively to en... |
355,459 | def reduce_sequences(object_a, object_b):
def is_seq(obj):
return hasattr(obj, "__getitem__") or hasattr(obj, "__iter__")
if object_a is None or object_b is None:
return None
elif is_seq(object_a) and is_seq(object_b):
reduced = []
for element_a, element_b in zi... | Performs an element-wise addition of sequences into a new list.
Both sequences must have the same length, and the addition operator must be
defined for each element of the sequence. |
355,460 | def run(cmd, input=None, capture_output=False, check=False, quiet=False, **kwargs):
if input is not None:
kwargs[] = subprocess.PIPE
if capture_output:
kwargs[] = kwargs[] = subprocess.PIPE
try:
proc = subprocess.Popen(cmd, startupinfo=get_startupinfo(), **kwargs)
except OS... | Run the command described by cmd and return its (stdout, stderr) tuple. |
355,461 | def verify_resource_dict(res_dict, is_create, attr_info):
if ((bc.NEUTRON_VERSION >= bc.NEUTRON_NEWTON_VERSION) and
in res_dict):
res_dict[] = res_dict[]
if is_create:
for attr, attr_vals in six.iteritems(attr_info):
if attr_vals[]:
if not in attr... | Verifies required attributes are in resource dictionary, res_dict.
Also checking that an attribute is only specified if it is allowed
for the given operation (create/update).
Attribute with default values are considered to be optional.
This function contains code taken from function 'prepare_request_... |
355,462 | def load_alleles_dict():
alleles = load_alleles()
result = {}
for allele in alleles:
for name in {allele.name}.union(allele.synonyms):
result[name] = allele
return result | Create a dictionary mapping each unique allele name to a namedtuple
containing information about that alleles class, locus, species, &c. |
355,463 | def ordered_repr(obj: object, attrlist: Iterable[str],
joiner: str = COMMA_SPACE) -> str:
return "<{classname}({kvp})>".format(
classname=type(obj).__name__,
kvp=joiner.join("{}={}".format(a, repr(getattr(obj, a)))
for a in attrlist)
) | Shortcut to make :func:`repr` functions ordered.
Define your :func:`__repr__` like this:
.. code-block:: python
def __repr__(self):
return ordered_repr(self, ["field1", "field2", "field3"])
Args:
obj: object to display
attrlist: iterable of attribute names
join... |
355,464 | def delete_client(self, identifier):
params = {: identifier}
response = yield from self._transact(SERVER_DELETECLIENT, params)
self.synchronize(response) | Delete client. |
355,465 | def distribute(self, func, partitioned_chunks, kwargs):
result = self.client.gather(self.client.map(partial(func, **kwargs), partitioned_chunks))
return [item for sublist in result for item in sublist] | Calculates the features in a parallel fashion by distributing the map command to the dask workers on a local
machine
:param func: the function to send to each worker.
:type func: callable
:param partitioned_chunks: The list of data chunks - each element is again
a list of ch... |
355,466 | def iters(cls, batch_size=32, device=0, root=, vectors=None, **kwargs):
TEXT = data.Field()
LABEL = data.Field(sequential=False)
train, val, test = cls.splits(TEXT, LABEL, root=root, **kwargs)
TEXT.build_vocab(train, vectors=vectors)
LABEL.build_vocab(train)
r... | Create iterator objects for splits of the SST dataset.
Arguments:
batch_size: Batch_size
device: Device to create batches on. Use - 1 for CPU and None for
the currently active GPU device.
root: The root directory that the dataset's zip archive will be
... |
355,467 | def setup_groups(portal):
logger.info("*** Setup Roles and Groups ***")
portal_groups = api.get_tool("portal_groups")
for gdata in GROUPS:
group_id = gdata["id"]
if group_id not in portal_groups.listGroupIds():
logger.info("+++ Adding group {title} ({id})".format(... | Setup roles and groups for BECHEM |
355,468 | def add_series(self, series):
if not isinstance(series, Series):
raise TypeError(" is not a Series" % str(series))
self._all_series.append(series)
series._chart = self | Adds a :py:class:`.Series` to the chart.
:param Series series: The :py:class:`.Series` to add. |
355,469 | def _rotate_to_arbitrary_vector(v,a,inv=False,_dontcutsmall=False):
normv= v/numpy.tile(numpy.sqrt(numpy.sum(v**2.,axis=1)),(3,1)).T
rotaxis= numpy.cross(normv,a)
rotaxis/= numpy.tile(numpy.sqrt(numpy.sum(rotaxis**2.,axis=1)),(3,1)).T
crossmatrix= numpy.empty((len(v),3,3))
crossmatrix[:,0,:]= n... | Return a rotation matrix that rotates v to align with unit vector a
i.e. R . v = |v|\hat{a} |
355,470 | def find_primitive(cell, symprec=1e-5, angle_tolerance=-1.0):
_set_no_error()
lattice, positions, numbers, _ = _expand_cell(cell)
if lattice is None:
return None
num_atom_prim = spg.primitive(lattice,
positions,
numbers,
... | Primitive cell is searched in the input cell.
The primitive cell is returned by a tuple of (lattice, positions, numbers).
If it fails, None is returned. |
355,471 | def page(self, value):
instance = copy(self)
instance._filters.append({
: value
})
return instance | Set the page which will be returned.
:param value: 'page' parameter value for the rest api call
:type value: str
Take a look at https://apihelp.surveygizmo.com/help/surveyresponse-sub-object |
355,472 | def def_variables(s):
frame = inspect.currentframe().f_back
try:
if isinstance(s,str):
s = re.split(, s)
res = []
for t in s:
if not t:
continue
if t.count("@") > 0:
sym = IndexedSymbol(t,Variable)
... | blabla |
355,473 | def charset_to_int(s, charset):
output = 0
for char in s:
output = output * len(charset) + charset.index(char)
return output | Turn a string into a non-negative integer.
>>> charset_to_int('0', B40_CHARS)
0
>>> charset_to_int('10', B40_CHARS)
40
>>> charset_to_int('abcd', B40_CHARS)
658093
>>> charset_to_int('', B40_CHARS)
0
>>> charset_to_int('muneeb.id', B40_CHARS)
149190078205533
>>> charset_to_i... |
355,474 | def read(self, user=True, defaults=True):
if user:
self._add_user_source()
if defaults:
self._add_default_source() | Find and read the files for this configuration and set them
as the sources for this configuration. To disable either
discovered user configuration files or the in-package defaults,
set `user` or `defaults` to `False`. |
355,475 | def training(loss_op):
global_step = tf.Variable(0, name=, trainable=False)
with tf.name_scope():
optimizer = tf.train.AdamOptimizer(epsilon=0.001)
train_op = optimizer.minimize(loss_op, global_step)
return train_op, global_step | Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float. |
355,476 | def sha1_digest(instr):
if six.PY3:
b = salt.utils.stringutils.to_bytes(instr)
return hashlib.sha1(b).hexdigest()
return hashlib.sha1(instr).hexdigest() | Generate an sha1 hash of a given string. |
355,477 | def mod_sys_path(paths):
old_path = sys.path
sys.path = paths + sys.path
try:
yield
finally:
sys.path = old_path | A context manager that will append the specified paths to Python's
``sys.path`` during the execution of the block.
:param paths: the paths to append
:type paths: list(str) |
355,478 | def simxGetDialogResult(clientID, dialogHandle, operationMode):
result = ct.c_int()
return c_GetDialogResult(clientID, dialogHandle, ct.byref(result), operationMode), result.value | Please have a look at the function description/documentation in the V-REP user manual |
355,479 | def set_client(self, *args, **kwargs):
Adam Yauch
self.client = {}
for arg, value in kwargs.iteritems():
if value:
self.client[arg] = value
client_schema(self.client) | Se você possui informações cadastradas sobre o comprador você pode utilizar
este método para enviar estas informações para o PagSeguro. É uma boa prática pois
evita que seu cliente tenha que preencher estas informações novamente na página
do PagSeguro.
Args:
name (str): (opc... |
355,480 | def get_facet_keys_as_list(self,field):
facet_testLoremipsumamet,dolorsit
facets = self.get_facets()
if facets == -1:
return facets
if field in facets.keys():
return [x for x in facets[field]] | :param str field: Name of facet field to retrieve keys from.
Similar to get_facet_values_as_list but returns the list of keys as a list instead.
Example::
>>> r.get_facet_keys_as_list('facet_test')
['Lorem', 'ipsum', 'amet,', 'dolor', 'sit'] |
355,481 | def init_benchmarks(n_values=None):
if n_values is None:
n_values = (0, 5, 50, 250, 1000, 5000, 10000)
string_tables = {n: gen_string_table(n) for n in n_values}
regexs = gen_regex_table()
data = []
for n in n_values:
for id in xrange(len(regexs)):
regex = regexs[... | Initialize the strings we'll run the regexes against.
The strings used in the benchmark are prefixed and suffixed by
strings that are repeated n times.
The sequence n_values contains the values for n.
If n_values is None the values of n from the original benchmark
are used.
The generated list... |
355,482 | def sqlmany(self, stringname, *args):
if hasattr(self, ):
return getattr(self.alchemist.many, stringname)(*args)
s = self.strings[stringname]
return self.connection.cursor().executemany(s, args) | Wrapper for executing many SQL calls on my connection.
First arg is the name of a query, either a key in the
precompiled JSON or a method name in
``allegedb.alchemy.Alchemist``. Remaining arguments should be
tuples of argument sequences to be passed to the query. |
355,483 | def compile_state_action_constraints(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> List[TensorFluent]:
scope = self.transition_scope(state, action)
constraints = []
with self.graph.as_default():
with tf.name_scope():
... | Compiles the state-action constraints given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A list of :obj:`rddl2tf.fluent.TensorFluent`. |
355,484 | def get_help_msg(self,
dotspace_ending=False,
**kwargs):
context = self.get_context_for_help_msgs(kwargs)
if self.help_msg is not None and len(self.help_msg) > 0:
context = copy(context)
try... | The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg'
attribute, whether it is defined at the instance level or at the class level.
The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot
and a ... |
355,485 | def add_userids_for_address(self, address: Address, user_ids: Iterable[str]):
self._address_to_userids[address].update(user_ids) | Add multiple ``user_ids`` for the given ``address``.
Implicitly adds any addresses if they were unknown before. |
355,486 | def get_package_filename(filename, package_dir=None):
if getattr(sys, , False):
package_dir = os.path.join(
sys._MEIPASS,
os.path.basename(os.path.dirname(__file__))
)
elif not package_dir:
package_dir = os.path.dirname(__file__)
return os.path.join(pack... | Return the filename of the data file. |
355,487 | def create_stack(self, stack_name, template_body=None, template_url=None,
parameters=[], notification_arns=[], disable_rollback=False,
timeout_in_minutes=None, capabilities=None):
params = {: "JSON", : stack_name,
: self.encode_bool(disable_rollback)}
if ... | Creates a CloudFormation Stack as specified by the template.
:type stack_name: string
:param stack_name: The name of the Stack, must be unique amoung running
Stacks
:type template_body: string
:param template_body: The template body (JSON string)
:t... |
355,488 | def print_build_info(zipped_pex=False):
if zipped_pex:
release_file = get_zipped_heron_release_file()
else:
release_file = get_heron_release_file()
with open(release_file) as release_info:
release_map = yaml.load(release_info)
release_items = sorted(release_map.items(), key=lambda tup: tup[0])... | Print build_info from release.yaml
:param zipped_pex: True if the PEX file is built with flag `zip_safe=False'. |
355,489 | def rewire_inputs(data_list):
if len(data_list) < 2:
return data_list
mapped_ids = {bundle[].id: bundle[].id for bundle in data_list}
for bundle in data_list:
updated = False
copy = bundle[]
for field_schema, fields in iterate_fields(copy.input, copy.process.input_sch... | Rewire inputs of provided data objects.
Input parameter is a list of original and copied data object model
instances: ``[{'original': original, 'copy': copy}]``. This
function finds which objects reference other objects (in the list)
on the input and replaces original objects with the copies (mutates
... |
355,490 | def get_clients_groups(self) -> typing.Iterator[]:
for group in self.groups:
if group.group_is_client_group:
yield group | Gets all clients groups
Returns: generator of Groups |
355,491 | def _set_signed_in(self):
names = [
controller.get_user_name(user, full_name=CONFIG[])
for user in controller.signed_in_users()
]
self.lbl_signedin_list.setText(.join(sorted(names))) | Populate the signed_in list with the names of currently
signed in users. |
355,492 | def cleanup(self):
if os.path.exists(self.path):
os.remove(self.path) | Clean up the saved state. |
355,493 | def download_file(self, response, outfile, quiet=True, chunk_size=1048576):
outpath = os.path.dirname(outfile)
if not os.path.exists(outpath):
os.makedirs(outpath)
size = int(response.headers[])
size_read = 0
if not quiet:
print( + os.path.basena... | download a file to an output file based on a chunk size
Parameters
==========
response: the response to download
outfile: the output file to download to
quiet: suppress verbose output (default is True)
chunk_size: the size of the chunk to stream |
355,494 | def node_has_namespace(self, node: BaseEntity, namespace: str) -> bool:
return any(
self._node_has_namespace_helper(n, namespace)
for n in self.iter_equivalent_nodes(node)
) | Check if the node have the given namespace.
This also should look in the equivalent nodes. |
355,495 | def user_stats_api(request, provider):
if not in request.GET or provider not in settings.USER_STATS_API_KEY \
or request.GET[] != settings.USER_STATS_API_KEY[provider]:
return HttpResponse(, status=401)
since = None
if in request.GET:
since = datetime.datetime.fromtimesta... | Get statistics for selected Edookit users
key:
api key
since:
time as timestamp - get stats changed since |
355,496 | def between(self, low, high):
newq = self.copy()
newq.setOp(Query.Op.Between)
newq.setValue((low, high))
return newq | Sets the operator type to Query.Op.Between and sets the
value to a tuple of the two inputted values.
:param low | <variant>
:param high | <variant>
:return <Query>
:usage |>>> from orb import Query as Q
|>>> query ... |
355,497 | def Hi(self, str_, salt, i):
Uj = self.HMAC(str_, salt + b"\000\000\000\001")
result = Uj
for _ in range(2, i + 1):
Uj = self.HMAC(str_, Uj)
result = self.XOR(result, Uj)
return result | The Hi(str, salt, i) function. |
355,498 | def _create_network_config(self):
path = os.path.join(self.working_dir, "etc", "network")
os.makedirs(path, exist_ok=True)
open(os.path.join(path, ".gns3_perms"), ).close()
os.makedirs(os.path.join(path, "if-up.d"), exist_ok=True)
os.makedirs(os.path.join(path, "if-down.... | If network config is empty we create a sample config |
355,499 | def get_section_path(section):
keys = []
p = section
for i in range(section.depth):
keys.insert(0, p.name)
p = p.parent
return keys | Return a list with keys to access the section from root
:param section: A Section
:type section: Section
:returns: list of strings in the order to access the given section from root
:raises: None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.