Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,800 | def pickle_dumps(self, protocol=None):
strio = StringIO()
pmg_pickle_dump(self, strio,
protocol=self.pickle_protocol if protocol is None
else protocol)
return strio.getvalue() | Return a string with the pickle representation.
`protocol` selects the pickle protocol. self.pickle_protocol is
used if `protocol` is None |
360,801 | async def message_data(request):
messages = []
if request.app[].MESSAGE_FILE.exists():
with request.app[].MESSAGE_FILE.open() as msg_file:
for line in msg_file:
if not line:
continue
... | As an example of aiohttp providing a non-html response, we load the actual messages for the "messages" view above
via ajax using this endpoint to get data. see static/message_display.js for details of rendering. |
360,802 | def cache_file(package, mode):
f = DummyFile()
with exception_to_warning(,
OutdatedCacheFailedWarning):
try:
cache_path = os.path.join(tempfile.gettempdir(),
get_cache_filename(package))
if ... | Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'do stuff with f'
block.
The file is... |
360,803 | def deserialize(doc_xml, pyxb_binding=None):
pyxb_binding = pyxb_binding or d1_common.types.dataoneTypes
try:
return pyxb_binding.CreateFromDocument(doc_xml)
except pyxb.ValidationError as e:
raise ValueError(
.format(
e.details(), doc_xml
)
... | Deserialize DataONE XML types to PyXB.
Args:
doc_xml: UTF-8 encoded ``bytes``
pyxb_binding: PyXB binding object. If not specified, the correct one should be
selected automatically.
Returns:
PyXB object
See Also:
``deserialize_d1_exception()`` for deserializing DataONE Excep... |
360,804 | def _validate_value(self, proposal):
"Replace all values with the actual objects in the options list"
try:
return tuple(findvalue(self._options_values, i, self.equals) for i in proposal.value)
except ValueError:
raise TraitError() | Replace all values with the actual objects in the options list |
360,805 | def get_seq_seq(self,obj,default=None):
if is_sequence2(obj):
return [self.get_seq(o,default) for o in obj]
else:
return [self.get_seq(obj,default)] | Return sequence of sequences. |
360,806 | def _create(cls, configuration=None, remoteckan=None, **kwargs):
kwargs = cls._environment_variables(**kwargs)
cls.setup(configuration, **kwargs)
cls._configuration.setup_remoteckan(remoteckan, **kwargs)
return cls._configuration.get_hdx_site_url() | Create HDX configuration
Args:
configuration (Optional[Configuration]): Configuration instance. Defaults to setting one up from passed arguments.
remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration.
**kwargs: See below
... |
360,807 | def _put_resource(self, url, body):
headers = {"Content-Type": "application/json",
"Accept": "application/json"}
if self.token:
headers["W-Token"] = "%s" % self.token
response = WhenIWork_DAO().putURL(url, headers, json.dumps(body))
if not (respon... | When I Work PUT method. |
360,808 | def get_player_summaries(players, **kwargs):
if (isinstance(players, list)):
params = {: .join(str(p) for p in players)}
elif (isinstance(players, int)):
params = {: players}
else:
raise ValueError("The players input needs to be a list or int")
return make_request("GetPlayer... | Get players steam profile from their steam ids |
360,809 | def filter_publication(publication, cache=_CACHE):
if cache is None:
cache = load_cache()
if publication._get_hash() in cache:
return None
cache.update(
[publication._get_hash()]
)
save_cache(cache)
return publication | Deduplication function, which compares `publication` with samples stored in
`cache`. If the match NOT is found, `publication` is returned, else None.
Args:
publication (obj): :class:`.Publication` instance.
cache (obj): Cache which is used for lookups.
Returns:
obj/None: Depends wh... |
360,810 | def get_image_file_path(instance, filename):
ext = filename.split()[-1]
filename = % (uuid.uuid4(), ext)
return os.path.join(
, str(instance.user.pk), , filename) | Returns a unique filename for images. |
360,811 | def _prepare(self):
if self.method not in http.ALLOWED_METHODS:
raise UberIllegalState()
api_host = self.api_host
headers = self._build_headers(self.method, self.auth_session)
url = build_url(api_host, self.path)
data, params = generate_data(self.method, sel... | Builds a URL and return a PreparedRequest.
Returns
(requests.PreparedRequest)
Raises
UberIllegalState (APIError) |
360,812 | def check_action_type(self, value):
if value is not None:
if not isinstance(value, ActionType):
raise AttributeError("Invalid check action %s" % value)
self._check_action_type = value | Set the value for the CheckActionType, validating input |
360,813 | def get_all_projects(url, token, top=HARD_CODED_TOP):
project_list = []
tfs_client = create_tfs_core_client(url, token)
collections = tfs_client.get_project_collections(top=top)
for collection in collections:
collection_client = create_tfs_core_client(.format(url=url, collection_name=coll... | Returns a list of all projects with their collection info from the server. Currently limited functionality to only return the first 1000 projects.
#TODO refactor to add multiple calls to api to retrieve all projects if more exist beyond top. |
360,814 | def extract_features(self, dataset, feature, batch_size=64, verbose=False):
from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter
from six.moves.queue import Queue as _Queue
from threading import Thread as _Thread
import turicreate as _tc
import array
... | Parameters
----------
dataset: SFrame
SFrame of images |
360,815 | def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback = False
prev_choices = []
for lang_choice in cho... | Fetch the object using a translated slug. |
360,816 | def connect(self, src, dst=None, callback=None):
assert src
if dst is None:
dst = src
src = self._root
src_id = src.hash()
dst_id = dst.hash()
if src_id not in self._graph:
raise KittyException( % (src_id, src))
self._graph[src... | :param src: source node, if dst is None it will be destination node and the root (dummy) node will be source
:param dst: destination node (default: None)
:type callback: func(fuzzer, edge, response) -> None
:param callback: a function to be called after the response for src received and before d... |
360,817 | def _start_local_queue_process(self):
comm_q = Queue(maxsize=10)
self.queue_proc = Process(target=interchange.starter,
args=(comm_q,),
kwargs={"client_ports": (self.outgoing_q.port,
... | TODO: docstring |
360,818 | def filter_by_background(in_vcf, full_vcf, background, data):
Filter = collections.namedtuple(, [, ])
back_filter = Filter(id=,
desc=)
out_file = "%s-filter.vcf" % utils.splitext_plus(in_vcf)[0]
if not utils.file_uptodate(out_file, in_vcf) and not utils.file_uptodate(out_fi... | Filter SV calls also present in background samples.
Skips filtering of inversions, which are not characterized differently
between cases and controls in test datasets. |
360,819 | def n1qlQueryAll(self, *args, **kwargs):
if not self.connected:
cb = lambda x: self.n1qlQueryAll(*args, **kwargs)
return self.connect().addCallback(cb)
kwargs[] = BatchedN1QLRequest
o = super(RawBucket, self).n1ql_query(*args, **kwargs)
o.start()
... | Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query`
... |
360,820 | def _get_reg_software(include_components=True,
include_updates=True):
<package_name><version>
reg_software = {}
def skip_component(hive, key, sub_key, use_32bit):
SystemComponent
if include_components:
return False
if __utils__[]... | This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bool):
Include sub components of installed software. Default is ``True``
include_upda... |
360,821 | def ingest_resources(mapping, schema_dir):
ingested_resources = []
for name, filepath in iteritems(mapping):
try:
ingested_resources.append(load_schema(filepath))
except IOError:
raise ApiDeclarationNotFoundError(
... | Consume the Swagger schemas and produce a queryable datastructure.
:param mapping: Map from resource name to filepath of its api declaration
:type mapping: dict
:param schema_dir: the directory schema files live inside
:type schema_dir: string
:returns: A list of mapping from :class:`RequestMatcher... |
360,822 | def set_branch_capacity(network, args):
network.lines["s_nom_total"] = network.lines.s_nom.copy()
network.transformers["s_nom_total"] = network.transformers.s_nom.copy()
network.lines["v_nom"] = network.lines.bus0.map(
network.buses.v_nom)
network.transformers["v_nom0"] = network.transf... | Set branch capacity factor of lines and transformers, different factors for
HV (110kV) and eHV (220kV, 380kV).
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
args: dict
Settings in appl.py |
360,823 | def line_on_device(
device: ,
length: int,
method: LinePlacementStrategy = greedy.GreedySequenceSearchStrategy()
) -> GridQubitLineTuple:
return method.place_line(device, length) | Searches for linear sequence of qubits on device.
Args:
device: Google Xmon device instance.
length: Desired number of qubits making up the line.
method: Line placement method. Defaults to
cirq.greedy.GreedySequenceSearchMethod.
Returns:
Line sequences search re... |
360,824 | def get_object(self, path):
key = self.native_container.get_key(path)
return self.obj_cls.from_key(self, key) | Get single object. |
360,825 | def remote_command(session, command, vehicle_index, poll=True):
if command not in SUPPORTED_COMMANDS:
raise MoparError("unsupported command: " + command)
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
if command in [COMMAND_LOCK, COMMAND_UNLOCK]:
url = REMO... | Send a remote command. |
360,826 | def _calculate_osdb_hash(self):
log.debug(.format(path=self._filepath))
f = self._filepath.open(mode=)
file_size = self.get_size()
longlong_format =
size_longlong = struct.calcsize(longlong_format)
block_size = min(file_size, 64 << 10)
block_size ... | Calculate OSDB (OpenSubtitleDataBase) hash of this VideoFile
:return: hash as string |
360,827 | def get_subscribers(object_type: str) -> List[str]:
return DB.get_list(_keys.subscribers(object_type)) | Get the list of subscribers to events of the object type.
Args:
object_type (str): Type of object.
Returns:
List[str], list of subscriber names. |
360,828 | def property_pickled(f):
def retrieve_from_cache(self):
if not in self.__dict__: self.__cache__ = {}
if f.__name__ in self.__cache__: return self.__cache__[f.__name__]
if in self.__dict__:
path = FilePath(self.__dict__[] + f.func_name + )
els... | Same thing as above but the result will be stored on disk
The path of the pickle file will be determined by looking for the
`cache_dir` attribute of the instance containing the cached property.
If no `cache_dir` attribute exists the `p` attribute will be accessed with
the name of the property being cach... |
360,829 | async def lookup(client: Client, search: str) -> dict:
return await client.get(MODULE + % search, schema=LOOKUP_SCHEMA) | GET UID/Public key data
:param client: Client to connect to the api
:param search: UID or public key
:return: |
360,830 | def dump_limits(conf_file, limits_file, debug=False):
conf = config.Config(conf_file=conf_file)
db = conf.get_database()
limits_key = conf[].get(, )
lims = [limits.Limit.hydrate(db, msgpack.loads(lim))
for lim in db.zrange(limits_key, 0, -1)]
root = etree.Element()... | Dump the current limits from the Redis database.
:param conf_file: Name of the configuration file, for connecting
to the Redis database.
:param limits_file: Name of the XML file that the limits will be
dumped to. Use '-' to dump to stdout.
:param debug: If Tru... |
360,831 | def _characterize_header(self, header, hgroups):
out = []
for h in [header[g[0]] for g in hgroups]:
this_ctype = None
for ctype, names in self._col_types.items():
if h.startswith(names):
this_ctype = ctype
break
... | Characterize header groups into different data types. |
360,832 | def getInterval(self, alpha):
dlnl = twosided_cl_to_dlnl(1.0 - alpha)
lo_lim = self.getDeltaLogLike(dlnl, upper=False)
hi_lim = self.getDeltaLogLike(dlnl, upper=True)
return (lo_lim, hi_lim) | Evaluate the interval corresponding to a C.L. of (1-alpha)%.
Parameters
----------
alpha : limit confidence level. |
360,833 | def _drawContents(self, reason=None, initiator=None):
self.crossPlotRow = None
self.crossPlotCol = None
gridLayout = self.graphicsLayoutWidget.ci.layout
if self.config.horCrossPlotCti.configValue:
gridLayout.setRowStretchFactor(ROW_HOR_LINE, 1)
if no... | Draws the plot contents from the sliced array of the collected repo tree item.
The reason parameter is used to determine if the axes will be reset (the initiator
parameter is ignored). See AbstractInspector.updateContents for their description. |
360,834 | def _encode_datetime(name, value, dummy0, dummy1):
millis = _datetime_to_millis(value)
return b"\x09" + name + _PACK_LONG(millis) | Encode datetime.datetime. |
360,835 | def filter_format(filter_template, assertion_values):
assert isinstance(filter_template, bytes)
return filter_template % (
tuple(map(escape_filter_chars, assertion_values))) | filter_template
String containing %s as placeholder for assertion values.
assertion_values
List or tuple of assertion values. Length must match
count of %s in filter_template. |
360,836 | def plot_prh_des_asc(p, r, h, asc, des):
import matplotlib.pyplot as plt
import numpy
from . import plotutils
des_ind = numpy.where(des)[0]
asc_ind = numpy.where(asc)[0]
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=)
ax1.title.set_text()
ax1 = plotutils.plot_noncontiguo... | Plot pitch, roll, and heading during the descent and ascent dive phases
Args
----
p: ndarray
Derived pitch data
r: ndarray
Derived roll data
h: ndarray
Derived heading data
des: ndarray
boolean mask for slicing descent phases of dives from tag dta
asc: ndarra... |
360,837 | def from_config(config):
result = Parameters()
if config == None or len(config) == 0:
return result
for (key, value) in config.items():
result.put(key, value)
return result | Creates new Parameters from ConfigMap object.
:param config: a ConfigParams that contain parameters.
:return: a new Parameters object. |
360,838 | def render(self):
(pthemedir, ptemplatefname) = self._theme_and_template_fp()
mylookup = TemplateLookup(directories=[self.site.dirs[], pthemedir], input_encoding=, output_encoding=)
makotemplate = Template(filename=ptemplatefname, lookup=mylookup,
modu... | Render this page and return the rendition.
Converts the markdown content to html, and then renders the
(mako) template specified in the config, using that html.
The task of writing of the rendition to a real file is
responsibility of the generate method. |
360,839 | def _is_modification_or_activity(feature):
if not (isinstance(feature, _bp()) or \
isinstance(feature, _bpimpl())):
return None
mf_type = feature.getModificationType()
if mf_type is None:
return None
mf_type_terms = mf_type.getTerm().toArray()
for term in mf_type_ter... | Return True if the feature is a modification |
360,840 | def contains(self, token: str) -> bool:
self._validate_token(token)
return token in self | Return if the token is in the list or not. |
360,841 | def _replace_link_brackets(msg_body):
if isinstance(msg_body, bytes):
msg_body = msg_body.decode()
def link_wrapper(link):
newline_index = msg_body[:link.start()].rfind("\n")
if msg_body[newline_index + 1] == ">":
return link.group()
else:
return "@@... | Normalize links i.e. replace '<', '>' wrapping the link with some symbols
so that '>' closing the link couldn't be mistakenly taken for quotation
marker.
Converts msg_body into a unicode |
360,842 | def get_backend_name(self, location):
for vc_type in self._registry.values():
logger.debug(,
location, vc_type.dirname, vc_type.name)
path = os.path.join(location, vc_type.dirname)
if os.path.exists(path):
logger.debug(,
... | Return the name of the version control backend if found at given
location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') |
360,843 | def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False,
metric=None, **metric_kwargs):
mp_eval = MultiprocEvaluationRunner(MultiprocEvaluationWorkerLDA, AVAILABLE_METRICS, data,
va... | Compute several Topic Models in parallel using the "lda" package. Calculate the models using a list of varying
parameters `varying_parameters` on a single Document-Term-Matrix `data`. Pass parameters in `constant_parameters`
dict to each model calculation. Use at maximum `n_max_processes` processors or use all ... |
360,844 | def delkey(ctx, pubkeys):
if not pubkeys:
pubkeys = click.prompt("Public Keys").split(" ")
if click.confirm(
"Are you sure you want to delete keys from your wallet?\n"
"This step is IRREVERSIBLE! If you don't have a backup, "
"You may lose access to your account!"
):
... | Delete a private key from the wallet |
360,845 | def get_work_item_type_field_with_references(self, project, type, field, expand=None):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if type is not None:
route_values[] = self._serialize.url(, type, )
if field... | GetWorkItemTypeFieldWithReferences.
[Preview API] Get a field for a work item type with detailed references.
:param str project: Project ID or project name
:param str type: Work item type.
:param str field:
:param str expand: Expand level for the API response. Properties: to incl... |
360,846 | def get_metadata(audio_filepaths):
artist, album, has_embedded_album_art = None, None, None
for audio_filepath in audio_filepaths:
try:
mf = mutagen.File(audio_filepath)
except Exception:
continue
if mf is None:
continue
for key in ("albumartist", "artist",
... | Return a tuple of album, artist, has_embedded_album_art from a list of audio files. |
360,847 | def StopToTuple(stop):
return (stop.stop_id, stop.stop_name, float(stop.stop_lat),
float(stop.stop_lon), stop.location_type) | Return tuple as expected by javascript function addStopMarkerFromList |
360,848 | def is_ready(self):
if not self.provisioning_state:
raise exception.ServiceException("The object doesn't contain "
"`provisioningState`.")
elif self.provisioning_state == constant.FAILED:
raise exception.ServiceException(
... | Check if the current model is ready to be used. |
360,849 | def _class_dispatch(args, kwargs):
_ = kwargs
if not args:
raise ValueError(
"Multimethods must be passed at least one positional arg.")
if not isinstance(args[0], type):
raise TypeError(
"class_multimethod must be called with a type, not instance.")
return... | See 'class_multimethod'. |
360,850 | def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=True, manager=None):
qpoints = []
qpoints_deps = []
for task in phononwfkq_work:
if isinstance(task,PhononTask):
qpt = task.input.get("qpt", [0,0... | Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands |
360,851 | def split_locator(self, path):
relative = self.relpath(path)
try:
locator, tail = relative.split(, 1)
except ValueError:
locator = relative
tail =
return locator, tail | Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path. |
360,852 | def _get_internal_min_value(self):
if self.min_value is None:
return None
else:
if self._transformation is None:
return self._external_min_value
else:
return self._transformation.forward(self.... | This is supposed to be only used by fitting engines to get the minimum value in internal representation.
It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter
:return: minimum value in internal representation (or None if there is no minimum) |
360,853 | def stop_process(self):
self._process.terminate()
if not self._process.waitForFinished(100):
self._process.kill() | Stops the child process. |
360,854 | def report_changes(self, content):
self.write(content)
if self.commit():
return True, self.reporter.report()
else:
return False, None | 1) Write changes in file,
2) Commit changes in git
3.1) If something changed, return tuple(True, changes)
3.2) If nothing changed, return tuple(False, None)
If style is "verbose", return changes in human-friendly format,
else use unified diff |
360,855 | def installed():
try:
path = ChromeCookies._getPath()
with open(path) as f: pass
return True
except Exception as e:
return False | Returns whether or not Google Chrome is installed
Determines the application data path for Google Chrome
and checks if the path exists. If so, returns True, otherwise
it will return False.
Returns
bool - True if Chrome is installed |
360,856 | def snapshot_registry(self):
unserializer = banana.Unserializer(externalizer=self)
serializer = banana.Serializer(externalizer=self)
return unserializer.convert(serializer.convert(self.registry)) | Give the dictionary of recorders detached from the existing instances.
It is safe to store those references for future use. Used by feattool. |
360,857 | def get_song_urls(song_input):
YOUTUBECLASS =
html = requests.get("https://www.youtube.com/results",
params={: song_input})
soup = BeautifulSoup(html.text, )
soup_section = soup.findAll(, {: YOUTUBECLASS})
youtube_list = list(zip(song_urls, song_titles))
d... | Gather all urls, titles for a search query
from youtube |
360,858 | def diff_objects(self, latest_commit_sha):
base = [, , , self.git_path]
object_shas = []
summary = {: [], : [], : []}
def read_parents_and_tree_from(commit):
if commit in self.synced_object_shas or commit in object_shas:
return None... | Push all changes to origin, based on objects, not on commits.
Important: Call this push after every new commit, or we lose commits. |
360,859 | def annotate(args):
p = OptionParser(annotate.__doc__.format(", ".join(Overlap_types)))
p.add_option("--maxhang", default=100, type="int",
help="Max hang to call dovetail overlap [default: %default]")
p.add_option("--all", default=False, action="store_true",
help="Outp... | %prog annotate coordsfile
Annotate coordsfile to append an additional column, with the following
overlaps: {0}. |
360,860 | def _get_dest(*args, **kwargs):
prefix_chars = kwargs.get(, )
option_strings = []
long_option_strings = []
for option_string in args:
option_strings.append(option_string)
if option_string[0] in prefix_chars:
if len(option_string) > 1:
if ... | Duplicate argument names processing logic from argparse.
argparse stores the variable in the namespace using the provided dest name,
the first long option string, or the first short option string |
360,861 | def standings(date=datetime.now()):
data = mlbgame.info.standings(date)
return mlbgame.info.Standings(data) | Return Standings object that contains standings info
date should be a datetime object,
leave empty to get current standings |
360,862 | def execute(self, jvm_options=None, args=None, executor=None,
workunit_factory=None, workunit_name=None, workunit_labels=None):
executor = executor or SubprocessExecutor(DistributionLocator.cached())
runner = self.runner(jvm_options=jvm_options, args=args, executor=executor)
... | Executes the ivy commandline client with the given args.
Raises Ivy.Error if the command fails for any reason.
:param executor: Java executor to run ivy with. |
360,863 | def _environment_variables(**kwargs):
user_agent = os.getenv()
if user_agent is not None:
kwargs[] = user_agent
preprefix = os.getenv()
if preprefix is not None:
kwargs[] = preprefix
return kwargs | Overwrite keyword arguments with environment variables
Args:
**kwargs: See below
user_agent (str): User agent string.
Returns:
kwargs: Changed keyword arguments |
360,864 | def update_quota(self, quota_info, error=None):
if not quota_info or quota_info[] != 0:
return
used = quota_info[]
total = quota_info[]
used_size = util.get_human_size(used)[0]
total_size = util.get_human_size(total)[0]
self.capicity_label.set_text(.f... | 更新网盘容量信息 |
360,865 | def use_any_status_sequence_rule_view(self):
self._operable_views[] = ANY_STATUS
for session in self._get_provider_sessions():
try:
session.use_any_status_sequence_rule_view()
except AttributeError:
pass | Pass through to provider SequenceRuleLookupSession.use_any_status_sequence_rule_view |
360,866 | def url_for(self, entity=None, object_type=None, object_id=None, **kwargs):
if object_type is None:
assert isinstance(entity, (db.Model, Hit, dict))
getter = attrgetter if isinstance(entity, db.Model) else itemgetter
object_id = getter("id")(entity)
objec... | Return canonical view URL for given entity instance.
If no view has been registered the registry will try to find an
endpoint named with entity's class lowercased followed by '.view'
and that accepts `object_id=entity.id` to generates an url.
:param entity: a instance of a subclass of
... |
360,867 | def _clear_cache_synthesizer(self):
self.log(u"Clearing synthesizer...")
self.synthesizer.clear_cache()
self.log(u"Clearing synthesizer... done") | Clear the cache of the synthesizer |
360,868 | def set_widgets(self):
last_layer = self.parent.layer and self.parent.layer.id() or None
self.lblDescribeCanvasAggLayer.clear()
self.list_compatible_canvas_layers()
self.auto_select_one_item(self.lstCanvasAggLayers)
if last_layer:
... | Set widgets on the Aggregation Layer from Canvas tab. |
360,869 | def asyncImap(asyncCallable, *iterables):
deferreds = imap(asyncCallable, *iterables)
return gatherResults(deferreds, consumeErrors=True) | itertools.imap for deferred callables |
360,870 | def _fake_openenumerateinstancepaths(self, namespace, **params):
self._validate_namespace(namespace)
self._validate_open_params(**params)
result_t = self._fake_enumerateinstancenames(namespace, **params)
return self._open_response(result_t[0][2], namespace,
... | Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.OpenEnumerationInstancePaths`
with data from the instance repository. |
360,871 | def com_find(ar_grid):
f_x = 0
f_y = 0
f_m = 0
for i in range(len(ar_grid)):
for j in range(len(ar_grid[i])):
if ar_grid[i][j]:
f_x += (j+1) * ar_grid[i][j]
f_y += (i+1) * ar_grid[i][j]
f_m += ar_grid[i][j]
... | Find the center of mass in array grid <ar_grid>. Mass elements
are grid index values.
Return an array, in format (x, y), i.e. col, row! |
360,872 | async def release_forks(self, philosopher):
forks = self.forks
self.forks = []
self.started_waiting = 0
for fork in forks:
philosopher.logger.debug(, fork)
await philosopher.send(, , fork)
await sleep(self.cfg.waiting_period) | The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor. |
360,873 | def process_lpd(name, dir_tmp):
logger_doi_main.info("enter process_lpd")
dir_root = os.getcwd()
dir_bag = os.path.join(dir_tmp, name)
dir_data = os.path.join(dir_bag, )
os.chdir(dir_data)
jld_data = read_json_from_file(os.path.join(dir_data, name + ))
jld_data = ... | Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag.
:param str name: Name of current .lpd file
:param str dir_tmp: Path to tmp directory
:return none: |
360,874 | def _Region1(T, P):
if P < 0:
P = Pmin
I = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4,
4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32]
J = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, 0,
6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, ... | Basic equation for region 1
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Returns
-------
prop : dict
Dict with calculated properties. The available properties are:
* v: Specific volume, [m³/kg]
* h: Specific ent... |
360,875 | def output(data, **kwargs):
rows = _find_durations(data)
kwargs[] = __opts__
kwargs[] =
kwargs[] =
to_show = {: [, , ],
: rows}
return table_out.output(to_show, **kwargs) | Display the profiling data in a table format. |
360,876 | def copy_to(self, dest, buffering: int = -1):
if isinstance(dest, str):
dest_path = dest
elif isinstance(dest, FileInfo):
dest_path = dest.path
elif isinstance(dest, DirectoryInfo):
dest_path = dest.path / self.path.name
else:
rais... | copy the file to dest path.
`dest` canbe `str`, `FileInfo` or `DirectoryInfo`.
if `dest` is `DirectoryInfo`, that mean copy into the dir with same name. |
360,877 | def export_for_schema(self):
ret = "{: "
for dc, repl_factor in sorted(self.dc_replication_factors.items()):
ret += ", : " % (dc, repl_factor)
return ret + "}" | Returns a string version of these replication options which are
suitable for use in a CREATE KEYSPACE statement. |
360,878 | def chat_meMessage(self, *, channel: str, text: str, **kwargs) -> SlackResponse:
kwargs.update({"channel": channel, "text": text})
return self.api_call("chat.meMessage", json=kwargs) | Share a me message into a channel.
Args:
channel (str): The channel id. e.g. 'C1234567890'
text (str): The message you'd like to share. e.g. 'Hello world' |
360,879 | def parse_event_writer(self, node):
if in node.lattrib:
path = node.lattrib[]
else:
self.raise_error()
if in node.lattrib:
file_path = node.lattrib[]
else:
self.raise_error("Event writer for must specify a filename.",
... | Parses <EventWriter>
@param node: Node containing the <EventWriter> element
@type node: xml.etree.Element |
360,880 | def view_creatr(filename):
if not check():
click.echo(Fore.RED + )
return
path = os.path.abspath() +
if not os.path.exists(path):
os.makedirs(path)
filename_ = str(filename + ".html").lower()
view_file = open(path + "/" + filename_, )
view_file.write("")
view_... | Name of the View File to be created |
360,881 | def get_message_urls(self, message_id, order="total_clicks desc"):
req_data = [ { "message_id": str(message_id) }, order, None ]
return self.request("query:Message_Url", req_data) | Returns a list of URLs you've included in a specific message.
List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items. |
360,882 | def restricted_activities_available_to_user(cls, user):
if not user:
return []
activities = set(user.restricted_activity_set.values_list("id", flat=True))
if user and user.grade and user.grade.number and user.grade.name:
grade = user.grade
else:
... | Find the restricted activities available to the given user. |
360,883 | def from_external(external=H2OFrame):
w2v_model = H2OWord2vecEstimator(pre_trained=external)
w2v_model.train()
return w2v_model | Creates new H2OWord2vecEstimator based on an external model.
:param external: H2OFrame with an external model
:return: H2OWord2vecEstimator instance representing the external model |
360,884 | def page_for(self, member, page_size=DEFAULT_PAGE_SIZE):
return self.page_for_in(self.leaderboard_name, member, page_size) | Determine the page where a member falls in the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the leaderboard. |
360,885 | def get_all_tags_of_offer(self, offer_id):
return self._iterate_through_pages(
get_function=self.get_tags_of_offer_per_page,
resource=OFFER_TAGS,
**{: offer_id}
) | Get all tags of offer
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param offer_id: the offer id
:return: list |
360,886 | def get_command_templates(command_tokens, file_tokens=[], path_tokens=[],
job_options=[]):
files = get_files(file_tokens)
paths = get_paths(path_tokens)
job_options = get_options(job_options)
templates = _get_command_templates(command_tokens, files, paths,
job_options)
for command... | Given a list of tokens from the grammar, return a
list of commands. |
360,887 | def is_constraint(self):
if self._is_constraint is None:
return None
return self._bundle.get_parameter(context=, uniqueid=self._is_constraint) | returns the expression of the constraint that constrains this parameter |
360,888 | def files(self, data):
current_files = self.files
if current_files:
raise RuntimeError()
for key in data:
current_files[key] = data[key] | Set files from data. |
360,889 | def gt(gt_value):
def validate(value):
if value <= gt_value:
return e("{} is not greater than {}", value, gt_value)
return validate | Validates that a field value is greater than the
value given to this validator. |
360,890 | def stopprocessmonitor(self, process_name):
if process_name in self._process_stats:
self._process_stats[process_name].stop()
return 1 | Stop memory and CPU monitoring
@param process_name: Process name, ex: firefox-bin.
@type process_name: string
@return: 1 on success
@rtype: integer |
360,891 | def reset(self):
self.wf.fill(0)
self.wf[(0,) * self.n_qubits] = complex(1.0, 0)
return self | Reset the wavefunction to the |000...00> state.
:return: ``self`` to support method chaining. |
360,892 | def get_model(self):
if self.minisat and self.status == True:
model = pysolvers.minisatgh_model(self.minisat)
return model if model != None else [] | Get a model if the formula was previously satisfied. |
360,893 | def route(self, dst, dev=None):
dst = dst.split("/")[0]
savedst = dst
dst = dst.replace("*","0")
l = dst.find("-")
while l >= 0:
m = (dst[l:]+":").find(":")
dst = dst[:l]+dst[l+m:]
l = dst.find("-")
try:
... | Provide best route to IPv6 destination address, based on Scapy6
internal routing table content.
When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address
of the set is used. Be aware of that behavior when using wildcards in
upper parts of addresses !
If 'dst' para... |
360,894 | def _extract_from_raw_reads(self, output_path, input_reads, raw_sequences_path, input_file_format, hits):
with tempfile.NamedTemporaryFile(prefix=) as tmp:
fxtract_cmd = "fxtract -H -X -f /dev/stdin "
if input_file_format == FORMAT_FASTA:
cmd = "%s... | _extract_from_raw_reads - call fxtract to extract the hit sequences
of the hmm/diamond search from the raw sequences file. Output into
specified file
Parameters
----------
output_path : str
Path of the desired output file
input_reads : list
list o... |
360,895 | def delete(self, obj):
del_id = obj.get_id()
if not del_id:
return
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
query = % tabname
cur.execute(query, (del_id,))
self._conn().commit()
cur.close() | Required functionality. |
360,896 | def connect_post_node_proxy_with_path(self, name, path, **kwargs):
kwargs[] = True
if kwargs.get():
return self.connect_post_node_proxy_with_path_with_http_info(name, path, **kwargs)
else:
(data) = self.connect_post_node_proxy_with_path_with_http_info(name, p... | connect_post_node_proxy_with_path # noqa: E501
connect POST requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_node_proxy_with_path(name, path, a... |
360,897 | def wait(self, timeout=None, do_raise=False):
if timeout is not None:
timeout = float(timeout)
start = time.clock()
with self._lock:
while not self._completed and not self._cancelled:
if timeout is not None:
time_left = timeout - (time.clock() - start)
else:
... | Wait for the future to complete. If *timeout* is specified, it must be a
floating point number representing the maximum number of seconds to wait.
:param timeout: The maximum number of seconds to wait for the future
to complete.
:param do_raise: Raise :class:`Timeout` when a timeout occurred.
:ra... |
360,898 | def rescale_rows(rows, rescale):
fs = [float(2 ** s[1] - 1)/float(2 ** s[0] - 1)
for s in rescale]
target_bitdepths = set(s[1] for s in rescale)
assert len(target_bitdepths) == 1
(target_bitdepth, ) = target_bitdepths
typecode = [target_bitdepth > 8]
n_chans = le... | Take each row in rows (an iterator) and yield
a fresh row with the pixels scaled according to
the rescale parameters in the list `rescale`.
Each element of `rescale` is a tuple of
(source_bitdepth, target_bitdepth),
with one element per channel. |
360,899 | def delete(filename, retry_params=None, _account_id=None):
api = storage_api._get_storage_api(retry_params=retry_params,
account_id=_account_id)
common.validate_file_path(filename)
filename = api_utils._quote_filename(filename)
status, resp_headers, content = api.delete_o... | Delete 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.
Raises:
errors.NotFoundError: if the file doesn't exi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.