language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Nullable
protected static SOAPFaultException createSfe(@NotNull SoapFaultCode soapFaultCode) {
try {
QName qname = new QName("http://schemas.xmlsoap.org/soap/envelope/", soapFaultCode.name());
SOAPFactory sf = SOAPFactory.newInstance();
SOAPFault fault = sf.createFault("... |
python | def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request() |
python | def join(args):
"""
%prog join file1.txt(pivotfile) file2.txt ..
Join tabular-like files based on common column.
--column specifies the column index to pivot on.
Use comma to separate multiple values if the pivot column is different
in each file. Maintain the order in the first file.
--... |
java | public static void writeTiles(GeoPackage geoPackage, String tileTable,
File directory, String imageFormat, Integer width, Integer height,
TileFormatType tileType, boolean rawImage) throws IOException {
// Get a tile data access object for the tile table
TileDao tileDao = geoPackage.getTileDao(tileTable);
... |
python | def filter(cls, pythons):
"""
Given a map of python interpreters in the format provided by PythonInterpreter.find(),
filter out duplicate versions and versions we would prefer not to use.
Returns a map in the same format as find.
"""
good = []
MAJOR, MINOR, SUBMINOR = range(3)
de... |
java | public static Matcher<ContextElement> attributes(final Matcher<Map<String, Object>> matcher) {
return new Matcher<ContextElement>() {
@Override
protected boolean matchesSafely(ContextElement t) {
return matcher.matches(t.attributes());
}
@Override
public String toString() {
... |
java | private void sendAck()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "sendAck");
long completedPrefix = oststream.getCompletedPrefix();
// Now that all messages are delivered we need to send Acks
// sendAck back to sending ME (... |
python | def benchmark(repeat=10):
"""Benchmark cyordereddict.OrderedDict against collections.OrderedDict
"""
columns = ['Test', 'Code', 'Ratio (stdlib / cython)']
res = _calculate_benchmarks(repeat)
try:
from tabulate import tabulate
print(tabulate(res, columns, 'rst'))
except ImportErro... |
java | public void run()
{
// Note: To make sure the user gets a chance to see the
// html text, we wait for a paint before returing.
// Since these threads are stacked in a private thread queue, the next
// thread is not executed until this one is finished.
if (! EventQueue.isD... |
python | def road_analysis_summary_report(feature, parent):
"""Retrieve an HTML road analysis table report from a multi exposure
analysis.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir(exposure_road['key'])
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
re... |
python | def summarize_events(self, events_json):
"""
The function for summarizing RDAP events in to a unique list.
https://tools.ietf.org/html/rfc7483#section-4.5
Args:
events_json (:obj:`dict`): A json mapping of events from RDAP
results.
Returns:
... |
java | public Map<String, Class> mapAllImplementations(Class interfase) throws IOException, ClassNotFoundException {
Map<String, Class> implementations = new HashMap<>();
Map<String, String> map = mapAllStrings(interfase.getName());
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext()... |
java | static public void appendHexString(StringBuilder buffer, short value) {
assertNotNull(buffer);
int nibble = (value & 0xF000) >>> 12;
buffer.append(HEX_TABLE[nibble]);
nibble = (value & 0x0F00) >>> 8;
buffer.append(HEX_TABLE[nibble]);
nibble = (value & 0x00F0) >>> 4;
... |
python | def registration_settings(request):
'''Expose selected settings to templates'''
context = {}
for setting in (
'WAFER_SSO',
'WAFER_HIDE_LOGIN',
'WAFER_REGISTRATION_OPEN',
'WAFER_REGISTRATION_MODE',
'WAFER_TALKS_OPEN',
'WAFER_VIDEO_LICENS... |
python | def urandom(*args: Any, **kwargs: Any) -> bytes:
"""Return a bytes object containing random bytes.
:return: Bytes.
"""
return os.urandom(*args, **kwargs) |
python | def result(self):
"""
Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won.
"""
if self._result.lower() == 'w':
return WIN
if self._result.lower() == 'l' and \
self.overtime != 0:
return... |
python | def gzip_uncompress(data, truncated=False):
'''Uncompress gzip data.
Args:
data (bytes): The gzip data.
truncated (bool): If True, the decompressor is not flushed.
This is a convenience function.
Returns:
bytes: The inflated data.
Raises:
zlib.error
'''
de... |
java | @Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
Character[] b;
if (a.length < size()) b = new Character[size()];
else b = (Character[]) a;
objectUnwrap(iterator(), b);
return (T[]) b;
} |
python | def grant(self, column=None, value=None, **kwargs):
"""
Provides various award, project, and grant personnel information.
>>> GICS().grant('project_city_name', 'San Francisco')
"""
return self._resolve_call('GIC_GRANT', column, value, **kwargs) |
java | public static String getWhereClauseForPartition(Map<String, String> spec, String prefix) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : spec.entrySet()) {
if (!sb.toString().isEmpty()) {
sb.append(" AND ");
}
sb.append(prefix + entry.getKey());
s... |
python | def to_networkx(graph):
""" Convert a Mapper 1-complex to a networkx graph.
Parameters
-----------
graph: dictionary, graph object returned from `kmapper.map`
Returns
--------
g: graph as networkx.Graph() object
"""
# import here so networkx is not always required.
import n... |
python | def flatten4d3d(x):
"""Flatten a 4d-tensor into a 3d-tensor by joining width and height."""
xshape = shape_list(x)
result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])
return result |
java | public int getMethodOrProperty(char[] array, int currentIndex, StringBuffer velocityBlock,
VelocityParserContext context) throws InvalidVelocityException
{
int i = currentIndex + 1;
// A Velocity method starts with [a-zA-Z]
if (i < array.length && Character.isLetter(array[i])) {
... |
python | def _do_home_key(self, event=None, select=False):
""" Performs home key action """
# get nb char to first significative char
delta = (self.textCursor().positionInBlock() -
TextHelper(self).line_indent())
cursor = self.textCursor()
move = QtGui.QTextCursor.MoveAnc... |
java | @Override
public boolean startsWith(final String other) {
if (other == null) {
throw new IllegalArgumentException("other path input must be specified");
}
final Path otherPath = this.fromString(other);
return this.startsWith(otherPath);
} |
python | def _init_cfg_interfaces(self, cb, intf_list=None, all_intf=True):
"""Configure the interfaces during init time. """
if not all_intf:
self.intf_list = intf_list
else:
self.intf_list = sys_utils.get_all_run_phy_intf()
self.cb = cb
self.intf_attr = {}
... |
java | @Override
public boolean authorizeURLRequest(Request.Builder builder) {
loadTokens();
if (IDToken != null && !haveSessionCookie) {
String auth = String.format(Locale.ENGLISH, "Bearer ", IDToken);
builder.addHeader("Authorization", auth);
return true;
} els... |
python | def update_user_attributes(self, user, claims):
"""
Updates user attributes based on the CLAIM_MAPPING setting.
Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): claims from the access token
"""
required_fields = [field.nam... |
python | def copy(self, *args, **kwargs):
"""
Make a copy of this object.
Note:
Copies both field data and field values.
See Also:
For arguments and description of behavior see `pandas docs`_.
.. _pandas docs: http://pandas.pydata.org/pandas-docs/stable/generate... |
python | def _get_args_to_parse(args, sys_argv):
"""Return the given arguments if it is not None else sys.argv if it contains
something, an empty list otherwise.
Args:
args: argument to be parsed
sys_argv: arguments of the command line i.e. sys.argv
"""
arguments = args if args is not No... |
python | def apply_op(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_k... |
python | def get_image(self, title, group):
'''
Retrieve image @title from group @group.
'''
return self.images[group.lower()][title.lower()] |
python | async def _get_user(self):
"""
Get the user dict from cache or query it from the platform if missing.
"""
if self._cache is None:
try:
self._cache = \
await self.facebook.get_user(self.fbid, self.page_id)
except PlatformOperati... |
java | public static void setDefaultCursor (Cursor defaultCursor) {
if (defaultCursor == null) throw new IllegalArgumentException("defaultCursor can't be null");
CursorManager.defaultCursor = defaultCursor;
CursorManager.systemCursorAsDefault = false;
} |
python | def sign(self, xml_doc):
"""Sign the document with a third party signatory.
:param str xml_doc: Document self signed in plain xml
:returns answer: Answer is given from the signatory
itself if connected.
"""
try:
self.client = Client(self.url)
exce... |
python | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._merchant_reference is not None:
... |
python | def get_option_path(self, name, section=None, vars=None, expect=None):
"""Just like ``get_option`` but return a ``pathlib.Path`` object of
the string.
"""
val = self.get_option(name, section, vars, expect)
return Path(val) |
python | def set_cookie_prefix(self, cookie_prefix=None):
"""Set a random cookie prefix unless one is specified.
In order to run multiple demonstration auth services on the
same server we need to have different cookie names for each
auth domain. Unless cookie_prefix is set, generate a random
... |
python | def xymatch(outfile, filenames, tol=2):
"""Given a list of MOPfiles merge them based on x/y coordinates matching.."""
import math
import sys
output={}
files=[]
for filename in filenames:
this_file=read(filename)
## match files based on the 'X' and 'Y' column.
## if those ... |
python | def create_items(portal_type=None, uid=None, endpoint=None, **kw):
""" create items
1. If the uid is given, get the object and create the content in there
(assumed that it is folderish)
2. If the uid is 0, the target folder is assumed the portal.
3. If there is no uid given, the payload is check... |
java | private static Principal getPrimaryPrincipal(final PrincipalElectionStrategy principalElectionStrategy,
final Set<Authentication> authentications,
final Map<String, List<Object>> principalAttributes) {
return princ... |
python | def _build_requested_prefetches(
self,
prefetches,
requirements,
model,
fields,
filters
):
"""Build a prefetch dictionary based on request requirements."""
for name, field in six.iteritems(fields):
original_field = field
if isi... |
python | def add_options(cls, parser: OptionManager) -> None:
"""
``flake8`` api method to register new plugin options.
See :class:`.Configuration` docs for detailed options reference.
Arguments:
parser: ``flake8`` option parser instance.
"""
parser.add_option(
... |
python | def _get_group_index(self, index):
"""Find and return the appropriate group index."""
g_index = None
for group in self.groups:
if group[0] == index:
g_index = group[1]
break
return g_index |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(OpenvzCollector, self).get_default_config()
config.update({
'path': 'openvz',
'bin': '/usr/sbin/vzlist',
'keyname': 'hostname'
})
return... |
java | public static ZooKeeperCheckpointIDCounter createCheckpointIDCounter(
CuratorFramework client,
Configuration configuration,
JobID jobId) {
String checkpointIdCounterPath = configuration.getString(
HighAvailabilityOptions.HA_ZOOKEEPER_CHECKPOINT_COUNTER_PATH);
checkpointIdCounterPath += ZooKeeperSubmi... |
python | def total_duration(self):
"""
Return the total amount of audio summed over all utterances in the corpus in seconds.
"""
duration = 0
for utterance in self.utterances.values():
duration += utterance.duration
return duration |
java | public <T> T callWithTimeout(String description, int timeout, Callable<T> task) {
Future<T> callFuture = threadPool.submit(task);
return getWithTimeout(callFuture, timeout, description);
} |
java | public JsonWriter keyUnescaped(CharSequence key) {
startKey();
if (key == null) {
throw new IllegalArgumentException("Expected map key, but got null.");
}
writer.write('\"');
writer.write(key.toString());
writer.write('\"');
writer.write(':');
... |
java | public Date getStart()
{
Date result = (Date) getCachedValue(AssignmentField.START);
if (result == null)
{
result = getTask().getStart();
}
return result;
} |
java | public MessageValidator getDefaultMessageHeaderValidator() {
return messageValidators
.stream()
.filter(validator -> DefaultMessageHeaderValidator.class.isAssignableFrom(validator.getClass()))
.findFirst()
.orElse(null);
} |
python | def close(self):
""" Tell all the workers to quit."""
if self.is_worker():
return
for worker in self.workers:
self.comm.send(None, worker, 0) |
python | def cnst_A(self, X):
r"""Compute :math:`A \mathbf{x}` component of ADMM problem
constraint. In this case :math:`A \mathbf{x} = (G_r^T \;\; G_c^T
\;\; I)^T \mathbf{x}`.
"""
return np.concatenate(
[sl.Gax(X, ax)[..., np.newaxis] for ax in self.axes] +
[X[..... |
python | def get_mac_address_table_input_request_type_get_interface_based_request_mac_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
input = ET.SubElement(get... |
python | def force_invalidate(self, cache_key):
"""Force-invalidate the cached item."""
try:
if self.cacheable(cache_key):
os.unlink(self._sha_file(cache_key))
except OSError as e:
if e.errno != errno.ENOENT:
raise |
java | protected NoTransactionWrapper getNoTransactionWrapper() {
final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();
if (isTracingEnabled && tc.isEntryEnabled()) {
Tr.entry(this, tc, "getNoTransactionWrapper");
}
if (noTranWrapper == null) {
noTran... |
java | private Duration plus(long secondsToAdd, long nanosToAdd) {
if ((secondsToAdd | nanosToAdd) == 0) {
return this;
}
long epochSec = Jdk8Methods.safeAdd(seconds, secondsToAdd);
epochSec = Jdk8Methods.safeAdd(epochSec, nanosToAdd / NANOS_PER_SECOND);
nanosToAdd = nanosTo... |
python | def not_evaluator(conditions, leaf_evaluator):
""" Evaluates a list of conditions as if the evaluator had been applied
to a single entry and NOT was applied to the result.
Args:
conditions: List of conditions ex: [operand_1, operand_2].
leaf_evaluator: Function which will be called to evaluate leaf condi... |
java | public Path download(Appcast appcast, Path targetDir) throws IOException, Exception {
Path downloaded = null;
Enclosure enclosure = appcast.getLatestEnclosure();
if (enclosure != null) {
String url = enclosure.getUrl();
if (url != null && !url.isEmpty()) {
... |
java | public static Object invokeConstructor(Class<?> clazz, Object... args) {
try {
return InvokerHelper.invokeConstructorOf(clazz, args);
} catch (InvokerInvocationException e) {
ExceptionUtil.sneakyThrow(e.getCause());
return null; // never reached
}
} |
java | public boolean hasField(final String fieldName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredField(fieldName)) {
return true;
}
}
return false;
} |
java | public static Optional<BatchStartedEvent> parse(Event event) {
Matcher matcher = PATTERN.matcher(event.getTag());
if (matcher.matches()) {
return Optional.of(new BatchStartedEvent(matcher.group(1), event.getData(Data.class)));
}
return Optional.empty();
} |
java | void removeConnectionListener(ConnectionManager cm, ConnectionListener cl)
{
if (cmToCl != null && cmToCl.get(cm) != null)
{
cmToCl.get(cm).remove(cl);
clToC.remove(cl);
}
} |
python | def pipeline_refine(d0, candloc, scaledm=2.1, scalepix=2, scaleuv=1.0, chans=[], returndata=False):
"""
Reproduces candidate and potentially improves sensitivity through better DM and imaging parameters.
scale* parameters enhance sensitivity by making refining dmgrid and images.
Other options include: ... |
python | def metric_delete(self, project, metric_name):
"""API call: delete a metric resource.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/delete
:type project: str
:param project: ID of the project containing the metric.
:type metric_name: ... |
python | def _svg_path_convert(paths):
"""
Convert an SVG path string into a Path2D object
Parameters
-------------
paths: list of tuples
Containing (path string, (3,3) matrix)
Returns
-------------
drawing : dict
Kwargs for Path2D constructor
"""
def complex_to_float(values... |
java | protected void collectAccessControls(AccessControlGroup group, Set<AccessControlGroup> toplevelGroups) {
if (!toplevelGroups.contains(group)) {
throw new IllegalStateException("Invalid group not declared as top-level group in schema: " + group);
}
AccessControl old = this.id2nodeMap.put(group.getId()... |
java | public static long sizedelta(final Object base, final Object obj) {
if (null == obj || isSharedFlyweight(obj)) {
return 0;
}
if (null == base) {
throw new IllegalArgumentException("null input: base");
}
final IdentityHashMap visited = new IdentityHashMap(... |
python | def pathways(self, fraction=1.0, maxiter=1000):
r"""Decompose flux network into dominant reaction paths.
Parameters
----------
fraction : float, optional
Fraction of total flux to assemble in pathway decomposition
maxiter : int, optional
Maximum number of... |
python | def getlayer(self, cls, nb=1, _track=None):
"""Return the nb^th layer that is an instance of cls."""
if type(cls) is int:
nb = cls+1
cls = None
if type(cls) is str and "." in cls:
ccls,fld = cls.split(".",1)
else:
ccls,fld = cls,None
... |
python | def map_overlay_forecast(self):
"""Returns capabilities data for forecast map overlays."""
return json.loads(self._query(LAYER, FORECAST, ALL, CAPABILITIES, "").decode(errors="replace")) |
java | public void setCenterColor(Color color) {
if (centerColor == null) {
centerColor = new RGBColor(0.0, 0.0, 0.0);
}
setGradation(true);
this.centerColor = color;
} |
java | private MetaMethod getMethodWithCachingInternal (Class sender, CallSite site, Class [] params) {
if (GroovyCategorySupport.hasCategoryInCurrentThread())
return getMethodWithoutCaching(sender, site.getName (), params, false);
final MetaMethodIndex.Entry e = metaMethodIndex.getMethods(sender,... |
python | def tag(*tags):
'''
Constructs a decorator that tags a function with specified
strings (@tags). The tags on the decorated function are
available via fn.tags
'''
def dfn(fn):
_tags = getattr(fn, 'tags', set())
_tags.update(tags)
fn.tags = _tags
return fn
return... |
java | public void handleError(SelectableChannel channel) {
LOG.info("Handling Error. Cleaning states in HeronClient.");
contextMap.clear();
responseMessageMap.clear();
messageMap.clear();
socketChannelHelper.clear();
nioLooper.removeAllInterest(channel);
try {
channel.close();
LOG.inf... |
java | public static void removeTemporaryType(int type) {
Integer typeInteger = type;
if (DEFAULT_TEMPORARY_HISTORY_TYPES.contains(typeInteger)) {
return;
}
synchronized (TEMPORARY_HISTORY_TYPES) {
TEMPORARY_HISTORY_TYPES.remove(typeInteger);
}
} |
python | def _get_reciprocal(self):
"""Return the :class:`Arrow` that connects my origin and destination
in the opposite direction, if it exists.
"""
orign = self.portal['origin']
destn = self.portal['destination']
if (
destn in self.board.arrow and
... |
python | def list_all_fixed_rate_shippings(cls, **kwargs):
"""List FixedRateShippings
Return a list of FixedRateShippings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_fixed_rate_shippings(a... |
java | private SheetTemplate exportExcelByModuleHandler(String templatePath,
int sheetIndex,
List<?> data,
Map<String, String> extendMap,
... |
python | def validate(self, data, schema):
'''Perform a data validation against a given schema.
:param data: an object to validate
:param schema: a Voluptous schema to validate against
'''
try:
return schema(data)
except MultipleInvalid as ie:
errors = []
... |
java | public static String getManifestXml(byte[] apkData, Locale locale) throws IOException {
try (ByteArrayApkFile apkFile = new ByteArrayApkFile(apkData)) {
apkFile.setPreferredLocale(locale);
return apkFile.getManifestXml();
}
} |
java | public void swapSubstring(BitString other, int start, int length)
{
assertValidIndex(start);
other.assertValidIndex(start);
int word = start / WORD_LENGTH;
int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH;
if (partialWordSize > 0)
{
swap... |
java | public NavPath findPath(float sx, float sy, float tx, float ty, boolean optimize) {
Space source = findSpace(sx,sy);
Space target = findSpace(tx,ty);
if ((source == null) || (target == null)) {
return null;
}
for (int i=0;i<spaces.size();i++) {
((Space) spaces.get(i)).clearCost();
}
target.fil... |
java | private Object loadObjectFromTemporary(String fieldname, String complete) throws Exception {
String realName = fieldname.substring(1);
if (!temporaryFields.containsKey(realName)) {
String message = String.format("The temporary field %s doesn't exist.", complete);
throw new Illega... |
python | def paid_totals_for(self, year, month):
"""Return paid Charges during a certain year, month with total amount, fee and refunded annotated."""
return (
self.during(year, month)
.filter(paid=True)
.aggregate(
total_amount=models.Sum("amount"), total_refunded=models.Sum("amount_refunded")
)
) |
python | def xpath(self, xpath_str):
"""
Override of ``lxml`` _Element.xpath() method to provide standard Open
XML namespace mapping in centralized location.
"""
return super(BaseOxmlElement, self).xpath(
xpath_str, namespaces=_nsmap
) |
java | @Nonnull
public static <T1, T2, R> LBiObjByteFunction<T1, T2, R> biObjByteFunctionFrom(Consumer<LBiObjByteFunctionBuilder<T1, T2, R>> buildingFunction) {
LBiObjByteFunctionBuilder builder = new LBiObjByteFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
python | def size(self):
"""The size of the element."""
size = {}
if self._w3c:
size = self._execute(Command.GET_ELEMENT_RECT)['value']
else:
size = self._execute(Command.GET_ELEMENT_SIZE)['value']
new_size = {"height": size["height"],
"width": ... |
python | def drop(self, table_name = 'dumptruck', if_exists = False, **kwargs):
'Drop a table.'
return self.execute(u'DROP TABLE %s %s;' % ('IF EXISTS' if if_exists else '', quote(table_name)), **kwargs) |
python | def pow2(x: int, p: int) -> int:
"""== pow(x, 2**p, q)"""
while p > 0:
x = x * x % q
p -= 1
return x |
java | public Response deleteTemplate(String id)
throws RequestException, LocalOperationException {
Request request = new Request(this);
return new Response(request.delete("/templates/" + id, new HashMap<String, Object>()));
} |
python | def simple_qa_dataset(
directory='data/',
train=False,
dev=False,
test=False,
extracted_name='SimpleQuestions_v2',
train_filename='annotated_fb_data_train.txt',
dev_filename='annotated_fb_data_valid.txt',
test_filename='annotated_fb_data_test.txt',
... |
java | public Set<PermissionDetails> list(AuthenticatedUser performer, Set<Permission> permissions, IResource resource, String of)
throws RequestValidationException, RequestExecutionException
{
if (!performer.isSuper() && !performer.getName().equals(of))
throw new UnauthorizedException(String.forma... |
python | def range_depth(ranges, size, verbose=True):
"""
Overlay ranges on [start, end], and summarize the ploidy of the intervals.
"""
from jcvi.utils.iter import pairwise
from jcvi.utils.cbook import percentage
# Make endpoints
endpoints = []
for a, b in ranges:
endpoints.append((a, L... |
java | private QrCode.Mode updateModeLogic( QrCode.Mode current , QrCode.Mode candidate )
{
if( current == candidate )
return current;
else if( current == QrCode.Mode.UNKNOWN ) {
return candidate;
} else {
return QrCode.Mode.MIXED;
}
} |
python | def _load_id_or_insert(self, session):
"""Load the id of the temporary context if it exists or return insert args.
As a side effect, this also inserts the Context object for the stableid.
:return: The record of the temporary context to insert.
:rtype: dict
"""
if self.i... |
java | private String getQueue(final Configuration driverConfiguration) {
try {
return Tang.Factory.getTang().newInjector(driverConfiguration).getNamedInstance(JobQueue.class);
} catch (final InjectionException e) {
return this.defaultQueueName;
}
} |
java | void expectExtends(Node n, FunctionType subCtor, FunctionType astSuperCtor) {
if (astSuperCtor == null || (!astSuperCtor.isConstructor() && !astSuperCtor.isInterface())) {
// toMaybeFunctionType failed, or we've got a loose type. Let it go for now.
return;
}
if (astSuperCtor.isConstructor() != ... |
python | def autopilot_version_encode(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid):
'''
Version and capability of autopilot software
cap... |
python | def make_4gaussians_image(noise=True):
"""
Make an example image containing four 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 5 is added to the output image.
Parameters
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.