positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def get_instance(self, payload):
"""
Build an instance of AssignedAddOnExtensionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance
:rt... | Build an instance of AssignedAddOnExtensionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionInstance
:rtype: twilio.rest.api.v2010.account.incoming_phone_num... |
def requested_packages(self, include_implicit=False):
"""Get packages in the request.
Args:
include_implicit (bool): If True, implicit packages are appended
to the result.
Returns:
List of `PackageRequest` objects.
"""
if include_implicit... | Get packages in the request.
Args:
include_implicit (bool): If True, implicit packages are appended
to the result.
Returns:
List of `PackageRequest` objects. |
async def auth(self):
"""Perform AirPlay device authentication."""
credentials = await self.atv.airplay.generate_credentials()
await self.atv.airplay.load_credentials(credentials)
try:
await self.atv.airplay.start_authentication()
pin = await _read_input(self.loo... | Perform AirPlay device authentication. |
def accept_response(self,
response_header,
content=EmptyValue,
content_type=EmptyValue,
accept_untrusted_content=False,
localtime_offset_in_seconds=0,
timestamp_skew_in_seconds... | Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=E... |
def generate_entities(ctx, output_path, mtz_file, exclude_namespace, namespace, maltego_entities, append, entity):
"""Converts Maltego entity definition files to Canari python classes.
Excludes Maltego built-in entities by default."""
from canari.commands.generate_entities import generate_entities
gener... | Converts Maltego entity definition files to Canari python classes.
Excludes Maltego built-in entities by default. |
def load_file(self, fname, table=None, sep="\t", bins=False, indexes=None):
"""
use some of the machinery in pandas to load a file into a table
Parameters
----------
fname : str
filename or filehandle to load
table : str
table to load the file t... | use some of the machinery in pandas to load a file into a table
Parameters
----------
fname : str
filename or filehandle to load
table : str
table to load the file to
sep : str
CSV separator
bins : bool
add a "bin" colu... |
def find_course_by_crn(self, crn):
"""Searches all courses by CRNs. Not particularly efficient.
Returns None if not found.
"""
for name, course in self.courses.iteritems():
if crn in course:
return course
return None | Searches all courses by CRNs. Not particularly efficient.
Returns None if not found. |
def __make_client(self):
"Make this node a client"
notice('Making client, getting server connection', self.color)
self.mode = 'c'
addr = utils.get_existing_server_addr()
sock = utils.get_client_sock(addr)
self.__s = sock
with self.__client_list_lock:
s... | Make this node a client |
def GetRpcServer(options):
"""Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made.
"""
rpc_server_class = HttpRpcServer
def GetUserCredentials():
"""Prompts the user for a username and password."""
# Disable status prints so they don't obscure the ... | Returns an instance of an AbstractRpcServer.
Returns:
A new AbstractRpcServer, on which RPC calls can be made. |
def parse_doc(doc):
"""
Parse docstrings to dict, it should look like:
key: value
"""
if not doc:
return {}
out = {}
for s in doc.split('\n'):
s = s.strip().split(':', maxsplit=1)
if len(s) == 2:
out[s[0]] = s[1]
return out | Parse docstrings to dict, it should look like:
key: value |
def karbasa(self, result):
""" Finding if class probabilities are close to eachother
Ratio of the distance between 1st and 2nd class,
to the distance between 1st and last class.
:param result: The dict returned by LM.calculate()
"""
probs = result['all_probs'... | Finding if class probabilities are close to eachother
Ratio of the distance between 1st and 2nd class,
to the distance between 1st and last class.
:param result: The dict returned by LM.calculate() |
def createEditor(self, delegate, parent, option):
""" Creates a ChoiceCtiEditor.
For the parameters see the AbstractCti constructor documentation.
"""
return ChoiceCtiEditor(self, delegate, parent=parent) | Creates a ChoiceCtiEditor.
For the parameters see the AbstractCti constructor documentation. |
def symlink_to_bytes(symlink_target):
# type: (str) -> bytes
'''
A function to generate UDF symlink data from a Unix-like path.
Parameters:
symlink_target - The Unix-like path that is the symlink.
Returns:
The UDF data corresponding to the symlink.
'''
symlink_data = bytearray()
... | A function to generate UDF symlink data from a Unix-like path.
Parameters:
symlink_target - The Unix-like path that is the symlink.
Returns:
The UDF data corresponding to the symlink. |
def set_bandwidth(self, bandwidth):
"""
Sets bandwidth constraint.
:param bandwidth: bandwidth integer value (in Kb/s)
"""
yield from self._hypervisor.send("nio set_bandwidth {name} {bandwidth}".format(name=self._name, bandwidth=bandwidth))
self._bandwidth = bandwidth | Sets bandwidth constraint.
:param bandwidth: bandwidth integer value (in Kb/s) |
def visitParam_def(self, ctx:SystemRDLParser.Param_defContext):
"""
Parameter Definition block
"""
self.compiler.namespace.enter_scope()
param_defs = []
for elem in ctx.getTypedRuleContexts(SystemRDLParser.Param_def_elemContext):
param_def = self.visit(elem)
... | Parameter Definition block |
def _draw_calendar(self, canvas, redraw=False):
"""Draws calendar."""
options = self.__options
# Update labels:
name = self._cal.formatmonthname(self._date.year, self._date.month, 0,
withyear=False)
self._lmonth.configure(text=name.title()... | Draws calendar. |
def _Build(self, storage_file):
"""Builds the event tag index.
Args:
storage_file (BaseStorageFile): storage file.
"""
self._index = {}
for event_tag in storage_file.GetEventTags():
self.SetEventTag(event_tag) | Builds the event tag index.
Args:
storage_file (BaseStorageFile): storage file. |
def left_axis_label(self, label, position=None, rotation=60, offset=0.08,
**kwargs):
"""
Sets the label on the left axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of... | Sets the label on the left axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, 60
The angle of rotation of the label
offset: float,
Used... |
def _find_spherical_axes(self):
"""
Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point
group T molecules have only one unique 3-fold and one unique 2-fold
axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules
have a unique 5-fold axis.
"""
... | Looks for R5, R4, R3 and R2 axes in spherical top molecules. Point
group T molecules have only one unique 3-fold and one unique 2-fold
axis. O molecules have one unique 4, 3 and 2-fold axes. I molecules
have a unique 5-fold axis. |
def print_header(text):
"""Prints header with given text and frame composed of '#' characters."""
print()
print('#'*(len(text)+4))
print('# ' + text + ' #')
print('#'*(len(text)+4))
print() | Prints header with given text and frame composed of '#' characters. |
def _dispatch_change_event(self, object, trait_name, old, new, handler):
""" Prepare and dispatch a trait change event to a listener. """
# Extract the arguments needed from the handler.
args = self.argument_transform(object, trait_name, old, new)
# Send a description of the event to the change event ... | Prepare and dispatch a trait change event to a listener. |
def _matches(self, url, options,
general_re, domain_required_rules, rules_with_options):
"""
Return if ``url``/``options`` are matched by rules defined by
``general_re``, ``domain_required_rules`` and ``rules_with_options``.
``general_re`` is a compiled regex for rules ... | Return if ``url``/``options`` are matched by rules defined by
``general_re``, ``domain_required_rules`` and ``rules_with_options``.
``general_re`` is a compiled regex for rules without options.
``domain_required_rules`` is a {domain: [rules_which_require_it]}
mapping.
``rules... |
def only_path(self):
"""Finds the only path from the start node. If there is more than one,
raises ValueError."""
start = [v for v in self.nodes if self.nodes[v].get('start', False)]
if len(start) != 1:
raise ValueError("graph does not have exactly one start node")
... | Finds the only path from the start node. If there is more than one,
raises ValueError. |
def has_conversion(self, plugin):
"""Return True if the plugin supports this block."""
plugin = kurt.plugin.Kurt.get_plugin(plugin)
return plugin.name in self._plugins | Return True if the plugin supports this block. |
def show_keyword_version_message(sender, keyword_version, inasafe_version):
"""Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the l... | Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the layer's keywords
:type keyword_version: str
:param inasafe_version: The ver... |
def addFilteringOptions(parser, samfileIsPositionalArg=False):
"""
Add options to an argument parser for filtering SAM/BAM.
@param samfileIsPositionalArg: If C{True} the SAM/BAM file must
be given as the final argument on the command line (without
being preceded by --sam... | Add options to an argument parser for filtering SAM/BAM.
@param samfileIsPositionalArg: If C{True} the SAM/BAM file must
be given as the final argument on the command line (without
being preceded by --samfile).
@param parser: An C{argparse.ArgumentParser} instance. |
async def _into_id_set(client, chats):
"""Helper util to turn the input chat or chats into a set of IDs."""
if chats is None:
return None
if not utils.is_list_like(chats):
chats = (chats,)
result = set()
for chat in chats:
if isinstance(chat, int):
if chat < 0:
... | Helper util to turn the input chat or chats into a set of IDs. |
def render_field(parser, token):
"""
Render a form field using given attribute-value pairs
Takes form field as first argument and list of attribute-value pairs for
all other arguments. Attribute-value pairs should be in the form of
attribute=value or attribute="a value" for assignment and attribut... | Render a form field using given attribute-value pairs
Takes form field as first argument and list of attribute-value pairs for
all other arguments. Attribute-value pairs should be in the form of
attribute=value or attribute="a value" for assignment and attribute+=value
or attribute+="value" for append... |
def addRequest(self, service, *args):
"""
Adds a request to be sent to the remoting gateway.
"""
wrapper = RequestWrapper(self, '/%d' % self.request_number,
service, *args)
self.request_number += 1
self.requests.append(wrapper)
if self.logger:
... | Adds a request to be sent to the remoting gateway. |
def cli():
"""\
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder.
"""
with open_client(cache_dir=get_cache_dir()) as client:
tip = client... | \
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder. |
def _create_subepochs(x, nperseg, step):
"""Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
--... | Transform the data into a matrix for easy manipulation
Parameters
----------
x : 1d ndarray
actual data values
nperseg : int
number of samples in each row to create
step : int
distance in samples between rows
Returns
-------
2d ndarray
a view (i.e. doesn'... |
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials):
"""
Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features.
"""
#######################################################################... | Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features. |
def xml_path_completion(xml_path):
"""
Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package
"""
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path =... | Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package |
def run(self):
''' Running the workbench CLI '''
# Announce versions
self.versions()
# Sample/Tag info and Help
self.tags()
print '\n%s' % self.workbench.help('cli')
# Now that we have the Workbench connection spun up, we register some stuff
# with the ... | Running the workbench CLI |
def _meta_schema_factory(self, columns, model, class_mixin):
"""
Creates ModelSchema marshmallow-sqlalchemy
:param columns: a list of columns to mix
:param model: Model
:param class_mixin: a marshamallow Schema to mix
:return: ModelSchema
"""
_model =... | Creates ModelSchema marshmallow-sqlalchemy
:param columns: a list of columns to mix
:param model: Model
:param class_mixin: a marshamallow Schema to mix
:return: ModelSchema |
def _get_prog_memory(resources, cores_per_job):
"""Get expected memory usage, in Gb per core, for a program from resource specification.
"""
out = None
for jvm_opt in resources.get("jvm_opts", []):
if jvm_opt.startswith("-Xmx"):
out = _str_memory_to_gb(jvm_opt[4:])
memory = resou... | Get expected memory usage, in Gb per core, for a program from resource specification. |
def main():
'''
Main function
'''
# We should only steal the root logger if we're the application, not the module
logging.basicConfig(level=logging.DEBUG)
args = get_args()
if args.password:
password = args.password
else:
password = getpass(
prompt='Enter pa... | Main function |
def predict_step(F, covX, filt):
"""Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
... | Predictive step of Kalman filter.
Parameters
----------
F: (dx, dx) numpy array
Mean of X_t | X_{t-1} is F * X_{t-1}
covX: (dx, dx) numpy array
covariance of X_t | X_{t-1}
filt: MeanAndCov object
filtering distribution at time t-1
Returns
-------
pred: MeanAn... |
def phase_search_names(self, source, phase):
"""Search the bundle.yaml metadata file for pipeline configurations. Looks for:
- <phase>-<source_table>
- <phase>-<dest_table>
- <phase>-<source_name>
"""
search = []
assert phase is not None
# Create a sear... | Search the bundle.yaml metadata file for pipeline configurations. Looks for:
- <phase>-<source_table>
- <phase>-<dest_table>
- <phase>-<source_name> |
def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork() # @UndefinedVariable
if pid:
# Parent process
if self.active_children is None:
self.active_children = [... | Fork a new subprocess to process the request. |
def isChar(ev):
""" Check if an event may be a typed character
"""
text = ev.text()
if len(text) != 1:
return False
if ev.modifiers() not in (Qt.ShiftModifier, Qt.KeypadModifier, Qt.NoModifier):
return False
asciiCode = ord(text)
if asciiCode <= 31 or asciiCode == 0x7f: # ... | Check if an event may be a typed character |
def calc_geo_centre_point(node_source, node_target):
""" Calculates the geodesic distance between `node_source` and `node_target`
incorporating the detour factor specified in config_calc.cfg.
Parameters
----------
node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0
sou... | Calculates the geodesic distance between `node_source` and `node_target`
incorporating the detour factor specified in config_calc.cfg.
Parameters
----------
node_source: LVStationDing0, GeneratorDing0, or CableDistributorDing0
source node, member of GridDing0._graph
node_target: LVStati... |
def append_code_expr(self, code):
"""Compile argument and adds it to the list of code objects."""
# expects a string.
if isinstance(code, str) and not isinstance(code, unicode):
code = unicode(code)
if not isinstance(code, unicode):
raise TypeError("string expecte... | Compile argument and adds it to the list of code objects. |
def random_like(ary=None, shape=None, dtype=None):
"""
Returns a random array of the same shape and type as the
supplied array argument, or the supplied shape and dtype
"""
if ary is not None:
shape, dtype = ary.shape, ary.dtype
elif shape is None or dtype is None:
raise ValueErr... | Returns a random array of the same shape and type as the
supplied array argument, or the supplied shape and dtype |
def _prepare_transition(self, is_on=None, brightness=None, color=None):
"""
Perform pre-transition tasks and construct the destination state.
:param is_on: The on-off state to transition to.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to... | Perform pre-transition tasks and construct the destination state.
:param is_on: The on-off state to transition to.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to transition to.
:return: The destination state of the transition. |
def _authenticated_call_geocoder(self, url, timeout=DEFAULT_SENTINEL):
"""
Wrap self._call_geocoder, handling tokens.
"""
if self.token is None or int(time()) > self.token_expiry:
self._refresh_authentication_token()
request = Request(
"&".join((url, urlen... | Wrap self._call_geocoder, handling tokens. |
def _get_data_files(data_specs, existing, top=HERE):
"""Expand data file specs into valid data files metadata.
Parameters
----------
data_specs: list of tuples
See [create_cmdclass] for description.
existing: list of tuples
The existing distrubution data_files metadata.
Returns... | Expand data file specs into valid data files metadata.
Parameters
----------
data_specs: list of tuples
See [create_cmdclass] for description.
existing: list of tuples
The existing distrubution data_files metadata.
Returns
-------
A valid list of data_files items. |
def primary_from_name(self, tax_name):
"""
Return tax_id and primary tax_name corresponding to tax_name.
"""
names = self.names
s1 = select([names.c.tax_id, names.c.is_primary],
names.c.tax_name == tax_name)
log.debug(str(s1))
res = s1.execu... | Return tax_id and primary tax_name corresponding to tax_name. |
async def get_authenticated_user(
self, redirect_uri: str, code: str
) -> Dict[str, Any]:
"""Handles the login for the Google user, returning an access token.
The result is a dictionary containing an ``access_token`` field
([among others](https://developers.google.com/identity/proto... | Handles the login for the Google user, returning an access token.
The result is a dictionary containing an ``access_token`` field
([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).
Unlike other ``get_authenticated_user`` methods in this packa... |
def point2pos(self, point):
"""Converts a point or offset in a file to a (row, col) position."""
row = self._vim.eval('byte2line({})'.format(point))
col = self._vim.eval('{} - line2byte({})'.format(point, row))
return (int(row), int(col)) | Converts a point or offset in a file to a (row, col) position. |
def _setProperty(self, _type, data, win=None, mask=None):
"""
Send a ClientMessage event to the root window
"""
if not win:
win = self.root
if type(data) is str:
dataSize = 8
else:
data = (data+[0]*(5-len(data)))[:5]
dataSiz... | Send a ClientMessage event to the root window |
def view(ctx):
""" Build and view docs.
"""
report.info(ctx, "docs.view", f"viewing documentation")
build_path = ctx.docs.directory / "build" / "html" / "index.html"
build_path = pathname2url(build_path.as_posix())
webbrowser.open(f"file:{build_path!s}") | Build and view docs. |
def _get_span(self, m):
"""
Gets a tuple that identifies a figure for the specific mention class
that m belongs to.
"""
return (m.figure.document.id, m.figure.position) | Gets a tuple that identifies a figure for the specific mention class
that m belongs to. |
def set_target_from_config(self, cp, section):
"""Sets the target using the given config file.
This looks for ``niterations`` to set the ``target_niterations``, and
``effective-nsamples`` to set the ``target_eff_nsamples``.
Parameters
----------
cp : ConfigParser
... | Sets the target using the given config file.
This looks for ``niterations`` to set the ``target_niterations``, and
``effective-nsamples`` to set the ``target_eff_nsamples``.
Parameters
----------
cp : ConfigParser
Open config parser to retrieve the argument from.
... |
def check_w_normalized(W, N_k, tolerance = 1.0e-4):
"""Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states... | Check the weight matrix W is properly normalized. The sum over N should be 1, and the sum over k by N_k should aslo be 1
Parameters
----------
W : np.ndarray, shape=(N, K), dtype='float'
The normalized weight matrix for snapshots and states.
W[n, k] is the weight of snapshot n in state k.
... |
def _rand_init(x_bounds, x_types, selection_num_starting_points):
'''
Random sample some init seed within bounds.
'''
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | Random sample some init seed within bounds. |
async def _wait(self, entity_type, entity_id, action, predicate=None):
"""
Block the calling routine until a given action has happened to the
given entity
:param entity_type: The entity's type.
:param entity_id: The entity's id.
:param action: the type of action (e.g., '... | Block the calling routine until a given action has happened to the
given entity
:param entity_type: The entity's type.
:param entity_id: The entity's id.
:param action: the type of action (e.g., 'add', 'change', or 'remove')
:param predicate: optional callable that must take as ... |
def _set_many(self, i, j, x):
"""Sets value at each (i, j) to x
Here (i,j) index major and minor respectively, and must not contain
duplicate entries.
"""
i, j, M, N = self._prepare_indices(i, j)
n_samples = len(x)
offsets = np.empty(n_samples, dtype=self.indices.dtype)
ret = _sparseto... | Sets value at each (i, j) to x
Here (i,j) index major and minor respectively, and must not contain
duplicate entries. |
def _validate_entities(self, tasks):
"""
Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task.
"""
if not tasks:
raise TypeError(expected_type=Task, actual_type=type(tasks))
if not isinstance(tasks, set):
if not is... | Purpose: Validate whether the 'tasks' is of type set. Validate the description of each Task. |
def t_singlecomment_NEWLINE(self, t):
r'\r?\n'
t.lexer.pop_state() # Back to initial
t.lexer.lineno += 1
return t | r'\r?\n |
def random_public_ip(self):
"""Return a randomly generated, public IPv4 address.
:return: ip address
"""
randomip = random_ip()
while self.is_reserved_ip(randomip):
randomip = random_ip()
return randomip | Return a randomly generated, public IPv4 address.
:return: ip address |
def get_file_paths(self, id_list):
"""Get a list of file paths based of a set of ids
Parameters
----------
id_list : list
List of integer file keys
Returns list of file paths
"""
if id_list is None:
return []
try:
pat... | Get a list of file paths based of a set of ids
Parameters
----------
id_list : list
List of integer file keys
Returns list of file paths |
def get_sequence_rule_admin_session_for_bank(self, bank_id):
"""Gets the ``OsidSession`` associated with the sequence rule administration service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.authoring.SequenceRuleAdminSession) - a
... | Gets the ``OsidSession`` associated with the sequence rule administration service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.authoring.SequenceRuleAdminSession) - a
``SequenceRuleAdminSession``
raise: NotFound - no ``Ba... |
def load_environment(global_conf, app_conf):
"""Configure the Pylons environment via the ``pylons.config``
object
"""
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
paths = dict(root=root,
controllers=os.path.join(root, 'controllers'),
... | Configure the Pylons environment via the ``pylons.config``
object |
def windows_k_distinct(x, k):
"""Find all largest windows containing exactly k distinct elements
:param x: list or string
:param k: positive integer
:yields: largest intervals [i, j) with len(set(x[i:j])) == k
:complexity: `O(|x|)`
"""
dist, i, j = 0, 0, 0 # dist = |{x[i], ..... | Find all largest windows containing exactly k distinct elements
:param x: list or string
:param k: positive integer
:yields: largest intervals [i, j) with len(set(x[i:j])) == k
:complexity: `O(|x|)` |
def post_multipart(host, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's re... | Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return the server's response page. |
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry):
"""tickEFP(EWrapper self, TickerId tickerId, TickType tickType, double basisPoints, IBString const & formattedBasisPoints, double totalDividends, int holdDays, IBS... | tickEFP(EWrapper self, TickerId tickerId, TickType tickType, double basisPoints, IBString const & formattedBasisPoints, double totalDividends, int holdDays, IBString const & futureExpiry, double dividendImpact, double dividendsToExpiry) |
def transform_frame(frame, transform, columns=None, direction='forward',
return_all=True, args=(), **kwargs):
"""
Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
Fals... | Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated |
def validate_header(cls,
header: BlockHeader,
parent_header: BlockHeader,
check_seal: bool = True) -> None:
"""
:raise eth.exceptions.ValidationError: if the header is not valid
"""
if parent_header is None:
... | :raise eth.exceptions.ValidationError: if the header is not valid |
def assert_valid(self, instance, value=None):
"""Checks if valid, including HasProperty instances pass validation"""
valid = super(Instance, self).assert_valid(instance, value)
if not valid:
return False
if value is None:
value = instance._get(self.name)
i... | Checks if valid, including HasProperty instances pass validation |
def from_pickle(cls, path):
"""Load all objects from pickle file and return as dict.
The dict returned will have keys named the same as the
JSSObject classes contained, and the values will be
JSSObjectLists of all full objects of that class (for example,
the equivalent of my_jss... | Load all objects from pickle file and return as dict.
The dict returned will have keys named the same as the
JSSObject classes contained, and the values will be
JSSObjectLists of all full objects of that class (for example,
the equivalent of my_jss.Computer().retrieve_all()).
T... |
def plot(ID, pipeline='everest2', show=True, campaign=None):
'''
Plots the de-trended flux for the given EPIC `ID` and for
the specified `pipeline`.
'''
# Get the data
time, flux = get(ID, pipeline=pipeline, campaign=campaign)
# Remove nans
mask = np.where(np.isnan(flux))[0]
time ... | Plots the de-trended flux for the given EPIC `ID` and for
the specified `pipeline`. |
def createNetcon(self, thresh=10):
""" created netcon to record spikes """
nc = h.NetCon(self.soma(0.5)._ref_v, None, sec = self.soma)
nc.threshold = thresh
return nc | created netcon to record spikes |
def _clean_data(self, str_value, file_data, obj_value):
"""This overwrite is neccesary for work with multivalues"""
str_value = str_value or None
obj_value = obj_value or None
return (str_value, None, obj_value) | This overwrite is neccesary for work with multivalues |
def parse(self, data):
# type: (bytes) -> None
'''
Parse the passed in data into a UDF Timestamp.
Parameters:
data - The data to parse.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Time... | Parse the passed in data into a UDF Timestamp.
Parameters:
data - The data to parse.
Returns:
Nothing. |
def namedtuple_asdict(obj):
"""
Serializing a nested namedtuple into a Python dict
"""
if obj is None:
return obj
if hasattr(obj, "_asdict"): # detect namedtuple
return OrderedDict(zip(obj._fields, (namedtuple_asdict(item)
for item in obj... | Serializing a nested namedtuple into a Python dict |
def handle_data(self, data):
'''
Internal for parsing
'''
if data:
inTag = self._inTag
if len(inTag) > 0:
inTag[-1].appendText(data)
elif data.strip(): #and not self.getRoot():
# Must be text prior to or after root n... | Internal for parsing |
def object_merge(old, new, unique=False):
"""
Recursively merge two data structures.
:param unique: When set to True existing list items are not set.
"""
if isinstance(old, list) and isinstance(new, list):
if old == new:
return
for item in old[::-1]:
if uniqu... | Recursively merge two data structures.
:param unique: When set to True existing list items are not set. |
def move(self, bucket, key, bucket_to, key_to, force='false'):
"""移动文件:
将资源从一个空间到另一个空间,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
Args:
bucket: 待操作资源所在空间
bucket_to: 目标资源空间名
key: 待操作资源文件名
key_to: ... | 移动文件:
将资源从一个空间到另一个空间,具体规格参考:
http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
Args:
bucket: 待操作资源所在空间
bucket_to: 目标资源空间名
key: 待操作资源文件名
key_to: 目标资源文件名
Returns:
一个dict变量,成功返回NULL,失败返回{"error": "<er... |
def generate_vector_color_map(self):
"""Generate color stops array for use with match expression in mapbox template"""
vector_stops = []
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_lis... | Generate color stops array for use with match expression in mapbox template |
def profiling_query_formatter(view, context, query_document, name):
"""Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery
"""
return Markup(
''.join(
[
'<div class="pymongo-query row">... | Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery |
def _set_pw_profile(self, v, load=False):
"""
Setter method for pw_profile, mapped from YANG variable /pw_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pw_profile is considered as a private
method. Backends looking to populate this variable should
... | Setter method for pw_profile, mapped from YANG variable /pw_profile (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pw_profile is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_pw_profile() directly... |
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two tensors"""
# Note: Relying on fact that vdot flattens arrays
return np.vdot(tensor0, tensor1) | Return the inner product between two tensors |
def _yyyymmdd_to_year_fraction(date):
"""Convert YYYMMDD.DD date string or float to YYYY.YYY"""
date = str(date)
if '.' in date:
date, residual = str(date).split('.')
residual = float('0.' + residual)
else:
residual = 0.0
date = _datetime.datetime.strptime(date, '%Y%m%d')
... | Convert YYYMMDD.DD date string or float to YYYY.YYY |
async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict:
"""Make a request against the RainMachine device."""
if not headers:
headers = {}
... | Make a request against the RainMachine device. |
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):
"""
Create an Assignment Group.
Create a new assignment group for this course.
"""
path = {}
data = {}
params... | Create an Assignment Group.
Create a new assignment group for this course. |
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
If this method is not overridden, the problem is solved without
any regularisation other than the option enforcement of
non-negativity of the solution and filter boundary crossing
supression. W... | r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
If this method is not overridden, the problem is solved without
any regularisation other than the option enforcement of
non-negativity of the solution and filter boundary crossing
supression. When it is overridden, it ... |
def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and main loop sections if the respective sections are present
:param config_path: path to the config file or the directory in ... |
def bed(args):
"""
%prog bed anchorsfile
Convert ANCHORS file to BED format.
"""
from collections import defaultdict
from jcvi.compara.synteny import AnchorFile, check_beds
from jcvi.formats.bed import Bed
from jcvi.formats.base import get_number
p = OptionParser(bed.__doc__)
p... | %prog bed anchorsfile
Convert ANCHORS file to BED format. |
def _invalid_implementation(self, t, missing, mistyped, mismatched):
"""
Make a TypeError explaining why ``t`` doesn't implement our interface.
"""
assert missing or mistyped or mismatched, "Implementation wasn't invalid."
message = "\nclass {C} failed to implement interface {I}... | Make a TypeError explaining why ``t`` doesn't implement our interface. |
def mavlink_packet(self, m):
'''handle an incoming mavlink packet from the master vehicle. Relay it to the tracker
if it is a GLOBAL_POSITION_INT'''
if m.get_type() in ['GLOBAL_POSITION_INT', 'SCALED_PRESSURE']:
connection = self.find_connection()
if not connection:
... | handle an incoming mavlink packet from the master vehicle. Relay it to the tracker
if it is a GLOBAL_POSITION_INT |
def get_all_reminders(self, params=None):
"""
Get all reminders
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
i... | Get all reminders
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list |
def info_impl(self):
"""Returns a dict of all runs and tags and their data availabilities."""
result = {}
def add_row_item(run, tag=None):
run_item = result.setdefault(run, {
'run': run,
'tags': {},
# A run-wide GraphDef of ops.
'run_graph': False})
tag_i... | Returns a dict of all runs and tags and their data availabilities. |
def make_measurement(name,
channels,
lumi=1.0, lumi_rel_error=0.1,
output_prefix='./histfactory',
POI=None,
const_params=None,
verbose=False):
"""
Create a Measurement from a list of Cha... | Create a Measurement from a list of Channels |
def ipv4_private(self, network=False, address_class=None):
"""
Returns a private IPv4.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:returns: Private IPv4
"""
# compute private networks from given class
supernet = ... | Returns a private IPv4.
:param network: Network address
:param address_class: IPv4 address class (a, b, or c)
:returns: Private IPv4 |
def process_quantity(self, properties):
"""Process the uncertainty information from a given quantity and return it
"""
quant = Q_(properties[0])
if len(properties) > 1:
unc = properties[1]
uncertainty = unc.get('uncertainty', False)
upper_uncertainty =... | Process the uncertainty information from a given quantity and return it |
def remove_event(self, ref):
"""
Removes an event for a ref (reference),
"""
# is this reference one which has been setup?
if ref in self._refs:
self._refs[ref].remove_callback(ref) | Removes an event for a ref (reference), |
def vertical_headers(self, value):
"""
Setter for **self.__vertical_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict
"""
if value is not None:
assert type(value) is OrderedDict, "'{0}' attribute: '{1}' type is not 'OrderedDict'!".... | Setter for **self.__vertical_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict |
def get_activities(self, activity_ids=None, max_records=50):
"""
Get all activies for this group.
"""
return self.connection.get_all_activities(self, activity_ids,
max_records) | Get all activies for this group. |
def from_pandas_dataframe(cls, bqm_df, offset=0.0, interactions=None):
"""Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame.
Args:
bqm_df (:class:`pandas.DataFrame`):
Quadratic unconstrained binary optimization (QUBO) model formatted
... | Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame.
Args:
bqm_df (:class:`pandas.DataFrame`):
Quadratic unconstrained binary optimization (QUBO) model formatted
as a pandas DataFrame. Row and column indices label the QUBO variables;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.