language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static ApptentiveAttachmentLoader getInstance() {
if (instance == null) {
synchronized (ApptentiveAttachmentLoader.class) {
if (instance == null) {
instance = new ApptentiveAttachmentLoader();
}
}
}
return instance;
} |
python | def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr):
""" Callback for self._client.new_job """
self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr)
self._waiting_jobs.remove(str(bjobid)) |
java | public BatcherBuilder listenerService(ExecutorService listenerService) {
checkState(this.listenerService == null, "A listener service has already been set");
requireNonNull(listenerService);
this.listenerService = listenerService;
return this;
} |
java | private void parseDouble(int start, int limit, boolean allowInfinity) {
assert start<limit;
// fake loop for easy exit and single throw statement
for(;;) {
// fast path for small integers and infinity
int value=0;
int isNegative=0; // not boolean so that we c... |
python | def save(self, message):
"""
Add version to repo object store, set repo head to version sha.
:param message: Message string.
"""
self.commit.message = message
self.commit.tree = self.tree
#TODO: store new blobs only
for item in self.tree.items():
... |
java | public EEnum getPageOverlayConditionalProcessingPgOvType() {
if (pageOverlayConditionalProcessingPgOvTypeEEnum == null) {
pageOverlayConditionalProcessingPgOvTypeEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(191);
}
return pageOverlayConditionalProcessingPgO... |
python | def compare_conditions(self, labels1, labels2, measure_name, alpha=0.01, repeats=100, num_samples=None, plot=False, random_state=None):
""" Test for significant difference in connectivity of two sets of class labels.
Connectivity estimates are obtained by bootstrapping. Correction for multiple testing ... |
java | public JSType getPropertyType(String propertyName) {
StaticTypedSlot slot = getSlot(propertyName);
if (slot == null) {
if (isNoResolvedType() || isCheckedUnknownType()) {
return getNativeType(JSTypeNative.CHECKED_UNKNOWN_TYPE);
} else if (isEmptyType()) {
return getNativeType(JSTypeN... |
python | def run_coral(clus_obj, out_dir, args):
"""
Run some CoRaL modules to predict small RNA function
"""
if not args.bed:
raise ValueError("This module needs the bed file output from cluster subcmd.")
workdir = op.abspath(op.join(args.out, 'coral'))
safe_dirs(workdir)
bam_in = op.abspath... |
java | @Override
public void close() {
closed = true;
Entry entry;
while ((entry = deque.pollFirst()) != null) {
inactiveCount.decrementAndGet();
try {
finalizer.accept(entry.object);
} catch (Exception e) {
// Ignored
}
}
} |
java | public String getRawDecomposition(int c) {
// We do not loop in this method because an algorithmic mapping itself
// becomes a final result rather than having to be decomposed recursively.
int norm16;
if(c<minDecompNoCP || isDecompYes(norm16=getNorm16(c))) {
// c does not dec... |
python | def generate_pcs(nni_search_space_content):
"""Generate the Parameter Configuration Space (PCS) which defines the
legal ranges of the parameters to be optimized and their default values.
Generally, the format is:
# parameter_name categorical {value_1, ..., value_N} [default value]
# parameter_... |
java | public static RuntimeException from(ByteBuf frame) {
Objects.requireNonNull(frame, "frame must not be null");
int errorCode = ErrorFrameFlyweight.errorCode(frame);
String message = ErrorFrameFlyweight.dataUtf8(frame);
switch (errorCode) {
case APPLICATION_ERROR:
return new ApplicationErr... |
python | def update_webhook(self, url, headers=None):
"""Register new webhook for incoming subscriptions.
If a webhook is already set, this will do an overwrite.
:param str url: the URL with listening webhook (Required)
:param dict headers: K/V dict with additional headers to send with request
... |
python | def get_s2_pixel_cloud_detector(threshold=0.4, average_over=4, dilation_size=2, all_bands=True):
""" Wrapper function for pixel-based S2 cloud detector `S2PixelCloudDetector`
"""
return S2PixelCloudDetector(threshold=threshold,
average_over=average_over,
... |
python | def _get_dns_cname(name, link=False):
"""
Looks for associated domain zone, nameservers and linked record name until no
more linked record name was found for the given fully qualified record name or
the CNAME lookup was disabled, and then returns the parameters as a tuple.
"""
... |
java | public static String getQueryStringFromParams(MultiValueMap<String, String> queryParams, boolean encodeValues) {
try {
return getQueryStringFromParams(queryParams, "UTF-8", encodeValues);
} catch (UnsupportedEncodingException e) {
// Should NEVER happen
throw new Ille... |
python | def stretch_logarithmic(self, ch_nb, factor=100.):
"""Move data into range [1:factor] and do a normalized logarithmic
enhancement.
"""
logger.debug("Perform a logarithmic contrast stretch.")
if ((self.channels[ch_nb].size ==
np.ma.count_masked(self.channels[ch_nb])) ... |
python | def get_extension_modules():
extension_modules = []
"""
Extension module which is actually a plain C++ library without Python bindings
"""
turbodbc_sources = _get_source_files('cpp_odbc') + _get_source_files('turbodbc')
turbodbc_library = Extension('libturbodbc',
... |
python | def _initialize(self):
'''Performs a IPC protocol handshake.'''
credentials = (self.username if self.username else '') + ':' + (self.password if self.password else '')
credentials = credentials.encode(self._encoding)
self._connection.send(credentials + b'\3\0')
response = self._c... |
java | public static boolean hasReturnType(final Method method) {
if (method == null) {
return false;
}
if (method.getReturnType() == null) {
return false;
}
if (Void.class.equals(method.getReturnType())) {
return false;
}
return !Void... |
python | def simple_cache(func):
"""
Save results for the :meth:'path.using_module' classmethod.
When Python 3.2 is available, use functools.lru_cache instead.
"""
saved_results = {}
def wrapper(cls, module):
if module in saved_results:
return saved_results[module]
saved_resu... |
python | def get_random_areanote(zone):
"""
省份行政区划代码,返回下辖的随机地区名称
:param:
* zone: (string) 省份行政区划代码 比如 '310000'
:returns:
* random_areanote: (string) 省份下辖随机地区名称
举例如下::
print('--- fish_data get_random_areanote demo ---')
print(cardbin_get_bank_by_name(310000))
print(... |
python | def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'):
"""
Insert or update a record in the repository
"""
keywords = []
if self.filter is not None:
catalog = Catalog.objects.get(id=int(self.filter.split()[-1]))
try:
... |
python | def from_string(data):
"""
Reads the exciting input from a string
"""
root=ET.fromstring(data)
speciesnode=root.find('structure').iter('species')
elements = []
positions = []
vectors=[]
lockxyz=[]
# get title
title_in=str(ro... |
python | async def sendContact(self, chat_id, phone_number, first_name,
last_name=None,
vcard=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
""" See: https://c... |
java | public List<CmsLock> getLocks(CmsDbContext dbc, String resourceName, CmsLockFilter filter) throws CmsException {
List<CmsLock> locks = new ArrayList<CmsLock>();
Iterator<CmsLock> itLocks = OpenCms.getMemoryMonitor().getAllCachedLocks().iterator();
while (itLocks.hasNext()) {
CmsLock... |
python | def receive_keys(keyserver=None, keys=None, user=None, gnupghome=None):
'''
Receive key(s) from keyserver and add them to keychain
keyserver
Keyserver to use for searching for GPG keys, defaults to pgp.mit.edu
keys
The keyID(s) to retrieve from the keyserver. Can be specified as a com... |
python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space derived from
residue-residue distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features ... |
python | def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):
"""
Return an ``lxml`` tree as a Unicode string.
"""
from lxml import etree
return gf.safe_unicode(etree.tostring(
root_element,
encoding="UTF-8",
method="xml",
... |
java | public static <K, V> MapField<K, V> newMapField(MapEntry<K, V> defaultEntry) {
return new MapField<K, V>(defaultEntry, StorageMode.MAP, new HashMap<K, V>(), null);
} |
python | def get_client(self, initial_timeout=0.1, next_timeout=30):
"""
Wait until a client instance is available
:param float initial_timeout:
how long to wait initially for an existing client to complete
:param float next_timeout:
if the pool could not obtain a client durin... |
java | public static String getClassFileName(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;
} |
python | def ends_with(self, suffix):
"""
Find all words ending with a suffix.
Args:
suffix: A suffix to be searched for.
Returns:
A list of all words found.
"""
suffix = suffix.lower()
found_words = []
res = cgaddag.gdg_ends_with(self.gd... |
python | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) |
java | public OptionalInt maxByDouble(IntToDoubleFunction keyExtractor) {
return collect(PrimitiveBox::new, (box, i) -> {
double key = keyExtractor.applyAsDouble(i);
if (!box.b || Double.compare(box.d, key) < 0) {
box.b = true;
box.d = key;
box.i ... |
java | public static double norm(double[] a) {
double squaredSum = 0;
for (double anA : a) {
squaredSum += anA * anA;
}
return Math.sqrt(squaredSum);
} |
java | public Map<String, SetAndCount> getAggregateResultFullSummary() {
Map<String, SetAndCount> summaryMap = new ConcurrentHashMap<String, SetAndCount>();
for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap
.entrySet()) {
summaryMap.put(entry.getKey(), new SetAn... |
python | def split_leading_indent(line, max_indents=None):
"""Split line into leading indent and main."""
indent = ""
while (
(max_indents is None or max_indents > 0)
and line.startswith((openindent, closeindent))
) or line.lstrip() != line:
if max_indents is not None and line.startswith(... |
java | private boolean shouldShowInContext(CmsContainerElementBean element, String contextKey) {
if (contextKey == null) {
return true;
}
try {
if ((element.getResource() != null)
&& !OpenCms.getTemplateContextManager().shouldShowType(
conte... |
java | public String toSMPTEString(boolean includeDays)
{
final String frameIndicator = dropFrame ? FRAME_SEPARATOR_DROP_FRAMES : FRAME_SEPARATOR_NO_DROP_FRAMES;
final String negativeIndicator = negative ? "-" : "";
if (days == 0 || !includeDays)
{
return String.format("%s%02d:%02d:%02d%s%02d", negativeIndicator,... |
java | protected void doConvert(IProject project, IProgressMonitor monitor) throws ExecutionException {
monitor.setTaskName(MessageFormat.format(Messages.AddSarlNatureHandler_2, project.getName()));
final SubMonitor mon = SubMonitor.convert(monitor, 2);
if (this.configurator.canConfigure(project, Collections.emptySet(),... |
java | public PoolRemoveNodesHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
} |
python | def get_history_window(self,
assets,
end_dt,
bar_count,
frequency,
field,
data_frequency,
ffill=True):
"""
Public A... |
python | def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to... |
java | private void duplicateDeletion(final String spaceId,
final String contentId)
throws TaskExecutionFailedException {
if (existsInSourceManifest(spaceId, contentId)) {
throw new TaskExecutionFailedException(
MessageFormat.format("item exists i... |
python | def run(self):
"""Main entry point for the auditor worker.
Returns:
`None`
"""
# Loop through all accounts that are marked as enabled
accounts = list(AWSAccount.get_all(include_disabled=False).values())
for account in accounts:
self.log.debug('Upd... |
python | def _text2bool(val):
"""
Converts strings to True/False depending on the 'truth' expressed by
the string. If the string can't be converted, the original value
will be returned.
See '__true_strings' and '__false_strings' for values considered
'true' or 'false respectively.
This is usable as... |
python | def getFileLink(self, full_path):
"""Get a link of file
>>> file_link = nd.getFileLink('/Picture/flower.png')
:param full_path: The full path of file to get file link. Path should start and end with '/'.
:return: ``Shared url`` or ``False`` if failed to share a file or di... |
java | public void setVertex(Vector3D v, float nx, float ny) {
gl.glTexCoord2f(nx, ny);
gl.glVertex3d(v.getX(), v.getY(), v.getZ());
} |
python | def __find_index(alig_file_pth, idx_extensions):
"""
Find an index file for a genome alignment file in the same directory.
:param alig_file_path: path to the alignment file.
:param idx_extensions: check for index files with these extensions
:return: path to first index file that matches the name of the align... |
java | public ModuleDeps getExplicitDeps() throws IOException {
final boolean entryExitLogging = log.isLoggable(Level.FINER);
final String methodName = "getExplicitDeps"; //$NON-NLS-1$
if (entryExitLogging) {
log.entering(DependencyList.class.getName(), methodName);
}
if (!initialized) {
initialize();
... |
java | public static route6[] get_filtered(nitro_service service, String filter) throws Exception{
route6 obj = new route6();
options option = new options();
option.set_filter(filter);
route6[] response = (route6[]) obj.getfiltered(service, option);
return response;
} |
java | public synchronized void updateCache() {
Map<byte[], QueueConsumerConfig> newCache = Maps.newTreeMap(Bytes.BYTES_COMPARATOR);
long now = System.currentTimeMillis();
HTable table = null;
try {
table = new HTable(hConf, configTableName);
Scan scan = new Scan();
scan.addFamily(QueueEntryR... |
python | def canClose(self):
"""
Checks to see if the view widget can close by checking all of its \
sub-views to make sure they're ok to close.
:return <bool>
"""
for view in self.findChildren(XView):
if not view.canClose():
return False
... |
java | @Override
public void run()
{
try {
startBarrier.await();
int idleCount = 0;
while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {
idleCount = (!shutdown && process()) ? 0 : (idleCount + 1... |
java | public static FastpathArg createOIDArg(long oid) {
if (oid > Integer.MAX_VALUE) {
oid -= NUM_OIDS;
}
return new FastpathArg((int) oid);
} |
java | @Inject
public void setup(ViewConfigExtension extension) {
for (Entry<String, Set<Annotation>> e : extension.getData().entrySet()) {
for (Annotation i : e.getValue()) {
addAnnotationData(e.getKey(), i);
}
}
} |
java | @Override
public boolean hasNext() {
if (!isForward) {
currentRec = currentRec - pointerSize;
isForward = true;
}
return currentRec > 0 || blk.number() > 0;
} |
python | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) |
java | public void marshall(GetTableRequest getTableRequest, ProtocolMarshaller protocolMarshaller) {
if (getTableRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getTableRequest.getCatalogId(), CA... |
java | public static void populate(Object bean, Map<String, Object> values, Options options) throws BeanException {
try {
for (Entry<String, Object> entry : values.entrySet()) {
populate(bean, entry, options);
}
} catch (InvocationTargetException | IllegalAccessException e) {
throw new BeanException("Failed t... |
python | def get_data_path(data, module, check_exists=True):
"""return a directory path to data within a module
Parameters
----------
data : str or list[str]
file name or list of sub-directories
and file name (e.g. ['lammps','data.txt'])
"""
basepath = os.path.dirname(os.path.abspath(in... |
java | @Override
public CreateBackupResult createBackup(CreateBackupRequest request) {
request = beforeClientExecution(request);
return executeCreateBackup(request);
} |
java | public final EObject ruleXMemberFeatureCall() throws RecognitionException {
EObject current = null;
Token otherlv_2=null;
Token lv_explicitStatic_3_0=null;
Token otherlv_8=null;
Token lv_nullSafe_9_0=null;
Token lv_explicitStatic_10_0=null;
Token otherlv_11=null;... |
java | public DescribeImagesRequest withOwners(String... owners) {
if (this.owners == null) {
setOwners(new com.amazonaws.internal.SdkInternalList<String>(owners.length));
}
for (String ele : owners) {
this.owners.add(ele);
}
return this;
} |
python | def should_ignore(self, filename):
"""Should ignore a given filename?"""
_, ext = os.path.splitext(filename)
return ext in self.ignored_file_extensions |
java | public final ComputeThreatListDiffResponse computeThreatListDiff(
ThreatType threatType,
ByteString versionToken,
ComputeThreatListDiffRequest.Constraints constraints) {
ComputeThreatListDiffRequest request =
ComputeThreatListDiffRequest.newBuilder()
.setThreatType(threatType)... |
java | public void setViewerPreferences(int preferences) {
this.pageLayoutAndMode |= preferences;
// for backwards compatibility, it is also possible
// to set the following viewer preferences with this method:
if ((preferences & viewerPreferencesMask) != 0) {
pageLayoutAndMode = ~viewerPreferencesMask & pageLayout... |
java | private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport)
throws IOException {
logger.entering(new Object[] { writer, templateReader, jsonReport });
String readLine = null;
while ((readLine = templateReader.readLine()) != null) {
... |
java | public boolean cancel(boolean mayInterruptIfRunning) {
boolean cancelled =
(result == null) && internalComplete(new AltResult(new CancellationException()));
postComplete();
return cancelled || isCancelled();
} |
python | def Network_getCertificate(self, origin):
"""
Function path: Network.getCertificate
Domain: Network
Method name: getCertificate
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'origin' (type: string) -> Origin to get certificate for.
Returns:
'table... |
python | def verify_ticket(self, ticket):
"""Verifies CAS 2.0+/3.0+ XML-based authentication ticket and returns extended attributes"""
(response, charset) = self.get_verification_response(ticket)
return self.verify_response(response, charset) |
python | def pass_creds_to_nylas():
"""
This view loads the credentials from Google and passes them to Nylas,
to set up native authentication.
"""
# If you haven't already connected with Google, this won't work.
if not google.authorized:
return "Error: not yet connected with Google!", 400
if... |
java | public Properties getAttributeValueAsEncryptedProperties(final String _key)
throws EFapsException
{
final Properties properties = getAttributeValueAsProperties(_key, false);
final Properties props = new EncryptableProperties(properties, SystemConfiguration.ENCRYPTOR);
return props;
... |
java | public static float smoothPulse(float a1, float a2, float b1, float b2, float x) {
if (x < a1 || x >= b2)
return 0;
if (x >= a2) {
if (x < b1)
return 1.0f;
x = (x - b1) / (b2 - b1);
return 1.0f - (x*x * (3.0f - 2.0f*x));
}
x = (x - a1) / (a2 - a1);
return x*x * (3.0f - 2.0f*x);
} |
python | def team(self, name=None, id=None, is_hidden=False, **kwargs):
"""
Team of KE-chain.
Provides a team of :class:`Team` of KE-chain. You can filter on team name or provide id.
:param name: (optional) team name to filter
:type name: basestring or None
:param id: (optional)... |
java | public Node<T> searchNearestHigher(long value, boolean acceptEquals) {
if (root == null) return null;
return searchNearestHigher(root, value, acceptEquals);
} |
java | public List<CarbonJobInfo> getJobList()
{
Element statusList = element.getChild("JobStatusList");
if (statusList != null)
{
List<CarbonJobInfo> jobs = new ArrayList<CarbonJobInfo>();
for (Element job : statusList.getChildren())
{
jobs.add(new CarbonJobInfo(job));
}
return jobs;
}
else i... |
python | def _verify_views():
'''
Verify that you have the views you need. This can be disabled by
adding couchbase.skip_verify_views: True in config
'''
global VERIFIED_VIEWS
if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False):
return
cb_ = _get_connection()
ddoc = {... |
java | public final synchronized void uninstall() {
// To transition a Stateful bean to the "does not exist" state,
// either ejbRemove or ejbPassivate must be called.
// ejbPassivate has been chosen, as it will generally perform
// better (it normally does less) assuming that the bean is not
... |
java | public void getActiveTransactions(Set<PersistentTranId> transactionList) throws MessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getActiveTransactions", transactionList);
AbstractItem item = null;
NonLockingCursor cursor = new... |
java | public static void executeCommand(String[] args) throws IOException {
OptionParser parser = getParser();
String url = null;
Boolean confirm = false;
// parse command-line input
OptionSet options = parser.parse(args);
if(options.has(AdminParserUti... |
python | def P_conditional(self, i, li, j, lj, y):
"""Compute the conditional probability
P_\theta(li | lj, y)
=
Z^{-1} exp(
theta_{i|y} \indpm{ \lambda_i = Y }
+ \theta_{i,j} \indpm{ \lambda_i = \lambda_j }
)
In other words, compute... |
java | <T extends Entity<?, ?>> Builder<BE, T> retreatTo(Relationships.WellKnown over, Class<T> entityType) {
return new Builder<>(this, hop(), Query.filter(), entityType).hop(Related.asTargetBy(over), type(entityType));
} |
python | def cluster_coincs_multiifo(stat, time_coincs, timeslide_id, slide, window, argmax=numpy.argmax):
"""Cluster coincident events for each timeslide separately, across
templates, based on the ranking statistic
Parameters
----------
stat: numpy.ndarray
vector of ranking values to maximize
t... |
java | public static boolean hasValue(InputComponent<?, ?> input)
{
boolean ret;
Object value = InputComponents.getValueFor(input);
if (value == null)
{
ret = false;
}
else if (value instanceof String && value.toString().isEmpty())
{
ret = false;
}
els... |
python | def scan_roles(self):
"""
Iterate over each role and report its stats.
"""
for key, value in sorted(self.roles.iteritems()):
self.paths["role"] = os.path.join(self.roles_path, key)
self.paths["meta"] = os.path.join(self.paths["role"], "meta",
... |
python | def print_element_xray_transitions(self, element, file=sys.stdout, tabulate_kwargs=None):
"""
Prints all x-ray transitions for an element, with their different
notations and energy.
{element}
:arg file: file for output, default to standard out
"""
header = ['IUP... |
python | def ParseRecord(self, parser_mediator, key, structure):
"""Parse the record and return an SCCM log event object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structure.
st... |
python | def notifications(self):
"""
Generator method that yields all HMC notifications (= JMS messages)
received by this notification receiver.
Example::
receiver = zhmcclient.NotificationReceiver(topic, hmc, userid,
password)... |
python | def fits_region_objects_to_table(regions):
"""
Converts list of regions to FITS region table.
Parameters
----------
regions : list
List of `regions.Region` objects
Returns
-------
region_string : `~astropy.table.Table`
FITS region table
Examples
--------
>... |
python | def _kp2(A, B):
"""Special case Kronecker tensor product of A[i] and B[i] at each
time interval i for i = 0 .. N-1
Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0]
"""
N = A.shape[0]
if B.shape[0] != N:
raise(ValueError)
newshape1 = A.shape[1]*B.shape[1]
return... |
python | def _run_raw(self, cmd: str, ignore_errors=False) -> Tuple[str, str]:
"""Runs given cmd in the task using current SSH session, returns
stdout/stderr as strings. Because it blocks until cmd is done, use it for
short cmds. Silently ignores failing commands.
This is a barebones method to be used during in... |
python | def start(self):
'''Get ready for a profiling run'''
self._configs = self._client.config_get('slow-*')
self._client.config_set('slowlog-max-len', 100000)
self._client.config_set('slowlog-log-slower-than', 0)
self._client.execute_command('slowlog', 'reset') |
python | def deserialize_json(cls, serialized_json):
'''Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon}
'''
serialized = json.loads(serialized_json)
return Macaroon.from_dict(serialized) |
python | def get_leaf(self, index):
"""
Returns a leaf at the given index.
:param index:
:return: leaf (value) at index
"""
leaf_level_index = len(self.tree['levels']) - 1
if index < 0 or index > len(self.tree['levels'][leaf_level_index]) - 1:
# index is out of... |
python | def event_detach(self, eventtype):
"""Unregister an event notification.
@param eventtype: the event type notification to be removed.
"""
if not isinstance(eventtype, EventType):
raise VLCException("%s required: %r" % ('EventType', eventtype))
k = eventtype.value
... |
python | def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request obje... |
python | def parse_results_mol2(mol2_outpath):
"""Parse a DOCK6 mol2 output file, return a Pandas DataFrame of the results.
Args:
mol2_outpath (str): Path to mol2 output file
Returns:
DataFrame: Pandas DataFrame of the results
"""
docked_ligands = pd.DataFrame()
lines = [line.strip() ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.