language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static String getMapperSql(SqlSession session, String fullMapperMethodName, Object... args) {
if (args == null || args.length == 0) {
return getNamespaceSql(session, fullMapperMethodName, null);
}
String methodName = fullMapperMethodName.substring(fullMapperMethodName.lastInde... |
python | def activate_clauses(self, beg):
"""
This method is used for activating the clauses that belong
to optimization levels up to the newly computed level. It
also reactivates previously deactivated clauses (see
:func:`process_sels` and :func:`process_sums` for
... |
java | @Override
public void info(final MessageItem messageItem) {
getLogger().log(messageItem.getMarker(), FQCN, LocationAwareLogger.INFO_INT, messageItem.getText(), null, null);
} |
python | def ordi(item, inset):
"""
The function returns the ordinal position of any given item in an
integer set. If the item does not appear in the set, the function
returns -1.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ordi_c.html
:param item: An item to locate within a set.
:type... |
python | def mcus():
"""MCU list."""
ls = []
for h in hwpack_names():
for b in board_names(h):
ls += [mcu(b, h)]
ls = sorted(list(set(ls)))
return ls |
java | @AuthType
int getType() {
switch (strategy) {
case "auth0":
return AuthType.DATABASE;
case "sms":
case "email":
return AuthType.PASSWORDLESS;
case "ad":
case "adfs":
case "auth0-adldap":
case ... |
java | public static UnsafeHeapBuffer wrap(byte[] bytes) {
return new UnsafeHeapBuffer(UnsafeHeapBytes.wrap(bytes), 0, bytes.length, bytes.length);
} |
java | SymbolTable[] getImportedTables()
{
int count = myImports.length - 1; // we don't include system symtab
SymbolTable[] imports = new SymbolTable[count];
if (count > 0)
{
// defensive copy
System.arraycopy(myImports, 1, imports, 0, count);
}
retu... |
java | public Task<AppLink> getAppLinkFromUrlInBackground(final Uri uri) {
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
Task<Map<Uri, AppLink>> resolveTask = getAppLinkFromUrlsInBackground(uris);
return resolveTask.onSuccess(new Continuation<Map<Uri, AppLink>, AppLink>() {
... |
python | def setup_hds(self):
""" setup modflow head save file observations for given kper (zero-based
stress period index) and k (zero-based layer index) pairs using the
kperk argument.
Note
----
this can setup a shit-ton of observations
this is useful for dataw... |
java | private static int branch(int srcOfs, int destIdx, Output context) {
return context.getCode().findOfs(destIdx) - srcOfs;
} |
python | def matrix_multiplication(self, matrix):
"""Multiply :py:obj:`self` with the given matrix and return result matrix.
param Matrix matrix: The matrix, which should be multiplied.
:return: Returns a new Matrix with the result of the multiplication
:rtype: Matrix
:note: Mak... |
java | public org.tensorflow.framework.SaveSliceInfoDef getSaveSliceInfoDef() {
return saveSliceInfoDef_ == null ? org.tensorflow.framework.SaveSliceInfoDef.getDefaultInstance() : saveSliceInfoDef_;
} |
python | def read_settings(self):
"""
Read the "dsbfile" file
Populates `self.settings`
"""
logger.debug('Reading settings from: %s', self.settings_path)
self.settings = Settings.from_dsbfile(self.settings_path) |
java | public static <T extends java.util.Date> T setMonths(final T date, final int amount) {
return set(date, Calendar.MONTH, amount);
} |
java | public static AliasOperationTransformer replaceLastElement(final PathElement element) {
return create(new AddressTransformer() {
@Override
public PathAddress transformAddress(final PathAddress original) {
final PathAddress address = original.subAddress(0, original.size() ... |
java | @SuppressWarnings("unchecked")
private static Collection<LogEntryValue>[][] calculateRequiredLogEntryValues(final Collection<Writer>[][] writers) {
Collection<LogEntryValue>[][] logEntryValues = new Collection[writers.length][Level.values().length - 1];
for (int tagIndex = 0; tagIndex < writers.length; ++tagIndex... |
python | def _construct_context_for_args(args):
"""Construct a new Context for the parsed arguments.
Args:
args: the dictionary of magic arguments.
Returns:
A new Context based on the current default context, but with any explicitly
specified arguments overriding the default's config.
"""
global_default... |
python | async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.temp... |
java | public ExpressRouteCircuitInner beginCreateOrUpdate(String resourceGroupName, String circuitName, ExpressRouteCircuitInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, circuitName, parameters).toBlocking().single().body();
} |
java | protected static String formatCommandLineOption(String name, String value) {
final StringBuilder str = new StringBuilder();
str.append("--"); //$NON-NLS-1$
if (!Strings.isNullOrEmpty(name)) {
str.append(name);
if (!Strings.isNullOrEmpty(value)) {
str.append("="); //$NON-NLS-1$
str.append(value);
... |
python | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
python | def lock_account(self, identifier):
"""
:type account: Account
"""
locked_time = int(time.time() * 1000) # milliseconds
self.account_store.lock_account(identifier, locked_time) |
python | def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_... |
python | def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to ch... |
java | public static MethodDesc forArguments(TypeDesc ret, TypeDesc[] params, String[] paramNames) {
if (ret == null) {
ret = TypeDesc.VOID;
}
if (params == null || params.length == 0) {
params = EMPTY_PARAMS;
}
if (paramNames == null || paramNames.length == 0) {... |
python | def tree_node_to_xml(self, parent, item):
"""Converts a treeview item and children to xml nodes"""
tree = self.treeview
data = self.treedata[item]
node = data.to_xml_node()
children = tree.get_children(item)
for child in children:
cnode = ET.Element('child')... |
python | def read_skel(self, fid):
"""Loads an acclaim skeleton format from a file stream."""
lin = self.read_line(fid)
while lin:
if lin[0]==':':
if lin[1:]== 'name':
lin = self.read_line(fid)
self.name = lin
elif lin[1:... |
python | def query(cls, owner=None, name=None, offset=None, limit=None, api=None):
"""
Query (List) projects
:param owner: Owner username.
:param name: Project name
:param offset: Pagination offset.
:param limit: Pagination limit.
:param api: Api instance.
:return:... |
python | def parse_torrent_link(table_data):
"""
Static method that parses list of table data, finds all anchor elements
and gets the torrent url. However the torrent url is usually hidden behind a fake spam ad url,
this is handled.
:param list lxml.HtmlElement table_data: table_data tag... |
python | def migrate(config):
"""Perform a migration according to config.
:param config: The configuration to be applied
:type config: Config
"""
webapp = WebApp(config.web_host, config.web_port,
custom_maintenance_file=config.web_custom_html)
webserver = WebServer(webapp)
webse... |
python | def copy_everything_except_instructions(self):
"""
Copy all the members that live on a Program object.
:return: a new Program
"""
new_prog = Program()
new_prog._defined_gates = self._defined_gates.copy()
if self.native_quil_metadata is not None:
new_p... |
python | async def update_firmware(
self,
firmware_file: str,
loop: asyncio.AbstractEventLoop = None,
explicit_modeset: bool = True) -> str:
""" Update the firmware on the Smoothie board.
:param firmware_file: The path to the firmware file.
:param explicit... |
python | def sanitize_host(host):
'''
Sanitize host string.
https://tools.ietf.org/html/rfc1123#section-2.1
'''
RFC952_characters = ascii_letters + digits + ".-"
return "".join([c for c in host[0:255] if c in RFC952_characters]) |
python | def render(self, xml, context, raise_on_errors=True):
"""Render xml string and apply XSLT transfomation with context"""
if xml:
self.xml = xml
# render XSL
self.render_xsl(self.root, context)
# create root XSL sheet
xsl_ns = self.namespaces[... |
python | def _get_servers_deque(servers, database):
""" Returns deque of servers for given tuple of servers and
database name.
This deque have active server at the begining, if first server
is not accessible at the moment the deque will be rotated,
second server will be moved to the first position, thirt to ... |
python | def find_class(self):
"""Return a class related with this type."""
classes = {1: InstructionGotoTable, 2: InstructionWriteMetadata,
3: InstructionWriteAction, 4: InstructionApplyAction,
5: InstructionClearAction, 6: InstructionMeter}
return classes.get(self.... |
java | public void setAvailability(Parameter newAvailability) {
if (newAvailability != availability) {
NotificationChain msgs = null;
if (availability != null)
msgs = ((InternalEObject)availability).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.RESOURCE_PARAMETERS__AVAILABILITY, null, msgs);
if (ne... |
python | def roman_to_int(roman):
"""
https://gist.github.com/kristopherjohnson/f4eca9018c5085fc736b2f29a202b8f8
"""
vals = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
total = 0
lastValue = sys.maxsize
for char in li... |
java | public <T extends Memory> T getNodeMemory(MemoryFactory<T> node) {
return nodeMemories.getNodeMemory( node, this );
} |
java | public static List<Entry> sortHashTable(final Hashtable<?, ?> hash, final boolean asc) {
// Put keys and values in to an arraylist using entryset
final ArrayList<Entry> myArrayList = new ArrayList(hash.entrySet());
// Sort the values based on values first and then keys.
Collections.sort(myArrayList, new Has... |
java | protected Button createCheckButton(Composite parent, String text)
{
return SWTFactory.createCheckButton(parent, text, null, false, 1);
} |
python | def iterdata(self, start, end=None, forward=True, condition=None):
"""
Perform a depth-first walk of the graph (as ``iterdfs``)
and yield the item data of every node where condition matches. The
condition callback is only called when node_data is not None.
"""
visited, ... |
java | public ServerBuilder annotatedService(String pathPrefix, Object service,
Function<Service<HttpRequest, HttpResponse>,
? extends Service<HttpRequest, HttpResponse>> decorator,
Iterable<?>... |
python | def get_angles(self) -> Tuple[List[float], List[float]]:
"""
Finds optimal angles with the quantum variational eigensolver method.
Stored VQE result
:returns: A tuple of the beta angles and the gamma angles for the optimal solution.
"""
stacked_params = np.hstack((self.... |
java | private static void printUsage() {
System.err.println(
"Usage: java AvatarNode [" +
StartupOption.STANDBY.getName() + "] | [" +
StartupOption.NODEZERO.getName() + "] | [" +
StartupOption.NODEONE.getName() + "] | [" +
StartupOption.FORMAT.getName() + "] | [" +
StartupOption.UPGRAD... |
java | @Nullable
public CSSMediaRule getMediaRuleAtIndex (@Nonnegative final int nIndex)
{
return m_aRules.getAtIndexMapped (r -> r instanceof CSSMediaRule, nIndex, r -> (CSSMediaRule) r);
} |
python | def batchsd(trace, batches=5):
"""
Calculates the simulation standard error, accounting for non-independent
samples. The trace is divided into batches, and the standard deviation of
the batch means is calculated.
"""
if len(np.shape(trace)) > 1:
dims = np.shape(trace)
# ttrace ... |
python | def print_table(lines, separate_head=True):
"""Prints a formatted table given a 2 dimensional array"""
#Count the column width
widths = []
for line in lines:
for i,size in enumerate([len(x) for x in line]):
while i >= len(widths):
widths.append(0)
if size > widths[i]:
widths[i] = size
... |
java | public final EObject ruleCrossReference() throws RecognitionException {
EObject current = null;
Token otherlv_0=null;
Token otherlv_2=null;
Token otherlv_4=null;
EObject lv_type_1_0 = null;
EObject lv_terminal_3_0 = null;
enterRule();
try {
... |
python | def adjoint(self):
"""Adjoint of this operator."""
if not self.is_linear:
raise NotImplementedError('this operator is not linear and '
'thus has no adjoint')
forward_op = self
class ResizingOperatorAdjoint(ResizingOperatorBase):
... |
python | def external_answer(self, *sequences):
"""Try to get answer from known external libraries.
"""
# if this feature disabled
if not getattr(self, 'external', False):
return
# all external libs doesn't support test_func
if hasattr(self, 'test_func') and self.test_... |
python | def get(self, objectType, *args, **coolArgs) :
"""Raba Magic inside. This is th function that you use for
querying pyGeno's DB.
Usage examples:
* myGenome.get("Gene", name = 'TPST2')
* myGene.get(Protein, id = 'ENSID...')
* myGenome.get(Transcript, {'start >' : x, 'end <' : y})"""
ret =... |
python | def get_hook_model():
"""
Returns the Custom Hook model if defined in settings,
otherwise the default Hook model.
"""
from rest_hooks.models import Hook
HookModel = Hook
if getattr(settings, 'HOOK_CUSTOM_MODEL', None):
HookModel = get_module(settings.HOOK_CUSTOM_MODEL)
return Hoo... |
java | @DefinedBy(Api.LANGUAGE_MODEL)
public boolean contentEquals(CharSequence cs) {
return toString().equals(cs.toString());
} |
java | @RuleSetup(RequirementLevel.OPTIONAL)
public void setLookupName(final String lookupName) {
assertStateBefore(State.CREATED);
this.lookupName = lookupName;
} |
python | def _modify_relationship(relationship, unlink=False, is_sub=False):
"""Return a function for relationship modification.
Used to support friending (user-to-user), as well as moderating,
contributor creating, and banning (user-to-subreddit).
"""
# The API uses friend and unfriend to manage all of th... |
python | def image_meta_delete(image_id=None, # pylint: disable=C0103
name=None,
keys=None,
profile=None, **kwargs):
'''
Delete a key=value pair from the metadata for an image
(nova image-meta set)
CLI Examples:
.. code-block:: bash
... |
java | private LiftingStepResults convertIntoLiftingStepResults(
ImmutableList<IQTree> liftedChildren, IQTree selectedGrandChild, int selectedChildPosition,
Optional<ImmutableExpression> newCondition, ImmutableSubstitution<ImmutableTerm> ascendingSubstitution,
ImmutableSubstitution<? extend... |
java | public Observable<ServiceResponse<Page<LongTermRetentionBackupInner>>> listByServerWithServiceResponseAsync(final String locationName, final String longTermRetentionServerName, final Boolean onlyLatestPerDatabase, final LongTermRetentionDatabaseState databaseState) {
return listByServerSinglePageAsync(locationN... |
python | def extract_tree_without(self, labels, suppress_unifurcations=True):
'''Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels``
Args:
``labels`` (``set``): Set of leaf labels to exclude
``suppress_unifurcations`` (``bool``): ``True`` to suppress ... |
python | def list_(return_yaml=True,
include_pillar=True,
include_opts=True,
**kwargs):
'''
List the beacons currently configured on the minion.
Args:
return_yaml (bool):
Whether to return YAML formatted output, default ``True``.
include_pillar (bool):
... |
java | public void addMailHost(
String hostname,
String port,
String order,
String protocol,
String security,
String username,
String password) {
Integer thePort;
try {
thePort = Integer.valueOf(port);
} catch (Throwable t) {
... |
java | public ArrayList<String> cdn_webstorage_serviceName_storage_GET(String serviceName, OvhOrderStorageEnum storage) throws IOException {
String qPath = "/order/cdn/webstorage/{serviceName}/storage";
StringBuilder sb = path(qPath, serviceName);
query(sb, "storage", storage);
String resp = exec(qPath, "GET", sb.toSt... |
java | public void addSelectionChangedListener(ISelectionChangedListener listener)
{
if (fOutlineViewer != null)
{
fOutlineViewer.addSelectionChangedListener(listener);
} else
{
fSelectionChangedListeners.add(listener);
}
} |
java | private void generateUUIDs(CmsSetupDb dbCon) throws SQLException {
System.out.println(new Exception().getStackTrace()[0].toString());
String query = readQuery(QUERY_GET_PROJECT_IDS);
CmsSetupDBWrapper db = null;
try {
db = dbCon.executeSqlStatement(query, null);
... |
java | public java.util.List<VirtualGateway> getVirtualGateways() {
if (virtualGateways == null) {
virtualGateways = new com.amazonaws.internal.SdkInternalList<VirtualGateway>();
}
return virtualGateways;
} |
java | @Override
public boolean setException(Throwable throwable) {
clientLogger.logServerError(clientMethod.serviceName(), clientMethod.name(), throwable);
return super.setException(throwable);
} |
java | public static void checkPositive(int number, String message, Object... args) {
if (number < 0) {
throw new IllegalArgumentException(String.format(message, args));
}
} |
python | def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
"""
path = tuple(path.split('.')) if isinstance(path , str) else tuple(path)
disallowed = [p for p in path if not type(self)._... |
java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_ftw_responses result = (xen_health_ftw_responses) service.get_payload_formatter().string_to_resource(xen_health_ftw_responses.class, response);
if(result.errorcode != 0)
{
if (result.er... |
python | def p_simple_list1(p):
'''simple_list1 : simple_list1 AND_AND newline_list simple_list1
| simple_list1 OR_OR newline_list simple_list1
| simple_list1 AMPERSAND simple_list1
| simple_list1 SEMICOLON simple_list1
| pipeline_command'''
... |
python | def _filter_child_model_fields(cls, fields):
""" Keep only related model fields.
Example: Inherited models: A -> B -> C
B has one-to-many relationship to BMany.
after inspection BMany would have links to B and C. Keep only B. Parent
model A could not be used (It would not be in ... |
python | def post_bug(self, bug):
'''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#create-bug'''
assert type(bug) is DotDict
assert 'product' in bug
assert 'component' in bug
assert 'summary' in bug
if (not 'version' in bug): bug.version = 'other'
if (not ... |
java | public KafkaMessage consumeMessage(String consumerGroupId, String topic, long waitTime,
TimeUnit waitTimeUnit) {
return consumeMessage(consumerGroupId, true, topic, waitTime, waitTimeUnit);
} |
python | def get_deepest_subsumer(self,list_terms):
'''
Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided
'''
#To store with how many terms every nonterminal appears
count_per_no_terminal = defaultdict(int)
#To ... |
java | public Optional<I> findIntersection(ChronoInterval<T> other) {
if (this.isEmpty() || other.isEmpty()) {
return Optional.empty();
}
Boundary<T> s;
Boundary<T> e;
if (this.start.isInfinite()) {
s = other.getStart();
} else if (other.getStart().isI... |
java | protected void validateEmailAddress(final List<Diagnostic> diags) {
if (!isEmpty()) {
String value = getValueAsString();
String errorMessage = getComponentModel().errorMessage;
// Email Pattern
if (!Pattern.matches(
"^(?:\".+\"|[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+)@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)+$",
... |
python | def _append_dataframe(self, df, source_info="", units=None):
"""
Appends a new data group from a Pandas data frame.
"""
units = units or {}
t = df.index
index_name = df.index.name
time_name = index_name or "time"
version = self.version
timestam... |
python | def network_interface_list_effective_network_security_groups(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get all network security groups applied to a specific network interface.
:param name: The name of the network interface to query.
:param resource_group: The resource group ... |
java | public static appflowpolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{
appflowpolicy obj = new appflowpolicy();
options option = new options();
option.set_filter(filter);
appflowpolicy[] response = (appflowpolicy[]) obj.getfiltered(service, option);
return response;
} |
java | public Observable<Page<DataLakeStoreAccountInfoInner>> listDataLakeStoreAccountsAsync(final String resourceGroupName, final String accountName) {
return listDataLakeStoreAccountsWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<DataLakeStoreAccountInfoInner... |
java | public Map < String, String > generate(String cobolSource,
String targetPackageName, final String xsltFileName) {
return generate(new StringReader(cobolSource), targetPackageName,
xsltFileName);
} |
python | def binary_value(self):
"""
Converts this field to binary (assuming it's a binary string)
"""
str_raw_value = str(self.raw_value)
if len(str_raw_value) % 2 == 1:
str_raw_value = '0' + str_raw_value
return binascii.unhexlify(str_raw_value) |
java | public void setInput(long seed, final double[] data) {
// Log.info("Data: " + ArrayUtils.toString(data));
assert(_dinfo != null);
double [] nums = MemoryManager.malloc8d(_dinfo._nums); // a bit wasteful - reallocated each time
int [] cats = MemoryManager.malloc4(_dinfo._cats); // a bit wastefu... |
java | public void marshall(AudioChannelMapping audioChannelMapping, ProtocolMarshaller protocolMarshaller) {
if (audioChannelMapping == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(audioChannelMapping.ge... |
java | @NonNull
public ListenerToken addDocumentReplicationListener(@NonNull DocumentReplicationListener listener) {
if (listener == null) { throw new IllegalArgumentException("listener cannot be null."); }
return addDocumentReplicationListener(null, listener);
} |
java | public void setUnChanged() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setUnChanged");
changed = false;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setUnChanged");
} |
python | def gen_repr(cls, template, *args, **kwargs):
"""Generates a string for :func:`repr`."""
buf = io.StringIO()
buf.write(u'<')
buf.write(cls.__module__.decode() if kwargs.pop('full', False) else u'etc')
buf.write(u'.')
buf.write(cls.__name__.decode())
if not kwargs.pop('dense', False):
... |
python | def stab(nick, rest):
"Stab, shank or shiv some(one|thing)!"
if rest:
stabee = rest
else:
stabee = 'wildly at anything'
if random.random() < 0.9:
karma.Karma.store.change(stabee, -1)
weapon = random.choice(phrases.weapon_opts)
weaponadj = random.choice(phrases.weapon_adjs)
violentact = random.choice(phr... |
java | public int convertToExternal(BaseMessage messageOut, BaseInternalMessageProcessor messageOutProcessor)
{
String strMessageInfoType = MessageInfoTypeModel.REQUEST;
String strMessageProcessType = MessageTypeModel.MESSAGE_OUT;
if (messageOut.getMessageHeader() != null)
{
str... |
python | def load_parameter(input_filename, only_header=False):
"""Load HTK parameter/feature file.
:param input_filename:
:param only_header: only load the metadata
:return: a named tuple representing the HTK parmeter file
"""
with open(input_filename, 'rb') as f:
meta = _parse_parameter_meta(... |
python | def _train_and_eval_single(train, valid, model,
batch_size=32, epochs=300, use_weight=False,
callbacks=[], eval_best=False, add_eval_metrics={}):
"""Fit and evaluate a keras model
eval_best: if True, load the checkpointed model for evaluation
"""
de... |
java | public void reverse() {
// overridden for performance only.
double tmp;
int limit=size/2;
int j=size-1;
double[] theElements = elements;
for (int i=0; i<limit;) { //swap
tmp=theElements[i];
theElements[i++]=theElements[j];
theElements[j--]=tmp;
}
} |
python | def preserve_context(f):
"""
Package up the given function with the current Eliot context, and then
restore context and call given function when the resulting callable is
run. This allows continuing the action context within a different thread.
The result should only be used once, since it relies o... |
python | def get_order(self):
""" Returns the result order by clauses
:rtype: str or None
"""
# first get the filtered attributes in order as they must appear
# in the order_by first
if not self.has_order:
return None
filter_order_clauses = OrderedDict([(filte... |
python | def delete(self, new_parent=None, recursive=False):
"""
Deletes a category. Optionally moves content to new category.
Note: If category is in root, new_parent must be specified.
:param int new_parent: (optional) Category ID of new parent
:param bool recursive: recursively delete... |
java | public static <T> KeyRange<T> lessThanBackward(final T stop) {
return new KeyRange<>(KeyRangeType.BACKWARD_LESS_THAN, null, stop);
} |
java | public void addFieldValue(String fieldName, String value) {
Utils.require(!Utils.isEmpty(fieldName), "fieldName");
if (fieldName.charAt(0) == '_') {
setSystemField(fieldName, value);
} else {
List<String> currValues = m_valueMap.get(fieldName);
... |
java | private void close(Component component) {
if (components.size() > 0) {
if (components.contains(component) == false) {
return;
}
components.remove(component);
depths.remove(component);
getModalPanel().removeAll();
fireCloseActionListener(listeners.get(component));
listeners.remove(component);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.