Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
345,000 | def convert_string(self, rest):
try:
html = publish_string(rest, writer_name=)
except SystemExit as e:
err_exit( % e.code)
else:
if sys.version_info[0] >= 3:
return html.decode()
return html | Convert a reST string to an HTML string. |
345,001 | def find_n50(contig_lengths_dict, genome_length_dict):
n50_dict = dict()
for file_name, contig_lengths in contig_lengths_dict.items():
currentlength = 0
for contig_length in contig_lengths:
currentlength += contig_length
if cur... | Calculate the N50 for each strain. N50 is defined as the largest contig such that at least half of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dic... |
345,002 | def drag_events(self):
if not self.is_dragging:
return None
event = self
events = []
while True:
if event is None or event.type == :
break
events.append(event)
event = event.last_event
return ... | Return a list of all mouse events in the current drag operation.
Returns None if there is no current drag operation. |
345,003 | def safedata(self, data, cdata=True):
r
safe = ( % data) if cdata else cgi.escape(str(data), True)
return safe | r"""Convert xml special chars to entities.
:param data: the data will be converted safe.
:param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data.
:type cdata: bool
:rtype: str |
345,004 | def vlans(self):
urn = "{urn:brocade.com:mgmt:brocade-interface-ext}"
result = []
has_more =
last_vlan_id =
while (has_more == ) or (has_more == ):
request_interface = self.get_vlan_brief_request(last_vlan_id)
interface_result = self._callback(... | list[dict]: A list of dictionary items describing the details of
vlan interfaces.
This method fetches the VLAN interfaces
Examples:
>>> import pynos.device
>>> switch = '10.24.39.202'
>>> auth = ('admin', 'password')
>>> conn = (switch, '22')
... |
345,005 | def with_arg_count(self, count):
exp = self._get_current_call()
exp.expected_arg_count = count
return self | Set the last call to expect an exact argument count.
I.E.::
>>> auth = Fake('auth').provides('login').with_arg_count(2)
>>> auth.login('joe_user') # forgot password
Traceback (most recent call last):
...
AssertionError: fake:auth.login() was called w... |
345,006 | def refresh():
override_files = []
for stack in traceback.extract_stack():
f = os.path.join(os.path.dirname(stack[0]), OVERRIDE_FILE)
if f not in override_files:
override_files.insert(0, f)
if OVERRIDE_FILE in override_files:
del override_files[override_files.index(O... | Scan over all the involved directories and load configs from them. |
345,007 | def elements(self) -> devicetools.Elements:
elements = devicetools.Elements()
for selection in self:
elements += selection.elements
return elements | A |set| containing the |Node| objects of all handled
|Selection| objects.
>>> from hydpy import Selection, Selections
>>> selections = Selections(
... Selection('sel1', ['node1'], ['element1']),
... Selection('sel2', ['node1'], ['element2', 'element3']))
>>> sele... |
345,008 | def intersect(self, other_curve, justonemode=False, tol=1e-12):
path1 = self
if isinstance(other_curve, Path):
path2 = other_curve
else:
path2 = Path(other_curve)
assert path1 != path2
intersection_list = []
for seg1 in path1:
... | returns list of pairs of pairs ((T1, seg1, t1), (T2, seg2, t2))
giving the intersection points.
If justonemode==True, then returns just the first
intersection found.
tol is used to check for redundant intersections (see comment above
the code block where tol is used).
Not... |
345,009 | def key_event_callback(self, window, key, scancode, action, mods):
self.keyboard_event(key, action, mods) | Key event callback for glfw.
Translates and forwards keyboard event to :py:func:`keyboard_event`
:param window: Window event origin
:param key: The key that was pressed or released.
:param scancode: The system-specific scancode of the key.
:param action: GLFW_PRESS, GLFW_RELEASE... |
345,010 | def generate_certificate_signing_request(
ctx, slot, pin, public_key, csr_output, subject):
controller = ctx.obj[]
_verify_pin(ctx, controller, pin)
data = public_key.read()
public_key = serialization.load_pem_public_key(
data, default_backend())
try:
csr = controller.... | Generate a Certificate Signing Request (CSR).
A private key need to exist in the slot.
\b
SLOT PIV slot where the private key is stored.
PUBLIC-KEY File containing a public key. Use '-' to use stdin.
CSR File to write CSR to. Use '-' to use stdout. |
345,011 | def get_prime(bits):
while True:
num = random.randrange(2 ** (bits - 1), 2 ** bits)
if Integer(str(num)).is_probably_prime():
return num | Creates (probable) prime number of given size
:param bits: size of number to generate
:return: prime number of given size |
345,012 | def process(self, message, user):
if not self._socket:
self.connect()
self.lhlo()
else:
self.rset()
if not self.dlmtp:
raise DspamClientError()
self.mailfrom(client_args=)
self.rcptto((user,))
self.data(message)
... | Process a message. |
345,013 | def configure(**kwargs):
for key in kwargs:
if key == :
Event.is_logging_enabled = kwargs[key]
elif key == :
Event.collector_queue = kwargs[key]
else:
Logger.get_logger(__name__).error("Unknown key %s in configure or ba... | Global configuration for event handling. |
345,014 | def set_mode(self, anchor_id, mode):
data = struct.pack(, LoPoAnchor.LPP_TYPE_MODE, mode)
self.crazyflie.loc.send_short_lpp_packet(anchor_id, data) | Send a packet to set the anchor mode. If the anchor receive the packet,
it will change mode and resets. |
345,015 | def next_weekday(weekday):
ix = WEEKDAYS.index(weekday)
if ix == len(WEEKDAYS)-1:
return WEEKDAYS[0]
return WEEKDAYS[ix+1] | Returns the name of the weekday after the given weekday name. |
345,016 | def _get_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout):
if mode == :
rnn_block = functools.partial(rnn.RNN, activation=)
elif mode == :
rnn_block = functools.partial(rnn.RNN, activation=)
elif mode == :
rnn_block = rnn.LSTM
elif mode == :
... | create rnn layer given specs |
345,017 | def P(Document, *fields, **kw):
__always__ = kw.pop(, set())
projected = set()
omitted = set()
for field in fields:
if field[0] in (, ):
omitted.add(field[1:])
elif field[0] == :
projected.add(field[1:])
else:
projected.add(field)
if not projected:
names = set(getattr(Document, , Documen... | Generate a MongoDB projection dictionary using the Django ORM style. |
345,018 | def set_shutdown(self, name, default=False, disable=True):
commands = [ % name]
commands.append(self.command_builder(, value=True,
default=default, disable=disable))
return self.configure(commands) | Configures the interface shutdown state
Default configuration for set_shutdown is disable=True, meaning
'no shutdown'. Setting both default and disable to False will
effectively enable shutdown on the interface.
Args:
name (string): The interface identifier. It must be a f... |
345,019 | def parse_request(api_secret, reqbody, dec_func=False):
try:
if type(reqbody) == type(dict):
return self.parse_form_request(reqbody)
if callable(dec_func):
req_msg = json.loads(dec_func(reqbody))
else:
req_msg = json.loads(reqbody)
ex... | >>> parse_request("123456",'{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}')
<Storage {u'nonce': 1451122677, u'msg': u'helllo', u'code': 0, u'sign': u'DB30F4D1112C20DFA736F65458F89C64'}> |
345,020 | def present(host, service_root, trigger_desc, service_name=None, **kwargs):
s docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring)
.. note::
If services on path does not exists they are created.
.. code-block:: yaml
... | .. versionadded:: Fluorine
Ensure service exists under service root.
:param host: Technical name of the host
:param service_root: Path of service (path is split by /)
:param service_name: Name of service
:param trigger_desc: Description of trigger in zabbix
:param _connection_user: Optional - ... |
345,021 | def draw(data, format=, size=(400, 300), drawing_type=,
camera_type=, shader=, display_html=True,
element_properties=None, show_save=False):
draw_options = [, , ]
camera_options = [, ]
shader_options = [, , , ]
if drawing_type not in draw_options:
raise Exception("Inv... | Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualization, in pixels.
drawing_type: Specifies the molecular represent... |
345,022 | def set_parameters(self, parameters_dict):
DB.set_hash_value(self._key, , parameters_dict)
self.publish("parameters_updated") | Set the subarray parameters.
Args:
parameters_dict (dict): Dictionary of Subarray parameters |
345,023 | def starter(cls):
archive = cls.url +
data = getPageContent(archive, cls.session)
search = compile(tagre("a", "href", r"(\d\d\d\d-\d\d.html)"))
archivepages = search.findall(data)
return cls.url + archivepages[-1] | Pick last one in a list of archive pages. |
345,024 | def set_network(ip, netmask, gateway, host=None,
admin_username=None, admin_password=None):
return __execute_cmd(.format(
ip, netmask, gateway, host=host, admin_username=admin_username,
admin_password=admin_password
)) | Configure Network on the CMC or individual iDRAC.
Use ``set_niccfg`` for blade and switch addresses.
CLI Example:
.. code-block:: bash
salt dell dracr.set_network [DRAC IP] [NETMASK] [GATEWAY]
salt dell dracr.set_network 192.168.0.2 255.255.255.0 192.168.0.1
admin_username=roo... |
345,025 | def _run_once(runner_list, extra_tick, use_poll):
if len(runner_list) > 0:
asyncore.loop(0, use_poll, None, 1)
for runner in runner_list:
if not runner.tick():
return runner
if extra_tick is not None:
code = extra_tick()
if code is False:
... | :return True - success; False - extra_tick failure; runner object - the runner who tick failure |
345,026 | def get_project(self, project_key):
try:
owner_id, project_id = parse_dataset_key(project_key)
return self._projects_api.get_project(owner_id,
project_id).to_dict()
except _swagger.rest.ApiException as e:
rais... | Retrieve an existing project
This method retrieves metadata about an existing project
:param project_key: Project identifier, in the form of owner/id
:type project_key: str
:returns: Project definition, with all attributes
:rtype: dict
:raises RestApiException: If a ser... |
345,027 | def imwrite(img, file_path, params=None, auto_mkdir=True):
if auto_mkdir:
dir_name = osp.abspath(osp.dirname(file_path))
mkdir_or_exist(dir_name)
return cv2.imwrite(file_path, img, params) | Write image to file
Args:
img (ndarray): Image array to be written.
file_path (str): Image file path.
params (None or list): Same as opencv's :func:`imwrite` interface.
auto_mkdir (bool): If the parent folder of `file_path` does not exist,
whether to create it automatica... |
345,028 | def is_type(obj,
type_,
**kwargs):
if not is_iterable(type_):
type_ = [type_]
return_value = False
for check_for_type in type_:
if isinstance(check_for_type, type):
return_value = isinstance(obj, check_for_type)
elif obj.__class__.__name__ ==... | Indicate if ``obj`` is a type in ``type_``.
.. hint::
This checker is particularly useful when you want to evaluate whether
``obj`` is of a particular type, but importing that type directly to use
in :func:`isinstance() <python:isinstance>` would cause a circular import
error.
To us... |
345,029 | def _options(self, **kwargs):
def _format_fq(d):
for k,v in d.items():
if isinstance(v, list):
d[k] = .join(map(lambda x: + x + , v))
else:
d[k] = + v +
values = []
for k,v in d.items():
... | Formats search parameters/values for use with API
:param \*\*kwargs: search parameters/values |
345,030 | def set_child_lane_set(self, value):
if value is None:
self.__child_lane_set = value
elif not isinstance(value, lane_set.LaneSet):
raise TypeError("ChildLaneSet must be a LaneSet")
else:
self.__child_lane_set = value | Setter for 'child_lane_set' field.
:param value - a new value of 'child_lane_set' field. Must be an object of LaneSet type. |
345,031 | def match_settings_edit_event(self, value):
sender = self.sender()
if sender is self.mode_type_combobox:
self.overall_config.set_value(MATCH_CONFIGURATION_HEADER, GAME_MODE, value)
elif sender is self.map_type_combobox:
self.overall_config.set_value(MATCH_CONFIG... | Handles all edits to match settings and sets the config value to the new value
:param value: the value to apply to the overall config
:return: |
345,032 | def get_namespaces(self):
cursor = self.cursor
cursor.execute()
return [namespace for namespace, in cursor] | Get a list of namespaces |
345,033 | def list_horizontal_pod_autoscaler_for_all_namespaces(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_horizontal_pod_autoscaler_for_all_namespace... | list_horizontal_pod_autoscaler_for_all_namespaces # noqa: E501
list or watch objects of kind HorizontalPodAutoscaler # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_horizontal_... |
345,034 | def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results):
try:
while True:
nextData = nonblock_read(stream, limit=blockSizeLimit)
if nextData is None:
break
elif nextData:
results.addBlock(nextData)
tim... | _do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData> |
345,035 | def parse_article(generator, metadata):
if not in metadata:
return
dtstart = parse_tstamp(metadata, )
if in metadata:
dtend = parse_tstamp(metadata, )
elif in metadata:
dtdelta = parse_timedelta(metadata)
dtend = dtstart + dtdelta
else:
msg = "Eith... | Collect articles metadata to be used for building the event calendar
:returns: None |
345,036 | def compare_md5(self):
if self.direction == "put":
remote_md5 = self.remote_md5()
return self.source_md5 == remote_md5
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
return self.source_md5 == local_md5 | Compare md5 of file on network device to md5 of local file. |
345,037 | def get_config(k: str) -> Any:
if k in list(CONFIG.keys()):
return CONFIG[k]
env_key = get_config_env_key(k)
if env_key in os.environ:
return os.environ[env_key]
env_dict = get_config_env()
if env_dict is not None and k in list(env_dict.keys()):
return e... | Returns a configuration variable's value or None if it is unset. |
345,038 | def put_scancode(self, scancode):
if not isinstance(scancode, baseinteger):
raise TypeError("scancode can only be an instance of type baseinteger")
self._call("putScancode",
in_p=[scancode]) | Sends a scancode to the keyboard.
in scancode of type int
raises :class:`VBoxErrorIprtError`
Could not send scan code to virtual keyboard. |
345,039 | def eventgroups(ctx, sport):
sport = Sport(sport, peerplays_instance=ctx.peerplays)
click.echo(pretty_print(sport.eventgroups, ctx=ctx)) | [bookie] List event groups for a sport
:param str sport: Sports id |
345,040 | def create_entry(self, group, **kwargs):
if group not in self.groups:
raise ValueError("Group doesn't exist / is not bound to this database.")
uuid = binascii.hexlify(get_random_bytes(16))
entry = Entry(uuid=uuid,
group_id=gro... | Create a new Entry object.
The group which should hold the entry is needed.
image must be an unsigned int >0, group a Group.
:param group: The associated group.
:keyword title:
:keyword icon:
:keyword url:
:keyword username:
:keyword pa... |
345,041 | def _adjust_sell_amount(self, stock_code, amount):
stock_code = stock_code[-6:]
user = self._users[0]
position = user.position
try:
stock = next(s for s in position if s[] == stock_code)
except StopIteration:
log.info(,
stock_... | 根据实际持仓值计算雪球卖出股数
因为雪球的交易指令是基于持仓百分比,在取近似值的情况下可能出现不精确的问题。
导致如下情况的产生,计算出的指令为买入 1049 股,取近似值买入 1000 股。
而卖出的指令计算出为卖出 1051 股,取近似值卖出 1100 股,超过 1000 股的买入量,
导致卖出失败
:param stock_code: 证券代码
:type stock_code: str
:param amount: 卖出股份数
:type amount: int
:return:... |
345,042 | def _auth(url, user, passwd, realm):
basic = _HTTPBasicAuthHandler()
basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)
return _build_opener(basic, digest) | returns a authentication handler. |
345,043 | def _onPublish(self, mqttc, obj, mid):
with self._messagesLock:
if mid in self._onPublishCallbacks:
midOnPublish = self._onPublishCallbacks.get(mid)
del self._onPublishCallbacks[mid]
if midOnPublish != None:
midOnPublish()
... | Called when a message from the client has been successfully sent to IBM Watson IoT Platform.
See [paho.mqtt.python#on_publish](https://github.com/eclipse/paho.mqtt.python#on_publish) for more information
# Parameters
mqttc (paho.mqtt.client.Client): The client instance for this... |
345,044 | def get(self):
key = self.get_key_from_request()
result = self.get_storage().get(key)
return result if result else None | Get the item from redis. |
345,045 | def event(self, name, owner=None, **kwargs):
return Event(self.tcex, name, owner=owner, **kwargs) | Create the Event TI object.
Args:
name:
**kwargs:
Return: |
345,046 | def mass_properties(self):
mass = triangles.mass_properties(triangles=self.triangles,
crosses=self.triangles_cross,
density=self._density,
center_mass=self._center_mass,
... | Returns the mass properties of the current mesh.
Assumes uniform density, and result is probably garbage if mesh
isn't watertight.
Returns
----------
properties : dict
With keys:
'volume' : in global units^3
'mass' : From specified dens... |
345,047 | def getPriorities(self, projectarea_id=None, projectarea_name=None):
return self._getPriorities(projectarea_id=projectarea_id,
projectarea_name=projectarea_name) | Get all :class:`rtcclient.models.Priority` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given.
If no :class:`rtcclient.models.Priority` is retrieved,
`None` is returned.
:param projectarea_id: the :class:`rtcclient.project_ar... |
345,048 | def copy(self, obj_id, folder_id, move=False):
t seem to work here.
Folders cannot be copied; this is an API limitation.copymove',
data=dict(destination=folder_id), auth_header=True ) | Copy specified file (object) to a folder with a given ID.
Well-known folder names (like "me/skydrive")
don't seem to work here.
Folders cannot be copied; this is an API limitation. |
345,049 | def request_signature(self):
signature = self.query_parameters.get(_x_amz_signature)
if signature is not None:
signature = signature[0]
else:
signature = self.authorization_header_parameters.get(_signature)
if signature is None:
raise ... | The signature passed in the request. |
345,050 | def render(self, nb_class=8, disc_func=None, user_defined_breaks=None,
output="GeoJSON", new_mask=False):
if disc_func and in disc_func and not jenks_breaks:
raise ValueError(
"Missing jenkspy package - could not use jenks breaks")
zi = self.zi
... | Parameters
----------
nb_class : int, optionnal
The number of class (default: 8).
disc_func : str, optionnal
The kind of data classification to be used (to be choosed in
"equal_interval", "jenks", "percentiles, "head_tail_breaks"
and "prog_geom"), ... |
345,051 | def export_agg_risk_csv(ekey, dstore):
writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
path = % (sanitize(ekey[0]), ekey[1])
fname = dstore.export_path(path)
writer.save(dstore[].value, fname)
return [fname] | :param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object |
345,052 | def change_state_type(self, state, new_state_class):
from rafcon.gui.helpers.state import create_new_state_from_state_with_type
state_id = state.state_id
if state_id not in self.states:
raise ValueError("State with id does not exist".format(state.name, state_id))
... | Changes the type of the state to another type
:param state: the state to be changed
:param new_state_class: the new type of the state
:return: the new state having the new state type
:rtype: :py:class:`rafcon.core.states.state.State`
:raises exceptions.ValueError: if the state d... |
345,053 | def offline_plotly_scatter3d(df, x=0, y=1, z=-1):
data = []
colors = [, , ]
x = get_array(df, x, default=0)
y = get_array(df, y, default=1)
z = get_array(df, z, default=-1)
for i in range(len(df[].unique())):
name = df[].unique()[i]
color = colors[i]
x = ... | Plot an offline scatter plot colored according to the categories in the 'name' column.
>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv')
>> offline_plotly(df) |
345,054 | def process_opres_input(key, value, key_options):
opres = None
if isinstance(value, OperationResult):
opres = value
elif isinstance(key, OperationResult):
opres = key
elif isinstance(value, (long, int)):
key_options[] = value
if opres is not None:
key = opres.k... | Check if `value` or `key` is a Result object and populate the
options accordingly.
:param key:
:param value:
:param key_options:
:return: |
345,055 | def _normalize_group_attrs(self, attrs):
for key in self.group_attrs_keys:
if key not in attrs:
raise MissingGroupAttr(key)
if type(attrs[key]) is list and len(attrs[key]) == 1:
attrs[key] = attrs[key][0]
if type(attrs[key]) is list an... | Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated. |
345,056 | def GetAllFiles(self):
for filepath in self._files:
yield filepath
for dirpath in self._dirs:
for filepath in ArtifactRegistrySources._GetDirYamlFiles(dirpath):
if filepath in self._files:
continue
yield filepath | Yields all defined source file paths.
This includes file paths defined directly and those defined implicitly by
defining a directory. |
345,057 | def configure() -> None:
light_grey = ".8"
matplotlib.rcParams["text.latex.preamble"].append(r"\usepackage{amsmath}")
matplotlib.rcParams["text.latex.preamble"].append(r"\usepackage{sfmath}")
params = {
"text.usetex": True,
"xtic... | Configure matplotlib according to my (biased) specification.
As a high level summary, this is a combination of a number of seaborn settings, along with
my own tweaks. By calling this function, the matplotlilb ``rcParams`` will be modified according
to these settings.
Up to this point, the settings hav... |
345,058 | def create_csv(filename, csv_data, mode="w"):
with open(filename, mode) as f:
csv_data.replace("_", r"\_")
f.write(csv_data) | Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file. It can
be 'w', 'a', etc. Default is 'w' |
345,059 | def json2parameter(in_x, parameter, name=ROOT):
out_y = copy.deepcopy(in_x)
if isinstance(in_x, dict):
if TYPE in in_x.keys():
_type = in_x[TYPE]
name = name + + _type
if _type == :
_index = parameter[name]
out_y = {
... | Change json to parameters. |
345,060 | def write_toml(self, data, path=None):
if path is None:
path = self.pipfile_location
data = convert_toml_outline_tables(data)
try:
formatted_data = tomlkit.dumps(data).rstrip()
except Exception:
document = tomlkit.document()
for se... | Writes the given data structure out as TOML. |
345,061 | def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
from ..receivable.peer import User
data = {}
data[] = u(array.get())
data[] = User.from_array(array.get())
d... | Deserialize a new CallbackQuery from a given dictionary.
:return: new CallbackQuery instance.
:rtype: CallbackQuery |
345,062 | def to_html(doc, output="/tmp", style="dep"):
file_name = "-".join([w.text for w in doc[:6] if not w.is_punct]) + ".html"
html = displacy.render(doc, style=style, page=True)
if output is not None:
output_path = Path(output)
if not output_path.exists():
output_path.mkd... | Doc method extension for saving the current state as a displaCy
visualization. |
345,063 | def get_stream(self, decision_point: str, for_initialization: bool = False) -> RandomnessStream:
return self._randomness_manager.get_randomness_stream(decision_point, for_initialization) | Provides a new source of random numbers for the given decision point.
``vivarium`` provides a framework for Common Random Numbers which allows for variance reduction
when modeling counter-factual scenarios. Users interested in causal analysis and comparisons
between simulation scenarios should ... |
345,064 | def parse_observation_response(json):
logging.debug(json)
iaqi = json[]
result = {
: json[],
: json.get(, ),
: json[],
: json.get("dominentpol", ),
: json[][],
: [{: item, : iaqi[item][]} for item in iaqi]
}
return result | Decode AQICN observation response JSON into python object. |
345,065 | def use_double_hash(self, password_hash=None):
single_hash = current_app.config.SECURITY_PASSWORD_SINGLE_HASH
if single_hash and self.security.password_salt:
raise RuntimeError(
)
if password_hash is None:
is_plaintext = self.secur... | Return a bool indicating whether a password should be hashed twice. |
345,066 | def update(self, source_clock_sample, target_clock_sample):
if self._resolved_time is None or self.source_clock_overflow_period is None:
self._resolved_time = decimal.Decimal(source_clock_sample)
self._prev_source_sample = source_clock_sample
self._prev_target_sample... | Args:
source_clock_sample: Sample of the source clock, in seconds
target_clock_sample: Sample of the target clock, in seconds
Returns: Resolved absolute source clock value |
345,067 | def pushd(path):
orig_path = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(orig_path) | pushd changes the actual working directory for the duration of the
context, unlike the _cwd arg this will work with other built-ins such as
sh.glob correctly |
345,068 | def remove_tags(self, tags):
if self.cloud_manager.remove_tags(self, tags):
new_tags = [tag for tag in self.tags if tag not in tags]
object.__setattr__(self, , new_tags) | Add tags to a server. Accepts tags as strings or Tag objects. |
345,069 | def check_quirks(block_id, block_op, db_state):
if op_get_opcode_name(block_op[]) in OPCODE_NAME_NAMEOPS and op_get_opcode_name(block_op[]) not in OPCODE_NAME_STATE_PREORDER:
assert in block_op, .format(op_get_opcode_name(block_op[]))
if block_op[] == NAME_IMPORT:
ass... | Check that all serialization compatibility quirks have been preserved.
Used primarily for testing. |
345,070 | def finish_upload(self, upload_id, hash_data, parent_data, remote_file_id):
self.data_service.complete_upload(upload_id, hash_data.value, hash_data.alg)
if remote_file_id:
result = self.data_service.update_file(remote_file_id, upload_id)
return result.json()
else... | Complete the upload and create or update the file.
:param upload_id: str: uuid of the upload we are completing
:param hash_data: HashData: hash info about the file
:param parent_data: ParentData: info about the parent of this file
:param remote_file_id: str: uuid of this file if it alrea... |
345,071 | def get_cgroup(fullpath):
fullpath = os.path.realpath(fullpath)
status = SubsystemStatus()
name = None
for name, path in status.paths.items():
if path in fullpath:
break
else:
raise Exception( + fullpath)
subsys = _get_subsystem(name)
return CGroup(sub... | It returns a CGroup object which is pointed by the fullpath. |
345,072 | def grants(self):
from linode_api4.objects.account import UserGrants
if not hasattr(self, ):
resp = self._client.get(UserGrants.api_endpoint.format(username=self.username))
grants = UserGrants(self._client, self.username, resp)
self._set(, grants)
r... | Retrieves the grants for this user. If the user is unrestricted, this
will result in an ApiError. This is smart, and will only fetch from the
api once unless the object is invalidated.
:returns: The grants for this user.
:rtype: linode.objects.account.UserGrants |
345,073 | def preview(self, obj, request=None):
source = self.get_thumbnail_source(obj)
if source:
try:
from easy_thumbnails.files import get_thumbnailer
except ImportError:
logger.warning(
_(
... | Generate the HTML to display for the image.
:param obj: An object with a thumbnail_field defined.
:return: HTML for image display. |
345,074 | def sideral(date, longitude=0., model=, eop_correction=True, terms=106):
theta = _sideral(date, longitude, model, eop_correction, terms)
return rot3(np.deg2rad(-theta)) | Sideral time as a rotation matrix |
345,075 | def disconnect(self):
if not self.socket:
logging.warning("No active socket to close!")
return
self.socket.close()
self.socket = None | Ends our server tcp connection. |
345,076 | def is_default(self):
for _, item in self.iter_items(recursive=True):
if not item.is_default:
return False
return True | ``True`` if values of all config items in this section and its subsections
have their values equal to defaults or have no value set. |
345,077 | def interprocess_locked(path):
lock = InterProcessLock(path)
def decorator(f):
@six.wraps(f)
def wrapper(*args, **kwargs):
with lock:
return f(*args, **kwargs)
return wrapper
return decorator | Acquires & releases a interprocess lock around call into
decorated function. |
345,078 | def p_partselect_pointer(self, p):
p[0] = Partselect(p[1], p[3], p[5], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | partselect : pointer LBRACKET expression COLON expression RBRACKET |
345,079 | def results_equal(a, b):
if a.v_is_parameter and b.v_is_parameter:
raise ValueError()
if a.v_is_parameter or b.v_is_parameter:
return False
if a.v_full_name != b.v_full_name:
return False
if hasattr(a, ) and not hasattr(b, ):
return False
if hasattr(a, ):
... | Compares two result instances
Checks full name and all data. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no result instances |
345,080 | def parse_cookie(name, sign_key, kaka, enc_key=None, sign_alg=):
if not kaka:
return None
parts = cookie_parts(name, kaka)
return ver_dec_content(parts, sign_key, enc_key, sign_alg) | Parses and verifies a cookie value
Parses a cookie created by `make_cookie` and verifies
it has not been tampered with.
You need to provide the same `sign_key` and `enc_key`
used when creating the cookie, otherwise the verification
fails. See `make_cookie` for details about the verification.
... |
345,081 | def filter(coro, iterable, assert_fn=None, limit=0, loop=None):
assert_corofunction(coro=coro)
assert_iter(iterable=iterable)
if len(iterable) == 0:
return iterable
results = [None] * len(iterable)
assert_fn = assert_fn or assert_true
pool = ConcurrentExecuto... | Returns a list of all the values in coll which pass an asynchronous truth
test coroutine.
Operations are executed concurrently by default, but results
will be in order.
You can configure the concurrency via `limit` param.
This function is the asynchronous equivalent port Python built-in
`filt... |
345,082 | def get_qapp():
global app
app = QtGui.QApplication.instance()
if app is None:
app = QtGui.QApplication([], QtGui.QApplication.GuiClient)
return app | Return an instance of QApplication. Creates one if neccessary.
:returns: a QApplication instance
:rtype: QApplication
:raises: None |
345,083 | def runner(self, clear_load):
auth_type, err_name, key, sensitive_load_keys = self._prep_auth_info(clear_load)
auth_check = self.loadauth.check_authentication(clear_load, auth_type, key=key)
error = auth_check.get()
if error:
return {... | Send a master control function back to the runner system |
345,084 | def add(self, child):
if isinstance(child, Assign):
self.add_assign(child)
else:
raise ModelError() | Adds a typed child object to the structure object.
@param child: Child object to be added. |
345,085 | def sort_file_tabs_alphabetically(self):
while self.sorted() is False:
for i in range(0, self.tabs.tabBar().count()):
if(self.tabs.tabBar().tabText(i) >
self.tabs.tabBar().tabText(i + 1)):
self.tabs.tabBar().moveTab(i, i + 1) | Sort open tabs alphabetically. |
345,086 | def get_posts_tags(subscribers, object_list, feed, tag_name):
tagd = dict()
user_obj = None
tag_obj = None
tags = models.Tag.objects.extra(
select=dict(post_id=.format(
*it.imap( connection.ops.quote_name,
(, ) ) )),
tables=[],
where=[
.format(*it.imap( connection.ops.quote_name,
(, , , ) )),
... | Adds a qtags property in every post object in a page.
Use "qtags" instead of "tags" in templates to avoid unnecesary DB hits. |
345,087 | def from_header(self, binary):
if binary is None:
return span_context_module.SpanContext(from_header=False)
try:
data = Header._make(struct.unpack(BINARY_FORMAT, binary))
except struct.error:
logging.warning(
... | Generate a SpanContext object using the trace context header.
The value of enabled parsed from header is int. Need to convert to
bool.
:type binary: bytes
:param binary: Trace context header which was extracted from the
request headers.
:rtype: :class:`~o... |
345,088 | def p_ExtendedAttributeIdent(p):
p[0] = model.ExtendedAttribute(
name=p[1],
value=model.ExtendedAttributeValue(name=p[3])) | ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER |
345,089 | def _refresh(self):
padding = self.height()
css_base =
css_oxygen =
if self._application_style == :
css_template = css_oxygen
else:
css_template = css_base
css = css_template.format(padding=padding)
self.setStyleSheet(css)
... | After an application style change, the paintEvent updates the
custom defined stylesheet. |
345,090 | def default_grid(n_items, max_cols=4, min_cols=3):
def in_bounds(val):
return np.clip(val, min_cols, max_cols)
if n_items <= max_cols:
return 1, n_items
ideal = in_bounds(round(n_items ** 0.5))
for offset in (0, 1, -1, 2, -2):
cols = in_bounds(ideal + offset)
ro... | Make a grid for subplots.
Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can,
but allows for custom logic
Parameters
----------
n_items : int
Number of panels required
max_cols : int
Maximum number of columns, inclusive
min_cols : int
Minimum number of... |
345,091 | def perform_content_negotiation(self, request, force=False):
renderers = self.get_renderers()
conneg = self.get_content_negotiator()
try:
return conneg.select_renderer(request, renderers, self.format_kwarg)
except Exception:
if force:
ret... | Determine which renderer and media type to use render the response. |
345,092 | def render_(cls, data={}, template_=None, layout_=None, **kwargs):
if not template_:
stack = inspect.stack()[1]
module = inspect.getmodule(cls).__name__
module_name = module.split(".")[-1]
action_name = stack[3]
view_name = cls.__name__ ... | To render data to the associate template file of the action view
:param data: The context data to pass to the template
:param template_: The file template to use. By default it will map the classname/action.html
:param layout_: The body layout, must contain {% include __template__ %} |
345,093 | def client_create(self, name, password):
body = {
"name": name,
"password": password
}
response = self._post(url.clients, body=body)
self._check_response(response, 201)
return self._create_response(response).get("client_id") | Create a new client. Uses the POST to /clients interface.
:Args:
* *name*: (str) Name of client
* *password*: (str) Password of client
:Returns: (str) ID of the newly created client. |
345,094 | def __validInputs(self):
try:
float(self.__minVal)
except ValueError as ex:
raise Sitools2Exception(ex)
try:
float(self.__maxVal)
except ValueError as ex:
raise Sitools2Exception(ex)
if float(self... | Validates the inputs of the constructor. |
345,095 | def open(self,
mode=,
encoding: typing.Union[list, tuple, set, str, typing.
Callable] = ):
if in mode:
return io.open(str(self), mode)
if callable(encoding):
return self.open(mode, encoding=encoding(str(sel... | :param mode: the same as the argument `mode` of `builtins.open`
:param encoding: similar to the argument `encoding` of `builtins.open` which is compatible to io.open.
- `encoding='auto'` to automatically detect the encoding.
- `encoding is a <list|tuple|set>` to... |
345,096 | def load(filename, relative_to_module=None, compound=None, coords_only=False,
rigid=False, use_parmed=False, smiles=False, **kwargs):
if relative_to_module:
script_path = os.path.realpath(
sys.modules[relative_to_module].__file__)
file_dir = os.path.dirname(s... | Load a file into an mbuild compound.
Files are read using the MDTraj package unless the `use_parmed` argument is
specified as True. Please refer to http://mdtraj.org/1.8.0/load_functions.html
for formats supported by MDTraj and https://parmed.github.io/ParmEd/html/
readwrite.html for formats supported ... |
345,097 | def list_users(self, limit=20):
parameters = dict()
parameters[] = limit
response = self.request(, parameters)
return response | List the public users in the system.
:param limit: (optional) The number of users to fetch.
:type limit: int | long
:returns: The list of users.
:rtype: list[dict] |
345,098 | def _get_api_events(self, function):
if not (function.valid() and
isinstance(function.properties, dict) and
isinstance(function.properties.get("Events"), dict)
):
return {}
api_events = {}
for event_id, event in ... | Method to return a dictionary of API Events on the function
:param SamResource function: Function Resource object
:return dict: Dictionary of API events along with any other configuration passed to it.
Example: {
FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, Meth... |
345,099 | def get_previous_identifiers(self):
previous_identifiers = None
stack = self.get_run_as_identifiers_stack()
if stack:
if (len(stack) == 1):
previous_identifiers = self.identifiers
else:
previous_identifiers = st... | :returns: SimpleIdentifierCollection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.