language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def depthtospace(attrs, inputs, proto_obj):
"""Rearranges data from depth into blocks of spatial data."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'blocksize':'block_size'})
return "depth_to_space", new_attrs, inputs |
python | def download_channel_image_file(self, channel_name, plate_name,
well_name, well_pos_y, well_pos_x, cycle_index,
tpoint, zplane, correct, align, directory):
'''Downloads a channel image and writes it to a `PNG` file on disk.
Parameters
----------
channel_name: str... |
python | def get_archives(self, title_id, language_code):
"""Get the archive list from a given `title_id` and `language_code`.
:param int title_id: title id.
:param int language_code: language code.
:return: the archives.
:rtype: list of :class:`LegendasTVArchive`
"""
lo... |
java | public INode[] getExistingPathINodes(String path) {
byte[][] components = getPathComponents(path);
INode[] inodes = new INode[components.length];
this.getExistingPathINodes(components, inodes);
return inodes;
} |
java | protected final boolean matchString(int state, char expected[]) throws Exception{
int length = expected.length;
while(state<length && position<limit){
if(input[position]!=expected[state])
throw expected(codePoint(), new String(new int[]{ Character.codePointAt(expected, state... |
python | def write_single_response(self, response_obj):
"""
Writes a json rpc response ``{"result": result, "error": error, "id": id}``.
If the ``id`` is ``None``, the response will not contain an ``id`` field.
The response is sent to the client as an ``application/json`` response. Only one call ... |
java | @SuppressWarnings({ "unchecked" })
public <VV> EntryStream<K, VV> selectValues(Class<VV> clazz) {
return (EntryStream<K, VV>) filter(e -> clazz.isInstance(e.getValue()));
} |
java | public SAXParseException[] getXMLWarnings() {
if (mWarnings == null) {
return null;
}
return (SAXParseException[]) mWarnings.toArray(new SAXParseException[mWarnings.size()]);
} |
python | def _get_block_header(self, block_hash, num):
"""Get block header by block header hash & number.
:param block_hash:
:param num:
:return:
"""
header_key = header_prefix + num + block_hash
block_header_data = self.db.get(header_key)
header = rlp.decode(blo... |
python | def from_jd(jd: float, fmt: str = 'jd') -> datetime:
"""
Converts a Julian Date to a datetime object.
Algorithm is from Fliegel and van Flandern (1968)
Parameters
----------
jd: float
Julian Date as type specified in the string fmt
fmt: str
Returns
-------
dt: datetime... |
python | def decode_solution(self, encoded_solution):
"""Return solution from an encoded representation."""
return self._decode_function(encoded_solution, *self._decode_args,
**self._decode_kwargs) |
java | protected String getArgumentValue(String arg, String[] args, String defalt) {
String argName = getArgName(arg);
for (int i = 1; i < args.length; i++) {
String currentArgName = getArgName(args[i]); // return what's to left of = if there is one
if (currentArgName.equalsIgnoreCase(a... |
java | public List<CmsGroup> getGroups(
CmsDbContext dbc,
CmsOrganizationalUnit orgUnit,
boolean includeSubOus,
boolean readRoles)
throws CmsException {
return getUserDriver(dbc).getGroups(dbc, orgUnit, includeSubOus, readRoles);
} |
python | def _known_stale(self):
"""
The commit is known to be from a file (and therefore stale) if a
SHA is supplied by git archive and doesn't match the parsed commit.
"""
if self._output_from_file() is None:
commit = None
else:
commit = self.commit
... |
python | def CreateBitmap(self, artid, client, size):
"""Adds custom images to Artprovider"""
if artid in self.extra_icons:
return wx.Bitmap(self.extra_icons[artid], wx.BITMAP_TYPE_ANY)
else:
return wx.ArtProvider.GetBitmap(artid, client, size) |
java | private Deferred<ChannelBuffer> serialize() throws Exception {
final long start = System.currentTimeMillis();
// buffers and an array list to stored the deferreds
final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
final OutputStream output_stream = new ChannelBufferOutputStream(response);
... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/waterbody/1.0", name = "WaterGroundSurface", substitutionHeadNamespace = "http://www.opengis.net/citygml/waterbody/1.0", substitutionHeadName = "_WaterBoundarySurface")
public JAXBElement<WaterGroundSurfaceType> createWaterGroundSurface(WaterGroundSurfaceT... |
java | public void execute()
throws MojoExecutionException {
if (watchFilter == null) {
removeFromWatching();
}
NPM.npm(this, name, version).execute(
binary != null ? binary : name, arguments);
} |
java | public static Object evaluateAsObject(Node node, String xPathExpression, NamespaceContext nsContext, QName resultType) {
return evaluateExpression(node, xPathExpression, nsContext, resultType);
} |
python | def attr_fill_null(args):
"""
Assign the null sentinel value for all entities which do not have a value
for the given attributes.
see gs://broad-institute-gdac/GDAC_FC_NULL for more details
"""
NULL_SENTINEL = "gs://broad-institute-gdac/GDAC_FC_NULL"
attrs = args.attributes
if not attr... |
python | def create_restore_point(self, name=None):
'''Creating a configuration restore point.
Parameters
----------
name : str
Name of the restore point. If not given, a md5 hash will be generated.
'''
if name is None:
for i in iter(int, 1):
... |
java | protected IPortletRenderExecutionWorker startPortletRenderInternal(
IPortletWindowId portletWindowId,
HttpServletRequest request,
HttpServletResponse response) {
// first check to see if there is a Throwable in the session for this IPortletWindowId
final Map<IPortletW... |
python | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w... |
python | def _new(self, src_path, dry_run=False, remove_uploaded=False):
'Code to upload'
# are we getting a symbolic link?
if os.path.islink(src_path):
sourcefile = os.path.normpath(os.path.join(self.topdir, os.readlink(src_path)))
if not os.path.exists(source... |
java | public static int requireNonNegative(int i, String message) {
Objects.requireNonNull(message, "message must not be null");
if (i < 0) {
throw new IllegalArgumentException(message);
}
return i;
} |
java | public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure)
{
if (iterable instanceof InternalIterable)
{
((InternalIterable<T>) iterable).forEach(procedure);
}
else if (iterable instanceof ArrayList)
{
ArrayListIterate.forEach... |
python | def get_server_capabilities(self):
"""Get hardware properties which can be used for scheduling
:return: a dictionary of server capabilities.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
... |
python | def roles_required(*roles):
"""Decorator which specifies that a user must have all the specified roles.
Example::
@app.route('/dashboard')
@roles_required('admin', 'editor')
def dashboard():
return 'Dashboard'
The current user must have both the `admin` role and `editor... |
python | def reverse(
self,
query,
exactly_one=DEFAULT_SENTINEL,
timeout=DEFAULT_SENTINEL,
kind=None,
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-reada... |
python | def _get_package_data():
"""
Import a set of important packages and return relevant data about them in a
dict.
Imports are done in here to avoid potential for circular imports and other
problems, and to make iteration simpler.
"""
moddata = []
modlist = (
"click",
"config... |
python | def cumulative_value(self, slip, mmax, mag_value, bbar, dbar, beta):
'''
Returns the rate of events with M > mag_value
:param float slip:
Slip rate in mm/yr
:param float mmax:
Maximum magnitude
:param float mag_value:
Magnitude value
:... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.BII__IMO_NAME:
return IMO_NAME_EDEFAULT == null ? imoName != null : !IMO_NAME_EDEFAULT.equals(imoName);
}
return super.eIsSet(featureID);
} |
python | def upload(self, resource_id, data):
"""Update the request URI to upload the a document to this resource.
Args:
resource_id (integer): The group id.
data (any): The raw data to upload.
"""
self.body = data
self.content_type = 'application/octet-stream'
... |
java | private static String getJsPackage(FileDescriptor file) {
String protoPackage = file.getPackage();
if (!protoPackage.isEmpty()) {
return "proto." + protoPackage;
}
return "proto";
} |
java | @Override
public void exec(Result<Object> result, Object ...args)
{
TableKelp tableKelp = _table.getTableKelp();
RowCursor minCursor = tableKelp.cursor();
RowCursor maxCursor = tableKelp.cursor();
minCursor.clear();
maxCursor.setKeyMax();
_keyExpr.fillMinCursor(minCursor, args... |
java | public Vector<Object> toValuesVector() {
final Vector<Object> values = new Vector<Object>();
for (final JKTableColumnValue value : this.columnsValues) {
values.add(value);
}
return values;
} |
java | public boolean completed() {
if (engine == null) {
return false;
}
if (length.isEnabled()) {
if (timeout > 0) {
return false;
}
return completed;
}
if (emitCount.isEnabled()) {
if (leftToEmit > 0) {
return false;
}
return completed;
}
if (wrapUp) {
retu... |
java | public List<DataSourceType<WebFragmentDescriptor>> getAllDataSource()
{
List<DataSourceType<WebFragmentDescriptor>> list = new ArrayList<DataSourceType<WebFragmentDescriptor>>();
List<Node> nodeList = model.get("data-source");
for(Node node: nodeList)
{
DataSourceType<WebFragmentDesc... |
python | def _tumor_normal_stats(rec, somatic_info, vcf_rec):
"""Retrieve depth and frequency of tumor and normal samples.
"""
out = {"normal": {"alt": None, "depth": None, "freq": None},
"tumor": {"alt": 0, "depth": 0, "freq": None}}
if hasattr(vcf_rec, "samples"):
samples = [(s, {}) for s in... |
python | def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7):
"""Log probability for full covariance matrices."""
n_samples, n_dim = X.shape
nmix = len(means)
log_prob = np.empty((n_samples, nmix))
for c, (mu, cv) in enumerate(zip(means, covars)):
try:
cv_chol = l... |
java | public void setInitializer(/* @Nullable */ JvmField field, /* @Nullable */ StringConcatenationClient strategy) {
if (field == null || strategy == null)
return;
removeExistingBody(field);
setCompilationStrategy(field, strategy);
} |
python | def localization_feature(app):
"""
Localization feature
This will initialize support for translations and localization of values
such as numbers, money, dates and formatting timezones.
"""
# apply app default to babel
app.config['BABEL_DEFAULT_LOCALE'] = app.config['DEFAULT_LOCALE']
app... |
python | def new_from_list(cls, items, **kwargs):
"""Populates the ListView with a string list.
Args:
items (list): list of strings to fill the widget with.
"""
obj = cls(**kwargs)
for item in items:
obj.append(ListItem(item))
return obj |
java | public void connect() throws DBException {
try {
LOGGER.debug("Initializing MongoDB client");
mongoClient = new MongoClient(this.host, this.port);
} catch (UnknownHostException e) {
throw new DBException(e.toString());
}
} |
java | public void fireDepthThresholdReachedEvent(ControlAdapter cAdapter,
boolean reachedHigh,
long numMsgs)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "fireDepthThresh... |
python | def reg_to_lex(conditions, wildcards):
"""Transform a regular expression into a LEPL object.
Replace the wildcards in the conditions by LEPL elements,
like xM will be replaced by Any() & 'M'.
In case of multiple same wildcards (like xMx), aliases
are created to allow the regexp to compile, like
... |
java | protected void postLayoutChild(final int dataIndex) {
if (!mContainer.isDynamic()) {
boolean visibleInLayout = !mViewPort.isClippingEnabled() || inViewPort(dataIndex);
ViewPortVisibility visibility = visibleInLayout ?
ViewPortVisibility.FULLY_VISIBLE : ViewPortVisibil... |
python | def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None):
"""Preprocess data. Produce output that can be used by training efficiently.
Args:
train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet.
If eval_dataset is None, the pipel... |
python | def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0... |
python | def on_rabbitmq_close(self, reply_code, reply_text):
"""Called when RabbitMQ has been connected to.
:param int reply_code: The code for the disconnect
:param str reply_text: The disconnect reason
"""
global rabbitmq_connection
LOGGER.warning('RabbitMQ has disconnected (... |
python | def batch_mutate(self, mutation_map, consistency_level):
"""
Mutate many columns or super columns for many row keys. See also: Mutation.
mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
*
Parameters:
- mutation_map
- consistency_level
... |
java | public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{
appfwlearningsettings obj = new appfwlearningsettings();
obj.set_profilename(profilename);
appfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);
return response;
} |
python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... |
python | def get_template_path(self, meta=None, **kwargs):
"""
Formats template_name_path_pattern with kwargs given.
"""
if 'template_name_suffix' not in kwargs or kwargs.get('template_name_suffix') is None:
kwargs['template_name_suffix'] = self.get_template_name_suffix()
... |
python | def path_parts(path):
"""Split path into container, object.
:param path: Path to resource (including container).
:type path: `string`
:return: Container, storage object tuple.
:rtype: `tuple` of `string`, `string`
"""
path = path if path is not None else ''
container_path = object_pat... |
java | public void setBackground(Color color) {
predraw();
GL.glClearColor(color.r, color.g, color.b, color.a);
postdraw();
} |
java | public void cancel() {
Exchange exchangeToCancel;
RealConnection connectionToCancel;
synchronized (connectionPool) {
canceled = true;
exchangeToCancel = exchange;
connectionToCancel = exchangeFinder != null && exchangeFinder.connectingConnection() != null
? exchangeFinder.connect... |
java | protected PrivateKey getSigningPrivateKey() throws Exception {
val samlIdp = casProperties.getAuthn().getSamlIdp();
val signingKey = samlIdPMetadataLocator.getSigningKey();
val privateKeyFactoryBean = new PrivateKeyFactoryBean();
privateKeyFactoryBean.setLocation(signingKey);
pri... |
java | public WaiterState accepts(AmazonServiceException exception) throws AmazonServiceException {
for (WaiterAcceptor<Output> acceptor : acceptors) {
if (acceptor.matches(exception)) {
return acceptor.getState();
}
}
throw exception;
} |
java | public void fire(StepEvent event) {
Step step = stepStorage.getLast();
event.process(step);
notifier.fire(event);
} |
python | def calculate_sets(rules):
"""Calculate FOLLOW sets.
Adapted from: http://lara.epfl.ch/w/cc09:algorithm_for_first_and_follow_sets"""
symbols = {sym for rule in rules for sym in rule.expansion} | {rule.origin for rule in rules}
# foreach grammar rule X ::= Y(1) ... Y(k)
# if k=0 or {Y(1),...,Y(k)} ... |
java | public static String toBundleName(String bundleBaseName, Locale locale) {
String baseName = bundleBaseName.replace('.', '/');
if (locale == null) {
return baseName;
}
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();
if (StringUtils.i... |
java | public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException,
IOException {
saveRequest(context);
String loginFormUrl = getLoginFormUrl();
if (StringUtils.isNotEmpty(loginFormUrl)) {
RedirectUtils.redirect(context.getRequest(), ... |
python | def _updateall(self, query, vars, returning=False):
"""
Update, with optional return.
"""
cursor = self.get_db().cursor()
self._log(cursor, query, vars)
cursor.execute(query, vars)
self.get_db().commit()
return cursor.fetchall() if returning else None |
java | public static XorPeerAddressAttribute createXorPeerAddressAttribute(
TransportAddress address, byte[] tranID) {
XorPeerAddressAttribute attribute = new XorPeerAddressAttribute();
// TODO shouldn't we be XORing the address before setting it?
attribute.setAddress(address, tranID);
return attribute;
} |
python | def swo_disable(self, port_mask):
"""Disables ITM & Stimulus ports.
Args:
self (JLink): the ``JLink`` instance
port_mask (int): mask specifying which ports to disable
Returns:
``None``
Raises:
JLinkException: on error
"""
res = s... |
java | public void marshall(ReplicaSettingsDescription replicaSettingsDescription, ProtocolMarshaller protocolMarshaller) {
if (replicaSettingsDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(r... |
java | @Override
public void selectRange(int startParagraphIndex, int startColPosition, int endParagraphIndex, int endColPosition) {
selectRange(textPosition(startParagraphIndex, startColPosition), textPosition(endParagraphIndex, endColPosition));
} |
python | def package_node(root=None, name=None):
'''package node aims to package a (present working node) for a user into
a container. This assumes that the node is a single partition.
:param root: the root of the node to package, default is /
:param name: the name for the image. If not specified, will use ma... |
python | def write(self, src, dest=None):
"""Schedules a write of the file at ``src`` to the ``dest`` path in this jar.
If the ``src`` is a file, then ``dest`` must be specified.
If the ``src`` is a directory then by default all descendant files will be added to the jar as
entries carrying their relative path.... |
python | def newAttemptForUser(self, user):
"""
Create an L{_PasswordResetAttempt} for the user whose username is C{user}
@param user: C{unicode} username
"""
# we could query for other attempts by the same
# user within some timeframe and raise an exception,
# if we wante... |
java | public synchronized void rollback()
throws SIIncorrectCallException,
SIResourceException,
SIConnectionLostException,
SIErrorException
{
if (tc.isEntryEnabled()) SibTr.entry(this, tc, "rollback");
if (!valid)
{
throw new SIIncorrectCall... |
python | def isnil(self):
"""
Get whether the element is I{nil} as defined by having an
I{xsi:nil="true"} attribute.
@return: True if I{nil}, else False
@rtype: boolean
"""
nilattr = self.getAttribute("nil", ns=Namespace.xsins)
return nilattr is not None and (nil... |
python | def end_container(self, cancel=None):
"""Finishes and registers the currently-active container, unless
'cancel' is True."""
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
... |
python | def read_http_header(sock):
"""Read HTTP header from socket, return header and rest of data."""
buf = []
hdr_end = '\r\n\r\n'
while True:
buf.append(sock.recv(bufsize).decode('utf-8'))
data = ''.join(buf)
i = data.find(hdr_end)
if i == -1:
continue
re... |
python | def plot_sediment_rate(self, ax=None):
"""Plot sediment accumulation rate prior and posterior distributions"""
if ax is None:
ax = plt.gca()
y_prior, x_prior = self.prior_sediment_rate()
ax.plot(x_prior, y_prior, label='Prior')
y_posterior = self.mcmcfit.sediment_ra... |
python | def quat_conjugate(quaternion):
"""Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quat_conjugate(q0)
>>> q1[3] == q0[3] and all(q1[:3] == -q0[:3])
True
"""
return np.array(
(-quaternion[0], -quaternion[1], -quaternion[2], quaternion[3]),
dtype=np.float3... |
java | protected Server configureJetty(final int port) {
final Server server = new Server();
final ServerConnector connector = new ServerConnector(server);
final ServletContextHandler sch = getServletContextHandler();
// TODO: make all of this configurable
connector.setIdleTimeout((int... |
java | public String logMessage(String strTrxIDIn, BaseMessage trxMessage, String strMessageInfoType, String strMessageProcessType, String strMessageStatus, String strMessageDescription, String strMessageMimeType)
{
String strTrxID = strTrxIDIn;
int iUserID = -1;
String strContactType = null;
... |
python | def digest_auth(realm, auth_func):
"""A decorator used to protect methods with HTTP Digest authentication.
"""
def digest_auth_decorator(func):
def func_replacement(self, *args, **kwargs):
# 'self' here is the RequestHandler object, which is inheriting
# from DigestAuthMixin... |
python | def _write_udf_descs(self, descs, outfp, progress):
# type: (PyCdlib._UDFDescriptors, BinaryIO, PyCdlib._Progress) -> None
'''
An internal method to write out a UDF Descriptor sequence.
Parameters:
descs - The UDF Descriptors object to write out.
outfp - The output fil... |
java | public Collection values() {
if (mValues==null) {
mValues = new AbstractCollection() {
public Iterator iterator() {
return getHashIterator(IdentityMap.VALUES);
}
public int size() {
return mCount;
... |
java | private static GradientDrawable getStandardBackground(int color) {
final GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadius(BackgroundUtils.convertToDIP(4));
gradientDrawable.setColor(color);
return gradientDrawable;
} |
java | public static String escapeCssStringMinimal(final String text) {
return escapeCssString(text,
CssStringEscapeType.BACKSLASH_ESCAPES_DEFAULT_TO_COMPACT_HEXA,
CssStringEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET);
} |
python | def filter_image(im_name, out_base, step_size=None, box_size=None, twopass=False, cores=None, mask=True, compressed=False, nslice=None):
"""
Create a background and noise image from an input image.
Resulting images are written to `outbase_bkg.fits` and `outbase_rms.fits`
Parameters
----------
i... |
java | @SuppressWarnings("unchecked")
public <V extends View> V findView(View containerView, int id) {
return (V)containerView.findViewById(id);
} |
java | public void removeOutputPlugin(OutputPluginModel outputPlugin) {
Future future = futureHashMap.remove(outputPlugin.getID());
if (future != null) {
future.cancel(true);
}
outputPlugins.remove(outputPlugin);
} |
java | public @Nullable Resource getResource(@NotNull Resource baseResource) {
return getResource((Predicate<Resource>)null, baseResource);
} |
python | def from_current(cls):
"""Create an application client from within a running container.
Useful for connecting to the application master from a running
container in a application.
"""
if properties.application_id is None:
raise context.ValueError("Not running inside a... |
python | def _parse_entry_record(self, lines):
"""Parse a single entry record from a list of lines."""
dn = None
entry = OrderedDict()
for line in lines:
attr_type, attr_value = self._parse_attr(line)
if attr_type == 'dn':
self._check_dn(dn, attr_value)
... |
python | def Morrison(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \frac{24}{Re} + \frac{2.6Re/5}{1 + \left(\frac{Re}{5}\right)^{1.52}}
+ \frac{0.411 \left(\frac{Re}{263000}\right)^{-7.94}}{1
+ \left(\frac{Re}{263000}\... |
java | public static Metadata from(UICommandMetadata origin, Class<? extends UICommand> type)
{
Assert.notNull(origin, "Parent UICommand must not be null.");
Assert.notNull(type, "UICommand type must not be null.");
Metadata metadata = new Metadata(type);
metadata.docLocation(origin.getDocLocation()... |
java | public static BufferedImage getResized(final BufferedImage originalImage,
final Method scalingMethod, final Mode resizeMode, final String formatName,
final int targetWidth, final int targetHeight) throws IOException
{
return read(resize(originalImage, scalingMethod, resizeMode, formatName, targetWidth,
target... |
python | def verifyChainFromCAPath(self, capath, untrusted_file=None):
"""
Does the same job as .verifyChainFromCAFile() but using the list
of anchors in capath directory. The directory should (only) contain
certificates files in PEM format. As for .verifyChainFromCAFile(),
a list of untr... |
java | public static final void setActiveSession(Session session) {
synchronized (Session.STATIC_LOCK) {
if (session != Session.activeSession) {
Session oldSession = Session.activeSession;
if (oldSession != null) {
oldSession.close();
}
... |
python | def reassign_label(self, label, new_label, relabel=False):
"""
Reassign a label number to a new number.
If ``new_label`` is already present in the segmentation image,
then it will be combined with the input ``label`` number.
Parameters
----------
labels : int
... |
java | private static boolean load(String name, boolean mustSucceed, boolean useJavaLib) {
if (s_loadedLibs.contains(name)) {
return true;
}
if (! VoltDB.getLoadLibVOLTDB()) {
return false;
}
test64bit();
StringBuilder msgBuilder = new StringBuilder("Load... |
java | protected HashMap<String, INode> createHash(IContext context) {
HashMap<String, INode> result = new HashMap<String, INode>();
int nodeCount = 0;
for (INode node : context.getNodesList()) {
result.put(getNodePathToRoot(node), node);
nodeCount++;
}
... |
python | def read_json(fh, byteorder, dtype, count, offsetsize):
"""Read JSON tag data from file and return as object."""
data = fh.read(count)
try:
return json.loads(unicode(stripnull(data), 'utf-8'))
except ValueError:
log.warning('read_json: invalid JSON') |
python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.