language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String mangleName(String name)
{
boolean toLower = CauchoUtil.isCaseInsensitive();
CharBuffer cb = new CharBuffer();
cb.append("_");
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == '/' || ch == CauchoUtil.getPathSeparatorChar()) {
if (... |
python | def printableVal(val, type_bit=True, justlength=False):
"""
Very old way of doing pretty printing. Need to update and refactor.
DEPRICATE
"""
from utool import util_dev
# Move to util_dev
# NUMPY ARRAY
import numpy as np
if type(val) is np.ndarray:
info = npArrInfo(val)
... |
python | def gen_columns_from_children(root):
"""
Generates columns that are being used in child elements of the delete query
this will be used to determine tables for the using clause.
:param root: the delete query
:return: a generator of columns
"""
if isinstance(root, (Delete, BinaryExpression, Bo... |
python | def compare_version(version1, version2):
"""
Compares two versions.
"""
def normalize(v):
return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")]
return (normalize(version1) > normalize(version2))-(normalize(version1) < normalize(version2)) |
python | def fragmentate(self, give_only_index=False,
use_lookup=None):
"""Get the indices of non bonded parts in the molecule.
Args:
give_only_index (bool): If ``True`` a set of indices is returned.
Otherwise a new Cartesian instance.
use_lookup (bool... |
java | protected static ForkJoinTask<?> pollTask() {
ForkJoinWorkerThread wt =
(ForkJoinWorkerThread)Thread.currentThread();
return wt.pool.nextTaskFor(wt.workQueue);
} |
python | def kill_tasks(self, app_id, scale=False, wipe=False,
host=None, batch_size=0, batch_delay=0):
"""Kill all tasks belonging to app.
:param str app_id: application ID
:param bool scale: if true, scale down the app by the number of tasks killed
:param str host: if provid... |
java | @Override
public ProgramGene<A> newInstance(
final Op<A> op,
final int childOffset,
final int childCount
) {
if (op.arity() != childCount) {
throw new IllegalArgumentException(format(
"Operation arity and child count are different: %d, != %d",
op.arity(), childCount
));
}
return new Program... |
java | public ProxyDataSourceBuilder logQueryBySlf4j(SLF4JLogLevel logLevel, String slf4jLoggerName) {
this.createSlf4jQueryListener = true;
this.slf4jLogLevel = logLevel;
this.slf4jLoggerName = slf4jLoggerName;
return this;
} |
java | public XYSeries getSeries( String seriesName ) {
XYSeries series = new XYSeries(seriesName);
dataset.addSeries(series);
return series;
} |
python | def get_archive_name(self):
"""
This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like th... |
python | def _readable(self, watcher, events):
"""Called by the pyev watcher (self.read_watcher) whenever the socket
is readable.
Calls recv and checks for errors. If there are no errors then read_cb
is called with the newly arrived bytes. Otherwise closes the socket
and calls close_cb w... |
python | def fit(self, X, y, **kwargs):
"""
Fits the learning curve with the wrapped model to the specified data.
Draws training and test score curves and saves the scores to the
estimator.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Tr... |
java | @Override
public X509Certificate[] getCertificateChain(String s) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "getCertificateChain: " + s);
X509Certificate[] rc = getX509KeyManager().getCertificateChain(s);
if (TraceComponent.isAnyTracingEnabl... |
python | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
(__active_provider_name__ or
... |
python | def shapes(self):
"""|GroupShapes| object for this group.
The |GroupShapes| object provides access to the group's member shapes
and provides methods for adding new ones.
"""
from pptx.shapes.shapetree import GroupShapes
return GroupShapes(self._element, self) |
python | def auto_newline(buffer):
r"""
Insert \n at the cursor position. Also add necessary padding.
"""
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
# When we are in the middle of a line. Always insert a newline.
insert_text('\n')
else:
# Go to... |
python | def release(self, *args, **kwargs):
"""
Really release the lock only if it's not a sub-lock. Then save the
sub-lock status and mark the model as unlocked.
"""
if not self.field.lockable:
return
if self.sub_lock_mode:
return
super(FieldLock,... |
python | def new(self, size, fill):
"""Return a new Image instance filled with a color."""
return Image(PIL.Image.new("RGB", size, fill)) |
java | public void marshall(ListStreamProcessorsRequest listStreamProcessorsRequest, ProtocolMarshaller protocolMarshaller) {
if (listStreamProcessorsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshal... |
python | def path(cls, name, type_=Type.String, description=None, default=None,
minimum=None, maximum=None, enum=None, **options):
"""
Define a path parameter
"""
if minimum is not None and maximum is not None and minimum > maximum:
raise ValueError("Minimum must be less ... |
python | def check_mismatches(read, pair, mismatches, mm_option, req_map):
"""
- check to see if the read maps with <= threshold number of mismatches
- mm_option = 'one' or 'both' depending on whether or not one or both reads
in a pair need to pass the mismatch threshold
- pair can be False if read does n... |
java | public RestoreDBInstanceFromS3Request withEnableCloudwatchLogsExports(String... enableCloudwatchLogsExports) {
if (this.enableCloudwatchLogsExports == null) {
setEnableCloudwatchLogsExports(new com.amazonaws.internal.SdkInternalList<String>(enableCloudwatchLogsExports.length));
}
for... |
java | public static Map<Class<?>, Boolean> getHandlerTypes(Class<? extends MessageHandler> clazz) {
Map<Class<?>, Boolean> types = new IdentityHashMap<>(2);
for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) {
exampleGenericInterfaces(types, c, clazz);
}
if (types.i... |
java | @Override
public Object get(final Attribute _attribute,
final Object _object)
throws EFapsException
{
final Object ret;
if (_attribute.getAttributeType().getDbAttrType() instanceof RateType) {
ret = getRate(_attribute, _object);
} else if (_attri... |
java | private void synchronizeBucketsWithHDD() {
int synchronizedBuckets = 0;
// run over all buckets
for (int i = 0; i < numberOfBuckets; i++) {
Bucket<Data> oldBucket = bucketContainer.getBucket(i);
// if the bucket is empty, then do nothing
if (oldBucket.element... |
java | @Override
public DescriptorValue calculate(IAtomContainer ac) {
ac = clone(ac); // don't mod original
int rotatableBondsCount = 0;
int degree0;
int degree1;
IRingSet ringSet;
try {
ringSet = new SpanningTree(ac).getBasicRings();
} catch (NoSuchAtom... |
java | @Override
public void notifySynchronization() {
try {
synchronisationObservable.notifyObservers(System.currentTimeMillis());
} catch (CouldNotPerformException ex) {
ExceptionPrinter.printHistory(new CouldNotPerformException("Could not notify observer about synchronization", e... |
java | public static void swap(int[] intArray, int index1, int index2) {
TrivialSwap.swap(intArray, index1, intArray, index2);
} |
python | def base(ctx, verbose, config):
"""Puzzle: manage DNA variant resources."""
# configure root logger to print to STDERR
loglevel = LEVELS.get(min(verbose, 3))
configure_stream(level=loglevel)
ctx.obj = {}
if config and os.path.exists(config):
ctx.obj = yaml.load(open(config, 'r')) or {}
... |
java | private Object readNonPrimitiveContent(boolean unshared)
throws ClassNotFoundException, IOException {
checkReadPrimitiveTypes();
int remaining = primitiveData.available();
if (remaining > 0) {
OptionalDataException e = new OptionalDataException(remaining);
e.l... |
java | public static <T> Collection<T> sortByJavaBeanProperty(String aProperyName,
Collection<T> aCollection)
{
return sortByJavaBeanProperty(aProperyName, aCollection, false);
} |
java | public boolean isExported(String pn, String target) {
return isExported(pn)
|| exports.containsKey(pn) && exports.get(pn).contains(target);
} |
python | def builtin_lookup(name):
"""lookup a name into the builtin module
return the list of matching statements and the astroid for the builtin
module
"""
builtin_astroid = MANAGER.ast_from_module(builtins)
if name == "__dict__":
return builtin_astroid, ()
try:
stmts = builtin_astr... |
python | def get_division(self, row):
"""
Gets the Division object for the given row of election results.
"""
# back out of Alaska county
if (
row["level"] == geography.DivisionLevel.COUNTY
and row["statename"] == "Alaska"
):
print("Do not tak... |
python | def convert_time(obj):
"""Returns a TIME column as a time object:
>>> time_or_None('15:06:17')
datetime.time(15, 6, 17)
Illegal values are returned as None:
>>> time_or_None('-25:06:17') is None
True
>>> time_or_None('random crap') is None
True
Note that MySQL always ... |
python | def parse_option(self, option, block_name, *values):
""" Parse domain values for option.
"""
_extra_subs = ('www', 'm', 'mobile')
if len(values) == 0: # expect some values here..
raise ValueError
for value in values:
value = value.lower()
... |
python | def top(self, num, key=None):
"""
Get the top N elements from an RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
.. note:: It returns the list sorted in descending order.
... |
python | def split(self, box_size):
"""
Splits the box object into many boxes each of given size.
Assumption: the entire box can be split into rows and columns with the given size.
:param box_size: (width, height) of the new tiny boxes
:return: Array of tiny boxes
"""
w, ... |
python | def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][k1] = v
... |
java | public <T extends Watermark> T getLowWatermark(Class<T> watermarkClass) {
return getLowWatermark(watermarkClass, GSON);
} |
python | def get_replacement_method(method_to_patch, side_effect=UNDEFINED, rvalue=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, context=UNDEFINED, subsequent_rvalue=UNDEFINED):
"""
Returns the method to be applied in place of an original method. This method either executes a side effect, returns an rvalue, or implem... |
python | def run_compare_gold_standard(in_prefix, in_type, out_prefix, base_dir,
options):
"""Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output p... |
java | @Override
public PCapPacket frame(final Packet parent, final Buffer buffer) throws IOException {
// note that for the PcapPacket the parent will always be null
// so we are simply ignoring it.
Buffer record = null;
try {
record = buffer.readBytes(16);
} catch (fi... |
java | protected void writeIterator(Iterator<?> iterator, CharBuf buffer) {
if (!iterator.hasNext()) {
buffer.addChars(EMPTY_LIST_CHARS);
return;
}
buffer.addChar(OPEN_BRACKET);
while (iterator.hasNext()) {
Object it = iterator.next();
if (!isExcl... |
python | def _finalize_ticks(self, axis, element, xticks, yticks, zticks):
"""
Apply ticks with appropriate offsets.
"""
yalignments = None
if xticks is not None:
ticks, labels, yalignments = zip(*sorted(xticks, key=lambda x: x[0]))
xticks = (list(ticks), list(labe... |
java | private int getChunkSize()
throws IOException
{
if (_chunkSize<0)
return -1;
_trailer=null;
_chunkSize=-1;
// Get next non blank line
org.browsermob.proxy.jetty.util.LineInput.LineBuffer line_buffer
=_in.readLineBuffer();
... |
java | public TableReader read() throws IOException
{
int tableHeader = m_stream.readInt();
if (tableHeader != 0x39AF547A)
{
throw new IllegalArgumentException("Unexpected file format");
}
int recordCount = m_stream.readInt();
for (int loop = 0; loop < recordCount; loop++)
... |
java | @Beta
public static <T> T checkIsInstance(Class<T> class_, Object reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
checkArgument(class_ != null, "Expected non-null class_");
check... |
python | def main(args, stop=False):
"""
Arguments parsing, etc..
"""
daemon = AMQPDaemon(
con_param=getConParams(
settings.RABBITMQ_MX2MODS_VIRTUALHOST
),
queue=settings.RABBITMQ_MX2MODS_INPUT_QUEUE,
out_exch=settings.RABBITMQ_MX2MODS_EXCHANGE,
out_key=setting... |
python | def get_global_threshold(threshold_method, image, mask = None, **kwargs):
"""Compute a single threshold over the whole image"""
if mask is not None and not np.any(mask):
return 1
if threshold_method == TM_OTSU:
fn = get_otsu_threshold
elif threshold_method == TM_MOG:
fn = ge... |
python | def get_device_access_interfaces(devId):
"""Function takes devId as input to RESTFUL call to HP IMC platform
:param devId: requires deviceID as the only input parameter
:return: list of dictionaries containing interfaces configured as access ports
"""
# checks to see if the imc credentials are alrea... |
java | public void build(final Field field, final DeviceImpl device, final Object businessObject) throws DevFailed {
xlogger.entry();
final String name = field.getName();
logger.debug("Has a DynamicAttributeManagement : {}", name);
BuilderUtils.checkStatic(field);
final String setterNa... |
java | public double getLongitudeFromX01(final double pX01, boolean wrapEnabled) {
final double longitude = getLongitudeFromX01(wrapEnabled ? Clip(pX01, 0, 1) : pX01);
return wrapEnabled ? Clip(longitude, getMinLongitude(), getMaxLongitude()) : longitude;
} |
java | public static Map<Integer, List<AnnotationInstance>> createParameterAnnotationMap(final MethodInfo method) {
final Map<Integer, List<AnnotationInstance>> result = new HashMap<>();
for (AnnotationInstance ai : method.annotations()) {
final AnnotationTarget at = ai.target();
if... |
java | public void addFields(Document document, DecoratedKey partitionKey) {
String serializedKey = ByteBufferUtils.toString(partitionKey.getKey());
Field field = new StringField(FIELD_NAME, serializedKey, Store.YES);
document.add(field);
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.LINE_DATA__LINEDATA:
setLinedata(LINEDATA_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
java | public static String canonical(String path) {
if (path == null || path.length() == 0) {
return path;
}
int end = path.length();
int start = path.lastIndexOf('/', end);
search:
while (end > 0) {
switch (end - start) {
case 2: // po... |
python | def json_compat_obj_encode(data_type, obj, caller_permissions=None, alias_validators=None,
old_style=False, for_msgpack=False, should_redact=False):
"""Encodes an object into a JSON-compatible dict based on its type.
Args:
data_type (Validator): Validator for obj.
obj... |
python | def show_raslog_output_show_all_raslog_number_of_entries(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_raslog = ET.SubEl... |
java | public static Config parseResourcesAnySyntax(Class<?> klass, String resourceBasename) {
return parseResourcesAnySyntax(klass, resourceBasename, ConfigParseOptions.defaults());
} |
python | def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num):
"""
This is called when the coordinator node determines that a read or
write operation cannot be successful because the number of live
replicas are too low to meet the requested :class:`.Consisten... |
java | private Class<?>[] getGroup(Invocable invocable) {
final List<Class<?>[]> groups = new ArrayList<>();
for (Parameter parameter : invocable.getParameters()) {
if (parameter.isAnnotationPresent(Validated.class)) {
groups.add(parameter.getAnnotation(Validated.class).value());
... |
python | def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) |
python | def write_resource_list(
self, paths=None, outfile=None, links=None, dump=None):
"""Write a Resource List or a Resource Dump for files on local disk.
Set of resources included is based on paths setting or else the mappings.
Optionally links can be added. Output will be to stdout unl... |
java | protected T create (Kryo kryo, Input input, Class<? extends T> type) {
return kryo.newInstance(type);
} |
java | @Override
public DescribeDBClusterBacktracksResult describeDBClusterBacktracks(DescribeDBClusterBacktracksRequest request) {
request = beforeClientExecution(request);
return executeDescribeDBClusterBacktracks(request);
} |
java | @Override
public void loadFullScreenImage(final ImageView iv, String imageUrl, int width, final LinearLayout bgLinearLayout) {
if (!TextUtils.isEmpty(imageUrl)) {
Picasso.with(iv.getContext())
.load(imageUrl)
.resize(width, 0)
.into(iv,... |
java | public void setCamera() {
glu.gluLookAt(width / 2.0, height / 2.0,
(height / 2.0) / Math.tan(Math.PI * 60.0 / 360.0), width / 2.0,
height / 2.0, 0, 0, 1, 0);
} |
python | def run_query(conn, query, retries=3):
'''
Get a cursor and run a query. Reconnect up to `retries` times if
needed.
Returns: cursor, affected rows counter
Raises: SaltCacheError, AttributeError, OperationalError
'''
try:
cur = conn.cursor()
out = cur.execute(query)
re... |
python | def normalize(self):
"""
Makes sure this egg distribution is stored only as an egg file.
The egg file will be created from another existing distribution format
if needed.
"""
if self.has_egg_file():
if self.has_zip():
self.__remove_... |
python | def separate(df, column, into, sep="[\W_]+", remove=True, convert=False,
extra='drop', fill='right'):
"""
Splits columns into multiple columns.
Args:
df (pandas.DataFrame): DataFrame passed in through the pipe.
column (str, symbolic): Label of column to split.
into (lis... |
java | static int dayNumToDate(Weekday dow0, int nDays, int weekNum,
Weekday dow, int d0, int nDaysInMonth) {
// if dow is wednesday, then this is the date of the first wednesday
int firstDateOfGivenDow = 1 + ((7 + dow.javaDayNum - dow0.javaDayNum) % 7);
int date;
i... |
java | public void createSubSitemap(final CmsUUID entryId) {
CmsRpcAction<CmsSitemapChange> subSitemapAction = new CmsRpcAction<CmsSitemapChange>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
... |
python | def list_catalogs(self):
"""
Lists existing catalogs respect to ui view template format
"""
_form = CatalogSelectForm(current=self.current)
_form.set_choices_of('catalog', [(i, i) for i in fixture_bucket.get_keys()])
self.form_out(_form) |
java | public static AuthHandler getAuth(Vertx vertx, Router router, VertxEngineConfig apimanConfig) {
String type = apimanConfig.getAuth().getString("type", "NONE");
JsonObject authConfig = apimanConfig.getAuth().getJsonObject("config", new JsonObject());
switch(AuthType.getType(type)) {
case... |
python | def add_connection(self):
"""
Convenience function to connect and store the resulting
connector.
"""
if self.ssl_options:
if not _HAS_SSL:
raise ImportError(
str(e) +
', pyOpenSSL must be installed to enable SSL... |
python | def call_service(self, service_id, action):
"""Call a Vera service.
This will call the Vera api to change device state.
"""
result = self.vera_request(id='action', serviceId=service_id,
action=action)
logger.debug("call_service: "
... |
java | public static <T> T newInstance(final Class<T> clazz) {
Constructor<?>[] constructors = getAllConstructorsOfClass(clazz, true);
if (constructors == null || constructors.length == 0) {
return null;
}
Object[] initParameters = getInitParameters(constructors[0].getParameterTypes... |
java | public <T extends AbstractPutObjectRequest> T withSSEAwsKeyManagementParams(
SSEAwsKeyManagementParams sseAwsKeyManagementParams) {
setSSEAwsKeyManagementParams(sseAwsKeyManagementParams);
@SuppressWarnings("unchecked") T t = (T)this;
return t;
} |
java | public static boolean isEditingModelGroups(CmsObject cms, CmsResource containerPage) {
return (OpenCms.getResourceManager().getResourceType(containerPage).getTypeName().equals(
CmsResourceTypeXmlContainerPage.MODEL_GROUP_TYPE_NAME)
&& OpenCms.getRoleManager().hasRole(cms, CmsRole.DEVELO... |
java | public void setSortOrder(boolean ascending) {
PdfObject o = get(PdfName.S);
if (o instanceof PdfName) {
put(PdfName.A, new PdfBoolean(ascending));
}
else {
throw new IllegalArgumentException("You have to define a boolean array for this collection sort dictionary.");
}
} |
java | static void setModelValue(final ModelNode model, final String value) {
if (value != null) {
model.set(value);
}
} |
java | public OutputStream appendFile(@NotNull final Transaction txn, @NotNull final File file) {
return new VfsAppendingStream(this, txn, file, new LastModifiedTrigger(txn, file, pathnames));
} |
python | def _Open(self, path_spec=None, mode='rb'):
"""Opens the file-like object defined by path specification.
Args:
path_spec (Optional[PathSpec]): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the... |
java | private boolean inSamePackage(Class<?> c1, Class<?> c2) {
String nameC1 = c1.getName();
String nameC2 = c2.getName();
int indexDotC1 = nameC1.lastIndexOf('.');
int indexDotC2 = nameC2.lastIndexOf('.');
if (indexDotC1 != indexDotC2) {
return false; // cannot be in the ... |
java | protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
SecurityProviderException, IOException {
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
// If user is anonymous, authentication is required
if (auth == nul... |
java | public static String stripDelimiters(final String value) {
if (value != null && value.length() > 1) {
if (value.charAt(0) == value.charAt(value.length() - 1)
&& (value.charAt(0) == '\'')) {
return value.substring(1, value.length() - 1);
}
i... |
java | public StringBuilder mapping(boolean makeDest,MappingType mtd,MappingType mts){
StringBuilder sb = new StringBuilder();
if(isNullSetting(makeDest, mtd, mts, sb)) return sb;
if(makeDest)
sb.append(newInstance(destination, stringOfSetDestination));
for (ASimpleOperation simpleOperation : s... |
java | public static Cell getOrCreateCell(Row row, int cellIndex) {
Cell cell = row.getCell(cellIndex);
if (null == cell) {
cell = row.createCell(cellIndex);
}
return cell;
} |
java | public Integer getFirstPosition(String key) {
int position = -1;
String processedKey = processKey(key);
if (this.values.containsKey(processedKey) == true) {
position = this.order.indexOf(processedKey);
}
return position;
} |
python | def check_lazy_load_perceel(f):
'''
Decorator function to lazy load a :class:`Perceel`.
'''
def wrapper(self):
perceel = self
if (getattr(perceel, '_%s' % f.__name__, None) is None):
log.debug(
'Lazy loading Perceel %s in Sectie %s in Afdeling %d',
... |
java | @Override
public InstagramPaginatingResponse<InstagramFeedItem> getSelfFeed(String accessToken,
int count,
String maxContentId,
... |
python | def get_validation_errors(data, schema=None):
"""Validation errors for a given record.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or... |
python | def addImagePath(new_path):
""" Convenience function. Adds a path to the list of paths to search for images.
Can be a URL (but must be accessible). """
if os.path.exists(new_path):
Settings.ImagePaths.append(new_path)
elif "http://" in new_path or "https://" in new_path:
request = reque... |
python | def balancedSlicer(text, openDelim='[', closeDelim=']'):
"""
Assuming that text contains a properly balanced expression using
:param openDelim: as opening delimiters and
:param closeDelim: as closing delimiters.
:return: text between the delimiters
"""
openbr = 0
cur = 0
for char in ... |
python | def _get_fill_value(dtype, fill_value=None, fill_value_typ=None):
""" return the correct fill value for the dtype of the values """
if fill_value is not None:
return fill_value
if _na_ok_dtype(dtype):
if fill_value_typ is None:
return np.nan
else:
if fill_valu... |
java | @SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyInitializers(ConfigurableApplicationContext context) {
for (ApplicationContextInitializer initializer : getInitializers()) {
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(
initializer.getClass(), ApplicationContextInitialize... |
java | public static <L, R> Either<L, R> fromMaybe(Maybe<R> maybe, Supplier<L> leftFn) {
return maybe.<Either<L, R>>fmap(Either::right)
.orElseGet(() -> left(leftFn.get()));
} |
java | @Override
public String getTopologyJsonPayload(Set<Host> activeHosts) {
int count = NUM_RETRIER_ACROSS_NODES;
String response;
Exception lastEx = null;
do {
try {
response = getTopologyFromRandomNodeWithRetry(activeHosts);
if (response != null) {
return response;
}
} catch (Exception... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.