language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | protected void showApplicationExceptionHandling(ActionRuntime runtime, RuntimeException cause, ActionResponse response) {
logAppEx(cause, () -> {
// not show forwardTo because of forwarding log later
final StringBuilder sb = new StringBuilder();
buildAppExHeader(sb, runtime, ... |
java | public static <T> ObjIntConsumer<T> objIntConsumer(CheckedObjIntConsumer<T> consumer, Consumer<Throwable> handler) {
return (t, u) -> {
try {
consumer.accept(t, u);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalSt... |
java | static void inferStrictRenderUnitNode(
RenderUnitNode node, Inferences inferences, ErrorReporter errorReporter) {
InferenceEngine inferenceEngine = new InferenceEngine(inferences, errorReporter);
// Context started off as startContext and we have propagated context through all of
// node's children, s... |
java | public void initializePlugins(final boolean init_rpcs) {
final String plugin_path = config.getString("tsd.core.plugin_path");
loadPluginPath(plugin_path);
try {
TagVFilter.initializeFilterMap(this);
// @#$@%$%#$ing typed exceptions
} catch (SecurityException e) {
throw new RuntimeExce... |
python | def _filter_nonextensions(cls, obj):
"""Remove all classes marked as not extensions.
This allows us to have a deeper hierarchy of classes than just
one base class that is filtered by _filter_subclasses. Any
class can define a class propery named:
__NO_EXTENSION__ = True
... |
python | def add_text(self, text, x, y, side='left', size=None,
rotation=None, ha='left', va='center',
family=None, **kws):
"""add text at supplied x, y position"""
axes = self.axes
if side == 'right':
axes = self.get_right_axes()
dynamic_size = False... |
java | public GetAccountAuthorizationDetailsResult withGroupDetailList(GroupDetail... groupDetailList) {
if (this.groupDetailList == null) {
setGroupDetailList(new com.amazonaws.internal.SdkInternalList<GroupDetail>(groupDetailList.length));
}
for (GroupDetail ele : groupDetailList) {
... |
java | private static String getCanonicalTypeName(DeclaredType declaredType) {
List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
if (!typeArguments.isEmpty()) {
StringBuilder typeString = new StringBuilder(declaredType.asElement().toString());
typeString.append('<');
for (int i = 0; i < ... |
java | public<V> Future<V> submit(Callable<V> task)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask<V> futureTask = new InternalFutureTask<V>(new FutureTask<V>(task));
executorService.execute(futureTask);
return futureTask;
} |
python | def get_marker_size(self):
"""
Gets the size of a message marker.
:return: QSize
"""
h = self.get_marker_height()
if h < 1:
h = 1
return QtCore.QSize(self.sizeHint().width() / 2, h) |
java | public static void zipDir(final File srcDir, final String destPath, final File destFile) throws IOException {
zipDir(srcDir, null, destPath, destFile);
} |
java | public static HashMap<String, HashMap<String, Float>> getHypotheses(
BayesianReasonerShanksAgent agent,
HashMap<String, List<String>> queries) throws ShanksException {
return ShanksAgentBayesianReasoningCapability.getHypotheses(
agent.getBayesianNetwork(), queries);
} |
python | def fetch_artifact(self, trial_id, prefix):
"""
Verifies that all children of the artifact prefix path are
available locally. Fetches them if not.
Returns the local path to the given trial's artifacts at the
specified prefix, which is always just
{log_dir}/{trial_id}/{p... |
java | public OperationStatusResponseInner beginDeallocate(String resourceGroupName, String vmScaleSetName, String instanceId) {
return beginDeallocateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceId).toBlocking().single().body();
} |
java | public void setToDefaults() {
this.buffer = new StringBuffer();
//this.data = null;
this.width = null;
this.height = null;
this.desiredWidth = null;
this.desiredHeight = null;
this.scaleX = Integer.valueOf(100);
this.scaleY = Integer.valueOf(100);
this.scaled = null;
this.inlinePicture = Boolean.FA... |
python | def save(self, filename, wildcard='*', verbose=False):
'''save parameters to a file'''
f = open(filename, mode='w')
k = list(self.keys())
k.sort()
count = 0
for p in k:
if p and fnmatch.fnmatch(str(p).upper(), wildcard.upper()):
f.write("%-16.1... |
python | def parse_text(file_name):
"""Parse data from Ohio State University text mocap files (http://accad.osu.edu/research/mocap/mocap_data.htm)."""
# Read the header
fid = open(file_name, 'r')
point_names = np.array(fid.readline().split())[2:-1:3]
fid.close()
for i in range(len(point_names)):
... |
python | def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True):
'''return an RGB image for an area of land, with ground_width
in meters, and width/height in pixels.
lat/lon is the top left corner. The zoom is automatically
chosen to avoid having to grow the tile... |
java | private void shuffleAndFilterInstances(Map<String, VipIndexSupport> srcMap, boolean filterUpInstances) {
Random shuffleRandom = new Random();
for (Map.Entry<String, VipIndexSupport> entries : srcMap.entrySet()) {
VipIndexSupport vipIndexSupport = entries.getValue();
AbstractQueu... |
java | public AppHelper setArguments(String[] args)
{
for(int i=0;i<args.length;i++)
{
if (args[i].equals("--help"))
{
printUsage();
System.exit(0);
}
else
{
boolean isValid = false;
... |
java | private void closeCallback(AddOnModel addOnModel, IzouSoundLine izouSoundLine) {
debug("removing soundline " + izouSoundLine + " from " + addOnModel);
Predicate<WeakReference<IzouSoundLineBaseClass>> removeFromList =
weakReference -> weakReference.get() != null && weakReference.get().equ... |
python | def parse(self):
"""Parse our data file and return a :class:`DatFile` or raise :exc:`ParseException`."""
log.debug("Parsing Compass .DAT file %s ...", self.datfilename)
datobj = DatFile(name_from_filename(self.datfilename), filename=self.datfilename)
with codecs.open(self.datfilename, '... |
java | @Override
public Iterator<Map.Entry<String, Order>> iterator() {
return sortOrder.entrySet().iterator();
} |
python | def linkorcopy(src, dst):
"""Hardlink src file to dst if possible, otherwise copy."""
if not os.path.isfile(src):
raise error.ButcherError('linkorcopy called with non-file source. '
'(src: %s dst: %s)' % src, dst)
elif os.path.isdir(dst):
dst = os.path.join(... |
python | def keys_create(gandi, fqdn, flag):
"""Create key for a domain."""
key_info = gandi.dns.keys_create(fqdn, int(flag))
output_keys = ['uuid', 'algorithm', 'algorithm_name', 'ds', 'fingerprint',
'public_key', 'flags', 'tag', 'status']
output_generic(gandi, key_info, output_keys, justify... |
java | private void generateLabel() {
HTML labelWidget = new HTML("<div class=\"" + formCss().label() + "\">" + m_label + "</div>");
addLabelHoverHandler(labelWidget);
m_widgetHolder.add(labelWidget);
} |
python | def find_names(node):
"""Return the unique :class:`ast.Name` instances in an AST.
Parameters
----------
node : ast.AST
Returns
-------
unique_names : List[ast.Name]
Examples
--------
>>> import ast
>>> node = ast.parse('a + b')
>>> names = find_names(node)
>>> name... |
java | public static boolean importFeatureCollection( ASpatialDb db, SimpleFeatureCollection featureCollection, String tableName,
int limit, IHMProgressMonitor pm ) throws Exception {
boolean noErrors = true;
SimpleFeatureType schema = featureCollection.getSchema();
List<AttributeDescriptor... |
java | @Nonnull
public static LLongToIntFunction longToIntFunctionFrom(Consumer<LLongToIntFunctionBuilder> buildingFunction) {
LLongToIntFunctionBuilder builder = new LLongToIntFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
java | public static auditmessages[] get_filtered(nitro_service service, String filter) throws Exception{
auditmessages obj = new auditmessages();
options option = new options();
option.set_filter(filter);
auditmessages[] response = (auditmessages[]) obj.getfiltered(service, option);
return response;
} |
java | public InventoryAggregator withGroups(InventoryGroup... groups) {
if (this.groups == null) {
setGroups(new com.amazonaws.internal.SdkInternalList<InventoryGroup>(groups.length));
}
for (InventoryGroup ele : groups) {
this.groups.add(ele);
}
return this;
... |
java | private static void serializeFsPermissions(State state, String key, FsPermission fsPermissions) {
state.setProp(key, String.format("%04o", fsPermissions.toShort()));
} |
java | @Override
public boolean apply(final HttpResponse httpResponse) {
try {
final InputStream content = httpResponse.getEntity().getContent();
int count = 0;
for(int i = BINARY_CHECK_SCAN_LENGTH; i-- != 0;) {
final int b = content.read();
if (b == -1) return false;
if (b == 0 && ++count == THRESHOLD... |
java | public XMLGregorianCalendar buildXMLGregorianCalendarDate(XMLGregorianCalendar cal) {
XMLGregorianCalendar result = null;
if (cal != null) {
result = newXMLGregorianCalendar(cal.getDay(), cal.getMonth(), cal.getYear());
}
return result;
} |
python | def to_bam(in_file, out_file, data):
"""Convert CRAM file into BAM.
"""
if not utils.file_uptodate(out_file, in_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["samtools", "view", "-O", "BAM", "-o", tx_out_file, in_file]
do.run(cmd, "Convert CRAM to BAM")
... |
java | public com.google.protobuf.ByteString
getSourceHostBytes() {
java.lang.Object ref = sourceHost_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
sourceHost_ = b;
retur... |
python | def get_rt(self):
"""Returns the right top border of the cell"""
cell_above_right = CellBorders(self.cell_attributes,
*self.cell.get_above_right_key_rect())
return cell_above_right.get_b() |
python | def normalize_exception(self, space):
"""Normalize the OperationError. In other words, fix w_type and/or
w_value to make sure that the __class__ of w_value is exactly w_type.
"""
#
# This method covers all ways in which the Python statement
# "raise X, Y" can produce a v... |
java | public ApiSuccessResponse submitFeedback(SubmitFeedbackData submitFeedbackData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = submitFeedbackWithHttpInfo(submitFeedbackData);
return resp.getData();
} |
java | private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)
{
if (!timeTakenByPhase.containsKey(phase))
{
RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,
RulePhaseExecutionStatisticsModel.... |
java | protected void initDelegate(boolean require) throws PortletException {
final ApplicationContext wac = findWebApplicationContext();
PortletFilter delegate = null;
//Check if initialization is complete
this.delegateReadLock.lock();
try {
delegate = this.delegate;
... |
python | def get_file_status(self, path, **kwargs):
"""Return a :py:class:`FileStatus` object that represents the path."""
return FileStatus(**_json(self._get(path, 'GETFILESTATUS', **kwargs))['FileStatus']) |
python | def _compute_projection_pick(artist, path, xy):
"""
Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* i... |
python | def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
nonzero_px = np.where(np.sum(self.raw_data, axis=2) > 0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
... |
java | public void addStatsError(boolean moreResultAvailable) {
if (cmdInformation == null) {
if (batch) {
cmdInformation = new CmdInformationBatch(expectedSize, autoIncrement);
} else if (moreResultAvailable) {
cmdInformation = new CmdInformationMultiple(expectedSize, autoIncrement);
} e... |
python | def read_until_regex(self, regex: bytes, max_bytes: int = None) -> Awaitable[bytes]:
"""Asynchronously read until we have matched the given regex.
The result includes the data that matches the regex and anything
that came before it.
If ``max_bytes`` is not None, the connection will be ... |
python | def word_vec(self, word, use_norm=False):
"""
Accept a single word as input.
Returns the word's representations in vector space, as a 1D numpy array.
If `use_norm` is True, returns the normalized word vector.
Example::
>>> trained_model['office']
array([ -1.40... |
java | public static Long getLong(String nm, Long val) {
String v = null;
try {
v = System.getProperty(nm);
} catch (IllegalArgumentException | NullPointerException e) {
}
if (v != null) {
try {
return Long.decode(v);
} catch (NumberFo... |
python | def validate_day(year, month, day):
"""Validate day."""
max_days = LONG_MONTH
if month == FEB:
max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH
elif month in MONTHS_30:
max_days = SHORT_MONTH
return ... |
java | void saveNamespace(boolean force, boolean uncompressed) throws AccessControlException, IOException {
LOG.info("Saving namespace");
writeLock();
try {
checkSuperuserPrivilege();
if(!force && !isInSafeMode()) {
throw new IOException("Safe mode should be turned ON " +
"in order to... |
java | public static Bean create(final BeanId id) {
Preconditions.checkNotNull(id);
Bean bean = new Bean(id);
bean.set(id.getSchema());
return bean;
} |
python | def nearest_neighbors(query_pts, target_pts=None, metric='euclidean',
k=None, epsilon=None, return_dists=False,
precomputed=False):
'''Find nearest neighbors of query points from a matrix of target points.
Returns a list of indices of neighboring points, one list pe... |
java | public String convertFNCYftUnitsToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
python | def var(names, **args):
"""
Create symbols and inject them into the global namespace.
INPUT:
- s -- a string, either a single variable name, or
- a space separated list of variable names, or
- a list of variable names.
This calls :func:`symbols` with the same... |
java | public static Template getFileTemplate(String dir, String templateFileName) {
return getTemplate(createFileGroupTemplate(dir), templateFileName);
} |
python | def format(self):
"""
Crop and resize the supplied image. Return the image and the crop_box used.
If the input format is JPEG and in EXIF there is information about rotation, use it and rotate resulting image.
"""
if hasattr(self.image, '_getexif'):
self.rotate_exif()... |
java | public final String getString(final String pNm) throws ExceptionWithCode {
if (this.strs != null && this.strs.keySet().contains(pNm)) {
return this.strs.get(pNm);
}
if (this.idStrs != null && this.idStrs.keySet().contains(pNm)) {
return this.idStrs.get(pNm);
}
throw new ExceptionWithCode... |
java | public static Expression getByName(final String function) {
final Expression expression = available_functions.get(function);
if (expression == null) {
throw new UnsupportedOperationException("Function " + function
+ " has not been implemented");
}
return expression;
} |
python | def check_manifest(source_tree='.', create=False, update=False,
python=sys.executable):
"""Compare a generated source distribution with list of files in a VCS.
Returns True if the manifest is fine.
"""
all_ok = True
if os.path.sep in python:
python = os.path.abspath(pytho... |
java | public ServiceFuture<List<DomainTopicInner>> listByDomainAsync(String resourceGroupName, String domainName, final ServiceCallback<List<DomainTopicInner>> serviceCallback) {
return ServiceFuture.fromResponse(listByDomainWithServiceResponseAsync(resourceGroupName, domainName), serviceCallback);
} |
java | private void runAlgorithm() {
textLength = initialTypes.length;
// Initialize output types.
// Result types initialized to input types.
resultTypes = (byte[])initialTypes.clone();
// 1) determining the paragraph level
// Rule P1 is the requireme... |
java | protected Stylesheet getStylesheetRoot(StylesheetHandler handler) throws TransformerConfigurationException
{
StylesheetRoot stylesheet;
stylesheet = new StylesheetRoot(handler.getSchema(), handler.getStylesheetProcessor().getErrorListener());
if (handler.getStylesheetProcessor().isSecureProcessing())
... |
java | public Set<OpenPgpV4Fingerprint> getUndecidedFingerprints()
throws IOException, PGPException {
return getFingerprintsOfKeysWithState(getAnyPublicKeys(), OpenPgpTrustStore.Trust.undecided);
} |
java | public void setTags(List<String> tags) {
if (tags == null) {
throw new IllegalArgumentException("Parameter tags must not be null.");
}
for (String tag : tags) {
if (!this.tags.contains(tag)) {
insertTagDb(tag);
}
}
for (String tag : this.tags) {
if (!tags.contains(tag)) {
de... |
java | public double samplePosition(SequenceModel model, int[] sequence, int pos, double temperature) {
double[] distribution = model.scoresOf(sequence, pos);
if (temperature!=1.0) {
if (temperature==0.0) {
// set the max to 1.0
int argmax = ArrayMath.argmax(distribution);
Arrays.fi... |
java | static Mono<Object> decode(HttpResponse httpResponse, SerializerAdapter serializer, HttpResponseDecodeData decodeData) {
Type headerType = decodeData.headersType();
if (headerType == null) {
return Mono.empty();
} else {
return Mono.defer(() -> {
try {
... |
python | def mapped(cls, key='id', **kwargs):
"""Create list of instances from a mapping."""
kwargs.setdefault('metadata', {})
kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
kwargs.setdefault('default', attr.Factory(list))
def converter(value):
"""Convert mapping to a list of instances.... |
java | public Logger getLogger(String name)
{
PaxLogger paxLogger;
if (m_paxLogging == null)
{
paxLogger = FallbackLogFactory.createFallbackLog(null, name);
}
else
{
paxLogger = m_paxLogging.getLogger(name, Slf4jLogger.SLF4J_FQCN);
}
S... |
python | def getclienturl(idclient, *args, **kwargs):
"""Request Clients URL.
If idclient is set, you'll get a response adequate for a MambuClient object.
If not set, you'll get a response adequate for a MambuClients object.
See mambuclient module and pydoc for further information.
Currently implemented fi... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.ENG__PGRP_NAME:
return PGRP_NAME_EDEFAULT == null ? pGrpName != null : !PGRP_NAME_EDEFAULT.equals(pGrpName);
case AfplibPackage.ENG__TRIPLETS:
return triplets != null && !triplets.isEmpty();
}
return super.eIsS... |
java | public Chunk new_close() {
Chunk chk = compress();
if(_vec instanceof AppendableVec)
((AppendableVec)_vec).closeChunk(_cidx,chk._len);
return chk;
} |
java | void addDocument(Document doc) throws IOException
{
update(Collections.<String> emptyList(), Arrays.asList(new Document[]{doc}));
} |
python | def serialize(self, entity, request=None):
""" Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary
"""
def should_we_insert(value, fiel... |
java | private ClassicCounter<Pair<F, L>> convertWeights(ClassicCounter<Integer> weights, Index<F> featureIndex, Index<L> labelIndex, boolean multiclass) {
return multiclass ? convertSVMStructWeights(weights, featureIndex, labelIndex) : convertSVMLightWeights(weights, featureIndex, labelIndex);
} |
python | def get_subscript(self, sub_script_name):
"""
finds the item that contains the sub_script with name sub_script_name
Args:
sub_script_name: name of subscript
Returns: B26QTreeItem in QTreeWidget which is a script
"""
# get tree of item
tree = self.tre... |
python | def device_retrieve(self, id, **kwargs): # noqa: E501
"""Get a devices # noqa: E501
Retrieve information about a specific device. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thre... |
java | public String getDestinationFilename(final DocWorkUnit workUnit) {
return DocletUtils.phpFilenameForClass(workUnit.getClazz(), HelpDoclet.outputFileExtension);
} |
java | static public void main (String[] args) throws Exception {
if (args.length == 0) {
String commandLine = "-f 0 -wi 1 -i 1 -t 1 -w 1s -r 1s " // For developement only (fork 0, short runs).
// + "-bs 2500000 ArrayBenchmark" //
// + "-rf csv FieldSerializerBenchmark.field FieldSerializerBenchmark.tagged" //
/... |
java | public Object eval(String script, Bindings bindings) throws ScriptException {
ScriptContext ctxt = getScriptContext(bindings);
return eval(script, ctxt);
} |
java | @RequestMapping(value = "changelog", method = RequestMethod.GET)
public BuildDiff changeLog(BuildDiffRequest request) {
GitChangeLog changeLog = gitService.changeLog(request);
// Stores in cache
logCache.put(changeLog.getUuid(), changeLog);
// OK
return changeLog;
} |
java | protected String getKey(final String ref, final String filename, final String extension) {
return prefix + ref + "/" + filename + "." + extension;
} |
python | def call(self, func_name, args=None, *,
timeout=-1.0, push_subscribe=False) -> _MethodRet:
"""
Call request coroutine. It is a call with a new behaviour
(return result of a Tarantool procedure is not wrapped into
an extra tuple). If you're connecting to Tarantool... |
java | public void forEachNode(IntProcedure proc, GraphEventType evt) throws ContradictionException {
int type;
if (evt == GraphEventType.REMOVE_NODE) {
type = GraphDelta.NR;
for (int i = frozenFirst[type]; i < frozenLast[type]; i++) {
if (delta.getCause(i, type) != propagator) {
proc.execute(delta.get(i, t... |
python | def get_element(source, path, separator=r'[/.]'):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (string): '/' or '.' string with attribute names
... |
java | static void putLongIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable Long value) {
if (value == null) {
return;
}
try {
jsonObject.put(fieldName, value.longValue());
} catch (JSONExce... |
python | def _get(self, field):
"""
Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================... |
java | @Override
final protected void addRange(int left, int right,
ArrayList<MtasTreeHit<T>> list) {
String key = left + "_" + right;
if (index.containsKey(key)) {
index.get(key).addList(list);
} else {
root = addRange(root, left, right, list);
root.color = IntervalRBTreeNode.BLACK;
... |
java | @Override
public T createMixin(final Elements elems) {
AbstractMixinInitializer initializer = new AbstractMixinInitializer() {
@Override
protected void initialize() {
implement(Object.class).with(elems);
implement(InternalWebElements.class).with(elems)... |
python | def most_common_nucleotides(partitioned_read_sequences):
"""
Find the most common nucleotide at each offset to the left and
right of a variant.
Parameters
----------
partitioned_read_sequences : list of tuples
Each tuple has three elements:
- sequence before mutant nucleotid... |
java | public static boolean report(WsRuntimeFwException ex) {
if (ex.reported) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "previously reported exception", new Exception(ex));
}
return false;
}
ex.reported = tru... |
java | @Override
public void exitScope() {
Map<Key<?>, Object> scopeMap = scopeStackCache.get().peek();
performDisposal(scopeMap);
scopeStackCache.get().pop();
log.debug("Exited scope.");
} |
java | @Test
public void MPJwtNoMpJwtConfig_formLoginInWebXML_mpJwtInApp() throws Exception {
genericLoginConfigFormLoginVariationTest(
MpJwtFatConstants.LOGINCONFIG_FORM_LOGIN_IN_WEB_XML_SERVLET_MP_JWT_IN_APP_ROOT_CONTEXT,
... |
python | def _copy_jsonsafe(value):
"""Deep-copy a value into JSON-safe types.
"""
if isinstance(value, six.string_types + (numbers.Number,)):
return value
if isinstance(value, collections_abc.Mapping):
return {six.text_type(k): _copy_jsonsafe(v) for k, v in value.items()}
if isinstance(value... |
python | def add_document(self, key, url, **kwargs):
"""
Adds document to record
Args:
key (string): document key
url (string): document url
Keyword Args:
description (string): simple description
fulltext (bool): mark if this is a full text
... |
java | public void marshall(GetAliasRequest getAliasRequest, ProtocolMarshaller protocolMarshaller) {
if (getAliasRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getAliasRequest.getFunctionName(),... |
java | private Dimension getDefaultResolution() {
if (getResolution() != null) {
WebcamResolution res = WebcamResolution.valueOf(getResolution());
return res.getSize();
} else {
return new Dimension(getWidth(), getHeight());
}
} |
python | def configure(self, options, conf):
""" Get the options. """
super(S3Logging, self).configure(options, conf)
self.options = options |
python | def load_neurons(neurons,
neuron_loader=load_neuron,
name=None,
population_class=Population,
ignored_exceptions=()):
'''Create a population object from all morphologies in a directory\
of from morphologies in a list of file names
Param... |
python | def properties(self):
"""Return the base station info."""
resource = "basestation"
basestn_event = self.publish_and_get_event(resource)
if basestn_event:
return basestn_event.get('properties')
return None |
java | private CmsListItemWidget createListWidget(CmsGalleryFolderEntry galleryFolder) {
String title;
if (galleryFolder.getOwnProperties().containsKey(CmsClientProperty.PROPERTY_TITLE)) {
title = galleryFolder.getOwnProperties().get(CmsClientProperty.PROPERTY_TITLE).getStructureValue();
}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.