Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
376,200 | def upgrade(self, flag):
for pkg in self.binary:
try:
subprocess.call("upgradepkg {0} {1}".format(flag, pkg),
shell=True)
check = pkg[:-4].split("/")[-1]
if os.path.isfile(self.meta.pkg_path + check):
... | Upgrade Slackware binary packages with new |
376,201 | def get_question_ids_for_assessment_part(self, assessment_part_id):
question_ids = []
for question_map in self._my_map[]:
if question_map[] == str(assessment_part_id):
question_ids.append(self.get_question(question_map=question_map).get_id())
return question_... | convenience method returns unique question ids associated with an assessment_part_id |
376,202 | def add_edge(self, from_index, to_index,
weight=None, warn_duplicates=True,
edge_properties=None):
if to_index < from_index:
to_index, from_index = from_index, to_index
from_index, to_index = int(from_index), int(to_inde... | Add edge to graph.
Since physically a 'bond' (or other connection
between sites) doesn't have a direction, from_index,
from_jimage can be swapped with to_index, to_jimage.
However, images will always always be shifted so that
from_index < to_index and from_jimage becomes (0, 0,... |
376,203 | def generate_random_upload_path(instance, filename):
return os.path.join(instance.__class__.__name__.lower(), uuid().hex, filename) | Pass this function to upload_to argument of FileField to store the file on an unguessable path.
The format of the path is class_name/hash/original_filename. |
376,204 | def ensure_compatible(left, right):
conflicts = list(conflicting_pairs(left, right))
if conflicts:
raise ValueError( % conflicts) | Raise an informative ``ValueError`` if the two definitions disagree. |
376,205 | def getUI(prog_name, args):
longDescription = "Given a set of BED intervals, compute a profile of " +\
"conservation by averaging over all intervals using a " +\
"whole genome alignment to a set of relevent species." +\
"\n\n" +\
"Usag... | Build and return user interface object for this script. |
376,206 | def print_annotation(self):
for path, ann in self.annotation.items():
print("{}: {}".format(path, ann[])) | Print annotation "key: value" pairs to standard output. |
376,207 | async def sonar_data_retrieve(self, trigger_pin):
sonar_pin_entry = self.active_sonar_map.get(trigger_pin)
value = sonar_pin_entry[1]
return value | Retrieve Ping (HC-SR04 type) data. The data is presented as a
dictionary.
The 'key' is the trigger pin specified in sonar_config()
and the 'data' is the current measured distance (in centimeters)
for that pin. If there is no data, the value is set to None.
:param trigger_pin: ke... |
376,208 | def parse(self, debug=False):
if self._parsed is None:
try:
if self._mode == "html":
self._parsed = self.html(self._content, self._show_everything, self._translation)
else:
self._parsed = self.rst(self._content, self._s... | Returns parsed text |
376,209 | def gen_gradient(args, resource, inflow, radius, loc, common=True):
return "".join(["GRADIENT_RESOURCE ", str(resource), ":height=",
str(radius), ":plateau=", str(inflow), ":spread=",
str(radius-1), ":common=", str(int(common)),
":updatestep=1000000:p... | Returns a line of text to add to an environment file, initializing a
gradient resource with the specified
name (string), inflow(int), radius(int), and location (tuple of ints) |
376,210 | def set_titles(self, template="{coord} = {value}", maxchar=30,
**kwargs):
import matplotlib as mpl
kwargs["size"] = kwargs.pop("size", mpl.rcParams["axes.labelsize"])
nicetitle = functools.partial(_nicetitle, maxchar=maxchar,
te... | Draw titles either above each facet or on the grid margins.
Parameters
----------
template : string
Template for plot titles containing {coord} and {value}
maxchar : int
Truncate titles at maxchar
kwargs : keyword args
additional arguments to ... |
376,211 | def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
logger = logging.getLogger()
if handler.__class__ in map(type, logger.handlers):
return False
logger.addHandler(handler)
for logger_name in exclude:
logger = logging.getLogger(logger_name)
logger.propagate =... | Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contri... |
376,212 | def _CreateWindowsPathResolver(
self, file_system, mount_point, environment_variables):
if environment_variables is None:
environment_variables = []
path_resolver = windows_path_resolver.WindowsPathResolver(
file_system, mount_point)
for environment_variable in environment_variabl... | Create a Windows path resolver and sets the environment variables.
Args:
file_system (dfvfs.FileSystem): file system.
mount_point (dfvfs.PathSpec): mount point path specification.
environment_variables (list[EnvironmentVariableArtifact]): environment
variables.
Returns:
dfvfs... |
376,213 | def SGg(self):
rargon
Vmg = self.VolumeGas(T=288.70555555555552, P=101325)
if Vmg:
rho = Vm_to_rho(Vmg, self.MW)
return SG(rho, rho_ref=1.2231876628642968)
return None | r'''Specific gravity of the gas phase of the chemical, [dimensionless].
The reference condition is air at 15.6 °C (60 °F) and 1 atm
(rho=1.223 kg/m^3). The definition for gases uses the compressibility
factor of the reference gas and the chemical both at the reference
conditions, not th... |
376,214 | def paula_etree_to_string(tree, dtd_filename):
return etree.tostring(
tree, pretty_print=True, xml_declaration=True,
encoding="UTF-8", standalone=,
doctype=.format(dtd_filename)) | convert a PAULA etree into an XML string. |
376,215 | def dd2dm(dd):
d,m,s = dd2dms(dd)
m = m + float(s)/3600
return d,m,s | Convert decimal to degrees, decimal minutes |
376,216 | def _htpasswd(username, password, **kwargs):
from passlib.apache import HtpasswdFile
pwfile = HtpasswdFile(kwargs[])
if salt.utils.versions.version_cmp(kwargs[], ) < 0:
return pwfile.verify(username, password)
else:
return pwfile.check_password(username, password) | Provide authentication via Apache-style htpasswd files |
376,217 | def get_slo_url(self):
url = None
idp_data = self.__settings.get_idp_data()
if in idp_data.keys() and in idp_data[]:
url = idp_data[][]
return url | Gets the SLO URL.
:returns: An URL, the SLO endpoint of the IdP
:rtype: string |
376,218 | def _store_oauth_access_token(self, oauth_access_token):
c = Cookie(version=0, name=, value=oauth_access_token,
port=None, port_specified=False,
domain=, domain_specified=True, domain_initial_dot=False,
path=, path_specified=True,
secure=False, expires=No... | Called when login is complete to store the oauth access token
This implementation stores the oauth_access_token in a seperate cookie for domain steamwebbrowser.tld |
376,219 | def retries(timeout=30, intervals=1, time=time):
start = time()
end = start + timeout
if isinstance(intervals, Iterable):
intervals = iter(intervals)
else:
intervals = repeat(intervals)
return gen_retries(start, end, intervals, time) | Helper for retrying something, sleeping between attempts.
Returns a generator that yields ``(elapsed, remaining, wait)`` tuples,
giving times in seconds. The last item, `wait`, is the suggested amount of
time to sleep before trying again.
:param timeout: From now, how long to keep iterating, in second... |
376,220 | def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None):
n_input_features = units.get_shape().as_list()[2]
if n_hidden is None:
n_hidden = n_input_features
if n_output_features is None:
n_output_features = n_input_features
units_pairs = tf.concat([... | Computes additive self attention for time series of vectors (with batch dimension)
the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)>
v is a learnable vector of n_hidden dimensionality,
W_1 and W_2 are learnable [n_hidden, n_input_features] matrices
Args:
units: tf tensor w... |
376,221 | def str_to_etree(xml_str, encoding=):
parser = xml.etree.ElementTree.XMLParser(encoding=encoding)
return xml.etree.ElementTree.fromstring(xml_str, parser=parser) | Deserialize API XML doc to an ElementTree.
Args:
xml_str: bytes
DataONE API XML doc
encoding: str
Decoder to use when converting the XML doc ``bytes`` to a Unicode str.
Returns:
ElementTree: Matching the API version of the XML doc. |
376,222 | def will_tag(self):
wanttags = self.retrieve_config(, )
if wanttags == :
if aux.staggerexists:
willtag = True
else:
willtag = False
print(("You want me to tag {0}, but you have not installed "
"the St... | Check whether the feed should be tagged |
376,223 | def list_market_catalogue(self, filter=market_filter(), market_projection=None, sort=None, max_results=1,
locale=None, session=None, lightweight=None):
params = clean_locals(locals())
method = % (self.URI, )
(response, elapsed_time) = self.request(method, ... | Returns a list of information about published (ACTIVE/SUSPENDED) markets
that does not change (or changes very rarely).
:param dict filter: The filter to select desired markets
:param list market_projection: The type and amount of data returned about the market
:param str sort: The orde... |
376,224 | def _get_network(self, network_info):
org_name = network_info.get(, )
part_name = network_info.get(, )
segment_id = network_info[]
url = self._network_url % (org_name, part_name, segment_id)
return self._send_request(, url, , ) | Send network get request to DCNM.
:param network_info: contains network info to query. |
376,225 | def _generate_reversed_sql(self, keys, changed_keys):
for key in keys:
if key not in changed_keys:
continue
app_label, sql_name = key
old_item = self.from_sql_graph.nodes[key]
new_item = self.to_sql_graph.nodes[key]
if not old_... | Generate reversed operations for changes, that require full rollback and creation. |
376,226 | def cleanup_kernels(self):
self.log.info()
km = self.kernel_manager
for kid in list(km.kernel_ids):
km.shutdown_kernel(kid) | shutdown all kernels
The kernels will shutdown themselves when this process no longer exists,
but explicit shutdown allows the KernelManagers to cleanup the connection files. |
376,227 | def _proxy(self):
if self._context is None:
self._context = ShortCodeContext(
self._version,
account_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ShortCodeContext for this ShortCodeInstance
:rtype: twilio.rest.api.v2010.account.short_code.ShortCodeContext |
376,228 | def dump(self, itemkey, filename=None, path=None):
if not filename:
filename = self.item(itemkey)["data"]["filename"]
if path:
pth = os.path.join(path, filename)
else:
pth = filename
file = self.file(itemkey)
if self.snapshot:
... | Dump a file attachment to disk, with optional filename and path |
376,229 | def build(template=, host=None, scheme=None, port=None, **template_vars):
parsed_host = urlparse.urlparse(host if host is not None else )
host_has_scheme = bool(parsed_host.scheme)
if host_has_scheme:
host = parsed_host.netloc
scheme = pars... | Builds a url with a string template and template variables; relative path if host is None, abs otherwise:
template format: "/staticendpoint/{dynamic_endpoint}?{params}" |
376,230 | def help_center_articles_attachment_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/article_attachments
api_path = "/api/v2/help_center/articles/attachments/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwa... | https://developer.zendesk.com/rest_api/docs/help_center/article_attachments#delete-article-attachment |
376,231 | def stop_times(self):
stop_times = set()
for trip in self.trips():
stop_times |= trip.stop_times()
return stop_times | Return all stop_times for this agency. |
376,232 | def fetch_next_page(self, data):
pagingnext
next_url = data[][]
if next_url != None:
next_data = self.http._post_data(next_url, None, self.http._headers_with_access_token())
return next_data
else:
return None | Fetches next page based on previously fetched data.
Will get the next page url from data['paging']['next'].
:param data: previously fetched API response.
:type data: dict
:return: API response.
:rtype: dict |
376,233 | def parse_from_parent(
self,
parent,
state
):
xml_value = self._processor.parse_from_parent(parent, state)
return _hooks_apply_after_parse(self._hooks, state, xml_value) | Parse the element from the given parent element. |
376,234 | def get_source_name(self, name):
if name not in self.like.sourceNames():
name = self.roi.get_source_by_name(name).name
return name | Return the name of a source as it is defined in the
pyLikelihood model object. |
376,235 | def register_list(self):
num_items = self.MAX_NUM_CPU_REGISTERS
buf = (ctypes.c_uint32 * num_items)()
num_regs = self._dll.JLINKARM_GetRegisterList(buf, num_items)
return buf[:num_regs] | Returns a list of the indices for the CPU registers.
The returned indices can be used to read the register content or grab
the register name.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of registers. |
376,236 | def read_hip(self, length, extension):
if length is None:
length = len(self)
_next = self._read_protos(1)
_hlen = self._read_unpack(1)
_type = self._read_binary(1)
if _type[0] != :
raise ProtocolError()
_vers = self._read_binary(1)
... | Read Host Identity Protocol.
Structure of HIP header [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... |
376,237 | async def send_document(self, path, entity):
await self.send_file(
entity, path,
force_document=True,
progress_callback=self.upload_progress_callback
)
print() | Sends the file located at path to the desired entity as a document |
376,238 | def to_html(self, wrap_slash=False):
if self.text is None:
return
else:
text =
for t in self.text:
text += t.to_html() +
text = .join(text.split())
if wrap_slash:
text = text.replace(, )
... | Render a Text MessageElement as html.
:param wrap_slash: Whether to replace slashes with the slash plus the
html <wbr> tag which will help to e.g. wrap html in small cells if
it contains a long filename. Disabled by default as it may cause
side effects if the text contains h... |
376,239 | def assignees(self):
if in self._json_data and self._json_data.get() == list():
return []
elif in self._json_data and self._json_data.get():
assignees_ids_str = .join([str(id) for id in self._json_data.get()])
return self._client.users(id__in=assignees_ids_... | List of assignees to the activity. |
376,240 | def load(self, data):
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(self.loader, data, objs) | Load a single row of data and convert it into entities and
relations. |
376,241 | def dip_pval_tabinterpol(dip, N):
if np.isnan(N) or N < 10:
return np.nan
qDiptab_dict = {: {4: 0.125,
5: 0.1,
6: 0.0833333333333333,
7: 0.0714285714285714,
8: 0.0625,
9: 0.0555555555555556,
10: 0.05,
15: 0.0341378172277919,
20: 0.0337185... | dip - dip value computed from dip_from_cdf
N - number of observations |
376,242 | def conditional_http_tween_factory(handler, registry):
settings = registry.settings if hasattr(registry, ) else {}
if in settings:
route_names = settings.get().split()
GENERATE_ETAG_ROUTE_NAMES.update(route_names)
def conditional_http_tween(request):
response = handler(request... | Tween that adds ETag headers and tells Pyramid to enable
conditional responses where appropriate. |
376,243 | def main(url, lamson_host, lamson_port, lamson_debug):
try:
worker = LamsonWorker(url=url,
lamson_host=lamson_host,
lamson_port=lamson_port,
lamson_debug=lamson_debug)
worker.connect()
worker.run_f... | Create, connect, and block on the Lamson worker. |
376,244 | def deleteRows(self, login, tableName, startRow, endRow):
self.send_deleteRows(login, tableName, startRow, endRow)
self.recv_deleteRows() | Parameters:
- login
- tableName
- startRow
- endRow |
376,245 | def list_to_str(lst):
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = .join(lst)
elif len(lst) > 2:
str_ = .join(lst[:-1])
str_ += .format(lst[-1])
else:
raise ValueError()
return str_ | Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``. |
376,246 | def as_dict(self, voigt=False):
input_array = self.voigt if voigt else self
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"input_array": input_array.tolist()}
if voigt:
d.update({"voigt": voigt})
return d | Serializes the tensor object
Args:
voigt (bool): flag for whether to store entries in
voigt-notation. Defaults to false, as information
may be lost in conversion.
Returns (Dict):
serialized format tensor object |
376,247 | def regulartype(prompt_template="default"):
echo_prompt(prompt_template)
command_string = ""
cursor_position = 0
with raw_mode():
while True:
in_char = getchar()
if in_char in {ESC, CTRLC}:
echo(carriage_return=True)
raise click.Abort(... | Echo each character typed. Unlike magictype, this echos the characters the
user is pressing.
Returns: command_string | The command to be passed to the shell to run. This is
| typed by the user. |
376,248 | def convert_ligatures(text_string):
if text_string is None or text_string == "":
return ""
elif isinstance(text_string, str):
for i in range(0, len(LIGATURES)):
text_string = text_string.replace(LIGATURES[str(i)]["ligature"], LIGATURES[str(i)]["term"])
return text_string... | Coverts Latin character references within text_string to their corresponding unicode characters
and returns converted string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument |
376,249 | def follow_directories_loaded(self, fname):
if self._to_be_loaded is None:
return
path = osp.normpath(to_text_string(fname))
if path in self._to_be_loaded:
self._to_be_loaded.remove(path)
if self._to_be_loaded is not None and len(self._to_be_loaded... | Follow directories loaded during startup |
376,250 | def create_document(
self,
parent,
collection_id,
document_id,
document,
mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "create_document"... | Creates a new document.
Example:
>>> from google.cloud import firestore_v1beta1
>>>
>>> client = firestore_v1beta1.FirestoreClient()
>>>
>>> parent = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]')
>>>
... |
376,251 | def screen_to_client(self, x, y):
return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) ) | Translates window screen coordinates to client coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.screen_to_client}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@pa... |
376,252 | def get_build_properties(self, project, build_id, filter=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if build_id is not None:
route_values[] = self._serialize.url(, build_id, )
query_parameters = {}
... | GetBuildProperties.
[Preview API] Gets properties for a build.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param [str] filter: A comma-delimited list of properties. If specified, filters to these specific properties.
:rtype: :class:`<... |
376,253 | def id_fix(value):
if value.startswith():
pass
else:
value = value.replace(,)
if value.startswith() or value.startswith() or value.startswith() or value.startswith() or value.startswith():
value = + value
elif value.startswith() or value.startswith():
... | fix @prefix values for ttl |
376,254 | def first(self):
if self.mode == :
return self.values[0]
if self.mode == :
return self.values.first().toarray() | Return the first element. |
376,255 | def __process_requests_stack(self):
while self.__requests_stack:
try:
exec self.__requests_stack.popleft() in self.__locals
except Exception as error:
umbra.exceptions.notify_exception_handler(error) | Process the requests stack. |
376,256 | def Random(self):
if len(self.d) == 0:
raise ValueError()
target = random.random()
total = 0.0
for x, p in self.d.iteritems():
total += p
if total >= target:
return x
assert False | Chooses a random element from this PMF.
Returns:
float value from the Pmf |
376,257 | def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT):
msg_info = MessageInfo(msg=msg, wait_nak=wait_nak,
wait_timeout=wait_timeout)
_LOGGER.debug("Queueing msg: %s", msg)
self._send_queue.put_nowait(msg_info) | Place a message on the send queue for sending.
Message are sent in the order they are placed in the queue. |
376,258 | def get_wsgi_app(self, name=None, defaults=None):
name = self._maybe_get_default_name(name)
defaults = self._get_defaults(defaults)
return loadapp(
self.pastedeploy_spec,
name=name,
relative_to=self.relative_to,
global_conf=defaults,
... | Reads the configuration source and finds and loads a WSGI
application defined by the entry with name ``name`` per the
PasteDeploy configuration format and loading mechanism.
:param name: The named WSGI app to find, load and return. Defaults to
``None`` which becomes ``main`` inside
... |
376,259 | def echo_percent(self,transferred=1, status=None):
self.transferred += transferred
self.status = status or self.status
end_str = "\r"
if self.transferred == self.toBeTransferred:
end_str =
self.status = status or self.fin_status
print(sel... | Sample usage:
f=lambda x,y:x+y
ldata = range(10)
toBeTransferred = reduce(f,range(10))
import time
progress = ProgressBarUtils("viewbar", toBeTransferred=toBeTransferred, run_status="正在下载", fin_status="下载完成")
for i in ldata:... |
376,260 | def is_subset(self, other):
if isinstance(other, _basebag):
for elem, count in self.counts():
if not count <= other.count(elem):
return False
else:
for elem in self:
if self.count(elem) > 1 or elem not in other:
return False
return True | Check that every element in self has a count <= in other.
Args:
other (Set) |
376,261 | def pxe_netboot(self, filename):
new_port = {
: [
{: , : + filename, : 4, },
{: , : , : },
{: , : , : }
]
}
self.neutron.update_port(self._provision_port_id, {: new_port}) | Specify which file ipxe should load during the netboot. |
376,262 | def sqrt(scalar):
if isinstance(scalar, ScalarValue):
scalar = scalar.val
if scalar == 1:
return One
elif scalar == 0:
return Zero
elif isinstance(scalar, (float, complex, complex128, float64)):
return ScalarValue.create(numpy.sqrt(scalar))
elif isinstance(scalar... | Square root of a :class:`Scalar` or scalar value
This always returns a :class:`Scalar`, and uses a symbolic square root if
possible (i.e., for non-floats)::
>>> sqrt(2)
sqrt(2)
>>> sqrt(2.0)
1.414213...
For a :class:`ScalarExpression` argument, it returns a
:class:`Sc... |
376,263 | def _log(self, content):
self._buffer += content
if self._auto_flush:
self.flush() | Write a string to the log |
376,264 | def ProcessHuntClientCrash(flow_obj, client_crash_info):
if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id):
hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id)
return
hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt_id)
with aff4.FACTORY.Open(hunt_urn, mode="rw") as fd:
f... | Processes client crash triggerted by a given hunt-induced flow. |
376,265 | def deserialize(cls, did_doc: dict) -> :
rv = None
if in did_doc:
rv = DIDDoc(did_doc[])
else:
if not in did_doc:
LOGGER.debug()
raise AbsentDIDDocItem()
for pubkey in did_doc[]:
pubkey_did = canon_... | Construct DIDDoc object from dict representation.
Raise BadIdentifier for bad DID.
:param did_doc: DIDDoc dict reprentation.
:return: DIDDoc from input json. |
376,266 | def readdir(self, path, fh):
log.debug(.format(path))
try:
dir = self._directory_cache[path]
except KeyError:
dir = self._get_directory(path)
self._directory_cache[path] = dir
return dir | Called by FUSE when a directory is opened.
Returns a list of file and directory names for the directory. |
376,267 | def com_google_fonts_check_contour_count(ttFont):
from fontbakery.glyphdata import desired_glyph_data as glyph_data
from fontbakery.utils import (get_font_glyph_data,
pretty_print_list)
desired_glyph_data = {}
for glyph in glyph_data:
desired_glyph_data[glyph[]] = glyph... | Check if each glyph has the recommended amount of contours.
This check is useful to assure glyphs aren't incorrectly constructed.
The desired_glyph_data module contains the 'recommended' countour count
for encoded glyphs. The contour counts are derived from fonts which were
chosen for their quality and unique... |
376,268 | def _filter_link_tag_data(self, source, soup, data, url):
link = FILTER_MAPS[][source]
html = soup.find_all(, {link[]: link[]})
if link[] == :
for line in html:
data[] = line.get()
else:
for line in html:
data[].append({
... | This method filters the web page content for link tags that match patterns given in the ``FILTER_MAPS``
:param source: The key of the meta dictionary in ``FILTER_MAPS['link']``
:type source: string
:param soup: BeautifulSoup instance to find meta tags
:type soup: instance
:param... |
376,269 | def get_segment_count_data(self, start, end, use_shapes=True):
cur = self.conn.cursor()
trips_df = self.get_tripIs_active_in_range(start, end)
segment_counts = Counter()
seg_to_info = {}
tripI_to_seq = defaultdict(list)
for ro... | Get segment data including PTN vehicle counts per segment that are
fully _contained_ within the interval (start, end)
Parameters
----------
start : int
start time of the simulation in unix time
end : int
end time of the simulation in unix time
use... |
376,270 | def upload_part(self, data, index=None, display_progress=False, report_progress_fn=None, **kwargs):
if not USING_PYTHON2:
assert(isinstance(data, bytes))
req_input = {}
if index is not None:
req_input["index"] = int(index)
md5 = hashlib.md5... | :param data: Data to be uploaded in this part
:type data: str or mmap object, bytes on python3
:param index: Index of part to be uploaded; must be in [1, 10000]
:type index: integer
:param display_progress: Whether to print "." to stderr when done
:type display_progress: boolean
... |
376,271 | def configfilepopulator(self):
self.forwardlength = self.metadata.header.forwardlength
self.reverselength = self.metadata.header.reverselength
cycles = [[1, self.forwardlength, self.runid],
[self.forwardlength + 1, self.forwardlength + 8, sel... | Populates an unpopulated config.xml file with run-specific values and creates
the file in the appropriate location |
376,272 | def circumcenter(pt0, pt1, pt2):
r
a_x = pt0[0]
a_y = pt0[1]
b_x = pt1[0]
b_y = pt1[1]
c_x = pt2[0]
c_y = pt2[1]
bc_y_diff = b_y - c_y
ca_y_diff = c_y - a_y
ab_y_diff = a_y - b_y
cb_x_diff = c_x - b_x
ac_x_diff = a_x - c_x
ba_x_diff = b_x - a_x
d_div = (a_x * bc... | r"""Calculate and return the circumcenter of a circumcircle generated by a given triangle.
All three points must be unique or a division by zero error will be raised.
Parameters
----------
pt0: (x, y)
Starting vertex of triangle
pt1: (x, y)
Second vertex of triangle
pt2: (x, y)... |
376,273 | def fitNull(self, verbose=False, cache=False, out_dir=, fname=None, rewrite=False, seed=None, n_times=10, factr=1e3, init_method=None):
if seed is not None: sp.random.seed(seed)
read_from_file = False
if cache:
assert fname is not None,
if not os.path.exists... | Fit null model |
376,274 | def add_perm(self, subj_str, perm_str):
self._assert_valid_permission(perm_str)
self._perm_dict.setdefault(perm_str, set()).add(subj_str) | Add a permission for a subject.
Args:
subj_str : str
Subject for which to add permission(s)
perm_str : str
Permission to add. Implicitly adds all lower permissions. E.g., ``write``
will also add ``read``. |
376,275 | def resizeEvent(self, event):
curr_item = self.currentItem()
self.closePersistentEditor(curr_item)
super(XMultiTagEdit, self).resizeEvent(event) | Overloads the resize event to control if we are still editing.
If we are resizing, then we are no longer editing. |
376,276 | def shebang(self):
with open(self.path, ) as file_handle:
hashtag = file_handle.read(2)
if hashtag == b:
file_handle.seek(0)
return file_handle.readline().decode()
return None | Get the file shebang if is has one. |
376,277 | def in6_getnsma(a):
r = in6_and(a, inet_pton(socket.AF_INET6, ))
r = in6_or(inet_pton(socket.AF_INET6, ), r)
return r | Return link-local solicited-node multicast address for given
address. Passed address must be provided in network format.
Returned value is also in network format. |
376,278 | def is_excluded_for_sdesc(self, sdesc, is_tpl=False):
if not is_tpl and self.service_includes:
return sdesc not in self.service_includes
if self.service_excludes:
return sdesc in self.service_excludes
return False | Check whether this host should have the passed service *description*
be "excluded" or "not included".
:param sdesc: service description
:type sdesc:
:param is_tpl: True if service is template, otherwise False
:type is_tpl: bool
:return: True if service description ex... |
376,279 | def do_replace(eval_ctx, s, old, new, count=None):
if count is None:
count = -1
if not eval_ctx.autoescape:
return unicode(s).replace(unicode(old), unicode(new), count)
if hasattr(old, ) or hasattr(new, ) and \
not hasattr(s, ):
s = escape(s)
else:
s = soft_un... | Return a copy of the value with all occurrences of a substring
replaced with a new one. The first argument is the substring
that should be replaced, the second is the replacement string.
If the optional third argument ``count`` is given, only the first
``count`` occurrences are replaced:
.. sourcec... |
376,280 | def forge_fdf(pdf_form_url=None, fdf_data_strings=[], fdf_data_names=[],
fields_hidden=[], fields_readonly=[],
checkbox_checked_name=b"Yes"):
fdf = [b]
fdf.append(b)
fdf.append(b)
fdf.append(b.join(handle_data_strings(fdf_data_strings,
... | Generates fdf string from fields specified
* pdf_form_url (default: None): just the url for the form.
* fdf_data_strings (default: []): array of (string, value) tuples for the
form fields (or dicts). Value is passed as a UTF-16 encoded string,
unless True/False, in which case it is assumed to be a ... |
376,281 | def triples_to_graph(self, triples, top=None):
inferred_top = triples[0][0] if triples else None
ts = []
for triple in triples:
if triple[0] == self.TOP_VAR and triple[1] == self.TOP_REL:
inferred_top = triple[2]
else:
ts.append(se... | Create a Graph from *triples* considering codec configuration.
The Graph class does not know about information in the codec,
so if Graph instantiation depends on special `TYPE_REL` or
`TOP_VAR` values, use this function instead of instantiating
a Graph object directly. This is also wher... |
376,282 | def _check_dir(self):
from os import path, mkdir
if not path.isdir(self.dirpath):
mkdir(self.dirpath)
ftypes = path.join(get_fortpy_templates(), "ftypes.py")
from shutil import copy
copy(ftypes, self.dirpath)
... | Makes sure that the working directory for the wrapper modules exists. |
376,283 | def new_file(self, basedir):
title = _("New file")
filters = _("All files")+" (*)"
def create_func(fname):
if osp.splitext(fname)[1] in (, , ):
create_script(fname)
else:
with open(fname, ) as f:
... | New file |
376,284 | def update_resolver_nameservers(resolver, nameservers, nameserver_filename):
if nameservers:
resolver.nameservers = nameservers
elif nameserver_filename:
nameservers = get_stripped_file_lines(nameserver_filename)
resolver.nameservers = nameservers
else:
pass
... | Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the resolver |
376,285 | def gen_reference_primitive(polypeptide, start, end):
prim = polypeptide.primitive
q = find_foot(a=start, b=end, p=prim.coordinates[0])
ax = Axis(start=q, end=end)
if not is_acute(polypeptide_vector(polypeptide), ax.unit_tangent):
ax = Axis(start=end, end=q)
arc_length = 0
poin... | Generates a reference Primitive for a Polypeptide given start and end coordinates.
Notes
-----
Uses the rise_per_residue of the Polypeptide primitive to define the separation of points on the line joining
start and end.
Parameters
----------
polypeptide : Polypeptide
start : numpy.arra... |
376,286 | def execute(self, args):
if args.name is not None:
self.show_workspace(slashes2dash(args.name))
elif args.all is not None:
self.show_all() | Execute show subcommand. |
376,287 | def get_network_name(network_id):
if os.environ.get():
logging.debug(.format(
os.environ.get()))
return os.environ.get()
return Keeper._network_name_map.get(network_id, Keeper.DEFAULT_NETWORK_NAME) | Return the keeper network name based on the current ethereum network id.
Return `development` for every network id that is not mapped.
:param network_id: Network id, int
:return: Network name, str |
376,288 | def p_catch(self, p):
p[0] = self.asttypes.Catch(identifier=p[3], elements=p[5])
p[0].setpos(p) | catch : CATCH LPAREN identifier RPAREN block |
376,289 | def list_commands(self, ctx):
commands = set(self.list_resource_commands())
commands.union(set(self.list_misc_commands()))
return sorted(commands) | Return a list of commands present in the commands and resources
folders, but not subcommands. |
376,290 | def coactivation(dataset, seed, threshold=0.0, output_dir=, prefix=, r=6):
if isinstance(seed, string_types):
ids = dataset.get_studies(mask=seed, activation_threshold=threshold)
else:
ids = dataset.get_studies(peaks=seed, r=r,
activation_threshold=thresho... | Compute and save coactivation map given input image as seed.
This is essentially just a wrapper for a meta-analysis defined
by the contrast between those studies that activate within the seed
and those that don't.
Args:
dataset: a Dataset instance containing study and activation data.
seed... |
376,291 | def cylrec(r, lon, z):
r = ctypes.c_double(r)
lon = ctypes.c_double(lon)
z = ctypes.c_double(z)
rectan = stypes.emptyDoubleVector(3)
libspice.cylrec_c(r, lon, z, rectan)
return stypes.cVectorToPython(rectan) | Convert from cylindrical to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/cylrec_c.html
:param r: Distance of a point from z axis.
:type r: float
:param lon: Angle (radians) of a point from xZ plane.
:type lon: float
:param z: Height of a point above xY plane... |
376,292 | def read(path, attribute, **kwargs):
**
kwargs = salt.utils.args.clean_kwargs(**kwargs)
hex_ = kwargs.pop(, False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
cmd = [, ]
if hex_:
cmd.append()
cmd.extend([attribute, path])
try:
ret = salt.utils.mac_utils.ex... | Read the given attributes on the given file/directory
:param str path: The file to get attributes from
:param str attribute: The attribute to read
:param bool hex: Return the values with forced hexadecimal values
:return: A string containing the value of the named attribute
:rtype: str
:rai... |
376,293 | def ldap_server_host_port(self, **kwargs):
config = ET.Element("config")
ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(ldap_server, "host")
hostname_key = ET.SubElement(host, "hostname")
hostname_key.tex... | Auto Generated Code |
376,294 | def bounding_polygon(self):
lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom)
print(lon_left, lat_bottom, lon_right, lat_top)
return Polygon([[[lon_left, lat_top],
[lon_right, lat_top],
[lon_right... | Returns the bounding box polygon for this tile
:return: `pywom.utils.geo.Polygon` instance |
376,295 | def _build_host_livestate(self, host_name, livestate):
state = livestate.get(, ).upper()
output = livestate.get(, )
long_output = livestate.get(, )
perf_data = livestate.get(, )
try:
timestamp = int(livestate.get(, ))
except ValueError:
... | Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:param livestate: livestate dictionary
:return: external command line |
376,296 | def _on_response(self, response):
_LOGGER.debug(
"Scheduling callbacks for %s messages.", len(response.received_messages)
)
items = [
requests.ModAckRequest(message.ack_id, self._ack_histogram.percentile(99))
for message in respons... | Process all received Pub/Sub messages.
For each message, send a modified acknowledgment request to the
server. This prevents expiration of the message due to buffering by
gRPC or proxy/firewall. This makes the server and client expiration
timer closer to each other thus preventing the m... |
376,297 | def min(self, key=None):
if key is None:
return self.reduce(min)
return self.reduce(lambda a, b: min(a, b, key=key)) | Find the minimum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0 |
376,298 | def queryMulti(self, queries):
self.lastError = None
self.affectedRows = 0
self.rowcount = None
self.record = None
cursor = None
try:
try:
self._GetConnection()
cursor = self.conn.getCursor()
for query in queries:
self.conn.query = query
if query.__class__ == [].__class__... | Execute a series of Deletes,Inserts, & Updates in the Queires List
@author: Nick Verbeck
@since: 9/7/2008 |
376,299 | def next(self):
t = time.time()
if len(self._agents_to_act) == 0:
self._init_step()
addr = self._agents_to_act.pop(0)
aiomas.run(until=self.env.trigger_act(addr=addr))
t2 = time.time()
self._step_processing_time += t2 - t
i... | Trigger next agent to :py:meth:`~creamas.core.CreativeAgent.act` in
the current step. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.