language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @NullSafe
public static ClassLoader getContextClassLoader(Thread thread) {
return (thread != null ? thread.getContextClassLoader() : ThreadUtils.class.getClassLoader());
} |
java | private static OkHttpClient client() {
return COREUTILS_CONTEXT.getClient(OkHttpClient.class, "coreutils-fiber", () -> {
final OkHttpClient client = new FiberOkHttpClient();
try {
// load default configuration
final Config config = new Configurer().loadConfig(null, "coreutils");
final long tmp = con... |
java | private void removeFromPermissionsCache(IPermission[] permissions)
throws AuthorizationException {
IAuthorizationPrincipal[] principals = getPrincipalsFromPermissions(permissions);
removeFromPermissionsCache(principals);
} |
java | public final long getRemainingTimeToLive() {
long ttl = getHdr2().getLongField(JsHdr2Access.TIMETOLIVE);
if (ttl > 0) {
return ttl - getMessageWaitTime().longValue();
}
else {
return -1;
}
} |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString name_validator = new MPSString();
name_validator.setConstraintIsReq(MPSConstants.DELETE_CONSTRAINT, true);
name_validator.setConstraintCharSetRegEx(MPSConstants.GENERIC_CONSTRAINT,"[ a-zA-Z0-9_#.:@=... |
python | def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: list
... |
java | public PagedList<SasDefinitionItem> getSasDefinitions(final String vaultBaseUrl, final String storageAccountName, final Integer maxresults) {
ServiceResponse<Page<SasDefinitionItem>> response = getSasDefinitionsSinglePageAsync(vaultBaseUrl, storageAccountName, maxresults).toBlocking().single();
return n... |
java | public static String utf2string(byte[] src, int sindex, int len) {
char dst[] = new char[len];
int len1 = utf2chars(src, sindex, dst, 0, len);
return new String(dst, 0, len1);
} |
python | def dmql(query):
"""Client supplied raw DMQL, ensure quote wrap."""
if isinstance(query, dict):
raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required."
" Did you mean to pass this to the search_filter parameter? ")
... |
java | public FieldInfoList getFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
// Implement field overriding
final FieldInfoList fieldInfoList = new FieldInfoList();
fi... |
python | def release(self, owner, access):
""" Release the lock """
assert isinstance(access, LockAccess)
debuglog("%s release(%s, %s)" % (self, owner, access.mode))
if not self._removeOwner(owner, access):
debuglog("%s already released" % self)
return
self._tryW... |
python | def compute_collections(self):
""" Finds the collections (clusters,chains) that exist in parsed_response.
Modified:
- self.collection_sizes: populated with a list of integers indicating
the number of units belonging to each collection
- self.collection_indices: p... |
python | def transform(self, X):
"""Transform data by adding two synthetic feature(s).
Parameters
----------
X: numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples and n_components is the number of components.
Returns
-------
... |
java | @Override
public void onMacroBlock(String macroName, WikiParameters params, String content)
{
getListener().onMacro(macroName, convertParameters(params), content, false);
} |
java | private <X extends Class, T extends Object> void populateMetadata(EntityMetadata metadata, Class<X> clazz,
Map puProperties)
{
// process for metamodelImpl
if (metadata.getPersistenceUnit() != null)
{
MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getAppli... |
java | @Override
protected int writeParameterWordsWireFormat ( byte[] dst, int dstIndex ) {
int start = dstIndex;
SMBUtil.writeInt2(this.fid, dst, dstIndex);
dstIndex += 2;
SMBUtil.writeInt2(this.mode, dst, dstIndex);
dstIndex += 2;
SMBUtil.writeInt4(this.offset, dst, dstInd... |
java | protected void setFlashCookie(HttpServerExchange exchange) {
Flash flash = this.attachment.getFlash();
Form form = this.attachment.getForm();
if (flash.isDiscard() || flash.isInvalid()) {
final Cookie cookie = new CookieImpl(this.config.getFlashCookieName())
... |
python | def _get_client_fqdn(self, client_info_contents):
"""Extracts a GRR client's FQDN from its client_info.yaml file.
Args:
client_info_contents: The contents of the client_info.yaml file.
Returns:
A (str, str) tuple representing client ID and client FQDN.
"""
yamldict = yaml.safe_load(cli... |
python | def GetRendererForValueOrClass(cls, value, limit_lists=-1):
"""Returns renderer corresponding to a given value and rendering args."""
if inspect.isclass(value):
value_cls = value
else:
value_cls = value.__class__
cache_key = "%s_%d" % (value_cls.__name__, limit_lists)
try:
render... |
python | def parse_docstring(docstring):
"""Parse the docstring into its components.
:return: a dictionary of form
{
"short_description": ...,
"long_description": ...,
"params": [{"name": ..., "doc": ...}, ...],
"vals": [{"name": ...,... |
java | public QueryHits execute(JcrIndexSearcher searcher, SessionImpl session, Sort sort) throws IOException
{
if (sort.getSort().length == 0)
{
return hits;
}
else
{
return null;
}
} |
java | @Override
public final void visit(final SourceDocument document) {
setBaseObject(new ApiSource(document.getType(), document.getString(),
title(document)));
addSplitAttributes(document);
} |
python | def _print_status(self):
'''Print an entire status line including bar and stats.'''
self._clear_line()
self._print(' ')
if self.max_value:
self._print_percent()
self._print(' ')
self._print_bar()
else:
self._print_throbber()
... |
java | public static MessageDigest getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm... |
java | public long getHardLinkId(String src) throws IOException {
byte[][] components = INode.getPathComponents(src);
readLock();
try {
INodeFile node = this.getFileINode(components);
if ((!exists(node)) || (!(node instanceof INodeHardLinkFile))) {
throw new IOException(src + " is not a valid h... |
java | public List<T> getAll(Rows<?, String> rows) throws InstantiationException,
IllegalAccessException {
List<T> list = Lists.newArrayList();
for (Row<?, String> row : rows) {
if (!row.getColumns().isEmpty()) {
list.add(newInstance(row.getColumns()));
}
... |
python | def update_instance(
self,
update_mask,
instance,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Updates the metadata and configuration of a specific Redis instance.
Comple... |
java | public Observable<ComapiResult<MessageSentResponse>> sendMessage(@NonNull final String conversationId, @NonNull final String body) {
SessionData session = dataMgr.getSessionDAO().session();
return sendMessage(conversationId, APIHelper.createMessage(conversationId, body, session != null ? session.getProf... |
python | def get_similar(self, results=15, start=0, buckets=None, limit=False, cache=True, max_familiarity=None, min_familiarity=None, \
max_hotttnesss=None, min_hotttnesss=None, min_results=None, reverse=False, artist_start_year_before=None, \
artist_start_year_after=None,artist_end_year... |
java | public synchronized void putSIMessageHandles(SIMessageHandle[] siMsgHandles)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "putSIMessageHandles", siMsgHandles);
putInt(siMsgHandles.length);
for (int handleIndex = 0; handleIndex < siMsgHandles.length; ++handleI... |
python | def status(config):
"""time series lastest record time by account."""
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
... |
java | public boolean getFeature(String name) {
// feature name cannot be null
if (name == null)
{
throw new NullPointerException(
XSLMessages.createMessage(
XSLTErrorResources.ER_GET_FEATURE_NULL_NAME, null));
}
// Try first with identity comparison, which
/... |
java | @Override
public synchronized Transaction getContract() {
checkState(multisigContract != null);
if (stateMachine.getState() == State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER) {
stateMachine.transition(State.READY);
}
return multisigContract;
} |
python | def create_assignment( # pylint: disable=too-many-arguments
self,
name,
short_name,
weight,
max_points,
due_date_str,
gradebook_id='',
**kwargs
):
"""Create a new assignment.
Create a new assignment. By... |
java | void compareTypes(Schema oldSchema,
Schema newSchema,
List<Message> messages,
String name) {
oldSchema = stripOptionalTypeUnion(oldSchema);
newSchema = stripOptionalTypeUnion(... |
python | def recv_message(self, debug=False):
"""
Reading socket and receiving message from server. Check the CRC32.
"""
if debug:
packet = self.sock.recv(1024) # reads how many bytes to read
hexdump(packet)
packet_length_data = self.sock.recv(4) # reads how man... |
python | def sourcekey(self, **kwargs):
""" Return a key that specifies the name and version of a source or component
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
try:
return NameFactory.sourcekey_format.f... |
java | public static int generationFromRevID(String revID) {
if (revID == null) return 0;
int generation = 0;
int dashPos = revID.indexOf('-');
if (dashPos > 0) {
generation = Integer.parseInt(revID.substring(0, dashPos));
}
return generation;
} |
python | def t_ID(self, t):
r'~?[a-zA-Z_][a-zA-Z0-9_]*'
if t.value[0] == '~':
t.type = 'TYVAR'
t.value = t.value[1:]
elif t.value in self.reserved_words:
t.type = self.reserved_words[t.value]
else:
t.type = 'ID'
return t |
python | def _read_para_esp_transform(self, code, cbit, clen, *, desc, length, version):
"""Read HIP ESP_TRANSFORM parameter.
Structure of HIP ESP_TRANSFORM parameter [RFC 7402]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2... |
python | def knn_impute_reference(
X,
missing_mask,
k,
verbose=False,
print_interval=100):
"""
Reference implementation of kNN imputation logic.
"""
n_rows, n_cols = X.shape
X_result, D, effective_infinity = \
knn_initialize(X, missing_mask, verbose=verbose)
... |
python | def get_episode_title(episode: Episode) -> int:
"""Get the episode title.
Japanese title is prioritized.
"""
for title in episode.titles:
if title.lang == 'ja':
return title.title
else:
return episode.titles[0].title |
java | public static Collection<Comparable<?>> getDatabaseShardingValues(final String logicTable) {
return null == HINT_MANAGER_HOLDER.get() ? Collections.<Comparable<?>>emptyList() : HINT_MANAGER_HOLDER.get().databaseShardingValues.get(logicTable);
} |
python | def _getActorLimits(self):
""" Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)],
one tuple per parameter, giving min and max for that parameter.
"""
actorLimits = []
for _ in range(self.env.numOffbids):
for _ in self.env.generators:
... |
java | public static String createTableFromShp( ASpatialDb db, File shapeFile, String newTableName, boolean avoidSpatialIndex )
throws Exception {
FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
SimpleFeatureSource featureSource = store.getFeatureSource();
SimpleFeatureTy... |
java | protected DialectFactory createDialectFactory() {
DialectFactoryImpl factory = new DialectFactoryImpl();
factory.injectServices(new ServiceRegistryImplementor() {
@Override
public <R extends Service> R getService(Class<R> serviceRole) {
if (serviceRole == Dialect... |
java | public PrivateKey getPrivateKey(String alias, String password) {
Key key = getKey(alias, password);
if (key instanceof PrivateKey) {
return (PrivateKey) key;
} else {
throw new IllegalStateException(format("Key with alias '%s' was not a private key, but was: %s",
... |
java | public void renderV8Style(StringBuilder sb) {
sb.append(" at ");
if ((functionName == null) || "anonymous".equals(functionName) || "undefined"
.equals(functionName)) {
// Anonymous functions in V8 don't have names in the stack trace
appendV8Location(sb);
... |
java | private void transformStartElement(Node node, Hashtable properties) {
// check hat kind of node we have
String nodeName = node.getNodeName();
// the <HTML> and <BODY> node must be skipped
if (nodeName.equals(NODE_HTML) || nodeName.equals(NODE_BODY)) {
// the <TITLE> node mu... |
java | public ArrayList<OvhAvailableMigrationOffer> serviceName_migration_offers_GET(String serviceName) throws IOException {
String qPath = "/overTheBox/{serviceName}/migration/offers";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t5);
} |
python | def one_of(self, items):
"""
Check if the value is contained in a list or generator.
>>> Query().f1.one_of(['value 1', 'value 2'])
:param items: The list of items to check with
"""
return self._generate_test(
lambda value: value in items,
('one_o... |
java | public static <T extends Collection<String>> T readUtf8Lines(String path, T collection) throws IORuntimeException {
return readLines(path, CharsetUtil.CHARSET_UTF_8, collection);
} |
java | public static String toHexString(byte in[]) {
if(in == null || in.length <= 0) {
return null;
}
int i = 0;
byte ch = 0x00;
String pseudo[] = {
"0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", "A", "B",
"C", "D", "E", "F"
};
StringBuffer out = new StringBuffer(in.length * 2);
while(... |
java | @Override
public WSJobExecution getJobExecution(long executionId) throws NoSuchJobExecutionException, JobSecurityException {
return persistenceManagerService.getJobExecution(authorizedExecutionRead(executionId));
} |
python | def create_node(self, network, participant):
"""Make a new node for participants."""
return self.models.RogersAgent(network=network, participant=participant) |
python | def ScheduleSystemCronJobs(names=None):
"""Schedules all system cron jobs."""
errors = []
disabled_classes = config.CONFIG["Cron.disabled_cron_jobs"]
for name in disabled_classes:
try:
cls = registry.SystemCronJobRegistry.CronJobClassByName(name)
except ValueError:
errors.append("Cron job n... |
java | private String getActivityInstanceId(PvmExecutionImpl targetScope) {
if (targetScope.isConcurrent()) {
return targetScope.getActivityInstanceId();
} else {
ActivityImpl targetActivity = targetScope.getActivity();
if ((targetActivity != null && targetActivity.getActivities().isEmpty())) {
... |
python | def formfield(self, **kwargs):
"""
Apply the widget class defined by the
``RICHTEXT_WIDGET_CLASS`` setting.
"""
default = kwargs.get("widget", None) or AdminTextareaWidget
if default is AdminTextareaWidget:
from yacms.conf import settings
richtext_... |
python | def all(guideids=None, filter=None, order=None):
'''
Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
... |
python | def stop_stack(self, stack):
"""停止服务组
停止服务组中所有运行状态的服务。
Args:
- stack: 服务所属的服务组名称
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回空dict{},失败返回{"error": "<errMsg string>"}
- ResponseInfo 请求的Response信息
... |
java | public static <E> List<Class<? extends E>>
filterSkipped(InvocationContext context, List<Class<? extends E>> components) {
Method request = context.getRequest();
if(!request.isAnnotationPresent(Skip.class)) {
return components;
}
List<Class<?>> skippedComponents = Arrays.asList(request.getAnn... |
java | public CloudTaskListSubtasksResult listSubtasks(String jobId, String taskId, TaskListSubtasksOptions taskListSubtasksOptions) {
return listSubtasksWithServiceResponseAsync(jobId, taskId, taskListSubtasksOptions).toBlocking().single().body();
} |
java | public void createTask(String jobId, TaskAddParameter taskToAdd, Iterable<BatchClientBehavior> additionalBehaviors)
throws BatchErrorException, IOException {
TaskAddOptions options = new TaskAddOptions();
BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors... |
python | def send_message(self,message):
""" Send awamp message to the server. We don't wait
for a response here. Just fire out a message
"""
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
message = message.as_str()
logger.... |
python | def _sidConversion(cls, val, **kwargs):
'''
converts a list of pysid objects to string representations
'''
if isinstance(val, six.string_types):
val = val.split(',')
usernames = []
for _sid in val:
try:
userSid = win32security.Looku... |
java | public static int search(double[] doubleArray, double value) {
int start = 0;
int end = doubleArray.length - 1;
int middle = 0;
while(start <= end) {
middle = (start + end) >> 1;
if(value == doubleArray[middle]) {
return middle;
... |
python | def HasWarnings(self):
"""Determines if a store contains extraction warnings.
Returns:
bool: True if the store contains extraction warnings.
"""
# To support older storage versions, check for the now deprecated
# extraction errors.
has_errors = self._HasAttributeContainers(
self._... |
python | def build(
documentPath,
outputUFOFormatVersion=3,
roundGeometry=True,
verbose=True, # not supported
logPath=None, # not supported
progressFunc=None, # not supported
processRules=True,
logger=None,
useVarlib=False,
... |
python | def build(self, builder):
"""Build XML by appending to builder"""
params = dict(OID=self.oid, Name=self.name)
if self.field_number is not None:
params["FieldNumber"] = str(self.field_number)
builder.start("mdsol:LabelDef", params)
for translation in self.translatio... |
java | public OperationStatusResponseInner beginStart(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
return beginStartWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).toBlocking().single().body();
} |
python | async def build_hardware_controller(
cls, config: robot_configs.robot_config = None,
port: str = None,
loop: asyncio.AbstractEventLoop = None,
force: bool = False) -> 'API':
""" Build a hardware controller that will actually talk to hardware.
This method ... |
python | def array_controllers(self):
"""This property gets the list of instances for array controllers
This property gets the list of instances for array controllers
:returns: a list of instances of array controllers.
"""
return array_controller.HPEArrayControllerCollection(
... |
java | protected Collection<X509CertSelector> getSignerSelectors() {
X509CertSelector digSigSelector = new X509CertSelector();
digSigSelector.setBasicConstraints(-2);
digSigSelector.setKeyUsage(new boolean[] { true });
X509CertSelector caSelector = new X509CertSelector();
caSelector.setBasicConstraints(0);
retur... |
python | def get_ca_bundle(opts=None):
'''
Return the location of the ca bundle file. See the following article:
http://tinyurl.com/k7rx42a
'''
if hasattr(get_ca_bundle, '__return_value__'):
return get_ca_bundle.__return_value__
if opts is None:
opts = {}
opts_bundle = opts.get... |
java | @Override
public Feed getCollection(final AtomRequest areq) throws AtomException {
LOG.debug("getCollection");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
final FileBasedCollec... |
python | def cursesMain(_scr, sheetlist):
'Populate VisiData object with sheets from a given list.'
colors.setup()
for vs in sheetlist:
vd().push(vs) # first push does a reload
status('Ctrl+H opens help')
return vd().run(_scr) |
python | def benchmark_file(
filename, compiler, include_dirs, (progress_from, progress_to),
iter_count, extra_flags = ''):
"""Benchmark one file"""
time_sum = 0
mem_sum = 0
for nth_run in xrange(0, iter_count):
(time_spent, mem_used) = benchmark_command(
'{0} -std=c++11 {1} -... |
java | static SimpleConfigOrigin readOrigin(DataInput in, SimpleConfigOrigin baseOrigin)
throws IOException {
Map<SerializedField, Object> m = new EnumMap<SerializedField, Object>(SerializedField.class);
while (true) {
Object v = null;
SerializedField field = readCode(in);
... |
python | def enhanced_vd_factory(sys_ident, vol_ident, set_size, seqnum,
log_block_size, vol_set_ident, pub_ident_str,
preparer_ident_str, app_ident_str, copyright_file,
abstract_file, bibli_file, vol_expire_date, app_use,
xa):
#... |
java | protected void sendWardenEmailToUser(NotificationContext context, SubSystem subSystem) {
EntityManager em = emf.get();
PrincipalUser user = getWardenUser(context.getAlert().getName());
SuspensionRecord record = SuspensionRecord.findByUserAndSubsystem(em, user, subSystem);
Set<String> to ... |
java | public void write(Object[] record) throws IOException, DbaseFileException {
if (record.length != header.getNumFields()) {
throw new DbaseFileException("Wrong number of fields "
+ record.length + " expected " + header.getNumFields());
}
buffer.position(0);
// put the 'not-deleted' marker
buffer.put(... |
java | protected String computeContextPath(
final IExpressionContext context, final String base, final Map<String, Object> parameters) {
if (!(context instanceof IWebContext)) {
throw new TemplateProcessingException(
"Link base \"" + base + "\" cannot be context relative (/... |
python | def _delColumn(cat, col):
"""
This function deletes a metadata column of the acatalog.
:cat: a catalog object
:col: a column id as string
:returns: a boolean as True if the element has been removed and
False otherwise
"""
# First check if the metadata column already exists
if col... |
java | public static final Integer parseInteger(String value)
{
return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));
} |
python | def mirror_sources(self, sourcedir, targetdir=None, recursive=True,
excludes=[]):
"""
Mirroring compilable sources filepaths to their targets.
Args:
sourcedir (str): Directory path to scan.
Keyword Arguments:
absolute (bool): Returned path... |
python | def url(self) -> str:
"""
Returns the URL that will open this project results file in the browser
:return:
"""
return 'file://{path}?id={id}'.format(
path=os.path.join(self.results_path, 'project.html'),
id=self.uuid
) |
java | public static <T extends ImageGray<T>>T average(Planar<T> input , T output ) {
Class type = input.getBandType();
if( type == GrayU8.class ) {
return (T)ConvertImage.average((Planar<GrayU8>)input,(GrayU8)output);
} else if( type == GrayS8.class ) {
return (T)ConvertImage.average((Planar<GrayS8>)input,(GrayS8... |
java | static void fixColumns(List<ParsedColInfo> src, Map<Integer, Pair<String, Integer>> m) {
// change to display column index-keyed map
src.forEach(ci -> {
if (m.containsKey(ci.m_index)) {
Pair<String, Integer> viewInfo = m.get(ci.m_index);
ci.updateColName(viewInfo.getFi... |
python | def _reraise_with_traceback(f):
"""
Call the function normally. But if the function raises an error, attach the str(traceback)
into the function.traceback attribute, then reraise the error.
Args:
f: The function to run.
Returns: A function that wraps f, attaching the traceback if an error o... |
java | @Override
public void activate(final Mp instance, final Object key) throws DempsyException {
try {
instance.activate(key);
} catch(final RuntimeException rte) {
throw new DempsyException(rte, true);
}
} |
java | @XmlElementDecl(namespace = PROV_NS, name = "value")
public JAXBElement<Value> createValue(Value value) {
return new JAXBElement<Value>(_Value_QNAME, Value.class, null, value);
} |
java | protected Content getFramesetJavaScript() {
HtmlTree script = new HtmlTree(HtmlTag.SCRIPT);
script.addAttr(HtmlAttr.TYPE, "text/javascript");
String scriptCode = DocletConstants.NL +
" tmpTargetPage = \"\" + window.location.search;" + DocletConstants.NL +
" ... |
java | public long gridDistance(int x, int y, int z, int w) {
return Math.abs(x - x()) + Math.abs(y - y()) + Math.abs(z - z()) + Math.abs(w - w());
} |
python | def commuting_sets_trivial(pauli_sum):
"""
Group a pauli term into commuting sets using trivial check
:param pauli_sum: PauliSum term
:return: list of lists containing individual Pauli Terms
"""
if not isinstance(pauli_sum, (PauliTerm, PauliSum)):
raise TypeError("This method can only g... |
python | def msg2long_form(msg, processor, **config):
""" Return a 'long form' text representation of a message.
For most message, this will just default to the terse subtitle, but for
some messages a long paragraph-structured block of text may be returned.
"""
result = processor.long_form(msg, **config)
... |
python | def resize_image(self, path, im):
"""
Generate assets from the given image and path in case you've already
called Image.open
"""
# Get the original filename
_, filename = os.path.split(path)
# Generate the new filename
filename = self.get_safe_filename(fi... |
java | private MappeableContainer convertToLazyBitmapIfNeeded() {
// when nbrruns exceed MappeableArrayContainer.DEFAULT_MAX_SIZE, then we know it should be
// stored as a bitmap, always
if (this.nbrruns > MappeableArrayContainer.DEFAULT_MAX_SIZE) {
MappeableBitmapContainer answer = new MappeableBitmapContai... |
java | public Deferred<Object> deleteUidAsync(final String type, final String name) {
final UniqueIdType uid_type = UniqueId.stringToUniqueIdType(type);
switch (uid_type) {
case METRIC:
return metrics.deleteAsync(name);
case TAGK:
return tag_names.deleteAsync(name);
case TAGV:
return tag_... |
java | public FastTrackTable getTable(FastTrackTableType type)
{
FastTrackTable result = m_tables.get(type);
if (result == null)
{
result = EMPTY_TABLE;
}
return result;
} |
python | def create_index_list(self, table_name, attr_names):
"""
:param str table_name: Table name that exists attribute.
:param list attr_names:
List of attribute names to create indices.
Ignore attributes that are not existing in the table.
.. seealso:: :py:meth:`.crea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.