language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public float getAverageGetTime() {
long unsupportedCacheGetTotalMillis = TimeUnit.NANOSECONDS.toMillis(unsupportCacheGetTotalTime.longValue());
return TimeUnit.MILLISECONDS.toMicros(mapToSpecValidStat(
cache.getStats().getAverageReadTime() + unsupportedCacheGetTotalMillis));
} |
python | def from_file(cls, filename):
"""Construct a molecule object read from the given file.
The file format is inferred from the extensions. Currently supported
formats are: ``*.cml``, ``*.fchk``, ``*.pdb``, ``*.sdf``, ``*.xyz``
If a file contains more than one molecule, only the f... |
java | public boolean mkdirs(String src, PermissionStatus permissions
) throws IOException {
INode newNode = mkdirsInternal(src, permissions);
getEditLog().logSync(false);
if (newNode != null && auditLog.isInfoEnabled()) {
logAuditEvent(getCurrentUGI(),
Server.getRemoteIp(),
"mkdirs", src, ... |
python | def lie_between(self, target_time_range):
"""
判断是否落在目标时间区间内
:param target_time_range: 目标时间区间
:return: True or False
"""
if self.begin_dt >= target_time_range.begin_dt and self.end_dt <= \
target_time_range.end_dt:
return True
else:
... |
python | def getfieldidd(bch, fieldname):
"""get the idd dict for this field
Will return {} if the fieldname does not exist"""
# print(bch)
try:
fieldindex = bch.objls.index(fieldname)
except ValueError as e:
return {} # the fieldname does not exist
# so there is no idd
... |
java | public static filterpolicy_csvserver_binding[] get(nitro_service service, String name) throws Exception{
filterpolicy_csvserver_binding obj = new filterpolicy_csvserver_binding();
obj.set_name(name);
filterpolicy_csvserver_binding response[] = (filterpolicy_csvserver_binding[]) obj.get_resources(service);
retur... |
python | def add_workflow_definitions(sbi_config: dict):
"""Add any missing SBI workflow definitions as placeholders.
This is a utility function used in testing and adds mock / test workflow
definitions to the database for workflows defined in the specified
SBI config.
Args:
sbi_config (dict): SBI ... |
java | public <T extends ChatStore> ChatConfig store(StoreFactory<T> builder) {
this.storeFactory = builder.asChatStoreFactory();
return this;
} |
python | def getCentroid(attribute_variants, comparator):
"""
Takes in a list of attribute values for a field,
evaluates the centroid using the comparator,
& returns the centroid (i.e. the 'best' value for the field)
"""
n = len(attribute_variants)
distance_matrix = numpy.zeros([n, n])
# popul... |
python | def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.confdir, '..')
setup_script = os.path.join(root, 'setup.py')
fields = ['--name', '--version', '--url', '--author']
dist_info_... |
java | @Override
public void addPermissions(Collection<Permission> aPermssions)
{
if (aPermssions == null)
throw new IllegalArgumentException(
"aPermssions required in SecurityAccessControl");
// SecurityPermission element = null;
for (Iterator<Permission> i = aPermssions.iterator(); i.hasNext();)
{
... |
python | def load(self, _override=True, _allow_undeclared=False, **kwargs):
"""load configuration values from kwargs, see load_from_dict()."""
self.load_from_dict(
kwargs, _override=_override, _allow_undeclared=_allow_undeclared) |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.EXTERNAL_ALGORITHM_RG__DIRCTN:
return DIRCTN_EDEFAULT == null ? dirctn != null : !DIRCTN_EDEFAULT.equals(dirctn);
case AfplibPackage.EXTERNAL_ALGORITHM_RG__PADBDRY:
return PADBDRY_EDEFAULT == null ? padbdry != null... |
java | private WDataTable createTable() {
WDataTable table = new WDataTable();
table.addColumn(new WTableColumn("First name", WText.class));
table.addColumn(new WTableColumn("Last name", WText.class));
table.addColumn(new WTableColumn("DOB", WText.class));
table.setPaginationMode(PaginationMode.DYNAMIC);
table.set... |
python | def query(self, query, *parameters, **kwargs):
"""Returns a row list for the given query and parameters."""
cursor = self._cursor()
try:
self._execute(cursor, query, parameters or None, kwargs)
if cursor.description:
column_names = [column.name for column ... |
java | public void scheduleExpirationTask() {
if (nodeEngine.getLocalMember().isLiteMember() || scheduled.get()
|| !scheduled.compareAndSet(false, true)) {
return;
}
scheduledExpirationTask =
globalTaskScheduler.scheduleWithRepetition(task, taskPeriodSeconds... |
java | private boolean tryIncrement(AtomicInteger counter, int max) {
// Repeatedly attempt to increment the given AtomicInteger until we
// explicitly succeed or explicitly fail
while (true) {
// Get current value
int count = counter.get();
// Bail out if the max... |
python | def getOrderVectors(self):
"""
Returns a list of lists, one for each preference, of candidates ordered from most preferred
to least. Note that ties are not indicated in the returned lists. Also returns a list of
the number of times each preference is given.
"""
orderVect... |
java | public static void setProperties( Properties prp ) {
Config.prp = new Properties( prp );
try {
Config.prp.putAll( System.getProperties() );
} catch( SecurityException se ) {
if( log.level > 1 )
log.println( "SecurityException: jcifs.smb1 will ignore System... |
java | public static boolean isSensitive(String key) {
Preconditions.checkNotNull(key, "key is null");
final String keyInLower = key.toLowerCase();
for (String hideKey : SENSITIVE_KEYS) {
if (keyInLower.length() >= hideKey.length()
&& keyInLower.contains(hideKey)) {
return true;
}
}
return false;
} |
java | public Object injectAndPostConstruct(Class<?> Klass) throws InjectionProviderException
{
Object instance = null;
ManagedObject mo = (ManagedObject) ((WASInjectionProvider) getInjectionProvider()).inject(Klass, true, _externalContext);
instance = mo.getObject();
if (instance... |
python | def set_dynamic_time_fn(self_,time_fn,sublistattr=None):
"""
Set time_fn for all Dynamic Parameters of this class or
instance object that are currently being dynamically
generated.
Additionally, sets _Dynamic_time_fn=time_fn on this class or
instance object, so that any ... |
python | def isOpen(self):
"""Returns whether all analyses from this Analysis Request are open
(their status is either "assigned" or "unassigned")
"""
for analysis in self.getAnalyses():
if not api.get_object(analysis).isOpen():
return False
return True |
python | def user_record(uid, type=0):
"""获取用户的播放列表,必须登录
:param uid: 用户的ID,可通过登录或者其他接口获取
:param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData
"""
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_RECORD'
r.data = {'type': type, 'uid': uid, "csrf_token": ""}
r.send()... |
python | def fill_auth_list_from_groups(self, auth_provider, user_groups, auth_list):
'''
Returns a list of authorisation matchers that a user is eligible for.
This list is a combination of the provided personal matchers plus the
matchers of any group the user is in.
'''
group_nam... |
python | def ParseFileObject(self, parser_mediator, file_object):
"""Parses a Windows Restore Point (rp.log) log file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like ob... |
java | public void println(String text) {
try {
if(autoIndent) printIndent();
out.write(text);
println();
} catch(IOException ioe) {
throw new GroovyRuntimeException(ioe);
}
} |
java | public static long getLongParameter(final ServletRequest pReq, final String pName, final long pDefault) {
String str = pReq.getParameter(pName);
try {
return str != null ? Long.parseLong(str) : pDefault;
}
catch (NumberFormatException nfe) {
return pDefaul... |
python | def get_torrent(self, torrent_id):
"""Gets the `.torrent` data for the given `torrent_id`.
:param torrent_id: the ID of the torrent to download
:raises TorrentNotFoundError: if the torrent does not exist
:returns: :class:`Torrent` of the associated torrent
"""
params = {... |
python | def add_user(name, password=None, runas=None):
'''
Add a rabbitMQ user via rabbitmqctl user_add <user> <password>
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.add_user rabbit_user password
'''
clear_pw = False
if password is None:
# Generate a random, temporary pas... |
java | @RequestMapping(path="/{orderId}/status", method = RequestMethod.PUT)
public ResponseEntity<Order> updateStatus(@PathVariable("orderId") Long orderId, @RequestParam("status") OrderStatus status){
Order order = orderService.updateStatus(orderId, status);
if(order != null){
return new Resp... |
java | private void mergeReleasedEntries(Segment segment, OffsetPredicate predicate, Segment compactSegment) {
for (long i = segment.firstIndex(); i <= segment.lastIndex(); i++) {
long offset = segment.offset(i);
if (offset != -1 && !predicate.test(offset)) {
compactSegment.release(i);
}
}
... |
java | private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) {
final int startLeft = mCapturedView.getLeft();
final int startTop = mCapturedView.getTop();
final int dx = finalLeft - startLeft;
final int dy = finalTop - startTop;
if (dx == 0 && dy ==... |
python | def timezone_from_str(tz_str):
"""
Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo)
"""
m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
if m:
# in format 'UTC±[hh]:[mm]'
... |
java | public JSONObject batchSynonyms(List<JSONObject> objects, boolean forwardToReplicas, boolean replaceExistingSynonyms) throws AlgoliaException {
return this.batchSynonyms(objects, forwardToReplicas, replaceExistingSynonyms, RequestOptions.empty);
} |
java | private boolean isClientChannelClosed(Throwable cause) {
if (cause instanceof ClosedChannelException ||
cause instanceof Errors.NativeIoException) {
LOG.error("ZuulFilterChainHandler::isClientChannelClosed - IO Exception");
return true;
}
return false;
... |
java | final void clearTransportVersion() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "clearTransportVersion");
getHdr2().setChoiceField(JsHdr2Access.TRANSPORTVERSION, JsHdr2Access.IS_TRANSPORTVERSION_EMPTY);
if (TraceComponent.isAnyTracingEnable... |
python | def _remove_layer_clicked(self):
"""Remove layer clicked."""
layer = self.list_layers_in_map_report.selectedItems()[0]
origin = layer.data(LAYER_ORIGIN_ROLE)
if origin == FROM_ANALYSIS['key']:
key = layer.data(LAYER_PURPOSE_KEY_OR_ID_ROLE)
parent = layer.data(LAYE... |
python | def _getConfiguration(self):
"""
Load application configuration files.
:return: <dict>
"""
configDirectoryPath = os.path.join("application", "config")
config = Config(configDirectoryPath)
configData = config.getData()
# setting application parameters
... |
java | public static PlotCanvas plot(double[] x, double[] y, double[][] z) {
double[] lowerBound = {Math.min(x), Math.min(y)};
double[] upperBound = {Math.max(x), Math.max(y)};
PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false);
canvas.add(new Heatmap(x, y, z));
canvas.g... |
python | def read_lines(self, max_lines=None):
"""Reads the content of this object as text, and return a list of lines up to some max.
Args:
max_lines: max number of lines to return. If None, return all lines.
Returns:
The text content of the object as a list of lines.
Raises:
Exception if the... |
java | private static List<BeanMappingObject> parseMappingObject(InputStream in) {
Document doc = XmlHelper.createDocument(
in,
Thread.currentThread().getContextClassLoader().getResourceAsStream(
... |
java | private void init(final Calendar definingCalendar) {
patterns = new ArrayList<>();
final StrategyParser fm = new StrategyParser(definingCalendar);
for (;;) {
final StrategyAndWidth field = fm.getNextStrategy();
if (field == null) {
break;
}
patterns.add(field);
}
} |
python | def build(outname, wcsname, refimage, undistort=False,
applycoeffs=False, coeffsfile=None, **wcspars):
""" Core functionality to create a WCS instance from a reference image WCS,
user supplied parameters or user adjusted reference WCS.
The distortion information can either be read in as pa... |
java | @Override
public Object getValue(final Object _currentObject)
throws EFapsException
{
final Type tempType;
if (this.type.getMainTable().getSqlColType() == null) {
tempType = this.type;
} else if (_currentObject != null) {
// check is necessary because Orac... |
java | @Override
public void validate(ValidationHelper helper, Context context, String key, Info t) {
if (t != null) {
ValidatorUtils.validateRequiredField(t.getVersion(), context, "version").ifPresent(helper::addValidationEvent);
ValidatorUtils.validateRequiredField(t.getTitle(), context, ... |
python | def link(self):
"""link the program, making it the active shader.
.. note:: Shader.bind() is preferred here, because link() Requires the Shader to be compiled already.
"""
gl.glLinkProgram(self.id)
# Check if linking was successful. If not, print the log.
link_status =... |
java | public ImportRestApiRequest withParameters(java.util.Map<String, String> parameters) {
setParameters(parameters);
return this;
} |
java | public static String getCurrentRemoteConnectionLink(){
if(!APILookupUtility.isLocal()) try{
return URLEncoder.encode(APILookupUtility.getCurrentRemoteInstance().getHost(), "UTF-8") +
COLON_URL_ENCODED +
APILookupUtility.getCurrentRemoteInstan... |
python | def tx_tmpdir(data=None, base_dir=None, remove=True):
"""Context manager to create and remove a transactional temporary directory.
Handles creating a transactional directory for running commands in. Will
use either the current directory or /tmp/bcbiotx.
Creates an intermediary location and time specif... |
java | @Override
public HystrixDynamicProperty<Integer> getInteger(final String name, final Integer fallback) {
return new HystrixDynamicProperty<Integer>() {
@Override
public String getName() {
return name;
}
@Override
... |
python | def document_members(self, all_members=False):
# type: (bool) -> None
"""Generate reST for member documentation.
If *all_members* is True, do all members, else those given by
*self.options.members*.
"""
sourcename = self.get_sourcename()
want_all = all_members o... |
java | public static void setSreSpecificData(SRESpecificDataContainer container, Object data) {
assert container != null;
container.$setSreSpecificData(data);
} |
java | private void checkForThreadErrors() throws IOException {
if(error == true && childException != null) {
error = false;
IOException temp = childException;
childException = null;
throw temp;
}
} |
python | def make_parser(parser_creator=None, **kwargs):
"""Returns a base argument parser for the ray.tune tool.
Args:
parser_creator: A constructor for the parser class.
kwargs: Non-positional args to be passed into the
parser class constructor.
"""
if parser_creator:
pars... |
python | def instantiate_components(self, callback=None):
"""
Instantiates the Components.
Usage::
>>> manager = Manager((tests_manager,))
>>> manager.register_components()
True
>>> manager.instantiate_components()
True
>>> manager... |
python | def cache_for(**timedelta_kw):
"""
Set Cache-Control headers and Expires-header.
Expects a timedelta instance.
"""
max_age_timedelta = timedelta(**timedelta_kw)
def decorate_func(func):
@wraps(func)
def decorate_func_call(*a, **kw):
callback = SetCacheControlHeaders... |
python | def _next_shape_id(self):
"""Return unique shape id suitable for use with a new shape element.
The returned id is the next available positive integer drawing object
id in shape tree, starting from 1 and making use of any gaps in
numbering. In practice, the minimum id is 2 because the sp... |
java | protected void safeExecuteChangeListener(CmsEntity entity, I_CmsEntityChangeListener listener) {
try {
listener.onEntityChange(entity);
} catch (Exception e) {
String stack = CmsClientStringUtil.getStackTrace(e, "<br />");
CmsDebugLog.getInstance().printLine("<... |
java | public <A> BindStep<ConfigFactory, A> bind(final Class<A> type) {
checkNotNull(type);
return new BindStep<ConfigFactory, A>() {
@Override
public ConfigFactory toInstance(A instance) {
return withBindings(
bindings.set(type, checkNotNull(ins... |
python | def relookup(self, pattern):
""" Dictionary lookup with a regular expression. Return pairs whose key
matches pattern.
"""
key = re.compile(pattern)
return filter(lambda x : key.match(x[0]), self.data.items()) |
python | def qteToBeKilled(self):
"""
Remove all selections and install the original lexer.
"""
self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig)
self.qteWidget.qteSetLexer(self.originalLexer) |
python | def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt |
python | def ask(self, choices, **options):
"""
Sends a prompt to the user and optionally waits for a response.
Arguments: "choices" is a Choices object
See https://www.tropo.com/docs/webapi/ask
"""
# # **Sun May 15 21:21:29 2011** -- egilchri
# Settng the voice in this method ca... |
python | def state_fidelity(state0: State, state1: State) -> bk.BKTensor:
"""Return the quantum fidelity between pure states."""
assert state0.qubits == state1.qubits # FIXME
tensor = bk.absolute(bk.inner(state0.tensor, state1.tensor))**bk.fcast(2)
return tensor |
python | def add_mongo_config(app, simple_connection_string,
mongo_uri, collection_name):
"""
Configure the application to use MongoDB.
:param app: Flask application
:param simple_connection_string:
Expects host:port:database_name or database_name
Mutally_exc... |
python | def iterate(self, params, repetition, iteration):
"""
Called once for each training iteration (== epoch here).
"""
print("\nStarting iteration",iteration)
print("Learning rate:", self.learningRate if self.lr_scheduler is None
else self.lr_scheduler.get_l... |
python | def generic_document_type_formatter(view, context, model, name):
"""Return AdminLog.document field wrapped in URL to its list view."""
_document_model = model.get('document').document_type
url = _document_model.get_admin_list_url()
return Markup('<a href="%s">%s</a>' % (url, _document_model.__name__)) |
python | def _export(self, path, variables_saver):
"""Internal.
Args:
path: string where to export the module to.
variables_saver: an unary-function that writes the module variables
checkpoint on the given path.
"""
self._saved_model_handler.export(path, variables_saver=variables_saver)
... |
python | def set_led(self, state):
"""Set the LED state to state (True or False)"""
if self.connected:
reports = self.device.find_output_reports()
for report in reports:
if self.led_usage in report:
report[self.led_usage] = state
... |
python | def _get_peer_connection(self, blacklist=None):
"""Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.
"... |
java | @BetaApi
public final Operation deleteAddress(ProjectRegionAddressName address) {
DeleteAddressHttpRequest request =
DeleteAddressHttpRequest.newBuilder()
.setAddress(address == null ? null : address.toString())
.build();
return deleteAddress(request);
} |
python | def set_parameter(self, name, value):
"""
Set a parameter value by name
Args:
name: The name of the parameter
value (float): The new value for the parameter
"""
i = self.get_parameter_names(include_frozen=True).index(name)
v = self.get_parameter_... |
python | def set_volume(self, volume):
"""Set volume."""
self._player.set_property(PROP_VOLUME, volume)
self._manager[ATTR_VOLUME] = volume
_LOGGER.info('volume set to %.2f', volume) |
python | def find_field(ctx, search, by_type, obj):
"""Find fields in registered data models."""
# TODO: Fix this to work recursively on all possible subschemes
if search is not None:
search = search
else:
search = _ask("Enter search term")
database = ctx.obj['db']
def find(search_sche... |
python | def update(self):
"""Updates the currently running animation.
This method should be called in every frame where you want an animation to run.
Its job is to figure out if it is time to move onto the next image in the animation.
"""
returnValue = False # typical return va... |
python | def active():
'''
Return current active profile
CLI Example:
.. code-block:: bash
salt '*' tuned.active
'''
# turn off all profiles
result = __salt__['cmd.run']('tuned-adm active')
pattern = re.compile(r'''(?P<stmt>Current active profile:) (?P<profile>\w+.*)''')
match = r... |
python | def replace_namespaced_service(self, name, namespace, body, **kwargs):
"""
replace the specified Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service(name, nam... |
java | public final void evaluate() throws IOException {
final SequenceLabelerEvaluator evaluator = new SequenceLabelerEvaluator(this.corpusFormat,
this.sequenceLabeler);
evaluator.evaluate(this.testSamples);
System.out.println(evaluator.getFMeasure());
} |
java | public void asyncPut(final byte[] data, final String key, final String token, StringMap params,
String mime, boolean checkCrc, UpCompletionHandler handler) throws IOException {
checkArgs(key, data, null, token);
if (mime == null) {
mime = Client.DefaultMime;
... |
python | def process_sums(self):
"""
Process cardinality sums participating in a new core.
Whenever necessary, some of the sum assumptions are
removed or split (depending on the value of
``self.minw``). Deleted sums are marked as garbage and are
dealt with in :... |
python | def readlines(self, encoding=None):
"""Reads from the file and returns result as a list of lines."""
try:
encoding = encoding or ENCODING
with codecs.open(self.path, encoding=None) as fi:
return fi.readlines()
except:
return [] |
java | public String asBase64(BaseEncoding.Dialect dialect, BaseEncoding.Padding padding) throws IOException {
String standardBase64 = DatatypeConverter.printBase64Binary(asByteArray(false));
if (dialect == BaseEncoding.Dialect.STANDARD && padding == BaseEncoding.Padding.STANDARD) {
return standard... |
python | def from_rgb(r, g=None, b=None):
"""
Return the nearest xterm 256 color code from rgb input.
"""
c = r if isinstance(r, list) else [r, g, b]
best = {}
for index, item in enumerate(colors):
d = __distance(item, c)
if(not best or d <= best['distance']):
best = {'distan... |
java | private void stop(Attributes attributes) throws SVGParseException
{
debug("<stop>");
if (currentElement == null)
throw new SVGParseException("Invalid document. Root element must be <svg>");
if (!(currentElement instanceof SVG.GradientElement))
throw new SVGParseException(... |
java | public static void runExample(
AdManagerServices adManagerServices, AdManagerSession session, long userId)
throws RemoteException {
// Get the UserService.
UserServiceInterface userService = adManagerServices.get(session, UserServiceInterface.class);
// Create a statement to only select a singl... |
python | def save_figure(self, event=None, transparent=False, dpi=600):
""" save figure image to file"""
file_choices = "PNG (*.png)|*.png|SVG (*.svg)|*.svg|PDF (*.pdf)|*.pdf"
try:
ofile = self.conf.title.strip()
except:
ofile = 'Image'
if len(ofile) > 64:
... |
java | public CellConstraints rchw(int row, int col, int rowSpan, int colSpan,
String encodedAlignments) {
CellConstraints result = rchw(row, col, rowSpan, colSpan);
result.setAlignments(encodedAlignments, false);
return result;
} |
python | def reduce_filename(f):
r'''
Expects something like /tmp/tmpAjry4Gdsbench/test.weights.e5.XXX.YYY.pb
Where XXX is a variation on the model size for example
And where YYY is a const related to the training dataset
'''
f = os.path.basename(f).split('.')
return keep_only_digits(f[-3]) |
python | def _check_umi_type(bam_file):
"""Determine the type of UMI from BAM tags: standard or paired.
"""
with pysam.Samfile(bam_file, "rb") as in_bam:
for read in in_bam:
cur_umi = None
for tag in ["RX", "XC"]:
try:
cur_umi = read.get_tag(tag)
... |
python | async def _handle_gzip_packed(self, message):
"""
Unpacks the data from a gzipped object and processes it:
gzip_packed#3072cfa1 packed_data:bytes = Object;
"""
self._log.debug('Handling gzipped data')
with BinaryReader(message.obj.data) as reader:
message... |
python | def setReadOnly( self, state ):
"""
Sets the read only for this widget to the inputed state.
Differs per type, not all types support read only.
:param text | <str>
"""
if ( self._editor and hasattr(self._editor, 'setReadOnly') ):
self._editor.s... |
python | def hasNext(self):
"""
Returns True if the cursor has a next position, False if not
:return:
"""
cursor_pos = self.cursorpos + 1
try:
self.cursordat[cursor_pos]
return True
except IndexError:
return False |
python | def create(input_dataset, target, feature=None, validation_set='auto',
warm_start='auto', batch_size=256,
max_iterations=100, verbose=True):
"""
Create a :class:`DrawingClassifier` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``... |
java | @JsonSetter("genre_ids")
@Override
public void setGenreIds(List<Integer> ids) {
this.genres = new ArrayList<>();
for (Integer id : ids) {
Genre g = new Genre();
g.setId(id);
genres.add(g);
}
} |
python | def get_user(prompt=None):
"""
Prompts the user for his login name, defaulting to the USER environment
variable. Returns a string containing the username.
May throw an exception if EOF is given by the user.
:type prompt: str|None
:param prompt: The user prompt or the default one if None.
:... |
java | public void deleteClassPipeProperties(String className,
String pipeName, List<String> propertyNames) throws DevFailed {
databaseDAO.deleteClassPipeProperties(this, className, pipeName, propertyNames);
} |
python | def where(cond, x, y):
"""Return elements from `x` or `y` depending on `cond`.
Performs xarray-like broadcasting across input arguments.
Parameters
----------
cond : scalar, array, Variable, DataArray or Dataset with boolean dtype
When True, return values from `x`, otherwise returns values... |
python | def _create_key(lang, instance):
"""Crea la clave única de la caché"""
model_name = instance.__class__.__name__
return "{0}__{1}_{2}".format(lang,model_name,instance.id) |
java | public void match(ByteBuffer data, int size, IMtrieHandler func, XPub pub)
{
assert (data != null);
assert (func != null);
assert (pub != null);
Mtrie current = this;
int idx = 0;
while (true) {
// Signal the pipes attached to this node.
if (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.