language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def Add(self, rdf_value, mutation_pool=None):
"""Adds an rdf value to the queue.
Adds an rdf value to the queue. Does not require that the queue be locked.
Args:
rdf_value: The rdf value to add to the queue.
mutation_pool: A MutationPool object to write to.
Raises:
ValueError: rdf_... |
java | void reload() {
CmsRpcAction<CmsResourceStatusBean> action = new CmsRpcAction<CmsResourceStatusBean>() {
@Override
public void execute() {
start(0, true);
CmsCoreProvider.getVfsService().getResourceStatus(
m_structureId,
... |
java | protected final void setControllerPath(String path) {
requireNonNull(path, "Global path cannot be change to 'null'");
if (!"".equals(path) && !"/".equals(path)) {
this.controllerPath = pathCorrector.apply(path);
}
} |
python | def package_and_copy(package_root_dir, setup_py, output_tar_path):
"""Repackage an CloudML package and copy it to a staging dir.
Args:
package_root_dir: the root dir to install package from. Usually you can get the path
from inside your module using a relative path to __file__.
setup_py: the path t... |
java | HdfsFileStatus getHdfsFileInfo(String src) {
String srcs = normalizePath(src);
byte[][] components = INodeDirectory.getPathComponents(srcs);
readLock();
try {
INode targetNode = rootDir.getNode(components);
if (targetNode == null) {
return null;
}
else {
return cr... |
python | def set_timeout(scope, timeout):
"""
Defines the time after which Exscript fails if it does not receive a
prompt from the remote host.
:type timeout: int
:param timeout: The timeout in seconds.
"""
conn = scope.get('__connection__')
conn.set_timeout(int(timeout[0]))
return True |
java | public void setAsynchConsumerCallback(int requestNumber,
int maxActiveMessages,
long messageLockExpiry,
int batchsize,
OrderingContext orderContext)
{
... |
java | public void init(CmsObject cms) {
m_cms = cms;
m_result = null;
m_lastException = null;
m_pageCount = 0;
m_nextUrl = null;
m_prevUrl = null;
} |
python | def validate_param_completion(self, param, leftover_args):
""" validates that a param should be completed """
# validates param starts with unfinished word
completes = self.validate_completion(param)
# show parameter completions when started
full_param = self.unfinished_word.sta... |
java | public static void exports(Media media, Map<Circuit, Collection<TileRef>> circuits)
{
Check.notNull(media);
Check.notNull(circuits);
final Xml nodeCircuits = new Xml(NODE_CIRCUITS);
for (final Map.Entry<Circuit, Collection<TileRef>> entry : circuits.entrySet())
{
... |
java | private HttpResponse init() throws HttpException {
try {
this.status = httpConnection.responseCode();
this.in = (this.status < HttpStatus.HTTP_BAD_REQUEST) ? httpConnection.getInputStream() : httpConnection.getErrorStream();
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
// 服... |
java | public void forwardNewSessionRequestAndUpdateRegistry(TestSession session)
throws NewSessionException {
try (NewSessionPayload payload = NewSessionPayload.create(
ImmutableMap.of("desiredCapabilities", session.getRequestedCapabilities()))) {
StringBuilder json = new StringBuilder();
payloa... |
python | def add_asset(self, asset_type, asset_name):
"""
Add an asset to the adversary
Args:
asset_type: (str) Either PHONE, HANDLER, or URL
asset_name: (str) the value for the asset
Returns:
"""
if not self.can_update():
self._tcex.handle_er... |
python | def get(cls, session, record_id, endpoint_override=None):
"""Return a specific record.
Args:
session (requests.sessions.Session): Authenticated session.
record_id (int): The ID of the record to get.
endpoint_override (str, optional): Override the default
... |
python | def resize(self, size, interp='bilinear'):
"""Resize the image.
Parameters
----------
size : int, float, or tuple
* int - Percentage of current size.
* float - Fraction of current size.
* tuple - Size of the output image.
interp : :obj:`str... |
java | static void checkArrayForDuplicates(Object[] array, String arrayName) {
if (array.length > 1) {
if (array.length == 2) {
if (array[0] == array[1] ||
(array[0] != null && array[0].equals(array[1]))) {
throw new IllegalArgumentException(arra... |
python | def evaluate_report(report):
"""Iterate over validation errors."""
if report["valid"]:
return
for warn in report["warnings"]:
LOGGER.warning(warn)
# We only ever test one table at a time.
for err in report["tables"][0]["errors"]:
LOGGER.error(e... |
python | def goto_step(self, inst: InstanceNode) -> InstanceNode:
"""Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance.
"""
try:
return inst._entry(
inst.value.index(self.parse_value(inst.schema_node)))
except... |
java | private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
String remote = ctx.channel().remoteAddress().toString();
String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
if (supportedMechanisms.length == 0) {... |
java | protected CellEditor createClassCellEditor() {
return new DialogCellEditor(getControl()) {
@Override
protected Object openDialogBox(Control cellEditorWindow) {
final OpenTypeSelectionDialog dialog = new OpenTypeSelectionDialog(
getControl().getShell(),
false,
PlatformUI.getWorkbench().getP... |
python | def content_type(self) -> ContentType:
"""Override superclass method."""
if self._ctype:
return self._ctype
return (ContentType.config if self.parent.config else
ContentType.nonconfig) |
python | def maxRange(self):
"""Sets the maximum range for the currently selection calibration,
determined from its range of values store on file
"""
try:
x, freqs = self.datafile.get_calibration(str(self.ui.calChoiceCmbbx.currentText()), self.calf)
self.ui.frangeLowSpnbx.... |
python | def create_pull_request_reviewers(self, reviewers, repository_id, pull_request_id, project=None):
"""CreatePullRequestReviewers.
[Preview API] Add reviewers to a pull request.
:param [IdentityRef] reviewers: Reviewers to add to the pull request.
:param str repository_id: The repository I... |
java | public static final <T extends Date> Function<T, DateMidnight> dateToDateMidnight(DateTimeZone dateTimeZone) {
return FnDateMidnight.dateToDateMidnight(dateTimeZone);
} |
python | def join(self, experiment, genometric_predicate, output="LEFT", joinBy=None,
refName="REF", expName="EXP", left_on=None, right_on=None):
"""
*Wrapper of* ``JOIN``
The JOIN operator takes in input two datasets, respectively known as anchor
(the first/left one) and experiment... |
java | @Override
public Iterator<Object[]> getDataByFilter(DataProviderFilter dataFilter)
throws IOException {
logger.entering(dataFilter);
InputStream inputStream = resource.getInputStream();
Yaml yaml = constructYaml(resource.getCls());
Object yamlObject;
// Mark the... |
python | def once(self):
"""
Inspected function should be called one time
Return: self
"""
def check(): #pylint: disable=missing-docstring
return super(SinonExpectation, self).calledOnce
self.valid_list.append(check)
return self |
java | public void write(Writer out)
throws IOException
{
if (codeBase != null)
attribute("codebase",codeBase);
if (debug)
paramHolder.add("<param name=\"debug\" value=\"yes\">");
if (params != null)
for (Enumeration enm = params.keys(); enm.has... |
python | def com_google_fonts_check_required_tables(ttFont):
"""Font contains all required tables?"""
from .shared_conditions import is_variable_font
REQUIRED_TABLES = {
"cmap", "head", "hhea", "hmtx", "maxp", "name", "OS/2", "post"}
OPTIONAL_TABLES = {
"cvt ", "fpgm", "loca", "prep", "VORG", "EBDT", "EBLC"... |
python | def add_module(self, module):
'''
Adds configuration parameters from a Python module.
'''
for key, value in module.__dict__.iteritems():
if key[0:2] != '__':
self.__setattr__(attr=key, value=value) |
java | void parameter(String name, Object value) {
Preconditions.checkNotNull(name, "parameter name cannot be null");
if (value instanceof Observable)
throw new IllegalArgumentException(
"use parameters() method not the parameter() method for an Observable");
this.parame... |
java | public Term createTermOptions(String type, String lemma, String pos, String morphofeat, List<WF> wfs) {
return this.newTermOptions(type, lemma, pos, morphofeat, this.<WF>list2Span(wfs));
} |
java | public static int getSizeAsInt(final String propertyName, final int defaultValue)
{
final String propertyValue = getProperty(propertyName);
if (propertyValue != null)
{
final long value = parseSize(propertyName, propertyValue);
if (value < 0 || value > Integer.MAX_VAL... |
python | def parse_options():
"""
Parse command line arguments.
Returns:
options, args
"""
parser = argparse.ArgumentParser(description='Video downloader by radzak.',
prog='RTVdownloader')
urls_group = parser.add_mutually_exclusive_group(required=True)
u... |
python | def import_users(
path,
resource_name=None,
send_email_to_user=None,
alternate_email=None,
verbose=None,
export_to_file=None,
**kwargs,
):
"""Import users from a CSV file with columns:
username
first_name
last_name
email
sites: a comma-separated li... |
java | public static float pixelsFromSpResource(Context context, @DimenRes int sizeRes) {
final Resources res = context.getResources();
return res.getDimension(sizeRes) / res.getDisplayMetrics().density;
} |
java | private Callable createListToObjectBinding(ListProperty<P> listProperty) {
return () -> {
if (!isListChange() && listProperty.get() != null && listProperty.get().size() != 0) {
return listProperty.get().get(0);
}
return null;
};
} |
python | def snapPointToCanvas(self, x, y):
"""
Moves a point x,y to within the boundaries of the canvas.
:return: (x,y,snapped) where snapped is True if x or y were changed, False if not.
"""
if x < 0 or x > self.pixmap.width() or y < 0 or y > self.pixmap.height():
x = max(x,... |
java | public void buildMemberDetails(XMLNode node, Content classContentTree) {
Content memberDetailsTree = writer.getMemberTreeHeader();
buildChildren(node, memberDetailsTree);
classContentTree.addContent(writer.getMemberDetailsTree(memberDetailsTree));
} |
java | @Override
public int executeUpdate() throws SQLException
{
checkClosed();
if (!this.Query.isOfType(VoltSQL.TYPE_EXEC,VoltSQL.TYPE_UPDATE)) {
throw SQLError.get(SQLError.ILLEGAL_STATEMENT, this.Query.toSqlString());
}
int result = this.executeUpdate(this.Query.getExecu... |
java | protected void processChangeTrackerChange(final Map<String, Object> change) {
// Process each change from the feed:
String docID = (String) change.get("id");
if (docID == null || !Document.isValidDocumentId(docID))
return;
String lastSequence = change.get("seq").toString();
... |
python | def install_database(name, owner, template='template0', encoding='UTF8', locale='en_US.UTF-8'):
"""
Require a PostgreSQL database.
::
from fabtools import require
require.postgres.database('myapp', owner='dbuser')
"""
create_database(name, owner, template=template, encoding=enc... |
python | async def scroll(self, value, mode='relative'):
"""Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Curre... |
python | def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("Starting in mitiff save_datasets ... ")
def _delayed_create(create_opts, datasets):
LOG.debug("create_op... |
python | def rebuild(self, image):
"""
Rebuild the droplet with the specified image
A rebuild action functions just like a new create. [APIDocs]_
:param image: an image ID, an image slug, or an `Image` object
representing the image the droplet should use as a base
:type ... |
java | public static HTMLElement element(com.google.gwt.dom.client.Element element) {
return Js.cast(element);
} |
java | private XmlHttpResponse getReportXml(String reportXmlFilename) {
String url = LalCallColumnFixture.getLalUrl() + "/xmlrr/archive/Report/" + reportXmlFilename;
return env.doHttpGetXml(url);
} |
java | public Vertex translate(double x, double y, double z)
{
this.x += x;
this.y += y;
this.z += z;
return this;
} |
java | @Override
public WsByteBuffer[] getRawRequestBodyBuffers() throws IOException, IllegalHttpBodyException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "getRawRequestBodyBuffers(sync)");
}
setRawBody(true);
WsByteBuffer[] list = getReques... |
python | def polydisperse_spheres(shape: List[int], porosity: float, dist,
nbins: int = 5, r_min: int = 5):
r"""
Create an image of randomly place, overlapping spheres with a distribution
of radii.
Parameters
----------
shape : list
The size of the image to generate in [... |
java | public T photos_getAlbums(Integer userId, Collection<Long> albumIds)
throws FacebookException, IOException {
boolean hasUserId = null != userId && userId != 0;
boolean hasAlbumIds = null != albumIds && !albumIds.isEmpty();
assert (hasUserId || hasAlbumIds); // one of the two must be provided
if (ha... |
python | def process(event_name, data):
"""Iterates over the event handler registry and execute each found
handler.
It takes the event name and its its `data`, passing the return of
`ejson.loads(data)` to the found handlers.
"""
deserialized = loads(data)
event_cls = find_event(event_name)
event... |
python | def get_historic_prices(self, **params):
"""https://developers.coinbase.com/api/v2#get-historic-prices"""
if 'currency_pair' in params:
currency_pair = params['currency_pair']
else:
currency_pair = 'BTC-USD'
response = self._get('v2', 'prices', currency_pair, 'his... |
python | def _push_writer(self):
"""push a capturing buffer onto this Context and return
the new writer function."""
buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write |
java | @Override
public WebElement findElement() {
SlowLoadingElement loadingElement = new SlowLoadingElement(clock, timeOutInSeconds);
try {
return loadingElement.get().getElement();
} catch (NoSuchElementError e) {
throw new NoSuchElementException(
String.format("Timed out after %d second... |
python | def getSpec(cls):
"""
Return the spec for the GridCellLocationRegion
"""
spec = dict(
description=GridCellLocationRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
anchorInput=dict(
description="An array of 0's and 1's representing the sensory input "
... |
python | def dataframe(self, dtype=False, parse_dates=True, *args, **kwargs):
"""Return a pandas datafrome from the resource"""
import pandas as pd
rg = self.row_generator
t = self.resolved_url.get_resource().get_target()
if t.target_format == 'csv':
return self.read_csv(... |
java | public ArrayList<String> cdn_dedicated_serviceName_backend_GET(String serviceName, Long backend) throws IOException {
String qPath = "/order/cdn/dedicated/{serviceName}/backend";
StringBuilder sb = path(qPath, serviceName);
query(sb, "backend", backend);
String resp = exec(qPath, "GET", sb.toString(), null);
... |
java | public static void writeHprof() {
try {
android.os.Debug.dumpHprofData(Environment.getExternalStorageDirectory().getAbsolutePath() + "/osmdroid/trace-" + System.currentTimeMillis() + ".hprof");
} catch (IOException e) {
e.printStackTrace();
}
} |
java | public List<CmsEntityAttribute> getAttributes() {
List<CmsEntityAttribute> result = new ArrayList<CmsEntityAttribute>();
for (String name : m_simpleAttributes.keySet()) {
result.add(getAttribute(name));
}
for (String name : m_entityAttributes.keySet()) {
r... |
python | def are_any_attributes_visible(self):
"""
checks to see if any attributes are set to true
"""
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith('__') or inspect.ismethod(type_instance):
continue
if isins... |
python | def _send_periodic_internal(self, msg, period, duration=None):
"""Default implementation of periodic message sending using threading.
Override this method to enable a more efficient backend specific approach.
:param can.Message msg:
Message to transmit
:param float period:
... |
python | def _cmd(binary, *args):
'''
Wrapper to run at(1) or return None.
'''
binary = salt.utils.path.which(binary)
if not binary:
raise CommandNotFoundError('{0}: command not found'.format(binary))
cmd = [binary] + list(args)
return __salt__['cmd.run_stdout']([binary] + list(args),
... |
java | private byte[] fromLong(long data)
{
return new byte[] { (byte) ((data >> 56) & 0xff), (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff),
(byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff),
(byte) ((data >> 8) & 0xff), (byte) ((d... |
python | def ropt(self, name):
"""
Remove one option
"""
try:
del self.chart_opts[name]
except KeyError:
self.warning("Option " + name + " is not set")
except:
self.err("Can not remove option " + name) |
java | public void marshall(ListUniqueProblemsRequest listUniqueProblemsRequest, ProtocolMarshaller protocolMarshaller) {
if (listUniqueProblemsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(list... |
java | public void notifyReceiveAllowed(DestinationHandler destinationHandler)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "notifyReceiveAllowed", new Object[] {destinationHandler});
if(isPubSub())
{
// Notify consumers on this localization
Subscri... |
java | public static <T> ObservableTransformer<T,T> doOnDisposeFx(Action onDipsose) {
return obs -> obs.doOnDispose(() -> runOnFx(onDipsose));
} |
python | def p_task(self, p):
'task : TASK ID SEMICOLON task_statement ENDTASK'
p[0] = Task(p[2], p[4], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
python | def save(path, data, compression='default'):
"""
Save any Python structure to an HDF5 file. It is particularly suited for
Numpy arrays. This function works similar to ``numpy.save``, except if you
save a Python object at the top level, you do not need to issue
``data.flat[0]`` to retrieve it from in... |
java | public static Rule getRule(final String inequalitySymbol,
final Stack stack) {
if (stack.size() < 2) {
throw new IllegalArgumentException("Invalid " + inequalitySymbol
+ " rule - expected two parameters but received "
+ stack.size());
... |
python | def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp... |
python | def constraint_stats(self,primarylist=None):
"""Returns information about effect of constraints on population.
:param primarylist:
List of constraint names that you want specific information on
(i.e., not blended within "multiple constraints".)
:return:
``dict`... |
python | def _prepareSQL(cls, operation="SELECT", where=None, selectfields=None, orderBy=None):
"""Return a sql for the given operation.
Possible operations:
SELECT read data for this id
SELECTALL read data for all ids
INSERT insert data, create new id
... |
python | def search_template_create(id, body, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Create search template by supplied definition
id
Template ID
body
Search template definition
CLI example::
salt myminion elasticsearch.search_template_create mytemplate '{"t... |
java | public static boolean isPropertyToFiltering (ClassPropertyFilterHandler pvClassPropertyFilterHandler, Class<?> pvClassForFindFilter, Object pvKey) {
boolean lvAddProperty = false;
if (pvClassPropertyFilterHandler != null) {
ClassPropertyFilter lvClassPropertyFilter = pvClassPropertyFilterHandler.getClassPrope... |
python | def _find_next_prime(N):
"""Find next prime >= N"""
def is_prime(n):
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i:
i += 2
else:
return False
return True
if N < 3:
return 2
if N % 2... |
java | public String getViewURI(String controllerName, String viewName) {
FastStringWriter buf = new FastStringWriter();
return getViewURIInternal(controllerName, viewName, buf, true);
} |
java | @Override
public EEnum getIfcSpatialZoneTypeEnum() {
if (ifcSpatialZoneTypeEnumEEnum == null) {
ifcSpatialZoneTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1068);
}
return ifcSpatialZoneTypeEnumEEnum;
} |
java | @Override
public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {
return delegate.getMatrixHistory(start, limit);
} |
python | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure device exists and store it in an instance attribute
* change queryset to return only devices of current node
"""
super(BaseInterfaceList, self).initial(request, *args, **kwargs)
... |
java | public void marshall(DescribeUserPoolDomainRequest describeUserPoolDomainRequest, ProtocolMarshaller protocolMarshaller) {
if (describeUserPoolDomainRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.m... |
python | def grant_client(self, client_id, read=True, write=True):
"""
Grant the given client id all the scopes and authorities
needed to work with the timeseries service.
"""
scopes = ['openid']
authorities = ['uaa.resource']
if write:
for zone in self.servic... |
python | def storedata(filename=None):
"""Store the state of the current credolib workspace in a pickle file."""
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'wb') as f:
d = {}
for var in ['_headers', '_loaders', '_data1d', '_data2... |
python | def enrich_pull_requests(self, ocean_backend, enrich_backend, raw_issues_index="github_issues_raw"):
"""
The purpose of this Study is to add additional fields to the pull_requests only index.
Basically to calculate some of the metrics from Code Development under GMD metrics:
https://gith... |
python | def read_hdf5_dict(h5f, names=None, group=None, **kwargs):
"""Read a `TimeSeriesDict` from HDF5
"""
# find group from which to read
if group:
h5g = h5f[group]
else:
h5g = h5f
# find list of names to read
if names is None:
names = [key for key in h5g if _is_timeseries... |
python | def set_checkbox_value(w, value):
"""
Sets a checkbox's "checked" property + signal blocking + value tolerance
Args:
w: QCheckBox instance
value: something that can be converted to a bool
"""
save = w.blockSignals(True)
try:
w.setChecked(bool(value))
final... |
java | public Collection<Size> getSizes(String photoId, boolean sign) throws FlickrException {
SizeList<Size> sizes = new SizeList<Size>();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_GET_SIZES);
parameters.put("photo_id", photoId);
... |
python | def beagle(args):
"""
%prog beagle input.vcf 1
Use BEAGLE4.1 to impute vcf on chromosome 1.
"""
p = OptionParser(beagle.__doc__)
p.set_home("beagle")
p.set_ref()
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
vcffile, c... |
python | def _model_exists_step(self, model, should_exist):
"""
Test for the existence of a model matching the given data.
"""
model = get_model(model)
data = guess_types(self.hashes)
queryset = model.objects
try:
existence_check = _TEST_MODEL[model]
except KeyError:
existence_... |
python | def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
consoleHandle = ct.c_int()
if (sys.version_info[0] == 3) and (type(title) is str):
... |
java | public static Set<String> listLinks(OperationContext context, PathAddress overlayAddress) {
Resource overlayResource = context.readResourceFromRoot(overlayAddress);
if (overlayResource.hasChildren(DEPLOYMENT)) {
return overlayResource.getChildrenNames(DEPLOYMENT);
}
return Co... |
python | def mutable_hash(self, obj_hash=None):
"""Creates a hash with the (im)mutable data fields of the object
Example:
>>> my_obj = type("MyDerivedClass", (Hashable,), { "update_hash": lambda self, h: h.update("RAFCON") })()
>>> my_obj_hash = my_obj.mutable_hash()
>>> prin... |
python | def validate(self, folder):
"""Validate files and folders contained in this folder
It validates all of the files and folders contained in this
folder if some observers are interested in them.
"""
for observer in list(self.observers):
observer.validate(folder) |
java | public static final void stringToBytes( String s, byte[] data, int[] offset ) {
byte[] s_bytes = s.getBytes();
if (data != null) {
intToBytes(s_bytes.length, data, offset);
memcpy(data, offset[0], s_bytes, 0, s_bytes.length);
} else {
offset[0] += SIZE_INT;
... |
java | @Override
public boolean enlistOnePhase(UOWCoordinator coord, OnePhaseXAResource opXaRes) throws RollbackException, IllegalStateException, SystemException {
if (isClient) {
throw new SystemException();
}
return etm().enlistOnePhase(coord, opXaRes);
} |
python | def pages_siblings_menu(context, page, url='/'):
"""Get the parent page of the given page and render a nested list of its
child pages. Good for rendering a secondary menu.
:param page: the page where to start the menu from.
:param url: not used anymore.
"""
lang = context.get('lang', pages_sett... |
python | def load(hdf5_file_name, data, minPts, eps = None, quantile = 50, subsamples_matrix = None, samples_weights = None,
metric = 'minkowski', p = 2, verbose = True):
"""Determines the radius 'eps' for DBSCAN clustering of 'data' in an adaptive, data-dependent way.
Parameters
----------
hdf5_file_name : fi... |
java | @Override
public ApiType getByKey(String key) {
lock.lock();
try {
return this.items.get(key);
} finally {
lock.unlock();
}
} |
python | def Clift(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\
\frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.