language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private boolean isDenyUncoveredHttpMethods(List<SecurityConstraint> scList) {
for (SecurityConstraint sc : scList) {
List<WebResourceCollection> wrcList = sc.getWebResourceCollections();
for (WebResourceCollection wrc : wrcList) {
if (wrc.getDenyUncoveredHttpMethods()) {
... |
python | def load_world_bank_health_n_pop():
"""Loads the world bank health dataset, slices and a dashboard"""
tbl_name = 'wb_health_population'
data = get_example_data('countries.json.gz')
pdf = pd.read_json(data)
pdf.columns = [col.replace('.', '_') for col in pdf.columns]
pdf.year = pd.to_datetime(pdf... |
java | @Deprecated
public Document getDocument(String rootPath) {
if (getDocument(CmsSearchField.FIELD_PATH, rootPath) != null) {
return (Document)getDocument(CmsSearchField.FIELD_PATH, rootPath).getDocument();
}
return null;
} |
java | public ServiceFuture<ImageTagCreateSummary> createImageTagsAsync(UUID projectId, CreateImageTagsOptionalParameter createImageTagsOptionalParameter, final ServiceCallback<ImageTagCreateSummary> serviceCallback) {
return ServiceFuture.fromResponse(createImageTagsWithServiceResponseAsync(projectId, createImageTags... |
python | def get(self, request, *args, **kwargs):
"""
Method for handling GET requests.
Calls the `render` method with the following
items in context.
* **adminForm** - The main form wrapped in an helper class \
that helps with fieldset iteration and html attributes.
* **... |
python | def input_tray_status(self,
filter_supported: bool = True) -> Dict[int, Any]:
"""Return the state of all input trays."""
tray_status = {}
for i in range(1, 5):
try:
tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {})
... |
python | def get_contract_center(self, root_symbol, dt, offset):
"""
Parameters
----------
root_symbol : str
The root symbol for the contract chain.
dt : Timestamp
The datetime for which to retrieve the current contract.
offset : int
The offset ... |
java | public static void convert(SequenceRecordReader reader, SequenceRecordWriter writer, boolean closeOnCompletion) throws IOException {
if(!reader.hasNext()){
throw new UnsupportedOperationException("Cannot convert SequenceRecordReader: reader has no next element");
}
while(reader.has... |
python | def addVSLCtoParent(self, vslc_id, parent_id):
"""
The VSLC can either be added to a genotype or to a GVC.
The vslc is added as a part of the parent.
:param vslc_id:
:param parent_id:
:return:
"""
self.addParts(vslc_id, parent_id, self.globaltt['has_varia... |
java | public HttpRequestInitializer getHttpRequestInitializer(
final ServiceOptions<?, ?> serviceOptions) {
Credentials scopedCredentials = serviceOptions.getScopedCredentials();
final HttpRequestInitializer delegate =
scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()
... |
python | def _clip_by_global_norm(self, max_norm):
"""Clips gradient norm.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
The method is first used in
`[ICML2013] On the difficulty of training recurren... |
python | def p_declaration_3(t):
"""declaration : type_specifier STAR ID"""
# encode this as the equivalent 'type_specifier ID LT 1 GT'
if not isinstance(t[1], type_info):
t[1] = type_info(t[1], t.lineno(1))
t[1].id = t[3]
t[1].array = True
t[1].fixed = False
t[1].len = '1'
t[0] = t[1] |
java | public void startIfNotRunning() {
boolean isStorageRunning = daemonExecutor.isProcessRunning(STORAGE_PIDFILE);
if (isStorageRunning) {
System.out.println(DISPLAY_NAME + " is already running");
} else {
FileUtils.deleteQuietly(STORAGE_PIDFILE.toFile()); // delete dangling ... |
python | def search(self, ngram):
'''
Parameters
----------
ngram, str or unicode, string to search for
Returns
-------
pd.DataFrame, {self._parsed_col: <matching texts>, self._category_col: <corresponding categories>, ...}
'''
mask = self._document_index... |
python | def export_coreml(self, filename):
"""
Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('./myModel.mlmodel')
"""
import coremltools
from coremltools.proto.FeatureTypes_pb2 import A... |
java | public static int sum( InterleavedS8 img ) {
if( BoofConcurrency.USE_CONCURRENT ) {
return ImplImageStatistics_MT.sum(img);
} else {
return ImplImageStatistics.sum(img);
}
} |
java | public static <T> Transformed<T> succ(Transformer transformer, T result) {
return new Basic<>(transformer, result, true);
} |
java | @NonNull
public static Point destination(@NonNull Point point, @FloatRange(from = 0) double distance,
@FloatRange(from = -180, to = 180) double bearing,
@NonNull @TurfConstants.TurfUnitCriteria String units) {
double longitude1 = degreesToRadian... |
python | def set_client_cert(self, cert):
"""*Sets the client cert for the requests.*
The cert is either a path to a .pem file, or a JSON array, or a list
having the cert path and the key path.
Values ``null`` and ``${None}`` can be used for clearing the cert.
*Examples*
| `Se... |
python | def upgrade():
"""Upgrade database."""
op.create_table(
'records_metadata',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column(
'id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False),
sa.C... |
python | def plot_pyro(calc_id=-1):
"""
Plot the pyroclastic cloud and the assets
"""
# NB: matplotlib is imported inside since it is a costly import
import matplotlib.pyplot as p
dstore = util.read(calc_id)
sitecol = dstore['sitecol']
asset_risk = dstore['asset_risk'].value
pyro, = numpy.whe... |
java | @Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) {
return NO_MATCH;
}
return matchNewClassOrMethodInvocation(tree, state);
} |
java | protected void onServiceInstanceAvailable(ServiceInstance instance){
String serviceName = instance.getServiceName();
synchronized(notificationHandlers){
if(notificationHandlers.containsKey(serviceName)){
for(NotificationHandler h : notificationHandlers.get(serviceName)){
... |
python | def get_position(fallback=CURSOR_POS_FALLBACK):
''' Return the current column number of the terminal cursor.
Used to figure out if we need to print an extra newline.
Returns:
tuple(int): (x, y), (,) - empty, if an error occurred.
TODO: needs non-ansi mode for Windows
N... |
java | public long getLong(String key, long defaultValue) {
String argument = getProperty(key, null);
return argument == null
? defaultValue
: Long.parseLong(argument);
} |
python | def _load_features(root):
"""Returns {name: Feature}"""
out = collections.OrderedDict()
for elem in root.findall('feature'):
name = elem.attrib['name']
api = elem.attrib['api']
number = tuple([int(x) for x in elem.attrib['number'].split('.')])
requires = [_load_require(x) for... |
java | public static nstrafficdomain_bridgegroup_binding[] get(nitro_service service, Long td) throws Exception{
nstrafficdomain_bridgegroup_binding obj = new nstrafficdomain_bridgegroup_binding();
obj.set_td(td);
nstrafficdomain_bridgegroup_binding response[] = (nstrafficdomain_bridgegroup_binding[]) obj.get_resources(... |
python | def upload_file(self, session, output, serverdir):
"""
Upload a file to koji
:return: str, pathname on server
"""
name = output.metadata['filename']
self.log.debug("uploading %r to %r as %r",
output.file.name, serverdir, name)
kwargs = {}
... |
python | def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... |
python | def mesh_to_vertexlist(mesh,
group=None,
smooth=True,
smooth_threshold=60000):
"""
Convert a Trimesh object to arguments for an
indexed vertex list constructor.
Parameters
-------------
mesh : trimesh.Trimesh
Mesh to be ... |
python | def custom_auth(principal, credentials, realm, scheme, **parameters):
""" Generate a basic auth token for a given user and password.
:param principal: specifies who is being authenticated
:param credentials: authenticates the principal
:param realm: specifies the authentication provider
:param sche... |
python | def tqx(mt, x, t):
""" nqx : Returns the probability to die within n years at age x """
return (mt.lx[x] - mt.lx[x + t]) / mt.lx[x] |
python | def qmax_boiling(rhol=None, rhog=None, sigma=None, Hvap=None, D=None, P=None,
Pc=None, Method=None, AvailableMethods=False):
r'''This function handles the calculation of nucleate boiling critical
heat flux and chooses the best method for performing the calculation.
Preferred methods a... |
python | def remote_evb_cfgd_uneq_store(self, remote_evb_cfgd):
"""This saves the EVB cfg, if it is not the same as stored. """
if remote_evb_cfgd != self.remote_evb_cfgd:
self.remote_evb_cfgd = remote_evb_cfgd
return True
return False |
python | def get_ladder(session, ladder_id, user_id=None, user_ids=None, start=0, limit=LADDER_RESULT_LIMIT):
"""Get ladder."""
params = {
'start': start,
'limit': limit
}
if isinstance(ladder_id, str):
ladder_id = lookup_ladder_id(ladder_id)
if limit > LADDER_RESULT_LIMIT:
ra... |
java | public Tree insert(int index, byte[] value, boolean asBase64String) {
if (asBase64String) {
return insertObjectInternal(index, BASE64.encode(value));
}
return insertObjectInternal(index, value);
} |
java | public static void validateString(final String what, final String s) {
if (s == null) {
throw new IllegalArgumentException("Invalid " + what + ": null");
} else if ("".equals(s)) {
throw new IllegalArgumentException("Invalid " + what + ": empty string");
}
final int n = s.length();
for (... |
java | @Override
public void initialize(Duration timeout) throws DurableDataLogException {
List<Long> ledgersToDelete;
LogMetadata newMetadata;
synchronized (this.lock) {
Preconditions.checkState(this.writeLedger == null, "BookKeeperLog is already initialized.");
assert this... |
python | def build_url(base_url, path):
""" prepend url with base_url unless it's already an absolute URL """
if absolute_http_url_regexp.match(path):
return path
elif base_url:
return "{}/{}".format(base_url.rstrip("/"), path.lstrip("/"))
else:
raise ParamsError("base url missed!") |
python | def force_utc(time, name='field', precision=6):
"""Appending 'Z' to isoformatted time - explicit timezone is required for most APIs"""
if not isinstance(time, datetime.datetime):
raise CloudValueError("%s should be of type datetime" % (name,))
clip = 6 - precision
timestring = time.isoformat()
... |
python | def GetManagedObject(self, inMo=None, classId=None, params=None, inHierarchical=False, dumpXml=None):
"""
Gets Managed Object from UCS.
- inMo, if provided, it acts as a parent for the present operation. It should be None unless a user wants to define a parent scope.
It can be a single MO or a list contai... |
java | private LoggingEvent appendStackTraceToEvent(final LoggingEvent event) {
String message = event.getMessage().toString();
// If there is a stack trace available, print it out
if (event.getThrowableInformation() != null) {
final String[] s = event.getThrowableStrRep();
for (final String line : s) ... |
java | protected static void checkNormal(String configKey, String configValue) throws SofaRpcRuntimeException {
checkPattern(configKey, configValue, NORMAL, "only allow a-zA-Z0-9 '-' '_' '.'");
} |
python | def strace_set_buffer_size(self, size):
"""Sets the STRACE buffer size.
Args:
self (JLink): the ``JLink`` instance.
Returns:
``None``
Raises:
JLinkException: on error.
"""
size = ctypes.c_uint32(size)
res = self._dll.JLINK_STRACE_C... |
java | @SuppressWarnings(value="unchecked")
public int setExpires(int deltaMinutes) {
if(!isValid()) {
throw new IllegalStateException("Impossible to change the sip application " +
"session timeout when it has been invalidated !");
}
expired = false;
if(logger.isDebugEnabled()) {
logger.debug("Post... |
java | private void WebPageCloseOnClick(GVRViewSceneObject gvrWebViewSceneObject, GVRSceneObject gvrSceneObjectAnchor, String url) {
final String urlFinal = url;
webPagePlusUISceneObject = new GVRSceneObject(gvrContext);
webPagePlusUISceneObject.getTransform().setPosition(webPagePlusUIPosition[0], web... |
java | @BetaApi
public final Operation deleteRouter(ProjectRegionRouterName router) {
DeleteRouterHttpRequest request =
DeleteRouterHttpRequest.newBuilder()
.setRouter(router == null ? null : router.toString())
.build();
return deleteRouter(request);
} |
python | def _permalink(self, absolute=False, expand=True, **kwargs):
""" Returns a canonical URL for the item """
return flask.url_for('entry',
entry_id=self._record.id,
category=self._record.category if expand else None,
slu... |
python | def translate(self, cdna_sequence, first_codon_is_start=False):
"""
Given a cDNA sequence which is aligned to a reading frame, returns
the translated protein sequence and a boolean flag indicating whether
the translated sequence ended on a stop codon (or just ran out of codons).
... |
python | def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat',... |
python | def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
"""
Gradient of the pdf at y, given link(f) w.r.t link(f)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\frac{1}{\\sigma^{2}}(y_{i} - \\lambda(f_{i}))
:param link_f: latent variables link(f)
:... |
python | def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t] |
java | public void beginStopEnvironment(String userName, String environmentId) {
beginStopEnvironmentWithServiceResponseAsync(userName, environmentId).toBlocking().single().body();
} |
java | public static String getParameterName(Parameter parameter) {
// identify parameter name and pattern from method signature
String methodParameterName = parameter.getName();
if (parameter.isAnnotationPresent(Param.class)) {
Param param = parameter.getAnnotation(Param.class);
... |
python | def flags(self):
"""Return set of flags."""
return set((name.lower() for name in sorted(TIFF.FILE_FLAGS)
if getattr(self, 'is_' + name))) |
python | async def kill_actor(request, aid, timeout=5):
'''Kill an actor with id ``aid``.
This command can only be executed by the arbiter,
therefore a valid sintax is only::
send('arbiter', 'kill_actor', 'abc')
Return 'killed abc` if successful, otherwise it returns ``None``.
'''
arb = request... |
python | def _get_current_label(self):
"""Get the label from the last line read"""
if len(self._last) == 0:
raise StopIteration
return self._last[:self._last.find(":")] |
python | def shuffle_characters(s):
'''Randomly shuffle the characters in a string'''
s = list(s)
random.shuffle(s)
s =''.join(s)
return s |
python | def scheduling_disjunctive(J,p,r,w):
"""
scheduling_disjunctive: model for the one machine total weighted completion time problem
Disjunctive optimization model for the one machine total weighted
completion time problem with release times.
Parameters:
- J: set of jobs
- p[j]: proce... |
java | public void set(String name, Object o){
Map<String,Object> m = getMap(name);
if(m!=null) {
memoryHeap.release(m.get(name));
m.put(name, o);
memoryHeap.take(m.get(name));
}
} |
python | def _get_install_sources(self):
"""Construct arguments to use alternative package indexes if
there were sources supplied, empty string if there were not.
"""
if not self._sources:
return ''
parts = ['--no-index']
for source in self._sources:
parts.... |
java | Node createSuperForFunction(Node functionNode) {
final Node result = IR.superNode();
if (isAddingTypes()) {
result.setJSType(getTypeOfSuperForFunctionNode(functionNode));
}
return result;
} |
python | def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_int()
if PL_get_long(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool") |
java | public NFBuildGraphNode getOrCreateNode(NFBuildGraphNodeList nodes, NFNodeSpec nodeSpec, int ordinal) {
return nodeCache.getNode(nodes, nodeSpec, ordinal);
} |
java | @Override
public String toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
StringBuilder buf = new StringBuilder();
buf.append('<').append(getElementName()).append(" xmlns=\"");
buf.append(getNamespace()).append("\" ");
synchronized (candidates) {
... |
python | def classes_and_not_datetimelike(*klasses):
"""
evaluate if the tipo is a subclass of the klasses
and not a datetimelike
"""
return lambda tipo: (issubclass(tipo, klasses) and
not issubclass(tipo, (np.datetime64, np.timedelta64))) |
java | private static String convert(String pkg) {
pkg = pkg.trim();
if (pkg.endsWith("*")) {
pkg = pkg.substring(0, pkg.length() - 1);
}
if (pkg.endsWith(".query")) {
// always work with entity bean packages so trim
pkg = pkg.substring(0, pkg.length() - 6);
}
pkg = pkg.replace('.', ... |
python | def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
"""Find all commits between two commit SHAs."""
repo = Repo(repo_dir)
commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
if hide_merges:
return [x for x in commits if not x.summary.startswith("Merge ")]
... |
python | def on_backward_end(self, **kwargs):
"accumulated step and reset samples, True will result in no stepping"
if (self.acc_batches % self.n_step) == 0:
for p in (self.learn.model.parameters()):
if p.requires_grad: p.grad.div_(self.acc_samples)
self.acc_samples = 0
... |
python | def user_information(self, access_token):
"""
Will retrieve the user information data for the authenticated user.
:type access_token: str
:rtype: dict[str, str]
:param access_token: The access token to be used to retrieve the data.
:return: Dictionary with attribute name... |
python | def p_expression_ulnot(self, p):
'expression : LNOT expression %prec ULNOT'
p[0] = Ulnot(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
python | def _get_qemu_img(self):
"""
Search the qemu-img binary in the same binary of the qemu binary
for avoiding version incompatibily.
:returns: qemu-img path or raise an error
"""
qemu_img_path = ""
qemu_path_dir = os.path.dirname(self.qemu_path)
try:
... |
java | @Override
public int getItemViewType(int position, @NonNull File file) {
if (isMultimedia(file)) {
if (isCheckable(file)) {
return VIEWTYPE_IMAGE_CHECKABLE;
} else {
return VIEWTYPE_IMAGE;
}
} else {
return super.getItem... |
java | public static INDArray reverseTimeSeries(INDArray in, LayerWorkspaceMgr workspaceMgr, ArrayType arrayType){
if(in == null){
return null;
}
if(in.ordering() != 'f' || in.isView() || !Shape.strideDescendingCAscendingF(in)){
in = workspaceMgr.dup(arrayType, in, 'f');
... |
java | public boolean checkObsolete(IGraphStore store, boolean isReorg, int lineNo, String fileName) {
if (type == RecordType.T) {
// Transaction boundaries are obsolete during reorg
return isReorg;
} else if (type == RecordType.L) {
// A log is always obsolete
... |
java | public static DatabaseFieldDescriptor getDatabaseFieldDescriptor(final Field field) {
DatabaseFieldDescriptor databaseFieldDescriptor = fieldToDataBaseFieldDescriptorMap.get(field);
if (databaseFieldDescriptor == null) {
DatabaseField databaseField = field.getAnnotation(DatabaseField.class)... |
python | def user_provenance(self, document): # type: (ProvDocument) -> None
"""Add the user provenance."""
self.self_check()
(username, fullname) = _whoami()
if not self.full_name:
self.full_name = fullname
document.add_namespace(UUID)
document.add_namespace(ORCID)... |
java | @TaskAction
public void downloadCloudSdkAction()
throws ManagedSdkVerificationException, ManagedSdkVersionMismatchException,
InterruptedException, CommandExecutionException, SdkInstallerException,
CommandExitException, IOException {
// managedCloudSdk is set by AppEngineCorePluginConfigu... |
python | def cycles_created_by(callable):
"""
Return graph of cyclic garbage created by the given callable.
Return an :class:`~refcycle.object_graph.ObjectGraph` representing those
objects generated by the given callable that can't be collected by Python's
usual reference-count based garbage collection.
... |
python | def bury(self, job: Job, priority: int = DEFAULT_PRIORITY) -> None:
"""Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
"""
self._send_cmd(b'bury %d %d' % (job.id, pri... |
python | def get_experiment_kind(root):
"""Read common properties from root of ReSpecTh XML file.
Args:
root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file
Returns:
properties (`dict`): Dictionary with experiment type and apparatus information.
"""
properties = {}
if root... |
python | def isns_isns_vrf_isns_discovery_domain_set_isns_discovery_domain_set_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns")
isns_vrf = ET.SubElement(isns, "isns-vrf")
... |
java | public void setChainStartRetryInterval(Object value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Setting chain start retry interval [" + value + "]");
}
try {
long num = MetatypeUtils.parseLong(PROPERTY_CONFIG_ALIAS, PROPERTY_CHAIN_S... |
java | public void watchDirectoryTree(Path dir) {
if (_watchedDirectories == null) {
throw new IllegalStateException("DirectoryWatcher.close() was called. Please make a new instance.");
}
try {
if (Files.exists(dir)) {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
... |
python | def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING):
"""
Validates instance properties, updates an XML tree with them, and writes the content to a file.
:param use_template: if True, updates a new template XML tree; otherwise the original XML tree
:param... |
java | public static NetworkInfo of(NetworkId networkId, NetworkConfiguration configuration) {
return newBuilder(networkId, configuration).build();
} |
python | def register(provider_factory, *args, **kwargs):
"""
Returns a decorator that registers its arguments for scanning, so it can be
picked up by :py:func:`wiring.scanning.scan.scan`.
First argument - `provider_factory` - is a callable that is invoked during
scanning with decorated argument and `kwargs... |
java | public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException {
LOGGER.trace("copy(InputStream, OutputStream, byte[])");
copy(inputStream, outputStream, buffer, null);
} |
java | @Override
public ProxyAuthenticationMethod getMethod() {
switch (authenticationMethod) {
case BASIC:
return ProxyAuthenticationMethod.BASIC;
case DIGEST:
return ProxyAuthenticationMethod.DIGEST;
case URL:
return ProxyAuthenticationMethod.URL;
default:
return null;
}
} |
python | def add_suffixes_to_gene_codes(self):
"""Appends pos1, pos2, etc to the gene_code if needed."""
out = []
for gene_code in self.data.gene_codes:
for sufix in self.make_gene_code_suffixes():
out.append('{0}{1}'.format(gene_code, sufix))
return out |
python | def policy_and_value_opt_step(i,
opt_state,
opt_update,
policy_and_value_net_apply,
old_params,
padded_observations,
padded_actions,
... |
python | def pick(options, title=None, indicator='*', default_index=0, multi_select=False, min_selection_count=0, options_map_func=None):
"""Construct and start a :class:`Picker <Picker>`.
Usage::
>>> from pick import pick
>>> title = 'Please choose an option: '
>>> options = ['option1', 'option2', '... |
python | def _parse_dnamasq(filename):
'''
Generic function for parsing dnsmasq files including includes.
'''
fileopts = {}
if not os.path.isfile(filename):
raise CommandExecutionError(
'Error: No such file \'{0}\''.format(filename)
)
with salt.utils.files.fopen(filename, 'r... |
python | def save_resource(self, name, resource, pushable=False):
'Saves an object such that it can be used by other tests.'
if pushable:
self.pushable_resources[name] = resource
else:
self.resources[name] = resource |
python | def meta(self):
"""Data for loading later"""
mount_points = []
for overlay in self.overlays:
mount_points.append(overlay.mount_point)
return [self.end_dir, self.start_dir, mount_points] |
java | public BoundStatement getQueryStatement(CqlRowSliceQueryImpl<?,?> rowSliceQuery, boolean useCaching) {
switch (rowSliceQuery.getColQueryType()) {
case AllColumns:
return SelectAllColumnsForRowRange.getBoundStatement(rowSliceQuery, useCaching);
case ColumnSet:
return SelectColumnSetForRowRange.getBoundSta... |
python | def chunks_str(str, n, separator="\n", fill_blanks_last=True):
"""returns lines with max n characters
:Example:
>>> print (chunks_str('123456X', 3))
123
456
X
"""
return separator.join(chunks(str, n)) |
java | private boolean mustContinue(BitSet potentialNode) {
boolean result = true;
boolean cancel = false;
BitSet projG1 = projectG1(potentialNode);
BitSet projG2 = projectG2(potentialNode);
// if we reached the maximum number of
// search iterations than do not continue
... |
java | public static GitHub getClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setLogLevel(RestAdapter.LogLevel.BASIC)
.build();
return restAdapter.create(GitHub.class);
} |
python | def bulk_send(self, topic, kmsgs, timeout=60):
""" Send a batch of messages
:param str topic: a kafka topic
:param ksr.transport.Message kmsgs: Messages to serialize
:param int timeout: Timeout in seconds
:return: Execution result
:rtype: kser.result.Result
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.