code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
n_autoinc = 0
int_autoinc_names = []
for col in table_.columns:
if col.autoincrement:
n_autoinc += 1
if is_sqlatype_integer(col.type):
int_autoinc_names.append(col.name)
if n_autoinc... | If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's
``AUTOINCREMENT``.
- Verify agai... |
def get_target_from_spec(self, spec, relative_to=''):
return self.get_target(Address.parse(spec, relative_to=relative_to)) | Converts `spec` into an address and returns the result of `get_target`
:API: public |
def ftp_walk(ftpconn: FTP, rootpath=''):
current_directory = rootpath
try:
directories, files = directory_listing(ftpconn, current_directory)
except ftplib.error_perm:
return
yield current_directory, directories, files
for name in directories:
new_path = os.path.join(current_... | Recursively traverse an ftp directory to discovery directory listing. |
def noisy_wrap(__func: Callable) -> Callable:
def wrapper(*args, **kwargs):
DebugPrint.enable()
try:
__func(*args, **kwargs)
finally:
DebugPrint.disable()
return wrapper | Decorator to enable DebugPrint for a given function.
Args:
__func: Function to wrap
Returns:
Wrapped function |
def shrank(self, block=None, percent_diff=0, abs_diff=1):
if block is None:
block = self.block
cur_nets = len(block.logic)
net_goal = self.prev_nets * (1 - percent_diff) - abs_diff
less_nets = (cur_nets <= net_goal)
self.prev_nets = cur_nets
return less_nets | Returns whether a block has less nets than before
:param Block block: block to check (if changed)
:param Number percent_diff: percentage difference threshold
:param int abs_diff: absolute difference threshold
:return: boolean
This function checks whether the change in the numbe... |
def advance(self):
self.cursor += 1
if self.cursor >= len(self.raw):
self.char = None
else:
self.char = self.raw[self.cursor] | Increments the cursor position. |
def insert_tile(self, tile_info):
for i, tile in enumerate(self.registered_tiles):
if tile.slot == tile_info.slot:
self.registered_tiles[i] = tile_info
return
self.registered_tiles.append(tile_info) | Add or replace an entry in the tile cache.
Args:
tile_info (TileInfo): The newly registered tile. |
def loglevel(level):
if isinstance(level, str):
level = getattr(logging, level.upper())
elif isinstance(level, int):
pass
else:
raise ValueError('{0!r} is not a proper log level.'.format(level))
return level | Convert any representation of `level` to an int appropriately.
:type level: int or str
:rtype: int
>>> loglevel('DEBUG') == logging.DEBUG
True
>>> loglevel(10)
10
>>> loglevel(None)
Traceback (most recent call last):
...
ValueError: None is not a proper log level. |
def write_port(self, port, value):
if port == 'A':
self.GPIOA = value
elif port == 'B':
self.GPIOB = value
else:
raise AttributeError('Port {} does not exist, use A or B'.format(port))
self.sync() | Use a whole port as a bus and write a byte to it.
:param port: Name of the port ('A' or 'B')
:param value: Value to write (0-255) |
def GetRequestFormatMode(request, method_metadata):
if request.path.startswith("/api/v2/"):
return JsonMode.PROTO3_JSON_MODE
if request.args.get("strip_type_info", ""):
return JsonMode.GRR_TYPE_STRIPPED_JSON_MODE
for http_method, unused_url, options in method_metadata.http_methods:
if (http_method == ... | Returns JSON format mode corresponding to a given request and method. |
def read_ncstream_err(fobj):
err = read_proto_object(fobj, stream.Error)
raise RuntimeError(err.message) | Handle reading an NcStream error from a file-like object and raise as error. |
def kill_all_processes(self, check_alive=True, allow_graceful=False):
if ray_constants.PROCESS_TYPE_RAYLET in self.all_processes:
self._kill_process_type(
ray_constants.PROCESS_TYPE_RAYLET,
check_alive=check_alive,
allow_graceful=allow_graceful)
... | Kill all of the processes.
Note that This is slower than necessary because it calls kill, wait,
kill, wait, ... instead of kill, kill, ..., wait, wait, ...
Args:
check_alive (bool): Raise an exception if any of the processes were
already dead. |
def _validate_jpx_compatibility(self, boxes, compatibility_list):
JPX_IDS = ['asoc', 'nlst']
jpx_cl = set(compatibility_list)
for box in boxes:
if box.box_id in JPX_IDS:
if len(set(['jpx ', 'jpxb']).intersection(jpx_cl)) == 0:
msg = ("A JPX box req... | If there is a JPX box then the compatibility list must also contain
'jpx '. |
def send_multipart(self, *args, **kwargs):
self.__in_send_multipart = True
try:
msg = super(GreenSocket, self).send_multipart(*args, **kwargs)
finally:
self.__in_send_multipart = False
self.__state_changed()
return msg | wrap send_multipart to prevent state_changed on each partial send |
def SetExpression(self, expression):
if isinstance(expression, lexer.Expression):
self.args = [expression]
else:
raise errors.ParseError(
'Expected expression, got {0:s}.'.format(expression)) | Set the expression. |
def _read_config(correlation_id, path, parameters):
value = YamlConfigReader(path)._read_object(correlation_id, parameters)
return ConfigParams.from_value(value) | Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object.
:param correlation_id: (optional) transaction id to trace execution through call chain.
:param path: a path to configuration file.
:param parameters: values to parameters the configuratio... |
def show_instance(name, call=None):
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
items = query(action='ve', command=name)
ret = {}
for item in items:
if 'text' in item.__dict__:
ret[item.t... | Show the details from Parallels concerning an instance |
def view_pmap(token, dstore):
grp = token.split(':')[1]
pmap = {}
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
pgetter = getters.PmapGetter(dstore, rlzs_assoc)
pmap = pgetter.get_mean(grp)
return str(pmap) | Display the mean ProbabilityMap associated to a given source group name |
def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
return self.ls(folder=folder, begin_from_file=begin_from_file, num=num, get_grants=True, all_grant_data=all_grant_data) | Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
num: integer, optional
number of results to return, by default it returns ... |
def fd_sine_gaussian(amp, quality, central_frequency, fmin, fmax, delta_f):
kmin = int(round(fmin / delta_f))
kmax = int(round(fmax / delta_f))
f = numpy.arange(kmin, kmax) * delta_f
tau = quality / 2 / numpy.pi / central_frequency
A = amp * numpy.pi ** 0.5 / 2 * tau
d = A * numpy.exp(-(numpy.pi... | Generate a Fourier domain sine-Gaussian
Parameters
----------
amp: float
Amplitude of the sine-Gaussian
quality: float
The quality factor
central_frequency: float
The central frequency of the sine-Gaussian
fmin: float
The minimum frequency to generate the sine-Ga... |
def from_xmldict(cls, xml_dict):
name = xml_dict['creatorName']
kwargs = {}
if 'affiliation' in xml_dict:
kwargs['affiliation'] = xml_dict['affiliation']
return cls(name, **kwargs) | Create an `Author` from a datacite3 metadata converted by
`xmltodict`.
Parameters
----------
xml_dict : :class:`collections.OrderedDict`
A `dict`-like object mapping XML content for a single record (i.e.,
the contents of the ``record`` tag in OAI-PMH XML). This d... |
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title):
im = ax.imshow(ptransfermatrix, interpolation="nearest", cmap=rigetti_3_color_cm, vmin=-1,
vmax=1)
dim = len(labels)
plt.colorbar(im, ax=ax)
ax.set_xticks(range(dim))
ax.set_xlabel("Input Pauli Operator", fontsize... | Visualize the Pauli Transfer Matrix of a process.
:param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix
:param ax: The matplotlib axes.
:param labels: The labels for the operator basis states.
:param title: The title for the plot
:return: The modified axis object.
:rtype: AxesSubplot |
def cardinality(self):
num_strings = {}
def get_num_strings(state):
if self.islive(state):
if state in num_strings:
if num_strings[state] is None:
raise OverflowError(state)
return num_strings[state]
num_strings[state] = None
n = 0
if state in self.finals:
n += 1
if state... | Consider the FSM as a set of strings and return the cardinality of that
set, or raise an OverflowError if there are infinitely many |
def get_data_source_bulk_request(self, rids, limit=5):
headers = {
'User-Agent': self.user_agent(),
'Content-Type': self.content_type()
}
headers.update(self.headers())
r = requests.get( self.portals_url()
+'/data-sources/['
... | This grabs each datasource and its multiple datapoints for a particular device. |
def json_dumps(self, data, **options):
params = {'sort_keys': True, 'indent': 2}
params.update(options)
if json.__version__.split('.') >= ['2', '1', '3']:
params.update({'use_decimal': False})
return json.dumps(data, cls=DjangoJSONEncoder, **params) | Wrapper around `json.dumps` that uses a special JSON encoder. |
def error(code, message, **kwargs):
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERROR, domain)
raise exc | Call this to raise an exception and have it stored in the journal |
def _get_elements(self, site):
try:
if isinstance(site.specie, Element):
return [site.specie]
return [Element(site.specie)]
except:
return site.species.elements | Get the list of elements for a Site
Args:
site (Site): Site to assess
Returns:
[Element]: List of elements |
def yaml_dump_hook(cfg, text: bool=False):
data = cfg.config.dump()
if not text:
yaml.dump(data, cfg.fd, Dumper=cfg.dumper, default_flow_style=False)
else:
return yaml.dump(data, Dumper=cfg.dumper, default_flow_style=False) | Dumps all the data into a YAML file. |
def user_exists(self, username):
path = "/users/{}".format(username)
return self._get(path).ok | Returns whether a user with username ``username`` exists.
:param str username: username of user
:return: whether a user with the specified username exists
:rtype: bool
:raises NetworkFailure: if there is an error communicating with the server
:return: |
def create_url(artist, song):
return (__BASE_URL__ +
'/wiki/{artist}:{song}'.format(artist=urlize(artist),
song=urlize(song))) | Create the URL in the LyricWikia format |
def detach(self):
if self.parent is not None:
if self in self.parent.children:
self.parent.children.remove(self)
self.parent = None
return self | Detach from parent.
@return: This element removed from its parent's
child list and I{parent}=I{None}
@rtype: L{Element} |
def abort(self):
if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
return self
path = self._path() + '/abort'
resp = self._get_resource_root().post(path)
return ApiCommand.from_json_dict(resp, self._get_resource_root()) | Abort a running command.
@return: A new ApiCommand object with the updated information. |
def get_squares(self, player=None):
if player:
return [k for k, v in enumerate(self.squares) if v == player]
else:
return self.squares | squares that belong to a player |
def __fetch_heatmap_data_from_profile(self):
with open(self.pyfile.path, "r") as file_to_read:
for line in file_to_read:
self.pyfile.lines.append(" " + line.strip("\n"))
self.pyfile.length = len(self.pyfile.lines)
line_profiles = self.__get_line_profile_data()
... | Method to create heatmap data from profile information. |
def create_set(self, set_id, etype, entities):
if etype not in {"sample", "pair", "participant"}:
raise ValueError("Unsupported entity type:" + str(etype))
payload = "membership:" + etype + "_set_id\t" + etype + "_id\n"
for e in entities:
if e.etype != etype:
... | Create a set of entities and upload to FireCloud.
Args
etype (str): one of {"sample, "pair", "participant"}
entities: iterable of firecloud.Entity objects. |
def _to_unicode(self, data, encoding, errors='strict'):
if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
da... | Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases |
def get_collection(source, name, collection_format, default):
if collection_format in COLLECTION_SEP:
separator = COLLECTION_SEP[collection_format]
value = source.get(name, None)
if value is None:
return default
return value.split(separator)
if collection_format == 'b... | get collection named `name` from the given `source` that
formatted accordingly to `collection_format`. |
def close(self):
if self.is_worker():
return
for worker in self.workers:
self.comm.send(None, worker, 0) | Tell all the workers to quit. |
def get_param_names(cls):
return [m[0] for m in inspect.getmembers(cls) \
if type(m[1]) == property] | Returns a list of plottable CBC parameter variables |
def getWifiState(self):
result = self.device.shell('dumpsys wifi')
if result:
state = result.splitlines()[0]
if self.WIFI_IS_ENABLED_RE.match(state):
return self.WIFI_STATE_ENABLED
elif self.WIFI_IS_DISABLED_RE.match(state):
return self... | Gets the Wi-Fi enabled state.
@return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN |
def register(model, fields, restrict_to=None, manager=None, properties=None, contexts=None):
if not contexts:
contexts = {}
global _REGISTRY
_REGISTRY[model] = {
'fields': fields,
'contexts': contexts,
'restrict_to': restrict_to,
'manager': manager,
'propertie... | Tell vinaigrette which fields on a Django model should be translated.
Arguments:
model -- The relevant model class
fields -- A list or tuple of field names. e.g. ['name', 'nickname']
restrict_to -- Optional. A django.db.models.Q object representing the subset
of objects to collect translation s... |
def open(filename, frame='unspecified'):
data = BagOfPoints.load_data(filename)
return Point(data, frame) | Create a Point from data saved in a file.
Parameters
----------
filename : :obj:`str`
The file to load data from.
frame : :obj:`str`
The frame to apply to the created point.
Returns
-------
:obj:`Point`
A point created from t... |
def _normalize_number_values(self, parameters):
for key, value in parameters.items():
if isinstance(value, (int, float)):
parameters[key] = str(Decimal(value).normalize(self._context)) | Assures equal precision for all number values |
def get_index_line(self,lnum):
if lnum < 1:
sys.stderr.write("ERROR: line number should be greater than zero\n")
sys.exit()
elif lnum > len(self._lines):
sys.stderr.write("ERROR: too far this line nuber is not in index\n")
sys.exit()
return self._lines[lnum-1] | Take the 1-indexed line number and return its index information |
def get_parent_device(self):
if not self.parent_instance_id:
return ""
dev_buffer_type = winapi.c_tchar * MAX_DEVICE_ID_LEN
dev_buffer = dev_buffer_type()
try:
if winapi.CM_Get_Device_ID(self.parent_instance_id, byref(dev_buffer),
MAX_DE... | Retreive parent device string id |
def auth_password(self, username, password, event=None, fallback=True):
if (not self.active) or (not self.initial_kex_done):
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.auth_handl... | Authenticate to the server using a password. The username and password
are sent over an encrypted link.
If an ``event`` is passed in, this method will return immediately, and
the event will be triggered once authentication succeeds or fails. On
success, `is_authenticated` will return ... |
def _discover(self):
for ep in pkg_resources.iter_entry_points('yamlsettings10'):
ext = ep.load()
if callable(ext):
ext = ext()
self.add(ext) | Find and install all extensions |
def by_email_address(cls, email):
return DBSession.query(cls).filter_by(email_address=email).first() | Return the user object whose email address is ``email``. |
def LogLikelihood(self, data):
m = len(data)
if self.n < m:
return float('-inf')
x = self.Random()
y = numpy.log(x[:m]) * data
return y.sum() | Computes the log likelihood of the data.
Selects a random vector of probabilities from this distribution.
Returns: float log probability |
def safe_translation_getter(self, field, default=None, language_code=None, any_language=False):
meta = self._parler_meta._get_extension_by_field(field)
if language_code and language_code != self._current_language:
try:
tr_model = self._get_translated_model(language_code, meta... | Fetch a translated property, and return a default value
when both the translation and fallback language are missing.
When ``any_language=True`` is used, the function also looks
into other languages to find a suitable value. This feature can be useful
for "title" attributes for example, ... |
def str2hashalgo(description):
algo = getattr(hashlib, description.lower(), None)
if not callable(algo):
raise ValueError('Unknown hash algorithm %s' % description)
return algo | Convert the name of a hash algorithm as described in the OATH
specifications, to a python object handling the digest algorithm
interface, PEP-xxx.
:param description
the name of the hash algorithm, example
:rtype: a hash algorithm class constructor |
def get_or_create_candidate_election(
self, row, election, candidate, party
):
return election.update_or_create_candidate(
candidate, party.aggregate_candidates, row["uncontested"]
) | For a given election, this function updates or creates the
CandidateElection object using the model method on the election. |
def get_cameras_rules(self):
resource = "rules"
rules_event = self.publish_and_get_event(resource)
if rules_event:
return rules_event.get('properties')
return None | Return the camera rules. |
def recursive(self):
for m in self.members.values():
if m.kind is not None and m.kind.lower() == self.name.lower():
return True
else:
return False | When True, this CustomType has at least one member that is of the same
type as itself. |
def ip(addr, version=None):
addr_obj = IPAddress(addr)
if version and addr_obj.version != version:
raise ValueError("{} is not an ipv{} address".format(addr, version))
return py23_compat.text_type(addr_obj) | Converts a raw string to a valid IP address. Optional version argument will detect that \
object matches specified version.
Motivation: the groups of the IP addreses may contain leading zeros. IPv6 addresses can \
contain sometimes uppercase characters. E.g.: 2001:0dB8:85a3:0000:0000:8A2e:0370:7334 has \
... |
def _try_convert_to_int_index(cls, data, copy, name, dtype):
from .numeric import Int64Index, UInt64Index
if not is_unsigned_integer_dtype(dtype):
try:
res = data.astype('i8', copy=False)
if (res == data).all():
return Int64Index(res, copy=... | Attempt to convert an array of data into an integer index.
Parameters
----------
data : The data to convert.
copy : Whether to copy the data or not.
name : The name of the index returned.
Returns
-------
int_index : data converted to either an Int64Index... |
def dist_calc(loc1, loc2):
R = 6371.009
dlat = np.radians(abs(loc1[0] - loc2[0]))
dlong = np.radians(abs(loc1[1] - loc2[1]))
ddepth = abs(loc1[2] - loc2[2])
mean_lat = np.radians((loc1[0] + loc2[0]) / 2)
dist = R * np.sqrt(dlat ** 2 + (np.cos(mean_lat) * dlong) ** 2)
dist = np.sqrt(dist ** 2... | Function to calculate the distance in km between two points.
Uses the flat Earth approximation. Better things are available for this,
like `gdal <http://www.gdal.org/>`_.
:type loc1: tuple
:param loc1: Tuple of lat, lon, depth (in decimal degrees and km)
:type loc2: tuple
:param loc2: Tuple of... |
def export_subprocess_info(bpmn_diagram, subprocess_params, output_element):
output_element.set(consts.Consts.triggered_by_event, subprocess_params[consts.Consts.triggered_by_event])
if consts.Consts.default in subprocess_params and subprocess_params[consts.Consts.default] is not None:
outpu... | Adds Subprocess node attributes to exported XML element
:param bpmn_diagram: BPMNDiagramGraph class instantion representing a BPMN process diagram,
:param subprocess_params: dictionary with given subprocess parameters,
:param output_element: object representing BPMN XML 'subprocess' element. |
def load_csv(path, delimiter=','):
try:
with open(path, 'rb') as csvfile:
reader = DictReader(csvfile, delimiter=delimiter)
for row in reader:
yield row
except (OSError, IOError):
raise ClientException("File not found: {}".format(path)) | Load CSV file from path and yield CSV rows
Usage:
for row in load_csv('/path/to/file'):
print(row)
or
list(load_csv('/path/to/file'))
:param path: file path
:param delimiter: CSV delimiter
:return: a generator where __next__ is a row of the CSV |
def set_servers(self, servers):
if isinstance(servers, six.string_types):
servers = [servers]
assert servers, "No memcached servers supplied"
self._servers = [Protocol(
server=server,
username=self.username,
password=self.password,
comp... | Iter to a list of servers and instantiate Protocol class.
:param servers: A list of servers
:type servers: list
:return: Returns nothing
:rtype: None |
def _create_extractors(col_params):
result = []
for col_param in col_params:
result.append(_create_extractor(col_param))
return result | Creates extractors to extract properties corresponding to 'col_params'.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
Returns:
A list of extractor functions. The ith element in the
returned list extracts the column corresponding to the ith element of
_request.col_params |
def _cont_norm_running_quantile_regions_mp(wl, fluxes, ivars, q, delta_lambda,
ranges, n_proc=2, verbose=False):
print("contnorm.py: continuum norm using running quantile")
print("Taking spectra in %s chunks" % len(ranges))
nchunks = len(ranges)
norm_fluxes = n... | Perform continuum normalization using running quantile, for spectrum
that comes in chunks.
The same as _cont_norm_running_quantile_regions(),
but using multi-processing.
Bo Zhang (NAOC) |
def load_labeled_events(filename, delimiter=r'\s+'):
r
events, labels = load_delimited(filename, [float, str], delimiter)
events = np.array(events)
try:
util.validate_events(events)
except ValueError as error:
warnings.warn(error.args[0])
return events, labels | r"""Import labeled time-stamp events from an annotation file. The file should
consist of two columns; the first having numeric values corresponding to
the event times and the second having string labels for each event. This
is primarily useful for processing labeled events which lack duration, such
as... |
def load_profile(self, profile):
profile_path = os.path.join(
self.root_directory, 'minimum_needs', profile + '.json')
self.read_from_file(profile_path) | Load a specific profile into the current minimum needs.
:param profile: The profile's name
:type profile: basestring, str |
def _mapping(self):
return (self.__search_client.get(
"/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index)))
["mappings"]) | Fetch the entire mapping for the specified index.
Returns:
dict: The full mapping for the index. |
def route_to_alt_domain(request, url):
alternative_domain = request.registry.settings.get("pyramid_notebook.alternative_domain", "").strip()
if alternative_domain:
url = url.replace(request.host_url, alternative_domain)
return url | Route URL to a different subdomain.
Used to rewrite URLs to point to websocket serving domain. |
def terminate(library, session, degree, job_id):
return library.viTerminate(session, degree, job_id) | Requests a VISA session to terminate normal execution of an operation.
Corresponds to viTerminate function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param degree: Constants.NULL
:param job_id: Specifies an oper... |
def _handleSelectAllAxes(self, evt):
if len(self._axisId) == 0:
return
for i in range(len(self._axisId)):
self._menu.Check(self._axisId[i], True)
self._toolbar.set_active(self.getActiveAxes())
evt.Skip() | Called when the 'select all axes' menu item is selected. |
def find_model(model_name, apps=settings.INSTALLED_APPS, fuzziness=0):
if '/' in model_name:
return model_name
if not apps and isinstance(model_name, basestring) and '.' in model_name:
apps = [model_name.split('.')[0]]
apps = util.listify(apps or settings.INSTALLED_APPS)
for app in apps:... | Find model_name among indicated Django apps and return Model class
Examples:
To find models in an app called "miner":
>>> find_model('WikiItem', 'miner')
>>> find_model('Connection', 'miner')
>>> find_model('InvalidModelName') |
def get_files(conn, aid: int) -> AnimeFiles:
with conn:
cur = conn.cursor().execute(
'SELECT anime_files FROM cache_anime WHERE aid=?',
(aid,))
row = cur.fetchone()
if row is None:
raise ValueError('No cached files')
return AnimeFiles.from_json(row... | Get cached files for anime. |
def set_info_page(self):
if self.info_page is not None:
self.infowidget.setHtml(
self.info_page,
QUrl.fromLocalFile(self.css_path)
) | Set current info_page. |
def register(klass):
assert(isinstance(klass, type))
name = klass.__name__.lower()
if name in Optimizer.opt_registry:
warnings.warn('WARNING: New optimizer %s.%s is overriding '
'existing optimizer %s.%s' %
(klass.__module__, klass.... | Registers a new optimizer.
Once an optimizer is registered, we can create an instance of this
optimizer with `create_optimizer` later.
Examples
--------
>>> @mx.optimizer.Optimizer.register
... class MyOptimizer(mx.optimizer.Optimizer):
... pass
>>>... |
def create_frvect(timeseries):
dims = frameCPP.Dimension(
timeseries.size, timeseries.dx.value,
str(timeseries.dx.unit), 0)
vect = frameCPP.FrVect(
timeseries.name or '', FRVECT_TYPE_FROM_NUMPY[timeseries.dtype.type],
1, dims, str(timeseries.unit))
vect.GetDataArray()[:] = nu... | Create a `~frameCPP.FrVect` from a `TimeSeries`
This method is primarily designed to make writing data to GWF files a
bit easier.
Parameters
----------
timeseries : `TimeSeries`
the input `TimeSeries`
Returns
-------
frvect : `~frameCPP.FrVect`
the output `FrVect` |
def file(ctx, data_dir, data_file):
if not ctx.file:
ctx.data_file = data_file
if not ctx.data_dir:
ctx.data_dir = data_dir
ctx.type = 'file' | Use the File SWAG Backend |
def calc_temp(Data_ref, Data):
T = 300 * ((Data.A * Data_ref.Gamma) / (Data_ref.A * Data.Gamma))
Data.T = T
return T | Calculates the temperature of a data set relative to a reference.
The reference is assumed to be at 300K.
Parameters
----------
Data_ref : DataObject
Reference data set, assumed to be 300K
Data : DataObject
Data object to have the temperature calculated for
Returns
-------
... |
def powered_up(self):
if not self.data.scripts.powered_up:
return False
for script in self.data.scripts.powered_up:
if not script.check(self):
return False
return True | Returns True whether the card is "powered up". |
def factors(number):
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.")
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors | Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for. |
def transcode(text, input=PREFERRED_ENCODING, output=PREFERRED_ENCODING):
try:
return text.decode("cp437").encode("cp1252")
except UnicodeError:
try:
return text.decode("cp437").encode(output)
except UnicodeError:
return text | Transcode a text string |
def cons(f, mindepth):
C = ClustFile(f)
for data in C:
names, seqs, nreps = zip(*data)
total_nreps = sum(nreps)
if total_nreps < mindepth:
continue
S = []
for name, seq, nrep in data:
S.append([seq, nrep])
res = stack(S)
yield [x[:4... | Makes a list of lists of reads at each site |
def __get_time_range(self, startDate, endDate):
today = date.today()
start_date = today - timedelta(days=today.weekday(), weeks=1)
end_date = start_date + timedelta(days=4)
startDate = startDate if startDate else str(start_date)
endDate = endDate if endDate else str(end_date)
... | Return time range |
def welcome_message():
message = m.Message()
message.add(m.Brand())
message.add(heading())
message.add(content())
return message | Welcome message for first running users.
.. versionadded:: 4.3.0
:returns: A message object containing helpful information.
:rtype: messaging.message.Message |
def setdefault(obj, field, default):
setattr(obj, field, getattr(obj, field, default)) | Set an object's field to default if it doesn't have a value |
def user_list(**connection_args):
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
try:
qry = 'SELECT User,Host FROM mysql.user'
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: ... | Return a list of users on a MySQL server
CLI Example:
.. code-block:: bash
salt '*' mysql.user_list |
def get_beamarea_deg2(self, ra, dec):
beam = self.get_beam(ra, dec)
if beam is None:
return 0
return beam.a * beam.b * np.pi | Calculate the area of the beam in square degrees.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
area : float
The area of the beam in square degrees. |
def add_fields(self, **fields):
self.__class__ = type(self.__class__.__name__,
(self.__class__,), fields)
for k, v in fields.items():
v.init_inst(self) | Add new data fields to this struct instance |
def from_json(cls, data: str, force_snake_case=True, force_cast: bool=False, restrict: bool=False) -> T:
return cls.from_dict(util.load_json(data),
force_snake_case=force_snake_case,
force_cast=force_cast,
restrict=restrict) | From json string to instance
:param data: Json string
:param force_snake_case: Keys are transformed to snake case in order to compliant PEP8 if True
:param force_cast: Cast forcibly if True
:param restrict: Prohibit extra parameters if True
:return: Instance
Usage:
... |
def open_image(fname_or_instance: Union[str, IO[bytes]]):
if isinstance(fname_or_instance, Image.Image):
return fname_or_instance
return Image.open(fname_or_instance) | Opens a Image and returns it.
:param fname_or_instance: Can either be the location of the image as a
string or the Image.Image instance itself. |
def findHTMLMeta(stream):
parser = YadisHTMLParser()
chunks = []
while 1:
chunk = stream.read(CHUNK_SIZE)
if not chunk:
break
chunks.append(chunk)
try:
parser.feed(chunk)
except HTMLParseError, why:
chunks.append(stream.read())
... | Look for a meta http-equiv tag with the YADIS header name.
@param stream: Source of the html text
@type stream: Object that implements a read() method that works
like file.read
@return: The URI from which to fetch the XRDS document
@rtype: str
@raises MetaNotFound: raised with the content... |
def run(self):
self.started_queue.put('STARTED')
while True:
event = self.publisher_queue.get()
if event == POISON_PILL:
return
else:
self.dispatch(event) | Start the exchange |
def get_edited_object(self, request):
resolvermatch = urls.resolve(request.path_info)
if resolvermatch.namespace == 'admin' and resolvermatch.url_name and resolvermatch.url_name.endswith('_change'):
match = RE_CHANGE_URL.match(resolvermatch.url_name)
if not match:
... | Return the object which is currently being edited.
Returns ``None`` if the match could not be made. |
def _process_hist(self, hist):
edges, hvals, widths, lims, isdatetime = super(SideHistogramPlot, self)._process_hist(hist)
offset = self.offset * lims[3]
hvals *= 1-self.offset
hvals += offset
lims = lims[0:3] + (lims[3] + offset,)
return edges, hvals, widths, lims, isdat... | Subclassed to offset histogram by defined amount. |
def _prep(e):
if 'lastupdate' in e:
e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))
for k in ['farm', 'server', 'id', 'secret']:
if not k in e:
return e
e["url"] = "https://farm%s.staticflickr.com/%s/%s_%s_b.jpg" % (e["farm"], e["se... | Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes. |
def cli(env):
table = formatting.Table([
'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'
])
table.align['Name'] = 'l'
table.align['Package Name'] = 'r'
table.align['Package Id'] = 'l'
manager = ordering.OrderingManager(env.client)
items = manager.get_quo... | List all active quotes on an account |
def scroll_mouse(self, mouse_x: int):
scrollbar = self.horizontalScrollBar()
if mouse_x - self.view_rect().x() > self.view_rect().width():
scrollbar.setValue(scrollbar.value() + 5)
elif mouse_x < self.view_rect().x():
scrollbar.setValue(scrollbar.value() - 5) | Scrolls the mouse if ROI Selection reaches corner of view
:param mouse_x:
:return: |
def format_index_array_attrs(series):
attrs = {}
for i, axis in zip(range(series.ndim), ('x', 'y')):
unit = '{}unit'.format(axis)
origin = '{}0'.format(axis)
delta = 'd{}'.format(axis)
aunit = getattr(series, unit)
attrs.update({
unit: str(aunit),
... | Format metadata attributes for and indexed array
This function is used to provide the necessary metadata to meet
the (proposed) LIGO Common Data Format specification for series data
in HDF5. |
def _builder_connect_signals(self, _dict):
assert not self.builder_connected, "Gtk.Builder not already connected"
if _dict and not self.builder_pending_callbacks:
GLib.idle_add(self.__builder_connect_pending_signals)
for n, v in _dict.items():
if n not in self.builder_pen... | Called by controllers which want to autoconnect their
handlers with signals declared in internal Gtk.Builder.
This method accumulates handlers, and books signal
autoconnection later on the idle of the next occurring gtk
loop. After the autoconnection is done, this method cannot be
... |
def sendRequest(self, extraHeaders=""):
self.addParam('src', 'mc-python')
params = urlencode(self._params)
url = self._url
if 'doc' in self._file.keys():
headers = {}
if (extraHeaders is not None) and (extraHeaders is dict):
headers = headers.updat... | Sends a request to the URL specified and returns a response only if the HTTP code returned is OK
:param extraHeaders:
Allows to configure additional headers in the request
:return:
Response object set to None if there is an error |
def pexpire(self, key, timeout):
if not isinstance(timeout, int):
raise TypeError("timeout argument must be int, not {!r}"
.format(timeout))
fut = self.execute(b'PEXPIRE', key, timeout)
return wait_convert(fut, bool) | Set a milliseconds timeout on key.
:raises TypeError: if timeout is not int |
def append_with_data(url, data):
if data is None:
return url
url_parts = list(urlparse(url))
query = OrderedDict(parse_qsl(url_parts[4], keep_blank_values=True))
query.update(data)
url_parts[4] = URLHelper.query_dict_to_string(query)
return urlunparse(url_part... | Append the given URL with the given data OrderedDict.
Args:
url (str): The URL to append.
data (obj): The key value OrderedDict to append to the URL.
Returns:
str: The new URL. |
def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):
if not no_warn:
warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning)
fbks = []
datasets = []
try:
datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))
exce... | Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.