Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
378,400 | def visit_BitVecExtract(self, expression, *operands):
op = expression.operands[0]
begining = expression.begining
end = expression.end
size = end - begining + 1
if begining == 0 and end + 1 == op.size:
return op
elif isinstance(op, BitVecExtr... | extract(sizeof(a), 0)(a) ==> a
extract(16, 0)( concat(a,b,c,d) ) => concat(c, d)
extract(m,M)(and/or/xor a b ) => and/or/xor((extract(m,M) a) (extract(m,M) a) |
378,401 | def get_billable_items(self):
items = []
for obj in self.context.getBillableItems():
if self.is_profile(obj):
items.append({
"obj": obj,
"title": obj.Title(),
"vat": obj.getAnalysisProfileVAT(),
... | Return a list of billable items |
378,402 | def filter(self, index):
return Datamat(categories=self._categories, datamat=self, index=index) | Filters a datamat by different aspects.
This function is a device to filter the datamat by certain logical
conditions. It takes as input a logical array (contains only True
or False for every datapoint) and kicks out all datapoints for which
the array says False. The logical array can c... |
378,403 | def get_order_parameters(self, structure, n, indices_neighs=None, \
tol=0.0, target_spec=None):
if n < 0:
raise ValueError("Site index smaller zero!")
if n >= len(structure):
raise ValueError("Site index beyond maximum!")
i... | Compute all order parameters of site n.
Args:
structure (Structure): input structure.
n (int): index of site in input structure,
for which OPs are to be
calculated. Note that we do not use the sites iterator
here, but directly access site... |
378,404 | def filter(cls, filters, iterable):
if isinstance(filters, Filter):
filters = [filters]
for filter in filters:
iterable = filter.generator(iterable)
return iterable | Returns the elements in `iterable` that pass given `filters` |
378,405 | def split_unescape(s, delim, escape=, unescape=True):
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
if not unescape:
current.append(escape)
current.append(next(itr))
excep... | >>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=False)
['foo$$', 'bar']
>>> s... |
378,406 | def remotesByConnected(self):
conns, disconns = [], []
for r in self.remotes.values():
array = conns if self.isRemoteConnected(r) else disconns
array.append(r)
return conns, disconns | Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes) |
378,407 | def versions(self):
print % (color.LightBlue, self.version, color.Normal)
print self.workbench.help() | Announce Versions of CLI and Server
Args: None
Returns:
The running versions of both the CLI and the Workbench Server |
378,408 | def __create_dynamic_connections(self):
if (self._stimulus is None):
raise NameError("Stimulus should initialed before creation of the dynamic connections in the network.");
self._dynamic_coupling = [ [0] * self._num_osc for i in range(self._num_osc)];
... | !
@brief Create dynamic connection in line with input stimulus. |
378,409 | def _call_scope(self, scope, *args, **kwargs):
result = getattr(self._model, scope)(self, *args, **kwargs)
return result or self | Call the given model scope.
:param scope: The scope to call
:type scope: str |
378,410 | def deps_from_pyp_format(requires, runtime=True):
parsed = []
logger.debug("Dependencies from setup.py: {0} runtime: {1}.".format(
requires, runtime))
for req in requires:
try:
parsed.append(Requirement.parse(req))
except ValueError:
logger.warn("Unparsa... | Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencies (see dependency_to_rpm for format). |
378,411 | def function(self, x, y, amp, R_sersic, n_sersic, e1, e2, center_x=0, center_y=0):
R_sersic = np.maximum(0, R_sersic)
phi_G, q = param_util.ellipticity2phi_q(e1, e2)
x_shift = x - center_x
y_shift = y - center_y
cos_phi = np.cos(phi_G... | returns Sersic profile |
378,412 | def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]:
color = lib.TCOD_image_get_pixel(self.image_c, x, y)
return color.r, color.g, color.b | Get the color of a pixel in this Image.
Args:
x (int): X pixel of the Image. Starting from the left at 0.
y (int): Y pixel of the Image. Starting from the top at 0.
Returns:
Tuple[int, int, int]:
An (r, g, b) tuple containing the pixels color value... |
378,413 | def add(self, interval):
if interval in self:
return
if interval.is_null():
raise ValueError(
"IntervalTree: Null Interval objects not allowed in IntervalTree:"
" {0}".format(interval)
)
if not self.top_node:
... | Adds an interval to the tree, if not already present.
Completes in O(log n) time. |
378,414 | def sanitize_for_archive(url, headers, payload):
if MeetupClient.PKEY in payload:
payload.pop(MeetupClient.PKEY)
if MeetupClient.PSIGN in payload:
payload.pop(MeetupClient.PSIGN)
return url, headers, payload | Sanitize payload of a HTTP request by removing the token information
before storing/retrieving archived items
:param: url: HTTP url request
:param: headers: HTTP headers request
:param: payload: HTTP payload request
:returns url, headers and the sanitized payload |
378,415 | def save_config(self, cmd="write memory", confirm=False, confirm_response=""):
return super(UbiquitiEdgeSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | Saves configuration. |
378,416 | def get_grade_system_form(self, *args, **kwargs):
if isinstance(args[-1], list) or in kwargs:
return self.get_grade_system_form_for_create(*args, **kwargs)
else:
return self.get_grade_system_form_for_update(*args, **kwargs) | Pass through to provider GradeSystemAdminSession.get_grade_system_form_for_update |
378,417 | def AnalizarXml(self, xml=""):
"Analiza un mensaje XML (por defecto el ticket de acceso)"
try:
if not xml or xml==:
xml = self.XmlResponse
elif xml==:
xml = self.XmlRequest
self.xml = SimpleXMLElement(xml)
return True
... | Analiza un mensaje XML (por defecto el ticket de acceso) |
378,418 | def delete_mount_cache(real_name):
*
cache = salt.utils.mount.read_cache(__opts__)
if cache:
if in cache:
if real_name in cache[]:
del cache[][real_name]
cache_write = salt.utils.mount.write_cache(cache, __opts__)
if not cache_write:
... | .. versionadded:: 2018.3.0
Provide information if the path is mounted
CLI Example:
.. code-block:: bash
salt '*' mount.delete_mount_cache /mnt/share |
378,419 | def infer_sedes(obj):
if is_sedes(obj.__class__):
return obj.__class__
elif not isinstance(obj, bool) and isinstance(obj, int) and obj >= 0:
return big_endian_int
elif BinaryClass.is_valid_type(obj):
return binary
elif not isinstance(obj, str) and isinstance(obj, collections... | Try to find a sedes objects suitable for a given Python object.
The sedes objects considered are `obj`'s class, `big_endian_int` and
`binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be
constructed recursively.
:param obj: the python object for which to find a sedes object
:raises: ... |
378,420 | def teardown_cluster(config_file, yes, workers_only, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
validate_config(config)
config = fillout_defaults(config)
confirm("This will d... | Destroys all nodes of a Ray cluster described by a config json. |
378,421 | def freeze(obj):
if isinstance(obj, collections.Mapping):
return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)})
elif isinstance(obj, list):
return FrozenList([freeze(e) for e in obj])
else:
return obj | Transform tree of dict and list in read-only
data structure.
dict instances are transformed to FrozenDict, lists
in FrozenList. |
378,422 | def lucas_gas(T, Tc, Pc, Zc, MW, dipole=0, CASRN=None):
r
Tr = T/Tc
xi = 0.176*(Tc/MW**3/(Pc/1E5)**4)**(1/6.)
if dipole is None:
dipole = 0
dipoler = 52.46*dipole**2*(Pc/1E5)/Tc**2
if dipoler < 0.022:
Fp = 1
elif 0.022 <= dipoler < 0.075:
Fp = 1 + 30.55*(0.292 - Z... | r'''Estimate the viscosity of a gas using an emperical
formula developed in several sources, but as discussed in [1]_ as the
original sources are in German or merely personal communications with the
authors of [1]_.
.. math::
\eta = \left[0.807T_r^{0.618}-0.357\exp(-0.449T_r) + 0.340\exp(-4.05... |
378,423 | def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
if len(mode) > 1 or mode not in "rw":
raise ValueError("mode must be or ")
try:
import gzip
gzip.GzipFile
except (ImportError, AttributeError):
raise CompressionEr... | Open gzip compressed tar archive name for reading or writing.
Appending is not allowed. |
378,424 | def gdaOnes(shape, dtype, numGhosts=1):
res = GhostedDistArray(shape, dtype)
res.setNumberOfGhosts(numGhosts)
res[:] = 1
return res | ghosted distributed array one constructor
@param shape the shape of the array
@param dtype the numpy data type
@param numGhosts the number of ghosts (>= 0) |
378,425 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.text is not None:
_dict[] = self.text
if hasattr(self, ) and self.score is not None:
_dict[] = self.score
return _dict | Return a json dictionary representing this model. |
378,426 | def update_one_time_key_counts(self, counts):
self.one_time_keys_manager.server_counts = counts
if self.one_time_keys_manager.should_upload():
logger.info()
self.upload_one_time_keys() | Update data on one-time keys count and upload new ones if necessary.
Args:
counts (dict): Counts of keys currently on the HS for each key type. |
378,427 | def export(export_path, vocabulary, embeddings, num_oov_buckets,
preprocess_text):
tmpdir = tempfile.mkdtemp()
vocabulary_file = os.path.join(tmpdir, "tokens.txt")
with tf.gfile.GFile(vocabulary_file, "w") as f:
f.write("\n".join(vocabulary))
vocab_size = len(vocabulary)
embeddings_dim = ... | Exports a TF-Hub module that performs embedding lookups.
Args:
export_path: Location to export the module.
vocabulary: List of the N tokens in the vocabulary.
embeddings: Numpy array of shape [N+K,M] the first N rows are the
M dimensional embeddings for the respective tokens and the next K
ro... |
378,428 | def add_data(self, data, table, delimiter=, bands=, clean_up=True, rename_columns={}, column_fill={}, verbose=False):
entry, del_records = data, []
if isinstance(data, str) and os.path.isfile(data):
data = ii.read(data, delimiter=delimiter)
elif ... | Adds data to the specified database table. Column names must match table fields to insert,
however order and completeness don't matter.
Parameters
----------
data: str, array-like, astropy.table.Table
The path to an ascii file, array-like object, or table. The first ... |
378,429 | def new_with_array(self, array):
arguments = vars(self)
arguments.update({"array": array})
if in arguments:
arguments.pop("centre")
return self.__class__(**arguments) | Parameters
----------
array: ndarray
An ndarray
Returns
-------
new_array: ScaledSquarePixelArray
A new instance of this class that shares all of this instances attributes with a new ndarray. |
378,430 | def _read_requirements(metadata, extras):
extras = extras or ()
requirements = []
for entry in metadata.run_requires:
if isinstance(entry, six.text_type):
entry = {"requires": [entry]}
extra = None
else:
extra = entry.get("extra")
if extra is ... | Read wheel metadata to know what it depends on.
The `run_requires` attribute contains a list of dict or str specifying
requirements. For dicts, it may contain an "extra" key to specify these
requirements are for a specific extra. Unfortunately, not all fields are
specificed like this (I don't know why)... |
378,431 | def business_match_query(self, **kwargs):
if not kwargs.get():
raise ValueError()
if not kwargs.get():
raise ValueError()
if not kwargs.get():
raise ValueError()
if not kwargs.get():
raise ValueError()
if not kwargs.get... | Query the Yelp Business Match API.
documentation: https://www.yelp.com/developers/documentation/v3/business_match
required parameters:
* name - business name
* city
* state
* country
* address1
... |
378,432 | def return_multiple_convert_numpy_base(dbpath, folder_path, set_object, start_id, end_id, converter, add_args=None):
engine = create_engine( + dbpath)
session_cl = sessionmaker(bind=engine)
session = session_cl()
tmp_object = session.query(set_object).get(start_id)
if add_args is None:
... | Generic function which converts several objects, with ids in the range (start_id, end_id)
into a 2d numpy array and returns the array, the conversion is done by the 'converter' function
Parameters
----------
dbpath : string, path to SQLite database file
folder_path : string, path to folder where th... |
378,433 | def enforce(self, rule, target, creds, exc=None, *args, **kwargs):
self.load_rules()
if isinstance(rule, checks.BaseCheck):
result = rule(target, creds, self, rule)
elif not self.rules:
result = False
if self.raise_error and not result... | Checks authorization of a rule against the target and credentials. |
378,434 | def _regex_flags_from_bits(self, bits):
flags =
return .join(flags[i - 1] if (1 << i) & bits else for i in range(1, len(flags) + 1)) | Return the textual equivalent of numerically encoded regex flags. |
378,435 | def commit_input_persist_id(self, **kwargs):
config = ET.Element("config")
commit = ET.Element("commit")
config = commit
input = ET.SubElement(commit, "input")
persist_id = ET.SubElement(input, "persist-id")
persist_id.text = kwargs.pop()
callback = kwar... | Auto Generated Code |
378,436 | def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
hourly, monthly, tag, columns, limit):
vsi = SoftLayer.VSManager(env.client)
guests = vsi.list_instances(hourly=hourly,
monthly=monthly,
hostname=hostname,
... | List virtual servers. |
378,437 | def reload_core(host=None, core_name=None):
hostsuccessdataerrorswarnings*successdataerrorswarnings
ret = _get_return_dict()
if not _check_for_cores():
err = []
return ret.update({: False, : err})
if _get_none_or_value(core_name) is None and _check_for_cores():
success = True
... | MULTI-CORE HOSTS ONLY
Load a new core from the same configuration as an existing registered core.
While the "new" core is initializing, the "old" one will continue to accept
requests. Once it has finished, all new request will go to the "new" core,
and the "old" core will be unloaded.
host : str (N... |
378,438 | def grouping_val(self):
grouping = self.grouping
if grouping is None:
return ST_Grouping.CLUSTERED
val = grouping.val
if val is None:
return ST_Grouping.CLUSTERED
return val | Return the value of the ``./c:grouping{val=?}`` attribute, taking
defaults into account when items are not present. |
378,439 | def get_social_accounts(user):
accounts = {}
for account in user.socialaccount_set.all().iterator():
providers = accounts.setdefault(account.provider, [])
providers.append(account)
return accounts | {% get_social_accounts user as accounts %}
Then:
{{accounts.twitter}} -- a list of connected Twitter accounts
{{accounts.twitter.0}} -- the first Twitter account
{% if accounts %} -- if there is at least one social account |
378,440 | def pages(self):
pages = []
for har_dict in self.har_data:
har_parser = HarParser(har_data=har_dict)
if self.page_id:
for page in har_parser.pages:
if page.page_id == self.page_id:
pages.append(page)
... | The aggregate pages of all the parser objects. |
378,441 | def __netjson_channel_width(self, radio):
htmode = radio.pop()
if htmode == :
return 20
channel_width = htmode.replace(, ).replace(, )
if in channel_width or in channel_width:
radio[] = htmode
channel_width = channel_width[0:-1]
... | determines NetJSON channel_width radio attribute |
378,442 | def update(self):
if self.input_method == :
if self._thread is None:
thread_is_running = False
else:
thread_is_running = self._thread.isAlive()
if self.timer_ports.finished() and not thread_is_run... | Update the ports list. |
378,443 | def unwrap(tensor):
while isinstance(tensor, (PrettyTensor, Loss)):
tensor = tensor.tensor
return tensor | Returns the underlying tensor if tensor is wrapped or tensor.
Args:
tensor: The tensor to unwrap.
Returns:
Tensor or if it is a pretty tensor, the unwrapped version.
Raises:
ValueError: if tensor holds a sequence. |
378,444 | def structure_to_abivars(structure, **kwargs):
if not structure.is_ordered:
raise ValueError()
types_of_specie = structure.types_of_specie
natom = structure.num_sites
znucl_type = [specie.number for specie in types_of_specie]
znucl_atoms = structure.atomic_numbers
typat = np.zero... | Receives a structure and returns a dictionary with the ABINIT variables. |
378,445 | def snmp_server_group_write(self, **kwargs):
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
group = ET.SubElement(snmp_server, "group")
group_name_key = ET.SubElement(group, "group-name")
group_... | Auto Generated Code |
378,446 | def controlled_by(self, *control_qubits: Qid) -> :
from cirq.ops import ControlledOperation
if control_qubits is None or len(control_qubits) is 0:
raise ValueError(
"Can't get controlled operation without control qubit. Op: {}"
.format(repr(s... | Returns a controlled version of this operation.
Args:
control_qubits: Qubits to control the operation by. Required. |
378,447 | def addEvent(self, event, fd, action):
self._events[event] = (fd, action) | Add a new win32 event to the event loop. |
378,448 | def as_dict(self, **extra):
return [self._construct_email(email, **extra) for email in self.emails] | Converts all available emails to dictionaries.
:return: List of dictionaries. |
378,449 | def remove(self, container, force=True, volumes=True):
super().remove(container, force=force, v=volumes) | Remove a container.
:param container: The container to remove.
:param force:
Whether to force the removal of the container, even if it is
running. Note that this defaults to True, unlike the Docker
default.
:param volumes:
Whether to remove any vo... |
378,450 | def _write_widget(self, val):
self._itsme = True
try:
setter = self._wid_info[self._wid][1]
wtype = self._wid_info[self._wid][2]
if setter:
if wtype is not None:
setter(self._wid, self._cast_value(val, wtype))
... | Writes value into the widget. If specified, user setter
is invoked. |
378,451 | def delete_channel_cb(self, viewer, channel):
chname = channel.name
del self.name_dict[chname]
un_hilite_set = set([])
for path in self._hl_path:
if path[0] == chname:
un_hilite_set.add(path)
self._hl_path -= un_hilite_set
i... | Called when a channel is deleted from the main interface.
Parameter is a channel (a Channel object). |
378,452 | def set_flair(self, subreddit, item, flair_text=, flair_css_class=):
data = {: six.text_type(subreddit),
: flair_text or ,
: flair_css_class or }
if isinstance(item, objects.Submission):
data[] = item.fullname
evict = item.permalink
... | Set flair for the user in the given subreddit.
`item` can be a string, Redditor object, or Submission object.
If `item` is a string it will be treated as the name of a Redditor.
This method can only be called by a subreddit moderator with flair
permissions. To set flair on yourself or ... |
378,453 | def replace_blocks(self, blocks):
start = 0
bulk_insert = self.bulk_insert
blocks_len = len(blocks)
select =
query = \
execute = self.cursor.execute
while start < blocks_len:
rows = blocks[start:start+bulk_insert]
pa... | Replace multiple blocks. blocks must be a list of tuples where
each tuple consists of (namespace, offset, key, data, flags) |
378,454 | def install(self, goal=None, first=False, replace=False, before=None, after=None):
goal = Goal.by_name(goal or self.name)
goal.install(self, first, replace, before, after)
return goal | Install the task in the specified goal (or a new goal with the same name as the task).
The placement of the task in the execution list of the goal defaults to the end but can be
:rtype : object
influence by specifying exactly one of the following arguments:
:API: public
:param first: Places this ... |
378,455 | def update_PCA_box(self):
if self.s in list(self.pmag_results_data[].keys()):
if self.current_fit:
tmin = self.current_fit.tmin
tmax = self.current_fit.tmax
calculation_type = self.current_fit.PCA_type
else:
calcul... | updates PCA box with current fit's PCA type |
378,456 | def set_source(self, propname, pores):
r
locs = self.tomask(pores=pores)
if (not np.all(np.isnan(self[][locs]))) or \
(not np.all(np.isnan(self[][locs]))):
raise Exception( +
)
self[propname] = locs
self.settings[].append(propna... | r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source term should be applied
Notes
--... |
378,457 | def _update_limits_from_api(self):
self.connect()
logger.debug("Querying ELB DescribeAccountLimits for limits")
attribs = self.conn.describe_account_limits()
name_to_limits = {
: ,
: ,
:
}
for attrib in attribs... | Query ELB's DescribeAccountLimits API action, and update limits
with the quotas returned. Updates ``self.limits``. |
378,458 | def _aggregrate_scores(its,tss,num_sentences):
final = []
for i,el in enumerate(its):
for j, le in enumerate(tss):
if el[2] == le[2]:
assert el[1] == le[1]
final.append((el[1],i+j,el[2]))
_final = sorted(final, key = lambda tup: tup[1])[:num_sentences... | rerank the two vectors by
min aggregrate rank, reorder |
378,459 | def allowed_info_messages(*info_messages):
def wrapper(func):
setattr(func, ALLOWED_INFO_MESSAGES, info_messages)
return func
return wrapper | Decorator ignoring defined info messages at the end of test method. As
param use what
:py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages`
returns.
.. versionadded:: 2.0 |
378,460 | def obfuscate(cls, idStr):
return unicode(base64.urlsafe_b64encode(
idStr.encode()).replace(b, b)) | Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures. |
378,461 | def get_extension_classes():
res = [SyntaxHighlightingExtension, SearchExtension, TagExtension,
DevhelpExtension, LicenseExtension, GitUploadExtension,
EditOnGitHubExtension]
if sys.version_info[1] >= 5:
res += [DBusExtension]
try:
from hotdoc.extensions.c.c_exte... | Hotdoc's setuptools entry point |
378,462 | def magic_file(filename):
head, foot = _file_details(filename)
if not head:
raise ValueError("Input was empty")
try:
info = _identify_all(head, foot, ext_from_filename(filename))
except PureError:
info = []
info.sort(key=lambda x: x.confidence, reverse=True)
return i... | Returns tuple of (num_of_matches, array_of_matches)
arranged highest confidence match first.
:param filename: path to file
:return: list of possible matches, highest confidence first |
378,463 | def file_to_md5(filename, block_size=8192):
md5 = hashlib.md5()
with open(filename, ) as f:
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest() | Calculate the md5 hash of a file. Memory-friendly solution,
it reads the file piece by piece. See stackoverflow.com/questions/1131220/
:param filename: filename to convert
:param block_size: size of block
:return: MD5 hash of file content |
378,464 | def _map_trajectory(self):
self.trajectory_map = {}
with open(self.filepath, ) as trajectory_file:
with closing(
mmap(
trajectory_file.fileno(), 0,
access=ACCESS_READ)) as mapped_file:
progress = 0
... | Return filepath as a class attribute |
378,465 | def _GetDenseDimensions(list_of_lists):
if not isinstance(list_of_lists, (list, tuple)):
return []
elif not list_of_lists:
return [0]
else:
return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0]) | Returns the inferred dense dimensions of a list of lists. |
378,466 | def wrap_class(cls, error_threshold=None):
methods = inspect.getmembers(cls, inspect.ismethod) + inspect.getmembers(cls, inspect.isfunction)
for method_name, method in methods:
wrapped_method = flawless.client.client._wrap_function_with_error_decorator(
method if not im_self(method) els... | Wraps a class with reporting to errors backend by decorating each function of the class.
Decorators are injected under the classmethod decorator if they exist. |
378,467 | def run_backdoor(address, namespace=None):
log.info("starting on %r" % (address,))
serversock = io.Socket()
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind(address)
serversock.listen(socket.SOMAXCONN)
while 1:
clientsock, address = serversock.accept... | start a server that runs python interpreters on connections made to it
.. note::
this function blocks effectively indefinitely -- it runs the listening
socket loop in the current greenlet. to keep the current greenlet free,
:func:`schedule<greenhouse.scheduler.schedule>` this function.
... |
378,468 | def get_scanner(self, skey):
if skey and self[] == :
skey = skey.lower()
return self._gsm().get(skey) | Find the appropriate scanner given a key (usually a file suffix). |
378,469 | def assign_global_ip(self, global_ip_id, target):
return self.client[].route(
target, id=global_ip_id) | Assigns a global IP address to a specified target.
:param int global_ip_id: The ID of the global IP being assigned
:param string target: The IP address to assign |
378,470 | def _merge_array(lhs, rhs, type_):
element_type = type_.array_element_type
if element_type.code in _UNMERGEABLE_TYPES:
lhs.list_value.values.extend(rhs.list_value.values)
return lhs
lhs, rhs = list(lhs.list_value.values), list(rhs.list_value.values)
if not len(lh... | Helper for '_merge_by_type'. |
378,471 | def _EncodeUnknownFields(message):
source = _UNRECOGNIZED_FIELD_MAPPINGS.get(type(message))
if source is None:
return message
result = _CopyProtoMessageVanillaProtoJson(message)
pairs_field = message.field_by_name(source)
if not isinstance(pairs_field, messages.MessageField):
... | Remap unknown fields in message out of message.source. |
378,472 | def objects_for_push_notification(notification):
notification_el = ElementTree.fromstring(notification)
objects = {: notification_el.tag}
for child_el in notification_el:
tag = child_el.tag
res = Resource.value_for_element(child_el)
objects[tag] = res
return objects | Decode a push notification with the given body XML.
Returns a dictionary containing the constituent objects of the push
notification. The kind of push notification is given in the ``"type"``
member of the returned dictionary. |
378,473 | def encode_bbox_target(boxes, anchors):
anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1)
waha = anchors_x2y2 - anchors_x1y1
xaya = (anchors_x2y2 + anchors_x1y1) * 0.5
boxes_x1y1x2y2 = tf.reshape(boxes, (-1, 2, 2))
boxes_x... | Args:
boxes: (..., 4), float32
anchors: (..., 4), float32
Returns:
box_encoded: (..., 4), float32 with the same shape. |
378,474 | def delete_tracking_beacon(self, tracking_beacons_id, **data):
return self.delete("/tracking_beacons/{0}/".format(tracking_beacons_id), data=data) | DELETE /tracking_beacons/:tracking_beacons_id/
Delete the :format:`tracking_beacons` with the specified :tracking_beacons_id. |
378,475 | def prepare_destruction(self, recursive=True):
if recursive:
for scoped_variable in self.scoped_variables:
scoped_variable.prepare_destruction()
for connection in self.transitions[:] + self.data_flows[:]:
connection.prepare_destruction()
... | Prepares the model for destruction
Recursively un-registers all observers and removes references to child models. Extends the destroy method of
the base class by child elements of a container state. |
378,476 | def flatten(l):
return sum(map(flatten, l), []) \
if isinstance(l, list) or isinstance(l, tuple) else [l] | Flatten a nested list. |
378,477 | def com(self):
if self._com is None:
self._com = np.mean(self.pmts.pos, axis=0)
return self._com | Center of mass, calculated from the mean of the PMT positions |
378,478 | def _populate_trace(self, graph: TraceGraph, trace_frame_ids: List[int]) -> None:
while len(trace_frame_ids) > 0:
trace_frame_id = trace_frame_ids.pop()
if trace_frame_id in self._visited_trace_frame_ids:
continue
trace_frame = graph._trace_frames[tr... | Populates (from the given trace graph) the forward and backward
traces reachable from the given traces (including input trace frames).
Make sure to respect trace kind in successors |
378,479 | def poll(self, event, timeout=None):
return self.llc.poll(self._tco, event, timeout) | Wait for a socket event. Posssible *event* values are the strings
"recv", "send" and "acks". Whent the timeout is present and
not :const:`None`, it should be a floating point number
specifying the timeout for the operation in seconds (or
fractions thereof). For "recv" or "send" the :meth... |
378,480 | def parse_data_directories(self, directories=None,
forwarded_exports_only=False,
import_dllnames_only=False):
directory_parsing = (
(, self.parse_import_directory),
(, self.parse_export_directory),
(, sel... | Parse and process the PE file's data directories.
If the optional argument 'directories' is given, only
the directories at the specified indexes will be parsed.
Such functionality allows parsing of areas of interest
without the burden of having to parse all others.
The directori... |
378,481 | def serializeEc(P, compress=True):
return _serialize(P, compress, librelic.ec_size_bin_abi,
librelic.ec_write_bin_abi) | Generates a compact binary version of this point. |
378,482 | def LAST(COND, N1, N2):
N2 = 1 if N2 == 0 else N2
assert N2 > 0
assert N1 > N2
return COND.iloc[-N1:-N2].all() | 表达持续性
从前N1日到前N2日一直满足COND条件
Arguments:
COND {[type]} -- [description]
N1 {[type]} -- [description]
N2 {[type]} -- [description] |
378,483 | def generation(self):
if not self.parent:
return 0
elif self.parent.is_dict:
return 1 + self.parent.generation
else:
return self.parent.generation | Returns the number of ancestors that are dictionaries |
378,484 | def add(self, item):
if self._unique:
key = self._key(item) if self._key else item
if key in self._seen:
return
self._seen.add(key)
self._work.append(item)
self._count += 1 | Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``, or a ``key``
callab... |
378,485 | def once(ctx, name):
from kibitzr.app import Application
app = Application()
sys.exit(app.run(once=True, log_level=ctx.obj[], names=name)) | Run kibitzr checks once and exit |
378,486 | def min(cls, x: , y: ) -> :
return cls._binary_op(x, y, tf.minimum, tf.float32) | Returns a TensorFluent for the minimum function.
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the minimum function. |
378,487 | def center_mass_exp(interval, scale=1.0):
assert isinstance(interval, tuple),
assert len(interval) == 2,
(interval_left, interval_right) = interval
assert interval_left >= 0,
assert interval_right > interval_left, \
assert scale > 0,
if interval_right < np.inf:
ret... | Calculate the center of mass of negative exponential distribution
p(x) = exp(-x / scale) / scale
in the interval of (interval_left, interval_right).
scale is the same scale parameter as scipy.stats.expon.pdf
Parameters
----------
interval: size 2 tuple, float
interval must ... |
378,488 | def decode(self, encoding=, errors=):
from future.types.newstr import newstr
if errors == :
from future.utils.surrogateescape import register_surrogateescape
register_surrogateescape()
return newstr(super(newbytes, self).decode(encoding, erro... | Returns a newstr (i.e. unicode subclass)
Decode B using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeDecodeError. Other possible values are ... |
378,489 | def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]):
r = self.verify_param(param, must)
if not r.is_succ():
return r
h = CommonResultHandler(lambda rsp: {VERSION_V1:rsp[SMS_REPLY] if SMS_REPLY in rsp else None, VERSION_V2:rsp}[self.version()]... | 查回复的短信
参数名 类型 是否必须 描述 示例
apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526
start_time String 是 短信回复开始时间 2013-08-11 00:00:00
end_time String 是 短信回复结束时间 2013-08-12 00:00:00
page_num Integer 是 页码,默认值为1 1
page_size Integer 是 每页个数,最大100个 20
mobile String... |
378,490 | def get_model_agents(self):
model_stmts = self.get_statements()
agents = []
for stmt in model_stmts:
for a in stmt.agent_list():
if a is not None:
agents.append(a)
return agents | Return a list of all Agents from all Statements.
Returns
-------
agents : list[indra.statements.Agent]
A list of Agents that are in the model. |
378,491 | def enqueue(self, s):
self._parts.append(s)
self._len += len(s) | Append `s` to the queue.
Equivalent to::
queue += s
if `queue` where a regular string. |
378,492 | def configure_upload(self, ns, definition):
upload = self.create_upload_func(ns, definition, ns.collection_path, Operation.Upload)
upload.__doc__ = "Upload a {}".format(ns.subject_name) | Register an upload endpoint.
The definition's func should be an upload function, which must:
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form (formname, tempfilepath, filename)
- optionally return a resource
:param ns: the namespac... |
378,493 | def create_role(self, name):
models = self.session.router
return models.role.new(name=name, owner=self) | Create a new :class:`Role` owned by this :class:`Subject` |
378,494 | def get_abs_and_rel_paths(self, root_path, file_name, input_dir):
relative_dir = root_path.replace(input_dir, )
return os.path.join(root_path, file_name), relative_dir + + file_name | Return absolute and relative path for file
:type root_path: str|unicode
:type file_name: str|unicode
:type input_dir: str|unicode
:rtype: tuple |
378,495 | def download_post(self, post: Post, target: str) -> bool:
dirname = _PostPathFormatter(post).format(self.dirname_pattern, target=target)
filename = dirname + + self.format_filename(post, target=target)
os.makedirs(os.path.dirname(filename), exist_ok=True)
downloaded ... | Download everything associated with one instagram post node, i.e. picture, caption and video.
:param post: Post to download.
:param target: Target name, i.e. profile name, #hashtag, :feed; for filename.
:return: True if something was downloaded, False otherwise, i.e. file was already there |
378,496 | def get_orm_columns(cls: Type) -> List[Column]:
mapper = inspect(cls)
colmap = mapper.columns
return colmap.values() | Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names. |
378,497 | def p_member_expr(self, p):
if len(p) == 2:
p[0] = p[1]
elif p[1] == :
p[0] = ast.NewExpr(p[2], p[3])
elif p[2] == :
p[0] = ast.DotAccessor(p[1], p[3])
else:
p[0] = ast.BracketAccessor(p[1], p[3]) | member_expr : primary_expr
| function_expr
| member_expr LBRACKET expr RBRACKET
| member_expr PERIOD identifier
| NEW member_expr arguments |
378,498 | def update(cls, name=None, public_nick_name=None, avatar_uuid=None,
address_main=None, address_postal=None, language=None,
region=None, country=None, ubo=None,
chamber_of_commerce_number=None, legal_form=None, status=None,
sub_status=None, session_timeout=None... | Modify a specific company's data.
:type user_company_id: int
:param name: The company name.
:type name: str
:param public_nick_name: The company's nick name.
:type public_nick_name: str
:param avatar_uuid: The public UUID of the company's avatar.
:type avatar_uui... |
378,499 | def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR):
if value is None:
value = self.get_default()
if value is None:
raise ValueError("Cannot pack a None value.")
if not nocheck:
self.check(value, major)
return self.encode(value, ma... | Return the value formatted as a KATCP parameter.
Parameters
----------
value : object
The value to pack.
nocheck : bool, optional
Whether to check that the value is valid before
packing it.
major : int, optional
Major version of KA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.