language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def compose_from_srts(srts, search, searchtype):
"""Takes a list of subtitle (srt) filenames, search term and search type
and, returns a list of timestamps for composing a supercut.
"""
composition = []
foundSearchTerm = False
# Iterate over each subtitles file.
for srt in srts:
pr... |
python | def withdrawal(self, asset, amount, private_key):
"""
This function is a wrapper function around the create and execute withdrawal functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
... |
java | private boolean isOnTheSameSideOut(final long pX0, final long pY0, final long pX1, final long pY1) {
return (pX0 < mXMin && pX1 < mXMin)
|| (pX0 > mXMax && pX1 > mXMax)
|| (pY0 < mYMin && pY1 < mYMin)
|| (pY0 > mYMax && pY1 > mYMax);
} |
python | def get_group(
self,
index,
raster=None,
time_from_zero=False,
use_display_names=False,
reduce_memory_usage=False,
):
""" get channel group as pandas DataFrames. If there are multiple
occurences for the same channel name, then a counter will be used to... |
python | def randn_ktensor(shape, rank, norm=None, random_state=None):
"""
Generates a random N-way tensor with rank R, where the entries are
drawn from the standard normal distribution.
Parameters
----------
shape : tuple
shape of the tensor
rank : integer
rank of the tensor
n... |
java | public static Invoker getInvoker(Object proxyObject, String proxyType) {
try {
ExtensionClass<Proxy> ext = ExtensionLoaderFactory.getExtensionLoader(Proxy.class)
.getExtensionClass(proxyType);
if (ext == null) {
throw ExceptionUtils.buildRuntime("consumer.... |
java | private String getVariableName(Class clazz, int nodeId) {
String type = clazz.getSimpleName();
return Character.toLowerCase(type.charAt(0)) + type.substring(1) + nodeId;
} |
java | public void info(String correlationId, String message, Object... args) {
formatAndWrite(LogLevel.Info, correlationId, null, message, args);
} |
python | def do_bugin(self, args):
"""bugin [ <logger> ] - add a console logging handler to a logger"""
args = args.split()
if _debug: ConsoleCmd._debug("do_bugin %r", args)
# get the logger name and logger
if args:
loggerName = args[0]
if loggerName in logging.L... |
java | private Token name() throws ScanException {
text = new StringBuilder();
while (!in(c, "[ \t\r\n=<>!]")) {
text.append(c);
nextChar();
}
String val = text.toString().toLowerCase(Locale.getDefault());
switch (val) {
case "where":
... |
python | def has_separate_working_tree(self):
"""
:return: True if our git_dir is not at the root of our working_tree_dir, but a .git file with a
platform agnositic symbolic link. Our git_dir will be wherever the .git file points to
:note: bare repositories will always return False here
... |
java | protected void scrollForward() {
int selectedIndex = tabPane.getSelectedIndex();
if (++selectedIndex >= tabPane.getTabCount()) {
tabPane.setSelectedIndex(tabPane.getTabCount() - 1);
} else {
tabPane.setSelectedIndex(selectedIndex);
}
tabPane.repaint();
... |
python | def _get_video(edx_video_id):
"""
Get a Video instance, prefetching encoded video and course information.
Raises ValVideoNotFoundError if the video cannot be retrieved.
"""
try:
return Video.objects.prefetch_related("encoded_videos", "courses").get(edx_video_id=edx_video_id)
except Vide... |
java | public GitlabProject getProject(Serializable projectId) throws IOException {
String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId);
return retrieve().to(tailUrl, GitlabProject.class);
} |
java | protected void updatePicker(MotionEvent event, boolean isActive)
{
final MotionEvent newEvent = (event != null) ? event : null;
final ControllerPick controllerPick = new ControllerPick(mPicker, newEvent, isActive);
context.runOnGlThread(controllerPick);
} |
java | private void tfClassNameActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_tfClassNameActionPerformed
{//GEN-HEADEREND:event_tfClassNameActionPerformed
// Commit on ENTER
aTable.setClassName(tfClassName.getText());
} |
python | def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
negativeInf=None, dateFormat=None, timestampFo... |
python | def get_identities(self, item):
""" Return the identities from an item """
# All identities are in the post stream
# The first post is the question. Next replies
posts = item['data']['post_stream']['posts']
for post in posts:
user = self.get_sh_identity(post)
... |
python | def get(cls, data, **kwargs):
"""
Call this when you have a JSON result and just want to turn it into the
appropriate Result subclass. This is less performant than calling
PingResult(json_string) directly however, as the JSON has to be parsed
first to find the type.
"""
... |
python | def _make_marker_token(self, type_):
"""Make a token that has no content"""
tok = Token(type_,
'',
self.line,
self.line_num,
self.start,
self.start)
return tok |
java | @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException {
log.debug("region access strategy nonstrict-read-write entity afterUpdate() {} {}", getInternalRegion().getCacheNamespace(), key);
getInternalRegion().... |
java | public String encode(Cookie cookie) {
final String name = checkNotNull(cookie, "cookie").name();
final String value = cookie.value() != null ? cookie.value() : "";
validateCookie(name, value);
StringBuilder buf = stringBuilder();
if (cookie.wrap()) {
addQuoted(buf,... |
java | public long optLong(String key){
LazyNode token=getOptionalFieldToken(key);
if(token==null)return 0l;
if(token.type==LazyNode.VALUE_NULL)return 0l;
return token.getLongValue();
} |
java | private void initialize() {
frame = new GameFrame( "Wumpus World" );
frame.getContentPane().setBackground( Color.WHITE );
frame.setDefaultCloseOperation(wumpusWorldConfiguration.isExitOnClose() ? JFrame.EXIT_ON_CLOSE : JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new MigLayout("", "[540px:n... |
python | def _diff(self, dir1, dir2):
"""
Private function which only does directory diff
"""
self._dcmp = self._compare(dir1, dir2)
if self._dcmp.left_only:
self.log('Only in %s' % dir1)
for x in sorted(self._dcmp.left_only):
self.log('>> %s' % x... |
python | def parse_bowtie_stats(self, stats_file):
"""
Parses Bowtie2 stats file, returns series with values.
:param str stats_file: Bowtie2 output file with alignment statistics.
"""
import pandas as pd
stats = pd.Series(index=["readCount", "unpaired", "unaligned", "unique", "mu... |
java | protected boolean internalEquals(ValueData another)
{
if (another instanceof NameValueData)
{
return ((NameValueData)another).value.equals(value);
}
return false;
} |
python | def pressure(self):
"""
The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled
"""
self._read_temperature()
# Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
adc =... |
python | def set_draw_color(self, r,g=-1,b=-1):
"Set color for all stroking operations"
if((r==0 and g==0 and b==0) or g==-1):
self.draw_color=sprintf('%.3f G',r/255.0)
else:
self.draw_color=sprintf('%.3f %.3f %.3f RG',r/255.0,g/255.0,b/255.0)
if(self.page>0):
... |
python | def _construct_user_dictionary(global_options, tool_options):
"""Cause dictionary with valid and user words to be cached on disk."""
del global_options
spellchecker_cache_path = tool_options.get("spellcheck_cache", None)
valid_words_dictionary_helper.create(spellchecker_cache_path) |
java | public AStarSegmentReplacer<ST> setSegmentReplacer(AStarSegmentReplacer<ST> replacer) {
final AStarSegmentReplacer<ST> old = this.segmentReplacer;
this.segmentReplacer = replacer;
return old;
} |
python | def get(self, conn, key, default=None):
"""Gets a single value from the server.
:param key: ``bytes``, is the key for the item being fetched
:param default: default value if there is no value.
:return: ``bytes``, is the data for this specified key.
"""
values, _ = yield ... |
python | async def CreatePool(self, attrs, name, provider):
'''
attrs : typing.Mapping[str, typing.Any]
name : str
provider : str
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='Storage',
request='Create... |
java | public Tag get(Class handlerClass) throws JspException {
Tag handler = null;
synchronized( this ) {
if (current >= 0) {
handler = handlers[current--];
return handler;
}
}
// Out of sync block - there is no need for other threads to
... |
java | public void marshall(BatchScheduleActionDeleteRequest batchScheduleActionDeleteRequest, ProtocolMarshaller protocolMarshaller) {
if (batchScheduleActionDeleteRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMar... |
python | def parse_rsa_data(rsa_outfile, ignore_hets=True):
"""Process a NACCESS or freesasa RSA output file. Adapted from Biopython NACCESS modele.
Args:
rsa_outfile (str): Path to RSA output file
ignore_hets (bool): If HETATMs should be excluded from the final dictionary. This is extremely importa... |
python | def _mib_register(ident, value, the_mib, unresolved):
"""Internal function used to register an OID and its name in a MIBDict"""
if ident in the_mib or ident in unresolved:
return ident in the_mib
resval = []
not_resolved = 0
for v in value:
if _mib_re_integer.match(v):
re... |
java | public static Version from(int major, int minor, int maintenance, Qualifier qualifier) {
return from(major, minor, maintenance, qualifier, 0);
} |
java | @Override
protected void initEventHandlers() throws CoreException {
linkCommand(view().getOpenButton(), MouseEvent.MOUSE_CLICKED, OpenEventTrackerFileCommand.class, CHECK_MOUSE_SINGLE_CLICK);
linkWave(view().getUnloadButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_UNLOAD);
linkWave(view... |
python | def serialize_to_xml_str(obj_pyxb, pretty=True, strip_prolog=False, xslt_url=None):
"""Serialize PyXB object to pretty printed XML ``str`` for display.
Args:
obj_pyxb: PyXB object
PyXB object to serialize.
pretty: bool
False: Disable pretty print formatting. XML will not have line ... |
python | def get(self, name):
"""Retrieves a single LXC by name"""
lxc_meta_path = self._service.lxc_path(name,
constants.LXC_META_FILENAME)
meta = LXCMeta.load_from_file(lxc_meta_path)
lxc = self._loader.load(name, meta)
return lxc |
python | def negociate_content(default='json-ld'):
'''Perform a content negociation on the format given the Accept header'''
mimetype = request.accept_mimetypes.best_match(ACCEPTED_MIME_TYPES.keys())
return ACCEPTED_MIME_TYPES.get(mimetype, default) |
java | public static byte[] sha3(byte[] input, int start, int length) {
Keccak256 digest = new Keccak256();
digest.update(input, start, length);
return digest.digest();
} |
python | def get_apod(cls, date=None, hd=False):
"""
Returns Astronomy Picture of the Day
Args:
date: date instance (default = today)
hd: bool if high resolution should be included
Returns:
json
"""
instance = cls('planetary/apod')
fi... |
java | @Override
public Cursor loadInBackground() {
final SQLiteDatabase db = Sprinkles.getDatabase();
Cursor cursor = db.rawQuery(mSql, null);
if (cursor != null) {
// Ensure the cursor window is filled
cursor.getCount();
if (mDependencies != null) {
cursor.registerContentObserver(mObserver);
for (C... |
python | def exchange_token(self, code):
"""Given the value of the code parameter, request an access token."""
url = '%s%s/oauth2/token' % (self.scheme, self.host)
options = {
'grant_type': 'authorization_code',
'redirect_uri': self._redirect_uri(),
'client_id': self.o... |
java | public static final long parseLong(CharSequence cs)
{
if (CharSequences.startsWith(cs, "0b"))
{
return parseLong(cs, 2, 2, cs.length());
}
if (CharSequences.startsWith(cs, "0x"))
{
return parseLong(cs, 16, 2, cs.length());
}
r... |
python | def validate(self, path, schema, value, results):
"""
Validates a given value against this rule.
:param path: a dot notation path to the value.
:param schema: a schema this rule is called from
:param value: a value to be validated.
:param results: a list with validati... |
java | public int addUniqueElement(int element, int treap) {
int treap_;
if (treap == -1) {
if (m_defaultTreap == nullNode())
m_defaultTreap = createTreap(-1);
treap_ = m_defaultTreap;
} else {
treap_ = treap;
}
return addElement_(element, 1, treap_);
} |
python | def merge_parts(self, version_id=None, **kwargs):
"""Merge parts into object version."""
self.file.update_checksum(**kwargs)
with db.session.begin_nested():
obj = ObjectVersion.create(
self.bucket,
self.key,
_file_id=self.file_id,
... |
java | public Observable<IterationPerformance> getIterationPerformanceAsync(UUID projectId, UUID iterationId, GetIterationPerformanceOptionalParameter getIterationPerformanceOptionalParameter) {
return getIterationPerformanceWithServiceResponseAsync(projectId, iterationId, getIterationPerformanceOptionalParameter).map... |
python | def _glob(pattern, skip_dirs=False):
"""Glob pattern, expand directories, return all files that matched."""
# Implicit recursive iff no / in pattern and starts with *
if "/" not in pattern and pattern.startswith("*"):
files = glob.glob(f"**/{pattern}", recursive=True)
else:
files = glob.... |
java | public void clear() {
this.variables.clear();
this.methods.clear();
this.importedClasses.clear();
this.importedPackages.clear();
this.importedCommands.clear();
this.importedObjects.clear();
if (this.parent == null)
this.loadDefaultImports();
th... |
java | public void revertFeatures(@NonNull INDArray features, INDArray mask, int input) {
strategy.revert(features, mask, getFeatureStats(input));
} |
python | def fromxlsx(filename, sheet=None, range_string=None, row_offset=0,
column_offset=0, **kwargs):
"""
Extract a table from a sheet in an Excel .xlsx file.
N.B., the sheet name is case sensitive.
The `sheet` argument can be omitted, in which case the first sheet in
the workbook is used b... |
python | def update_agent(self, agent_id, **kwargs):
"""Updates an agent"""
url = 'agents/%s' % agent_id
agent = self._api._put(url, data=json.dumps(kwargs))
return Agent(**agent) |
java | @Override
public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) {
VisitorState state =
processMatchers(
parameterizedTypeMatchers,
tree,
ParameterizedTypeTreeMatcher::matchParameterizedType,
visitorState);
return super... |
python | def irange(self, minimum=None, maximum=None, inclusive=(True, True),
reverse=False):
"""
Create an iterator of values between `minimum` and `maximum`.
`inclusive` is a pair of booleans that indicates whether the minimum
and maximum ought to be included in the range, respe... |
python | def get_role_types(self):
"""
Get a list of role types in a service.
@return: A list of role types (strings)
"""
resp = self._get_resource_root().get(self._path() + '/roleTypes')
return resp[ApiList.LIST_KEY] |
python | def normalize_password(text, encoding='utf-8'):
'''Normalize a password
Percent-encodes unacceptable characters and ensures percent-encoding is
uppercase.
'''
path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET)
return uppercase_percent_encoding(path) |
java | protected String generateClass (String path)
{
// remove the trailing file extension
int ldidx = path.lastIndexOf(".");
if (ldidx != -1) {
path = path.substring(0, ldidx);
}
// convert slashes to dots
path = path.replace('/', '.');
// prepend the b... |
python | def get_tree(self, tgt_env):
'''
Return a tree object for the specified environment
'''
if not self.env_is_exposed(tgt_env):
return None
tgt_ref = self.ref(tgt_env)
if tgt_ref is None:
return None
for ref_type in self.ref_types:
... |
java | public static void assertRequiredDescriptionTriples(final Model model)
throws ConstraintViolationException {
assertContainsRequiredProperties(model, REQUIRED_PROPERTIES);
assertContainsRequiredTypes(model, BINARY_TYPES);
} |
python | def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_obje... |
python | def send_mass_contributor_emails(self):
"""Send report email to all relevant contributors."""
# If the report configuration is not active we only send to the debugging user.
for contributor in self.contributors:
if contributor.email not in EMAIL_SETTINGS.get("EXCLUDED", []):
... |
python | def should_log(self, request, response):
"""
Method that should return a value that evaluated to True if the request should be logged.
By default, check if the request method is in logging_methods.
"""
return self.logging_methods == '__all__' or request.method in self.logging_met... |
java | private QueryResultImpl combineResults(QueryResultImpl a, QueryResultImpl b, boolean distinct) {
QueryResultImpl result = new QueryResultImpl(a.getQuery());
for (QueryBindingImpl bindingA : a.getBindings()) {
for (QueryBindingImpl bindingB : b.getBindings()) {
QueryBindingIm... |
python | def _prepare_kappa(model):
"""Return a Kappa STD with the model loaded."""
import kappy
kappa = kappy.KappaStd()
model_str = export(model, 'kappa')
kappa.add_model_string(model_str)
kappa.project_parse()
return kappa |
java | @Override
public void run() {
try {
waitUntilServerIsInitialized();
recoveryLog.log("Start recovery.");
while (true) {
if (shutdown) {
break;
}
ConsumerJournalEntry cje = reader.readJournalEntry();
... |
java | static String getDefaultLocalizedString(String key, Object... args) {
return getLocalizedString(List.of(getDefaultBundle()), key, args);
} |
python | def hash(obj, hash_name='md5', coerce_mmap=False):
""" Quick calculation of a hash to identify uniquely Python objects
containing numpy arrays.
Parameters
-----------
hash_name: 'md5' or 'sha1'
Hashing algorithm used. sha1 is supposedly safer, but md5 is
faste... |
python | def translate_node_id(self, ni: PrefName, sctx: SchemaContext) -> QualName:
"""Translate node identifier to a qualified name.
Args:
ni: Node identifier (with optional prefix).
sctx: SchemaContext.
Raises:
ModuleNotRegistered: If `mid` is not registered in th... |
java | private ItemsToPush missingRevisionsToJsonDocs(
Map<String, DocumentRevisionTree> allTrees,
Map<String, CouchClient.MissingRevisions> revisions) throws AttachmentException {
ItemsToPush itemsToPush = new ItemsToPush();
for(Map.Entry<String, CouchClient.MissingRevisions> e : rev... |
python | def _get_prefixes(self):
"""Get the possible nick prefixes and associated modes for a client."""
prefixes = {
"@": "o",
"+": "v",
}
feature_prefixes = self.server.features.get('PREFIX')
if feature_prefixes:
modes = feature_prefixes[1:len(featur... |
java | public static <T> ComposableFuture<T> buildEager(final Producer<T> producer) {
return EagerComposableFuture.build(producer);
} |
java | protected DocPath pathString(PackageDoc pd, DocPath name) {
return pathToRoot.resolve(DocPath.forPackage(pd).resolve(name));
} |
python | def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise ... |
java | private static Optional<String> getFullName(FileDescriptorProto descriptor, List<Integer> path) {
String fullNameSoFar = descriptor.getPackage();
switch (path.get(0)) {
case FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER:
final DescriptorProto message = descriptor.getMessageTy... |
java | private boolean askBeforeExit(SwingFrame navigationFrameView) {
if (Configuration.isDevModeActive()) {
return true;
} else {
int answer = JOptionPane.showConfirmDialog(navigationFrameView, Resources.getString("Exit.confirm"), Resources.getString("Exit.confirm.title"), JOptionPane.YES_NO_OPTION);
return ans... |
python | def java(items):
"""Check for presence of external Java 1.7 for tools that require it.
"""
if any([_needs_java(d) for d in items]):
min_version = "1.7"
max_version = "1.8"
with setpath.orig_paths():
java = utils.which("java")
if not java:
retur... |
java | @SuppressWarnings({"unchecked", "unused"})
@Internal
protected final Object getProxiedBean(BeanContext beanContext) {
DefaultBeanContext defaultBeanContext = (DefaultBeanContext) beanContext;
Optional<String> qualifier = getAnnotationMetadata().getAnnotationNameByStereotype(javax.inject.Qualifie... |
python | def filter_by_IDs(self, ids, ID=None):
"""
Keep only Measurements with given IDs.
"""
fil = lambda x: x in ids
return self.filter_by_attr('ID', fil, ID) |
java | public MonetaryFormat positiveSign(char positiveSign) {
checkArgument(!Character.isDigit(positiveSign));
if (positiveSign == this.positiveSign)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
... |
java | public BooleanBuilder and(@Nullable Predicate right) {
if (right != null) {
if (predicate == null) {
predicate = right;
} else {
predicate = ExpressionUtils.and(predicate, right);
}
}
return this;
} |
python | def _to_event_data(obj):
'''
Convert the specified object into a form that can be serialised by msgpack as event data.
:param obj: The object to convert.
'''
if obj is None:
return None
if isinstance(obj, bool):
return obj
if isinstance(obj, int):
return obj
if ... |
java | public static URL getResourceURL(String resourcePath, Object source) throws ResourceNotFoundException {
// Try the current classloader
URL url = source.getClass().getResource(resourcePath);
// Weblogic 10 likes this one better..
if (null == url) {
ClassLoader cl = source.getClass().getClassLoader();
if ... |
java | public Markdown getMarkdown(String text) throws GitLabApiException {
if (!isApiVersion(ApiVersion.V4)) {
throw new GitLabApiException("Api version must be v4");
}
Form formData = new GitLabApiForm().withParam("text", text, true);
Response response = post(Response.Status.OK,... |
python | def s3_cache_timeout(self):
"""
The socket timeout in seconds for connections to Amazon S3 (an integer).
This value is injected into Boto's configuration to override the
default socket timeout used for connections to Amazon S3.
- Environment variable: ``$PIP_ACCEL_S3_TIMEOUT``
... |
java | public String getTable(FilterNode node) {
if (tableStrategy == null) return table;
String t = tableStrategy.getTable(table, node);
return t == null || t.isEmpty() ? table : t;
} |
python | def transaction(self, compare, success=None, failure=None):
"""
Perform a transaction.
Example usage:
.. code-block:: python
etcd.transaction(
compare=[
etcd.transactions.value('/doot/testing') == 'doot',
etcd.transac... |
java | public KeyArea setupKey(int iKeyArea)
{
KeyArea keyArea = null;
if (iKeyArea == 0)
{
keyArea = this.makeIndex(DBConstants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, DBConstants.ASCENDING);
}
if (iKeyArea == 1)
{
keyArea = this.makeInd... |
python | def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_client_exception():
response = self.client.get_account()
for container in response[1]:
yield container.p... |
java | private void handleGlobalArguments(Section section) {
for (String key : section.keySet()) {
switch (key) {
case OPTION_OFFLINE_MODE:
if (section.get(key).toLowerCase().equals("true")) {
this.offlineMode = true;
}
break;
case OPTION_QUIET:
if (section.get(key).toLowerCase().equals("true")... |
java | List<ImageManager> getNonFileImageManagers() {
List<ImageManager> nonFile = new ArrayList<ImageManager>();
for (ImageManager im : imageManagers) {
if (!(im instanceof FileImageManager)) {
nonFile.add(im);
}
}
return nonFile;
} |
java | private void processPropValidators() {
getMethodsWithAnnotation(component, PropValidator.class).forEach(method -> {
PropValidator propValidator = method.getAnnotation(PropValidator.class);
if (!TypeName.get(method.getReturnType()).equals(TypeName.BOOLEAN)) {
printError("Method "
+ m... |
python | def loadIcon(self, fileName, color=None):
""" Reads SVG from a file name and creates an QIcon from it.
Optionally replaces the color. Caches the created icons.
:param fileName: absolute path to an icon file.
If False/empty/None, None returned, which yields no icon.
... |
python | def search(self, **kwargs):
"""
Method to search environments based on extends search.
:param search: Dict containing QuerySets to find environments.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
... |
python | def read_run(filename, modelfn=None):
"""
Read chain from a hdf5 saved with `save_run`.
This function will also read the labels, data table, and metadata blobs
stored in the original sampler. If you want to use the result object with
`plot_fit` and setting the ``e_range`` parameter, you must provid... |
java | public static int findMaxIndex( int[] a ) {
int max = a[0];
int index = 0;
for( int i = 1; i< a.length; i++ ) {
int val = a[i];
if( val > max ) {
max = val;
index = i;
}
}
return index;
} |
java | public static <T> boolean all(Iterable<T> it, Predicate<? super T> p) {
if (it == null) {
return false;
}
for (T elem : it) {
if (!p.apply(elem)) {
return false;
}
}
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.