language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static void addLinkHeader(HttpServletResponse response,
CaptureSearchResults results, WaybackRequest wbr,
boolean includeTimegateLink, boolean includeOriginalLink) {
response.setHeader(
LINK,
generateMementoLinkHeaders(results, wbr, includeTimegateLink,
includeOriginalLink));
} |
java | @Override
public void disable(final String jobType, final String comment) {
setValue(jobType, KEY_DISABLED, comment != null ? comment : "");
} |
python | def construct_xblock(self, block_type, scope_ids, field_data=None, *args, **kwargs):
r"""
Construct a new xblock of the type identified by block_type,
passing \*args and \*\*kwargs into `__init__`.
"""
return self.construct_xblock_from_class(
cls=self.load_block_type(... |
python | def visitTerminal(self, ctx):
"""Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values.
"""
text = str(super().visitTerm... |
java | public static double[] tileLatLonBounds( int tx, int ty, int zoom, int tileSize ) {
double[] bounds = tileBounds3857(tx, ty, zoom, tileSize);
double[] mins = metersToLatLon(bounds[0], bounds[1]);
double[] maxs = metersToLatLon(bounds[2], bounds[3]);
return new double[]{mins[1], maxs[0], ... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.GBIMG__XPOS:
return getXPOS();
case AfplibPackage.GBIMG__YPOS:
return getYPOS();
case AfplibPackage.GBIMG__FORMAT:
return getFORMAT();
case AfplibPackage.GBIMG__RES:
re... |
python | def await_message(self, *args, **kwargs) -> 'asyncio.Future[Message]':
"""
Block until a message matches. See `on_message`
"""
fut = asyncio.Future()
@self.on_message(*args, **kwargs)
async def handler(message):
fut.set_result(message)
# remove handler... |
python | def _set_local_file_path(self):
"""
Take from environment variable, create dirs and
create file if doesn' exist.
"""
self.FILE_LOCAL = self._transfer.get_env('FILE_LOCAL')
if not self.FILE_LOCAL:
filename = '{}_{}.{}'.format(str(self._transfer.prefix),
... |
python | def repeat(col, n):
"""
Repeats a string column n times, and returns it as a new string column.
>>> df = spark.createDataFrame([('ab',)], ['s',])
>>> df.select(repeat(df.s, 3).alias('s')).collect()
[Row(s=u'ababab')]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.func... |
python | def check_required_columns(df, filename, required_columns):
"""
Ensure that all required columns are present in the given dataframe,
otherwise raise an exception.
"""
available_columns = set(df.columns)
for column_name in required_columns:
if column_name not in available_columns:
... |
java | public static List<CPMeasurementUnit> findByUuid_C(String uuid,
long companyId) {
return getPersistence().findByUuid_C(uuid, companyId);
} |
python | def queries(self):
"""
Access the queries
:returns: twilio.rest.autopilot.v1.assistant.query.QueryList
:rtype: twilio.rest.autopilot.v1.assistant.query.QueryList
"""
if self._queries is None:
self._queries = QueryList(self._version, assistant_sid=self._soluti... |
java | private boolean scopeIncludesImplicitOrAttributeTypes(GraqlCompute query) {
if (query.in().isEmpty()) return false;
return query.in().stream().anyMatch(t -> {
Label label = Label.of(t);
SchemaConcept type = tx.getSchemaConcept(label);
return (type != null && (type.isA... |
java | public ServiceCall<Entity> updateEntity(UpdateEntityOptions updateEntityOptions) {
Validator.notNull(updateEntityOptions, "updateEntityOptions cannot be null");
String[] pathSegments = { "v1/workspaces", "entities" };
String[] pathParameters = { updateEntityOptions.workspaceId(), updateEntityOptions.entity(... |
python | def tag(self):
'''
:param tag:
Checks out specified tag. If set to ``None`` the latest
tag will be checked out
:returns:
A list of all tags, sorted as version numbers, ascending
'''
tag = self.m(
'getting git tags',
cmd... |
python | def quaternion_rotation(quat, vector):
"""Apply the rotation represented by the quaternion to the vector
Warning: This only works correctly for normalized quaternions.
"""
dp = np.dot(quat[1:], vector)
cos = (2*quat[0]*quat[0] - 1)
return np.array([
2 * (quat[0] * (quat[2] * vector[2... |
java | public void unpin()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "unpin: " + ivBeanId);
synchronized (ivBucket)
{
if (pinned > 0)
{
pinned--;
// Touch the LRU flag; since an object cannot... |
java | public static BshMethod getMethod(Object object, String name, Class<?>[] sig) {
return getMethod(getThisNS(object), name, sig);
} |
java | public Datatype.Builder mapType(UnaryOperator<TypeClass> mapper) {
Objects.requireNonNull(mapper);
return setType(mapper.apply(getType()));
} |
python | def plot_path(line, lattice=None, coords_are_cartesian=False, ax=None,
**kwargs):
"""
Adds a line passing through the coordinates listed in 'line' to a matplotlib Axes
Args:
line: list of coordinates.
lattice: Lattice object used to convert from reciprocal to cartesian coordin... |
java | public void setValue(Object obj, Object value) {
if (setters.length > 0) {
for (Method method : setters) {
if (value == null || method.getParameterTypes()[0].isAssignableFrom(value.getClass())) {
try {
method.invoke(obj, value);
return;
} catch (IllegalAcces... |
java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WMenu menu = (WMenu) component;
XmlStringBuilder xml = renderContext.getWriter();
int rows = menu.getRows();
xml.appendTagOpen("ui:menu");
xml.appendAttribute("id", component.getId());
xml.appendOptionalA... |
java | private void parseAttachment(final DirectoryEntry dir, final OutlookMessage msg)
throws IOException {
final OutlookFileAttachment attachment = new OutlookFileAttachment();
// iterate through all document entries
for (final Iterator<?> iter = dir.getEntries(); iter.hasNext(); ) {
final Entry entry = (Entry... |
python | def get_seqstarts(bamfile, N):
""" Go through the SQ headers and pull out all sequences with size
greater than the resolution settings, i.e. contains at least a few cells
"""
import pysam
bamfile = pysam.AlignmentFile(bamfile, "rb")
seqsize = {}
for kv in bamfile.header["SQ"]:
if kv[... |
python | def cvm_stat(data):
"""
Calculates the Cramer-von Mises statistic for sorted values from U(0, 1).
"""
samples2 = 2 * len(data)
minuends = arange(1, samples2, 2) / samples2
return 1 / (6 * samples2) + ((minuends - data) ** 2).sum() |
python | def plot_run_nlive(method_names, run_dict, **kwargs):
"""Plot the allocations of live points as a function of logX for the input
sets of nested sampling runs of the type used in the dynamic nested
sampling paper (Higson et al. 2019).
Plots also include analytically calculated distributions of relative
... |
java | private Service getServiceInfos(ClassLoader compileClassLoader) {
Service service = new Service();
// get some service properties from pom
service.setServiceId(serviceId);
service.setName(project.getName());
// find @ServiceDoc annotated class in source folder
JavaProjectBuilder builder = new ... |
python | def is_file(dirname):
'''Checks if a path is an actual file that exists'''
if not os.path.isfile(dirname):
msg = "{0} is not an existing file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname |
python | def absolutize(self, region_id, relative_address):
"""
Convert a relative address in some memory region to an absolute address.
:param region_id: The memory region ID
:param relative_address: The relative memory offset in that memory region
:return: ... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'label') and self.label is not None:
_dict['label'] = self.label
if hasattr(self, 'value') and self.value is not None:
_dict['value'] = self.value._to_dict()
... |
java | public static String diff(String expression) throws InvalidExpressionException {
ExpressionTree expTree = parseToTree(expression);
expTree.derive();
expTree.reduce();
return expTree.toString();
} |
python | def console(cls, id):
"""Open a console to virtual machine."""
vm_info = cls.info(id)
if not vm_info['console']:
# first activate console
cls.update(id, memory=None, cores=None, console=True,
password=None, background=False, max_memory=None)
... |
python | def float(self, item, default=None):
""" Return value of key as a float
:param item: key of value to transform
:param default: value to return if item does not exist
:return: float of value
"""
try:
item = self.__getattr__(item)
except AttributeError ... |
java | @Help(
help = "Create the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id"
)
public PhysicalNetworkFunctionRecord postPhysicalNetworkFunctionRecord(
final String idNsr, final PhysicalNetworkFunctionRecord physicalNetworkFunctionRecord)
throws SDKException {
String url = ... |
java | public double linearInterpolateY( double xValue ) {
double first = xList[0];
double last = xList[xList.length - 1];
// check out of range
if (first <= last) {
if (xValue < xList[0] || xValue > xList[xList.length - 1]) {
return Double.NaN;
}
... |
java | public static String unescapeHtml(final String text) {
if (text == null) {
return null;
}
if (text.indexOf('&') < 0) {
// Fail fast, avoid more complex (and less JIT-table) method to execute if not needed
return text;
}
return HtmlEscapeUtil.un... |
python | def relpath(path, start=posixpath.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = posixpath.abspath(start).split(posixpath.sep)
path_list = posixpath.abspath(path).split(posixpath.sep)
# Work out how much of the filepath is... |
python | def quantstr(typestr, num, plural_suffix='s'):
r"""
Heuristically generates an english phrase relating to the quantity of
something. This is useful for writing user messages.
Args:
typestr (str): singular form of the word
num (int): quanity of the type
plural_suffix (str): heur... |
java | @Override
public Query query(Schema schema) {
BooleanQuery luceneQuery = new BooleanQuery();
luceneQuery.setBoost(boost);
for (Condition query : must) {
luceneQuery.add(query.query(schema), Occur.MUST);
}
for (Condition query : should) {
luceneQuery.ad... |
python | def all_pairs_normalized_distances_reference(X):
"""
Reference implementation of normalized all-pairs distance, used
for testing the more efficient implementation above for equivalence.
"""
n_samples, n_cols = X.shape
# matrix of mean squared difference between between samples
D = np.ones((n... |
python | def _save_bm_state(self):
"""Save current state of ``block_matcher``."""
for parameter in self.block_matcher.parameter_maxima.keys():
self.bm_settings[parameter].append(
self.block_matcher.__getattribute__(parameter)) |
java | public synchronized void pushMetric(final MetricsRecord mr) {
if (changed) {
try {
mr.setMetric(getName(), value);
} catch (Exception e) {
LOG.info("pushMetric failed for " + getName() + "\n" +
StringUtils.stringifyException(e));
}
}
changed = false;
} |
java | private String getFNSignatureFromIContext(INode node) {
String ret = node.getNodeData().getName();
List<INode> children = node.getChildrenList();
if (children != null && children.size() > 0) {
ret += "(";
for (INode aChildren : children) {
ret += g... |
python | def metric_get(self, project, metric_name):
"""API call: retrieve a metric resource.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/get
:type project: str
:param project: ID of the project containing the metric.
:type metric_name: str
... |
java | public SimpleJob setSimpleJoin(String[] masterLabels, String masterColumn,
String dataColumn, String masterPath) {
String separator = conf.get(SEPARATOR);
return setSimpleJoin(masterLabels, masterColumn, dataColumn, masterPath, separator, false);
} |
python | def _get_simple_assignments(tree):
"""Get simple assignments from node tree."""
result = {}
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
result[target.id] = node.value
ret... |
python | def ws025(self, value=None):
""" Corresponds to IDD Field `ws025`
Wind speed corresponding to 2.5% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `ws025`
Unit: m/s
if `value` is None it will not be checked against ... |
python | def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
... |
java | protected Authorizable resolveAuthorizable(final String authorizableId) throws RepositoryException {
final Session session = getAdminSession();
final UserManager userManager = ((JackrabbitSession) session).getUserManager();
final Authorizable authorizable = userManager.getAuthorizable(authoriza... |
python | def _read_work_units_file(self, work_units_fh):
'''work_units_fh is iterable on lines (could actually be ['{}',...])
'''
count = 0
for line in work_units_fh:
if not line:
continue
line = line.strip()
if not line:
continu... |
java | @Override
public com.liferay.commerce.model.CPDAvailabilityEstimate deleteCPDAvailabilityEstimate(
long CPDAvailabilityEstimateId)
throws com.liferay.portal.kernel.exception.PortalException {
return _cpdAvailabilityEstimateLocalService.deleteCPDAvailabilityEstimate(CPDAvailabilityEstimateId);
} |
java | public long readStartCode() throws IOException {
byte frameCode = in.readByte();
if (frameCode != 'N') {
return (long) (frameCode & 0xff);
}
// Otherwise read the remaining 64bit startCode
byte[] buffer = new byte[8];
buffer[0] = frameCode;
readFully(buffer, 1, 7);
return (((long)... |
java | private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
feedback = UserFeedback.Cancel;
synchronized (WAITER_LOCK) {
okButton.setEnabled(false);
cancelButton.setEnabled(false);
WAITER_LOCK.notifyAll();
... |
python | def mnemonic(self, value):
"""Set instruction mnemonic.
"""
if value not in REIL_MNEMONICS:
raise Exception("Invalid instruction mnemonic : %s" % str(value))
self._mnemonic = value |
java | public static void setXSLTVersion(String s) {
try {
Number n = NumberFormat.getInstance(Locale.US).parse(s);
if (n.doubleValue() < 0) {
throw new ConfigurationException(s + " doesn't reperesent a"
+ " positive number.");
... |
python | def nodes_to_object(self, node, object):
"Map all child nodes to one object's attributes"
for n in list(node):
self.node_to_object(n, object) |
java | public Options put(String key, IComplexOption value)
{
options.put(key, value);
return this;
} |
java | @SuppressWarnings("unchecked")
public EList<IfcConnectedFaceSet> getFbsmFaces() {
return (EList<IfcConnectedFaceSet>) eGet(Ifc2x3tc1Package.Literals.IFC_FACE_BASED_SURFACE_MODEL__FBSM_FACES,
true);
} |
python | def set_state(self, state):
"""
Set the state of this device to on or off.
"""
self.basicevent.SetBinaryState(BinaryState=int(state))
self._state = int(state) |
python | def release_apply(ui, repo, clname, **opts):
"""apply a CL to the release branch
Creates a new CL copying a previously committed change
from the main branch to the release branch.
The current client must either be clean or already be in
the release branch.
The release branch must be created by starting with a
... |
java | public byte[] getRawData() throws IOException
{
int contentLength = request.getContentLength();
if( contentLength<0 ) {
return null;
}
byte[] buffer = new byte[contentLength];
ServletInputStream is = request.getInputStream();
for (int i = 0; i < c... |
python | def date_range(cls,start_time,end_time,freq):
'''
Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound fo... |
java | public void setMnemonic(int mnemonic) {
this.mnemonic = mnemonic;
renderButton.setMnemonic(mnemonic);
editButton.setMnemonic(mnemonic);
} |
python | def annotateText(self, text, layer, addEmptyAnnotations = True):
''' Applies this WordTemplate ( more specifically: its method self.matchingTokens() )
on all words of given text, and adds results of the matching to the text as
a new annotation layer. Returns the input text (which is ... |
java | public BitString[] learn(int size, int generation, ClassifierTrainer<double[]> trainer, ClassificationMeasure measure, double[][] x, int[] y, int k) {
if (size <= 0) {
throw new IllegalArgumentException("Invalid population size: " + size);
}
if (k < 2) {
throw ne... |
python | def setup_app(app, cfg):
"""Setup Flask app and handle reverse proxy setup if configured.
Arguments:
app - Flask application
cfg - configuration data
"""
# Set up app_host and app_port in case that we are running
# under reverse proxy setup, otherwise they default to
# config.ho... |
java | @Override
public void tidyUpUIContext() {
RepeaterModel model = getComponentModel();
if (model.rowContextMap != null) {
for (Iterator<Map.Entry<Object, SubUIContext>> i = model.rowContextMap.entrySet().
iterator(); i.hasNext();) {
Map.Entry<Object, SubUIContext> entry = i.next();
SubUIContext subC... |
python | def group_members(self, group_id, include_orphans=False):
"""
Find all group member trigger definitions
:param group_id: group trigger id
:param include_orphans: If True, include orphan members
:return: list of asociated group members as trigger objects
"""
param... |
python | def explore_tabs(self, *, num_items=100, genre_id=None):
"""Get a listing of explore tabs.
Parameters:
num_items (int, Optional): Number of items per tab to return.
Default: ``100``
genre_id (genre_id, Optional): Genre ID from :meth:`explore_genres` to explore.
Default: ``None``.
Returns:
dict:... |
python | def get_time_interval(time1, time2):
'''get the interval of two times'''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2)... |
python | def inspect(self, w):
""" Get the value of a wirevector in the last simulation cycle.
:param w: the name of the WireVector to inspect
(passing in a WireVector instead of a name is deprecated)
:return: value of w in the current step of simulation
Will throw KeyError if w is ... |
java | static <T> T resolveAttributeFromMap(
Node node, String attributeName, Map<String, ? extends T> map)
{
String id = XmlUtils.getAttributeValue(node, attributeName, null);
if (id == null)
{
throw new XmlException(
"No attribute \""+attributeName+"\" f... |
python | def cancel_offer(self, offer_id):
"""
Cancelles an offer
:param offer_id: the offer id
:return Response
"""
return self._create_put_request(
resource=OFFERS,
billomat_id=offer_id,
command=CANCEL,
) |
python | def build_pattern(body, features):
'''Converts body into a pattern i.e. a point in the features space.
Applies features to the body lines and sums up the results.
Elements of the pattern indicate how many times a certain feature occurred
in the last lines of the body.
'''
line_patterns = apply_... |
java | private void associateVariablesWithBlocks() {
int varRefNo = 0;
int activeBlockNo = 0;
int nextBlockNo = 1;
while (varRefNo < varRefTabCnt) {
VarRefTabRec vrtr = varRefTab[varRefNo];
int varRefTPos = vrtr.tPosBegin;
int varNo = vrtr.varNo;
... |
python | def as_entry(self, energies):
"""
Returns a ComputedEntry representation of the reaction.
:return:
"""
relevant_comp = [comp * abs(coeff) for coeff, comp
in zip(self._coeffs, self._all_comp)]
comp = sum(relevant_comp, Composition())
entry ... |
java | private int getComponentState(JComponent c, Region region) {
if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON && c.isEnabled()) {
if (((JTextComponent) c).getText().length() == 0) {
return DISABLED;
} else if (isCancelArmed) {
return PRESSED;
... |
python | def image_create(request, **kwargs):
"""Create image.
:param kwargs:
* copy_from: URL from which Glance server should immediately copy
the data and store it in its configured image store.
* data: Form data posted from client.
* location: URL where the data for this image alr... |
java | @Override
public final <T> String evalSqlSelect(final Map<String, Object> pAddParam,
final Class<T> pEntityClass) throws Exception {
String tableName = pEntityClass.getSimpleName().toUpperCase();
StringBuffer result = new StringBuffer("select ");
StringBuffer joints = new StringBuffer();
boolean i... |
python | def _handle_POST(self, env, start_response):
"""Dispatch Method called by twisted render, creates a
request/response handler chain.
request -- twisted.web.server.Request
"""
input = env['wsgi.input']
data = input.read( int(env['CONTENT_LENGTH']) )
mimeType = "text... |
python | def list_of_dict(self):
"""
This will convert the data from a list of list to a list of dictionary
:return: list of dict
"""
ret = []
for row in self:
ret.append(dict([(self._col_names[i], row[i]) for i in
range(len(self._col_names... |
java | public static MozuUrl getShippingInclusionRuleUrl(String id, String profilecode, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/shipping/admin/profiles/{profilecode}/rules/shippinginclusions/{id}?responseFields={responseFields}");
formatter.formatUrl("id", id);
formatter.fo... |
python | def is_directory(value, **kwargs):
"""Indicate whether ``value`` is a directory that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contai... |
python | def get_payload(self):
"""Return Payload."""
ret = bytes([self.status.value])
ret += bytes([self.session_id >> 8 & 255, self.session_id & 255])
return ret |
java | public static void validateEntityID(final EntityID id) {
int changes = 0;
// Changed new UUID(m, l)
if (id.mostSigBits() != EntityID.DEFAULT_MOST_SIG_BITS
|| id.leastSigBits() != EntityID.DEFAULT_LEAST_SIG_BITS) {
changes++;
}
// Changed fromString(n)
if (!EntityID.DEFAULT_NAME.equals(id.name())) {
c... |
python | def set_uploading(self, files_uploaded):
""" set_uploading: records progress during uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
"""
self.files_uploaded = files_uploaded
self.__record_progress(Statu... |
python | def pvwatts_dc(self, g_poa_effective, temp_cell):
"""
Calcuates DC power according to the PVWatts model using
:py:func:`pvwatts_dc`, `self.module_parameters['pdc0']`, and
`self.module_parameters['gamma_pdc']`.
See :py:func:`pvwatts_dc` for details.
"""
kwargs = _... |
python | def get_initial_broks(self, broker_name):
"""Send a HTTP request to the satellite (GET /_initial_broks)
Used to build the initial broks for a broker connecting to a scheduler
:param broker_name: the concerned broker name
:type broker_name: str
:return: Boolean indicating if the... |
java | @Override
public void draw(@NonNull Canvas canvas) {
final boolean positionChanged = adapterPositionChanged();
if (rippleOverlay) {
super.draw(canvas);
if (!positionChanged) {
if (rippleRoundedCornersPx != 0) {
Path clipPath = new Path();
... |
python | def _detect_eggs_in_folder(folder):
"""
Detect egg distributions located in the given folder.
Only direct folder content is considered and subfolders are not searched
recursively.
"""
eggs = {}
for x in os.listdir(folder):
zip = x.endswith(_zip_ext)
if zip:
... |
java | public StringArray getSemanticTypes() {
if (OntClassMention_Type.featOkTst && ((OntClassMention_Type)jcasType).casFeat_semanticTypes == null)
jcasType.jcas.throwFeatMissing("semanticTypes", "de.julielab.jules.types.OntClassMention");
return (StringArray)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_g... |
python | def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades.
.. versionadded:: 2018.3.0
refresh
Whether or not to refresh the package database before installing.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
pkgs = {}
for... |
python | def backup_file(*, file, host):
"""
Perform backup action
:param file: Name of the file to be used by the driver
:param host: Corresponding host name associated with file
"""
log.msg("[{host}] Backing up file '{file}'".format(host=host, file=file)) |
python | def write_entity(self, entity):
"""
Write a single entity to a line in the output file
"""
db, db_object_id = self._split_prefix(entity)
taxon = normalize_taxon(entity["taxon"]["id"])
vals = [
db,
db_object_id,
entity.get('label'),
... |
java | public static Integer max(Connection connection, String table,
String column, String where, String[] args) {
Integer max = null;
if (count(connection, table, where, args) > 0) {
StringBuilder maxQuery = new StringBuilder();
maxQuery.append("select max(")
.append(CoreSQLUtils.quoteWrap(column)).append... |
java | public static AudioFormat getFailsafe()
{
try
{
return new Sc68Format();
}
catch (final LionEngineException exception)
{
Verbose.exception(exception, ERROR_LOAD_LIBRARY);
return new AudioVoidFormat(FORMATS);
}
} |
python | def get_ancestors(self):
"""
:returns: A queryset containing the current node object's ancestors,
starting by the root node and descending to the parent.
"""
if self.is_root():
return get_result_class(self.__class__).objects.none()
return get_result_class(... |
java | public static InetAddress InetAddressByIPv4(String address) {
StringTokenizer addressTokens = new StringTokenizer(address, ".");
byte[] bytes;
if (addressTokens.countTokens() == 4) {
bytes = new byte[]{
getByBytes(addressTokens),
getByBytes(addressTokens),
getByByt... |
java | public void stop() {
if (mMonitorStarted) {
mMonitorStarted = false;
Looper.getMainLooper().setMessageLogging(null);
mBlockCanaryCore.stackSampler.stop();
mBlockCanaryCore.cpuSampler.stop();
}
} |
java | private AstNode propertyAccess(int tt, AstNode pn)
throws IOException
{
if (pn == null) codeBug();
int memberTypeFlags = 0, lineno = ts.lineno, dotPos = ts.tokenBeg;
consumeToken();
if (tt == Token.DOTDOT) {
mustHaveXML();
memberTypeFlags = Node.D... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.