language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void curveTo2 (final float x2, final float y2, final float x3, final float y3) throws IOException
{
if (inTextMode)
{
throw new IllegalStateException ("Error: curveTo2 is not allowed within a text block.");
}
writeOperand (x2);
writeOperand (y2);
writeOperand (x3);
writeOperan... |
python | def make_request(self, method, *args, **kwargs):
"""Creates a request from a method function call."""
if args and not use_signature:
raise NotImplementedError("Only keyword arguments allowed in Python2")
new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()}
if use_signature:
... |
python | def make_context(headers: Headers) -> Optional[TraceContext]:
"""Converts available headers to TraceContext, if headers mapping does
not contain zipkin headers, function returns None.
"""
# TODO: add validation for trace_id/span_id/parent_id
# normalize header names just in case someone passed regu... |
python | def __update_rating(uid, rating):
'''
Update rating.
'''
entry = TabRating.update(
rating=rating
).where(TabRating.uid == uid)
entry.execute() |
python | def ucs_manager_connect(self, ucsm_ip):
"""Connects to a UCS Manager."""
if not self.ucsmsdk:
self.ucsmsdk = self._import_ucsmsdk()
ucsm = CONF.ml2_cisco_ucsm.ucsms.get(ucsm_ip)
if not ucsm or not ucsm.ucsm_username or not ucsm.ucsm_password:
LOG.error('UCS Mana... |
python | def query(self, *args, **kwargs):
"""
Reimplemented from base class.
This method does not add additional functionality of the
base class' :meth:`~couchbase.bucket.Bucket.query` method (all the
functionality is encapsulated in the view class anyway). However it
does requi... |
python | def connect(self, force=False):
'''Establish a connection'''
# Don't re-establish existing connections
if not force and self.alive():
return True
self._reset()
# Otherwise, try to connect
with self._socket_lock:
try:
logger.info('... |
java | public static Function<Object,Boolean> bool(final String methodName, final Object... optionalParameters) {
return methodForBoolean(methodName, optionalParameters);
} |
java | public void marshall(AssociationOverview associationOverview, ProtocolMarshaller protocolMarshaller) {
if (associationOverview == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associationOverview.ge... |
python | def _id_handler(self, f):
"""
Given a Feature from self.iterator, figure out what the ID should be.
This uses `self.id_spec` identify the ID.
"""
# If id_spec is a string, convert to iterable for later
if isinstance(self.id_spec, six.string_types):
id_key = ... |
python | def _parse_return(cls, result):
"""Extract the result, return value and context from a result object
"""
return_value = None
success = result['result']
context = result['context']
if 'return_value' in result:
return_value = result['return_value']
re... |
java | public void marshall(Beard beard, ProtocolMarshaller protocolMarshaller) {
if (beard == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(beard.getValue(), VALUE_BINDING);
protocolMarshaller... |
python | def loadAddressbyID(self, id, callback=None, errback=None):
"""
Load an existing address by ID into a high level Address object
:param int id: id of an existing Address
"""
import ns1.ipam
address = ns1.ipam.Address(self.config, id=id)
return address.load(callbac... |
java | public static <R> MethodResult<R> success(R result) {
return new MethodResult<>(result, null, false);
} |
java | protected boolean exists(PointcutPatternRule pointcutPatternRule, String transletName,
String beanId, String className, String methodName) {
boolean matched = true;
if (transletName != null && pointcutPatternRule.getTransletNamePattern() != null) {
matched = patt... |
java | @Override
public synchronized boolean removeHost(Host host, boolean refresh) {
HostConnectionPool<CL> pool = hosts.remove(host);
if (pool != null) {
topology.removePool(pool);
rebuildPartitions();
monitor.onHostRemoved(host);
pool.shutdown();
... |
python | def create_normal_logq(self,z):
"""
Create logq components for mean-field normal family (the entropy estimate)
"""
means, scale = self.get_means_and_scales()
return ss.norm.logpdf(z,loc=means,scale=scale).sum() |
python | def arg_comparitor(name):
"""
:param arg name
:return: pair containing name, comparitor
given an argument name, munge it and return a proper comparitor
>>> arg_comparitor("a")
a, operator.eq
>>> arg_comparitor("a__in")
a, operator.contains
"""
if name.endswith("__in"):
... |
java | public BaseTile getBaseTile (int tx, int ty)
{
BaseTile tile = _base[index(tx, ty)];
if (tile == null && _defset != null) {
tile = (BaseTile)_defset.getTile(
TileUtil.getTileHash(tx, ty) % _defset.getTileCount());
}
return tile;
} |
java | public static void serializeCopyableDataset(State state, CopyableDatasetMetadata copyableDataset) {
state.setProp(SERIALIZED_COPYABLE_DATASET, copyableDataset.serialize());
} |
java | public static boolean validateSignatureForPost(String body, Map<String, String> headers, String url, String apiKey) throws OneTouchException, UnsupportedEncodingException {
HashMap<String, String> params = new HashMap<>();
if (body == null || body.isEmpty())
throw new OneTouchException("'PAR... |
java | public static int[] executeBatch(Connection conn, Iterable<String> sqls) throws SQLException {
Statement statement = null;
try {
statement = conn.createStatement();
for (String sql : sqls) {
statement.addBatch(sql);
}
return statement.executeBatch();
} finally {
DbUtil.close(statement);
}
} |
java | public Map<String, CmsModuleVersion> getInstalledModules() {
String file = CmsModuleConfiguration.DEFAULT_XML_FILE_NAME;
// /opencms/modules/module[?]
String basePath = new StringBuffer("/").append(CmsConfigurationManager.N_ROOT).append("/").append(
CmsModuleConfiguration.N_MODULES)... |
python | def main():
"""
What will be executed when running as a stand alone program.
"""
args = parse_args()
try:
s = pyhsm.base.YHSM(device=args.device, debug=args.debug)
get_entropy(s, args.iterations, args.ratio)
return 0
except pyhsm.exception.YHSM_Error as e:
sys.st... |
python | def _parse_names_set(feature_names):
"""Helping function of `_parse_feature_names` that parses a set of feature names."""
feature_collection = OrderedDict()
for feature_name in feature_names:
if isinstance(feature_name, str):
feature_collection[feature_name] = ..... |
java | public static double KullbackLeiblerDivergence(SparseArray x, double[] y) {
if (x.isEmpty()) {
throw new IllegalArgumentException("List x is empty.");
}
Iterator<SparseArray.Entry> iter = x.iterator();
boolean intersection = false;
double kl = 0.0;
while (it... |
python | def generate_synonym(self, input_word):
""" Generate Synonym using a WordNet
synset.
"""
results = []
results.append(input_word)
synset = wordnet.synsets(input_word)
for i in synset:
index = 0
syn = i.name.split('.')
i... |
java | @Override
public final void setReportNAN(Boolean value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setReportNAN", value);
if (value != null) {
getApi().setField(JsApiAccess.REPORTNAN_VALUE, value);
}
else {
... |
java | private long extractCommittedSpHandle(ExportRow row, long committedSeqNo) {
long ret = 0;
if (committedSeqNo == ExportDataSource.NULL_COMMITTED_SEQNO) {
return ret;
}
// Get the rows's sequence number (3rd column)
long seqNo = (long) row.values[2];
if (seqNo ... |
java | protected String cleanDocumentationContent( String content ) {
Pattern REMOVE_WHITESPACE_AND_LINE_FEEDS_PATTERN = Pattern.compile("[\\n\\r\\s]+");
Matcher matcher = REMOVE_WHITESPACE_AND_LINE_FEEDS_PATTERN.matcher(content);
return matcher.replaceAll(" ");
} |
python | def setCurrentPage( self, pageno ):
"""
Sets the current page for this widget to the inputed page.
:param pageno | <int>
"""
if ( pageno == self._currentPage ):
return
if ( pageno <= 0 ):
pageno = 1
... |
java | protected void initializeDataExtends(Relation<NumberVector> relation, int dim, double[] min, double[] extend) {
assert (min.length == dim && extend.length == dim);
// if no parameter for min max compute min max values for each dimension
// from dataset
if(minima == null || maxima == null || minima.lengt... |
python | def reward_battery(self):
"""
Add a battery level reward
"""
if not 'battery' in self.mode:
return
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['reward'] += ... |
java | @GwtIncompatible("Unnecessary")
private boolean shouldGenerateOutputPerModule(String output) {
return !config.module.isEmpty()
&& output != null && output.contains("%outname%");
} |
java | @RequestMapping(value = "download/{branchId}")
public ResponseEntity<String> download(@PathVariable ID branchId, String path) {
return gitService.download(structureService.getBranch(branchId), path)
.map(ResponseEntity::ok)
.orElseThrow(
() -> new SCMD... |
java | @Override
public EClass getIfcCartesianTransformationOperator3DnonUniform() {
if (ifcCartesianTransformationOperator3DnonUniformEClass == null) {
ifcCartesianTransformationOperator3DnonUniformEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(85);
}
... |
java | public static boolean loadLibrary(String shortName, int loadFlags) throws UnsatisfiedLinkError {
sSoSourcesLock.readLock().lock();
try {
if (sSoSources == null) {
// This should never happen during normal operation,
// but if we're running in a non-Android environment,
// fall back... |
python | def tile(ctx, point, zoom):
"""Print Tile containing POINT.."""
tile = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile_from_xy(*point, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
click.echo('%s %s %s' % tile.id)
... |
python | def track_name_event(self, name):
"""Return the bytes for a track name meta event."""
l = self.int_to_varbyte(len(name))
return '\x00' + META_EVENT + TRACK_NAME + l + name |
python | def add_vrf(self):
""" Add a new VRF to NIPAP and return its data.
"""
v = VRF()
if 'rt' in request.json:
v.rt = validate_string(request.json, 'rt')
if 'name' in request.json:
v.name = validate_string(request.json, 'name')
if 'description' in requ... |
java | public boolean isInverse() {
Boolean value = (Boolean) getStateHelper().eval(PropertyKeys.inverse, false);
return (boolean) value;
} |
java | public String domain_confirmTermination_POST(String domain, String commentary, OvhTerminationReasonEnum reason, String token) throws IOException {
String qPath = "/email/domain/{domain}/confirmTermination";
StringBuilder sb = path(qPath, domain);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody... |
python | def upload_async(data_service_auth_data, config, upload_id,
filename, index, num_chunks_to_send, progress_queue):
"""
Method run in another process called from ParallelChunkProcessor.make_and_start_process.
:param data_service_auth_data: tuple of auth data for rebuilding DataServiceAuth
... |
java | public static boolean pushImage(Launcher launcher, final JenkinsBuildInfoLog log, final String imageTag, final String username, final String password, final String host)
throws IOException, InterruptedException {
return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {... |
java | @Override
public <G, H> Choice6<A, B, C, D, G, H> biMap(Function<? super E, ? extends G> lFn,
Function<? super F, ? extends H> rFn) {
return match(Choice6::a, Choice6::b, Choice6::c, Choice6::d, e -> e(lFn.apply(e)), f -> f(rFn.apply(f)));
} |
java | @Nullable
private static DimFilter toExpressionLeafFilter(
final PlannerContext plannerContext,
final RowSignature rowSignature,
final RexNode rexNode
)
{
final DruidExpression druidExpression = toDruidExpression(plannerContext, rowSignature, rexNode);
return druidExpression != null
... |
java | public void marshall(SubResourceSummary subResourceSummary, ProtocolMarshaller protocolMarshaller) {
if (subResourceSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(subResourceSummary.getTyp... |
java | public static String serializeFromField(final Object containingObject, final String fieldName,
final int indentWidth, final boolean onlySerializePublicFields, final ClassFieldCache classFieldCache) {
final FieldTypeInfo fieldResolvedTypeInfo = classFieldCache
.get(containingObject.ge... |
java | @NonNull public <T> T peek(int index) {
//noinspection unchecked
return (T) history.get(history.size() - index - 1);
} |
python | def replace(self, replacements):
"""
Replace variables with other variables.
:param dict replacements: A dict of variable replacements.
:return: self
"""
for old_var, new_var in replacements.items():
old_var_id = id(old_var)
... |
java | public static int searchLast(short[] shortArray, short value, int occurrence) {
if(occurrence <= 0 || occurrence > shortArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
... |
java | private static void addOne2InverseMap(DisconfKey disconfKey, Map<DisconfKey, List<IDisconfUpdate>> inverseMap,
IDisconfUpdate iDisconfUpdate) {
// 忽略的key 应该忽略掉
if (DisClientConfig.getInstance().getIgnoreDisconfKeySet().contains(disconfKey.getKey())) {
... |
python | def redraw(self, reset_camera=False):
"""
Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False.
"""
self.ren.RemoveAllViewProps()
self.picker = None
... |
java | public void notEnabled(double seconds) {
double end = System.currentTimeMillis() + (seconds * 1000);
try {
double timeTook = elementPresent(seconds);
WebDriverWait wait = new WebDriverWait(element.getDriver(), (long) (seconds - timeTook), DEFAULT_POLLING_INTERVAL);
wa... |
java | public void addPenalizingValidation(Object key, PenalizingValidation penalizingValidation){
initMapOnce();
penalties.put(key, penalizingValidation);
// update penalized value
if(!penalizingValidation.passed()){
assignedPenalties = true;
double p = penalizingValida... |
python | def defUtilityFuncs(self):
'''
Defines CRRA utility function for this period (and its derivatives),
saving them as attributes of self for other methods to use.
Parameters
----------
none
Returns
-------
none
'''
self.u = lambda ... |
python | def handle_log_entry(self, m):
'''handling incoming log entry'''
if m.time_utc == 0:
tstring = ''
else:
tstring = time.ctime(m.time_utc)
self.entries[m.id] = m
print("Log %u numLogs %u lastLog %u size %u %s" % (m.id, m.num_logs, m.last_log_num, m.size, ts... |
java | @Override
public CompletableFuture<ExecutionInfo> executeAsyncWithStats() {
final StatementWrapper statementWrapper = new NativeStatementWrapper(getOperationType(boundStatement), meta, boundStatement, encodedBoundValues);
final String queryString = statementWrapper.getBoundStatement().preparedState... |
java | public Object lookup(String name) {
Object result = null;
for (Registry reg: registryList){
result = reg.lookup(name);
if (result != null){
break;
}
}
return result;
} |
python | def get_linkrolls(num='All', destination_slug=None, *args, **kwargs):
"""
Takes an optional number and destination slug and returns a list of LinkRolls.
Given a number, return list limited to the given number.
Given a destination slug, limit linkrolls to the matching destination.
Usage:
{% g... |
java | public static void initialize(MapWidget mapWidget, SearchHandler searchResultGrid, boolean modalSearch) {
SearchWidgetRegistry.mapWidget = mapWidget;
searchController = new SearchController(mapWidget, modalSearch);
favouritesController = new FavouritesController();
if (searchResultGrid != null) {
searchContr... |
python | def sync(self, owner, id, **kwargs):
"""
Sync files
Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to use webhooks or scr... |
python | def get_bitcoind( new_bitcoind_opts=None, reset=False, new=False ):
"""
Get or instantiate our bitcoind client.
Optionally re-set the bitcoind options.
"""
global bitcoind
if reset:
bitcoind = None
elif not new and bitcoind is not None:
return bitcoind
if new or bitcoind is None:... |
python | def delete_source(ident):
'''Delete an harvest source'''
source = get_source(ident)
source.deleted = datetime.now()
source.save()
signals.harvest_source_deleted.send(source)
return source |
python | def new(self, platform_id):
# type: (int) -> None
'''
A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing.
'''
if self._initialized:
raise ... |
python | def export(cls, folder, particles, datetimes):
"""
Export trackline data to GeoJSON file
"""
normalized_locations = [particle.normalized_locations(datetimes) for particle in particles]
track_coords = []
for x in xrange(0, len(datetimes)):
points = MultiPo... |
java | public final void mINSERT_REALTIME() throws RecognitionException {
try {
int _type = INSERT_REALTIME;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:583:17: ( ( 'INSERT_REALTIME' | 'insert_realtime' ) )
// druidG.g:583:18: ( 'INSERT_REALTIME' | 'insert_realtime' )
{
// druidG.g:583:18: ( 'INSERT_... |
java | @Override
public List<CPInstance> findByCPDefinitionId(long CPDefinitionId,
int start, int end) {
return findByCPDefinitionId(CPDefinitionId, start, end, null);
} |
java | @RequestMapping(value = "changeLog/fileFilter/{projectId}/create", method = RequestMethod.POST)
public Resource<SCMFileChangeFilter> createChangeLogFileFilter(@PathVariable ID projectId, @RequestBody SCMFileChangeFilter filter) {
securityService.checkProjectFunction(projectId.get(), ProjectConfig.class);
... |
java | public long getDuration(TimeUnit targetUnit) {
if (isRunning()) {
throw new IllegalStateException("The clock is not yet stopped.");
}
return targetUnit.convert(durationNanos, TimeUnit.NANOSECONDS);
} |
python | def fn_mean(self, a, axis=None):
"""
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array.
"""
return numpy.nanmean(self._to_ndarray(a), axis=axis) |
java | public void saveOldProperty(Map<String,String> oldProperties, String param)
{
oldProperties.put(param, this.getTask().getProperty(param));
} |
java | @SuppressWarnings("unchecked")
public static Expression<String> likeToRegex(Expression<String> expr, boolean matchStartAndEnd) {
// TODO : this should take the escape character into account
if (expr instanceof Constant<?>) {
final String like = expr.toString();
final StringBu... |
java | @Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int contentWidth = mWidth - paddingLeft - paddingRight;
int contentHeight = mHeight - paddingTop - paddingBottom;
mCirclePaint.setStyle(Paint.Style.FILL);
mCirclePaint.setColor(Color.RED);
// Dra... |
python | def maf_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
drop_silent=False):
"""Performs null-permutations across all genes and records the results in
a format like a MAF... |
python | def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... |
python | def _accumulate(iterable, func=(lambda a,b:a+b)): # this was from the itertools documentation
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
... |
python | def optimize_layout(
head_embedding,
tail_embedding,
head,
tail,
n_epochs,
n_vertices,
epochs_per_sample,
a,
b,
rng_state,
gamma=1.0,
initial_alpha=1.0,
negative_sample_rate=5.0,
verbose=False,
):
"""Improve an embedding using stochastic gradient descent to mi... |
java | public static <T> boolean arrayContainsRef(T[] array, T value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
} |
python | def str2dict(strdict, required_keys=None, optional_keys=None):
"""Convert key1=value1,key2=value2,... string into dictionary.
:param strdict: string in the form of key1=value1,key2=value2
:param required_keys: list of required keys. All keys in this list must be
specified. Otherwise ... |
java | @Override
List<XMLFilter> getProcessingPipe(final URI fileToParse) {
final List<XMLFilter> pipe = new ArrayList<>();
if (genDebugInfo) {
final DebugFilter debugFilter = new DebugFilter();
debugFilter.setLogger(logger);
debugFilter.setCurrentFile(currentFile);
... |
python | def verify_sms_code(phone_number, code):
"""
获取到手机验证码之后,验证验证码是否正确。如果验证失败,抛出异常。
:param phone_number: 需要验证的手机号码
:param code: 接受到的验证码
:return: None
"""
params = {
'mobilePhoneNumber': phone_number,
}
leancloud.client.post('/verifySmsCode/{0}'.format(code), params=params)
ret... |
python | def fixup_building_sdist():
''' Check for 'sdist' and ensure we always build BokehJS when packaging
Source distributions do not ship with BokehJS source code, but must ship
with a pre-built BokehJS library. This function modifies ``sys.argv`` as
necessary so that ``--build-js`` IS present, and ``--inst... |
python | def initialize(self):
""" A reimplemented initializer.
This method will add the include objects to the parent of the
include and ensure that they are initialized.
"""
super(Block, self).initialize()
block = self.block
if block: #: This block is setting the con... |
java | public void marshall(DeleteFacetRequest deleteFacetRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteFacetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteFacetRequest.getSch... |
java | public void setExcludedMembers(java.util.Collection<String> excludedMembers) {
if (excludedMembers == null) {
this.excludedMembers = null;
return;
}
this.excludedMembers = new com.amazonaws.internal.SdkInternalList<String>(excludedMembers);
} |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BpsimPackage.PRIORITY_PARAMETERS__INTERRUPTIBLE:
return interruptible != null;
case BpsimPackage.PRIORITY_PARAMETERS__PRIORITY:
return priority != null;
}
return super.eIsSet(featureID);
} |
python | def crossMatchTo(self, reference, radius=1*u.arcsec, visualize=False):
'''
Cross-match this catalog onto another reference catalog.
If proper motions are included in the reference, then
its coordinates will be propagated to the obstime/epoch
of this current catalog.
Para... |
python | def check(self, diff):
r"""Check that the new file introduced has a valid name
The module can either be an __init__.py file or must
match ``feature_[a-zA-Z0-9_]+\.\w+``.
"""
filename = pathlib.Path(diff.b_path).parts[-1]
is_valid_feature_module_name = re_test(
... |
java | public byte[] set(byte[] key,byte[] value){
Jedis jedis = jedisPool.getResource();
try{
jedis.set(key,value);
if(this.expire != 0){
jedis.expire(key, this.expire);
}
}finally{
jedisPool.returnResource(jedis);
}
return value;
} |
python | def parse(self):
"""Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy."""
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <... |
python | def get_vmpolicy_macaddr_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vmpolicy_macaddr = ET.Element("get_vmpolicy_macaddr")
config = get_vmpolicy_macaddr
output = ET.SubElement(get_vmpolicy_macaddr, "output")
has_mo... |
java | private static String getResourceBase() {
String resourceBase = setting.getStr("webRoot");
if (StrUtil.isEmpty(resourceBase)) {
resourceBase = "./src/main/webapp";// 用于Maven测试
File file = new File(resourceBase);
if (false == file.exists() || false == file.isDirectory()) {
resourceBase = ".";
... |
java | public boolean goInto(ElementContext rootContext, String... innerElements) throws IOException, XMLException {
ElementContext parent = rootContext;
for (int i = 0; i < innerElements.length; ++i) {
if (!nextInnerElement(parent, innerElements[i]))
return false;
parent = event.context.getFirst();
}
... |
python | def add_node(self, node):
"""Add a node and connect it to the center."""
nodes = self.nodes()
if len(nodes) > 1:
first_node = min(nodes, key=attrgetter("creation_time"))
first_node.connect(direction="both", whom=node) |
python | def available_string(self, episode):
"""Return a string of available episodes."""
available = [ep for ep in self if ep > episode]
string = ','.join(str(ep) for ep in available[:self.EPISODES_TO_SHOW])
if len(available) > self.EPISODES_TO_SHOW:
string += '...'
return s... |
java | protected void disposeCacheValue(T value)
{
if (value instanceof DisposableCacheValue) {
try {
((DisposableCacheValue) value).dispose();
} catch (Throwable e) {
// We catch Throwable because this method is usually automatically called by an event send ... |
java | public final void synpred6_InternalSARL_fragment() throws RecognitionException {
// InternalSARL.g:7821:4: ( ( () 'synchronized' '(' ) )
// InternalSARL.g:7821:5: ( () 'synchronized' '(' )
{
// InternalSARL.g:7821:5: ( () 'synchronized' '(' )
// InternalSARL.g:7822:5: () 'sync... |
python | def assert_same_rank(self, other):
"""Raises an exception if `self` and `other` do not have convertible ranks.
Args:
other: Another `TensorShape`.
Raises:
ValueError: If `self` and `other` do not represent shapes with the
same rank.
"""
other = a... |
java | public static <T extends Comparable<T>> RelationalOperator<T> lessThanEqualToOrGreaterThan(T lowerBound, T upperBound) {
return ComposableRelationalOperator.compose(lessThanEqualTo(lowerBound), LogicalOperator.OR, greaterThan(upperBound));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.