Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
365,700 | def ignore_file_extension(self, extension):
logger.info(.format(extension))
self.watcher.ignore_file_extension(extension) | Configure a file extension to be ignored.
:param extension: file extension to be ignored
(ex. .less, .scss, etc) |
365,701 | def pricing(sort=, **kwargs):
for name, provider in env.providers.items():
print name
provider.pricing(sort, **kwargs)
print | Print pricing tables for all enabled providers |
365,702 | def nextstate(self, newstate, treenode=None, user_data=None):
if newstate is None:
return self
if isinstance(newstate, State) and id(newstate) != id(self):
return newstate
elif isinstance(newstate, StateEvent):
self.state_register.named_events[newstat... | Manage transition of state. |
365,703 | def validate_address(self, address_deets):
request = self._post(, address_deets)
return self.responder(request) | Validates a customer address and returns back a collection of address matches. |
365,704 | def send_cmd(self, command, connId=):
thisConn = self.__getConnection(connId)
outputMsg = ""
try:
outputMsg += str(thisConn.sendcmd(command))
except ftplib.all_errors as e:
raise FtpLibraryError(str(e))
if self.printOutput:
logger.info... | Sends any command to FTP server. Returns server output.
Parameters:
- command - any valid command to be sent (invalid will result in exception).
- connId(optional) - connection identifier. By default equals 'default'
Example:
| send cmd | HELP | |
365,705 | def get_proxies(self, quantity, type):
url_queue = Queue()
need_pages = int(math.ceil(quantity/15))
if type == 1:
base_url = self.domestic_gn_url
elif type == 2:
base_url = self.domestic_pt_url
elif type == 3:
... | quantity: 数量
type: 类型
1.国内高匿代理
2.国内普通代理
3.国外高匿代理
4.国外普通代理 |
365,706 | def _update_libdata(self, line):
if re.match(, line, re.IGNORECASE):
comments = re.findall(, line)
for c in comments:
self._parse_meta_info(c)
self._parse_compound_info(c)
... | Update the library meta data from the current line being parsed
Args:
line (str): The current line of the of the file being parsed |
365,707 | def send(self, sender: PytgbotApiBot):
return sender.send_sticker(
sticker=self.sticker, chat_id=self.receiver, reply_to_message_id=self.reply_id, disable_notification=self.disable_notification, reply_markup=self.reply_markup
) | Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage |
365,708 | def update(self, callback=None, errback=None, parent=True, **kwargs):
if not self.data:
raise AddressException()
def success(result, *args):
self.data = result
self.id = result[]
self.prefix = result[]
self.type = result[]
... | Update address configuration. Pass a list of keywords and their values to
update. For the list of keywords available for address configuration, see :attr:`ns1.rest.ipam.Addresses.INT_FIELDS` and :attr:`ns1.rest.ipam.Addresses.PASSTHRU_FIELDS` |
365,709 | def notify(self, data):
string_channels = {
ChannelIdentifiers.de_registrations,
ChannelIdentifiers.registrations_expired
}
if data[] in string_channels:
message = {: data["value"], : data["channel"]}
else:
message = DeviceStateCh... | Notify this channel of inbound data |
365,710 | def add_type_struct_or_union(self, name, interp, node):
self.add_type_class(name, StructUnionDef(name, interp, node)) | Store the node with the name. When it is instantiated,
the node itself will be handled.
:name: name of the typedefd struct/union
:node: the union/struct node
:interp: the 010 interpreter |
365,711 | def show(ctx, project_id, backend):
try:
project = ctx.obj[].get(project_id, backend)
except IOError:
raise Exception("Error: the projects database file doesnviewview'].project_with_activities(project) | Shows the details of the given project id. |
365,712 | def generation_time(self):
timestamp = struct.unpack(">I", self.__id[0:4])[0]
return datetime.datetime.fromtimestamp(timestamp, utc) | A :class:`datetime.datetime` instance representing the time of
generation for this :class:`ObjectId`.
The :class:`datetime.datetime` is timezone aware, and
represents the generation time in UTC. It is precise to the
second. |
365,713 | def effsnr(snr, reduced_x2, fac=250.):
snr = numpy.array(snr, ndmin=1, dtype=numpy.float64)
rchisq = numpy.array(reduced_x2, ndmin=1, dtype=numpy.float64)
esnr = snr / (1 + snr ** 2 / fac) ** 0.25 / rchisq ** 0.25
if hasattr(snr, ):
return esnr
else:
return esnr[0] | Calculate the effective SNR statistic. See (S5y1 paper) for definition. |
365,714 | def cli(env, name, public):
image_mgr = SoftLayer.ImageManager(env.client)
images = []
if public in [False, None]:
for image in image_mgr.list_private_images(name=name,
mask=image_mod.MASK):
images.append(image)
if public in ... | List images. |
365,715 | def get_autoregressive_bias(max_length: int, dtype: str = C.DTYPE_FP32) -> mx.sym.Symbol:
length_array = mx.sym.arange(max_length, dtype=dtype)
bias = mx.sym.broadcast_greater(mx.sym.reshape(length_array, shape=(1, -1)),
mx.sym.reshape(length_array, shape=(-1, 1)))
... | Returns bias/mask to ensure position i can only attend to positions <i.
:param max_length: Sequence length.
:param dtype: dtype of bias
:return: Bias symbol of shape (1, max_length, max_length). |
365,716 | def touch(self, key, expire=0, noreply=None):
if noreply is None:
noreply = self.default_noreply
key = self.check_key(key)
cmd = b + key + b + six.text_type(expire).encode()
if noreply:
cmd += b
cmd += b
results = self._misc_cmd([cmd], b, ... | The memcached "touch" command.
Args:
key: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional bool, True to not wait for the reply (defaults to
... |
365,717 | def __CheckValid(self, value):
"check for validity of value"
val = self.__val
self.is_valid = True
try:
val = set_float(value)
if self.__min is not None and (val < self.__min):
self.is_valid = False
val = self.__min
if s... | check for validity of value |
365,718 | def get_range(self, i):
try:
m = i.match(RE_INT_ITER)
if m:
return self.get_int_range(*m.groups())
m = i.match(RE_CHR_ITER)
if m:
return self.get_char_range(*m.groups())
except Exception:
... | Check and retrieve range if value is a valid range.
Here we are looking to see if the value is series or range.
We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). |
365,719 | def _begin(self, retry_id=None):
if self.in_progress:
msg = _CANT_BEGIN.format(self._id)
raise ValueError(msg)
transaction_response = self._client._firestore_api.begin_transaction(
self._client._database_string,
options_=self._options_protobuf(re... | Begin the transaction.
Args:
retry_id (Optional[bytes]): Transaction ID of a transaction to be
retried.
Raises:
ValueError: If the current transaction has already begun. |
365,720 | def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname):
key = idfobject.obj[0].upper()
keyi = data.dtls.index(key)
fieldi = idfobject.objls.index(fieldname)
thiscommdct = commdct[keyi][fieldi]
return thiscommdct | get the idd comment for the field |
365,721 | def create_circuit(name, provider_id, circuit_type, description=None):
nb_circuit_provider = get_(, , provider_id)
nb_circuit_type = get_(, , slug=slugify(circuit_type))
if nb_circuit_provider and nb_circuit_type:
payload = {
: name,
: nb_circuit_provider[],
... | .. versionadded:: 2019.2.0
Create a new Netbox circuit
name
Name of the circuit
provider_id
The netbox id of the circuit provider
circuit_type
The name of the circuit type
asn
The ASN of the circuit provider
description
The description of the circuit
... |
365,722 | def render_select_site_form(self, request, context, form_url=):
app_label = self.opts.app_label
context.update({
: self.has_change_permission(request),
: mark_safe(form_url),
: self.opts,
: True,
: self.save_on_top,
})
... | Render the site choice form. |
365,723 | def _get_alpha(self, C, vs30, pga_rock):
alpha = np.zeros(len(pga_rock))
idx = vs30 < C["k1"]
if np.any(idx):
af1 = pga_rock[idx] +\
self.CONSTS["c"] * ((vs30[idx] / C["k1"]) ** self.CONSTS["n"])
af2 = pga_rock[idx] + self.CONSTS["c"]
... | Returns the alpha, the linearised functional relationship between the
site amplification and the PGA on rock. Equation 31. |
365,724 | def headpart_types(self, method, input=True):
if input:
headers = method.soap.input.headers
else:
headers = method.soap.output.headers
return [self.__part_type(h.part, input) for h in headers] | Get a list of header I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: A service method.
@type method: I{service.Method}
... |
365,725 | def _send_command(self, command, expected_bytes):
response = self.con.send_xid_command(command, expected_bytes)
return response | Send an XID command to the device |
365,726 | def run_migrations_offline():
url = winchester_config[][]
context.configure(url=url)
with context.begin_transaction():
context.run_migrations() | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. |
365,727 | def process_management_config_section(config, management_config):
if in management_config:
for command in management_config[]:
config.management[].append(command) | Processes the management section from a configuration data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param management_config: Management section from a config data dict. |
365,728 | def defUtilityFuncs(self):
self.u = lambda c : utility(c,gam=self.CRRA)
self.uP = lambda c : utilityP(c,gam=self.CRRA)
self.uPP = lambda c : utilityPP(c,gam=self.CRRA) | Defines CRRA utility function for this period (and its derivatives),
saving them as attributes of self for other methods to use.
Parameters
----------
none
Returns
-------
none |
365,729 | def main(output):
from hbp_knowledge import get_graph
graph = get_graph()
text = to_html(graph)
print(text, file=output) | Output the HBP knowledge graph to the desktop |
365,730 | def run(self):
init_folder = os.getcwd()
os.chdir(self.folder)
with zopen(self.log_file, ) as fout:
subprocess.call([self._NWCHEM2FIESTA_cmd, self._nwcheminput_fn,
self._nwchemoutput_fn, self._nwchemmovecs_fn],
stdou... | Performs actual NWCHEM2FIESTA run |
365,731 | def get_footnote_backreferences(text, markdown_obj):
footnotes = OrderedDict()
for footnote_id, footnote in re_footnote_backreferences.findall(text):
footnote_id = re.sub(r, r, footnote_id).lower().strip()
footnote = re.sub(r, , footnote, flags=re.M)
footnotes[footnote_id] = footnot... | Retrieves all footnote backreferences within the text.
Fotnote backreferences can be defined anywhere in the text, and
look like this:
[^id]: text
The corresponding footnote reference can then be placed anywhere in
the text
This is some text.[^id]
Footnote IDs are case insensiti... |
365,732 | def update_payload(self, fields=None):
payload = super(DiscoveryRule, self).update_payload(fields)
if in payload:
payload[] = payload.pop()
return {u: payload} | Wrap submitted data within an extra dict. |
365,733 | def state_get(self, block_id, addresses):
block = self._get_blocks([block_id.hex()])[0]
block_header = BlockHeader()
block_header.ParseFromString(block.header)
try:
state_view = self._state_view_factory.create_view(
block_header.state_root_hash)
... | Returns a list of address/data pairs (str, bytes) |
365,734 | def p_statement_expr(self, t):
if len(t)<3 :
self.accu.add(Term(, [t[1]]))
print(, t[1])
else :
self.accu.add(Term(, ["gen(\""+t[1]+"\")","gen(\""+t[3]+"\")"]))
self.accu.add(Term(, ["gen(\""+t[1]+"\")","gen(\""+t[3]+"\")",t[2]])) | statement : node_expression PLUS node_expression
| node_expression MINUS node_expression |
365,735 | def do_cli(ctx, host, port, template, env_vars, debug_port, debug_args,
debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image,
force_image_build, parameter_overrides):
LOG.debug("local start_lambda command is called")
try:
... | Implementation of the ``cli`` method, just separated out for unit testing purposes |
365,736 | def split_(self, col: str) -> "list(Ds)":
try:
dss = {}
unique = self.df[col].unique()
for key in unique:
df2 = self.df.loc[self.df[col] == key]
ds2 = self._duplicate_(df2)
dss[key] = ds2
return dss
... | Split the main dataframe according to a column's unique values and
return a dict of dataswim instances
:return: list of dataswim instances
:rtype: list(Ds)
:example: ``dss = ds.slit_("Col 1")`` |
365,737 | def show_rich_text(self, text, collapse=False, img_path=):
self.switch_to_plugin()
self.switch_to_rich_text()
context = generate_context(collapse=collapse, img_path=img_path,
css_path=self.css_path)
self.render_sphinx_doc(text, context) | Show text in rich mode |
365,738 | def _req_files_move(self, pid, fids):
url = self.web_api_url +
data = {}
data[] = pid
for i, fid in enumerate(fids):
data[ % i] = fid
req = Request(method=, url=url, data=data)
res = self.http.send(req)
if res.state:
return True
... | Move files or directories
:param str pid: destination directory id
:param list fids: a list of ids of files or directories to be moved |
365,739 | def apply_raw(self):
try:
result = reduction.reduce(self.values, self.f, axis=self.axis)
except Exception:
result = np.apply_along_axis(self.f, self.axis, self.values)
if result.ndim == 2:
return self.obj._constructor(result,
... | apply to the values as a numpy array |
365,740 | def auth(**kwargs):
option =
path = kwargs[]
key = kwargs[]
if kwargs[]:
option =
if kwargs[]:
output, err = cli_syncthing_adapter.auth(option, key, path)
click.echo("%s" % output, err=err)
else:
verb = if not kwargs[] else
if click.confirm("Are you sure you want to %s thi... | Authorize device synchronization. |
365,741 | def getsinIm(alat):
alat = np.float64(alat)
return 2*np.sin(np.radians(alat))/np.sqrt(4 - 3*np.cos(np.radians(alat))**2) | Computes sinIm from modified apex latitude.
Parameters
==========
alat : array_like
Modified apex latitude
Returns
=======
sinIm : ndarray or float |
365,742 | def bulk_record_workunits(self, engine_workunits):
for workunit in engine_workunits:
duration = workunit[] - workunit[]
span = zipkin_span(
service_name="pants",
span_name=workunit[],
duration=duration,
span_storage=self.span_storage,
)
span.zipkin_attrs... | A collection of workunits from v2 engine part |
365,743 | def shape_offset_y(self):
min_y = self._start_y
for drawing_operation in self:
if hasattr(drawing_operation, ):
min_y = min(min_y, drawing_operation.y)
return min_y | Return y distance of shape origin from local coordinate origin.
The returned integer represents the topmost extent of the freeform
shape, in local coordinates. Note that the bounding box of the shape
need not start at the local origin. |
365,744 | def to_decimal(alpha_number, alphabet=ALPHABET, default=_marker):
num = api.to_int(alpha_number, default=None)
if num is not None:
return num
alpha_number = str(alpha_number)
regex = re.compile(r"([A-Z]+)(\d+)", re.IGNORECASE)
matches = re.findall(regex, alpha_number)
if not matche... | Converts an alphanumeric code (e.g AB12) to an integer
:param alpha_number: representation of an alphanumeric code
:param alphabet: alphabet to use when alpha_number is a non-int string
:type number: int, string, Alphanumber, float
:type alphabet: string |
365,745 | def set_children(self, child_ids):
if not isinstance(child_ids, list):
raise errors.InvalidArgument()
if self.get_children_metadata().is_read_only():
raise errors.NoAccess()
idstr_list = []
for object_id in child_ids:
if not self._is_valid_id(... | Sets the children.
arg: child_ids (osid.id.Id[]): the children``Ids``
raise: InvalidArgument - ``child_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* |
365,746 | def create( cls, model, parent = None, uifile = , commit = True ):
dlg = QDialog(parent)
dlg.setWindowTitle( % model.schema().name())
cls = model.schema().property(, cls)
widget = cls(dlg)
if ( uifile ):
widget.... | Prompts the user to create a new record for the inputed table.
:param model | <subclass of orb.Table>
parent | <QWidget>
:return <orb.Table> || None/ | instance of the inputed table class |
365,747 | def write_all_files(filename, data, wref_data=None, params=None):
if len(data.shape) == 1:
shape = (1, 1, 1)
elif len(data.shape) == 2:
shape = (data.shape[0], 1, 1)
elif len(data.shape) == 3:
shape = (data.shape[0], data.shape[1], 1)
elif len(data.shape) == 4:
... | Creates an LCModel control file for processing the supplied MRSData, and
optional water reference data, updating the default parameters with any
values supplied through params.
:param filename: the location where the control file should be saved.
:param data: MRSData to be processed.
:param wref_da... |
365,748 | def get_average_record(self, n):
history_deque = collections.deque()
averages = []
for d in self.data_points:
history_deque.appendleft(d)
if len(history_deque) > n:
history_deque.pop()
avg = sum(history_deque) / len(history_deque)
... | Returns a list of average current numbers, each representing the
average over the last n data points.
Args:
n: Number of data points to average over.
Returns:
A list of average current values. |
365,749 | def p_encaps_var_object_property(p):
p[0] = ast.ObjectProperty(ast.Variable(p[1], lineno=p.lineno(1)), p[3],
lineno=p.lineno(2)) | encaps_var : VARIABLE OBJECT_OPERATOR STRING |
365,750 | def default_to_hashed_rows(self, default=None):
if default is not None:
self._default_to_hashed_rows = (default is True)
return self._default_to_hashed_rows | Gets the current setting with no parameters, sets it if a boolean is passed in
:param default: the value to set
:return: the current value, or new value if default is set to True or False |
365,751 | def mk_examples_menu(text, root_dir=None, depth=0):
examples_dir = ide_utils.get_example_dir()
if not examples_dir:
return None, []
root_dir = root_dir or examples_dir
file_actions = []
menu = Gio.Menu.new()
base_item = Gio.MenuItem.new_submenu(text, menu)
for f... | :return: base_item, rel_paths |
365,752 | def add_reporter(self, reporter):
with self._lock:
reporter.init(list(self.metrics.values()))
self._reporters.append(reporter) | Add a MetricReporter |
365,753 | def orthogonal(name, shape, scale=1.1, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True):
r
flat_shape = (shape[0], np.prod(shape[1:]))
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
q = u if u.shape == flat_shape else v
q = q.re... | r"""Creates a tensor variable of which initial values are of
an orthogonal ndarray.
See [Saxe et al. 2014.](http://arxiv.org/pdf/1312.6120.pdf)
Args:
name: The name of new variable.
shape: A tuple/list of integers.
scale: A Python scalar.
dtype: Either float32 or float64.
... |
365,754 | def get_init(self, filename="__init__.py"):
import ast
with open(filename) as init_file:
module = ast.parse(init_file.read())
itr = lambda x: (ast.literal_eval(node.value) for node in ast.walk(module) \
if isinstance(node, ast.Assign) and node.targets[0].id == ... | Get various info from the package without importing them |
365,755 | def format_url(url: str, url_vars: Mapping[str, Any]) -> str:
url = urllib.parse.urljoin(DOMAIN, url)
expanded_url: str = uritemplate.expand(url, var_dict=url_vars)
return expanded_url | Construct a URL for the GitHub API.
The URL may be absolute or relative. In the latter case the appropriate
domain will be added. This is to help when copying the relative URL directly
from the GitHub developer documentation.
The dict provided in url_vars is used in URI template formatting. |
365,756 | def generate_method(service_module, service_name, method_name):
assert service_module
assert service_name
assert method_name
args_type = getattr(service_module, method_name + )
result_type = getattr(service_module, method_name + , None)
serializer = ThriftSerializer(result_type)
... | Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called |
365,757 | def _get_stack_info_for_trace(
self,
frames,
library_frame_context_lines=None,
in_app_frame_context_lines=None,
with_locals=True,
locals_processor_func=None,
):
return list(
iterate_with_template_sources(
frames,
... | If the stacktrace originates within the elasticapm module, it will skip
frames until some other module comes up. |
365,758 | def __setLock(self, command):
if command in (TURN_ON, TURN_OFF):
self._operation = command
elif command in INV_SOURCES:
self._operation = SOURCE
else:
self._operation = ALL
self._isLocked = True
self._timer = time.time() | Set lock on requests. |
365,759 | def _create_more_application():
from prompt_toolkit.shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding()
@registry.add_binding()
@registry.add_binding()
@registry.add_binding(Keys.ControlJ)
@registry.add_binding(Keys.ControlI)
def _(event):
... | Create an `Application` instance that displays the "--MORE--". |
365,760 | def retrieveVals(self):
name =
if self.hasGraph(name):
for fspath in self._fslist:
if self._statsSpace.has_key(fspath):
self.setGraphVal(name, fspath,
self._statsSpace[fspath][])
name =
if se... | Retrieve values for graphs. |
365,761 | def argsort(self, axis=-1, kind=, order=None):
index_array = np.core.fromnumeric._wrapit(self, , axis,
kind, order)
index_array = index_array.view(np.ndarray)
return index_array | Returns the indices that would sort an array.
.. note::
This method wraps `numpy.argsort`. This documentation is
modified from that of `numpy.argsort`.
Perform an indirect sort along the given axis using the algorithm
specified by the `kind` keyword. It ret... |
365,762 | def query_random(num=6, kind=):
return TabWiki.select().where(
TabWiki.kind == kind
).order_by(
peewee.fn.Random()
).limit(num) | Query wikis randomly. |
365,763 | def sign(self, value):
payload = struct.pack(, self.version, int(time.time()))
payload += force_bytes(value)
return payload + self.signature(payload).finalize() | :type value: any
:rtype: bytes |
365,764 | def limits_hydrate(db, lims):
return [limits.Limit.hydrate(db, lim) for lim in lims] | Helper function to hydrate a list of limits.
:param db: A database handle.
:param lims: A list of limit strings, as retrieved from the
database. |
365,765 | def isdir(self, dirname):
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
if not path.endswith("/"):
path += "/"
r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/")
if r.get("Contents") or r.get("CommonPrefixes"):
... | Returns whether the path is a directory or not. |
365,766 | def SplitMeta(meta):
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
% meta)
return meta[:n // 2], meta[n // 2:] | Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it. |
365,767 | def cmd_link_add(self, args):
descriptor = args[0]
print("Adding link %s" % descriptor)
self.link_add(descriptor) | add new link |
365,768 | def concat_same_type(self, to_concat, placement=None):
values = self._concatenator([blk.values for blk in to_concat],
axis=self.ndim - 1)
return self.make_block_same_class(
values, placement=placement or slice(0, len(values), 1)) | Concatenate list of single blocks of the same type. |
365,769 | def is_callable(instance, attribute, value):
if not callable(value):
raise TypeError(" must be callable".format(attribute.name)) | Raises a :exc:`TypeError` if the value is not a callable. |
365,770 | def initialize_communities_bucket():
bucket_id = UUID(current_app.config[])
if Bucket.query.get(bucket_id):
raise FilesException("Bucket with UUID {} already exists.".format(
bucket_id))
else:
storage_class = current_app.config[]
location = Location.get_default()
... | Initialize the communities file bucket.
:raises: `invenio_files_rest.errors.FilesException` |
365,771 | def _rd_dat_signals(file_name, dir_name, pb_dir, fmt, n_sig, sig_len,
byte_offset, samps_per_frame, skew, sampfrom, sampto,
smooth_frames):
tsamps_per_frame = sum(samps_per_frame)
read_len = sampto - sampfrom
(start_byte, n_read_samples, block_floo... | Read all signals from a WFDB dat file.
Parameters
----------
file_name : str
The name of the dat file
* other params
See docstring for `_rd_segment`.
Returns
-------
signals : numpy array, or list
See docstring for `_rd_segment`.
Notes
-----
See docstri... |
365,772 | def rest_api_url(self, *url_parts, **kwargs):
url_parts = list(url_parts)
if url_parts and re.match(r, url_parts[0]):
return .join(url_parts)
relative = kwargs.pop(, False)
api_ver = kwargs.pop(, None)
api_ver = api_ver if api_ver is not None else self.api_ve... | Join the URL of REST_API
parameters:
upl_parts: strings that are joined to the url by "/".
a REST url like https://na1.salesforce.com/services/data/v44.0/
is usually added, but not if the first string starts with https://
api_ver: API version that shoul... |
365,773 | def _build_youtube_dl(worker, destdir, site):
class _YoutubeDL(youtube_dl.YoutubeDL):
logger = logging.getLogger(__module__ + "." + __qualname__)
def urlopen(self, req):
try:
url = req.full_url
except AttributeError:
url = req
... | Builds a `youtube_dl.YoutubeDL` for brozzling `site` with `worker`.
The `YoutubeDL` instance does a few special brozzler-specific things:
- keeps track of urls fetched using a `YoutubeDLSpy`
- periodically updates `site.last_claimed` in rethinkdb
- if brozzling through warcprox and downloading segment... |
365,774 | def send_zipfile(request, fileList):
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, , zipfile.ZIP_DEFLATED)
for artist,files in fileList.iteritems():
for f in files:
archive.write(f[0], % (artist, f[1]))
archive.close()
wrapper = FixedFileWrapper(temp)
... | Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files. |
365,775 | def _cons(self, word, i):
if word[i] in self.vowels:
return False
if word[i] == :
if i == 0:
return True
else:
return (not self._cons(word, i - 1))
return True | cons(i) is TRUE <=> b[i] is a consonant. |
365,776 | def delete_relationship(self, session, data, api_type, obj_id, rel_key):
model = self._fetch_model(api_type)
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.EDIT)
relationship = self._get_relationship(resource, rel_key,
... | Delete a resource or multiple resources from a to-many relationship.
:param session: SQLAlchemy session
:param data: JSON data provided with the request
:param api_type: Type of the resource
:param obj_id: ID of the resource
:param rel_key: Key of the relationship to fetch |
365,777 | def draw_graph(graph_instance, map_coloring = None):
if (graph_instance.space_description is None):
raise NameError("The graph haven
if (x_maximum < graph_instance.space_description[i][0]): x_maximum = graph_instance.space_description[i][0];
if (x_minimum > graph_instanc... | !
@brief Draw graph.
@param[in] graph_instance (graph): Graph that should be drawn.
@param[in] map_coloring (list): List of color indexes for each vertex. Size of this list should be equal to size of graph (number of vertices).
If it's not specified (None) than grap... |
365,778 | def get_time_slice(time, z, zdot=None, timeStart=None, timeEnd=None):
if timeStart == None:
timeStart = time[0]
if timeEnd == None:
timeEnd = time[-1]
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]... | Get slice of time, z and (if provided) zdot from timeStart to timeEnd.
Parameters
----------
time : ndarray
array of time values
z : ndarray
array of z values
zdot : ndarray, optional
array of zdot (velocity) values.
timeStart : float, optional
time at which to ... |
365,779 | def push(self, files, run=None, entity=None, project=None, description=None, force=True, progress=False):
if project is None:
project = self.get_project()
if project is None:
raise CommError("No project configured.")
if run is None:
run = self.current... | Uploads multiple files to W&B
Args:
files (list or dict): The filenames to upload
run (str, optional): The run to upload to
entity (str, optional): The entity to scope this project to. Defaults to wandb models
project (str, optional): The name of the project to ... |
365,780 | def remove_config(chassis_id=None,
community=None,
contact=None,
location=None,
test=False,
commit=True,
**kwargs):
*abcd
dic = {
: ,
: test,
: commit
}
if chassis_id:... | Removes a configuration element from the SNMP configuration.
:param chassis_id: (optional) Chassis ID
:param community: (optional) A dictionary having the following optional keys:
- acl (if any policy / ACL need to be set)
- mode: rw or ro. Default: ro
:param contact: Contact details
:param... |
365,781 | def create(self, timeout=values.unset, priority=values.unset,
task_channel=values.unset, workflow_sid=values.unset,
attributes=values.unset):
data = values.of({
: timeout,
: priority,
: task_channel,
: workflow_sid,
... | Create a new TaskInstance
:param unicode timeout: The amount of time in seconds the task is allowed to live up to a maximum of 2 weeks.
:param unicode priority: Override priority for the Task.
:param unicode task_channel: When MultiTasking is enabled specify the type of the task by passing eith... |
365,782 | def run(dest, router, args, deadline=None, econtext=None):
if econtext is not None:
mitogen.parent.upgrade_router(econtext)
context_id = router.allocate_id()
fakessh = mitogen.parent.Context(router, context_id)
fakessh.name = u % (context_id,)
sock1, sock2 = socket.socketpair()
s... | Run the command specified by `args` such that ``PATH`` searches for SSH by
the command will cause its attempt to use SSH to execute a remote program
to be redirected to use mitogen to execute that program using the context
`dest` instead.
:param list args:
Argument vector.
:param mitogen.co... |
365,783 | def set_resize_parameters(
self,
degrad=6,
labels=None,
resize_mm=None,
resize_voxel_number=None,
):
logger.debug("set_resize_parameters(\ndegrad={}, \nlabels={}\nresize_mm={}\nresize_voxel_number={}".format(
degrad,... | set_input_data() should be called before
:param degrad:
:param labels:
:param resize_mm:
:param resize_voxel_number:
:return: |
365,784 | def load_policy_config(filters=None,
prepend=True,
pillar_key=,
pillarenv=None,
saltenv=None,
merge_pillar=True,
only_lower_merge=False,
revision_id=None,
... | Generate and load the configuration of the whole policy.
.. note::
The order of the filters and their terms is very important.
The configuration loaded on the device respects the order
defined in the ``filters`` and/or inside the pillar.
When merging the ``filters`` with the pilla... |
365,785 | def promote(self, name):
return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items()))) | Promote to a PartitionName by combining with a bundle Name. |
365,786 | def scheduled_status_delete(self, id):
id = self.__unpack_id(id)
url = .format(str(id))
self.__api_request(, url) | Deletes a scheduled status. |
365,787 | def create_api_key(self, body, params=None):
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument .")
return self.transport.perform_request(
"PUT", "/_security/api_key", params=params, body=body
) | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html>`_
:arg body: The api key request to create an API key
:arg refresh: If `true` (the default) then refresh the affected shards
to make this operation visible to search, if `wait_for` then wait
... |
365,788 | async def process_ltd_doc(session, github_api_token, ltd_product_url,
mongo_collection=None):
logger = logging.getLogger(__name__)
ltd_product_data = await get_ltd_product(session, url=ltd_product_url)
product_name = ltd_product_data[]
doc_handle_match = DOCUMENT_HA... | Ingest any kind of LSST document hosted on LSST the Docs from its
source.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
github_api_token : `str`
A GitHub personal AP... |
365,789 | def add_header_callback(self, cb, port, channel, port_mask=0xFF,
channel_mask=0xFF):
self.cb.append(_CallbackContainer(port, port_mask,
channel, channel_mask, cb)) | Add a callback for a specific port/header callback with the
possibility to add a mask for channel and port for multiple
hits for same callback. |
365,790 | def _check_required_settings(batches):
required_settings = [
,
]
for batch in batches:
for txn in batch.transactions:
txn_header = TransactionHeader()
txn_header.ParseFromString(txn.header)
if txn_header.family_name == :
settings_... | Ensure that all settings required at genesis are set. |
365,791 | def kernel_command_line(self, kernel_command_line):
log.info(.format(name=self._name,
id=self._id,
... | Sets the kernel command line for this QEMU VM.
:param kernel_command_line: QEMU kernel command line |
365,792 | def get_plugin(self, service_provider=None, auth_url=None, plugins=None,
**kwargs):
plugins = plugins or []
if utils.get_keystone_version() < 3 or not service_provider:
return None
keystone_idp_id = getattr(settings, ,
... | Authenticate using keystone to keystone federation.
This plugin uses other v3 plugins to authenticate a user to a
identity provider in order to authenticate the user to a service
provider
:param service_provider: service provider ID
:param auth_url: Keystone auth url
:p... |
365,793 | def v1(self):
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a1], Va[self.a1]) | Return voltage phasors at the "from buses" (bus1) |
365,794 | def revoke_permission(user, permission_name):
roles = get_user_roles(user)
for role in roles:
if permission_name in role.permission_names_list():
permission = get_permission(permission_name)
user.user_permissions.remove(permission)
return
raise RolePermissi... | Revoke a specified permission from a user.
Permissions are only revoked if they are in the scope any of the user's
roles. If the permission is out of scope, a RolePermissionScopeException
is raised. |
365,795 | def _downgrade_v4(op):
op.drop_index()
op.drop_index()
op.execute("UPDATE equities SET exchange = exchange_full")
with op.batch_alter_table() as batch_op:
batch_op.drop_column()
op.create_index(,
table_name=,
columns=[])
op.create_index(,
... | Downgrades assets db by copying the `exchange_full` column to `exchange`,
then dropping the `exchange_full` column. |
365,796 | def Drop(self: Iterable, n):
con = tuple(self)
n = len(con) - n
if n <= 0:
yield from con
else:
for i, e in enumerate(con):
if i == n:
break
yield e | [
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [1, 2]
}
] |
365,797 | def _gen_records(self, record, zone_id, creating=False):
return _Route53Record.new(self, record, zone_id, creating) | Turns an octodns.Record into one or more `_Route53*`s |
365,798 | def plus_dora(tile, dora_indicators):
tile_index = tile // 4
dora_count = 0
for dora in dora_indicators:
dora //= 4
if tile_index < EAST:
if dora == 8:
dora = -1
elif dora == 17:
dora = 8
elif d... | :param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora |
365,799 | def read_numpy_text (self, dfcols=None, **kwargs):
import numpy as np
if dfcols is not None:
kwargs[] = True
retval = np.loadtxt (text_type (self), **kwargs)
if dfcols is not None:
import pandas as pd
if isinstance (dfcols, six.string_types... | Read this path into a :class:`numpy.ndarray` as a text file using
:func:`numpy.loadtxt`. In normal conditions the returned array is
two-dimensional, with the first axis spanning the rows in the file and
the second axis columns (but see the *unpack* and *dfcols* keywords).
If *dfcols* is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.