language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def summary_df(df_in, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This is similar to pandas.DataFrame.describe but also includes estimates of
the numerical uncertainties.
The output DataFrame has multiindex level... |
java | protected void read() throws IOException {
buffer.rewind();
buffer.limit(buffer.capacity());
device.read(offset, buffer);
this.dirty = false;
} |
java | public Object getArrayElement(Object o, int index) throws IndexOutOfBoundsException {
if (o instanceof List)
return ((List)o).get(index);
return Array.get(o,index);
} |
python | def convert_value(value, field):
"""Given a :class:`.fields.Field` and a value, ensure that the value matches the given type, otherwise
attempt to convert it.
:param value: field value.
:param field: :class:`.fields.Field` instance.
:return: Result value.
"""
clz... |
java | public static Optional<CopyableFileWatermarkGenerator> getCopyableFileWatermarkGenerator(State state)
throws IOException {
try {
if (state.contains(WATERMARK_CREATOR)) {
Class<?> watermarkCreatorClass = Class.forName(state.getProp(WATERMARK_CREATOR));
return Optional.of((CopyableFileWate... |
python | def get_newest(blocks, layout_blocks):
"""Filter out old layout blocks from list
Arguments:
List:blocks -- List of block objects
List:layout_blocks -- List of layout block indexes
Returns:
List -- Newest layout blocks in list
"""
layout_temp = list(layout_blocks)
for i in r... |
java | public static void setResultDisplayDurationInMs(Intent intent, long duration) {
intent.putExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS, duration);
} |
python | def parse_buckets(self, bucket, params):
"""
Parse a single S3 bucket
TODO:
- CORS
- Lifecycle
- Notification ?
- Get bucket's policy
:param bucket:
:param params:
:return:
"""
bucket['name'] = bucket.pop('Name')
a... |
java | public Observable<Void> beginRefreshHubSchemaAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName) {
return beginRefreshHubSchemaWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
... |
java | public static int validateZone(CharSequence zone) {
for(int i = 0; i < zone.length(); i++) {
char c = zone.charAt(i);
if (c == IPAddress.PREFIX_LEN_SEPARATOR) {
return i;
}
if (c == IPv6Address.SEGMENT_SEPARATOR) {
return i;
}
}
return -1;
} |
java | public static void addFull(JSONWriter writer, String field, Date value)
throws JSONException {
final SimpleDateFormat format = RedmineDateUtils.FULL_DATE_FORMAT.get();
JsonOutput.add(writer, field, value, format);
} |
java | @Override
public void body(String namespace, String name, String bodyText) throws Exception {
if (m_paramCount == 0) {
m_bodyText = bodyText.trim();
}
} |
python | def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc, srcDiffData,
destDesc, destData, beta, destDiffDesc, destDiffData):
""""
Gradient of activation function.
This routine computes the gradient of a neuron activation function.
In-place operation i... |
python | def _setup_stats_plugins(self):
'''
Sets up the plugin stats collectors
'''
self.stats_dict['plugins'] = {}
for key in self.plugins_dict:
plugin_name = self.plugins_dict[key]['instance'].__class__.__name__
temp_key = 'stats:redis-monitor:{p}'.format(p=plug... |
java | public IPv4AddressSection[] spanWithSequentialBlocks(IPv4AddressSection other) {
return getSpanningSequentialBlocks(
this,
other,
IPv4AddressSection::getLower,
IPv4AddressSection::getUpper,
Address.ADDRESS_LOW_VALUE_COMPARATOR::compare,
IPv4AddressSection::withoutPrefixLength,
getAddressCr... |
java | private void previewButtonClicked() {
if (!tagPreviewBtnClicked) {
colorPickerLayout
.setSelectedColor(ColorPickerHelper.rgbToColorConverter(ColorPickerConstants.DEFAULT_COLOR));
}
tagPreviewBtnClicked = !tagPreviewBtnClicked;
colorPickerLayout.setVisible... |
java | private int compareScheme(URI other) {
String scheme = getScheme();
String otherScheme = other.getScheme();
if (scheme == null && otherScheme == null) {
return 0;
}
if (scheme != null) {
if (otherScheme != null) {
return scheme.compareToIgnoreCase(otherScheme);
}
// ... |
python | def export_items(elastic_url, in_index, out_index, elastic_url_out=None,
search_after=False, search_after_value=None, limit=None,
copy=False):
""" Export items from in_index to out_index using the correct mapping """
if not limit:
limit = DEFAULT_LIMIT
if search_a... |
python | def groups_close(self, room_id, **kwargs):
"""Removes the private group from the user’s list of groups, only if you’re part of the group."""
return self.__call_api_post('groups.close', roomId=room_id, kwargs=kwargs) |
java | @SuppressWarnings("unused")
private void allocateBuffers(int numVertices) {
/*
* the allocated buffers are native order direct byte buffers, so they
* can be passed directly to LWJGL or similar graphics APIs
*/
m_numVertices = numVertices;
/* allocate for each ve... |
java | public void delete(DbSession dbSession, String permission, String organizationUuid, @Nullable Integer groupId, @Nullable Long rootComponentId) {
mapper(dbSession).delete(permission, organizationUuid, groupId, rootComponentId);
} |
python | def GetParserFromFilename(self, path):
"""Returns the appropriate parser class from the filename."""
# Find the configuration parser.
handler_name = path.split("://")[0]
for parser_cls in itervalues(GRRConfigParser.classes):
if parser_cls.name == handler_name:
return parser_cls
# Hand... |
java | public static <T extends Savepoint> void storeCheckpointMetadata(
T checkpointMetadata,
OutputStream out) throws IOException {
DataOutputStream dos = new DataOutputStream(out);
storeCheckpointMetadata(checkpointMetadata, dos);
} |
python | def getOrCreate(cls, sc):
"""
Get the existing SQLContext or create a new one with given SparkContext.
:param sc: SparkContext
"""
if cls._instantiatedContext is None:
jsqlContext = sc._jvm.SQLContext.getOrCreate(sc._jsc.sc())
sparkSession = SparkSession(... |
java | public List<Type> randomSplit(Random rand, double... splits)
{
if(splits.length < 1)
throw new IllegalArgumentException("Input array of split fractions must be non-empty");
IntList randOrder = new IntList(size());
ListUtils.addRange(randOrder, 0, size(), 1);
Collect... |
java | @Override
final public XAResource getXAResource() throws ResourceException {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "getXAResource");
}
if (_coreConnection == null) {
throw new ResourceAdapterInternalException... |
java | public <T extends D6Model> T[] execSelectTable(String preparedSql, Object[] searchKeys, Class<T> modelClazz) {
@SuppressWarnings("unchecked")
final Map<Class<?>, List<Object>> result = execSelectTableWithJoin(preparedSql, searchKeys, modelClazz);
final List<Object> rowList = result.get(modelClazz);
r... |
python | def expand(self, flm, nmax=None):
"""
Return the Slepian expansion coefficients of the input function.
Usage
-----
s = x.expand(flm, [nmax])
Returns
-------
s : SlepianCoeff class instance
The Slepian expansion coefficients of the input funct... |
python | def trap_exceptions(results, handler, exceptions=Exception):
"""
Iterate through the results, but if an exception occurs, stop
processing the results and instead replace
the results with the output from the exception handler.
"""
try:
for result in results:
yield result
except exceptions as exc:
for resul... |
java | private boolean familyHalogen(IAtom atom) {
String symbol = atom.getSymbol();
return symbol.equals("F") || symbol.equals("Cl") || symbol.equals("Br") || symbol.equals("I");
} |
java | protected HttpURLConnection openConnection(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS);
connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS);
connection.setRequestPropert... |
python | def add_primary_relationship(parent, childrel, child, parentrel, parentcol):
"""
When a parent-child relationship is defined as one-to-many,
:func:`add_primary_relationship` lets the parent refer to one child as the
primary, by creating a secondary table to hold the reference. Under
PostgreSQL, a tr... |
python | def get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True):
"""
Returns git style diff between given ``filenode_old`` and ``filenode_new``.
:param ignore_whitespace: ignore whitespaces in diff
"""
for filenode in (filenode_old, filenode_new):
if not isinstance(filenode, FileNode):... |
python | def updatepLvlGrid(self):
'''
Update the grid of persistent income levels. Currently only works for
infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not
clear what to do about cycles>1 because the distribution of persistent
income will be different within a p... |
java | private void updateEvseStatus(ChargingStation chargingStation, String componentId, ComponentStatus status) {
for (Evse evse : chargingStation.getEvses()) {
if (evse.getEvseId().equals(componentId)) {
evse.setStatus(status);
}
}
} |
java | public static <A, B> Multiset<B> mutableTransformedCopy(Multiset<A> ms,
Function<A, B> func) {
final Multiset<B> ret = HashMultiset.create();
for (final Multiset.Entry<A> entry : ms.entrySet()) {
final B transformedElement = func.apply(entry.getElement());
ret.add(transformedElement, entry.ge... |
python | def convert_coordinates(q, conversion, axisorder):
"""
Convert a 3-tuple in data coordinates into to simplex data
coordinates for plotting.
Parameters
----------
q: 3-tuple
the point to be plotted in data coordinates
conversion: dict
keys = ['b','l','r']
values = lam... |
python | def chunk_encoding(chunks, chunk):
'''Write a chunk::
chunk-size(hex) CRLF
chunk-data CRLF
If the size is 0, this is the last chunk, and an extra CRLF is appended.
'''
chunks.extend(("%X\r\n" % len(chunk)).encode('utf-8'))
chunks.extend(chunk)
chunks.extend(CRLF) |
python | def init_dense_weight(layer):
'''initilize dense layer weight.
'''
units = layer.units
weight = np.eye(units)
bias = np.zeros(units)
layer.set_weights(
(add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1])))
) |
java | private HttpSession2 buildSession(boolean create) {
if (create) {
session = buildSession(sessionManager.getSessionIdGenerator().generate(request), true);
log.debug("Build new session[{}].", session.getId());
return session;
} else {
return null;
}
... |
python | def scrape_metrics(self, scraper_config):
"""
Poll the data from prometheus and return the metrics as a generator.
"""
response = self.poll(scraper_config)
try:
# no dry run if no label joins
if not scraper_config['label_joins']:
scraper_co... |
java | public static void incrLogMetrics(Map<String, Long> incrMetrics) {
if (incrMetrics == null || incrMetrics.size() == 0) {
return;
}
MetricsRegistry registry = RaidNodeMetrics.getInstance(
RaidNodeMetrics.DEFAULT_NAMESPACE_ID).getMetricsRegistry();
Map<String, MetricsTimeVaryingLong> logMetr... |
java | static public IParserInput getInstance(
final char commandPrefix,
final boolean allowEmbeddedCommandPrefix,
final File args)
throws IOException
{
final CommandLineParser parser = new CommandLineParser();
parser.commandPrefix = commandPrefix;
... |
python | def get_block_start(lines, lineno, maximum_indents=80):
"""Approximate block start"""
pattern = get_block_start_patterns()
for i in range(lineno, 0, -1):
match = pattern.search(lines.get_line(i))
if match is not None and \
count_line_indents(lines.get_line(i)) <= maximum_indents:
... |
python | def remove(self, payload):
"""Remove specified entries from the queue."""
succeeded = []
failed = []
for key in payload['keys']:
running = self.process_handler.is_running(key)
if not running:
removed = self.queue.remove(key)
if remo... |
java | private void initialize(Locale locale) {
// start with a new instance of the widgets and unique widgets
m_widgets = new HashMap<String, I_CmsWidget>(25);
m_uniqueWidgets = new ArrayList<I_CmsWidget>(12);
m_values = new HashMap<String, I_CmsXmlContentValue>(25);
// store Locale t... |
python | def wrap(self, message):
"""
NTM GSSwrap()
:param message: The message to be encrypted
:return: A Tuple containing the signature and the encrypted messaging
"""
cipher_text = _Ntlm2Session.encrypt(self, message)
signature = _Ntlm2Session.sign(self, message)
... |
python | def make_cache_key(request):
""" Generate a cache key from request object data """
headers = frozenset(request._p['header'].items())
path = frozenset(request._p['path'].items())
query = frozenset(request._p['query'])
return (request.url, headers, path, query) |
java | private void callLifecycleInterceptors(Class<?> mbClass, Object mbInstance)
throws InjectionException
{
Collection<MethodInfo> methods = MethodMap.getAllDeclaredMethods(mbClass);
for (MethodInfo methodInfo : methods)
{
Method method = methodInfo.getMethod();
... |
java | public ComplexDouble subi(ComplexDouble c, ComplexDouble result) {
if (this == result) {
r -= c.r;
i -= c.i;
} else {
result.r = r - c.r;
result.i = i - c.i;
}
return this;
} |
python | def translate_to_stackdriver(self, trace):
"""Translate the spans json to Stackdriver format.
See: https://cloud.google.com/trace/docs/reference/v2/rest/v2/
projects.traces/batchWrite
:type trace: dict
:param trace: Trace dictionary
:rtype: dict
:returns: ... |
java | public void activateVersionControl(final Package converterPackage) throws CouldNotPerformException {
try {
String entryType;
try {
entryType = getDatabaseName();
} catch (Exception ex) {
throw new CouldNotPerformException("Could not detect entr... |
python | def approve(
self,
allowed_address: Address,
allowance: TokenAmount,
):
""" Aprove `allowed_address` to transfer up to `deposit` amount of token.
Note:
For channel deposit please use the channel proxy, since it does
additional validations... |
python | def idempotency_key(self, idempotency_key):
"""
Sets the idempotency_key of this BatchUpsertCatalogObjectsRequest.
A value you specify that uniquely identifies this request among all your requests. A common way to create a valid idempotency key is to use a Universally unique identifier (UUID). ... |
java | public BaasResult<BaasUser> loginSync(String registrationId) {
BaasBox box = BaasBox.getDefault();
if (password == null) throw new IllegalStateException("password cannot be null");
NetworkTask<BaasUser> task = new LoginRequest(box, this, registrationId, RequestOptions.DEFAULT, null);
ret... |
java | public static Builder measurementByPOJO(final Class<?> clazz) {
Objects.requireNonNull(clazz, "clazz");
throwExceptionIfMissingAnnotation(clazz, Measurement.class);
String measurementName = findMeasurementName(clazz);
return new Builder(measurementName);
} |
java | public String processInterfaceTypes(TDefinitions descriptionType, boolean addAddress)
{
String allAddress = DBConstants.BLANK;
for (TDocumented nextElement : descriptionType.getAnyTopLevelOptionalElement())
{
// Create the service type
if (nextElement instanc... |
java | public static Pair<INDArray, INDArray> mergeTimeSeries(INDArray[][] arrays, INDArray[][] masks, int inOutIdx) {
Pair<INDArray[], INDArray[]> p = selectColumnFromMDSData(arrays, masks, inOutIdx);
return mergeTimeSeries(p.getFirst(), p.getSecond());
} |
python | def data_not_in(db_data, user_data):
"""Validate data not in user data.
Args:
db_data (str): The data store in Redis.
user_data (list): The user provided data.
Returns:
bool: True if the data passed validation.
"""
if isinstance(user_data, li... |
python | def get_context_files(data):
"""Retrieve pre-installed annotation files for annotating genome context.
"""
ref_file = dd.get_ref_file(data)
all_files = []
for ext in [".bed.gz"]:
all_files += sorted(glob.glob(os.path.normpath(os.path.join(os.path.dirname(ref_file), os.pardir,
... |
python | def to_string(interval, conv=repr, disj=' | ', sep=',', left_open='(',
left_closed='[', right_open=')', right_closed=']', pinf='+inf', ninf='-inf'):
"""
Export given interval (or atomic interval) to string.
:param interval: an Interval or AtomicInterval instance.
:param conv: function tha... |
java | public List<DomainTopicInner> listByDomain(String resourceGroupName, String domainName) {
return listByDomainWithServiceResponseAsync(resourceGroupName, domainName).toBlocking().single().body();
} |
java | public void marshall(DeleteSizeConstraintSetRequest deleteSizeConstraintSetRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteSizeConstraintSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshalle... |
python | def format_distance(kilometers, fmt=DISTANCE_FORMAT, unit='km'):
"""
TODO docs.
"""
magnitude = DISTANCE_UNITS[unit](kilometers)
return fmt % {'magnitude': magnitude, 'unit': unit} |
java | public Object constantValue() {
Object result = sym.getConstValue();
if (result != null && sym.type.hasTag(BOOLEAN))
// javac represents false and true as Integers 0 and 1
result = Boolean.valueOf(((Integer)result).intValue() != 0);
return result;
} |
java | public static ProxyInfo setProxyCfg(String host, String port, String userName, String password) {
return new ProxyInfo(host, port, userName, password);
} |
java | private boolean isExcludedClass(Class<?> clazz) {
for (Class<?> c : excludedClasses) {
if (c.isAssignableFrom(clazz)) {
return true;
}
}
return false;
} |
java | protected Queue<AsyncResourceRequest<V>> getRequestQueueForExistingKey(K key) {
Queue<AsyncResourceRequest<V>> requestQueue = requestQueueMap.get(key);
return requestQueue;
} |
python | def convertDict2Attrs(self, *args, **kwargs):
"""Each element on the atttrs attribute gest converted to a
proper python object, depending on type.
Some default constantFields are left as is (strings), because
they are better treated as strings.
"""
constantFields = ['id'... |
python | def Upload(self,directory,filename):
"""Uploads/Updates/Replaces files"""
db = self._loadDB(directory)
logger.debug("wp: Attempting upload of %s"%(filename))
# See if this already exists in our DB
if db.has_key(filename):
pid=db[filename]
logger.debug('... |
python | def unlock(self):
'''Unlock card with SCardEndTransaction.'''
component = self.component
while True:
if isinstance(
component,
smartcard.pcsc.PCSCCardConnection.PCSCCardConnection):
hresult = SCardEndTransaction(component.hcard,... |
python | def insrtc(item, inset):
"""
Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
... |
python | def bam_conversion(job, samfile, sample_type, univ_options, samtools_options):
"""
Convert a sam to a bam.
:param dict samfile: The input sam file
:param str sample_type: Description of the sample to inject into the filename
:param dict univ_options: Dict of universal options used by almost all too... |
java | @Override
public void put(List<Put> puts) throws IOException {
LOG.trace("put(List<Put>)");
if (puts == null || puts.isEmpty()) {
return;
} else if (puts.size() == 1) {
try {
put(puts.get(0));
} catch (IOException e) {
throw createRetriesExhaustedWithDetailsException(e, p... |
python | def _cleanup_api(self):
'''
Helper method to clean up resources and models if we detected a change in the swagger file
for a stage
'''
resources = __salt__['boto_apigateway.describe_api_resources'](restApiId=self.restApiId,
... |
python | def add_library_search_paths(self, paths, recursive=True, escape=False, target_name=None, configuration_name=None):
"""
Adds paths to the LIBRARY_SEARCH_PATHS configuration.
:param paths: A string or array of strings
:param recursive: Add the paths as recursive ones
:param escape... |
python | def configure(self, binder):
# type: (Binder) -> None
"""Initializer of the cache - creates the Redis cache module as the
default cache infrastructure. The module is bound to `RedisCacheModule`
and `CacheModule` keys. The initializer also creates `RedisIdHelper`
and bounds it to ... |
python | def _quantize(x, params, randomize=True):
"""Quantize x according to params, optionally randomizing the rounding."""
if not params.quantize:
return x
if not randomize:
return tf.bitcast(
tf.cast(x / params.quantization_scale, tf.int16), tf.float16)
abs_x = tf.abs(x)
sign_x = tf.sign(x)
y =... |
python | def _scopes_registered(self):
"""
Return a list that contains all the scopes registered
in the class.
"""
scopes = []
for name in dir(self.__class__):
if name.startswith('scope_'):
scope = name.split('scope_')[1]
scopes.append(... |
java | public void addMBeanAttribute(String mbean, MBeanAttribute attr)
throws Exception {
MBeanHolder mbeanHolder = mbeanMap.get(mbean);
if (mbeanHolder == null) {
mbeanHolder = new MBeanHolder(this, process, mbean);
mbeanMap.put(mbean, mbeanHolder);
}
mbeanHolder.addAttribute(attr);
log.info("Added attrib... |
java | public static String buildCommand(YarnContainerType containerType, Map<String, String> args) {
CommandBuilder commandBuilder =
new CommandBuilder("./" + ALLUXIO_SETUP_SCRIPT).addArg(containerType.getName());
for (Entry<String, String> argsEntry : args.entrySet()) {
commandBuilder.addArg(argsEntry.... |
java | public INDArray inferVector(String text, double learningRate, double minLearningRate, int iterations) {
if (tokenizerFactory == null)
throw new IllegalStateException("TokenizerFactory should be defined, prior to predict() call");
if (this.vocab == null || this.vocab.numWords() == 0)
... |
java | private static List<CharSequence> splitHeader(CharSequence header) {
final StringBuilder builder = new StringBuilder(header.length());
final List<CharSequence> protocols = new ArrayList<CharSequence>(4);
for (int i = 0; i < header.length(); ++i) {
char c = header.charAt(i);
... |
java | @NotNull
public Exceptional<T> ifPresent(@NotNull Consumer<? super T> consumer) {
if (throwable == null) {
consumer.accept(value);
}
return this;
} |
java | public Object getKey(Key key, String[] actualReturn) {
return getKey(key, actualReturn, null);
} |
java | @Benchmark
@BenchmarkMode(Mode.AverageTime)
public void byteArrayRandomAccessFile(final Configuration configuration) throws IOException {
byte[] buffer = new byte[BUFFER_CAPACITY];
int position = 0;
try (RandomAccessFile file = new RandomAccessFile(configuration.file, "rw")) {
for (long i = 0; i < LINES; ++... |
java | public static Interval plus(final Interval interval, final Period period) {
return new Interval(interval.getStart().plus(period),
interval.getEnd().plus(period));
} |
python | def loads(self, param):
'''
Checks the return parameters generating new proxy instances to
avoid query concurrences from shared proxies and creating
proxies for actors from another host.
'''
if isinstance(param, ProxyRef):
try:
return self.look... |
python | def collect_manifest_dependencies(manifest_data, lockfile_data):
"""Convert the manifest format to the dependencies schema"""
output = {}
for dependencyName, dependencyConstraint in manifest_data.items():
output[dependencyName] = {
# identifies where this dependency is installed from
... |
python | def _walk_factory(self, dep_predicate):
"""Construct the right context object for managing state during a transitive walk."""
walk = None
if dep_predicate:
walk = self.DepPredicateWalk(dep_predicate)
else:
walk = self.NoDepPredicateWalk()
return walk |
java | public JvmTypeReference inferredType() {
XComputedTypeReference result = xtypesFactory.createXComputedTypeReference();
result.setTypeProvider(new InferredTypeIndicator(null));
return result;
} |
python | def filesizeformat(bytes, decimals=1):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
Based on django.template.defaultfilters.filesizeformat
"""
try:
bytes = float(bytes)
except (TypeError, ValueError, UnicodeDecodeError):
raise... |
python | def get_cookie(self, key, default=None, secret=None):
""" Return the content of a cookie. To read a `Signed Cookie`, the
`secret` must match the one used to create the cookie (see
:meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
cookie or wrong signature), re... |
python | def remove_entry(data, entry):
'''
Remove an entry in place.
'''
file_field = entry['fields'].get('file')
if file_field:
try:
os.remove(file_field)
except IOError:
click.echo('This entry\'s file was missing')
data.remove(entry) |
java | public NumberExpression<Integer> numInteriorRing() {
if (numInteriorRing == null) {
numInteriorRing = Expressions.numberOperation(Integer.class, SpatialOps.NUM_INTERIOR_RING, mixin);
}
return numInteriorRing;
} |
java | public static Table setPadding (final Padding padding, final Table table) {
table.pad(padding.getTop(), padding.getLeft(), padding.getBottom(), padding.getRight());
return table;
} |
java | public static final boolean xor(boolean b1, boolean b2) {
if (b1 == false && b2 == false) {
return false;
} else if (b1 == false && b2 == true) {
return true;
} else if (b1 == true && b2 == false) {
return true;
} else {
return false;
}
} |
python | def process(self, response):
""" Returns HTTP backend agnostic ``Response`` data. """
try:
code = response.status_code
# 204 - No Content
if code == 204:
body = None
# add an error message to 402 errors
elif code == 402:
... |
java | public LoadBalancerTlsCertificateRenewalSummary withDomainValidationOptions(LoadBalancerTlsCertificateDomainValidationOption... domainValidationOptions) {
if (this.domainValidationOptions == null) {
setDomainValidationOptions(new java.util.ArrayList<LoadBalancerTlsCertificateDomainValidationOption>(... |
python | def get_source_scanner(self, node):
"""Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.