Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
374,100 | def visit_BitVecSub(self, expression, *operands):
left = expression.operands[0]
right = expression.operands[1]
if isinstance(left, BitVecAdd):
if self._same_constant(left.operands[0], right):
return left.operands[1]
elif self._same_constant(left.o... | a - 0 ==> 0
(a + b) - b ==> a
(b + a) - b ==> a |
374,101 | def serialize(self, content):
content = super(JSONPEmitter, self).serialize(content)
callback = self.request.GET.get(, )
return u % (callback, content) | Serialize to JSONP.
:return string: serializaed JSONP |
374,102 | def set_privkey_compressed(privkey, compressed=True):
if len(privkey) != 64 and len(privkey) != 66:
raise ValueError("expected 32-byte private key as a hex string")
if compressed and len(privkey) == 64:
privkey +=
if not compressed and len(privkey) == 66:
if privkey[-2:]... | Make sure the private key given is compressed or not compressed |
374,103 | def dump(self):
for modpath in sorted(self.map):
title = % modpath
print( + title + + *len(title))
for name, value in sorted(self.map.get(modpath, {}).items()):
print( % (name, .join(sorted(value)))) | Prints out the contents of the import map. |
374,104 | def element_at(index):
if index < 0:
raise IndexError("element_at used with illegal index {}".format(index))
def element_at_transducer(reducer):
return ElementAt(reducer, index)
return element_at_transducer | Create a transducer which obtains the item at the specified index. |
374,105 | def classinstances(cls):
l = [i for i in cls.allinstances() if type(i) == cls]
return l | Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won\'t return instances of further subclasses.
:returns: all instnaces of the current class
:rty... |
374,106 | def setWidth(self, typeID, width):
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_WIDTH, typeID, width) | setWidth(string, double) -> None
Sets the width in m of vehicles of this type. |
374,107 | def _ExtractContentSettingsExceptions(self, exceptions_dict, parser_mediator):
for permission in exceptions_dict:
if permission not in self._EXCEPTIONS_KEYS:
continue
exception_dict = exceptions_dict.get(permission, {})
for urls, url_dict in exception_dict.items():
last_used ... | Extracts site specific events.
Args:
exceptions_dict (dict): Permission exceptions data from Preferences file.
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs. |
374,108 | def decode(self, encoded_packet):
b64 = False
if not isinstance(encoded_packet, binary_types):
encoded_packet = encoded_packet.encode()
elif not isinstance(encoded_packet, bytes):
encoded_packet = bytes(encoded_packet)
self.packet_type = six.byte2int(enco... | Decode a transmitted package. |
374,109 | def _process_request(self, request, client_address):
try:
self.finish_request(request, client_address)
except Exception:
self.handle_error(request, client_address)
finally:
self.shutdown_request(request) | Actually processes the request. |
374,110 | def get_task_runner(local_task_job):
if _TASK_RUNNER == "StandardTaskRunner":
return StandardTaskRunner(local_task_job)
elif _TASK_RUNNER == "CgroupTaskRunner":
from airflow.contrib.task_runner.cgroup_task_runner import CgroupTaskRunner
return CgroupTaskRunner(local_task_job)
el... | Get the task runner that can be used to run the given job.
:param local_task_job: The LocalTaskJob associated with the TaskInstance
that needs to be executed.
:type local_task_job: airflow.jobs.LocalTaskJob
:return: The task runner to use to run the task.
:rtype: airflow.task.task_runner.base_t... |
374,111 | def read(cls, proto):
regionImpl = proto.regionImpl.as_struct(cls.getSchema())
return cls.readFromProto(regionImpl) | Calls :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto`
on subclass after converting proto to specific type using
:meth:`~nupic.bindings.regions.PyRegion.PyRegion.getSchema`.
:param proto: PyRegionProto capnproto object |
374,112 | def timeline(self, timeline="home", max_id=None, min_id=None, since_id=None, limit=None):
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = s... | Fetch statuses, most recent ones first. `timeline` can be 'home', 'local', 'public',
'tag/hashtag' or 'list/id'. See the following functions documentation for what those do.
Local hashtag timelines are supported via the `timeline_hashtag()`_ function.
The default timeline is the "home" ... |
374,113 | def align(s1,s2,test=False,seqfmt=,
psm=None,pmm=None,pgo=None,pge=None,
matrix=None,
outscore=False):
import operator
from Bio import pairwise2
if seqfmt==:
if any([p is None for p in [psm,pmm,pgo,pge]]):
alignments = pairwise2.align.localxx(s1.upper(),s2... | Creates pairwise local alignment between seqeunces.
Get the visualization and alignment scores.
:param s1: seqeunce 1
:param s2: seqeunce 2
REF: http://biopython.org/DIST/docs/api/Bio.pairwise2-module.html
The match parameters are:
CODE DESCRIPTION
x No parameters. Identical c... |
374,114 | def bind_top_down(lower, upper, __fval=None, **fval):
if __fval is not None:
fval.update(__fval)
upper._overload_fields = upper._overload_fields.copy()
upper._overload_fields[lower] = fval | Bind 2 layers for building.
When the upper layer is added as a payload of the lower layer, all the arguments # noqa: E501
will be applied to them.
ex:
>>> bind_top_down(Ether, SNAP, type=0x1234)
>>> Ether()/SNAP()
<Ether type=0x1234 |<SNAP |>> |
374,115 | def unsplit_query(query):
def unsplit_assignment((x, y)):
if (x is not None) and (y is not None):
return x + + y
elif x is not None:
return x
elif y is not None:
return + y
else:
return
return .join(map(unsplit_assignment, q... | Create a query string using the tuple query with a format as the one
returned by split_query() |
374,116 | def autoExpand(self, level=None):
return self._autoExpand.get(level, self._autoExpand.get(None, False)) | Returns whether or not to expand for the inputed level.
:param level | <int> || None
:return <bool> |
374,117 | def get(self, url):
r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)
self._check_response(r, 200)
return r.json() | Do a GET request |
374,118 | def destroy(name, call=None):
if call == :
raise SaltCloudSystemExit(
)
__utils__[](
,
,
.format(name),
args={: name},
sock_dir=__opts__[],
transport=__opts__[]
)
vm_properties = [
"name",
"s... | To destroy a VM from the VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -d vmname
salt-cloud --destroy vmname
salt-cloud -a destroy vmname |
374,119 | def _get_dependency_order(g, node_list):
access_ = accessibility(g)
deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems())
nodes = node_list + list(set(g.nodes()) - set(node_list))
ordered_nodes = []
while nodes:
n_ = nodes[0]
n_deps = deps.get(n_)
if (n_ i... | Return list of nodes as close as possible to the ordering in node_list,
but with child nodes earlier in the list than parents. |
374,120 | def computeRange(corners):
x = corners[:, 0]
y = corners[:, 1]
_xrange = (np.minimum.reduce(x), np.maximum.reduce(x))
_yrange = (np.minimum.reduce(y), np.maximum.reduce(y))
return _xrange, _yrange | Determine the range spanned by an array of pixel positions. |
374,121 | def parallel_starfeatures_lcdir(lcdir,
outdir,
lc_catalog_pickle,
neighbor_radius_arcsec,
fileglob=None,
maxobjects=None,
deredd... | This runs parallel star feature extraction for a directory of LCs.
Parameters
----------
lcdir : list of str
The directory to search for light curves.
outdir : str
The output directory where the results will be placed.
lc_catalog_pickle : str
The path to a catalog contain... |
374,122 | def _convert_iterable(self, iterable):
if not callable(self._wrapper):
return iterable
return [self._wrapper(x) for x in iterable] | Converts elements returned by an iterable into instances of
self._wrapper |
374,123 | def list_pools(self):
search_opts = {: True}
return [FloatingIpPool(pool) for pool
in self.client.list_networks(**search_opts).get()] | Fetches a list of all floating IP pools.
:returns: List of FloatingIpPool objects |
374,124 | def max_age(self, value):
option = Option()
option.number = defines.OptionRegistry.MAX_AGE.number
option.value = int(value)
self.del_option_by_number(defines.OptionRegistry.MAX_AGE.number)
self.add_option(option) | Set the MaxAge of the response.
:type value: int
:param value: the MaxAge option |
374,125 | def get_possible_initializer_keys(
cls, use_peepholes=False, use_batch_norm_h=True, use_batch_norm_x=False,
use_batch_norm_c=False):
possible_keys = cls.POSSIBLE_INITIALIZER_KEYS.copy()
if not use_peepholes:
possible_keys.difference_update(
{cls.W_F_DIAG, cls.W_I_DIAG, cls.W_O_... | Returns the keys the dictionary of variable initializers may contain.
The set of all possible initializer keys are:
w_gates: weight for gates
b_gates: bias of gates
w_f_diag: weight for prev_cell -> forget gate peephole
w_i_diag: weight for prev_cell -> input gate peephole
w_o_diag:... |
374,126 | def all_coarse_grains_for_blackbox(blackbox):
for partition in all_partitions(blackbox.output_indices):
for grouping in all_groupings(partition):
coarse_grain = CoarseGrain(partition, grouping)
try:
validate.blackbox_and_coarse_grain(blackbox, coarse_grain)
... | Generator over all |CoarseGrains| for the given blackbox.
If a box has multiple outputs, those outputs are partitioned into the same
coarse-grain macro-element. |
374,127 | def minion_sign_in_payload(self):
payload = {}
payload[] =
payload[] = self.opts[]
if in self.opts:
autosign_grains = {}
for grain in self.opts[]:
autosign_grains[grain] = self.opts[].get(grain, None)
payload[] = autosign_gra... | Generates the payload used to authenticate with the master
server. This payload consists of the passed in id_ and the ssh
public key to encrypt the AES key sent back from the master.
:return: Payload dictionary
:rtype: dict |
374,128 | def plot_sections(self, fout_dir=".", **kws_usr):
kws_plt, _ = self._get_kws_plt(None, **kws_usr)
PltGroupedGos(self).plot_sections(fout_dir, **kws_plt) | Plot groups of GOs which have been placed in sections. |
374,129 | def hexedit(x):
x = bytes(x)
fname = get_temp_file()
with open(fname,"wb") as f:
f.write(x)
subprocess.call([conf.prog.hexedit, fname])
with open(fname, "rb") as f:
x = f.read()
return x | Run external hex editor on a packet or bytes. Set editor in conf.prog.hexedit |
374,130 | def metadata(self):
params = {
self.PCTYPE: self.CTYPE_XML
}
response = self.call(self.CGI_BUG, params)
return response | Get metadata information in XML format. |
374,131 | def build_option_parser(parser):
parser.add_argument(
"--os-data-processing-api-version",
metavar="<data-processing-api-version>",
default=utils.env(
,
default=DEFAULT_DATA_PROCESSING_API_VERSION),
help=("Data processing API version, default=" +
... | Hook to add global options. |
374,132 | def reducing(reducer, init=UNSET):
reducer2 = reducer
def reducing_transducer(reducer):
return Reducing(reducer, reducer2, init)
return reducing_transducer | Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A singl... |
374,133 | def adsSyncReadReqEx2(
port, address, index_group, index_offset, data_type, return_ctypes=False
):
sync_read_request = _adsDLL.AdsSyncReadReqEx2
ams_address_pointer = ctypes.pointer(address.amsAddrStruct())
index_group_c = ctypes.c_ulong(index_group)
index_offset_c = ctypes.c_ulong(index_... | Read data synchronous from an ADS-device.
:param int port: local AMS port as returned by adsPortOpenEx()
:param pyads.structs.AmsAddr address: local or remote AmsAddr
:param int index_group: PLC storage area, according to the INDEXGROUP
constants
:param int index_offset: PLC storage address
... |
374,134 | def infer_call(self, context=None):
callcontext = contextmod.copy_context(context)
callcontext.callcontext = contextmod.CallContext(
args=self.args, keywords=self.keywords
)
callcontext.boundnode = None
if context is not None:
callcontext.extra_context = _populate_context_lookup... | infer a Call node by trying to guess what the function returns |
374,135 | def _get_cache_key(self):
keys = list(self.params.keys())
keys.sort()
cache_key = str()
for key in keys:
if key != "api_sig" and key != "api_key" and key != "sk":
cache_key += key + self.params[key]
return hashlib.sha1(cache_key.encode("ut... | The cache key is a string of concatenated sorted names and values. |
374,136 | def checkQueryRange(self, start, end):
condition = (
(start < 0 or end > self.getLength()) or
start > end or start == end)
if condition:
raise exceptions.ReferenceRangeErrorException(
self.getId(), start, end) | Checks to ensure that the query range is valid within this reference.
If not, raise ReferenceRangeErrorException. |
374,137 | def taskfile_created_data(file_, role):
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
dt = file_.date_created
return dt_to_qdatetime(dt) | Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date
:rtype: depending on role
:raises: None |
374,138 | def path(self):
if (self.source_file.startswith() and
self.target_file.startswith()):
filepath = self.source_file[2:]
elif (self.source_file.startswith() and
self.target_file == ):
filepath = self.source_file[2:]
elif (self.target_fi... | Return the file path abstracted from VCS. |
374,139 | def add_prefix(self, ncname: str) -> None:
if ncname not in self.prefixmap:
uri = cu.expand_uri(ncname + , self.curi_maps)
if uri and in uri:
self.prefixmap[ncname] = uri
else:
print(f"Unrecognized prefix: {ncname}", file=sys.stderr)
... | Look up ncname and add it to the prefix map if necessary
@param ncname: name to add |
374,140 | def _ensure_create_ha_compliant(self, router, router_type):
details = router.pop(ha.DETAILS, {})
if details == ATTR_NOT_SPECIFIED:
details = {}
res = {ha.ENABLED: router.pop(ha.ENABLED, ATTR_NOT_SPECIFIED),
ha.DETAILS: details}
if not is_attr_set(res[... | To be called in create_router() BEFORE router is created in DB. |
374,141 | def person_details(self, person_id, standardize=False):
resp = self._request(path.join(ENDPOINTS[], person_id))
if standardize:
resp[] = [self.standardize(res) for res in resp[]]
return resp | Get a detailed person object
:param person_id:
String corresponding to the person's id.
>>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438') |
374,142 | def get_start_time(self):
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
CreationTime = win32.GetProce... | Determines when has this process started running.
@rtype: win32.SYSTEMTIME
@return: Process start time. |
374,143 | def get(cls, name, raise_exc=True):
element = cls.objects.filter(name, exact_match=True).first() if \
name is not None else None
if not element and raise_exc:
raise ElementNotFound(
% (name, cls.__name__))
return element | Get the element by name. Does an exact match by element type.
:param str name: name of element
:param bool raise_exc: optionally disable exception.
:raises ElementNotFound: if element does not exist
:rtype: Element |
374,144 | def nth(lst, n):
expect_type(n, (String, Number), unit=None)
if isinstance(n, String):
if n.value.lower() == :
i = 0
elif n.value.lower() == :
i = -1
else:
raise ValueError("Invalid index %r" % (n,))
else:
i = n.to_python_ind... | Return the nth item in the list. |
374,145 | def get_file(self, fp, headers=None, cb=None, num_cb=10,
torrent=False, version_id=None, override_num_retries=None,
response_headers=None, callback=None):
if cb:
if num_cb > 2:
cb_count = self.size / self.BufferSize / (num_cb-2)
... | Retrieves a file from an S3 Key
:type fp: file
:param fp: File pointer to put the data into
:type headers: string
:param: headers to send when retrieving the files
:type cb: function
:param cb: a callback function that will be called to report
progre... |
374,146 | def act(self, event, *args, **kwargs):
if not isinstance(event, LifeCycleEvents):
raise ValueError(" must be an instance of LifeCycleEvents class")
method_name = "on_" + event.name
for plugin in self._plugins:
if not hasattr(plugin, method_name):
... | Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins.
*args and **kwargs will be passed directly to the plugin's hook functions
:param samtranslator.plugins.LifeCycleEvents event: Event to act upon
:return: Nothing
:raises ValueE... |
374,147 | def estimate_maximum_read_length(fastq_file, quality_format="fastq-sanger",
nreads=1000):
in_handle = SeqIO.parse(open_fastq(fastq_file), quality_format)
lengths = []
for _ in range(nreads):
try:
lengths.append(len(next(in_handle).seq))
excep... | estimate average read length of a fastq file |
374,148 | def set_attribute(self, element, attribute, value):
self.browser.execute_script( % (
attribute, self.__type2js(value=value)), element) | :Description: Modify the given attribute of the target element.
:param element: Element for browser instance to target.
:type element: WebElement
:param attribute: Attribute of target element to modify.
:type attribute: string
:param value: Value of target element's attribute to ... |
374,149 | def remove_translation(self, context_id, translation_id):
return self.context.deleteAddressTranslation(translation_id,
id=context_id) | Removes a translation entry from a tunnel context.
:param int context_id: The id-value representing the context instance.
:param int translation_id: The id-value representing the translation.
:return bool: True if translation entry removal was successful. |
374,150 | def put(self, data, block=True):
self.start(test_connection=False)
while True:
response = self._req_rep(QueuingServerMessageListener.SPACE)
if response == QueuingServerMessageListener.SPACE_AVAILABLE:
self._req_rep((QueuingServerMessageListener.DATA, dat... | If there is space it sends data to server
If no space in the queue
It returns the request in every 10 millisecond
until there will be space in the queue. |
374,151 | def createFile(
self,
fileName,
desiredAccess,
shareMode,
creationDisposition,
flagsAndAttributes,
dokanFileInfo,
):
return self.operations(, fileName) | Creates a file.
:param fileName: name of file to create
:type fileName: ctypes.c_wchar_p
:param desiredAccess: desired access flags
:type desiredAccess: ctypes.c_ulong
:param shareMode: share mode flags
:type shareMode: ctypes.c_ulong
:param creationDisposition: ... |
374,152 | def column_names(self):
if self._is_vertex_frame():
return self.__graph__.__proxy__.get_vertex_fields()
elif self._is_edge_frame():
return self.__graph__.__proxy__.get_edge_fields() | Returns the column names.
Returns
-------
out : list[string]
Column names of the SFrame. |
374,153 | def set_value(self, instance, value, parent=None):
self.resolve_base(instance)
value = self.deserialize(value, parent)
instance.values[self.alias] = value
self._trigger_changed(instance, value) | Set prop value
:param instance:
:param value:
:param parent:
:return: |
374,154 | def query_file(self, path, fetchall=False, **params):
with self.get_connection() as conn:
return conn.query_file(path, fetchall, **params) | Like Database.query, but takes a filename to load a query from. |
374,155 | def get_saved_rules(conf_file=None):
*
if _conf() and not conf_file:
conf_file = _conf()
with salt.utils.files.fopen(conf_file) as fp_:
lines = salt.utils.data.decode(fp_.readlines())
rules = []
for line in lines:
tmpline = line.strip()
if not tmpline:
co... | Return a data structure of the rules in the conf file
CLI Example:
.. code-block:: bash
salt '*' nftables.get_saved_rules |
374,156 | def _broadcast_shapes(s1, s2):
n1 = len(s1)
n2 = len(s2)
n = max(n1, n2)
res = [1] * n
for i in range(n):
if i >= n1:
c1 = 1
else:
c1 = s1[n1-1-i]
if i >= n2:
c2 = 1
else:
c2 = s2[n2-1-i]
if c1 == 1:
... | Given array shapes `s1` and `s2`, compute the shape of the array that would
result from broadcasting them together. |
374,157 | def to_type(self, dtype: type, *cols, **kwargs):
try:
allcols = self.df.columns.values
for col in cols:
if col not in allcols:
self.err("Column " + col + " not found")
return
self.df[col] = self.df[col].asty... | Convert colums values to a given type in the
main dataframe
:param dtype: a type to convert to: ex: ``str``
:type dtype: type
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \*\*kwargs: keyword arguments for ``df.astype``
:type \*\*kwar... |
374,158 | def get_formfield(model, field):
class_field = model._meta.get_field(field)
if hasattr(class_field, "field"):
formfield = class_field.field.formfield()
else:
formfield = class_field.formfield()
if isinstance(formfield, ChoiceField):
formfield.choices = class_field... | Return the formfied associate to the field of the model |
374,159 | def get_toolbar_buttons(self):
buttons = []
if self.stop_button is None:
self.stop_button = create_toolbutton(
self,
text=_("Stop"),
icon=self.stop_icon,
... | Return toolbar buttons list. |
374,160 | def shrink(self, fraction=0.85):
poly = self.polydata(True)
shrink = vtk.vtkShrinkPolyData()
shrink.SetInputData(poly)
shrink.SetShrinkFactor(fraction)
shrink.Update()
return self.updateMesh(shrink.GetOutput()) | Shrink the triangle polydata in the representation of the input mesh.
Example:
.. code-block:: python
from vtkplotter import *
pot = load(datadir + 'shapes/teapot.vtk').shrink(0.75)
s = Sphere(r=0.2).pos(0,0,-0.5)
show(pot, s)
... |
374,161 | def add_replica(self, partition_name, count=1):
try:
partition = self.cluster_topology.partitions[partition_name]
except KeyError:
raise InvalidPartitionError(
"Partition name {name} not found".format(name=partition_name),
)
if partiti... | Increase the replication-factor for a partition.
The replication-group to add to is determined as follows:
1. Find all replication-groups that have brokers not already
replicating the partition.
2. Of these, find replication-groups that have fewer than the
... |
374,162 | def eval_gpr(expr, knockouts):
if isinstance(expr, Expression):
return eval_gpr(expr.body, knockouts)
elif isinstance(expr, Name):
return expr.id not in knockouts
elif isinstance(expr, BoolOp):
op = expr.op
if isinstance(op, Or):
return any(eval_gpr(i, knocko... | evaluate compiled ast of gene_reaction_rule with knockouts
Parameters
----------
expr : Expression
The ast of the gene reaction rule
knockouts : DictList, set
Set of genes that are knocked out
Returns
-------
bool
True if the gene reaction rule is true with the give... |
374,163 | def _is_valid_datatype(datatype_instance):
global _simple_type_remap
if datatype_instance in _simple_type_remap:
return True
if isinstance(datatype_instance, (Int64, Double, String, Array)):
return True
elif isinstance(datatype_instance, Dictionary):
kt = dataty... | Returns true if datatype_instance is a valid datatype object and false otherwise. |
374,164 | def twitch_receive_messages(self):
self._push_from_buffer()
result = []
while True:
try:
msg = self.s.recv(4096).decode()
except socket.error as e:
err = e.args[0]
if err == errno.EAGAIN or err == ... | Call this function to process everything received by the socket
This needs to be called frequently enough (~10s) Twitch logs off
users not replying to ping commands.
:return: list of chat messages received. Each message is a dict
with the keys ['channel', 'username', 'message'] |
374,165 | def create_from_tuple(cls, volume):
if isinstance(volume, six.string_types):
return Volume(target=volume)
elif len(volume) == 2:
return Volume(source=volume[0],
target=volume[1])
elif len(volume) == 3:
return Volume(source=vo... | Create instance from tuple.
:param volume: tuple in one one of the following forms: target | source,target | source,target,mode
:return: instance of Volume |
374,166 | def roll(self, count=0, func=sum):
if count:
return [func([die.roll() for die in self._dice]) for x in range(0, count)]
else:
return func([die.roll() for die in self._dice]) | Roll some dice!
:param count: [0] Return list of sums
:param func: [sum] Apply func to list of individual die rolls func([])
:return: A single sum or list of ``count`` sums |
374,167 | def get_tuple(nuplet, index, default=None):
if nuplet is None:
return default
try:
return nuplet[index]
except IndexError:
return default | :param tuple nuplet: A tuple
:param int index: An index
:param default: An optional default value
:return: ``nuplet[index]`` if defined, else ``default`` (possibly ``None``) |
374,168 | def _get_property_values_with_defaults(self, classname, property_values):
final_values = self.get_default_property_values(classname)
final_values.update(property_values)
return final_values | Return the property values for the class, with default values applied where needed. |
374,169 | def get_objects_from_from_queues(self):
_t0 = time.time()
had_some_objects = False
for module in self.modules_manager.get_external_instances():
queue = module.from_q
if not queue:
continue
while True:
queue_size = queue... | Get objects from "from" queues and add them.
:return: True if we got something in the queue, False otherwise.
:rtype: bool |
374,170 | def act(self):
g = get_root(self).globals
g.clog.debug()
self.stopping = False
self.stopped_ok = False
t = threading.Thread(target=stop_in_background)
t.daemon = True
t.start()
self.after(500, ... | Carries out the action associated with Stop button |
374,171 | def p_propertyDeclaration_3(p):
p[0] = CIMProperty(p[2], None, type=p[1], is_array=True,
array_size=p[3]) | propertyDeclaration_3 : dataType propertyName array '; |
374,172 | def send_feedback(self, document_id: str, feedback: List[Field]) -> dict:
return self.post_document_id(document_id, feedback) | Send feedback to the model.
This method takes care of sending feedback related to document specified by document_id.
Feedback consists of ground truth values for the document specified as a list of Field instances.
>>> from las import ApiClient
>>> api_client = ApiClient(endpoint='<api ... |
374,173 | def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
if fit_profile not in VALID_FIT_PROFILES:
msg = "`fit_profile` must be one of {}, got ".format(
VALID_FIT_PROFILES,
fit_profile)
raise ValueError(msg)
... | Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of background profile to fit:
- "offset": offset only
- "poly2o": 2D 2nd order polynomial with mixed terms
... |
374,174 | def password_attributes_max_retry(self, **kwargs):
config = ET.Element("config")
password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa")
max_retry = ET.SubElement(password_attributes, "max-retry")
max_retry.text = kwargs.pop()... | Auto Generated Code |
374,175 | def push(self, x):
if isinstance(x, Frame):
frame = x
else:
frame = Frame(x)
self.stack.append(frame)
return frame | Push an I{object} onto the stack.
@param x: An object to push.
@type x: L{Frame}
@return: The pushed frame.
@rtype: L{Frame} |
374,176 | def delete(self, session, commit=True, soft=True):
if soft:
self.time_removed = sqlalchemy.func.unix_timestamp()
else:
session.delete(self)
if commit:
session.commit() | Delete a row from the DB.
:param session: flask_sqlalchemy session object
:param commit: whether to issue the commit
:param soft: whether this is a soft delete (i.e., update time_removed) |
374,177 | def last_version():
try:
last_update, version, success = last_version._cache
except AttributeError:
last_update = 0
version = None
success = False
cache_delta = 24 * 3600 if success else 600
if (time.time() - last_update) < cache_delta:
return version
els... | Fetch the last version from pypi and return it. On successful fetch from pypi, the response
is cached 24h, on error, it is cached 10 min.
:return: the last django-cas-server version
:rtype: unicode |
374,178 | def load_tab_data(self):
for tab in self._tabs.values():
if tab.load and not tab.data_loaded:
try:
tab._data = tab.get_context_data(self.request)
except Exception:
tab._data = False
exceptions.handle... | Preload all data that for the tabs that will be displayed. |
374,179 | def disabled(name):
ret = {: name,
: True,
: {},
: }
stat = __salt__[]()
if stat:
if __opts__[]:
ret[] = None
ret[] =
return ret
ret[] = __salt__[]()
ret[] = {: True}
return ret
ret[] =
re... | Disable the RDP service |
374,180 | def assign_reads_to_database(query, database_fasta, out_path, params=None):
if params is None:
params = {}
params[] = out_path
if not in params:
raise InvalidArgumentApplicationError("Must specify which algorithm to"
" use ... | Assign a set of query sequences to a reference database
database_fasta_fp: absolute file path to the reference database
query_fasta_fp: absolute file path to query sequences
output_fp: absolute file path of the file to be output
params: dict of BWA specific parameters.
* Specify which algor... |
374,181 | def get_changes(self, checks=None, imports=None, resources=None,
task_handle=taskhandle.NullTaskHandle()):
if checks is not None:
warnings.warn(
,
DeprecationWarning, stacklevel=2)
for name, value in checks.ite... | Get the changes needed by this restructuring
`resources` can be a list of `rope.base.resources.File`\s to
apply the restructuring on. If `None`, the restructuring will
be applied to all python files.
`checks` argument has been deprecated. Use the `args` argument
of the constr... |
374,182 | def split_by_idxs(self, train_idx, valid_idx):
"Split the data between `train_idx` and `valid_idx`."
return self.split_by_list(self[train_idx], self[valid_idx]) | Split the data between `train_idx` and `valid_idx`. |
374,183 | def check_reaction_consistency(database, solver, exchange=set(),
checked=set(), zeromass=set(), weights={}):
prob = solver.create_problem()
compound_set = _non_localized_compounds(database)
mass_compounds = compound_set.difference(zeromass)
m = prob.namesp... | Check inconsistent reactions by minimizing mass residuals
Return a reaction iterable, and compound iterable. The reaction iterable
yields reaction ids and mass residuals. The compound iterable yields
compound ids and mass assignments.
Each compound is assigned a mass of at least one, and the masses ar... |
374,184 | def minkowski_distance(x, y, p=2):
from math import pow
assert len(y) == len(x)
assert len(x) >= 1
sum = 0
for i in range(len(x)):
sum += abs(x[i] - y[i]) ** p
return pow(sum, 1.0 / float(p)) | Calculates the minkowski distance between two points.
:param x: the first point
:param y: the second point
:param p: the order of the minkowski algorithm. If *p=1* it is equal
to the manhatten distance, if *p=2* it is equal to the euclidian
distance. The higher the order, the closer it conv... |
374,185 | async def connect(self, client_id, conn_string):
conn_id = self.adapter.unique_conn_id()
self._client_info(client_id)
await self.adapter.connect(conn_id, conn_string)
self._hook_connect(conn_string, conn_id, client_id) | Connect to a device on behalf of a client.
See :meth:`AbstractDeviceAdapter.connect`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will be
passed to the underlying device adapter to connect.
Raises:
... |
374,186 | def isNumber(self, value):
try:
str(value)
float(value)
return True
except ValueError:
return False | Validate whether a value is a number or not |
374,187 | def _step(self, dataset):
if dataset is None:
values = [self.f_step()]
else:
values = [self.f_step(*x) for x in dataset]
return collections.OrderedDict(
zip(self._monitor_names, np.mean(values, axis=0))) | Advance the state of the optimizer by one step.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A dataset for optimizing the model.
Returns
-------
train_monitors : dict
A dictionary mapping monitor names to values. |
374,188 | def get_centroids(self, ridx):
centroids = []
with h5py.File(self.source_file, "r") as hdf5:
for idx in ridx:
trace = "{:s}/{:s}".format(self.idx_set["sec"], str(idx))
centroids.append(hdf5[trace + "/Centroids"].value)
return numpy.concatenate... | :returns: array of centroids for the given rupture index |
374,189 | def extract_params():
uri = _get_uri_from_request(request)
http_method = request.method
headers = dict(request.headers)
if in headers:
del headers[]
if in headers:
del headers[]
if request.authorization:
headers[] = request.authorization
body =... | Extract request params. |
374,190 | def pack(self, value=None):
r
if isinstance(value, type(self)):
return value.pack()
if value is None:
value = self.value
elif in dir(value):
value = value.value
try:
return struct.pack(self._fmt, value)
excep... | r"""Pack the value as a binary representation.
Considering an example with UBInt8 class, that inherits from
GenericType:
>>> from pyof.foundation.basic_types import UBInt8
>>> objectA = UBInt8(1)
>>> objectB = 5
>>> objectA.pack()
b'\x01'
>>> objectA.pac... |
374,191 | def register(self, resource=None, **meta):
if resource is None:
def wrapper(resource):
return self.register(resource, **meta)
return wrapper
if not issubclass(resource, ResourceView):
raise AssertionError("%s not subclass of Resource... | Add resource to the API.
:param resource: Resource class for registration
:param **meta: Redefine Meta options for the resource
:return adrest.views.Resource: Generated resource. |
374,192 | def split (s, delimter, trim = True, limit = 0):
ret = []
special1 = [, , , , , ]
special2 = ["\\'
flags1 = [0, 0, 0]
flags2 = [False, False]
flags3 = False
start = 0
nlim = 0
for i, c in enumerate(s):
if c == special3:
flags3 = not flags3
elif not flags3:
if c in spec... | Split a string using a single-character delimter
@params:
`s`: the string
`delimter`: the single-character delimter
`trim`: whether to trim each part. Default: True
@examples:
```python
ret = split("'a,b',c", ",")
# ret == ["'a,b'", "c"]
# ',' inside quotes will be recognized.
```
@returns... |
374,193 | def make_unique_str(num_chars=20):
chars =
all_chars = chars + chars.upper() +
picks = list(all_chars)
return .join([choice(picks) for i in range(num_chars)]) | make a random string of characters for a temp filename |
374,194 | def create(self, file_or_path, **kwargs):
opened = False
if isinstance(file_or_path, str_type()):
file_or_path = open(file_or_path, )
opened = True
elif not getattr(file_or_path, , False):
raise Exception("A file or path to a file is required for thi... | Creates an upload for the given file or path. |
374,195 | def data_worker(**kwargs):
if kwargs is not None:
if "function" in kwargs:
function = kwargs["function"]
else:
Exception("Invalid arguments, no function specified")
if "input" in kwargs:
input_queue = kwargs["input"]
else:
Exceptio... | Function to be spawned concurrently,
consume data keys from input queue, and push the resulting dataframes to output map |
374,196 | def add_repo(self, repo):
url = self._build_url(, repo, base_url=self._api)
return self._boolean(self._put(url), 204, 404) | Add ``repo`` to this team.
:param str repo: (required), form: 'user/repo'
:returns: bool |
374,197 | def polfit_residuals_with_sigma_rejection(
x, y, deg, times_sigma_reject,
color=, size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=None,
geometry=(0,0,640,480),
debugplot=0):
if type(x) is not np.ndarray:
raise Valu... | Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted... |
374,198 | def _get_devices_by_activation_state(self, state):
devices_with_state = []
for device in self.devices:
act = device.tm.cm.devices.device.load(
name=get_device_info(device).name,
partition=self.partition
)
if act.failoverState ... | Get a list of bigips by activation statue.
:param state: str -- state to filter the returned list of devices
:returns: list -- list of devices that are in the given state |
374,199 | def _compute_mean(self, C, f0, f1, f2, SC, mag, rrup, idxs, mean,
scale_fac):
mean[idxs] = (C[] +
C[] * mag +
C[] * (mag ** 2) +
(C[] + C[] * mag) * f1[idxs] +
(C[] + C[] * mag) * f2[idxs] +
... | Compute mean value (for a set of indexes) without site amplification
terms. This is equation (5), p. 2191, without S term. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.