language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | protected void cleanFile(String path) {
try {
PrintWriter writer;
writer = new PrintWriter(path);
writer.print("");
writer.close();
} catch (FileNotFoundException e) {
throw new RuntimeException("An error occurred while cleaning the file: " + e.getMessage(), e);
}
} |
python | def _extract_numbers(arg: Message_T) -> List[float]:
"""Extract all numbers (integers and floats) from a message-like object."""
s = str(arg)
return list(map(float, re.findall(r'[+-]?(\d*\.?\d+|\d+\.?\d*)', s))) |
java | public BigFloat multiply(BigFloat x) {
if (x.isSpecial())
return x.multiply(this);
Context c = max(context, x.context);
return c.valueOf(value.multiply(x.value, c.mathContext));
} |
java | private ARCRecordMetaData computeMetaData(List<String> keys,
List<String> values, String v, String origin,
long offset, final String identifier)
throws IOException {
if (keys.size() != values.size()) {
List<String> originalValues = values;
if (!isStric... |
python | def _augment(graph, capacity, flow, source, target):
"""find a shortest augmenting path
"""
n = len(graph)
A = [0] * n # A[v] = min residual cap. on path source->v
augm_path = [None] * n # None = node was not visited yet
Q = deque() # BFS
Q.append(source)
a... |
java | private boolean performDialogOperation(HttpServletRequest request) throws CmsException {
List<CmsPropertyDefinition> propertyDef = getCms().readAllPropertyDefinitions();
boolean useTempfileProject = Boolean.valueOf(getParamUsetempfileproject()).booleanValue();
try {
if (useTempfileP... |
java | private static ByteBuf writePayload(
final ByteBufAllocator alloc,
final long requestId,
final MessageType messageType,
final byte[] payload) {
final int frameLength = HEADER_LENGTH + REQUEST_ID_SIZE + payload.length;
final ByteBuf buf = alloc.ioBuffer(frameLength + Integer.BYTES);
buf.writeInt(fram... |
java | public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) {
final PathAddress address = PathAddress.EMPTY_ADDRESS;
return new TransformersSubRegistrationImpl(range, domain, address);
} |
python | def _is_viable_phone_number(number):
"""Checks to see if a string could possibly be a phone number.
At the moment, checks to see that the string begins with at least 2
digits, ignoring any punctuation commonly found in phone numbers. This
method does not require the number to be normalized in advance ... |
java | public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options) {
super.initialize(subject, callbackHandler, sharedState, options);
Properties props = loadProperties((String) options.get("file"));
initWithProps(props);
} |
python | def strip_accents(string):
"""
Strip all the accents from the string
"""
return u''.join(
(character for character in unicodedata.normalize('NFD', string)
if unicodedata.category(character) != 'Mn')) |
python | def factorize(
self,
na_sentinel: int = -1,
) -> Tuple[np.ndarray, ABCExtensionArray]:
"""
Encode the extension array as an enumerated type.
Parameters
----------
na_sentinel : int, default -1
Value to use in the `labels` array to indicate... |
python | def add_blacklisted_directories(self,
directories,
remove_from_stored_directories=True):
"""
Adds `directories` to be blacklisted. Blacklisted directories will not
be returned or searched recursively when calling the
... |
python | def _POTUpdateBuilder(env, **kw):
""" Creates `POTUpdate` builder object """
import SCons.Action
from SCons.Tool.GettextCommon import _POTargetFactory
kw['action'] = SCons.Action.Action(_update_pot_file, None)
kw['suffix'] = '$POTSUFFIX'
kw['target_factory'] = _POTargetFactory(env, alias='$POTUP... |
python | def group_batches(xs):
"""Group samples into batches for simultaneous variant calling.
Identify all samples to call together: those in the same batch
and variant caller.
Pull together all BAM files from this batch and process together,
Provide details to pull these finalized files back into individ... |
python | def process_entries(
self, omimids, transform, included_fields=None, graph=None, limit=None,
globaltt=None
):
"""
Given a list of omim ids,
this will use the omim API to fetch the entries, according to the
```included_fields``` passed as a parameter.
I... |
java | private void addEPStatementListener(UpdateListener listener) {
if (this.subscriber == null) {
if (epStatement != null) {
epStatement.addListener(listener);
}
}
} |
java | protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response)
throws IOException, ResourceNotFoundException {
// Send gzipped resource if user agent supports it.
int idx = requestedPath.indexOf(BundleRenderer.GZIP_PATH_PREFIX);
if (idx != -1) {
requestedPath =... |
java | @Help(help = "Get the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id")
public PhysicalNetworkFunctionRecord getPhysicalNetworkFunctionRecord(
final String idNsr, final String idPnfr) throws SDKException {
String url = idNsr + "/pnfrecords" + "/" + idPnfr;
return (PhysicalNetwor... |
python | def _execute_batch(self, actions):
"""
Execute a single batch of Actions.
For each action that has a problem, we annotate the action with the
error information for that action, and we return the number of
successful actions in the batch.
:param actions: the list of Action... |
java | public void setHitCount(IDbgpSession session, int value)
throws CoreException
{
synchronized (sessions)
{
PerSessionInfo info = (PerSessionInfo) sessions.get(session);
if (info == null)
{
info = new PerSessionInfo();
sessions.put(session, info);
}
info.hitCount = value;
}
} |
python | def _add_hash(cls, attrs):
"""
Add a hash method to *cls*.
"""
cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False)
return cls |
python | def CharacterData(self, data):
'''
Expat character data event handler
'''
if data.strip():
data = data.encode()
if not self.data:
self.data = data
else:
self.data += data |
java | private static List<String> maskNull(List<String> pTypes) {
return (pTypes == null) ? Collections.<String>emptyList() : pTypes;
} |
python | def default_token_user_loader(self, token):
"""
Default token user loader
Accepts a token and decodes it checking signature and expiration. Then
loads user by id from the token to see if account is not locked. If
all is good, returns user record, otherwise throws an exception.
... |
python | def _check_install(self):
"""Check if tlgu installed, if not install it."""
try:
subprocess.check_output(['which', 'tlgu'])
except Exception as exc:
logger.info('TLGU not installed: %s', exc)
logger.info('Installing TLGU.')
if not subprocess.check_... |
java | private Set<String> getColumnsOfEmbeddableAndComputeEmbeddableNullness(String embeddable) {
Set<String> columnsOfEmbeddable = new HashSet<String>();
boolean hasOnlyNullColumns = true;
for ( String selectableColumn : columns ) {
if ( !isColumnPartOfEmbeddable( embeddable, selectableColumn ) ) {
continue;
... |
python | def check_role(*roles, **args_map):
"""
It's just like has_role, but it's a decorator. And it'll check request.user
"""
def f1(func, roles=roles):
@wraps(func)
def f2(*args, **kwargs):
from uliweb import request, error
arguments = {}
... |
java | public String applyTransletNamePattern(String transletName, boolean absolutely) {
DefaultSettings defaultSettings = assistantLocal.getDefaultSettings();
if (defaultSettings == null) {
return transletName;
}
if (StringUtils.startsWith(transletName, ActivityContext.NAME_SEPARAT... |
java | protected Message createMessage(ConnectionContext context, BasicMessage basicMessage) throws JMSException {
return createMessage(context, basicMessage, null);
} |
java | public List<CorporationMiningObserverResponse> getCorporationCorporationIdMiningObserversObserverId(
Integer corporationId, Long observerId, String datasource, String ifNoneMatch, Integer page, String token)
throws ApiException {
ApiResponse<List<CorporationMiningObserverResponse>> resp ... |
python | def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None,
region=None, key=None, keyid=None, profile=None):
'''
List objects in a given S3 bucket.
Returns a list of objects.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.list_object... |
java | public boolean validateModcaString4(String modcaString4, DiagnosticChain diagnostics, Map<Object, Object> context) {
boolean result = validateModcaString4_MinLength(modcaString4, diagnostics, context);
if (result || diagnostics != null) result &= validateModcaString4_MaxLength(modcaString4, diagnostics, context);
... |
java | public static JSONObject loadPublicJSONFile(final String publicDirectory, final String file) {
final File dir = Environment.getExternalStoragePublicDirectory(publicDirectory);
return loadJSONFile(dir, file);
} |
java | public void marshall(Service service, ProtocolMarshaller protocolMarshaller) {
if (service == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(service.getId(), ID_BINDING);
protocolMarshall... |
java | static public String toUri(Object o)
{
if (o == null)
{
return null;
}
String uri = o.toString();
if (uri.startsWith("/"))
{
// Treat two slashes as server-relative
if (uri.startsWith("//"))
{
uri = uri.substring(1);
}
... |
python | def _handle_cancel_notification(self, msg_id):
"""Handle a cancel notification from the client."""
request_future = self._client_request_futures.pop(msg_id, None)
if not request_future:
log.warn("Received cancel notification for unknown message id %s", msg_id)
return
... |
java | public void createCertificate(InputStream certStream) throws BatchErrorException, IOException, CertificateException, NoSuchAlgorithmException {
createCertificate(certStream, null);
} |
java | public static <T> T fromJson(String json, Class<T> T) {
return getGson().fromJson(json, T);
} |
java | public AptControlInterface getMostDerivedInterface()
{
//
// Walk up ControlInterface chain looking for the 1st instance annotated
// w/ @ControlInterface (as opposed to @ControlExtension)
//
// REVIEW: TBD rules for inheritance of @ControlInterface will affect this.
... |
java | public GedRenderer<? extends GedObject> create(
final GedObject gedObject,
final RenderingContext renderingContext) {
if (gedObject != null) {
final RendererBuilder builder = builders.get(gedObject.getClass());
if (builder != null) {
return builder... |
python | def call_api_fetch(self, params, get_latest_only=True):
"""
GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1
Host: myserver
Accept: application / json"""
output_format = 'application/json'
... |
python | def has_connection(graph, A, B):
r"""Check if the given graph contains a path connecting A and B.
Parameters
----------
graph : scipy.sparse matrix
Adjacency matrix of the graph
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
... |
java | private static StartupInfo parseArguments(String args[]) {
InstanceId instance = InstanceId.NODEZERO;
StartupOption startOpt = StartupOption.REGULAR;
boolean isStandby= false;
String serviceName = null;
boolean force = false;
int argsLen = (args == null) ? 0 : args.length;
for (int i=0; i < ... |
java | public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) {
if (node.getKind() != Kind.ANNOTATION) return false;
return typeMatches(type, node, ((JCAnnotation) node.get()).annotationType);
} |
python | def commit(self, message, files=None):
"""Run git-commit."""
if files:
self.add(*files)
return _run_command(["git", "commit", "-m", f'"{message}"']) |
python | def credit_card_security_code(self, card_type=None):
""" Returns a security code string. """
sec_len = self._credit_card_type(card_type).security_code_length
return self.numerify('#' * sec_len) |
python | def fix_jumps(self, row_selected, delta):
'''fix up jumps when we add/remove rows'''
numrows = self.grid_mission.GetNumberRows()
for row in range(numrows):
command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL)
if command in ["DO_JUMP", "DO_CONDITION_JUMP"]:
... |
python | def convolve_map(m, k, cpix, threshold=0.001, imin=0, imax=None, wmap=None):
"""
Perform an energy-dependent convolution on a sequence of 2-D spatial maps.
Parameters
----------
m : `~numpy.ndarray`
3-D map containing a sequence of 2-D spatial maps. First
dimension should be energy.... |
python | def recruitment(temporalcommunities, staticcommunities):
"""
Calculates recruitment coefficient for each node. Recruitment coefficient is the average probability of nodes from the
same static communities being in the same temporal communities at other time-points or during different tasks.
Parameters... |
python | def _enum_from_op_string(op_string):
"""Convert a string representation of a binary operator to an enum.
These enums come from the protobuf message definition
``StructuredQuery.FieldFilter.Operator``.
Args:
op_string (str): A comparison operation in the form of a string.
Acceptable... |
python | def variable_name_from_full_name(full_name):
"""Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-con... |
java | public String getStringValue(String property) {
final List<JawrConfigManagerMBean> mBeans = getInitializedConfigurationManagers();
try {
if (mBeans.size() == 3) {
if (areEquals(getProperty(jsMBean, property), getProperty(cssMBean, property),
getProperty(binaryMBean, property))) {
return getPro... |
java | public String buildCheckboxEnableNotification() {
String propVal = null;
if (!isMultiOperation()) {
// get current settings for single resource dialog
try {
propVal = getCms().readPropertyObject(
getParamResource(),
CmsProp... |
java | private T checkHealthyAndRetry(T resource, long endTimeMs) throws TimeoutException, IOException {
if (isHealthy(resource)) {
return resource;
} else {
LOG.info("Clearing unhealthy resource {}.", resource);
remove(resource);
closeResource(resource);
return acquire(endTimeMs - mClock... |
python | def header_encode_lines(self, string, maxlengths):
"""Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must ... |
java | protected long loadAll( NodeSequence sequence,
QueueBuffer<BufferedRow> buffer,
AtomicLong batchSize ) {
return loadAll(sequence, buffer, batchSize, null, 0);
} |
java | private DiffPart decodeCut(final int blockSize_S, final int blockSize_E,
final int blockSize_B)
throws DecodingException
{
if (blockSize_S < 1 || blockSize_E < 1 || blockSize_B < 1) {
throw new DecodingException("Invalid value for blockSize_S: "
+ blockSize_S + ", blockSize_E: " + blockSize_E
+ " ... |
python | def find_processes_by_filename(self, fileName):
"""
@type fileName: str
@param fileName: Filename to search for.
If it's a full pathname, the match must be exact.
If it's a base filename only, the file part is matched,
regardless of the directory where it's l... |
python | def fetch(self, **kwargs) -> 'FetchContextManager':
'''
Sends the request to the server and reads the response.
You may use this method either with plain synchronous Session or
AsyncSession. Both the followings patterns are valid:
.. code-block:: python3
from ai.bac... |
java | @Inject(optional = true)
protected Pattern setEndTag(@Named(AbstractMultiLineCommentProvider.END_TAG) final String endTag) {
return this.endTagPattern = Pattern.compile((endTag + "\\z"));
} |
python | def _purge_expired(self):
"""
Remove all expired entries from the cache that do not have a reference
count.
"""
time_horizon = time.time() - self._keep_time
new_cache = {}
dec_count_for = []
for (k, v) in self._cache.items():
if v.count > 0:
... |
python | def postings(self, quarter, stats_counter=None):
"""Yield job postings in common schema format
Args:
quarter (str) The quarter, in format '2015Q1'
stats_counter (object, optional) A counter that can track both
input and output documents using a 'track' method.
... |
python | def nacm_enable_nacm(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
enable_nacm = ET.SubElement(nacm, "enable-nacm")
enable_nacm.text = kwargs.pop('enable... |
python | def check_arguments(self):
"""Make sure all arguments have a specification"""
for name, default in self.argdict.items():
if name not in self.names and default is NODEFAULT:
raise NameError('Missing argparse specification for %r' % name) |
python | def __load_profile(self, profile, uuid, verbose):
"""Create a new profile when the unique identity does not have any."""
def is_empty_profile(prf):
return not (prf.name or prf.email or
prf.gender or prf.gender_acc or
prf.is_bot or prf.country_... |
python | def getRegistrationReferralCounts(startDate,endDate):
'''
When a user accesses the class registration page through a
referral URL, the marketing_id gets saved in the extra JSON
data associated with that registration. This just returns
counts associated with how often given referral terms appear
... |
java | @Override
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
throws SAXException {
if (isParsing || qName.equals(currentRoot)) {
isParsing = true;
currentNode = new XMLNode(currentNode, qName);
for (int i = 0; i < attrs... |
python | def prepend(self, key, val, time=0, min_compress_len=0):
'''Prepend the value to the beginning of the existing key's value.
Only stores in memcache if key already exists.
Also see L{append}.
@return: Nonzero on success.
@rtype: int
'''
return self._set("prepend"... |
java | @Override
public int compareTo(Days otherAmount) {
int thisValue = this.days;
int otherValue = otherAmount.days;
return Integer.compare(thisValue, otherValue);
} |
python | def main():
"""Command-Mode: Retrieve and display data then process commands."""
(cred, providers) = config_read()
cmd_mode = True
conn_objs = cld.get_conns(cred, providers)
while cmd_mode:
nodes = cld.get_data(conn_objs, providers)
node_dict = make_node_dict(nodes, "name")
i... |
java | public Future<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit);... |
java | private ExpressionAndSubstitution convertIntoExpressionAndSubstitution(ImmutableExpression expression,
ImmutableSet<Variable> nonLiftableVariables)
throws UnsatisfiableConditionException {
ImmutableSet<Immut... |
python | def rotate(self, pitch, roll, yaw):
"""
Rotate the gimbal to a specific vector.
.. code-block:: python
#Point the gimbal straight down
vehicle.gimbal.rotate(-90, 0, 0)
:param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude... |
java | public static void notNull(Object parameter, String name, Object... args) throws IllegalArgumentException {
if (parameter == null) {
throw new IllegalArgumentException(String.format(name, args) + " parameter is null.");
}
} |
java | private byte[] xor(final byte[] input) {
final byte[] output = new byte[input.length];
if (this.secret.length == 0) {
System.arraycopy(input, 0, output, 0, input.length);
} else {
int spos = 0;
for (int pos = 0; pos < input.length; ++pos) {
out... |
java | @Override
public String getServletPath() {
// unwrap the request to prevent multiple unneeded attempts to generate missing JSP files
// m_controller.getTopRequest() does not return the right request here when forwarding
// this method is generally called exactly once per request on differen... |
python | def check_yaml_configs(configs, key):
"""Get a diagnostic for the yaml *configs*.
*key* is the section to look for to get a name for the config at hand.
"""
diagnostic = {}
for i in configs:
for fname in i:
with open(fname) as stream:
try:
res... |
java | public static long castToIntegral(Decimal dec) {
BigDecimal bd = dec.toBigDecimal();
// rounding down. This is consistent with float=>int,
// and consistent with SQLServer, Spark.
bd = bd.setScale(0, RoundingMode.DOWN);
return bd.longValue();
} |
python | def getPixelValue(self, x, y):
"""Get the value of a pixel from the data, handling voids in the
SRTM data."""
assert x < self.size, "x: %d<%d" % (x, self.size)
assert y < self.size, "y: %d<%d" % (y, self.size)
# Same as calcOffset, inlined for performance reasons
offs... |
python | def __substituteFromClientStatement(self,match,prevResponse,extraSymbol="",sessionID = "general"):
"""
Substitute from Client statement into respose
"""
prev = 0
startPadding = 1+len(extraSymbol)
finalResponse = ""
for m in re.finditer(r'%'+extraSymbol+'[0-9]+', p... |
java | @Override
protected void initParser() throws MtasConfigException {
super.initParser();
if (config != null) {
// always word, no mappings
wordType = new MtasParserType<>(MAPPING_TYPE_WORD, null, false);
for (int i = 0; i < config.children.size(); i++) {
MtasConfiguration current = c... |
python | def add_reference_context_args(parser):
"""
Extends an ArgumentParser instance with the following commandline arguments:
--context-size
"""
reference_context_group = parser.add_argument_group("Reference Transcripts")
parser.add_argument(
"--context-size",
default=CDNA_CONTEXT... |
java | public static Basic2DMatrix constant(int rows, int columns, double constant) {
double[][] array = new double[rows][columns];
for (int i = 0; i < rows; i++) {
Arrays.fill(array[i], constant);
}
return new Basic2DMatrix(array);
} |
python | def rogers_huff_r(gn):
"""Estimate the linkage disequilibrium parameter *r* for each pair of
variants using the method of Rogers and Huff (2008).
Parameters
----------
gn : array_like, int8, shape (n_variants, n_samples)
Diploid genotypes at biallelic variants, coded as the number of
... |
java | public MarkedSection addMarkedSection() {
MarkedSection section = new MarkedSection(new Section(null, numberDepth + 1));
add(section);
return section;
} |
java | private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings)
throws IOException
{
final String outputDirectory = settings.getOutputDirectory();
final String fileName = type.getName() + settings.getLanguage().getFileExten... |
java | @VisibleForTesting
protected static Dimension getMaxLabelSize(final ScaleBarRenderSettings settings) {
float maxLabelHeight = 0.0f;
float maxLabelWidth = 0.0f;
for (final Label label: settings.getLabels()) {
maxLabelHeight = Math.max(maxLabelHeight, label.getHeight());
... |
java | public static void eachByte(Path self, int bufferLen, @ClosureParams(value = FromString.class, options = "byte[],Integer") Closure closure) throws IOException {
BufferedInputStream is = newInputStream(self);
IOGroovyMethods.eachByte(is, bufferLen, closure);
} |
java | public void setActionNames(java.util.Collection<String> actionNames) {
if (actionNames == null) {
this.actionNames = null;
return;
}
this.actionNames = new com.amazonaws.internal.SdkInternalList<String>(actionNames);
} |
java | public JType []getActualTypeArguments()
{
Type []rawArgs = _type.getActualTypeArguments();
JType []args = new JType[rawArgs.length];
for (int i = 0; i < args.length; i++) {
Type type = rawArgs[i];
if (type instanceof Class) {
args[i] = _loader.forName(((Class) type).getName());
... |
python | def import_element(self, xml_element):
"""
Imports the element from an lxml element and loads its content.
"""
super(HTMLElement, self).import_element(xml_element)
self.content = self.get_html_content() |
python | def backward(ctx, grad_output):
"""
In the backward pass, we set the gradient to 1 for the winning units, and 0
for the others.
"""
batchSize = grad_output.shape[0]
indices, = ctx.saved_tensors
g = grad_output.reshape((batchSize, -1))
grad_x = torch.zeros_like(g, requires_grad=False)
... |
java | private String toDN(String username)
{
String userDN = new StringBuilder(userDnPrefix).append(username).append(this.userDnSuffix).toString();
return userDN;
} |
java | public void debug(Object message, Throwable t) {
doLog(Level.DEBUG, FQCN, message, null, t);
} |
java | public List<String> getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
final String[] names = getFile(mountPoint, target).list();
return names == null ? Collections.<String>emptyList() : Arrays.asList(names);
} |
python | def get_instance(self, payload):
"""
Build an instance of SyncListInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.sync.v1.service.sync_list.SyncListInstance
:rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance
"""
retu... |
python | def position_with_ref(msg, lat_ref, lon_ref):
"""Decode position with only one message,
knowing reference nearby location, such as previously
calculated location, ground station, or airport location, etc.
Works with both airborne and surface position messages.
The reference position shall be with in... |
python | def convert_decimal(value, parameter):
'''
Converts to decimal.Decimal:
'', '-', None convert to parameter default
Anything else uses Decimal constructor
'''
value = _check_default(value, parameter, ( '', '-', None ))
if value is None or isinstance(value, decimal.Decimal):
re... |
java | @SneakyThrows
public static String dumps(@NonNull Map<String, ?> map) {
Resource strResource = new StringResource();
try (JsonWriter writer = new JsonWriter(strResource)) {
writer.beginDocument();
for (Map.Entry<String, ?> entry : map.entrySet()) {
writer.property(entry.getK... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.