language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @NotNull public static <T> Single<T> from(@NotNull final ApolloStoreOperation<T> operation) {
checkNotNull(operation, "operation == null");
return Single.create(new Single.OnSubscribe<T>() {
@Override
public void call(final SingleSubscriber<? super T> subscriber) {
operation.enqueue(new Apol... |
java | public void marshall(OutputArtifact outputArtifact, ProtocolMarshaller protocolMarshaller) {
if (outputArtifact == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(outputArtifact.getName(), NAME_BINDIN... |
java | public boolean merge(final PluginXmlAccess other) {
boolean _xblockexpression = false;
{
String _path = this.getPath();
String _path_1 = other.getPath();
boolean _notEquals = (!Objects.equal(_path, _path_1));
if (_notEquals) {
String _path_2 = this.getPath();
String _plus... |
java | @Override
@SuppressWarnings("unchecked")
public <T> Future<T> submit(Callable<T> task) {
Map<String, String> execProps = getExecutionProperties(task);
ThreadContextDescriptor contextDescriptor;
if (task instanceof ContextualAction) {
ContextualAction<Callable<T>> a = (Contex... |
java | private void populateValues(GriddedTile griddedTile, TImage image,
Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int minX, int maxX, int minY, int maxY,
Double[][] values) {
for (int yLocation = maxY; values != null && yLocation >= minY; yLocation--) {
for (int xLocation = maxX;... |
java | @Override
public FileBaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException {
final FileBaseStatistics stats = super.getStatistics(cachedStats);
return stats == null ? null :
new FileBaseStatistics(stats.getLastModificationTime(), stats.getTotalInputSize(), this.recordLength);
} |
java | public ComputeNodeGetRemoteLoginSettingsResult getComputeNodeRemoteLoginSettings(String poolId, String nodeId) throws BatchErrorException, IOException {
return getComputeNodeRemoteLoginSettings(poolId, nodeId, null);
} |
python | def get_commit_if_possible(filename):
"""Try to retrieve VCS information for a given file.
Currently only supports git using the gitpython package.
Parameters
----------
filename : str
Returns
-------
path: str
The base path of the repository
commit: str
... |
python | def get_outputs(self, merge_multi_context=True):
"""Gets outputs from a previous forward computation.
Parameters
----------
merge_multi_context : bool
Default is ``True``. In the case when data-parallelism is used, the outputs
will be collected from multiple devi... |
python | def find_label(label, label_color, label_description):
"""Find label."""
edit = None
for name, values in label_list.items():
color, description = values
if isinstance(name, tuple):
old_name = name[0]
new_name = name[1]
else:
old_name = name
... |
python | def isScheduleValid(self, schedule, node_srvs, force) -> (bool, str):
"""
Validates schedule of planned node upgrades
:param schedule: dictionary of node ids and upgrade times
:param node_srvs: dictionary of node ids and services
:return: a 2-tuple of whether schedule valid or n... |
java | private void commit(boolean force) {
if (_db == null) {
return;
}
if (_transaction && !force) {
return;
}
try {
_db.commit();
} catch (Exception e) {
throw new IllegalStateException("Could not commit transaction", e);
}
} |
python | def get(self, name, defval=None):
'''
Retrieve a value from the closest scope frame.
'''
for frame in reversed(self.frames):
valu = frame.get(name, s_common.novalu)
if valu != s_common.novalu:
return valu
task = self.ctors.get(name)
... |
python | def metastable_sets(self):
"""
Crisp clustering using PCCA. This is only recommended for visualization purposes. You *cannot* compute any
actual quantity of the coarse-grained kinetics without employing the fuzzy memberships!
Returns
-------
A list of length equal to meta... |
python | def get_redirect_args(self, request, callback):
"Get request parameters for redirect url."
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.provider.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
st... |
python | def customchain(**kwargsChain):
""" This decorator allows you to access ``ctx.bitshares`` which is
an instance of BitShares. But in contrast to @chain, this is a
decorator that expects parameters that are directed right to
``BitShares()``.
... code-block::python
@ma... |
java | @Override
void writeStreamBlob(OutputStream os,
byte[] buffer, int rowOffset,
byte []blobBuffer,
PageServiceImpl tableService)
throws IOException
{
int offset = rowOffset + offset();
int blobLen = BitsUtil.readInt16(buffer, offse... |
java | public static DataStoreEvent removalEvent(DBIDs removals) {
return new DataStoreEvent(DBIDUtil.EMPTYDBIDS, removals, DBIDUtil.EMPTYDBIDS);
} |
python | def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10,
numInnerItermax=200, stopThr=1e-9, verbose=False, log=False):
"""
Solve the general regularized OT problem with the generalized conditional gradient
The function solves the following optimization problem:
.. math::
\gamma ... |
python | def plot_pointings(self,pointings=None):
"""Plot pointings on canavs"""
if pointings is None:
pointings=self.pointings
i=0
for pointing in pointings:
items=[]
i=i+1
label={}
label['text']=pointing['label']['text']
for ccd in pointing["camera"... |
python | def _in(field, value, document):
"""
Returns True if document[field] is in the interable value. If the
supplied value is not an iterable, then a MalformedQueryException is raised
"""
try:
values = iter(value)
except TypeError:
raise MalformedQueryException("'$in' must accept an i... |
java | public static void registerFunction(Statement st,Function function,String packagePrepend,boolean dropAlias) throws SQLException {
String functionClass = function.getClass().getName();
String functionAlias = getAlias(function);
if(function instanceof ScalarFunction) {
ScalarFunction ... |
python | def _gatk_extract_reads_cl(data, region, prep_params, tmp_dir):
"""Use GATK to extract reads from full BAM file.
"""
args = ["PrintReads",
"-L", region_to_gatk(region),
"-R", dd.get_ref_file(data),
"-I", data["work_bam"]]
# GATK3 back compatibility, need to specify an... |
java | public int compare(CaptureSearchResult o1, CaptureSearchResult o2) {
String k1 = objectToKey(o1);
String k2 = objectToKey(o2);
if(backwards) {
return k2.compareTo(k1);
}
return k1.compareTo(k2);
} |
python | def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
... |
java | public int getAlignedResIndex(Group g, Chain c) {
boolean contained = false;
for (Chain member:getChains()) {
if (c.getId().equals(member.getId())) {
contained = true;
break;
}
}
if (!contained)
throw new IllegalArgumentException("Given chain with asym_id "+c.getId()+" is not a member of this ... |
java | private void handleEnd(GuacamoleInstruction instruction) {
// Verify all required arguments are present
List<String> args = instruction.getArgs();
if (args.size() < 1)
return;
// Terminate stream
closeInterceptedStream(args.get(0));
} |
java | public String readLine() throws IOException {
String line = readLine(false);
if (line != null) {
bytesRead = bytesRead + line.length();
}
return line;
} |
python | def _decode(self):
"""
Convert the characters of string s to standard value (WFN value).
Inspect each character in value of component. Copy quoted characters,
with their escaping, into the result. Look for unquoted non
alphanumerics and if not "*" or "?", add escaping.
:... |
java | protected static void checkCache(final Request request, final Instant modified, final EntityTag etag) {
final ResponseBuilder builder = request.evaluatePreconditions(from(modified), etag);
if (nonNull(builder)) {
throw new WebApplicationException(builder.build());
}
} |
java | static byte[] incrementBlocks(byte[] counter, long blockDelta) {
if (blockDelta == 0)
return counter;
if (counter == null || counter.length != 16)
throw new IllegalArgumentException();
// Can optimize this later. KISS for now.
if (blockDelta > MAX_GCM_BLOCKS)
... |
java | protected synchronized List<TaskInProgress> findSpeculativeTaskCandidates
(Collection<TaskInProgress> list) {
ArrayList<TaskInProgress> candidates = new ArrayList<TaskInProgress>();
long now = JobTracker.getClock().getTime();
Iterator<TaskInProgress> iter = list.iterator();
while (iter.hasNext()) {... |
python | def _format_pr(pr_):
'''
Helper function to format API return information into a more manageable
and useful dictionary for pull request information.
pr_
The pull request to format.
'''
ret = {'id': pr_.get('id'),
'pr_number': pr_.get('number'),
'state': pr_.get('st... |
python | def delete(self, record):
"""Delete a record.
:param record: Record instance.
"""
index, doc_type = self.record_to_index(record)
return self.client.delete(
id=str(record.id),
index=index,
doc_type=doc_type,
) |
python | def is_output_supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
is_a_tty = hasattr(sys.stdout,... |
java | public static URL createHttpUrl(LibertyServer server, String contextRoot, String path) throws Exception {
return new URL(createHttpUrlString(server, contextRoot, path));
} |
python | def timeline(self, user_id=None, screen_name=None, max_id=None,
since_id=None, max_pages=None):
"""
Returns a collection of the most recent tweets posted
by the user indicated by the user_id or screen_name parameter.
Provide a user_id or screen_name.
"""
... |
python | def write_report(summary_dict, seqid, genus, key):
"""
Parse the PointFinder outputs, and write the summary report for the current analysis type
:param summary_dict: nested dictionary containing data such as header strings, and paths to reports
:param seqid: name of the strain,
:... |
python | def _parse_acl_config(self, acl_config):
"""Parse configured ACLs and rules
ACLs are returned as a dict of rule sets:
{<eos_acl1_name>: set([<eos_acl1_rules>]),
<eos_acl2_name>: set([<eos_acl2_rules>]),
...,
}
"""
parsed_acls = dict()
for acl in... |
java | final public Selector PrimaryNotPlusMinus(boolean negated) throws ParseException {
Selector ans; Token tok;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TRUE:
jj_consume_token(TRUE);
ans = new LiteralImpl(Boolean.TRUE);
break;
case F... |
python | def inverted(self):
"""Return the inverse of the transform."""
# This is a bit of hackery so that we can put a single "inverse"
# function here. If we just made "self._inverse_type" point to the class
# in question, it wouldn't be defined yet. This way, it's done at
# at runtime ... |
java | protected synchronized void incrFileFixReadBytesRemoteRack(long incr) {
if (incr < 0) {
throw new IllegalArgumentException("Cannot increment by negative value " +
incr);
}
RaidNodeMetrics.getInstance(RaidNodeMetrics.DEFAULT_NAMESPACE_ID).numFileFixReadByte... |
java | @Override
public Array getArray(int index) {
check(index);
final Object obj = fleeceValueToObject(index);
return obj instanceof Array ? (Array) obj : null;
} |
java | public float[] t3(float[] z, int k, int M) {
float[] result = new float[M];
for (int i = 1; i <= M - 1; i++) {
int head = (i - 1) * k / (M - 1) + 1;
int tail = i * k / (M - 1);
float[] subZ = subVector(z, head - 1, tail - 1);
result[i - 1] = (new Transformations()).rNonsep(subZ, ... |
java | public List<Section> getAreas() {
List<Section> areasCopy = new ArrayList<Section>(10);
areasCopy.addAll(areas);
return areasCopy;
} |
python | def tocimxmlstr(value, indent=None):
"""
Return the CIM-XML representation of the CIM object or CIM data type,
as a :term:`unicode string`.
*New in pywbem 0.9.*
The returned CIM-XML representation is consistent with :term:`DSP0201`.
Parameters:
value (:term:`CIM object` or :term:`CIM d... |
java | public static IdGenerator getIdGeneratorByType(GenerationType generationType) {
if (generationType == null)
return null;
switch (generationType) {
case IDENTITY:
return IdentityIdGenerator.INSTANCE;
case AUTO:
return AutoIdGenerator.INSTANCE;
case UUID25:
return UUID25Generator.INSTANCE;
case UU... |
python | def subscribe(self, stream):
""" Subscribe to a stream.
:param stream: stream to subscribe to
:type stream: str
:raises: :class:`~datasift.exceptions.StreamSubscriberNotStarted`, :class:`~datasift.exceptions.DeleteRequired`, :class:`~datasift.exceptions.StreamNotConnected`
... |
python | def observe(self, callback, err_callback, duration=60):
"""Observe resource and call callback when updated."""
def observe_callback(value):
"""
Called when end point is updated.
Returns a Command.
"""
self.raw = value
callback(self... |
python | def from_raw_message(cls, rawmessage):
"""Create message from raw byte stream."""
userdata = Userdata.from_raw_message(rawmessage[11:25])
return ExtendedReceive(rawmessage[2:5],
rawmessage[5:8],
{'cmd1': rawmessage[9],
... |
java | @Nonnull
public static <T, R> LObjBoolFunction<T, R> objBoolFunctionFrom(Consumer<LObjBoolFunctionBuilder<T, R>> buildingFunction) {
LObjBoolFunctionBuilder builder = new LObjBoolFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
java | public void setPushLevel(Level newLevel) throws SecurityException {
if (newLevel == null) {
throw new NullPointerException();
}
LogManager manager = LogManager.getLogManager();
checkPermission();
pushLevel = newLevel;
} |
python | def use_forwarded_port(graph):
"""
Inject the `X-Forwarded-Port` (if any) into the current URL adapter.
The URL adapter is used by `url_for` to build a URLs.
"""
# There must be a better way!
context = _request_ctx_stack.top
if _request_ctx_stack is None:
return None
# determ... |
java | public Formula getFormula() {
Reagent[] reagents = new Reagent[] {KEY, VALUE, PARENT, EXPRESSION};
final Formula rslt = new SimpleFormula(getClass(), reagents);
return rslt;
} |
python | def generateViewHierarchies(self):
'''
Wrapper method to create the view hierarchies. Currently it just calls
:func:`~exhale.graph.ExhaleRoot.generateClassView` and
:func:`~exhale.graph.ExhaleRoot.generateDirectoryView` --- if you want to implement
additional hierarchies, implem... |
java | public PdfName getVersionAsName(char version) {
switch(version) {
case PdfWriter.VERSION_1_2:
return PdfWriter.PDF_VERSION_1_2;
case PdfWriter.VERSION_1_3:
return PdfWriter.PDF_VERSION_1_3;
case PdfWriter.VERSION_1_4:
return PdfWriter.PDF_VERSION_1_4;
case PdfWriter.VERSION_1_5:
return PdfWriter.P... |
java | private static void thresholdBlock(byte[] luminances,
int xoffset,
int yoffset,
int threshold,
int stride,
BitMatrix matrix) {
for ... |
python | def get_external_link(self, id, **kwargs): # noqa: E501
"""Get a specific external link # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_external_link(id, ... |
python | def put(self, item, block=True, timeout=None, size=None):
"""Put *item* into the queue.
If the queue is currently full and *block* is True (the default), then
wait up to *timeout* seconds for space to become available. If no
timeout is specified, then wait indefinitely.
If the ... |
java | public static THttpService ofFormats(
Object implementation,
SerializationFormat defaultSerializationFormat,
Iterable<SerializationFormat> otherAllowedSerializationFormats) {
return new THttpService(ThriftCallService.of(implementation),
newAll... |
java | public void process(Iterator<String> text) {
String nextToken = null, curToken = null;
// Base case for the next token buffer to ensure we always have two
// valid tokens present
if (text.hasNext())
nextToken = text.next();
while (text.hasNext()) {
curToke... |
java | protected String columnNameToPropertyName(String columnName){
String normalized = columnName.replaceAll("[^a-zA-Z0-9]+", " ");
String capitalized = WordUtils.capitalizeFully(normalized);
String blankRemmoved = StringUtils.remove(capitalized, ' ');
return StringUtils.uncapitalize(blankRemmoved);
} |
python | def set_from_config_file(self, filename):
""" Loads lint config from a ini-style config file """
if not os.path.exists(filename):
raise LintConfigError(u"Invalid file path: {0}".format(filename))
self._config_path = os.path.abspath(filename)
try:
parser = ConfigPa... |
python | def rewrite_guides(self, guides):
"""
Remove any ``<a:gd>`` element children of ``<a:avLst>`` and replace
them with ones having (name, val) in *guides*.
"""
self._remove_avLst()
avLst = self._add_avLst()
for name, val in guides:
gd = avLst._add_gd()
... |
java | @Override
public EClass getIfcCsgPrimitive3D() {
if (ifcCsgPrimitive3DEClass == null) {
ifcCsgPrimitive3DEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(156);
}
return ifcCsgPrimitive3DEClass;
} |
python | def _get_library_os_path_from_library_dict_tree(self, library_path, library_name):
"""Hand verified library os path from libraries dictionary tree."""
if library_path is None or library_name is None:
return None
path_list = library_path.split(os.sep)
target_lib_dict = self.li... |
java | private boolean openTemplate(String filename)
{
InputStreamReader isr = null;
try
{
isr = new InputStreamReader(IOUtil.newInputStream(filename), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) !... |
java | public final void makeDocReversed(final Map<String, Object> pReqVars,
final ADoc pReversing, final ADoc pReversed,
final String pLangDef) throws Exception {
pReversing.setIdDatabaseBirth(pReversed.getIdDatabaseBirth());
pReversing.setReversedId(pReversed.getItsId());
pReversing.setReversedIdDataba... |
java | private static List<TransformationDescription> loadDescrtipionsFromXMLInputSource(InputSource source,
String fileName) throws Exception {
XMLReader xr = XMLReaderFactory.createXMLReader();
TransformationDescriptionXMLReader reader = new TransformationDescriptionXMLReader(fileName);
x... |
java | public String getClassPath()
{
String rawClassPath = buildClassPath();
if (true)
return rawClassPath;
char sep = CauchoUtil.getPathSeparatorChar();
String []splitClassPath = rawClassPath.split("[" + sep + "]");
String javaHome = System.getProperty("java.home");
PathImpl pwd = VfsOld.... |
java | public static <R extends Tuple, T extends Tuple> R summarize(DataSet<T> input) throws Exception {
if (!input.getType().isTupleType()) {
throw new IllegalArgumentException("summarize() is only implemented for DataSet's of Tuples");
}
final TupleTypeInfoBase<?> inType = (TupleTypeInfoBase<?>) input.getType();
... |
java | public String getOutputUserDisplayName(String inputVirtualRealm) {
// initialize the return value
String returnValue = getOutputMapping(inputVirtualRealm, Service.CONFIG_DO_USER_DISPLAY_NAME_MAPPING,
USER_DISPLAY_NAME_DEFAULT);
return returnValue;
... |
java | public static void register() throws SQLException {
if (isRegistered()) {
throw new IllegalStateException(
"Driver is already registered. It can only be registered once.");
}
CloudSpannerDriver registeredDriver = new CloudSpannerDriver();
DriverManager.registerDriver(registeredDriv... |
python | def is_reached(self, uid=None):
"""
is_reached is to be called for every object that counts towards the limit.
- When called with no uid, the Limiter assumes this is a new object and
unconditionally increments the counter (less CPU and memory usage).
- When a given object can be ... |
java | @Override
protected Outlet createOutlet(final boolean append, final String encoding, final String name, final boolean overwrite, final String path) {
Outlet _xifexpression = null;
if (((Objects.equal(name, Generator.SRC_GEN) || Objects.equal(name, Generator.SRC_GEN_IDE)) || Objects.equal(name, Generator.SRC_G... |
java | public ServiceFuture<ExpressRouteGatewayInner> beginCreateOrUpdateAsync(String resourceGroupName, String expressRouteGatewayName, ExpressRouteGatewayInner putExpressRouteGatewayParameters, final ServiceCallback<ExpressRouteGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWit... |
python | def checksum(thing):
"""
Get the checksum of a calculation from the calculation ID (if already
done) or from the job.ini/job.zip file (if not done yet). If `thing`
is a source model logic tree file, get the checksum of the model by
ignoring the job.ini, the gmpe logic tree file and possibly other fi... |
python | def _get_application_module(self, controller, application):
"""Return the module for an application. If it's a entry-point
registered application name, return the module name from the entry
points data. If not, the passed in application name is returned.
:param str controller: The contr... |
java | public void add(Entry entry) throws LdapException {
CoreSession session = this.service.getAdminSession();
session.add(entry);
} |
java | private void maxiEncodingModeComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maxiEncodingModeComboActionPerformed
// TODO add your handling code here:
if (maxiEncodingModeCombo.getSelectedIndex() == 0 || maxiEncodingModeCombo.getSelectedIndex() == 1) {
maxiPrimaryData... |
java | public void deleteAddOn(final String planCode, final String addOnCode) {
doDELETE(Plan.PLANS_RESOURCE +
"/" +
planCode +
AddOn.ADDONS_RESOURCE +
"/" +
addOnCode);
} |
python | def pks_from_objects(self, objects):
"""
Extract all the primary key strings from the given objects.
Objects may be Versionables, or bare primary keys.
:rtype : set
"""
return {o.pk if isinstance(o, Model) else o for o in objects} |
python | def build_journals_re_kb(fpath):
"""Load journals regexps knowledge base
@see build_journals_kb
"""
def make_tuple(match):
regexp = match.group('seek')
repl = match.group('repl')
return regexp, repl
kb = []
with file_resolving(fpath) as fh:
for rawline in fh:
... |
python | def replace_rep_after(text: str) -> str:
"Replace repetitions at the character level in `text` after the repetition"
def _replace_rep(m):
c, cc = m.groups()
return f"{c}{TK_REP}{len(cc)+1}"
re_rep = re.compile(r"(\S)(\1{2,})")
return re_rep.sub(_replace_rep, text) |
python | def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that the properties make sense
self.sanitize()
# Write the version
bitstream = BitStream('uint:4=%d' % self.version)
# Write the traffic class
bitstream += BitStream('uint:8=%d' % ... |
python | def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size):
""" word embedding + LSTM Projected """
state_names = []
data = S.var('data')
weight = S.var("encoder_weight", stype='row_sparse')
embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size,
... |
python | def convert(self, value, param, ctx):
"""
ParamType.convert() is the actual processing method that takes a
provided parameter and parses it.
"""
# passthrough conditions: None or already processed
if value is None or isinstance(value, tuple):
return value
... |
python | def _escape_parameters(self, char):
"""
Parse parameters in an escape sequence. Parameters are a list of
numbers in ascii (e.g. '12', '4', '42', etc) separated by a semicolon
(e.g. "12;4;42").
See the [vt102 user guide](http://vt100.net/docs/vt102-ug/) for more
d... |
java | public static final void writeScript(Writer writer)
throws IOException
{
String newline = IO.newline();
boolean isWindows = System.getProperty("os.name").startsWith("Windows");
String variablePrefix = "$C";
String variableSuffix = File.pathSeparator;
if(isWindows)
... |
java | public void readExternal(final ObjectInput in) throws IOException,
ClassNotFoundException {
this.size = in.readLong();
this.nodeId = in.readInt();
} |
python | def computer_desc(name):
'''
Manage the computer's description field
name
The desired computer description
'''
# Just in case someone decides to enter a numeric description
name = six.text_type(name)
ret = {'name': name,
'changes': {},
'result': True,
... |
java | protected boolean validateLayout(Dimension dim)
{
if (majorAxis == X_AXIS)
{
majorRequest = getRequirements(X_AXIS, majorRequest);
minorRequest = getRequirements(Y_AXIS, minorRequest);
oldDimension.setSize(majorRequest.preferred, minorRequest.preferred);
}... |
java | @Benchmark
@BenchmarkMode(Mode.Throughput)
public StackFrame stackWalkerWithLambda() {
return StackWalker.getInstance().walk(stream -> stream.skip(1).findFirst().get());
} |
python | def get_weather(test=False):
"""
Returns weather reports from the dataset.
"""
if _Constants._TEST or test:
rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = ... |
python | def update(self):
'''
Updates LaserData.
'''
if self.hasproxy():
laserD = LaserData()
values = []
data = self.proxy.getLaserData()
#laserD.values = laser.distanceData
for i in range (data.numLaser):
values.appen... |
java | private static void print(Metadata metadata, String method)
{
System.out.println();
System.out.println("-------------------------------------------------");
System.out.print(' ');
System.out.print(method);
System.out.println("-------------------------------------------------"... |
python | def get_gateway_id(self):
"""Return a unique id for the gateway."""
host, _ = self.server_address
try:
ip_address = ipaddress.ip_address(host)
except ValueError:
# Only hosts using ip address supports unique id.
return None
if ip_address.versio... |
java | @Override
Transformers.ResourceIgnoredTransformationRegistry createRegistry(OperationContext context, Resource remote, Set<String> remoteExtensions) {
final ReadMasterDomainModelUtil.RequiredConfigurationHolder rc = new ReadMasterDomainModelUtil.RequiredConfigurationHolder();
final PathElement host... |
python | def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... |
python | def bind_socket(self, config):
""" :meth:`.WNetworkNativeTransportProto.bind_socket` method implementation
"""
address = config[self.__bind_socket_config.section][self.__bind_socket_config.address_option]
port = config.getint(self.__bind_socket_config.section, self.__bind_socket_config.port_option)
return WIP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.