language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def profileit(func):
"""
Decorator straight up stolen from stackoverflow
"""
def wrapper(*args, **kwargs):
datafn = func.__name__ + ".profile" # Name the data file sensibly
prof = cProfile.Profile()
prof.enable()
retval = prof.runcall(func, *args, **kwargs)
prof.d... |
java | public static java.util.Date getDayAsDate(int day) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, day);
return cal.getTime();
} |
python | def get_partition_function(self):
r"""
Returns the partition function for a given undirected graph.
A partition function is defined as
.. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i)
where m is the number of factors present in the graph
and X are all the random variables pr... |
java | public static String tryResolveHostName(final String nameToResolve, final boolean preferIPv6) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Trying to resolve hostname : " + nameToResolve + ", prefer IPv6 : " + preferIPv6);
}
return AccessControl... |
java | public static <CustomSubjectBuilderT extends CustomSubjectBuilder>
CustomSubjectBuilderT assertAbout(
CustomSubjectBuilder.Factory<CustomSubjectBuilderT> factory) {
return assert_().about(factory);
} |
java | public void marshall(DescribeEventCategoriesRequest describeEventCategoriesRequest, ProtocolMarshaller protocolMarshaller) {
if (describeEventCategoriesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshalle... |
python | def clear_choice_ids(self):
"""stub"""
if (self.get_choice_ids_metadata().is_read_only() or
self.get_choice_ids_metadata().is_required()):
raise NoAccess()
self.my_osid_object_form._my_map['choiceIds'] = \
self._choice_ids_metadata['default_object_values']... |
java | private Object checkNullValues(Object val1, Object val2, int index,
CallStack callstack) throws EvalError {
if ( Primitive.NULL == val1 && Primitive.VOID != val2
&& jjtGetChild(index).jjtGetChild(0)
instanceof BSHAmbiguousName) try {
Variable var = nul... |
python | def write_bus_data(self, file):
""" Writes bus data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BUS_ATTRS)
for bus in self.case.buses:
writer.writerow([getattr(bus, attr) for attr in BUS_ATTRS]) |
java | public static PactDslRootValue numberType(Number number) {
PactDslRootValue value = new PactDslRootValue();
value.setValue(number);
value.setMatcher(TypeMatcher.INSTANCE);
return value;
} |
python | def setup_argparse():
"""
Setup the argparse argument parser
:return: instance of argparse
:rtype: ArgumentParser
"""
parser = argparse.ArgumentParser(
description='Convert old ini-style GNS3 topologies (<=0.8.7) to '
'the newer version 1+ JSON format')
parser.ad... |
python | def combinations(n, k, strength=1, vartype=BINARY):
r"""Generate a bqm that is minimized when k of n variables are selected.
More fully, we wish to generate a binary quadratic model which is minimized
for each of the k-combinations of its variables.
The energy for the binary quadratic model is given b... |
java | public static boolean arrayequals(byte[] a,
byte[] b,
int count) {
for (int i = 0; i < count; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
} |
python | def list_all_orders(cls, **kwargs):
"""List Orders
Return a list of Orders
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_orders(async=True)
>>> result = thread.get()
... |
python | def pub(self, topic=b'', embed_topic=False):
"""
Returns a callable that can be used to transmit a message, with a given
``topic``, in a publisher-subscriber fashion. Note that the sender
function has a ``print`` like signature, with an infinite number of
arguments. Each one bein... |
python | def transp(I,J,c,d,M):
"""transp -- model for solving the transportation problem
Parameters:
I - set of customers
J - set of facilities
c[i,j] - unit transportation cost on arc (i,j)
d[i] - demand at node i
M[j] - capacity
Returns a model, ready to be solved.
"""
... |
python | def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Logical Partitions of CPC (empty result in DPM
mode."""
cpc_oid = uri_parms[0]
query_str = uri_parms[1]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid)
except KeyError:
raise Inval... |
java | private static void getAttachedPrep(final List<Token> sentenceToken, final List<Phrase> sentencePhrase,
final int index) {
final String prep;
boolean nameSequenceMeetEnd = true;
final Collection<Phrase> phraseSequence = new HashSet<>();
int phrase... |
python | def search(fcn, x0, incr=0, fac=1.1, maxit=100, analyzer=None):
""" Search for and bracket root of one-dimensional function ``fcn(x)``.
This method searches for an interval in ``x`` that brackets
a root of ``fcn(x)=0``. It examines points ::
x[j + 1] = fac * x[j] + incr
where ``x[0]=x0`` and... |
python | def get_lowest_numeric_score_metadata(self):
"""Gets the metadata for the lowest numeric score.
return: (osid.Metadata) - metadata for the lowest numeric score
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.Resource... |
python | def _execute_task_group(self, queue, tasks, all_task_ids, queue_lock):
"""
Executes the given tasks in the queue. Updates the heartbeat for task
IDs passed in all_task_ids. This internal method is only meant to be
called from within _process_from_queue.
"""
log = self.log... |
java | public void setAdditionalHeaders(Map<String,String> additionalHeaders) {
Map<String, String> newMap = new HashMap<>();
for (Entry<String,String> e : additionalHeaders.entrySet()) {
boolean found = false;
for(String restrictedHeaderField : RESTRICTED_HTTP_HEADERS) {
... |
python | def _extract_variable_parts(variable_key, variable):
"""Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: Name of the variable up to the pa... |
java | @Override
public void destroy(String name) {
checkStarted();
if(persistenceService == null) {
return;
}
PersistenceSpace space = knownPersistenceSpaces.remove(name);
SafeSpaceIdentifier identifier = (space == null) ?
persistenceService.createSafeSpaceIdentifier(PERSISTENCE_SPACE_OWNE... |
java | public NumberExpression<T> mod(Expression<T> num) {
return Expressions.numberOperation(getType(), Ops.MOD, mixin, num);
} |
java | @Override
public void doMessageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
// GL.debug("http", getClass().getSimpleName() + " request received.");
if (! httpRequestMessageReceived(nextFilter, session, message)) return;
HttpRequestMessage httpReques... |
java | public static String toJsonString(Object val, boolean pretty) {
try {
return pretty ? mapper.writerWithDefaultPrettyPrinter().with(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(val) : mapper.writeValueAsString(val);
} catch (Exception e) {
throw new RuntimeEx... |
java | @Override
public boolean route(RoutedMessage routedMessage) {
if (routedMessage == null) {
return true;
}
//There can be many Reader locks, but only one writer lock.
//This ReaderWriter lock is needed to avoid duplicate messages when the class is passing on the EarlyBuff... |
python | def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.... |
java | private void printUntokenizable(final Properties properties) {
final String untokenizable = properties.getProperty("untokenizable");
if (untokenizable.equalsIgnoreCase("yes")) {
this.unTokenizable = true;
} else {
this.unTokenizable = false;
}
} |
java | public static String resolveSchema(String schema, RamlRoot document) {
if (document == null || schema == null || schema.indexOf("{") != -1) {
return null;
}
if (document.getSchemas() != null && !document.getSchemas().isEmpty()) {
for (Map<String, String> map : document.getSchemas()) {
if (map.containsKe... |
python | def _evaluate_function(self, Ybus, V, Sbus, pv, pq):
""" Evaluates F(x).
"""
mis = multiply(V, conj(Ybus * V)) - Sbus
F = r_[mis[pv].real, mis[pq].real, mis[pq].imag]
return F |
java | public void delete() {
Buffer buffer = this.buffer instanceof SlicedBuffer ? ((SlicedBuffer) this.buffer).root() : this.buffer;
if (buffer instanceof FileBuffer) {
((FileBuffer) buffer).delete();
} else if (buffer instanceof MappedBuffer) {
((MappedBuffer) buffer).delete();
}
offsetInde... |
python | def FieldDefinitionProtosFromTuples(field_def_tuples):
"""Converts (field-name, type) tuples to MetricFieldDefinition protos."""
# TODO: This needs fixing for Python 3.
field_def_protos = []
for field_name, field_type in field_def_tuples:
if field_type in (int, long):
field_type = rdf_stats.MetricFiel... |
java | private void createPropertyAccessor(ClassNode classNode, PropertyNode fxProperty, FieldNode fxFieldShortName,
Expression initExp) {
FieldExpression fieldExpression = new FieldExpression(fxFieldShortName);
ArgumentListExpression ctorArgs = initExp == null ?
... |
python | def make_article_info_correspondences(self, article_info_div):
"""
Articles generally provide a first contact, typically an email address
for one of the authors. This will supply that content.
"""
corresps = self.article.root.xpath('./front/article-meta/author-notes/corresp')
... |
python | def stringmethod(func):
""" Validator factory which call a single method on the string. """
method_name = func()
@wraps(func)
def factory():
def validator(v):
if not isinstance(v, six.string_types):
raise Invalid(_(u'Not a string'), get_type_name(six.text_type), get_... |
java | protected T _jdoLoad(
final K id
)
{
if (id == null) {
return null;
}
Object p_object = null;
try {
p_object = getCastorTemplate().load( _objectType, id );
} catch (DataAccessException ex) {
Throwab... |
java | void onDateGroupChanged(@Observes DataSetGroupDateChanged event) {
ColumnGroup columnGroup = event.getColumnGroup();
DataSetGroup groupOp = getFirstGroupOp();
if (groupOp != null) {
groupOp.setColumnGroup(columnGroup);
changeEvent.fire(new DataSetLookupChangedEvent(dataS... |
python | def recompress_archive(archive, verbosity=0, interactive=True):
"""Recompress an archive to hopefully smaller size."""
util.check_existing_filename(archive)
util.check_writable_filename(archive)
if verbosity >= 0:
util.log_info("Recompressing %s ..." % (archive,))
res = _recompress_archive(a... |
java | @Override
public synchronized boolean load(File tempDir) {
if (!NativeLibraryLoader.load(tempDir, NATIVE_LIBRARY_NAME)) {
return false;
}
if (!initialized) {
initNative();
initialized = true;
}
return true;
} |
python | def likelihood_weighted_sample(self, evidence=None, size=1, return_type="dataframe"):
"""
Generates weighted sample(s) from joint distribution of the bayesian
network, that comply with the given evidence.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Fried... |
python | def get_formset(self, request, obj=None, **kwargs):
"""
Return a form, if the obj has a staffmember object, otherwise
return an empty form
"""
if obj is not None and self.model.objects.filter(user=obj).count():
return super(StaffMemberAdmin, self).get_formset(
... |
python | def adjust_learning_rate(optimizer, epoch):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.lr * (0.1 ** (epoch // 30))
for param_group in optimizer.param_groups:
param_group['lr'] = lr |
python | def get_preds(model:nn.Module, dl:DataLoader, pbar:Optional[PBar]=None, cb_handler:Optional[CallbackHandler]=None,
activ:nn.Module=None, loss_func:OptLossFunc=None, n_batch:Optional[int]=None) -> List[Tensor]:
"Tuple of predictions and targets, and optional losses (if `loss_func`) using `dl`, max batc... |
java | public void visit(final WebAppServlet webAppServlet) {
NullArgumentException.validateNotNull(webAppServlet, "Web app servlet");
Class<? extends Servlet> servletClass = webAppServlet
.getServletClass();
if (servletClass == null && webAppServlet.getServletClassName() != null) {
try {
servletClass =... |
python | async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
"""
Stores the value in the given key with ttl if specified. Raises an error if the
key already exists.
:param key: str
:param value: obj
:param ttl: int the expiration time in seco... |
java | public static Matrix pascal(int size)
{
if(size <= 0 )
throw new ArithmeticException();
DenseMatrix P = new DenseMatrix(size, size);
RowColumnOps.fillRow(P, 0, 0, size, 1.0);
RowColumnOps.fillCol(P, 0, 0, size, 1.0);
for(int i = 1; i < size; i++)
for(i... |
python | def geopotential2geometric(h: float, latitude: float) -> float:
"""Converts geopoential height to geometric height
Parameters
----------
h : float
Geopotential height (meters)
latitude : float
Latitude (degrees)
Returns
-------
z : float
Geometric Height (meters... |
python | def parallel_safe(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in parallel.
One thread per Crazyflie is started to execute the function. The
threads are joined at the end and if one or more of the threads raised
an exception this function w... |
java | public DataLakeAnalyticsAccountInner beginCreate(String resourceGroupName, String accountName, CreateDataLakeAnalyticsAccountParameters parameters) {
return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body();
} |
python | def pfopen(self, event=None):
""" Load the parameter settings from a user-specified file. """
# Get the selected file name
fname = self._openMenuChoice.get()
# Also allow them to simply find any file - do not check _task_name_...
# (could use tkinter's FileDialog, but this one ... |
java | public alluxio.grpc.UpdateUfsModePOptionsOrBuilder getOptionsOrBuilder() {
return options_ == null ? alluxio.grpc.UpdateUfsModePOptions.getDefaultInstance() : options_;
} |
java | public PagedList<JobPreparationAndReleaseTaskExecutionInformation> listPreparationAndReleaseTaskStatusNext(final String nextPageLink, final JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions) {
ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecution... |
python | def vote(seglists, n):
"""
Given a sequence of segmentlists, returns the intervals during
which at least n of them intersect. The input segmentlists must be
coalesced, the output is coalesced.
Example:
>>> from pycbc_glue.segments import *
>>> w = segmentlist([segment(0, 15)])
>>> x = segmentlist([segment(5,... |
java | @Override
public final Iterable<RootDocument> findAll(final String filename) {
final Query searchQuery =
new Query(Criteria.where("filename").is(filename));
final List<RootDocumentMongo> rootDocumentsMongo =
mongoTemplate.find(searchQuery, RootDocumentMongo.class);
... |
python | def find_child(sexpr: Sexpr, *tags: str) -> Optional[Sexpr]:
"""Search for a tag among direct children of the s-expression."""
_assert_valid_sexpr(sexpr)
for child in sexpr[1:]:
if _is_sexpr(child) and child[0] in tags:
return child
return None |
python | def general_eq(a, b, attributes):
"""Return whether two objects are equal up to the given attributes.
If an attribute is called ``'phi'``, it is compared up to |PRECISION|.
If an attribute is called ``'mechanism'`` or ``'purview'``, it is
compared using set equality. All other attributes are compared ... |
java | public static final boolean hasProperty(Object bean, String property)
{
try
{
return (boolean) doFor(
bean,
property,
null,
(Object a, int i)->{return true;},
(List l, int i)->{return true;},
... |
java | protected void setMapProperty(Map<String, Object> map, String name, Object value, FormMappingOption option, Object parentBean,
String parentName) {
final boolean strArray = isMapValueStringArray(parentBean, parentName);
final Object registered;
if (value instanceof String[]) {
... |
java | @SuppressWarnings("unchecked")
protected <A extends Comparable> ComparablePath<A> createComparable(String property, Class<? super A> type) {
return add(new ComparablePath<A>((Class) type, forProperty(property)));
} |
java | public int setPageCount(final int num) {
int diff = num - getCheckableCount();
if (diff > 0) {
addIndicatorChildren(diff);
} else if (diff < 0) {
removeIndicatorChildren(-diff);
}
if (mCurrentPage >=num ) {
mCurrentPage = 0;
}
s... |
python | def n_pitche_classes_used(pianoroll):
"""Return the number of unique pitch classes used in a pianoroll."""
_validate_pianoroll(pianoroll)
chroma = _to_chroma(pianoroll)
return np.count_nonzero(np.any(chroma, 0)) |
java | @Override
public void backward() {
Tensor tmp1 = new Tensor(yAdj); // copy
tmp1.multiply(weightX);
modInX.getOutputAdj().elemAdd(tmp1);
Tensor tmp2 = new Tensor(yAdj); // copy
tmp2.multiply(weightW);
modInW.getOutputAdj().elemAdd(tmp2);
} |
java | public static synchronized void initializeDefaults(String processName, boolean useMsgs, boolean isClient) {
BundleRepositoryRegistry.isClient = isClient;
BundleRepositoryRegistry.initializeDefaults(processName, useMsgs);
} |
python | def kill_random_node(cluster_config_file, yes, cluster_name):
"""Kills a random Ray node. For testing purposes only."""
click.echo("Killed node with IP " +
kill_node(cluster_config_file, yes, cluster_name)) |
java | @Override
public SubclassRelationship getClassesDefinedByCall(Node callNode) {
SubclassRelationship relationship =
super.getClassesDefinedByCall(callNode);
if (relationship != null) {
return relationship;
}
Node callName = callNode.getFirstChild();
SubclassType type = typeofClassDef... |
java | public boolean shouldDisplay() throws IOException, ServletException {
if (!Functions.hasPermission(Jenkins.ADMINISTER)) {
return false;
}
StaplerRequest req = Stapler.getCurrentRequest();
if (req == null) {
return false;
}
List<Ancestor> ancestor... |
python | def process_docstring(app, what, name, obj, options, lines):
"""
Process the docstring for a given python object.
Note that the list 'lines' is changed in this function. Sphinx
uses the altered content of the list.
"""
result = [re.sub(r'U\{([^}]*)\}', r'\1',
re.sub(r'(L|C)\... |
python | def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... |
python | def parse_keystring(conn, key_string):
"""
A utility function to turn strings like 'Mod1+Mod4+a' into a pair
corresponding to its modifiers and keycode.
:param key_string: String starting with zero or more modifiers followed
by exactly one key press.
Avail... |
python | def values(self, corr, snrv, snr_norm, psd, indices, template):
""" Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sample index
chisq_dof: Array
Number of statistical degrees of freedom for the chi... |
python | def on_menu_save_interpretation(self, event):
'''
save interpretations to a redo file
'''
thellier_gui_redo_file = open(
os.path.join(self.WD, "thellier_GUI.redo"), 'w')
#--------------------------------------------------
# write interpretations to thellier... |
python | def to_op(self):
"""
Extracts the modification operation(s) from the map.
:rtype: list, None
"""
removes = [('remove', r) for r in self._removes]
value_updates = list(self._extract_updates(self._value))
new_updates = list(self._extract_updates(self._updates))
... |
python | def format_stats(self, stats:TensorOrNumList)->None:
"Format stats before printing."
str_stats = []
for name,stat in zip(self.names,stats):
str_stats.append('#na#' if stat is None else str(stat) if isinstance(stat, int) else f'{stat:.6f}')
if self.add_time: str_stats.append(f... |
java | public I withOpenStart() {
if (this.start.isOpen()) {
return this.getContext();
} else {
Boundary<T> b = Boundary.of(IntervalEdge.OPEN, this.start.getTemporal());
return this.getFactory().between(b, this.end);
}
} |
java | public void setNetworkInterfaces(java.util.Collection<ScheduledInstancesNetworkInterface> networkInterfaces) {
if (networkInterfaces == null) {
this.networkInterfaces = null;
return;
}
this.networkInterfaces = new com.amazonaws.internal.SdkInternalList<ScheduledInstances... |
python | def filter_taxa(records, taxids, unclassified=False, discard=False):
'''
Selectively include or discard specified taxon IDs from tictax annotated FASTA/Qs
Filters all children of specified taxon IDs
Returns subset of input SeqRecords
Taxon IDs of 1 and 2 are considered unclassified
'''
taxi... |
java | private String removeProperty(Node node, HierarchicalProperty property)
{
try
{
node.getProperty(property.getStringName()).remove();
node.save();
return WebDavConst.getStatusDescription(HTTPStatus.OK);
}
catch (AccessDeniedException e)
{
r... |
python | def commit_docs(*, added, removed):
"""
Commit the docs to the current branch
Assumes that :func:`setup_GitHub_push`, which sets up the ``doctr_remote``
remote, has been run.
Returns True if changes were committed and False if no changes were
committed.
"""
TRAVIS_BUILD_NUMBER = os.env... |
python | def _get_conn(self, host, port, afi):
"""Get or create a connection to a broker using host and port"""
host_key = (host, port)
if host_key not in self._conns:
self._conns[host_key] = BrokerConnection(
host, port, afi,
request_timeout_ms=self.timeout * ... |
java | public Deferred<IncomingDataPoint> getLastPoint(final boolean resolve_names,
final int back_scan) {
if (back_scan < 0) {
throw new IllegalArgumentException(
"Backscan must be zero or a positive number");
}
this.resolve_names = resolve_names;
this.back_scan = back_scan;
... |
python | def get_smt_userid():
"""Get the userid of smt server"""
cmd = ["sudo", "/sbin/vmcp", "query userid"]
try:
userid = subprocess.check_output(cmd,
close_fds=True,
stderr=subprocess.STDOUT)
userid = bytes.decode(u... |
java | private JobConfig.Builder createJobBuilder (Properties jobProps) {
// Create a single task for job planning
String planningId = getPlanningJobId(jobProps);
Map<String, TaskConfig> taskConfigMap = Maps.newHashMap();
Map<String, String> rawConfigMap = Maps.newHashMap();
for (String key : jobProps.stri... |
java | @SuppressWarnings("unchecked")
public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException
{
List importList = getImportList(parameters);
return executeMacro(importList);
} |
java | public static Request errorReport(Class<?> klass, Throwable cause) {
return runner(new ErrorReportingRunner(klass, cause));
} |
java | protected void close()
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass
, "close"
);
if (flushHelper != null)
flushHelper.shutdown(); ... |
java | @Override
public SparseDoubleVector getRowVector(int row) {
// Check whether we have this row cached
VersionedVector cachedRow = colToVectorCache.get(row);
// If the cache was empty or if the matrix has been updated since this
// vector was created, recreate the vector and cache it b... |
java | protected String prototypeToString() {
return (prototype instanceof double[]) ? FormatUtil.format((double[]) prototype) : prototype.toString();
}
@Override
public String getPrototypeType() {
return "Prototype";
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + pr... |
python | def keys_recover(cls, fqdn, key):
"""Recover deleted key for a domain."""
data = {
"deleted": False,
}
return cls.json_put('%s/domains/%s/keys/%s' % (cls.api_url, fqdn, key),
data=json.dumps(data),) |
python | def __store_recent_file(self, file):
"""
Stores given recent file into the settings.
:param file: File to store.
:type file: unicode
"""
LOGGER.debug("> Storing '{0}' file in recent files.".format(file))
recentFiles = [foundations.strings.to_string(recentFile)
... |
java | public void run() {
// todo if (logger.isDebugEnabled()) {
// logger.debug("start running PooledDataSourceCleaner");
// }
state = STATE_CLEANER.RUNNING;
while (state != STATE_CLEANER.SHUTDOWN) {
try {
Thread.sleep(interval * 1000);
} catch... |
python | def _lint(dxapp_json_filename, mode):
"""
Examines the specified dxapp.json file and warns about any
violations of app guidelines.
Precondition: the dxapp.json file exists and can be parsed.
"""
def _find_readme(dirname):
for basename in ['README.md', 'Readme.md', 'readme.md']:
... |
python | def _Rforce(self, R, z, phi=0, t=0):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
rad... |
java | public synchronized void addShutdownListener(ShutdownListener listener) {
if (state == CLOSED) {
listener.handleCompleted();
} else {
listeners.add(listener);
}
} |
python | def visit_Block(self, node, frame):
"""Call a block and register it for the template."""
level = 0
if frame.toplevel:
# if we know that we are a child template, there is no need to
# check if we are one
if self.has_known_extends:
return
... |
python | def node_copy(node, nodefactory=Node):
"""Make a deep copy of the node"""
return nodefactory(node.tag, node.attrib.copy(), node.text,
[node_copy(n, nodefactory) for n in node]) |
java | public static boolean isMatrix(IntBuffer shapeInfo) {
int rank = Shape.rank(shapeInfo);
if (rank != 2)
return false;
return !isVector(shapeInfo);
} |
java | protected KeyStore loadKeyStore(char[] pw) throws VectorPrintException {
try {
return CertificateHelper.loadKeyStore(getValue(KEYSTORE, URL.class).openStream(),
getValue(KEYSTORETYPE_PARAM, KEYSTORETYPE.class).name(), pw);
} catch (IOException | KeyStoreException | NoSuchAlgorithmExcep... |
python | def get_epoch_start(self, window_start):
""" Get the position (seconds) of the nearest epoch.
Parameters
----------
window_start : float
Position of the current window (seconds)
Returns
-------
float
Position (seconds) of the nearest epoc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.