Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
383,500 | def to_html(
self,
suppress_newlines=False,
in_div_flag=False):
if in_div_flag or self.in_div_flag:
message = % self.html_attributes()
else:
message =
last_was_text = False
for m in self.message:
if la... | Render a MessageElement as html.
:param suppress_newlines: Whether to suppress any newlines in the
output. If this option is enabled, the entire html output will be
rendered on a single line.
:type suppress_newlines: bool
:param in_div_flag: Whether the message should b... |
383,501 | def xyz2lonlat(x, y, z):
lon = xu.rad2deg(xu.arctan2(y, x))
lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))
return lon, lat | Convert cartesian to lon lat. |
383,502 | def authenticate(self,
username=None, password=None,
actions=None, response=None,
authorization=None):
if response is None:
with warnings.catch_warnings():
_ignore_warnings(self)
response... | Authenticate to the registry using a username and password,
an authorization header or otherwise as the anonymous user.
:param username: User name to authenticate as.
:type username: str
:param password: User's password.
:type password: str
:param actions: If you know ... |
383,503 | def dataReceived(self, data):
try:
address = self.guid
data = json.loads(data)
threads.deferToThread(send_signal, self.dispatcher, data)
if in data:
return self.dispatcher.subscribe(self.transport, data)
if in data:
... | Takes "data" which we assume is json encoded
If data has a subject_id attribute, we pass that to the dispatcher
as the subject_id so it will get carried through into any
return communications and be identifiable to the client
falls back to just passing the message along.... |
383,504 | def stem(self, word, alternate_vowels=False):
word = normalize(, word.lower())
word = word.replace(, )
if len(word) > 2:
for i in range(2, len(word)):
if word[i] in self._vowels and word[i - 2] in self._vowels:
if word[i - 1] == ... | Return Snowball German stem.
Parameters
----------
word : str
The word to stem
alternate_vowels : bool
Composes ae as ä, oe as ö, and ue as ü before running the algorithm
Returns
-------
str
Word stem
Examples
... |
383,505 | def set_shape(self, id, new_shape):
old_shape = self.id_to_shape[id]
old_buffer = self.get_buffer(old_shape)
model, color = old_buffer.get(id)
new_data = self._create_turtle(id, new_shape, model, color)
old_buffer.remove(id)
self.id_to_shape[id] = new_shape
... | Copies the turtle data from the old shape buffer to the new |
383,506 | def _Initialize(self, http, url):
self.EnsureUninitialized()
if self.http is None:
self.__http = http or http_wrapper.GetHttp()
self.__url = url | Initialize this download by setting self.http and self.url.
We want the user to be able to override self.http by having set
the value in the constructor; in that case, we ignore the provided
http.
Args:
http: An httplib2.Http instance or None.
url: The url for this ... |
383,507 | def offer(self, item):
try:
self._buffer.put(item, block=False)
if self._consumer_callback is not None:
self._consumer_callback()
return True
except Queue.Full:
Log.debug("%s: Full in offer()" % str(self))
raise Queue.Full | Offer to the buffer
It is a non-blocking operation, and when the buffer is full, it raises Queue.Full exception |
383,508 | def _clean_up_gene_id(geneid, sp, curie_map):
geneid = re.sub(r, , geneid)
geneid = re.sub(r, , geneid)
geneid = re.sub(r, , geneid)
if sp == :
if re.match(r, geneid):
geneid = re.sub(
r,
... | A series of identifier rewriting to conform with
standard gene identifiers.
:param geneid:
:param sp:
:return: |
383,509 | def do_mumble(self, args):
repetitions = args.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
output = []
if random.random() < .33:
output.append(random.choice(self.MUMBLE_FIRST))
for word in args.words:
if rando... | Mumbles what you tell me to. |
383,510 | def MergeData(self, merge_data, raw_data=None):
self.FlushCache()
if raw_data is None:
raw_data = self.raw_data
for k, v in iteritems(merge_data):
if isinstance(v, dict) and k not in self.type_infos:
if k not in self.valid_contexts:
raise InvalidContextError("Inval... | Merges data read from a config file into the current config. |
383,511 | def printDuplicatedTPEDandTFAM(tped, tfam, samples, oldSamples, prefix):
outputTPED = None
try:
outputTPED = open(prefix + ".duplicated_samples.tped", "w")
except IOError:
msg = "%(prefix)s.duplicated_samples.tped: cant write " \
"file" % locals()
raise Progra... | Print the TPED and TFAM of the duplicated samples.
:param tped: the ``tped`` containing duplicated samples.
:param tfam: the ``tfam`` containing duplicated samples.
:param samples: the updated position of the samples in the tped containing
only duplicated samples.
:param oldSamples:... |
383,512 | def increment(self, delta=1, text=None):
return self.update(value=min(self.max, self.value + delta), text=text) | Redraw the progress bar, incrementing the value by delta
(default=1) and optionally changing the text. Returns the
ProgressBar's new value. See also .update(). |
383,513 | def _proc_member(self, tarfile):
if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK):
return self._proc_gnulong(tarfile)
elif self.type == GNUTYPE_SPARSE:
return self._proc_sparse(tarfile)
elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE):
return... | Choose the right processing method depending on
the type and call it. |
383,514 | def attach_tracker(self, stanza, tracker=None):
if stanza.xep0184_received is not None:
raise ValueError(
"requesting delivery receipts for delivery receipts is not "
"allowed"
)
if stanza.type_ == aioxmpp.MessageType.ERROR:
ra... | Return a new tracker or modify one to track the stanza.
:param stanza: Stanza to track.
:type stanza: :class:`aioxmpp.Message`
:param tracker: Existing tracker to attach to.
:type tracker: :class:`.tracking.MessageTracker`
:raises ValueError: if the stanza is of type
... |
383,515 | def remove(self, elem):
self._values.remove(elem)
self._message_listener.Modified() | Removes an item from the list. Similar to list.remove(). |
383,516 | def _lstrip_word(word, prefix):
if six.text_type(word).startswith(prefix):
return six.text_type(word)[len(prefix):]
return word | Return a copy of the string after the specified prefix was removed
from the beginning of the string |
383,517 | def stat(filename, retry_params=None, _account_id=None):
common.validate_file_path(filename)
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
status, headers, content = api.head_object(
api_utils._quote_filename(filename))
errors... | Get GCSFileStat of a Google Cloud storage file.
Args:
filename: A Google Cloud Storage filename of form '/bucket/filename'.
retry_params: An api_utils.RetryParams for this call to GCS. If None,
the default one is used.
_account_id: Internal-use only.
Returns:
a GCSFileStat object containing ... |
383,518 | def get_heat_capacity(self, temperature, structure, n, u, cutoff=1e2):
k = 1.38065e-23
kt = k*temperature
hbar_w = 1.05457e-34*self.omega(structure, n, u)
if hbar_w > kt * cutoff:
return 0.0
c = k * (hbar_w / kt) ** 2
c *= np.exp(hbar_w / kt) / (np.ex... | Gets the directional heat capacity for a higher order tensor
expansion as a function of direction and polarization.
Args:
temperature (float): Temperature in kelvin
structure (float): Structure to be used in directional heat
capacity determination
n (... |
383,519 | def nodeprep(string, allow_unassigned=False):
chars = list(string)
_nodeprep_do_mapping(chars)
do_normalization(chars)
check_prohibited_output(
chars,
(
stringprep.in_table_c11,
stringprep.in_table_c12,
stringprep.in_table_c21,
string... | Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised. |
383,520 | def parse(self):
token_type = self.current_token.type.lower()
handler = getattr(self, f, None)
if handler is None:
raise self.error(f)
return handler() | Parse and return an nbt literal from the token stream. |
383,521 | def get_queue_info(self, instance, cursor):
cursor.execute(self.QUEUE_INFO_STATEMENT)
for queue_name, ticker_lag, ev_per_sec in cursor:
yield queue_name, {
: ticker_lag,
: ev_per_sec,
} | Collects metrics for all queues on the connected database. |
383,522 | def _check_valid_translation(self, translation):
if not isinstance(translation, np.ndarray) or not np.issubdtype(translation.dtype, np.number):
raise ValueError()
t = translation.squeeze()
if len(t.shape) != 1 or t.shape[0] != 3:
raise ValueError() | Checks that the translation vector is valid. |
383,523 | def merge_requests(self, **kwargs):
path = % (self.manager.path, self.get_id())
data_list = self.manager.gitlab.http_list(path, as_list=False,
**kwargs)
manager = ProjectMergeRequestManager(self.manager.gitlab,
... | List the merge requests related to this milestone.
Args:
all (bool): If True, return all the items, without pagination
per_page (int): Number of items to retrieve per request
page (int): ID of the page to return (starts with page 1)
as_list (bool): If set to Fals... |
383,524 | def retrieve(self, cursor):
assert isinstance(cursor, dict), "expected cursor type "
query = self.get_query()
assert isinstance(query, peewee.Query)
query
return query.get(**cursor) | Retrieve items from query |
383,525 | def listurl_get(self, q, **kwargs):
request = TOPRequest()
request[] = q
for k, v in kwargs.iteritems():
if k not in (, , ) and v==None: continue
request[k] = v
self.create(self.execute(request), fields=[], models={:TaobaokeItem})
return self.taob... | taobao.taobaoke.listurl.get 淘宝客关键词搜索URL
淘宝客关键词搜索URL |
383,526 | def request(self, location, fragment_enc=False):
_l = as_unicode(location)
_qp = as_unicode(self.to_urlencoded())
if fragment_enc:
return "%s
else:
if "?" in location:
return "%s&%s" % (_l, _qp)
else:
return "%s... | Given a URL this method will add a fragment, a query part or extend
a query part if it already exists with the information in this instance.
:param location: A URL
:param fragment_enc: Whether the information should be placed in a
fragment (True) or in a query part (False)
... |
383,527 | def fetch(self):
params = values.of({})
payload = self._version.fetch(
,
self._uri,
params=params,
)
return VariableInstance(
self._version,
payload,
service_sid=self._solution[],
environment_s... | Fetch a VariableInstance
:returns: Fetched VariableInstance
:rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance |
383,528 | def size(config, accounts=(), day=None, group=None, human=True, region=None):
config = validate.callback(config)
destination = config.get()
client = boto3.Session().client()
day = parse(day)
def export_size(client, account):
paginator = client.get_paginator()
count = 0
... | size of exported records for a given day. |
383,529 | def request(self, url, method=, params=None, data=None,
expected_response_code=200):
url = "{0}/{1}".format(self._baseurl, url)
if params is None:
params = {}
auth = {
: self._username,
: self._password
}
params.upda... | Make a http request to API. |
383,530 | def get_parent_tag(mention):
span = _to_span(mention)
i = _get_node(span.sentence)
return str(i.getparent().tag) if i.getparent() is not None else None | Return the HTML tag of the Mention's parent.
These may be tags such as 'p', 'h2', 'table', 'div', etc.
If a candidate is passed in, only the tag of its first Mention is returned.
:param mention: The Mention to evaluate
:rtype: string |
383,531 | def _item_list(profile=None, **connection_args):
*
kstone = auth(profile, **connection_args)
ret = []
for item in kstone.items.list():
ret.append(item.__dict__)
return ret | Template for writing list functions
Return a list of available items (keystone items-list)
CLI Example:
.. code-block:: bash
salt '*' keystone.item_list |
383,532 | def endswith(self, name: str) -> List[str]:
return sorted(keyword for keyword in self if keyword.endswith(name)) | Return a list of all keywords ending with the given string.
>>> from hydpy.core.devicetools import Keywords
>>> keywords = Keywords('first_keyword', 'second_keyword',
... 'keyword_3', 'keyword_4',
... 'keyboard')
>>> keywords.endswith('key... |
383,533 | def parse_clubs(self, clubs_page):
character_info = self.parse_sidebar(clubs_page)
second_col = clubs_page.find(u, {: }).find(u).find(u).find_all(u, recursive=False)[1]
try:
clubs_header = second_col.find(u, text=u)
character_info[u] = []
if clubs_header:
curr_elt = clubs_hea... | Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes. |
383,534 | def deserialize(self,
node: SchemaNode,
cstruct: Union[str, ColanderNullType]) \
-> Optional[Pendulum]:
if not cstruct:
return colander.null
try:
result = coerce_to_pendulum(cstruct,
... | Deserializes string representation to Python object. |
383,535 | def content_recommendations(access_token, content_item_id):
headers = {: + str(access_token)}
recommendations_url =\
construct_content_recommendations_url(enrichment_url, content_item_id)
request = requests.get(recommendations_url, headers=headers)
if request.status_code == 200:
recommendations = request.j... | Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary |
383,536 | def restore(self, value, context=None):
value = super(DatetimeWithTimezoneColumn, self).restore(value, context)
if value in (, ):
value = datetime.date.now()
if isinstance(value, datetime.datetime):
tz = pytz.timezone(context.timezone)
if tz is not... | Restores the value from a table cache for usage.
:param value | <variant>
context | <orb.Context> || None |
383,537 | def v_unique_name_children(ctx, stmt):
def sort_pos(p1, p2):
if p1.line < p2.line:
return (p1,p2)
else:
return (p2,p1)
dict = {}
chs = stmt.i_children
def check(c):
key = (c.i_module.i_modulename, c.arg)
if key in dict:
dup = di... | Make sure that each child of stmt has a unique name |
383,538 | def print_partlist(input, timeout=20, showgui=False):
print raw_partlist(input=input, timeout=timeout, showgui=showgui) | print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None |
383,539 | def c_join(self, other, psi=-40.76, omega=-178.25, phi=-65.07,
o_c_n_angle=None, c_n_ca_angle=None, c_n_length=None,
relabel=True):
if isinstance(other, Residue):
other = Polypeptide([other])
if not isinstance(other, Polypeptide):
raise Type... | Joins other to self at the C-terminus via a peptide bond.
Notes
-----
This function directly modifies self. It does not return a new object.
Parameters
----------
other: Residue or Polypeptide
psi: float, optional
Psi torsion angle (degrees) between ... |
383,540 | def initializeSessionAsBob(sessionState, sessionVersion, parameters):
sessionState.setSessionVersion(sessionVersion)
sessionState.setRemoteIdentityKey(parameters.getTheirIdentityKey())
sessionState.setLocalIdentityKey(parameters.getOurIdentityKey().getPublicKey())
secrets = byt... | :type sessionState: SessionState
:type sessionVersion: int
:type parameters: BobAxolotlParameters |
383,541 | def a_alpha_and_derivatives(self, T, full=True, quick=True):
r
if not full:
return self.a
else:
a_alpha = self.a
da_alpha_dT = 0.0
d2a_alpha_dT2 = 0.0
return a_alpha, da_alpha_dT, d2a_alpha_dT2 | r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `a`.
.. math::
a\alpha = a
... |
383,542 | def team(self):
team_dict = self._json_data.get()
if team_dict and team_dict.get():
return self._client.team(id=team_dict.get())
else:
return None | Team to which the scope is assigned. |
383,543 | def doc2md(docstr, title, min_level=1, more_info=False, toc=True, maxdepth=0):
text = doctrim(docstr)
lines = text.split()
sections = find_sections(lines)
if sections:
level = min(n for n,t in sections) - 1
else:
level = 1
shiftlevel = 0
if level < min_level:
s... | Convert a docstring to a markdown text. |
383,544 | def getTableMisnestedNodePosition(self):
lastTable = None
fosterParent = None
insertBefore = None
for elm in self.openElements[::-1]:
if elm.name == "table":
lastTable = elm
break
if lastTable:
... | Get the foster parent element, and sibling to insert before
(or None) when inserting a misnested table node |
383,545 | def _ParseValueData(self, knowledge_base, value_data):
if not isinstance(value_data, py2to3.UNICODE_TYPE):
raise errors.PreProcessFail(
.format(
type(value_data), self.ARTIFACT_DEFINITION_NAME))
if not knowledge_base.GetHostname():
hostname_artifact = artifac... | Parses Windows Registry value data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
value_data (object): Windows Registry value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. |
383,546 | def remove_request(self, uuid):
for key in list(self._request):
if self._request[key] == uuid:
del self._request[key] | Remove any RPC request(s) using this uuid.
:param str uuid: Rpc Identifier.
:return: |
383,547 | def fix(self, *args, **kwargs):
self.set(**kwargs)
pnames = list(args) + list(kwargs.keys())
for pname in pnames:
if not pname in self._pnames:
self._error("Naughty. is not a valid fit parameter name.")
else:
... | Turns parameters to constants. As arguments, parameters must be strings.
As keyword arguments, they can be set at the same time.
Note this will NOT work when specifying a non-string fit function,
because there is no flexibility in the number of arguments. To get
around this, su... |
383,548 | def parent_link_record_exists(self):
if not self._initialized:
raise pycdlibexception.PyCdlibInternalError()
return self.dr_entries.pl_record is not None or self.ce_entries.pl_record is not None | Determine whether this Rock Ridge entry has a parent link record (used
for relocating deep directory records).
Parameters:
None:
Returns:
True if this Rock Ridge entry has a parent link record, False otherwise. |
383,549 | def monitor_experiment(args):
if args.time <= 0:
print_error()
exit(1)
while True:
try:
os.system()
update_experiment()
show_experiment_info()
time.sleep(args.time)
except KeyboardInterrupt:
exit(0)
except E... | monitor the experiment |
383,550 | def to_cartesian(r, theta, theta_units="radians"):
assert theta_units in [, ],\
"kwarg theta_units must specified in radians or degrees"
if theta_units == "degrees":
theta = to_radians(theta)
theta = to_proper_radians(theta)
x = r * cos(theta)
y = r * sin(theta)
retu... | Converts polar r, theta to cartesian x, y. |
383,551 | def cpp_app_builder(build_context, target):
yprint(build_context.conf, , target)
if target.props.executable and target.props.main:
raise KeyError(
)
if target.props.executable:
if target.props.executable not in target.artifacts.get(AT.app):
target.artifacts.add(A... | Pack a C++ binary as a Docker image with its runtime dependencies.
TODO(itamar): Dynamically analyze the binary and copy shared objects
from its buildenv image to the runtime image, unless they're installed. |
383,552 | def _carregar(self):
if self._convencao is None:
if self._caminho.endswith((, )):
self._convencao = constantes.WINDOWS_STDCALL
else:
self._convencao = constantes.STANDARD_C
if self._convencao == constantes.STANDARD_C:
loader =... | Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada
ainda não tiver sido definida, será determinada pela extensão do
arquivo da biblioteca.
:raises ValueError: Se a convenção de chamada não puder ser determinada
ou se não for um valor válido. |
383,553 | def fa(a, b, alpha=2):
return np.sum((a > b / alpha) & (a < b * alpha), dtype=float) / len(a) * 100 | Returns the factor of 'alpha' (2 or 5 normally) |
383,554 | def map(self, f_list: List[Callable[[np.ndarray], int]], *, axis: int = 0, chunksize: int = 1000, selection: np.ndarray = None) -> List[np.ndarray]:
return self.layers[""].map(f_list, axis, chunksize, selection) | Apply a function along an axis without loading the entire dataset in memory.
Args:
f: Function(s) that takes a numpy ndarray as argument
axis: Axis along which to apply the function (0 = rows, 1 = columns)
chunksize: Number of rows (columns) to load per chunk
selection: Columns (rows) to include
... |
383,555 | async def close(self):
if self._server:
self._server.close()
self._server = None
self.event().fire() | Stop serving the :attr:`.Server.sockets` and close all
concurrent connections. |
383,556 | def unzip(self, directory):
if not os.path.exists(directory):
os.makedirs(directory)
shutil.copytree(self.src_dir, directory) | Write contents of zipfile to directory |
383,557 | def get_all_item_data(items, conn, graph=None, output=, **kwargs):
if kwargs.get():
template = kwargs.pop()
else:
template = "sparqlAllItemDataTemplate.rq"
template_kwargs = {"prefix": NSM.prefix(), "output": output}
if isinstance(items, list):
template_kwargs[] = ... | queries a triplestore with the provided template or uses a generic
template that returns triples 3 edges out in either direction from the
provided item_uri
args:
items: the starting uri or list of uris to the query
conn: the rdfframework triplestore connection to query against
outpu... |
383,558 | def _worker_fn(samples, batchify_fn, dataset=None):
global _worker_dataset
batch = batchify_fn([_worker_dataset[i] for i in samples])
buf = io.BytesIO()
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(batch)
return buf.getvalue() | Function for processing data in worker process. |
383,559 | def is_up(coordinate, current_time):
cfht.date = current_time.iso.replace(, )
cfht.horizon = math.radians(-7)
sun.compute(cfht)
sun_rise = Time(str(sun.rise_time).replace(, ))
sun_set = Time(str(sun.set_time).replace(, ))
if current_time < sun_set or current_time > sun_rise:
return... | Given the position and time determin if the given target is up.
@param coordinate: the J2000 location of the source
@param current_time: The time of the observations
@return: True/False |
383,560 | def create_comment_commit(self, body, commit_id, path, position, pr_id):
comments_url = f"{self.GITHUB_API_URL}/repos/{self.user}/{self.repo}/pulls/{pr_id}/comments"
data = {: body, : commit_id, : path, : position}
return requests.post(comments_url, json=data, headers=self.auth_header) | Posts a comment to a given commit at a certain pull request.
Check https://developer.github.com/v3/pulls/comments/#create-a-comment
param body: str -> Comment text
param commit_id: str -> SHA of the commit
param path: str -> Relative path of the file to be commented
param positi... |
383,561 | def library(self):
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query()
return Library(self, data)
... | Library to browse or search your media. |
383,562 | def is_consonant(note1, note2, include_fourths=True):
return (is_perfect_consonant(note1, note2, include_fourths) or
is_imperfect_consonant(note1, note2)) | Return True if the interval is consonant.
A consonance is a harmony, chord, or interval considered stable, as
opposed to a dissonance.
This function tests whether the given interval is consonant. This
basically means that it checks whether the interval is (or sounds like)
a unison, third, sixth, p... |
383,563 | def unique_items(seq):
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] | Return the unique items from iterable *seq* (in order). |
383,564 | def remote_image_request(self, image_url, params=None):
data = self._init_data(params)
data[] = image_url
response = requests.post(REQUESTS_URL, headers={
: self.auth.authorize(, REQUESTS_URL, data),
: USER_AGENT,
}, data=data)
return self._unwrap... | Send an image for classification. The imagewill be retrieved from the
URL specified. The params parameter is optional.
On success this method will immediately return a job information. Its
status will initially be :py:data:`cloudsight.STATUS_NOT_COMPLETED` as
it usually takes 6-... |
383,565 | def doi_input(doi_string, download=True):
log.debug(.format(doi_string))
doi_string = doi_string[4:]
if in doi_string:
log.debug()
xml_url = plos_doi_to_xmlurl(doi_string)
else:
log.critical()
sys.exit()
return url_input(xml_url, download) | This method accepts a DOI string and attempts to download the appropriate
xml file. If successful, it returns a path to that file. As with all URL
input types, the success of this method depends on supporting per-publisher
conventions and will fail on unsupported publishers |
383,566 | def check_folder_exists(project, path, folder_name):
ResolutionError/
if folder_name is None or path is None:
return False
try:
folder_list = dxpy.api.container_list_folder(project, {"folder": path, "only": "folders"})
except dxpy.exceptions.DXAPIError as e:
if e.name == :
... | :param project: project id
:type project: string
:param path: path to where we should look for the folder in question
:type path: string
:param folder_name: name of the folder in question
:type folder_name: string
:returns: A boolean True or False whether the folder exists at the specified path
... |
383,567 | def apply(self, builder):
if in self.attributes:
builder.apply_theme(
self.attributes[],
builder.theme_options,
) | Apply the Slide Configuration to a Builder. |
383,568 | def write(self, buf, url):
(store_name, path) = self._split_url(url)
adapter = self._create_adapter(store_name)
with adapter.open(path, ) as f:
f.write(buf.encode()) | Write buffer to storage at a given url |
383,569 | def __extract_tags(self):
tags = list()
current = None
for line in self._comment:
parts = re.match(r, line)
if parts:
current = (parts.group(1), list())
tags.append(current)
if current:
if line == :
... | Extract tags from the DocBlock. |
383,570 | def subroutine(*effects):
def subroutine(value, context, *args, **kwargs):
d = defer.succeed(value)
for effect in effects:
d.addCallback(effect, context, *args, **kwargs)
return d
return subroutine | Returns an effect performing a list of effects. The value passed to each
effect is a result of the previous effect. |
383,571 | def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True):
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
data = plot.create_subsample(data, percent=percent, seed=seed)
... | Plots two attributes against each other.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
:param data: the dataset
:type data: Instances
:param index_x: the 0-based index of the attribute on the x axis
:type index_x: int
:param index_y: the 0-based index of th... |
383,572 | def in_template_path(fn):
return os.path.join(
os.path.abspath(os.path.dirname(__file__)),
"../templates",
fn,
) | Return `fn` in template context, or in other words add `fn` to template
path, so you don't need to write absolute path of `fn` in template
directory manually.
Args:
fn (str): Name of the file in template dir.
Return:
str: Absolute path to the file. |
383,573 | def validatefeatures(self,features):
validatedfeatures = []
for feature in features:
if isinstance(feature, int) or isinstance(feature, float):
validatedfeatures.append( str(feature) )
elif self.delimiter in feature and not self.sklearn:
r... | Returns features in validated form, or raises an Exception. Mostly for internal use |
383,574 | def _CompileTemplate(
template_str, builder, meta=, format_char=, default_formatter=,
whitespace=):
meta_left, meta_right = SplitMeta(meta)
balance_counter = 0
comment_counter = 0
has_defines = False
for token_type, token in _Tokenize(template_str... | Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
builder: The interface of _ProgramBuilder isn't fixed. Use at your own
risk.
... |
383,575 | def color(self):
return (self.get_value(CONST.STATUSES_KEY).get(),
self.get_value(CONST.STATUSES_KEY).get()) | Get light color. |
383,576 | def resolve_metric_as_tuple(metric):
if "." in metric:
_, metric = metric.split(".")
r = [
(operator, match) for operator, match in ALL_METRICS if match[0] == metric
]
if not r or len(r) == 0:
raise ValueError(f"Metric {metric} not recognised.")
else:
return r[0... | Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric` |
383,577 | def fingerprint(self, word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG):
if n_bits % 2:
n_bits += 1
w_len = len(word) // 2
w_1 = set(word[:w_len])
w_2 = set(word[w_len:])
fingerprint = 0
for letter in most_common:
if n_bits:
... | Return the occurrence halved fingerprint.
Based on the occurrence halved fingerprint from :cite:`Cislak:2017`.
Parameters
----------
word : str
The word to fingerprint
n_bits : int
Number of bits in the fingerprint returned
most_common : list
... |
383,578 | def coerce(self, value):
if self._coerce is not None:
value = self._coerce(value)
return value | Coerce a cleaned value. |
383,579 | def _install_one(
repo_url, branch, destination, commit=, patches=None,
exclude_modules=None, include_modules=None, base=False, work_directory=
):
patches = patches or []
patches = [
core.FilePatch(file=patch[], work_directory=work_directory)
if in patch else core.Patch(**patch)
... | Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to checkout.
:param string destination: the folder where the add-on should end up at.
:param string commit: Optional commit rev to checkout to. If mentioned, that ... |
383,580 | def identical_signature_wrapper(original_function, wrapped_function):
s which
will call the ``wrapped_function``.
__wrapped__def {0}({1}):\n return __wrapped__({2})timeout=1<string>exec'
)
six.exec_(function_def, context)
return wraps(original_function)(context[original_function.__name__]) | Return a function with identical signature as ``original_function``'s which
will call the ``wrapped_function``. |
383,581 | def mount(directory, lower_dir, upper_dir, mount_table=None):
return OverlayFS.mount(directory, lower_dir, upper_dir,
mount_table=mount_table) | Creates a mount |
383,582 | def aget(dct, key):
r
key = iter(key)
try:
head = next(key)
except StopIteration:
return dct
if isinstance(dct, list):
try:
idx = int(head)
except ValueError:
raise IndexNotIntegerError(
"non-integer index %r provided on a list... | r"""Allow to get values deep in a dict with iterable keys
Accessing leaf values is quite straightforward:
>>> dct = {'a': {'x': 1, 'b': {'c': 2}}}
>>> aget(dct, ('a', 'x'))
1
>>> aget(dct, ('a', 'b', 'c'))
2
If key is empty, it returns unchanged the ``dct`` value.
... |
383,583 | def env(var_name, default=False):
try:
value = os.environ[var_name]
if str(value).strip().lower() in [, , , , , , , ]:
return None
return value
except:
from traceback import format_exc
msg = "Unable to find the %s environment variable.\nUsing the value %... | Get the environment variable. If not found use a default or False, but print to stderr a warning about the missing env variable. |
383,584 | def parse_template(self, tmp, reset=False, only_body=False):
logging.debug(, tmp)
if self.sent_time:
self.modified_since_sent = True
if only_body:
self.body = tmp
else:
m = re.match(r,
tmp)
assert m
... | parses a template or user edited string to fills this envelope.
:param tmp: the string to parse.
:type tmp: str
:param reset: remove previous envelope content
:type reset: bool |
383,585 | def _dcm_array_to_matrix3(self, dcm):
assert(dcm.shape == (3, 3))
a = Vector3(dcm[0][0], dcm[0][1], dcm[0][2])
b = Vector3(dcm[1][0], dcm[1][1], dcm[1][2])
c = Vector3(dcm[2][0], dcm[2][1], dcm[2][2])
return Matrix3(a, b, c) | Converts dcm array into Matrix3
:param dcm: 3x3 dcm array
:returns: Matrix3 |
383,586 | def update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None):
kwargs = {
: new_value,
: {
: keep_null,
: wait_for_sync,
: limit,
}
}
return cls._cons... | This will find all documents in the collection that match the specified example object,
and partially update the document body with the new value specified. Note that document meta-attributes
such as _id, _key, _from, _to etc. cannot be replaced.
Note: the limit attribute is not sup... |
383,587 | async def websocket_disconnect(self, message):
self.closing = True
await self.send_upstream(message)
await super().websocket_disconnect(message) | Handle the disconnect message.
This is propagated to all upstream applications. |
383,588 | def commit(func):
def wrap(**kwarg):
with session_withcommit() as session:
a = func(**kwarg)
session.add(a)
return session.query(songs).order_by(
songs.song_id.desc()).first().song_id
return wrap | Used as a decorator for automatically making session commits |
383,589 | def utterances_from_tier(eafob: Eaf, tier_name: str) -> List[Utterance]:
try:
speaker = eafob.tiers[tier_name][2]["PARTICIPANT"]
except KeyError:
speaker = None
tier_utterances = []
annotations = sort_annotations(
list(eafob.get_annotation_data_for_tier(tier_name)))
... | Returns utterances found in the given Eaf object in the given tier. |
383,590 | def Dirname(self):
result = self.Copy()
while 1:
last_directory = posixpath.dirname(result.last.path)
if last_directory != "/" or len(result) <= 1:
result.last.path = last_directory
result.last.inode = None
break
result.Pop(-1)
return result | Get a new copied object with only the directory path. |
383,591 | def fetchone(self, query, *args):
cursor = self.connection.cursor()
try:
cursor.execute(query, args)
return cursor.fetchone()
finally:
cursor.close() | Returns the first result of the given query.
:param query: The query to be executed as a `str`.
:param params: A `tuple` of parameters that will be replaced for
placeholders in the query.
:return: The retrieved row with each field being one element in a
`... |
383,592 | def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None:
fileobj.write(.join(lines) + ) | Writes lines, plus terminating newline characters, to the file.
(Since :func:`fileobj.writelines` doesn't add newlines...
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file) |
383,593 | def load_file(self, app, pathname, relpath, pypath):
try:
view_class = self.get_file_view_cls(relpath)
return create_view_from_file(pathname, source_template=relpath, view_class=view_class)
except DeclarativeViewError:
pass | Loads a file and creates a View from it. Files are split
between a YAML front-matter and the content (unless it is a .yml file). |
383,594 | def _ensure_frames(cls, documents):
frames = []
for document in documents:
if not isinstance(document, Frame):
frames.append(cls(document))
else:
frames.append(document)
return frames | Ensure all items in a list are frames by converting those that aren't. |
383,595 | def ParseMessage(descriptor, byte_str):
result_class = MakeClass(descriptor)
new_msg = result_class()
new_msg.ParseFromString(byte_str)
return new_msg | Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object. |
383,596 | def infer_datetime_units(dates):
dates = np.asarray(dates).ravel()
if np.asarray(dates).dtype == :
dates = pd.to_datetime(dates, box=False)
dates = dates[pd.notnull(dates)]
reference_date = dates[0] if len(dates) > 0 else
reference_date = pd.Timestamp(reference_date)
el... | Given an array of datetimes, returns a CF compatible time-unit string of
the form "{time_unit} since {date[0]}", where `time_unit` is 'days',
'hours', 'minutes' or 'seconds' (the first one that can evenly divide all
unique time deltas in `dates`) |
383,597 | def flush_stream_threads(process, out_formatter=None,
err_formatter=terminal.fg.red, size=1):
out = FlushStreamThread(process=process, stream_name="stdout",
formatter=out_formatter, size=size)
err = FlushStreamThread(process=process, stream_name... | Context manager that creates 2 threads, one for each standard
stream (stdout/stderr), updating in realtime the piped data.
The formatters are callables that receives manipulates the data,
e.g. coloring it before writing to a ``sys`` stream. See
``FlushStreamThread`` for more information. |
383,598 | def get_item_query_session(self):
if not self.supports_item_query():
raise errors.Unimplemented()
return sessions.ItemQuerySession(runtime=self._runtime) | Gets the ``OsidSession`` associated with the item query service.
return: (osid.assessment.ItemQuerySession) - an
``ItemQuerySession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_item_query()`` is ``false``
*compliance: optional... |
383,599 | def prepare_inputs(self, times=None, weather=None):
if weather is not None:
self.weather = weather
if self.weather is None:
self.weather = pd.DataFrame(index=times)
if times is not None:
self.times = times
self.solar_position = self.location... | Prepare the solar position, irradiance, and weather inputs to
the model.
Parameters
----------
times : None or DatetimeIndex, default None
Times at which to evaluate the model. Can be None if
attribute `times` is already set.
weather : None or DataFrame, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.