Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
365,200 | def _bnot8(ins):
output = _8bit_oper(ins.quad[2])
output.append()
output.append()
return output | Negates (BITWISE NOT) top of the stack (8 bits in AF) |
365,201 | def emit_accepted(self):
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filename) | Sends signal that the file dialog was closed properly.
Sends:
filename |
365,202 | def merge_cycles(self):
while True:
own_edges = self.get_self_edges()
if len(own_edges) > 0:
for e in own_edges: self.remove_edge(e)
c = self.find_cycle()
if not c: return
keep = c[0]
remove_list = c[1:]
for n in remove_li... | Work on this graph and remove cycles, with nodes containing concatonated lists of payloads |
365,203 | def process_gatt_service(services, event):
length = len(event.payload) - 5
handle, start, end, uuid = unpack( % length, event.payload)
uuid = process_uuid(uuid)
services[uuid] = {: uuid, : start, : end} | Process a BGAPI event containing a GATT service description and add it to a dictionary
Args:
services (dict): A dictionary of discovered services that is updated with this event
event (BGAPIPacket): An event containing a GATT service |
365,204 | def _get(self, field):
if field in self._list_fields():
return self.__proxy__.get(field)
else:
raise KeyError( % (field, .join(self._list_fields()))) | Return the value for the queried field.
Get the value of a given field. The list of all queryable fields is
documented in the beginning of the model class.
>>> out = m._get('graph')
Parameters
----------
field : string
Name of the field to be retrieved.
... |
365,205 | def prox_xline(x, step):
if not np.isscalar(x):
x= x[0]
if x > 0.5:
return np.array([0.5])
else:
return np.array([x]) | Projection onto line in x |
365,206 | def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
for i in range(retries):
humidity, temperature = read(sensor, pin, platform)
if humidity is not None and temperature is not None:
return (humidity, temperature)
time.sleep(delay_seconds)
return (Non... | Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read function, this read_retry function will attempt to read
multiple times (up to ... |
365,207 | def clone(self):
result = copy.copy(self)
result.size_class_masses = copy.deepcopy(self.size_class_masses)
return result | Create a complete copy of self.
:returns: A MaterialPackage that is identical to self. |
365,208 | def generate_csv(path, out):
def is_berlin_cable(filename):
return in filename
writer = UnicodeWriter(open(out, ), delimiter=)
writer.writerow((, , , ))
for cable in cables_from_source(path, predicate=is_berlin_cable):
writer.writerow((cable.reference_id, cable.created, cable.origi... | \
Walks through the `path` and generates the CSV file `out` |
365,209 | def get(self, request, format=None):
action = request.query_params.get(, )
action = action if action == or action == else
mark_as_read = request.query_params.get(, ) ==
notifications = self.get_queryset().filter(to_user=request.user)
... | get HTTP method |
365,210 | def binaryEntropyVectorized(x):
entropy = - x*np.log2(x) - (1-x)*np.log2(1-x)
entropy[x*(1 - x) == 0] = 0
return entropy | Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy |
365,211 | def choice(*es):
msg = .format(.join(map(repr, es)))
def match_choice(s, grm=None, pos=0):
errs = []
for e in es:
try:
return e(s, grm, pos)
except PegreError as ex:
errs.append((ex.message, ex.position))
if errs:
r... | Create a PEG function to match an ordered choice. |
365,212 | def _request_api(self, **kwargs):
_url = kwargs.get()
_method = kwargs.get(, )
_status = kwargs.get(, 200)
counter = 0
if _method not in [, ]:
raise ValueError()
while True:
try:
res = REQ[_method](_url, cookies=self._coo... | Wrap the calls the url, with the given arguments.
:param str url: Url to call with the given arguments
:param str method: [POST | GET] Method to use on the request
:param int status: Expected status code |
365,213 | def get_description(self):
paths = [,
,
]
for path in paths:
elm = self.root.find(path, NS)
if elm is not None and elm.text:
return elm.text | Tries to get WF description from 'collabration' or 'process' or 'pariticipant'
Returns str: WF description |
365,214 | def _get_descending_key(gettime=time.time):
now_descending = int((_FUTURE_TIME - gettime()) * 100)
request_id_hash = os.environ.get("REQUEST_ID_HASH")
if not request_id_hash:
request_id_hash = str(random.getrandbits(32))
return "%d%s" % (now_descending, request_id_hash) | Returns a key name lexically ordered by time descending.
This lets us have a key name for use with Datastore entities which returns
rows in time descending order when it is scanned in lexically ascending order,
allowing us to bypass index building for descending indexes.
Args:
gettime: Used for testing.
... |
365,215 | def chat_unfurl(
self, *, channel: str, ts: str, unfurls: dict, **kwargs
) -> SlackResponse:
self._validate_xoxp_token()
kwargs.update({"channel": channel, "ts": ts, "unfurls": unfurls})
return self.api_call("chat.unfurl", json=kwargs) | Provide custom unfurl behavior for user-posted URLs.
Args:
channel (str): The Channel ID of the message. e.g. 'C1234567890'
ts (str): Timestamp of the message to add unfurl behavior to. e.g. '1234567890.123456'
unfurls (dict): a dict of the specific URLs you're offering an u... |
365,216 | def add_to_linestring(position_data, kml_linestring):
global kml
position_data[2] += float(args.aoff)
kml_linestring.coords.addcoordinates([position_data]) | add a point to the kml file |
365,217 | def fit_params_to_1d_data(logX):
m_max = logX.shape[0]
p_max = logX.shape[1]
params = np.zeros((m_max, p_max, 3))
for m_ in range(m_max):
for p_ in range(p_max):
params[m_,p_] = skewnorm.fit(logX[m_,p_])
return params | Fit skewed normal distributions to 1-D capactity data,
and return the distribution parameters.
Args
----
logX:
Logarithm of one-dimensional capacity data,
indexed by module and phase resolution index |
365,218 | def avail(search=None, verbose=False):
**
ret = {}
cmd =
res = __salt__[](cmd)
retcode = res[]
if retcode != 0:
ret[] = _exit_status(retcode)
return ret
for image in salt.utils.json.loads(res[]):
if image[][] or not image[][]:
continue
if search ... | Return a list of available images
search : string
search keyword
verbose : boolean (False)
toggle verbose output
CLI Example:
.. code-block:: bash
salt '*' imgadm.avail [percona]
salt '*' imgadm.avail verbose=True |
365,219 | def pack(self):
for i in range(len(self.values)):
if math.isnan(self.values[i]):
self.values[i] = 0
return struct.pack(self.pack_string, *self.values) | pack a FD FDM buffer from current values |
365,220 | def getCompleteFile(self, basepath):
dirname = getDirname(self.getName())
return os.path.join(basepath, dirname, "complete.txt") | Get filename indicating all comics are downloaded. |
365,221 | def execute_javascript(self, *args, **kwargs):
ret = self.__exec_js(*args, **kwargs)
return ret | Execute a javascript string in the context of the browser tab. |
365,222 | def word_to_id(self, word):
if word in self.vocab:
return self.vocab[word]
else:
return self.unk_id | Returns the integer word id of a word string. |
365,223 | def node_link_graph(data: Mapping[str, Any]) -> BELGraph:
graph = BELGraph()
graph.graph = data.get(, {})
graph.graph[GRAPH_ANNOTATION_LIST] = {
keyword: set(values)
for keyword, values in graph.graph.get(GRAPH_ANNOTATION_LIST, {}).items()
}
mapping = []
for node_data in d... | Return graph from node-link data format.
Adapted from :func:`networkx.readwrite.json_graph.node_link_graph` |
365,224 | def cmd_ublox(self, args):
if len(args) == 0:
print(self.usage())
elif args[0] == "status":
print(self.cmd_status())
elif args[0] == "set":
self.ublox_settings.command(args[1:])
elif args[0] == "reset":
self.cmd_ublox_reset(args[1:... | control behaviour of the module |
365,225 | def get_user_best(self, username, *, mode=OsuMode.osu, limit=50):
return self._make_req(endpoints.USER_BEST, dict(
k=self.key,
u=username,
type=_username_type(username),
m=mode.value,
limit=limit
), JsonList(SoloScore)) | Get a user's best scores.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
The osu! game mode for which to look up. Defaults to osu!standard.
... |
365,226 | def solution(self, e, v, extra_constraints=(), exact=None):
if exact is False and o.VALIDATE_APPROXIMATIONS in self.state.options:
ar = self._solver.solution(e, v, extra_constraints=self._adjust_constraint_list(extra_constraints), exact=False)
er = self._solver.solution(e, v, ex... | Return True if `v` is a solution of `expr` with the extra constraints, False otherwise.
:param e: An expression (an AST) to evaluate
:param v: The proposed solution (an AST)
:param extra_constraints: Extra constraints (as ASTs) to add to the solver for this... |
365,227 | def add_phenotype(self, ind_obj, phenotype_id):
if phenotype_id.startswith() or len(phenotype_id) == 7:
logger.debug()
hpo_results = phizz.query_hpo([phenotype_id])
else:
logger.debug()
hpo_results = phizz.query_disease([phenotype_id])
ad... | Add a phenotype term to the case. |
365,228 | def format_camel_case(text):
text = text.strip()
if len(text) == 0:
raise ValueError("can not be empty string!")
else:
text = text.lower()
words = list()
word = list()
for char in text:
if char in ALPHA_DIGITS:
word.append... | Example::
ThisIsVeryGood
**中文文档**
将文本格式化为各单词首字母大写, 拼接而成的长变量名。 |
365,229 | def _control_vm(self, command, expected=None):
result = None
if self.is_running() and self._monitor:
log.debug("Execute QEMU monitor command: {}".format(command))
try:
log.info("Connecting to Qemu monitor on {}:{}".format(self._monitor_host, self._monito... | Executes a command with QEMU monitor when this VM is running.
:param command: QEMU monitor command (e.g. info status, stop etc.)
:param expected: An array of expected strings
:returns: result of the command (matched object or None) |
365,230 | def clustered_vert(script, cell_size=1.0, strategy=, selected=False):
if strategy.lower() == :
strategy_num = 0
elif strategy.lower() == :
strategy_num = 1
filter_xml = .join([
,
,
.format(cell_size),
,
,
,
,
,
,
... | "Create a new layer populated with a subsampling of the vertexes of the
current mesh
The subsampling is driven by a simple one-per-gridded cell strategy.
Args:
script: the FilterScript object or script filename to write
the filter to.
cell_size (float): The size of the cell... |
365,231 | def execute_nb(fname, metadata=None, save=True, show_doc_only=False):
"Execute notebook `fname` with `metadata` for preprocessing."
NotebookNotary().sign(nb) | Execute notebook `fname` with `metadata` for preprocessing. |
365,232 | def _pull(keys):
user_ns = globals()
if isinstance(keys, (list,tuple, set)):
for key in keys:
if not user_ns.has_key(key):
raise NameError("name is not defined"%key)
return map(user_ns.get, keys)
else:
if not user_ns.has_key(keys):
raise ... | helper method for implementing `client.pull` via `client.apply` |
365,233 | def disassociate_failure_node(self, parent, child):
return self._disassoc(
self._forward_rel_name(), parent, child) | Remove a failure node link.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove a failure node link.
:param parent: Primary key of parent node to disassociate failure node from.
:type parent: int
:param child: Primary key of child node to be di... |
365,234 | def parse_list_line_windows(self, b):
line = b.decode(encoding=self.encoding).rstrip("\r\n")
date_time_end = line.index("M")
date_time_str = line[:date_time_end + 1].strip().split(" ")
date_time_str = " ".join([x for x in date_time_str if len(x) > 0])
line = line[date_ti... | Parsing Microsoft Windows `dir` output
:param b: response line
:type b: :py:class:`bytes` or :py:class:`str`
:return: (path, info)
:rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`) |
365,235 | def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None,
load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None,
outbound_nat_rules=None, tags=None, connection_auth=None, **k... | .. versionadded:: 2019.2.0
Ensure a load balancer exists.
:param name:
Name of the load balancer.
:param resource_group:
The resource group assigned to the load balancer.
:param sku:
The load balancer SKU, which can be 'Basic' or 'Standard'.
:param tags:
A dictio... |
365,236 | def runfile(filename, args=None, wdir=None, namespace=None):
try:
if hasattr(filename, ):
filename = filename.decode()
except (UnicodeError, TypeError):
pass
global __umd__
if os.environ.get("PYDEV_UMD_ENABLED", "").lower() == "true":
if __umd__ is None:
... | Run filename
args: command line arguments (string)
wdir: working directory |
365,237 | def stop(self, timeout=None):
assert self.scan_id is not None,
if timeout is None:
url = % self.scan_id
self.conn.send_request(url, method=)
return
self.stop()
for _ in xrange(timeout)... | Send the GET request required to stop the scan
If timeout is not specified we just send the request and return. When
it is the method will wait for (at most) :timeout: seconds until the
scan changes it's status/stops. If the timeout is reached then an
exception is raised.
:para... |
365,238 | def _axis_in_detector(geometry):
du, dv = geometry.det_axes_init
axis = geometry.axis
c = np.array([np.vdot(axis, du), np.vdot(axis, dv)])
cnorm = np.linalg.norm(c)
assert cnorm != 0
return c / cnorm | A vector in the detector plane that points along the rotation axis. |
365,239 | def init_app(self, app):
self.init_config(app)
app.extensions[] = self
@app.before_first_request
def connect_signals():
from invenio_oauthclient.models import RemoteAccount
from invenio_oauthclient.signals import account_setup_committed
... | Flask application initialization. |
365,240 | def pip_install_requirements(requirements, constraints=None, **options):
command = ["install"]
available_options = (, , , )
for option in parse_options(options, available_options):
command.append(option)
command.append("-r {0}".format(requirements))
if constraints:
command.app... | Install a requirements file.
:param constraints: Path to pip constraints file.
http://pip.readthedocs.org/en/stable/user_guide/#constraints-files |
365,241 | def prettify(root, encoding=):
if isinstance(root, ElementTree.Element):
node = ElementTree.tostring(root, )
else:
node = root
| Return a pretty-printed XML string for the Element.
@see: http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html |
365,242 | def download_user_playlists_by_search(self, user_name):
try:
user = self.crawler.search_user(user_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_user_playlists_by_id(user.user_id) | Download user's playlists by his/her name.
:params user_name: user name. |
365,243 | def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None):
name_map = {}
name_map.update(base_interfaces)
interface_type, interface_number = split_interface(interface)
if isinstance(addl_name_map, dict):
name_map.update(addl_name_map)
rev_name_map = {}
... | Function to return an abbreviated representation of the interface name.
:param interface: The interface you are attempting to abbreviate.
:param addl_name_map (optional): A dict containing key/value pairs that updates
the base mapping. Used if an OS has specific differences. e.g. {"Po": "PortChannel"} vs
... |
365,244 | def get_raw_path(self, include_self=False):
v = self
if not include_self:
if v._paths.get():
return v._paths[]
elif v._paths.get():
return v._paths[]
elif v.parent and v.parent != self.disk:
v = v.... | Retrieves the base mount path of the volume. Typically equals to :func:`Disk.get_fs_path` but may also be the
path to a logical volume. This is used to determine the source path for a mount call.
The value returned is normally based on the parent's paths, e.g. if this volume is mounted to a more specif... |
365,245 | def create_role(name):
role = role_manager.create(name=name)
if click.confirm(f):
role_manager.save(role, commit=True)
click.echo(f)
else:
click.echo() | Create a new role. |
365,246 | def handle(self, state, message=False):
if message:
if state != chatstates_xso.ChatState.ACTIVE:
raise ValueError(
"Only the state ACTIVE can be sent with messages."
)
elif self._state == state:
return False
se... | Handle a state update.
:param state: the new chat state
:type state: :class:`~aioxmpp.chatstates.ChatState`
:param message: pass true to indicate that we handle the
:data:`ACTIVE` state that is implied by
sending a content message.
:type ... |
365,247 | def getmany(self, *keys):
pickled_keys = (self._pickle_key(k) for k in keys)
pickled_values = self.redis.hmget(self.key, *pickled_keys)
ret = []
for k, v in zip(keys, pickled_values):
value = self.cache.get(k, self._unpickle(v))
ret.append(value)
... | Return a list of values corresponding to the keys in the iterable of
*keys*.
If a key is not present in the collection, its corresponding value will
be :obj:`None`.
.. note::
This method is not implemented by standard Python dictionary
classes. |
365,248 | def _get_listlike_indexer(self, key, axis, raise_missing=False):
o = self.obj
ax = o._get_axis(axis)
indexer, keyarr = ax._convert_listlike_indexer(key,
kind=self.name)
if indexer is not None and ... | Transform a list-like of keys into a new index and an indexer.
Parameters
----------
key : list-like
Target labels
axis: int
Dimension on which the indexing is being made
raise_missing: bool
Whether to raise a KeyError if some labels are not f... |
365,249 | def iter_sys(self):
names = self.sys_names()
for name in names:
osys = self.GetOverallSys(name)
hsys = self.GetHistoSys(name)
yield name, osys, hsys | Iterate over sys_name, overall_sys, histo_sys.
overall_sys or histo_sys may be None for any given sys_name. |
365,250 | def descend(self, remote, force=False):
remote_dirs = remote.split()
for directory in remote_dirs:
try:
self.conn.cwd(directory)
except Exception:
if force:
self.conn.mkd(directory)
self.conn.cwd(dir... | Descend, possibly creating directories as needed |
365,251 | def striter(self):
pad = self.padding or 0
for i in self._sorted():
yield "%0*d" % (pad, i) | Iterate over each (optionally padded) string element in RangeSet. |
365,252 | def make_abstract_dist(req_to_install):
if req_to_install.editable:
return IsSDist(req_to_install)
elif req_to_install.link and req_to_install.link.is_wheel:
return IsWheel(req_to_install)
else:
return IsSDist(req_to_install) | Factory to make an abstract dist object.
Preconditions: Either an editable req with a source_dir, or satisfied_by or
a wheel link, or a non-editable req with a source_dir.
:return: A concrete DistAbstraction. |
365,253 | def download_image(self, image_type, image):
url = self._getUrl("/{}/images/{}".format(image_type, image))
response = yield from self._session().request("GET", url, auth=self._auth)
if response.status == 404:
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".for... | Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream |
365,254 | def rewrite_kwargs(conn_type, kwargs, module_name=None):
if conn_type != and module_name != :
if in kwargs:
kwargs[] = % kwargs.pop()
if conn_type == and module_name == :
if in kwargs:
del kwargs[]
return kwargs | Manipulate connection keywords.
Modifieds keywords based on connection type.
There is an assumption here that the client has
already been created and that these keywords are being
passed into methods for interacting with various services.
Current modifications:
- if conn_type is not cloud... |
365,255 | def get_next_job_by_port(plugin_name, port, verify_job=True, conn=None):
return get_next_job(plugin_name, None, port, verify_job, conn) | Deprecated - Use get_next_job |
365,256 | def contains(ell, p, shell_only=False):
v = augment(p)
_ = ell.solve(v)
return N.allclose(_,0) if shell_only else _ <= 0 | Check to see whether point is inside
conic.
:param exact: Only solutions exactly on conic
are considered (default: False). |
365,257 | def _update_element(name, element_type, data, server=None):
s properties
propertiespropertiesnamevalue{0}/{1}/propertypropertiesretcodeCannot update {0}{0}/{1}'.format(element_type, name), _clean_data(update_data), server)
return unquote(name) | Update an element, including it's properties |
365,258 | def load(self, context):
if not (context.flags.debugger_data_server_grpc_port > 0 or
context.flags.debugger_port > 0):
return None
flags = context.flags
try:
import tensorflow
except ImportError:
raise ImportError(
)
try:
fr... | Returns the debugger plugin, if possible.
Args:
context: The TBContext flags including `add_arguments`.
Returns:
A DebuggerPlugin instance or None if it couldn't be loaded. |
365,259 | def to_array(self, channels=2):
if channels == 1:
return self.volume_frames.reshape(-1, 1)
if channels == 2:
return np.tile(self.volume_frames, (2, 1)).T
raise Exception(
"RawVolume doesn't know what to do with %s channels" % channels) | Return the array of multipliers for the dynamic |
365,260 | async def extend(self, additional_time):
if self.local.token is None:
raise LockError("Cannot extend an unlocked lock")
if self.timeout is None:
raise LockError("Cannot extend a lock with no timeout")
return await self.do_extend(additional_time) | Adds more time to an already acquired lock.
``additional_time`` can be specified as an integer or a float, both
representing the number of seconds to add. |
365,261 | def readlist(self, fmt, **kwargs):
value, self._pos = self._readlist(fmt, self._pos, **kwargs)
return value | Interpret next bits according to format string(s) and return list.
fmt -- A single string or list of strings with comma separated tokens
describing how to interpret the next bits in the bitstring. Items
can also be integers, for reading new bitstring of the given length.
k... |
365,262 | def insert_into_table(table, data):
fields = data[]
fields[] = datetime.datetime.now().date()
query =
for key in fields.keys():
query += key +
query = query[:-1:] + ")"
client.execute(f"INSERT INTO {table} {query} VALUES", [tuple(fields.values())]) | SQL query for inserting data into table
:return: None |
365,263 | def ended(self):
self._end_time = time.time()
if setting(key=, expected_type=bool):
self._end_memory = get_free_memory() | We call this method when the function is finished. |
365,264 | def register_palette(self):
default =
palette = list(self.palette)
mapping = CONFIG[]
for tok in self.style.styles.keys():
for t in tok.split()[::-1]:
st = self.style.styles[t]
if in st:
break
if not ... | Converts pygmets style to urwid palatte |
365,265 | def compute_eigenvalues(in_prefix, out_prefix):
with open(out_prefix + ".parameters", "w") as o_file:
print >>o_file, "genotypename: " + in_prefix + ".bed"
print >>o_file, "snpname: " + in_prefix + ".bim"
print >>o_file, "indivname: " + in_prefix + ".fam"
p... | Computes the Eigenvalues using smartpca from Eigensoft.
:param in_prefix: the prefix of the input files.
:param out_prefix: the prefix of the output files.
:type in_prefix: str
:type out_prefix: str
Creates a "parameter file" used by smartpca and runs it. |
365,266 | def lookup(self, key):
assert self._mph
key = convert_to_bytes(key)
box = ffi.new(, key)
try:
result = _cmph.cmph_search(self._mph, box, len(key))
return result
finally:
del box | Generate hash code for a key from the Minimal Perfect Hash (MPH)
Parameters
----------
Key : object
The item to generate a key for, this works best for keys that
are strings, or can be transformed fairly directly into bytes
Returns : int
The code for... |
365,267 | def is_installed(config):
try:
config_utils.get_program("pindel2vcf", config)
config_utils.get_program("pindel", config)
return True
except config_utils.CmdNotFound:
return False | Check for pindel installation on machine.
:param config: (dict) information from yaml(items[0]['config'])
:returns: (boolean) if pindel is installed |
365,268 | def _get_max_subplot_ids(fig):
max_subplot_ids = {subplot_type: 0
for subplot_type in _subplot_types}
max_subplot_ids[] = 0
max_subplot_ids[] = 0
for trace in fig.get(, []):
trace_type = trace.get(, )
subplot_types = _trace_to_subplot.get(trace_type, [])
... | Given an input figure, return a dict containing the max subplot number
for each subplot type in the figure
Parameters
----------
fig: dict
A plotly figure dict
Returns
-------
dict
A dict from subplot type strings to integers indicating the largest
subplot number in... |
365,269 | def get_credentials(self, *args, **kwargs):
arguments, _ = self.argparser.parse_known_args()
if self.is_pipe and self.use_pipe:
return self.get_pipe(self.object_type)
elif arguments.tags or arguments.type or arguments.search or arguments.password or arguments.cracked or argu... | Retrieves the users from elastic. |
365,270 | def g(self):
"Hour, 12-hour format without leading zeros; i.e. to "
if self.data.hour == 0:
return 12
if self.data.hour > 12:
return self.data.hour - 12
return self.data.hour | Hour, 12-hour format without leading zeros; i.e. '1' to '12 |
365,271 | def determine_end_idx_for_adjustment(self,
adjustment_ts,
dates,
upper_bound,
requested_quarter,
sid_estimates):
... | Determines the date until which the adjustment at the given date
index should be applied for the given quarter.
Parameters
----------
adjustment_ts : pd.Timestamp
The timestamp at which the adjustment occurs.
dates : pd.DatetimeIndex
The calendar dates ov... |
365,272 | def _get_compressed_vlan_list(self, pvlan_ids):
if not pvlan_ids:
return []
pvlan_list = list(pvlan_ids)
pvlan_list.sort()
compressed_list = []
begin = -1
prev_vlan = -1
for port_vlan in pvlan_list:
if prev_vlan == -1:
... | Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])
Returned compressed XML list:
-----------... |
365,273 | def validate_alias(self, name, cmd):
if name in self.no_alias:
raise InvalidAliasError("The name %s can%s%lThe %s and %l specifiers are mutually exclusive in alias definitions.')
return nargs | Validate an alias and return the its number of arguments. |
365,274 | def get_public_events(self):
return github.PaginatedList.PaginatedList(
github.Event.Event,
self._requester,
self.url + "/events/public",
None
) | :calls: `GET /users/:user/events/public <http://developer.github.com/v3/activity/events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event` |
365,275 | def validate_email_with_regex(email_address):
if not re.match(VALID_ADDRESS_REGEXP, email_address):
emsg = .format(
email_address)
raise YagInvalidEmailAddress(emsg)
if "." not in email_address and "localhost" not in email_address.lower():
raise YagInvalidEmailAddre... | Note that this will only filter out syntax mistakes in emailaddresses.
If a human would think it is probably a valid email, it will most likely pass.
However, it could still very well be that the actual emailaddress has simply
not be claimed by anyone (so then this function fails to devalidate). |
365,276 | def by_version(cls, session, package_name, version):
return cls.first(session,
join=(Package,),
where=((Package.name == package_name),
(cls.version == version))) | Get release for a given version.
:param session: SQLAlchemy session
:type session: :class:`sqlalchemy.Session`
:param package_name: package name
:type package_name: unicode
:param version: version
:type version: unicode
:return: release instance
:rtype... |
365,277 | def GetHashCode(self):
slice_length = 4 if len(self.Data) >= 4 else len(self.Data)
return int.from_bytes(self.Data[:slice_length], ) | uint32 identifier |
365,278 | def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/generate%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view(), name="api_tileset_generate"),
url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$... | Add the following array of urls to the Tileset base urls |
365,279 | def append_data(file_strings, file_fmt, tag):
if file_fmt.lower() == "csv":
return append_csv_data(file_strings)
else:
return append_ascii_data(file_strings, tag) | Load the SuperMAG files
Parameters
-----------
file_strings : array-like
Lists or arrays of strings, where each string contains one file of data
file_fmt : str
String denoting file type (ascii or csv)
tag : string
String denoting the type of file to load, accepted values are... |
365,280 | def Tt(CASRN, AvailableMethods=False, Method=None):
rs triple temperature.
Lookup is based on CASRNs. Will automatically select a data source to use
if no Method is provided; returns None if the data is not available.
Returns data from [1]_, or a chemical7664-41-7
def list_methods():
method... | r'''This function handles the retrieval of a chemical's triple temperature.
Lookup is based on CASRNs. Will automatically select a data source to use
if no Method is provided; returns None if the data is not available.
Returns data from [1]_, or a chemical's melting point if available.
Parameters
... |
365,281 | def type_name(value):
return type(value).__name__ if isinstance(value, EncapsulatedNode) else \
"struct" if isinstance(value, dict) else \
"sequence" if isinstance(value, (tuple, list)) else \
type(value).__name__ | Returns pseudo-YAML type name of given value. |
365,282 | def dot(self, other):
dot_product = 0
a = self.elements
b = other.elements
a_len = len(a)
b_len = len(b)
i = j = 0
while i < a_len and j < b_len:
a_val = a[i]
b_val = b[j]
if a_val < b_val:
i += 2
... | Calculates the dot product of this vector and another vector. |
365,283 | def sample_following_dist(handle_iter, n, totalf):
multiplier = 1.0
if totalf == 1.0:
multiplier = 1e8
while A and val < j:
yield (val, w)
if A:
i, val = A.pop()
else:
break | Samples n passwords following the distribution from the handle
@handle_iter is an iterator that gives (pw,f) @n is the total
number of samle asked for @totalf is the total number of users,
which is euqal to sum(f for pw,f in handle_iter)
As, handle_iterator is an iterator and can only traverse once.
... |
365,284 | def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True,
gzip_encoded=False, **kwds):
if mime_type is None:
raise exceptions.InvalidUserInputError(
)
return cls(stream, mime_type, total_size=total_size,
close_s... | Create a new Upload object from a stream. |
365,285 | def stream_buckets(self, bucket_type=None, timeout=None):
if not self.bucket_stream():
raise NotImplementedError(
"supported on %s" %
self.server_version.vstring)
bucket_type = self._get_bucket_type(bucket_t... | Stream list of buckets through an iterator |
365,286 | def rebin(self, factor):
if self.pilimage != None:
raise RuntimeError, "Cannot rebin anymore, PIL image already exists !"
if type(factor) != type(0):
raise RuntimeError, "Rebin factor must be an integer !"
if factor < 1:
ret... | I robustly rebin your image by a given factor.
You simply specify a factor, and I will eventually take care of a crop to bring
the image to interger-multiple-of-your-factor dimensions.
Note that if you crop your image before, you must directly crop to compatible dimensions !
We update th... |
365,287 | def list_udas(self, database=None, like=None):
if not database:
database = self.current_database
statement = ddl.ListFunction(database, like=like, aggregate=True)
with self._execute(statement, results=True) as cur:
result = self._get_udfs(cur, udf.ImpalaUDA)
... | Lists all UDAFs associated with a given database
Parameters
----------
database : string
like : string for searching (optional) |
365,288 | def get_keys(self, alias_name, key_format):
uri = self.URI + "/keys/" + alias_name + "?format=" + key_format
return self._client.get(uri) | Retrieves the contents of PKCS12 file in the format specified.
This PKCS12 formatted file contains both the certificate as well as the key file data.
Valid key formats are Base64 and PKCS12.
Args:
alias_name: Key pair associated with the RabbitMQ
key_format: Valid key fo... |
365,289 | def set_password(self, password = None):
if password is None or type(password) is not str:
raise KPError("Need a new image number")
else:
self.password = password
self.last_mod = datetime.now().replace(microsecond=0)
return True | This method is used to set the password.
password must be a string. |
365,290 | def parse_selfsm(self, f):
if headers is None:
headers = s
else:
s_name = self.clean_s_name(s[0], f[])
parsed_data[s_name] = {}
for i, v in enumerate(s):
if i != 0:
if "CHIP" in [headers[i]] and v != "NA":
self.hide_chip_columns=... | Go through selfSM file and create a dictionary with the sample name as a key, |
365,291 | def _wrapper(func):
@functools.wraps(func)
def the_func(expr):
try:
return func(expr)
except (TypeError, ValueError) as err:
raise IntoDPValueError(expr, "expr", "could not be transformed") \
from err
return the_func | Wraps a generated function so that it catches all Type- and ValueErrors
and raises IntoDPValueErrors.
:param func: the transforming function |
365,292 | def _pollCallStatus(self, expectedState, callId=None, timeout=None):
callDone = False
timeLeft = timeout or 999999
while self.alive and not callDone and timeLeft > 0:
time.sleep(0.5)
if expectedState == 0:
timeLeft -= 0.5
try:
... | Poll the status of outgoing calls.
This is used for modems that do not have a known set of call status update notifications.
:param expectedState: The internal state we are waiting for. 0 == initiated, 1 == answered, 2 = hangup
:type expectedState: int
:raise Timeou... |
365,293 | def get_info_by_tail_number(self, tail_number, page=1, limit=100):
url = REG_BASE.format(tail_number, str(self.AUTH_TOKEN), page, limit)
return self._fr24.get_aircraft_data(url) | Fetch the details of a particular aircraft by its tail number.
This method can be used to get the details of a particular aircraft by its tail number.
Details include the serial number, age etc along with links to the images of the aircraft.
It checks the user authentication and returns the dat... |
365,294 | def _pwm_to_str(self, precision=4):
if not self.pwm:
return ""
fmt = "{{:.{:d}f}}".format(precision)
return "\n".join(
["\t".join([fmt.format(p) for p in row])
for row in self.pwm]
) | Return string representation of pwm.
Parameters
----------
precision : int, optional, default 4
Floating-point precision.
Returns
-------
pwm_string : str |
365,295 | def _add_domains_xml(self, document):
for domain, attrs in self.domains.items():
domain_element = document.createElement()
domain_element.setAttribute(, domain)
if attrs[] is not None:
domain_element.setAttribute(
,
... | Generates the XML elements for allowed domains. |
365,296 | def write_composer_operation_log(filename):
from featuremonkey.tracing import serializer
from featuremonkey.tracing.logger import OPERATION_LOG
ol = copy.deepcopy(OPERATION_LOG)
ol = serializer.serialize_operation_log(ol)
with open(filename, ) as operation_log_file:
operation_log_file.w... | Writes the composed operation log from featuremonkey's Composer to a json file.
:param filename:
:return: |
365,297 | def output_tap(self):
tracker = Tracker(streaming=True, stream=sys.stdout)
for group in self.config.analysis_groups:
n_providers = len(group.providers)
n_checkers = len(group.checkers)
if not group.providers and group.checkers:
test_suite = gr... | Output analysis results in TAP format. |
365,298 | def target_socket(self, config):
target = WUDPNetworkNativeTransport.target_socket(self, config)
if WNetworkIPV4.is_multicast(target.address()) is False:
raise ValueError()
return target | This method overrides :meth:`.WNetworkNativeTransport.target_socket` method. Do the same thing as
basic method do, but also checks that the result address is IPv4 multicast address.
:param config: beacon configuration
:return: WIPV4SocketInfo |
365,299 | def tree():
def incr_value(obj):
for val in leaf_values:
if val.value < 10:
val.value += 1
break
n.make_room(test_d)
while not are_we_done(test_d):
sleep(0.2 * random.random())
n.curs... | Example showing tree progress view |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.