Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
375,200 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.dialog_node is not None:
_dict[] = self.dialog_node
if hasattr(self, ) and self.description is not None:
_dict[] = self.description
if hasattr(self, ) and self.conditions is not None:
... | Return a json dictionary representing this model. |
375,201 | def aggregate_weights(weights, drop_date=False):
dwts = pd.DataFrame(weights,
columns=["generic", "contract", "weight", "date"])
dwts = dwts.pivot_table(index=[, ],
columns=[], values=, fill_value=0)
dwts = dwts.astype(float)
dwts = dwts.sort_inde... | Transforms list of tuples of weights into pandas.DataFrame of weights.
Parameters:
-----------
weights: list
A list of tuples consisting of the generic instrument name,
the tradeable contract as a string, the weight on this contract as a
float and the date as a pandas.Timestamp.
... |
375,202 | def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs):
path = kwargs.get(, None)
if quiet:
log.warning(" argument is being deprecated."
)
ret = {: , : True}
if host is None:
ret[] =
ret[] = False
return ret
if isinstan... | Initialize a new container
.. code-block:: bash
salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[template=lxc_template_name] [clone=original name] \\
[profile=lxc_profile] [network_prof... |
375,203 | def sources_to_nr_vars(sources):
sources = default_sources(**sources)
try:
return OrderedDict((SOURCE_VAR_TYPES[name], nr)
for name, nr in sources.iteritems())
except KeyError as e:
raise KeyError((
) % (e, SOURCE_VAR_TYPES.keys())) | Converts a source type to number of sources mapping into
a source numbering variable to number of sources mapping.
If, for example, we have 'point', 'gaussian' and 'sersic'
source types, then passing the following dict as an argument
sources_to_nr_vars({'point':10, 'gaussian': 20})
will return an... |
375,204 | def connect_from(self, vertex, weight=1):
for edge in self.edges_in:
if vertex == edge.vertex_out:
return edge
return Edge(vertex, self, weight) | Connect another vertex to this one.
Args:
vertex (Vertex): vertex to connect from.
weight (int): weight of the edge.
Returns:
Edge: the newly created edge. |
375,205 | def f_measure(precision, recall, beta=1.0):
if precision == 0 and recall == 0:
return 0.0
return (1 + beta**2)*precision*recall/((beta**2)*precision + recall) | Compute the f-measure from precision and recall scores.
Parameters
----------
precision : float in (0, 1]
Precision
recall : float in (0, 1]
Recall
beta : float > 0
Weighting factor for f-measure
(Default value = 1.0)
Returns
-------
f_measure : float
... |
375,206 | def get_distinct_values_from_cols(self, l_col_list):
uniq_vals = []
for l_col_name in l_col_list:
uniq_vals.append(set(self.get_col_data_by_name(l_col_name)))
if len(l_col_list) == 0:
return []
elif len... | returns the list of distinct combinations in a dataset
based on the columns in the list. Note that this is
currently implemented as MAX permutations of the combo
so it is not guarenteed to have values in each case. |
375,207 | def _create_hosting_device_templates_from_config(self):
hdt_dict = config.get_specific_config()
attr_info = ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP[
ciscohostingdevicemanager.DEVICE_TEMPLATES]
adm_context = bc.context.get_admin_context()
for hdt_uuid, kv_di... | To be called late during plugin initialization so that any hosting
device templates defined in the config file is properly inserted in
the DB. |
375,208 | def send_response(self, response):
response_bytes = response.encode(config.CODEC)
log.debug("About to send reponse: %r", response_bytes)
self.socket.send(response_bytes) | Send a unicode object as reply to the most recently-issued command |
375,209 | def transform_cb(self, setting, value):
self.make_callback()
whence = 0
self.redraw(whence=whence) | Handle callback related to changes in transformations. |
375,210 | def solution(self, x0, y0):
def soln(x):
if numpy.size(x) > 1:
x = [soln.x] + list(x)
ans = self(soln.y, interval=x)
soln.x = x[-1]
soln.y = ans[-1]
return ans
else:
soln.y = self(sol... | Create a solution function ``y(x)`` such that ``y(x0) = y0``.
A list of solution values ``[y(x0), y(x1) ...]`` is returned if the
function is called with a list ``[x0, x1 ...]`` of ``x`` values. |
375,211 | def cmd_create(self, name, auto=False):
LOGGER.setLevel()
LOGGER.propagate = 0
router = Router(self.database,
migrate_dir=self.app.config[],
migrate_table=self.app.config[])
if auto:
auto = self.models
route... | Create a new migration. |
375,212 | def astra_parallel_3d_geom_to_vec(geometry):
angles = geometry.angles
mid_pt = geometry.det_params.mid_pt
vectors = np.zeros((angles.shape[-1], 12))
vectors[:, 0:3] = -geometry.det_to_src(angles, mid_pt)
vectors[:, 3:6] = geometry.det_point_position(angles, mid_pt)
d... | Create vectors for ASTRA projection geometries from ODL geometry.
The 3D vectors are used to create an ASTRA projection geometry for
parallel beam geometries, see ``'parallel3d_vec'`` in the
`ASTRA projection geometry documentation`_.
Each row of the returned vectors corresponds to a single projection... |
375,213 | def events_system(self):
response = self._get(url.events_system)
self._check_response(response, 200)
return self._create_response(response).get("events") | Get all system events. Uses GET to /events/system interface.
:Returns: (list) Events |
375,214 | def translate_changes(initial_change):
agenda = [initial_change]
result = []
while agenda:
change = agenda.pop(0)
if isinstance(change, rope_change.ChangeSet):
agenda.extend(change.changes)
elif isinstance(change, rope_change.ChangeContents):
result.appen... | Translate rope.base.change.Change instances to dictionaries.
See Refactor.get_changes for an explanation of the resulting
dictionary. |
375,215 | def object_as_dict(obj):
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs} | Turn an SQLAlchemy model into a dict of field names and values.
Based on https://stackoverflow.com/a/37350445/1579058 |
375,216 | def p_arr_decl_initialized(p):
def check_bound(boundlist, remaining):
lineno = p.lineno(8)
if not boundlist:
if not isinstance(remaining, list):
return True
for row in remaining:
if not check_bound(boundlist[1:], row):
... | var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector |
375,217 | def remove(self, nodes):
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k] | Remove a node and its edges. |
375,218 | def indexXY(self, index):
rect = self.visualRect(index)
return rect.x(), rect.y() | Returns the top left coordinates of the item for the given index
:param index: index for the item
:type index: :qtdoc:`QModelIndex`
:returns: (int, int) -- (x, y) view coordinates of item |
375,219 | def is_contiguous(self):
if self._keyframe is None:
raise RuntimeError()
if self._keyframe.is_contiguous:
return self._offsetscounts[0][0], self._keyframe.is_contiguous[1]
return None | Return offset and size of contiguous data, else None. |
375,220 | def __serve_forever(self):
thread_list = {}
while self.screen.is_end == False:
logger.debug("Iter through the following server list: {}".format(self.get_servers_list()))
for v in self.get_servers_list():
key = v["key"]
... | Main client loop. |
375,221 | def _proxy(self):
if self._context is None:
self._context = AvailablePhoneNumberCountryContext(
self._version,
account_sid=self._solution[],
country_code=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance
:rtype: twilio.rest.api.v2010.account.available_phone_n... |
375,222 | def submit_all(self):
for args in self.task_args:
self.submit(*args)
return self.get_results() | :returns: an IterResult object |
375,223 | def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None):
x, y = np.asarray(x), np.asarray(y)
x, y = np.squeeze(x), np.squeeze(y)
if x.size != y.size:
raise ValueError()
nx, ny = gridsize
n = x.size
if weights is None:
weig... | Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and
produces an essentially id... |
375,224 | def zone(self) -> Optional[str]:
if self._device_category == DC_BASEUNIT:
return None
return .format(self._group_number, self._unit_number) | Zone the device is assigned to. |
375,225 | def compiled_quil(self):
prog = self._raw.get("program", {}).get("compiled-quil", None)
if prog is not None:
return parse_program(prog)
else:
if self._raw[] == :
return self.result() | If the Quil program associated with the Job was compiled (e.g., to translate it to the
QPU's natural gateset) return this compiled program.
:rtype: Optional[Program] |
375,226 | def line(self, lines):
shapeType = POLYLINE
self._shapeparts(parts=lines, shapeType=shapeType) | Creates a POLYLINE shape.
Lines is a collection of lines, each made up of a list of xy values. |
375,227 | def readlink(self, path):
path = self._adjust_cwd(path)
self._log(DEBUG, % path)
t, msg = self._request(CMD_READLINK, path)
if t != CMD_NAME:
raise SFTPError()
count = msg.get_int()
if count == 0:
return None
if count != 1:
... | Return the target of a symbolic link (shortcut). You can use
L{symlink} to create these. The result may be either an absolute or
relative pathname.
@param path: path of the symbolic link file
@type path: str
@return: target path
@rtype: str |
375,228 | def write_xml(xml, output_file=None):
gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now())
utils.write_xml(xml, output_loc=output_file, filename=gen_filename) | Outputs the XML content into a file. |
375,229 | def missing_parameter_values(self, parameter_values):
if not self._is_valid_parameter_values(parameter_values):
raise InvalidParameterValues("Parameter values are required to process a policy template")
return list(set(self.parameters.keys()) - set(parameter_values.keys())) | Checks if the given input contains values for all parameters used by this template
:param dict parameter_values: Dictionary of values for each parameter used in the template
:return list: List of names of parameters that are missing.
:raises InvalidParameterValues: When parameter values is not ... |
375,230 | def getDataset(self, itemId):
if self._url.lower().find() > -1:
url = self._url
else:
url = self._url + "/datasets"
return OpenDataItem(url=url,
itemId=itemId,
securityHandler=self._securityHandler,
... | gets a dataset class |
375,231 | def get_profile(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "get_profile" not in self._inner_api_calls:
self._inner_api_calls[
"get_prof... | Gets the specified profile.
Example:
>>> from google.cloud import talent_v4beta1
>>>
>>> client = talent_v4beta1.ProfileServiceClient()
>>>
>>> name = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]')
>>>
>>> response =... |
375,232 | def get_collection_instance(klass, api_client = None, request_api=True, **kwargs):
_type = klass
if api_client is None and request_api:
api_client = api.APIClient()
if isinstance(klass, dict):
_type = klass[]
obj = CollectionResource(_type, api_client, **kwargs)
return obj ... | instatiates the collection lookup of json type klass
:param klass: json file name
:param api_client: transportation api
:param request_api: if True uses the default APIClient |
375,233 | def stickers_translate_get(self, api_key, s, **kwargs):
kwargs[] = True
if kwargs.get():
return self.stickers_translate_get_with_http_info(api_key, s, **kwargs)
else:
(data) = self.stickers_translate_get_with_http_info(api_key, s, **kwargs)
return dat... | Sticker Translate Endpoint
The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please de... |
375,234 | def _competition(self, x):
index = 0
minimum = euclidean_distance_square(self._weights[0], x)
for i in range(1, self._size, 1):
candidate = euclidean_distance_square(self._weights[i], x)
if candidate < minimum:
index = i... | !
@brief Calculates neuron winner (distance, neuron index).
@param[in] x (list): Input pattern from the input data set, for example it can be coordinates of point.
@return (uint) Returns index of neuron that is winner. |
375,235 | def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL):
if self._user is not None:
if not cgroups:
cgroups = find_cgroups_of_process(pid)
pids = cgroups.get_all_tasks(FREEZER)
tr... | Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to sudo's child in this case. |
375,236 | def _read_register(self, reg):
self.buf[0] = reg
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.readinto(self.buf, end=2)
return self.buf[0] << 8 | self.buf[1] | Read 16 bit register value. |
375,237 | def remove_cache(self, namespace, key=None):
if key is None:
self.cursor.execute(
, (namespace,))
else:
self.cursor.execute(
,
(namespace, key)) | Remove all cached values for the specified namespace,
optionally specifying a key |
375,238 | def coroutine(func):
def decorator(*args, **kwargs):
generator = func(*args, **kwargs)
next(generator)
return lambda *args: generator.send(args)
return decorator | A decorator to wrap a generator function into a callable interface.
>>> @coroutine
... def sum(count):
... sum = 0
... for _ in range(0, count):
... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...`
... ... |
375,239 | def endswith(self, search_str):
for entry in reversed(list(open(self._jrnl_file, ))[-5:]):
if search_str in entry:
return True
return False | Check whether the provided string exists in Journal file.
Only checks the last 5 lines of the journal file. This method is
usually used when tracking a journal from an active Revit session.
Args:
search_str (str): string to search for
Returns:
bool: if True the... |
375,240 | def purge(vm_, dirs=False, removables=None, **kwargs):
s to also delete the directories containing the virtual machine disk
images - USE WITH EXTREME CAUTION!
Pass removables=False to avoid deleting cdrom and floppy images. To avoid
disruption, the default but dangerous value is True. This will be chan... | Recursively destroy and delete a persistent virtual machine, pass True for
dir's to also delete the directories containing the virtual machine disk
images - USE WITH EXTREME CAUTION!
Pass removables=False to avoid deleting cdrom and floppy images. To avoid
disruption, the default but dangerous value is... |
375,241 | def _infer_all_output_dims(self, inputs):
batch_size = tf.expand_dims(tf.shape(inputs)[0], 0)
out_channels = (self.output_channels,)
if self._n == 1:
out_shape = (1,) + self.output_shape
else:
out_shape = self.output_shape
if self._data_format.startswith("... | Calculate the output shape for `inputs` after a deconvolution.
Args:
inputs: A Tensor of shape `data_format` and of type `tf.float16`,
`tf.bfloat16` or `tf.float32`.
Returns:
output_shape: A tensor of shape (`batch_size`, `conv_output_shape`). |
375,242 | def more_than_one_error(self, field):
msg = .format(field)
self.logger.log(msg)
self.error = True | Logs a more than one error.
field is the field/property that has more than one defined. |
375,243 | def from_dynacRepr(cls, pynacRepr):
pynacList = pynacRepr[1][0]
L = float(pynacList[3])
TTF = float(pynacList[4])
TTFprime = float(pynacList[5])
TTFprimeprime = float(pynacList[13])
EField = float(pynacList[10])
phase = float(pynacList[11])
F = f... | Construct a ``AccGap`` instance from the Pynac lattice element |
375,244 | def distrib_release():
with settings(hide(, )):
kernel = (run() or ).strip().lower()
if kernel == LINUX:
return run()
elif kernel == SUNOS:
return run() | Get the release number of the distribution.
Example::
from burlap.system import distrib_id, distrib_release
if distrib_id() == 'CentOS' and distrib_release() == '6.1':
print(u"CentOS 6.2 has been released. Please upgrade.") |
375,245 | def t_IDENTIFER(self, t):
r
t.type = SpecParser.reserved.get(t.value, )
return t | r'\#?[a-zA-Z_][a-zA-Z_0-9]* |
375,246 | def write_document(self, document: BioCDocument):
tree = self.encoder.encode(document)
self.__writer.send(tree) | Encode and write a single document. |
375,247 | def get_hash(fName, readSize, dire=pDir()):
if not fileExists(fName, dire):
return -1
readSize = readSize * 1024
fName = os.path.join(dire, fName)
with open(fName, ) as f:
size = os.path.getsize(fName)
if size < readSize * 2:
return -1
data = f.read(rea... | creates the required hash |
375,248 | def redact_secrets(line):
def redact(match):
if match.group(2) in SECRET_WHITELIST:
return match.group(0)
return match.group(1) +
return SECRET_PATTERN.sub(redact, line) | Returns a sanitized string for any ``line`` that looks like it contains a
secret (i.e. matches SECRET_PATTERN). |
375,249 | def pager(__text: str, *, pager: Optional[str] = ):
if pager:
run([pager, ], input=__text.encode())
else:
print(__text) | Pass output through pager.
See :manpage:`less(1)`, if you wish to configure the default pager. For
example, you may wish to check ``FRSX`` options.
Args:
__text: Text to page
pager: Pager to use |
375,250 | def has_active_subscription(self, plan=None):
if plan is None:
valid_subscriptions = self._get_valid_subscriptions()
if len(valid_subscriptions) == 0:
return False
elif len(valid_subscriptions) == 1:
return True
else:
raise TypeError(
"plan cannot be None if more than one valid subsc... | Checks to see if this customer has an active subscription to the given plan.
:param plan: The plan for which to check for an active subscription. If plan is None and
there exists only one active subscription, this method will check if that subscription
is valid. Calling this method with no plan and multiple va... |
375,251 | def run(self):
t_last_click = -1
while True:
d = self.device.read(13)
if d is not None and self._enabled:
if d[0] == 1:
self.y = convert(d[1], d[2])
self.x = convert(d[3], d[4])
self.z = con... | Listener method that keeps pulling new messages. |
375,252 | def count_of_certain_kind(kind):
recs = TabPost.select().where(TabPost.kind == kind)
return recs.count() | Get the count of certain kind. |
375,253 | def browse(fileNames=None,
inspectorFullName=None,
select=None,
profile=DEFAULT_PROFILE,
resetProfile=False,
resetAllProfiles=False,
resetRegistry=False):
from argos.qt import QtWidgets, QtCore
from argos.application import ... | Opens the main window(s) for the persistent settings of the given profile,
and executes the application.
:param fileNames: List of file names that will be added to the repository
:param inspectorFullName: The full path name of the inspector that will be loaded
:param select: a path of t... |
375,254 | def iter_symbols(code):
for name in code.co_names:
yield name
for const in code.co_consts:
if isinstance(const, six.string_types):
yield const
elif isinstance(const, CodeType):
for name in iter_symbols(const):
yield name | Yield names and strings used by `code` and its nested code objects |
375,255 | def set_weight(self, weight):
if weight is not None and np.all(weight == 1):
weight = None
self.weight = weight
if self.handle is not None and weight is not None:
weight = list_to_1d_numpy(weight, name=)
self.set_field(, weight)
return self | Set weight of each instance.
Parameters
----------
weight : list, numpy 1-D array, pandas Series or None
Weight to be set for each data point.
Returns
-------
self : Dataset
Dataset with set weight. |
375,256 | def stop(self, devices):
for device in devices:
self.logger.info(, device.id)
try:
device.power_off()
except packet.baseapi.Error:
raise PacketManagerException(.format(device.id)) | Power-Off one or more running devices. |
375,257 | def fw_retry_failures(self):
if not self.fw_init:
return
try:
self.fw_retry_failures_create()
self.fw_retry_failures_delete()
except Exception as exc:
LOG.error("Exception in retry failures %s", str(exc)) | Top level retry routine called. |
375,258 | def from_dict(cls, data):
fulfillment = data[]
if not isinstance(fulfillment, (Fulfillment, type(None))):
try:
fulfillment = Fulfillment.from_uri(data[])
except ASN1DecodeError:
raise InvalidSignature("Ful... | Transforms a Python dictionary to an Input object.
Note:
Optionally, this method can also serialize a Cryptoconditions-
Fulfillment that is not yet signed.
Args:
data (dict): The Input to be transformed.
Returns:
:cla... |
375,259 | def connect_to_images(region=None, public=True):
return _create_client(ep_name="image", region=region, public=public) | Creates a client for working with Images. |
375,260 | def alpha_view(qimage):
bytes = byte_view(qimage, byteorder = None)
if bytes.shape[2] != 4:
raise ValueError("For alpha_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)")
return bytes[...,_bgra[3]] | Returns alpha view of a given 32-bit color QImage_'s memory.
The result is a 2D numpy.uint8 array, equivalent to
byte_view(qimage)[...,3]. The image must have 32 bit pixel size,
i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is
not enforced that the given qimage has a format that actuall... |
375,261 | def add_dicts(*args):
counters = [Counter(arg) for arg in args]
return dict(reduce(operator.add, counters)) | Adds two or more dicts together. Common keys will have their values added.
For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':1, 'c':3}
>>> t3 = {'d':4}
>>> add_dicts(t1, t2, t3)
{'a': 1, 'c': 3, 'b': 3, 'd': 4} |
375,262 | def Deserialize(self, reader):
super(SpentCoinState, self).Deserialize(reader)
self.TransactionHash = reader.ReadUInt256()
self.TransactionHeight = reader.ReadUInt32()
count = reader.ReadVarInt()
items = [0] * count
for i in range(0, count):
index ... | Deserialize full object.
Args:
reader (neocore.IO.BinaryReader): |
375,263 | def clone(self):
result = copy.copy(self)
result.compound_masses = copy.deepcopy(self.compound_masses)
return result | Create a complete copy of self.
:returns: A MaterialPackage that is identical to self. |
375,264 | def parse_version(v):
parts = v.split(".")
parts = (parts + 3 * [])[:3]
return tuple(int(x) for x in parts) | Take a string version and conver it to a tuple (for easier comparison), e.g.:
"1.2.3" --> (1, 2, 3)
"1.2" --> (1, 2, 0)
"1" --> (1, 0, 0) |
375,265 | def create(
cls,
path,
template_engine=None,
output_filename=None,
output_ext=None,
view_name=None
):
if isinstance(path, dict):
return StatikViewComplexPath(
path,
templ... | Create the relevant subclass of StatikView based on the given path variable and
parameters. |
375,266 | def colon_subscripts(u):
if u.__class__ in (node.arrayref,node.cellarrayref):
for w in u.args:
if w.__class__ is node.expr and w.op == ":":
w._replace(op="::") | Array colon subscripts foo(1:10) and colon expressions 1:10 look
too similar to each other. Now is the time to find out who is who. |
375,267 | def remove(self, key, column_path, timestamp, consistency_level):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_remove(key, column_path, timestamp, consistency_level)
return d | Remove data from the row specified by key at the granularity specified by column_path, and the given timestamp. Note
that all the values in column_path besides column_path.column_family are truly optional: you can remove the entire
row by just specifying the ColumnFamily, or you can remove a SuperColumn or a si... |
375,268 | def fig_to_geojson(fig=None, **kwargs):
if fig is None:
fig = plt.gcf()
renderer = LeafletRenderer(**kwargs)
exporter = Exporter(renderer)
exporter.run(fig)
return renderer.geojson() | Returns a figure's GeoJSON representation as a dictionary
All arguments passed to fig_to_html()
Returns
-------
GeoJSON dictionary |
375,269 | def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None:
self.types.append(HierarkeyType(type=type, serialize=serialize, unserialize=unserialize)) | Adds serialization support for a new type.
:param type: The type to add support for.
:param serialize: A callable that takes an object of type ``type`` and returns a string.
:param unserialize: A callable that takes a string and returns an object of type ``type``. |
375,270 | def setText(self, text: str):
undoObj = UndoSetText(self, text)
self.qteUndoStack.push(undoObj) | Undo safe wrapper for the native ``setText`` method.
|Args|
* ``text`` (**str**): text to insert at the specified position.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. |
375,271 | def controldata(self):
result = {}
except subprocess.CalledProcessError:
logger.exception("Error when calling pg_controldata")
return result | return the contents of pg_controldata, or non-True value if pg_controldata call failed |
375,272 | def listidentifiers(**kwargs):
e_tree, e_listidentifiers = verb(**kwargs)
result = get_records(**kwargs)
for record in result.items:
pid = oaiid_fetcher(record[], record[][])
header(
e_listidentifiers,
identifier=pid.pid_value,
datestamp=record[],
... | Create OAI-PMH response for verb ListIdentifiers. |
375,273 | def forwardMessage(self, chat_id, from_chat_id, message_id,
disable_notification=None):
p = _strip(locals())
return self._api_request(, _rectify(p)) | See: https://core.telegram.org/bots/api#forwardmessage |
375,274 | def coerce(self, value):
if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \
list_diff(self.domain, value.domain) == []):
return value
elif value in self.domain:
return LinearOrderedCell(self.domain, value, value)
... | Takes one or two values in the domain and returns a LinearOrderedCell
with the same domain |
375,275 | def delete_subnet_group(name, region=None, key=None, keyid=None,
profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not conn:
return {: bool(conn)}
r = conn.delete_db_subnet_group(DBSubnetGroupName=name)
... | Delete an RDS subnet group.
CLI example::
salt myminion boto_rds.delete_subnet_group my-subnet-group \
region=us-east-1 |
375,276 | def gen_lazy_function(self):
if self._value is None:
if self._random is not None:
self.value = self._random(**self._parents.value)
else:
raise ValueError(
+
se... | Will be called by Node at instantiation. |
375,277 | def clear(self):
for variable in self._project.variables.list(all=True):
variable.delete() | Clears all of the build variables. |
375,278 | def _get_default_values(self, default_values=None):
if not default_values:
default_values = self.DEFAULT_VALUES
if default_values:
api_version = str(self._connection._apiVersion)
values = default_values.get(api_version, {}).copy()
else:
... | Gets the default values set for a resource |
375,279 | def answerPreCheckoutQuery(self, pre_checkout_query_id, ok,
error_message=None):
p = _strip(locals())
return self._api_request(, _rectify(p)) | See: https://core.telegram.org/bots/api#answerprecheckoutquery |
375,280 | def get_internal_urls(self):
internal_urls = self.get_subfields("856", "u", i1="4", i2="0")
internal_urls.extend(self.get_subfields("998", "a"))
internal_urls.extend(self.get_subfields("URL", "u"))
return map(lambda x: x.replace("&", "&"), internal_urls) | URL's, which may point to edeposit, aleph, kramerius and so on.
Fields ``856u40``, ``998a`` and ``URLu``.
Returns:
list: List of internal URLs. |
375,281 | def hardware_flexport_flexport_type_instance(self, **kwargs):
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
flexport = ET.SubElement(hardware, "flexport")
id_key = ET.SubElement(flexport, "id")
i... | Auto Generated Code |
375,282 | def getResultFromProcess(res, tempname, process):
if not isinstance(res, (UndefinedValue, Exception)):
value = getRepresentation(tempname, process)
return value, res
else:
return res, str(res) | Get a value from process, return tuple of value, res if succesful |
375,283 | def parse_bdstoken(content):
bdstoken =
bds_re = re.compile(, re.IGNORECASE)
bds_match = bds_re.search(content)
if bds_match:
bdstoken = bds_match.group(1)
return bdstoken | 从页面中解析出bdstoken等信息.
这些信息都位于页面底部的<script>, 只有在授权后的页面中才出现.
这里, 为了保证兼容性, 就不再使用cssselect模块解析了.
@return 返回bdstoken |
375,284 | def speed_rms(Temperature,element,isotope):
r
atom = Atom(element, isotope)
return sqrt(3*Temperature*k_B/atom.mass) | r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
m is the mass of the atom (in kilograms).
... |
375,285 | def restore(self, hist_uid):
if self.check_post_role()[]:
pass
else:
return False
histinfo = MWikiHist.get_by_uid(hist_uid)
if histinfo:
pass
else:
return False
postinfo = MWiki.get_by_uid(histinfo.wiki_id)
... | Restore by ID |
375,286 | def main(argv, reactor=None):
if reactor is None:
from twisted.internet import gtk2reactor
gtk2reactor.install()
from twisted.internet import reactor
try:
AWSStatusIndicator(reactor)
gobject.set_application_name("aws-status")
reactor.run()
except ValueErr... | Run the client GUI.
Typical use:
>>> sys.exit(main(sys.argv))
@param argv: The arguments to run it with, e.g. sys.argv.
@param reactor: The reactor to use. Must be compatible with gtk as this
module uses gtk API"s.
@return exitcode: The exit code it returned, as per sys.exit. |
375,287 | def close(self):
if self._sock:
with utils.ignore_except():
self._sock.close()
self._sock = None
self._recvbuf = []
self._recvbuf_partial = | Close the connection.
:param purge: If True (the default), the receive buffer will
be purged. |
375,288 | def upload_image(self,
image_file,
referer_url=None,
title=None,
desc=None,
created_at=None,
collection_id=None):
url = self.upload_url +
data = {}
if referer_u... | Upload an image
:param image_file: File-like object of an image file
:param referer_url: Referer site URL
:param title: Site title
:param desc: Comment
:param created_at: Image's created time in unix time
:param collection_id: Collection ID |
375,289 | def create_or_replace_primary_key(self,
table: str,
fieldnames: Sequence[str]) -> int:
sql = .format(self.get_current_schema_expr())
row = self.fetchone(sql, table)
has_pk_already = True if row... | Make a primary key, or replace it if it exists. |
375,290 | def ok(self):
try:
v = int(self._value)
if v < 0:
return False
else:
return True
except:
return False | Returns True if OK to use, else False |
375,291 | def Start(self):
try:
self.stats = {}
self.BeginProcessing()
processed_count = 0
if data_store.RelationalDBEnabled():
for client_info_batch in _IterateAllClients(
recency_window=self.recency_window):
for client_info in client_info_batch:
sel... | Retrieve all the clients for the AbstractClientStatsCollectors. |
375,292 | def adapt_files(solver):
print("adapting {0}solvers', solver)
for arch in to_extract[solver]:
arch = os.path.join(root, arch)
extract_archive(arch, solver, put_inside=True)
for fnames in to_move[solver]:
old = os.path.join(root, fnames[0])
new = os.path.join(root, fna... | Rename and remove files whenever necessary. |
375,293 | def get_match(sport, team1, team2):
sport = sport.lower()
team1_pattern = re.compile(team1, re.I)
team2_pattern = re.compile(team2, re.I)
matches = get_sport(sport)
for match in matches:
if re.search(team1_pattern, match.home_team) or re.search(team1_pattern, match.away_team) \
... | Get live scores for a single match
:param sport: the sport being played
:type sport: string
:param team1: first team participating in the match
:ttype team1: string
:param team2: second team participating in the match
:type team2: string
:return: A specific match
:rtype: Match |
375,294 | def assign(self, pm):
if isinstance(pm, QPixmap):
self._pm = pm
else:
self._xpmstr = pm
self._pm = None
self._icon = None | Reassign pixmap or xpm string array to wrapper |
375,295 | def ssh_version():
ret = subprocess.Popen(
[, ],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()
try:
version_parts = ret[1].split(b)[0].split(b)[1]
parts = []
for part in version_parts:
try:
par... | Returns the version of the installed ssh command |
375,296 | def set_up(self, test_args=(), clear=True, debug=False):
self.test_args = test_args
self.debug, self.clear = debug, clear | Sets properties right before calling run.
``test_args`` The arguments to pass to the test runner.
``clear`` Boolean. Set to True if we should clear console before
running the tests.
``debug`` Boolean. Set to True if we want to print debugging
... |
375,297 | def execute():
boto_server_error_retries = 3
for table_name, table_key in sorted(dynamodb.get_tables_and_gsis()):
try:
table_num_consec_read_checks = \
CHECK_STATUS[][table_name][]
except KeyError:
table_num_consec_read_checks = 0
try:
... | Ensure provisioning |
375,298 | def infile(self):
return os.path.join(OPTIONS[],
.format(self.name, OPTIONS[])) | Path of the input file |
375,299 | def p_rule(self, rule):
if len(rule[1]) == 4:
rule[0] = Guideline(rule[1][1], rule[1][2], rule[1][3])
else:
indentsize = rule[1][0]
number = rule[1][1]
text = rule[1][2]
parent = None
... | rule : GUIDELINE
| REGULATION |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.