code stringlengths 59 4.4k | docstring stringlengths 5 7.69k |
|---|---|
def subdivide(self, points_per_edge):
if len(self.coords) <= 1 or points_per_edge < 1:
return self.deepcopy()
coords = interpolate_points(self.coords, nb_steps=points_per_edge,
closed=False)
return self.deepcopy(coords=coords) | Adds ``N`` interpolated points with uniform spacing to each edge.
For each edge between points ``A`` and ``B`` this adds points
at ``A + (i/(1+N)) * (B - A)``, where ``i`` is the index of the added
point and ``N`` is the number of points to add per edge.
Calling this method two times w... |
def do_notify(context, event_type, payload):
LOG.debug('IP_BILL: notifying {}'.format(payload))
notifier = n_rpc.get_notifier('network')
notifier.info(context, event_type, payload) | Generic Notifier.
Parameters:
- `context`: session context
- `event_type`: the event type to report, i.e. ip.usage
- `payload`: dict containing the payload to send |
def find_working_password(self, usernames=None, host_strings=None):
r = self.local_renderer
if host_strings is None:
host_strings = []
if not host_strings:
host_strings.append(self.genv.host_string)
if usernames is None:
usernames = []
if not u... | Returns the first working combination of username and password for the current host. |
def on_goto_out_of_doc(self, assignment):
editor = self.open_file(assignment.module_path)
if editor:
TextHelper(editor).goto_line(assignment.line, assignment.column) | Open the a new tab when goto goes out of the current document.
:param assignment: Destination |
def _bind_success(self, stanza):
payload = stanza.get_payload(ResourceBindingPayload)
jid = payload.jid
if not jid:
raise BadRequestProtocolError(u"<jid/> element mising in"
" the bind response")
self.stream.me = jid
... | Handle resource binding success.
[initiating entity only]
:Parameters:
- `stanza`: <iq type="result"/> stanza received.
Set `streambase.StreamBase.me` to the full JID negotiated. |
def add(name, path, branch, type):
if not name and not path:
ctx = click.get_current_context()
click.echo(ctx.get_help())
examples = (
'\nExamples:\n'
' cpenv module add my_module ./path/to/my_module\n'
' cpenv module add my_module git@github.com:use... | Add a module to an environment. PATH can be a git repository path or
a filesystem path. |
def add_prepare_handler(self, prepare_handlers):
if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES):
prepare_handlers = [prepare_handlers]
if self.prepare_handlers_chain is None:
self.prepare_handlers_chain = []
for handler in prepare_handlers:
... | Add prepare handler to bundle
:type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler |
def _calculate_distance(latlon1, latlon2):
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | Calculates the distance between two points on earth. |
def get_channel_classes(channel_code):
if channel_code:
channel_code = channel_code.upper()
if channel_code not in INTEGRATED_CHANNEL_CHOICES:
raise CommandError(_('Invalid integrated channel: {channel}').format(channel=channel_code))
channel_classes = [INTEGR... | Assemble a list of integrated channel classes to transmit to.
If a valid channel type was provided, use it.
Otherwise, use all the available channel types. |
def check_confirmations_or_resend(self, use_open_peers=False, **kw):
if self.confirmations() == 0:
self.send(use_open_peers, **kw) | check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers endpoint |
def _peekNextID(self, conn=None):
if conn is None:
conn = self._get_connection()
return to_unicode(conn.get(self._get_next_id_key()) or 0) | _peekNextID - Look at, but don't increment the primary key for this model.
Internal.
@return int - next pk |
def _map(self, event):
description = event.get('description', '')
start_time = google_base.parse_rfc3339_utc_string(
event.get('timestamp', ''))
for name, regex in _EVENT_REGEX_MAP.items():
match = regex.match(description)
if match:
return {'name': name, 'start-time': start_time}... | Extract elements from an operation event and map to a named event. |
def update(self, fp):
if 'b' not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
url = self._upload_url
if fp.peek(1):
response = self._put(url, data=fp)
else:
response = self._put(url, data=b'')
if response.status_code !=... | Update the remote file from a local file.
Pass in a filepointer `fp` that has been opened for writing in
binary mode. |
def _qsub_block(self, output_dir, error_dir, tid_specs):
processes = []
job_names = []
for (tid, spec) in tid_specs:
job_name = "%s_%s_tid_%d" % (self.batch_name, self.job_timestamp, tid)
job_names.append(job_name)
cmd_args = self.command(
... | This method handles static argument specifiers and cases where
the dynamic specifiers cannot be queued before the arguments
are known. |
def initialize_dictionaries(self, e_set, max_feats2 = 200):
if(hasattr(e_set, '_type')):
if(e_set._type == "train"):
nvocab = util_functions.get_vocab(e_set._text, e_set._score, max_feats2 = max_feats2)
svocab = util_functions.get_vocab(e_set._clean_stem_text, e_set._... | Initializes dictionaries from an essay set object
Dictionaries must be initialized prior to using this to extract features
e_set is an input essay set
returns a confirmation of initialization |
def _symlink(path, link, overwrite=0, verbose=0):
if exists(link) and not os.path.islink(link):
if verbose:
print('link location already exists')
is_junc = _win32_is_junction(link)
if os.path.isdir(link):
if is_junc:
pointed = _win32_read_junction(link... | Windows helper for ub.symlink |
def write(self, data, sections=None):
if self.error[0]:
self.status = self.error[0]
data = b(self.error[1])
if not self.headers_sent:
self.send_headers(data, sections)
if self.request_method != 'HEAD':
try:
if self.chunked:
... | Write the data to the output socket. |
def nullspace(A, atol=1e-13, rtol=0):
A = np.atleast_2d(A)
u, s, vh = np.linalg.svd(A)
tol = max(atol, rtol * s[0])
nnz = (s >= tol).sum()
ns = vh[nnz:].conj().T
return ns | Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value
decomposition of `A`.
Parameters
----------
A : numpy.ndarray
A should be at most 2-D. A 1-D array with length k will be treated
as a 2-D with shape (1, k)
at... |
def replaceIterationCycle(self, phaseSpecs):
self.__phaseManager = _PhaseManager(
model=self.__model,
phaseSpecs=phaseSpecs)
return | Replaces the Iteration Cycle phases
:param phaseSpecs: Iteration cycle description consisting of a sequence of
IterationPhaseSpecXXXXX elements that are performed in the
given order |
def Tliquidus(Tms=None, ws=None, xs=None, CASRNs=None, AvailableMethods=False,
Method=None):
def list_methods():
methods = []
if none_and_length_check([Tms]):
methods.append('Maximum')
methods.append('Simple')
methods.append('None')
return method... | This function handles the retrival of a mixtures's liquidus point.
This API is considered experimental, and is expected to be removed in a
future release in favor of a more complete object-oriented interface.
>>> Tliquidus(Tms=[250.0, 350.0], xs=[0.5, 0.5])
350.0
>>> Tliquidus(Tms=[250, 350], xs=[... |
def delete_keys(self, *args, **kwargs):
ikeys = iter(kwargs.get('keys', args[0] if args else []))
while True:
try:
key = ikeys.next()
except StopIteration:
break
if isinstance(key, basestring):
mimicdb.backend.srem(tpl.b... | Remove each key or key name in an iterable from the bucket set. |
def read_adc(self, channel, gain=1, data_rate=None):
assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'
return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE) | Read a single ADC channel and return the ADC value as a signed integer
result. Channel must be a value within 0-3. |
def get_namespace_hash(self, hash_fn=hashlib.md5) -> str:
m = hash_fn()
if self.has_names:
items = self._get_namespace_name_to_encoding(desc='getting hash').items()
else:
items = self._get_namespace_identifier_to_encoding(desc='getting hash').items()
for name, enc... | Get the namespace hash.
Defaults to MD5. |
def precision(ntp, nfp):
if (ntp+nfp) > 0:
return ntp/(ntp+nfp)
else:
return np.nan | This calculates precision.
https://en.wikipedia.org/wiki/Precision_and_recall
Parameters
----------
ntp : int
The number of true positives.
nfp : int
The number of false positives.
Returns
-------
float
The precision calculated using `ntp/(ntp + nfp)`. |
def nmap_smb_vulnscan():
service_search = ServiceSearch()
services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)
services = [service for service in services]
service_dict = {}
for service in services:
service.add_tag('smb_vulnscan')
service_dict[str(se... | Scans available smb services in the database for smb signing and ms17-010. |
def resource(**kwargs):
def inner(function):
name = kwargs.pop('name', None)
if name is None:
name = utils.dasherize(function.__name__)
methods = kwargs.pop('methods', None)
if isinstance(methods, six.string_types):
methods = methods,
handler = (functi... | Wraps the decorated function in a lightweight resource. |
def owsproxy_delegate(request):
twitcher_url = request.registry.settings.get('twitcher.url')
protected_path = request.registry.settings.get('twitcher.ows_proxy_protected_path', '/ows')
url = twitcher_url + protected_path + '/proxy'
if request.matchdict.get('service_name'):
url += '/' + request.m... | Delegates owsproxy request to external twitcher service. |
async def update_read_timestamp(self, read_timestamp=None):
if read_timestamp is None:
read_timestamp = (self.events[-1].timestamp if self.events else
datetime.datetime.now(datetime.timezone.utc))
if read_timestamp > self.latest_read_timestamp:
logge... | Update the timestamp of the latest event which has been read.
This method will avoid making an API request if it will have no effect.
Args:
read_timestamp (datetime.datetime): (optional) Timestamp to set.
Defaults to the timestamp of the newest event.
Raises:
... |
def draw(self):
if self.enabled:
self._vertex_list.colors = self._gl_colors
self._vertex_list.vertices = self._gl_vertices
self._vertex_list.draw(pyglet.gl.GL_TRIANGLES) | Draw the shape in the current OpenGL context. |
def process(self, tensor):
for processor in self.preprocessors:
tensor = processor.process(tensor=tensor)
return tensor | Process state.
Args:
tensor: tensor to process
Returns: processed state |
def same_log10_order_of_magnitude(x, delta=0.1):
dmin = np.log10(np.min(x)*(1-delta))
dmax = np.log10(np.max(x)*(1+delta))
return np.floor(dmin) == np.floor(dmax) | Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
----------
x : array-like
Values in base 10. ... |
def do_toggle_variables(self, action):
self.show_vars = action.get_active()
if self.show_vars:
self.show_variables_window()
else:
self.hide_variables_window() | Widget Action to toggle showing the variables window. |
def total_regular_pixels_from_mask(mask):
total_regular_pixels = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
total_regular_pixels += 1
return total_regular_pixels | Compute the total number of unmasked regular pixels in a masks. |
def pop(self, nbytes):
size = 0
popped = []
with self._lock_packets:
while size < nbytes:
try:
packet = self._packets.pop(0)
size += len(packet.data.data)
self._remaining -= len(packet.data.data)
... | pops packets with _at least_ nbytes of payload |
def aoi(self, **kwargs):
g = self._parse_geoms(**kwargs)
if g is None:
return self
else:
return self[g] | Subsets the Image by the given bounds
Args:
bbox (list): optional. A bounding box array [minx, miny, maxx, maxy]
wkt (str): optional. A WKT geometry string
geojson (str): optional. A GeoJSON geometry dictionary
Returns:
image: an image instance of the sa... |
def initialize(self, config, context):
self.logger.info("Initializing PulsarSpout with the following")
self.logger.info("Component-specific config: \n%s" % str(config))
self.logger.info("Context: \n%s" % str(context))
self.emit_count = 0
self.ack_count = 0
self.fail_count = 0
if not PulsarSp... | Implements Pulsar Spout's initialize method |
def scan_mem(self, data_to_find):
if isinstance(data_to_find, bytes):
data_to_find = [bytes([c]) for c in data_to_find]
for mapping in sorted(self.maps):
for ptr in mapping:
if ptr + len(data_to_find) >= mapping.end:
break
candi... | Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches.
:param bytes data_to_find: String to locate
:return: |
def predict(self, x, *args, **kwargs):
if len(args) > 0:
if type(args[0]) == nx.Graph or type(args[0]) == nx.DiGraph:
return self.orient_graph(x, *args, **kwargs)
else:
return self.predict_proba(x, *args, **kwargs)
elif type(x) == DataFrame:
... | Generic predict method, chooses which subfunction to use for a more
suited.
Depending on the type of `x` and of `*args`, this function process to execute
different functions in the priority order:
1. If ``args[0]`` is a ``networkx.(Di)Graph``, then ``self.orient_graph`` is executed.
... |
def CheckForHeaderGuard(filename, clean_lines, error):
raw_lines = clean_lines.lines_without_raw_strings
for i in raw_lines:
if Search(r'//\s*NOLINT\(build/header_guard\)', i):
return
for i in raw_lines:
if Search(r'^\s*
return
cppvar = GetHeaderGuardCPPVariable(filename)
ifndef = ''
ifn... | Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
clean_lines: A CleansedLines instance containing the file.
error: The function to call with a... |
def get_all_files(folder):
for path, dirlist, filelist in os.walk(folder):
for fn in filelist:
yield op.join(path, fn) | Generator that loops through all absolute paths of the files within folder
Parameters
----------
folder: str
Root folder start point for recursive search.
Yields
------
fpath: str
Absolute path of one file in the folders |
def arcovar(x, order):
r
from spectrum import corrmtx
import scipy.linalg
X = corrmtx(x, order, 'covariance')
Xc = np.matrix(X[:, 1:])
X1 = np.array(X[:, 0])
a, _residues, _rank, _singular_values = scipy.linalg.lstsq(-Xc, X1)
Cz = np.dot(X1.conj().transpose(), Xc)
e = np.dot(X1.conj(... | r"""Simple and fast implementation of the covariance AR estimate
This code is 10 times faster than :func:`arcovar_marple` and more importantly
only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`
:param array X: Array of complex data samples
:param int oder: Order of linear predic... |
def write_bel_annotation(self, file: TextIO) -> None:
if not self.is_populated():
self.populate()
values = self._get_namespace_name_to_encoding(desc='writing names')
write_annotation(
keyword=self._get_namespace_keyword(),
citation_name=self._get_namespace_nam... | Write as a BEL annotation file. |
def predictions_and_gradient(
self, image=None, label=None, strict=True, return_details=False):
assert self.has_gradient()
if image is None:
image = self.__original_image
if label is None:
label = self.__original_class
in_bounds = self.in_bounds(image)... | Interface to model.predictions_and_gradient for attacks.
Parameters
----------
image : `numpy.ndarray`
Single input with shape as expected by the model
(without the batch dimension).
Defaults to the original image.
label : int
Label used t... |
def intensity_at_radius(self, radius):
return self.intensity * np.exp(
-self.sersic_constant * (((radius / self.effective_radius) ** (1. / self.sersic_index)) - 1)) | Compute the intensity of the profile at a given radius.
Parameters
----------
radius : float
The distance from the centre of the profile. |
def get_self_user_id(session):
response = make_get_request(session, 'self')
if response.status_code == 200:
return response.json()['result']['id']
else:
raise UserIdNotRetrievedException(
'Error retrieving user id: %s' % response.text, response.text) | Get the currently authenticated user ID |
def run(self):
logger.info(u'Started listening')
while not self._stop:
xml = self._readxml()
if xml is None:
break
if not self.modelize:
logger.info(u'Raw xml: %s' % xml)
self.results.put(xml)
continue
... | Start listening to the server |
def contains(x):
if isinstance(x, str):
x = canonical_name(x)
return x in _TO_COLOR_USER or x in _TO_COLOR
else:
x = tuple(x)
return x in _TO_NAME_USER or x in _TO_NAME | Return true if this string or integer tuple appears in tables |
def init(self, username, reponame, force, backend=None):
key = self.key(username, reponame)
server_repodir = self.server_rootdir(username,
reponame,
create=False)
if os.path.exists(server_repodir) and not f... | Initialize a Git repo
Parameters
----------
username, reponame : Repo name is tuple (name, reponame)
force: force initialization of the repo even if exists
backend: backend that must be used for this (e.g. s3) |
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
self._write('\x8A')
if adaptive:
self._write('\x96')
else:
self._write('\x97')
if three_phase:
self._write('\x8C')
else:
self._write('\x8D')
divisor = i... | Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it. |
def _get_heron_support_processes(self):
retval = {}
retval[self.heron_shell_ids[self.shard]] = Command([
'%s' % self.heron_shell_binary,
'--port=%s' % self.shell_port,
'--log_file_prefix=%s/heron-shell-%s.log' % (self.log_dir, self.shard),
'--secret=%s' % self.topology_id], self.... | Get a map from all daemon services' name to the command to start them |
def SHLD(cpu, dest, src, count):
OperandSize = dest.size
tempCount = Operators.ZEXTEND(count.read(), OperandSize) & (OperandSize - 1)
arg0 = dest.read()
arg1 = src.read()
MASK = ((1 << OperandSize) - 1)
t0 = (arg0 << tempCount)
t1 = arg1 >> (OperandSize - tempCoun... | Double precision shift right.
Shifts the first operand (destination operand) to the left the number of bits specified by the third operand
(count operand). The second operand (source operand) provides bits to shift in from the right (starting with
the least significant bit of the destination op... |
def plot_txn_time_hist(transactions, bin_minutes=5, tz='America/New_York',
ax=None, **kwargs):
if ax is None:
ax = plt.gca()
txn_time = transactions.copy()
txn_time.index = txn_time.index.tz_convert(pytz.timezone(tz))
txn_time.index = txn_time.index.map(lambda x: x.hour * ... | Plots a histogram of transaction times, binning the times into
buckets of a given duration.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full explanation in tears.create_full_tear_sheet.
bin_minutes : float, optio... |
def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False):
flags = 0
if rsa_oaep_padding:
flags = Advapi32Const.CRYPT_OAEP
out_len = new(advapi32, 'DWORD *', len(data))
res = advapi32.CryptEncrypt(
certificate_or_public_key.ex_key_handle,
null(),
True... | Encrypts a value using an RSA public key via CryptoAPI
:param certificate_or_public_key:
A Certificate or PublicKey instance to encrypt with
:param data:
A byte string of the data to encrypt
:param rsa_oaep_padding:
If OAEP padding should be used instead of PKCS#1 v1.5
:raise... |
def SWAP(self, *operands):
a = operands[0]
b = operands[-1]
return (b,) + operands[1:-1] + (a,) | Exchange 1st and 2nd stack items |
def mkdir(self, folder):
current_folder = self._ftp.pwd()
folders = folder.split('/')
for fld in folders:
try:
self.cd(fld)
except error_perm:
self._ftp.mkd(fld)
self.cd(fld)
self.cd(current_folder) | Creates a folder in the server
:param folder: the folder to be created.
:type folder: string |
def _tile(self, n):
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad) | Get the update tile surrounding particle `n` |
def get_configuration(self, key, default=None):
if key in self.config:
return self.config.get(key)
else:
return default | Returns the configuration for KEY |
async def fire(self, *args, **kwargs):
logger.debug('Fired {}'.format(self))
for observer in self._observers:
gen = observer(*args, **kwargs)
if asyncio.iscoroutinefunction(observer):
await gen | Fire this event, calling all observers with the same arguments. |
def delete(self, force=True, pid=None):
pid = pid or self.pid
if self['_deposit'].get('pid'):
raise PIDInvalidAction()
if pid:
pid.delete()
return super(Deposit, self).delete(force=force) | Delete deposit.
Status required: ``'draft'``.
:param force: Force deposit delete. (Default: ``True``)
:param pid: Force pid object. (Default: ``None``)
:returns: A new Deposit object. |
def luminosity_within_circle_in_units(self, radius: dim.Length, unit_luminosity='eps', kpc_per_arcsec=None,
exposure_time=None):
if not isinstance(radius, dim.Length):
radius = dim.Length(value=radius, unit_length='arcsec')
profile = self.new_profile... | Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \
centred on the light profile's centre.
The following units for mass can be specified and output:
- Electrons per second (default) - 'eps'.
- Counts - 'counts' (multiplies the lumi... |
def expand_filepaths(base_dir, rel_paths):
return [os.path.join(base_dir, os.path.normpath(rp)) for rp in rel_paths] | Expand a list of relative paths to a give base directory.
Parameters
----------
base_dir : str
The target base directory
rel_paths : list (or list-like)
Collection of relative path strings
Returns
-------
expanded_paths : list
`rel_paths` rooted at `base_dir`
... |
def get_deck_link(self, deck: BaseAttrDict):
deck_link = 'https://link.clashroyale.com/deck/en?deck='
for i in deck:
card = self.get_card_info(i.name)
deck_link += '{0.id};'.format(card)
return deck_link | Form a deck link
Parameters
---------
deck: official_api.models.BaseAttrDict
An object is a deck. Can be retrieved from ``Player.current_deck``
Returns str |
def acquireConnection(self):
self._logger.debug("Acquiring connection")
self._conn._ping_check()
connWrap = ConnectionWrapper(dbConn=self._conn,
cursor=self._conn.cursor(),
releaser=self._releaseConnection,
lo... | Get a Connection instance.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's release() method or use it in a context manag... |
def create(self, store_id, order_id, data):
self.store_id = store_id
self.order_id = order_id
if 'id' not in data:
raise KeyError('The order line must have an id')
if 'product_id' not in data:
raise KeyError('The order line must have a product_id')
if 'pro... | Add a new line item to an existing order.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param order_id: The id for the order in a store.
:type order_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data =... |
def default_headers(self):
_headers = {
"User-Agent": "Pyzotero/%s" % __version__,
"Zotero-API-Version": "%s" % __api_version__,
}
if self.api_key:
_headers["Authorization"] = "Bearer %s" % self.api_key
return _headers | It's always OK to include these headers |
def get_data(filename):
name, ext = get_file_extension(filename)
func = json_get_data if ext == '.json' else yaml_get_data
return func(filename) | Calls right function according to file extension |
def get_repository(self, path, info=None, verbose=True):
if path.strip() in ('','.'):
path = os.getcwd()
realPath = os.path.realpath( os.path.expanduser(path) )
if not os.path.isdir(realPath):
os.makedirs(realPath)
if not self.is_repository(realPath):
... | Create a repository at given real path or load any existing one.
This method insures the creation of the directory in the system if it is missing.\n
Unlike create_repository, this method doesn't erase any existing repository
in the path but loads it instead.
**N.B. On some systems and s... |
def updatecache(filename, module_globals=None):
if filename in cache:
del cache[filename]
if not filename or (filename.startswith('<') and filename.endswith('>')):
return []
fullname = filename
try:
stat = os.stat(fullname)
except OSError:
basename = filename
... | Update a cache entry and return its list of lines.
If something's wrong, print a message, discard the cache entry,
and return an empty list. |
def pid_context(pid_filename=None):
pid_filename = pid_filename or DEFAULT_PID_FILENAME
if os.path.exists(pid_filename):
contents = open(pid_filename).read(16)
log.warning('pid_filename %s already exists with contents %s',
pid_filename, contents)
with open(pid_filename, '... | For the duration of this context manager, put the PID for this process into
`pid_filename`, and then remove the file at the end. |
def _pprint(params, offset=0, printer=repr):
options = np.get_printoptions()
np.set_printoptions(precision=5, threshold=64, edgeitems=2)
params_list = list()
this_line_length = offset
line_sep = ',\n' + (1 + offset // 2) * ' '
for i, (k, v) in enumerate(sorted(six.iteritems(params))):
if... | Pretty print the dictionary 'params'
Parameters
----------
params: dict
The dictionary to pretty print
offset: int
The offset in characters to add at the begin of each line.
printer:
The function to convert entries to strings, typically
the builtin str or repr |
def count_snps(mat):
snps = np.zeros(4, dtype=np.uint32)
snps[0] = np.uint32(\
mat[0, 5] + mat[0, 10] + mat[0, 15] + \
mat[5, 0] + mat[5, 10] + mat[5, 15] + \
mat[10, 0] + mat[10, 5] + mat[10, 15] + \
mat[15, 0] + mat[15, 5] + mat[15, 10])
for i in range(16):
... | get dstats from the count array and return as a float tuple |
def join(self, timeout=None):
if not self.__initialized:
raise RuntimeError("Thread.__init__() not called")
if not self.__started.is_set():
raise RuntimeError("cannot join thread before it is started")
if self is current_thread():
raise RuntimeError("cannot jo... | Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is
called terminates -- either normally or through an unhandled exception
or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a
... |
def formfield(self, **kwargs):
defaults = {
'form_class': RichTextFormField,
'config': self.config,
}
defaults.update(kwargs)
return super(RichTextField, self).formfield(**defaults) | Get the form for field. |
def set_pkg_source_info(self, doc, text):
self.assert_package_exists()
if not self.package_source_info_set:
self.package_source_info_set = True
doc.package.source_info = text
return True
else:
raise CardinalityError('Package::SourceInfo') | Sets the package's source information, if not already set.
text - Free form text.
Raises CardinalityError if already defined.
Raises OrderError if no package previously defined. |
def get(ctx):
user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
try:
response = PolyaxonClient().build_job.get_build(user, project_name, _build)
cache.cache(config_manager=BuildJobManager, response=response)
except (PolyaxonHTTPError, PolyaxonShoul... | Get build job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon build -b 1 get
```
\b
```bash
$ polyaxon build --build=1 --project=project_name get
``` |
def stem(self, word):
word = normalize('NFC', text_type(word.lower()))
word = word.translate(self._umlauts)
wlen = len(word) - 1
if wlen > 3:
if wlen > 5:
if word[-3:] == 'nen':
return word[:-3]
if wlen > 4:
if w... | Return CLEF German stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGerman()
>>> stmr.stem('lesen')
'lese'
>>> stmr.stem('graue... |
def _get_comp_config(self):
proto_config = topology_pb2.Config()
key = proto_config.kvs.add()
key.key = TOPOLOGY_COMPONENT_PARALLELISM
key.value = str(self.parallelism)
key.type = topology_pb2.ConfigValueType.Value("STRING_VALUE")
if self.custom_config is not None:
sanitized = self._saniti... | Returns component-specific Config protobuf message
It first adds ``topology.component.parallelism``, and is overriden by
a user-defined component-specific configuration, specified by spec(). |
def settings(self):
stmt = "select {fields} from pg_settings".format(fields=', '.join(SETTINGS_FIELDS))
settings = []
for row in self._iter_results(stmt):
row['setting'] = self._vartype_map[row['vartype']](row['setting'])
settings.append(Settings(**row))
return se... | Returns settings from the server. |
def __refill_tokenbuffer(self):
if len(self.tokens) == 0:
self.__tokenize(self.dxfile.readline()) | Add a new tokenized line from the file to the token buffer.
__refill_tokenbuffer()
Only reads a new line if the buffer is empty. It is safe to
call it repeatedly.
At end of file, method returns empty strings and it is up to
__peek and __consume to flag the end of the stream. |
def get_credentials_from_file(filepath):
try:
creds = load_file_as_yaml(filepath)
except Exception:
creds = {}
profile_name = os.environ.get(citr_env_vars.CITRINATION_PROFILE)
if profile_name is None or len(profile_name) == 0:
profile_name = DEFAULT_CITRINATION_PROFILE
api_ke... | Extracts credentials from the yaml formatted credential filepath
passed in. Uses the default profile if the CITRINATION_PROFILE env var
is not set, otherwise looks for a profile with that name in the credentials file.
:param filepath: The path of the credentials file |
def _open(self, f):
if None in self.files:
fd = self.files.index(None)
self.files[fd] = f
else:
fd = len(self.files)
self.files.append(f)
return fd | Adds a file descriptor to the current file descriptor list
:rtype: int
:param f: the file descriptor to add.
:return: the index of the file descriptor in the file descr. list |
def _scan_footpaths(self, stop_id, walk_departure_time):
for _, neighbor, data in self._walk_network.edges_iter(nbunch=[stop_id], data=True):
d_walk = data["d_walk"]
arrival_time = walk_departure_time + d_walk / self._walk_speed
self._update_stop_label(neighbor, arrival_time) | Scan the footpaths originating from stop_id
Parameters
----------
stop_id: int |
def set_seq2(self, b):
if b is self.b:
return
self.b = b
self.matching_blocks = self.opcodes = None
self.fullbcount = None
self.__chain_b() | Set the second sequence to be compared.
The first sequence to be compared is not changed.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.set_seq2("abcd")
>>> s.ratio()
1.0
>>>
SequenceMatcher computes and caches detailed ... |
def fwhm2sigma(fwhm):
fwhm = np.asarray(fwhm)
return fwhm / np.sqrt(8 * np.log(2)) | Convert a FWHM value to sigma in a Gaussian kernel.
Parameters
----------
fwhm: float or numpy.array
fwhm value or values
Returns
-------
fwhm: float or numpy.array
sigma values |
def is_home_environment(path):
home = unipath(os.environ.get('CPENV_HOME', '~/.cpenv'))
path = unipath(path)
return path.startswith(home) | Returns True if path is in CPENV_HOME |
def analyzeAll(self):
searchableData=str(self.files2)
self.log.debug("considering analysis for %d ABFs",len(self.IDs))
for ID in self.IDs:
if not ID+"_" in searchableData:
self.log.debug("%s needs analysis",ID)
try:
self.analyzeABF(... | analyze every unanalyzed ABF in the folder. |
def _encrypt(self, value):
value = json.dumps(value)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
encrypted_value = self.cipher.encrypt(value.encode('utf8'))
hexified_value = binascii.hexlify(encrypted_value).decode('ascii')
return hexified_valu... | Turn a json serializable value into an jsonified, encrypted,
hexa string. |
def tf_combined_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):
q_model_loss = self.fn_loss(
states=states,
internals=internals,
actions=actions,
terminal=terminal,
reward=reward,
... | Combines Q-loss and demo loss. |
def find_effect_class(self, path) -> Type[Effect]:
package_name, class_name = parse_package_string(path)
if package_name:
package = self.get_package(package_name)
return package.find_effect_class(class_name, raise_for_error=True)
for package in self.packages:
... | Find an effect class by class name or full python path to class
Args:
path (str): effect class name or full python path to effect class
Returns:
Effect class
Raises:
EffectError if no class is found |
def expGenerator(args):
parser = OptionParser()
parser.set_usage("%prog [options] --description='{json object with args}'\n" + \
"%prog [options] --descriptionFromFile='{filename}'\n" + \
"%prog [options] --showSchema")
parser.add_option("--description", dest = "description",... | Parses, validates, and executes command-line options;
On success: Performs requested operation and exits program normally
On Error: Dumps exception/error info in JSON format to stdout and exits the
program with non-zero status. |
def begin(self):
return Range(self.source_buffer, self.begin_pos, self.begin_pos,
expanded_from=self.expanded_from) | Returns a zero-length range located just before the beginning of this range. |
def load(fp, separator=DEFAULT, index_separator=DEFAULT, cls=dict, list_cls=list):
converter = None
output = cls()
arraykeys = set()
for line in fp:
if converter is None:
if isinstance(line, six.text_type):
converter = six.u
else:
converter... | Load an object from the file pointer.
:param fp: A readable filehandle.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separator: The separator between key and index. Defaults to u'_' or b'_', depending on the types.
:param cls: A... |
def vector_to_volume(arr, mask, order='C'):
if mask.dtype != np.bool:
raise ValueError("mask must be a boolean array")
if arr.ndim != 1:
raise ValueError("vector must be a 1-dimensional array")
if arr.ndim == 2 and any(v == 1 for v in arr.shape):
log.debug('Got an array of shape {}, ... | Transform a given vector to a volume. This is a reshape function for
3D flattened and maybe masked vectors.
Parameters
----------
arr: np.array
1-Dimensional array
mask: numpy.ndarray
Mask image. Must have 3 dimensions, bool dtype.
Returns
-------
np.ndarray |
def Carcinogen(CASRN, AvailableMethods=False, Method=None):
r
methods = [COMBINED, IARC, NTP]
if AvailableMethods:
return methods
if not Method:
Method = methods[0]
if Method == IARC:
if CASRN in IARC_data.index:
status = IARC_codes[IARC_data.at[CASRN, 'group']]
... | r'''Looks up if a chemical is listed as a carcinogen or not according to
either a specifc method or with all methods.
Returns either the status as a string for a specified method, or the
status of the chemical in all available data sources, in the format
{source: status}.
Parameters
----------... |
def calc_key_stats(self, metric_store):
stats_to_calculate = ['mean', 'std', 'min', 'max']
percentiles_to_calculate = range(0, 100, 1)
for column, groups_store in metric_store.items():
for group, time_store in groups_store.items():
data = metric_store[column][group].values()
if self.gr... | Calculate stats such as percentile and mean
:param dict metric_store: The metric store used to store all the parsed log data
:return: None |
def format_parameters(self, **kwargs):
req_data = {}
for k, v in kwargs.items():
if isinstance(v, (list, tuple)):
k = k + '[]'
req_data[k] = v
return req_data | Properly formats array types |
def _serialize_int(value, size=32, padding=0):
if size <= 0 or size > 32:
raise ValueError
if not isinstance(value, (int, BitVec)):
raise ValueError
if issymbolic(value):
buf = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid... | Translates a signed python integral or a BitVec into a 32 byte string, MSB first |
def query(self, input = '', params = {}):
payload = {'input': input,
'appid': self.appid}
for key, value in params.items():
if isinstance(value, (list, tuple)):
payload[key] = ','.join(value)
else:
payload[key] = value
t... | Query Wolfram Alpha and return a Result object |
def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs):
def curry_wrapper(wrapped_function):
@wraps(wrapped_function)
def enabled_wrapper(request, *args, **kwargs):
return_url = decorator_kwargs.pop('return_url',
request.... | Decorator to enable OAuth Credentials if authorized, and setup
the oauth object on the request object to provide helper functions
to start the flow otherwise.
.. code-block:: python
:caption: views.py
:name: views_enabled3
from oauth2client.django_util.decorators import oauth_enabled
... |
def actions(self, state):
"In the leftmost empty column, try all non-conflicting rows."
if state[-1] is not None:
return []
else:
col = state.index(None)
return [row for row in range(self.N)
if not self.conflicted(state, row, col)] | In the leftmost empty column, try all non-conflicting rows. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.