language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String getStatusAsString(int status)
{
if (status >= Status.STATUS_ACTIVE && status <= Status.STATUS_ROLLING_BACK)
{
return TX_STATUS_STRINGS[status];
}
else
{
return "STATUS_INVALID(" + status + ")";
}
} |
java | static Class getClassForName(String className)
throws ClassNotFoundException
{
// Hack for backwards compatibility with XalanJ1 stylesheets
if(className.equals("org.apache.xalan.xslt.extensions.Redirect")) {
className = "org.apache.xalan.lib.Redirect";
}
return ObjectFactory.findProviderC... |
java | @Deprecated
@Inline(value="$3.$4sortWith($1, $2)", imported=IterableExtensions.class)
public static <T> List<T> sort(Iterable<T> iterable, Comparator<? super T> comparator) {
return sortWith(iterable, comparator);
} |
java | @Test(groups = {SAMPLES})
public void getMonitoringStatisticsGroupedByDatacenters() {
List<MonitoringStatsEntry> stats = statisticsService
.monitoringStats()
.forGroups(
new GroupFilter().nameContains(nameCriteria)
)
.forTime(new ServerMonitori... |
python | def verify(expr, params=None):
"""
Determine if expression can be successfully translated to execute on
MapD
"""
try:
compile(expr, params=params)
return True
except com.TranslationError:
return False |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'used_bytes') and self.used_bytes is not None:
_dict['used_bytes'] = self.used_bytes
return _dict |
java | public Date rescheduleJob (final TriggerKey triggerKey, final ITrigger newTrigger) throws SchedulerException
{
validateState ();
if (triggerKey == null)
throw new IllegalArgumentException ("triggerKey cannot be null");
if (newTrigger == null)
throw new IllegalArgumentException ("newTrigger ca... |
python | def _init_project_service(self, version):
"""
Method to initialize the Project Service from the config data
Args:
version (string): Version of Boss API to use.
Returns:
None
Raises:
(KeyError): if given invalid version.
"""
p... |
python | def add(self, name: Any) -> None:
"""Before adding a new name, it is checked to be valid variable
identifiers.
>>> from hydpy.core.devicetools import Keywords
>>> keywords = Keywords('first_keyword', 'second_keyword',
... 'keyword_3', 'keyword_4',
...... |
java | public static <T> List<Collection<T>> partitionIntoFolds(List<T> values, int numFolds) {
List<Collection<T>> folds = new ArrayList<Collection<T>>();
int numValues = values.size();
int foldSize = numValues / numFolds;
int remainder = numValues % numFolds;
int start = 0;
int end = fold... |
python | def detect_converters(pattern: str,
converter_dict: Dict[str, Callable],
default: Callable = str):
""" detect pairs of varname and converter from pattern"""
converters = {}
for matched in VARS_PT.finditer(pattern):
matchdict = matched.groupdict()
v... |
python | def is_identifier(s):
"""Check whether given string is a valid Python identifier.
Note that this excludes language keywords, even though they exhibit
a general form of an identifier. See also :func:`has_identifier_form`.
:param s: String to check
:return: Whether ``s`` is a valid Python identifier... |
java | @Override
public String getUserDisplayName(String userSecurityName) throws EntryNotFoundException, RegistryException {
if (userSecurityName == null) {
throw new IllegalArgumentException("userSecurityName is null");
}
if (userSecurityName.isEmpty()) {
throw new Illegal... |
python | def set_split_extents_by_indices_per_axis(self):
"""
Sets split shape :attr:`split_shape` and
split extents (:attr:`split_begs` and :attr:`split_ends`)
from values in :attr:`indices_per_axis`.
"""
if self.indices_per_axis is None:
raise ValueError("Got None fo... |
python | def setValue(self, key, value):
"""
Some devices allow to directly set values to perform a specific task.
"""
LOG.debug("HMGeneric.setValue: address = '%s', key = '%s' value = '%s'" % (self._ADDRESS, key, value))
try:
self._proxy.setValue(self._ADDRESS, key, value)
... |
python | def gen_yaml_category():
'''
find YAML.
'''
for wroot, _, wfiles in os.walk('./database/meta'):
for wfile in wfiles:
if wfile.endswith('.yaml'):
gen_category(os.path.join(wroot, wfile), wfile[0]) |
python | def I(self,**kwargs): #pragma: no cover
"""
NAME:
I
PURPOSE:
Calculate I, the 'ratio' between the radial and azimutha period
INPUT:
+scipy.integrate.quadrature keywords
OUTPUT:
I(R,vT,vT) + estimate of the error
HISTORY:
... |
python | def __construct_really (project, name, target_type, prop_set, sources):
""" Attempts to construct target by finding viable generators, running them
and selecting the dependency graph.
"""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
... |
python | def ScanForVolumeSystem(self, source_path_spec):
"""Scans the path specification for a supported volume system format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: volume system path specification or None if no supported volume
system type was foun... |
java | static boolean contains(CodeSigner[] set, CodeSigner signer)
{
for (int i = 0; i < set.length; i++) {
if (set[i].equals(signer))
return true;
}
return false;
} |
python | def to_drawdown_series(prices):
"""
Calculates the `drawdown <https://www.investopedia.com/terms/d/drawdown.asp>`_ series.
This returns a series representing a drawdown.
When the price is at all time highs, the drawdown
is 0. However, when prices are below high water marks,
the drawdown series ... |
python | def lines_diff(before_lines, after_lines, check_modified=False):
'''Diff the lines in two strings.
Parameters
----------
before_lines : iterable
Iterable containing lines used as the baseline version.
after_lines : iterable
Iterable containing lines to be compared against the baseli... |
java | public void learn(RNNSearch<double[], double[]> range, double[][] samples, double radius, int Nz, double sigma) {
TrainSample[] training = new TrainSample[samples.length];
for (int i = 0; i < samples.length; i++) {
training[i] = new TrainSample();
training[i].query = samples[i];
... |
java | public static Path pathForFileInRoot(
final File rootDir,
final File file
)
{
String filePath = file.getAbsolutePath();
String rootPath = rootDir.getAbsolutePath();
if (!filePath.startsWith(rootPath)) {
throw new IllegalArgumentException("not a file in... |
java | public final Tuple7<T2, T3, T4, T5, T6, T7, T8> skip1() {
return new Tuple7<>(v2, v3, v4, v5, v6, v7, v8);
} |
python | def run(self):
'''
Run server.
:return:
'''
listen_ip = self._config.get(self.LISTEN_IP, self.DEFAULTS[self.LISTEN_IP])
port = self._config.get(self.PORT, self.DEFAULTS[self.PORT])
self.log.info('Starting service discovery listener on udp://%s:%s', listen_ip, port... |
java | private void updateTransitive(Collection<Tile> resolved, Tile tile, Tile neighbor, GroupTransition transitive)
{
final String transitiveOut = transitive.getOut();
final Transition transition = new Transition(TransitionType.CENTER, transitiveOut, transitiveOut);
final Collection<TileRef> ... |
python | def init(self, with_soft=True):
"""
The method for the SAT oracle initialization. Since the oracle is
is used non-incrementally, it is reinitialized at every iteration
of the MaxSAT algorithm (see :func:`reinit`). An input parameter
``with_soft`` (``False`` by def... |
java | public void readData(String path) {
reset();
resetP();
this.jTextFieldResultPath.setText(path);
this.path = path;
rf = new ReadFile(path);
String str = rf.processFiles();
if (str.equals("")) {
int algSize = rf.getAlgShortNames().size();
in... |
python | def close(self):
"""
Unclaim the PEP node and unregister the registered features.
It is not necessary to call close if this claim is managed by
:class:`~aioxmpp.pep.register_pep_node`.
"""
if self._closed:
return
self._closed = True
self._pep... |
python | def _get_history_lines(self):
"""Returns list of history entries."""
history_file_name = self._get_history_file_name()
if os.path.isfile(history_file_name):
with io.open(history_file_name, 'r',
encoding='utf-8', errors='ignore') as history_file:
... |
python | def get_commands_from_file(self, mission_file, role):
"""Get commands from xml file as a list of (command_type:int, turnbased:boolean, command:string)"""
doc = etree.parse(mission_file)
mission = doc.getroot()
return self.get_commands_from_xml(mission, role) |
java | public boolean removeAll(final Collection<?> c, final long occurrences) {
checkOccurrences(occurrences);
if (N.isNullOrEmpty(c) || occurrences == 0) {
return false;
}
boolean result = false;
for (Object e : c) {
if (result == false) {
... |
python | def usergroup_list(**kwargs):
'''
Retrieve all enabled user groups.
.. versionadded:: 2016.3.0
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see... |
java | public static String getLatkeProperty(final String key) {
String ret = latkeProps.getProperty(key);
if (StringUtils.isBlank(ret)) {
return ret;
}
ret = replaceEnvVars(ret);
return ret;
} |
java | protected void afterSend(RpcInternalContext context, InvokeContext invokeContext, SofaRequest request) {
currentRequests.decrementAndGet();
if (RpcInternalContext.isAttachmentEnable()) {
putToContextIfNotNull(invokeContext, InvokeContext.CLIENT_CONN_CREATETIME, context,
RpcCo... |
java | private static Pointer mapMemory(String mapName, int mode, int size) {
HANDLE mapping = Kernel32.INSTANCE.OpenFileMapping(mode, false, mapName);
Pointer v = Kernel32.INSTANCE.MapViewOfFile(mapping, mode, 0, 0, new SIZE_T(size));
Kernel32.INSTANCE.CloseHandle(mapping);
return v;
} |
python | def _pnorm_diagweight(x, p, w):
"""Diagonally weighted p-norm implementation."""
# Ravel both in the same order (w is a numpy array)
order = 'F' if all(a.flags.f_contiguous for a in (x.data, w)) else 'C'
# This is faster than first applying the weights and then summing with
# BLAS dot or nrm2
x... |
java | public WasInvalidatedBy newWasInvalidatedBy(QualifiedName id, QualifiedName entity, QualifiedName activity, XMLGregorianCalendar time, Collection<Attribute> attributes) {
WasInvalidatedBy res=newWasInvalidatedBy(id,entity,activity);
res.setTime(time);
setAttributes(res, attributes);
return res;
} |
python | def _get_domain_id(self, domain):
"""
Pulls all domains managed by authenticated Hetzner account, extracts their IDs
and returns the ID for the current domain, if exists. Otherwise raises error.
"""
api = self.api[self.account]['domain_id']
qdomain = dns.name.from_text(do... |
java | HashMap<String, byte[]> getExplainPlans(Catalog catalog) {
HashMap<String, byte[]> retval = new HashMap<>();
Database db = getCatalogDatabase(m_catalog);
assert(db != null);
for (Procedure proc : db.getProcedures()) {
for (Statement stmt : proc.getStatements()) {
... |
java | public static <T extends CatalogType> void getSortedCatalogItems(CatalogMap<T> items, String sortFieldName, List<T> result) {
result.addAll(getSortedCatalogItems(items, sortFieldName ));
} |
python | def unused_keys(self):
"""Lists all keys which are present in the ConfigTree but which have not been accessed."""
unused = set()
for k, c in self._children.items():
if isinstance(c, ConfigNode):
if not c.has_been_accessed():
unused.add(k)
... |
java | public ActiveTrustedSigners withItems(Signer... items) {
if (this.items == null) {
setItems(new com.amazonaws.internal.SdkInternalList<Signer>(items.length));
}
for (Signer ele : items) {
this.items.add(ele);
}
return this;
} |
java | protected RequestContext createRequestContext(HttpServletRequest request, HttpServletResponse response) {
return new RequestContext(request, response, servletContext);
} |
java | public int filterObject(CaptureSearchResult r) {
String resultUrl = r.getUrlKey();
return url.equals(resultUrl) ?
FILTER_INCLUDE : FILTER_ABORT;
} |
python | def node_labels(node_labels, node_indices):
"""Validate that there is a label for each node."""
if len(node_labels) != len(node_indices):
raise ValueError("Labels {0} must label every node {1}.".format(
node_labels, node_indices))
if len(node_labels) != len(set(node_labels)):
ra... |
python | def get_instance(self, payload):
"""
Build an instance of WorkerStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.work... |
python | def to_csv(col, options={}):
"""
Converts a column containing a :class:`StructType` into a CSV string.
Throws an exception, in the case of an unsupported type.
:param col: name of column containing a struct.
:param options: options to control converting. accepts the same options as the CSV datasour... |
python | def setPageCount( self, pageCount ):
"""
Sets the number of pages that this widget holds.
:param pageCount | <int>
"""
if ( pageCount == self._pageCount ):
return
pageCount = max(1, pageCount)
self._pageCount ... |
java | @Override
public String toJsonString( Object obj ) {
try {
return objectMapper.writeValueAsString( obj );
}
catch ( IOException e ) {
throw new JsonMarshalException("Unable to serialize object : " + obj, e );
}
} |
python | def clean(self, value):
"""Clean
Goes through each of the values in the list, cleans it, stores it, and
returns a new list
Arguments:
value {list} -- The value to clean
Returns:
list
"""
# If the value is None and it's optional, return as is
if value is None and self._optional:
return None
... |
python | def _string_to_int(x, vocab):
"""Given a vocabulary and a string tensor `x`, maps `x` into an int tensor.
Args:
x: A `Column` representing a string value.
vocab: list of strings.
Returns:
A `Column` where each string value is mapped to an integer representing
its index in the vocab. Out of vocab ... |
java | public static SimpleModule getModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(Headers.class, new HeadersSerializer());
return module;
} |
java | @Deprecated
public static <PE extends ExtensionElement> PE packetExtensionfromCollection(
Collection<ExtensionElement> collection, String element,
String namespace) {
return extensionElementFrom(collection, element, namespace);
} |
java | public ThymeLeafTemplateImplementation addTemplate(Bundle bundle, URL templateURL) {
ThymeLeafTemplateImplementation template = getTemplateByURL(templateURL);
if (template != null) {
// Already existing.
return template;
}
synchronized (this) {
// need... |
java | <V> ElementRule<T, V> getRule(ChronoElement<V> element) {
return this.getChronology().getRule(element);
} |
python | def challenges(self):
"""
Access the challenges
:returns: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeList
"""
if self._challenges is None:
self._challenges = Challen... |
python | def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[strin... |
java | @AnyThread
public void bodyRemovedFromChannel (ChatChannel channel, final int bodyId)
{
_peerMan.invokeNodeAction(new ChannelAction(channel) {
@Override protected void execute () {
ChannelInfo info = _channelMan._channels.get(_channel);
if (info != null) {
... |
python | def euler_tour(G, node=None, seen=None, visited=None):
"""
definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edges = [
>>... |
python | def query(self, coords, **kwargs):
"""
Returns E(B-V), in mags, at the specified location(s) on the sky.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of the reddening, in magnitudes of E(B-V), at the
... |
python | def __logfile_error(self, e):
"""
Shows an error message to standard error
if the log file can't be written to.
Used internally.
@type e: Exception
@param e: Exception raised when trying to write to the log file.
"""
from sys import stderr
msg =... |
python | def paged_call(function, *args, **kwargs):
"""Retrieve full set of values from a boto3 API call that may truncate
its results, yielding each page as it is obtained.
"""
marker_flag = kwargs.pop('marker_flag', 'NextMarker')
marker_arg = kwargs.pop('marker_arg', 'Marker')
while True:
ret =... |
python | def _meta_name(self, name):
"""
Translate HTTP header names to the format used by Django request objects.
See https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpRequest.META
"""
name = name.upper().replace('-', '_')
if name not in self.UNPREFIXED... |
java | public int getLength()
{
if (m_count == -1)
{
short count = 0;
for (int n = dtm.getFirstAttribute(element); n != -1;
n = dtm.getNextAttribute(n))
{
++count;
}
m_count = count;
}
return (int) m_count;
} |
python | def paginate(objects, page_num, per_page, max_paging_links):
"""
Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``.
"""
if not per_page:
return Paginator(objects, 0)
paginator = Paginator(objects, per_p... |
java | public static int silog2Wide(long v) {
while (true) {
if (v == 0) return 0;
if (v > 0) {
int l = 0;
while (v != 0) {
l++;
v >>= 1;
}
return l + 1;
}
if (v == -1... |
python | def __get_subnetwork(vm_):
'''
Get configured subnetwork.
'''
ex_subnetwork = config.get_cloud_config_value(
'subnetwork', vm_, __opts__,
search_global=False)
return ex_subnetwork |
java | @Override
public LiferayWarPackagingProcessor importBuildOutput(
MavenResolutionStrategy strategy) {
log.debug("Building Liferay Plugin Archive");
ParsedPomFile pomFile = session.getParsedPomFile();
// Compile and add Java classes
if (Validate.isReadable(pomFile.getSourceDirectory())) {
compile(
p... |
python | def deserialize(data):
"""
Create instance from serial data
"""
# Import module & get class
try:
module = import_module(data.get('class').get('module'))
cls = getattr(module, data.get('class').get('name'))
except ImportError:
raise Impo... |
python | def train(hparams, output_dir, env_problem_name, report_fn=None):
"""Train."""
env_fn = initialize_env_specs(hparams, env_problem_name)
tf.logging.vlog(1, "HParams in trainer_model_free.train : %s",
misc_utils.pprint_hparams(hparams))
tf.logging.vlog(1, "Using hparams.base_algo: %s", hparams.... |
java | public void addValueToKey(K key, V value) {
this.addValuesToKey(key, Collections.singletonList(value));
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case XtextPackage.TYPE_REF__METAMODEL:
setMetamodel((AbstractMetamodelDeclaration)null);
return;
case XtextPackage.TYPE_REF__CLASSIFIER:
setClassifier((EClassifier)null);
return;
}
super.eUnset(featureID);
} |
python | def call(self, method, *args, **kwargs):
"""
Make an XML-RPC call to the server.
If this client is logged in (with login()), this call will be
authenticated.
Koji has its own custom implementation of XML-RPC that supports named
args (kwargs). For example, to use the "qu... |
java | public void processDocument(WikiDoc doc) {
String rawArticleName = doc.name;
String articleName = StringUtils.unescapeHTML(rawArticleName);
articleName = articleName.trim().toLowerCase();
// skip articles that are not text-based or are
// wikipedia-specific
if (... |
python | def division(
cls,
divisor,
dividend,
base,
precision=None,
method=RoundingMethods.ROUND_DOWN
):
"""
Division of natural numbers.
:param divisor: the divisor
:type divisor: list of int
:param dividend: the dividend
:type di... |
python | def downstream(self, f, n=1):
"""find n downstream features where downstream is determined by
the strand of the query Feature f
Overlapping features are not considered.
f: a Feature object
n: the number of features to return
"""
if f.strand == -1:
ret... |
java | public UniqueEntityLoader buildLoader(
OuterJoinLoadable persister,
int batchSize,
LockOptions lockOptions,
SessionFactoryImplementor factory,
LoadQueryInfluencers influencers,
BatchableEntityLoaderBuilder innerEntityLoaderBuilder) {
if ( batchSize <= 1 ) {
// no batching
return buildNonBatchi... |
java | public ProxyDataSourceBuilder logSlowQueryToSysOut(long thresholdTime, TimeUnit timeUnit) {
this.createSysOutSlowQueryListener = true;
this.slowQueryThreshold = thresholdTime;
this.slowQueryTimeUnit = timeUnit;
return this;
} |
python | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Frame Relay switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_num... |
python | def check_status_code(response, codes=None):
"""
Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid
"""
codes = codes or [200]
if response.status_code... |
java | public void markTask(StatusTrail st, boolean success) {
st.setStatus(success ? JobStatus.done : JobStatus.not_done);
st.setAttemptsDone(st.getAttemptsDone() + 1);
st.setGivenUp(st.getAttemptsDone() >= getMaxTaskAttempts() ? 1 : 0);
updateStatusTrail(st);
} |
python | def _create_security_groups(self, role):
"""
Create the security groups for a given role, including a group for the
cluster if it doesn't exist.
"""
self._check_role_name(role)
security_group_names = self._get_all_group_names()
cluster_group_name = self._get_cluster_group_name()
if not ... |
java | private SOAPElement constructSoapHeader(Map<String, Object> headerData,
AdWordsServiceDescriptor adWordsServiceDescriptor) {
String requestHeaderNamespace =
adWordsApiConfiguration.getNamespacePrefix() + "/"
+ adWordsServiceDescriptor.getPackageGroup() + "/"
+ adWordsServiceDes... |
java | private EJBException mapCSIException(EJSDeployedSupport s, CSIException e, Exception rootEx)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "mapCSIException: " + e);
}
String message = " ";
EJBException ejbex;
if (e instanceof C... |
java | @Override
public void initIterator(Partition dp, S config) {
jdbcDeepJobConfig = initConfig(config, jdbcDeepJobConfig);
this.jdbcReader = new JdbcReader(jdbcDeepJobConfig);
try {
this.jdbcReader.init(dp);
} catch(Exception e) {
throw new DeepGenericException("... |
python | def should_show_by_depth(self, cur_level=None):
"""
Args:
cur_level (int): depth level to take into account
Returns:
bool: True if the given depth level should show messages (not
taking into account the log level)
"""
if cur_level is None:... |
java | public String getPrefixStatsMultiplePositionPrefixAttribute(String field) {
return String.join(MtasToken.DELIMITER, multiplePositionPrefix.get(field));
} |
java | private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
Frame frame = ScreenUtil.getFrame(this);
frame.remove(this);
if (frame != null)
ScreenUtil.centerDialogInFrame(loginDialog, frame);
loginDialog.setVisible(t... |
java | private Node createCommaNode(Node expr1, Node expr2) {
Node commaNode = IR.comma(expr1, expr2);
if (shouldAddTypesOnNewAstNodes) {
commaNode.setJSType(expr2.getJSType());
}
return commaNode;
} |
java | static Object workObject(Map<String, Object> workList, String name, boolean isArray) {
logger.trace("get working object for {}", name);
if (workList.get(name) != null) return workList.get(name);
else {
String[] parts = splitName(name); // parts: (parent, name, isArray)
... |
java | @Override
public InputSource resolveEntity(String publicId, String systemId) {
logger.debug("CMLResolver: resolving ", publicId, ", ", systemId);
systemId = systemId.toLowerCase();
if ((systemId.indexOf("cml-1999-05-15.dtd") != -1) || (systemId.indexOf("cml.dtd") != -1)
|| (s... |
java | private static StringBuffer generateBody(MetaEntity entity, Context context) {
StringWriter sw = new StringWriter();
PrintWriter pw = null;
try {
pw = new PrintWriter( sw );
if ( context.addGeneratedAnnotation() ) {
pw.println( writeGeneratedAnnotation( entity, context ) );
}
if ( context.isAddSu... |
java | public static ParamWrapper newInstance(String key, Object value) {
Map<String, Object> paramMap = new HashMap<String, Object>(16);
paramMap.put(key, value);
return new ParamWrapper(paramMap);
} |
python | def _setup_resources():
"""Attempt to increase resource limits up to hard limits.
This allows us to avoid out of file handle limits where we can
move beyond the soft limit up to the hard limit.
"""
target_procs = 10240
cur_proc, max_proc = resource.getrlimit(resource.RLIMIT_NPROC)
target_pr... |
java | @Override
public void initialize(IAggregator aggregator, IAggregatorExtension extension,
IExtensionRegistrar registrar) {
final String sourceMethod = "initialize"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(BundleVersionsHash.class.getName... |
python | def parse(self, inputstring, parser, preargs, postargs):
"""Use the parser to parse the inputstring with appropriate setup and teardown."""
self.reset()
pre_procd = None
with logger.gather_parsing_stats():
try:
pre_procd = self.pre(inputstring, **preargs)
... |
python | def cleanup(self):
"""
Return aggregated (table, rowdata) tuples and clear the state.
"""
inserts = []
last_run = self._runs[self._last_run_id]
if 'end' not in last_run:
last_run['end'] = datetime.now()
for run_id in sorted(self._runs):
r... |
python | def read_format_from_metadata(text, ext):
"""Return the format of the file, when that information is available from the metadata"""
metadata = read_metadata(text, ext)
rearrange_jupytext_metadata(metadata)
return format_name_for_ext(metadata, ext, explicit_default=False) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.