language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def compare_branches_tags_commits(self, project_id, from_id, to_id):
"""
Compare branches, tags or commits
:param project_id: The ID of a project
:param from_id: the commit sha or branch name
:param to_id: the commit sha or branch name
:return: commit list and diff betwe... |
python | def get_random(self):
"""
Returns a random statement from the database
"""
from random import randint
count = self.count()
if count < 1:
raise self.EmptyDatabaseException()
random_integer = randint(0, count - 1)
statements = self.statements... |
python | def update_quota(self, tenant_id, subnet=None, router=None,
network=None, floatingip=None, port=None,
sec_grp=None, sec_grp_rule=None):
'''
Update a tenant's quota
'''
body = {}
if subnet:
body['subnet'] = subnet
if ro... |
java | protected VelocityContext createAndPopulateContext()
{
VelocityContext context = new VelocityContext();
context.put( "dependencies", getDependenciesText() );
context.put( "arguments", getArgumentsText() );
// Note: properties that contain dots will not be properly parsed by Veloci... |
python | async def close_room(self, room, namespace=None):
"""Close a room.
The only difference with the :func:`socketio.Server.close_room` method
is that when the ``namespace`` argument is not given the namespace
associated with the class is used.
Note: this method is a coroutine.
... |
python | def fixed_gaussian_prior_builder(
getter, name, dtype=None, *args, **kwargs):
"""A pre-canned builder for fixed gaussian prior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a scalar-valued fixed gaussian prior which
will be br... |
python | def signal_handler(signal_name, frame):
"""Quit signal handler."""
sys.stdout.flush()
print("\nSIGINT in frame signal received. Quitting...")
sys.stdout.flush()
sys.exit(0) |
java | public Where<T, ID> ne(String columnName, Object value) throws SQLException {
addClause(new SimpleComparison(columnName, findColumnFieldType(columnName), value,
SimpleComparison.NOT_EQUAL_TO_OPERATION));
return this;
} |
python | def lfc(pressure, temperature, dewpt, parcel_temperature_profile=None, dewpt_start=None):
r"""Calculate the level of free convection (LFC).
This works by finding the first intersection of the ideal parcel path and
the measured parcel temperature.
Parameters
----------
pressure : `pint.Quantity... |
java | public boolean loadClasses() {
Boolean result = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
Policy policy = jaccProviderService.getService().getPolicy();
if (tc.isDebugEnabled())
Tr.... |
java | public static <E> Stream<E> repeat(Stream<E> stream, int repeatingFactor) {
Objects.requireNonNull(stream);
RepeatingSpliterator<E> spliterator = RepeatingSpliterator.of(stream.spliterator(), repeatingFactor);
return StreamSupport.stream(spliterator, stream.isParallel()).onClose(stream::close);... |
java | public void addResult(CmsContentCheckResource testResource) {
List warnings = testResource.getWarnings();
List errors = testResource.getErrors();
// add the warnings if there were any
if ((warnings != null) && (warnings.size() > 0)) {
m_warnings.put(testResource.getResourceN... |
java | public final T parseJson(JCalValue value, ICalDataType dataType, ICalParameters parameters, ParseContext context) {
T property = _parseJson(value, dataType, parameters, context);
property.setParameters(parameters);
return property;
} |
java | protected Content getNavLinkTree() {
Content linkContent = getHyperLink(DocPaths.PACKAGE_TREE,
treeLabel);
Content li = HtmlTree.LI(linkContent);
return li;
} |
python | def subscribe_get(self, nick, article_code):
'''taobao.vas.subscribe.get 订购关系查询
用于ISV根据登录进来的淘宝会员名查询该为该会员开通哪些收费项目,ISV只能查询自己名下的应用及收费项目的订购情况'''
request = TOPRequest('taobao.vas.subscribe.get')
request['nick'] = nick
request['article_code'] = article_code
self.create... |
python | def CheckUserForLabels(username, authorized_labels, token=None):
"""Verify that the username has all the authorized_labels set."""
authorized_labels = set(authorized_labels)
try:
user = aff4.FACTORY.Open(
"aff4:/users/%s" % username, aff4_type=aff4_users.GRRUser, token=token)
# Only return if al... |
python | def validate(self, str_in):
# type: (Text) -> None
""" Validates an entry in the field.
Raises `InvalidEntryError` iff the entry is invalid.
An entry is invalid iff it is not one of the permitted
values.
:param str str_in: String to validate.
... |
python | def write(self, values):
"""
Write values to the targeted documents
Values need to be a dict as : {document_id: value}
"""
# Insert only for docs targeted by the target
filtered = {_id: value for _id, value in values.items() if _id in self._document_ids}
if not f... |
python | def get(self):
"""Get a task from the queue."""
tasks = self._get_avaliable_tasks()
if not tasks:
return None
name, data = tasks[0]
self._client.kv.delete(name)
return data |
java | @SuppressWarnings("WeakerAccess")
public Cluster getCluster(String instanceId, String clusterId) {
return ApiExceptions.callAndTranslateApiException(getClusterAsync(instanceId, clusterId));
} |
java | public JavadocLink javadocMethodLink(String memberName, Type... types) {
return new JavadocLink("%s#%s(%s)",
getQualifiedName(),
memberName,
(Excerpt) code -> {
String separator = "";
for (Type type : types) {
code.add("%s%s", separator, type.getQualifiedName(... |
python | def methylqa_alignment_plot (self):
""" Make the HighCharts HTML to plot the alignment rates """
if len(self.methylqa_coverage_counts) == 0:
return '<div class="alert alert-danger">No histogram data found.</div>'
pconfig = {
'id': 'methylqa_coverage',
'title... |
java | @Override
public ResultSet resultSet() {
try {
return agent().query(context());
} catch (SQLException e) {
throw new UroborosqlSQLException(e);
}
} |
java | private LazyNode pop(){
LazyNode value=stackTop;
stackPointer--;
if(stackPointer>0){
stackTop=stack[stackPointer-1];
}
return value;
} |
java | private ReceiveMessageFuture issueFuture(int size,
QueueBufferCallback<ReceiveMessageRequest, ReceiveMessageResult> callback) {
synchronized (futures) {
ReceiveMessageFuture theFuture = new ReceiveMessageFuture(callback, size);
futures.addLast... |
python | def _get_relationship_cell_val(self, obj, column):
"""
Return the value to insert in a relationship cell
"""
val = ""
key = column['key']
related_key = column.get('related_key', None)
related_obj = getattr(obj, key, None)
if related_obj is None:
... |
python | def _return_result(self, done):
"""Called set the returned future's state that of the future
we yielded, and set the current future for the iterator.
"""
chain_future(done, self._running_future)
self.current_future = done
self.current_index = self._unfinished.pop(done) |
java | public static byte[] parseBinary(InputStream inputStream, final int size) throws IOException {
byte value[] = new byte[size];
int i = value.length;
while (i != 0) {
i -= inputStream.read(value, value.length - i, i);
}
return value;
} |
java | static Method checkTimeMethod(Method timeMethod) throws InvalidBenchmarkException {
checkArgument(isTimeMethod(timeMethod));
Class<?>[] parameterTypes = timeMethod.getParameterTypes();
if (!Arrays.equals(parameterTypes, new Class<?>[] {int.class})
&& !Arrays.equals(parameterTypes, new Class<?>[] {lo... |
python | def kdtree(self):
"""
Return a scipy.spatial.cKDTree of the vertices of the mesh.
Not cached as this lead to observed memory issues and segfaults.
Returns
---------
tree : scipy.spatial.cKDTree
Contains mesh.vertices
"""
from scipy.spatial impo... |
python | def search_mode_provides(self, product, pipeline='default'):
"""Search the mode that provides a given product"""
pipeline = self.pipelines[pipeline]
for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
# extract name from obj
if obj.name() == product... |
python | def attrdump(value: Any, **kwargs) -> Any:
"""
Quick function to do a dump that supports the "attr"
module.
"""
from . import datadumper
from .plugins import attrdump as dumpplugin
dumper = datadumper.Dumper(**kwargs)
dumpplugin.add2dumper(dumper)
return dumper.dump(value) |
java | public OptionalThing<RunnerResult> stopIfNeeds(ReadableJobState jobState, Supplier<String> stateDisp) {
if (jobExecutingDeterminer.test(jobState)) {
final JobConcurrentExec concurrentExec = jobState.getConcurrentExec();
if (concurrentExec.equals(JobConcurrentExec.QUIT)) {
... |
java | public FirewallRuleInner createOrUpdate(String resourceGroupName, String accountName, String firewallRuleName, CreateOrUpdateFirewallRuleParameters parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, firewallRuleName, parameters).toBlocking().single().body();
} |
java | public void process(CAS tcas) {
String text = tcas.getDocumentText();
Document document = new DocumentImpl(text);
cogroo.analyze(document);
for (Sentence sentence : document.getSentences()) {
// create sentence annotations
AnnotationFS sentenceAnn = tcas.createAnnotation(mSentenceType,
sentence.g... |
python | def set_parameters_upstream(self, parameters):
"""Set parameters to all upstream Steps including this Step.
Parameters is dict() where key is Step attribute, and value is new value to set.
"""
assert isinstance(parameters, dict), 'parameters must be dict, got {} instead'.format(type(para... |
python | def find_version(filename):
"""
Search for assignment of __version__ string in given file and
return what it is assigned to.
"""
with open(filename, "r") as filep:
version_file = filep.read()
version_match = re.search(
r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, ... |
python | def GetChangeAddress(self, from_addr=None):
"""
Get the address where change is send to.
Args:
from_address (UInt160): (optional) from address script hash.
Raises:
Exception: if change address could not be found.
Returns:
UInt160: script has... |
python | def metal_complexation(metals, metal_binding_lig, metal_binding_bs):
"""Find all metal complexes between metals and appropriate groups in both protein and ligand, as well as water"""
data = namedtuple('metal_complex', 'metal metal_orig_idx metal_type target target_orig_idx target_type '
... |
python | def count_braces(self):
"""
returns a count of "{{" and "}}" in the template, as (N_left_braces, N_right_braces)
Useful to check after resolve() has run, to infer that template has an error since no {{ or }}
should be present in the template after resolve()
"""
n_left = len(re.findall("{{", self... |
python | def get_flipped_ext(file_id,ccd):
"""Given a list of exposure numbers and CCD, get them from the DB"""
import MOPfits
import os, shutil
filename=MOPfits.adGet(file_id,extno=int(ccd))
if int(ccd)<18:
tfname=filename+"F"
shutil.move(filename, tfname)
os.system("imcopy %s[-*,... |
java | static void handleWriteToChunk(ByteChannel sock, AutoBuffer ab) throws IOException {
String frameKey = ab.getStr();
byte[] expectedTypes = ab.getA1();
if( expectedTypes == null){
throw new RuntimeException("Expected types can't be null.");
}
int[] maxVecSizes = ab.getA4... |
java | public CharTrie product(CharTrie z) {
return reduceSimple(z, (left, right) -> (null == left ? 0 : left) * (null == right ? 0 : right));
} |
java | @GwtIncompatible("incompatible method")
private static Date parseDateWithLeniency(
final String str, final Locale locale, final String[] parsePatterns, final boolean lenient) throws ParseException {
if (str == null || parsePatterns == null) {
throw new IllegalArgumentException("Date ... |
java | public ViaCEPEndereco getEndereco(String cep) throws IOException {
char[] chars = cep.toCharArray();
StringBuilder builder = new StringBuilder();
for (int i = 0; i< chars.length; i++){
if (Character.isDigit(chars[i])){
builder.append(chars[i]);
}
}
cep = builder.toString();
if (cep.length() ... |
python | def _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation."""
if isinstance(value, decimal.Decimal):
value = str(value)
return value |
python | def prepare(self):
'''
Run the preparation sequence required to start a salt proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(ProxyMinion, self).prepare()
if not self.values.proxyid:
self.... |
python | def new_add_public_key_transaction(self, ont_id: str, bytes_operator: bytes, new_pub_key: str or bytes,
b58_payer_address: str, gas_limit: int, gas_price: int,
is_recovery: bool = False):
"""
This interface is used to send a T... |
python | def symlink(target, linkname):
"""
Create a symlink to `target` called `linkname`.
Converts `target` and `linkname` to absolute paths; creates
`dirname(linkname)` if needed.
"""
target = os.path.abspath(target)
linkname = os.path.abspath(linkname)
if not os.path.exists(target):
... |
python | def hpd_threshold(mu_in, post, alpha, tol):
'''
For a PDF post over samples mu_in, find a density
threshold such that the region having higher density
has coverage of at least alpha, and less than alpha
plus a given tolerance.
'''
norm_post = normalize_pdf(mu_in, post)
# initialize bisec... |
python | def get_auth(sock, dname, protocol, host, dno):
"""auth_name, auth_data = get_auth(sock, dname, protocol, host, dno)
Return authentication data for the display on the other side of
SOCK, which was opened with DNAME, HOST and DNO, using PROTOCOL.
Return AUTH_NAME and AUTH_DATA, two strings to be used i... |
java | public void setRemoteProperty(String strProperty, String strValue) throws RemoteException
{
m_tableRemote.setRemoteProperty(strProperty, strValue);
} |
python | def process(data_stream):
"""
Process a diff file stream into a class with objects separated.
Parameters
----------
data_stream : class
A file-like class containing a decompressed diff file data stream.
Returns
-------
data_object : osc_decoder class
A class containing ... |
java | public String toStringList() {
int size = size();
StringBuilder buf = new StringBuilder(20 * size);
buf.append('[');
for (int i = 0; i < size; i++) {
if (i > 0) {
buf.append(',').append(' ');
}
buf.append(iTypes[i].getName());
... |
java | public CellConstraints rc(int row, int col,
Alignment rowAlign, Alignment colAlign) {
return rchw(row, col, 1, 1, rowAlign, colAlign);
} |
python | def gather_positions(tree):
"""Makes a list of positions and position commands from the tree"""
pos = {'data-x': 'r0',
'data-y': 'r0',
'data-z': 'r0',
'data-rotate-x': 'r0',
'data-rotate-y': 'r0',
'data-rotate-z': 'r0',
'data-scale': 'r0',
... |
python | def gen_rst_url_split_opts(opts_str):
"""generate option list for RST docs
Parameters
----------
opts_str : str
a string including all SUEWS related options/variables.
e.g. 'SUEWS_a, SUEWS_b'
Returns
-------
list
a list of parsed RST `:ref:` roles.
e.g. [':... |
python | def to_flake8(self, checker_cls: type) -> Flake8Error:
"""
Args:
checker_cls: Class performing the check to be passed back to
flake8.
"""
return Flake8Error(
line_number=self.line_number,
offset=self.offset,
text=self.text,
... |
java | static public HsqlName getAutoColumnName(int i) {
if (i < autoColumnNames.length) {
return autoColumnNames[i];
}
return new HsqlName(staticManager, makeAutoColumnName("C_", i), 0, false);
} |
java | public Cell<C,T> minSize (float size) {
minWidth = new FixedValue<C, T>(layout.toolkit, size);
minHeight = new FixedValue<C, T>(layout.toolkit, size);
return this;
} |
python | def dict(self, var, cast=dict, default=NOTSET):
"""
:rtype: dict
"""
return self.get_value(var, cast=cast, default=default) |
python | def update_lb_node_condition(self, lb_id, node_id, condition):
"""
Update node condition - specifically to disable/enable
:param string lb_id: Balancer id
:param string node_id: Node id
:param string condition: ENABLED/DISABLED
"""
self._request(
... |
java | public int readInt(int off) {
this.buffer.rewind();
return ((buffer.get(off++) & 0xFF) << 24)
| ((buffer.get(off++) & 0xFF) << 16)
| ((buffer.get(off++) & 0xFF) << 8)
| (buffer.get(off++) & 0xFF);
} |
java | public void downloadS3Object(S3ObjectSummary s3ObjectSummary,
String targetDirectory)
throws IOException {
final AmazonS3 amazonS3 = getS3Client();
final GetObjectRequest getObjectRequest = new GetObjectRequest(
s3ObjectSummary.getBucketName(),
s3ObjectSummary.getKey());
final... |
python | def NotificationsDelete(self, notification_id):
"""
Delete a notification from CommonSense.
@param notification_id (int) - Notification id of the notification to delete.
@return (bool) - Boolean indicating whether NotificationsDelete was succes... |
python | def add_host_to_dvs(host, username, password, vmknic_name, vmnic_name,
dvs_name, target_portgroup_name, uplink_portgroup_name,
protocol=None, port=None, host_names=None):
'''
Adds an ESXi host to a vSphere Distributed Virtual Switch and migrates
the desired adapters t... |
python | def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()):
"""Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable... |
java | public InvoiceData getInvoice(Date date, String pricingAccountAlias) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return getInvoice(calendar, pricingAccountAlias);
} |
java | static Startup defaultStartup(MessageHandler mh) {
if (defaultStartup != null) {
return defaultStartup;
}
try {
String content = readResource(DEFAULT_STARTUP_NAME);
return defaultStartup = new Startup(
new StartupEntry(true, DEFAULT_STARTUP... |
java | private static void printUsageMessage() {
System.err.println("Descrption:");
System.err.println("");
System.err.println("Required arguments:");
System.err.println(" The paths to one or more binary classes, jars, or");
System.err.println(" directories to scan for classes and jar... |
java | private CompletableFuture<Void> flush(Void ignored) {
checkRunning();
long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "flush");
// Flush everything we can flush.
val flushFutures = this.processors.values().stream()
.f... |
java | public static void copyRecursively(final Path source, final Path target, boolean overwrite) throws IOException {
final CopyOption[] options;
if (overwrite) {
options = new CopyOption[]{StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING};
} else {
opti... |
python | def wrap_function(func):
"""
RETURN A THREE-PARAMETER WINDOW FUNCTION TO MATCH
"""
if is_text(func):
return compile_expression(func)
numarg = func.__code__.co_argcount
if numarg == 0:
def temp(row, rownum, rows):
return func()
return temp
elif numarg ==... |
python | def show_and_run(self):
"""Show the main widget in a window and run the gtk loop"""
if not self._ui_ready:
self.prepare_ui()
self.display_widget = Gtk.Window()
self.display_widget.add(self.widget)
self.display_widget.show()
self.display_widget.connect('destroy... |
java | public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession(false);
String action = request.getParameter("Action");
String name = request.getParameter("Name");
... |
python | def _hotellings_fourier(self):
""" hotelling's T2 tests for fourier domain waveforms"""
sigma_2 = self._catalog_object.sigma**2
# compute residual
df = self._df #degrees of freedom
R = self._A - np.dot(self._X, self._Bhat)
R = np.matrix(R)
# residual covariance ma... |
java | public GetSamplingTargetsResult withSamplingTargetDocuments(SamplingTargetDocument... samplingTargetDocuments) {
if (this.samplingTargetDocuments == null) {
setSamplingTargetDocuments(new java.util.ArrayList<SamplingTargetDocument>(samplingTargetDocuments.length));
}
for (SamplingTar... |
python | def getAnalysisKeywords(self):
""" The analysis service keywords found
"""
analyses = []
for rows in self.getRawResults().values():
for row in rows:
analyses = list(set(analyses + row.keys()))
return analyses |
python | def max(self, e, extra_constraints=(), exact=None):
"""
Return the maximum value of expression `e`.
:param e : expression (an AST) to evaluate
:param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve
:param exact : if Fa... |
python | def forward(self, query, context):
"""
Args:
query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of
queries to query the context.
context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data
ove... |
python | def as_unicode(s, encoding='utf-8'):
"""Force conversion of given string to unicode type.
Unicode is ``str`` type for Python 3.x and ``unicode`` for Python 2.x .
If the string is already in unicode, then no conversion is done and the same string is returned.
Parameters
----------
s: str or byt... |
python | def add_automatic_comment(self, ref):
"""Add comment on ref for downtime
:param ref: the host/service we want to link a comment to
:type ref: alignak.objects.schedulingitem.SchedulingItem
:return: None
"""
if self.fixed is True:
text = (DOWNTIME_FIXED_MESSAG... |
java | @Override
protected void setupHtmlData(final ActionRuntime runtime) {
super.setupHtmlData(runtime);
runtime.registerData("helpLink", systemHelper.getHelpLink(fessConfig.getOnlineHelpNameScheduler()));
} |
python | def cholesky(X):
"""
Supernodal multifrontal Cholesky factorization:
.. math::
X = LL^T
where :math:`L` is lower-triangular. On exit, the argument :math:`X`
contains the Cholesky factor :math:`L`.
:param X: :py:class:`cspmatrix`
"""
assert isinstance(X, cspmatrix) and X.i... |
java | public JSONToken yylex() throws java.io.IOException, ParseException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char[] zzBufferL = zzBuffer;
char[] zzCMapL = ZZ_CMAP;
int[] zzTra... |
java | @Override
public void init(String jsonString) throws AuthenticationException {
try {
setConfig(new JsonSimpleConfig(jsonString));
} catch (UnsupportedEncodingException e) {
throw new AuthenticationException(e);
} catch (IOException e) {
throw new Authentic... |
python | def infer(self, ob):
"""Add new observation to frame stack and infer policy.
Args:
ob: array of shape (height, width, channels)
Returns:
logits and vf.
"""
self._add_to_stack(ob)
logits, vf = self.infer_from_frame_stack(self._frame_stack)
return logits, vf |
python | def labelLines(lines, align=True, xvals=None, **kwargs):
'''Label all lines with their respective legends.
Parameters
----------
lines : list of matplotlib lines
The lines to label
align : boolean, optional
If True, the label will be aligned with the slope of the line
at the lo... |
java | public void addMapShape(GoogleMapShape mapShape, long featureId, String database, String table) {
FeatureShape featureShape = getFeatureShape(database, table, featureId);
featureShape.addShape(mapShape);
} |
java | private Category searchCategory(String breadcrumb) {
return model.getFlatCategoriesLst().stream().filter(
cat -> cat.getBreadcrumb().equals(breadcrumb)
).findAny().orElse(null);
} |
java | protected void prepareDroppingTablesApproachScripts() throws DBCleanException
{
cleaningScripts.addAll(getTablesDroppingScripts());
cleaningScripts.addAll(getDBInitializationScripts());
cleaningScripts.addAll(getFKRemovingScripts());
cleaningScripts.addAll(getIndexesDroppingScripts());
... |
python | def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be ra... |
python | def receive_fmf_metadata(name, path, object_list=False):
"""
search node identified by name fmfpath
:param path: path to filesystem
:param name: str - name as pattern to search - "/name" (prepended hierarchy item)
:param object_list: bool, if true, return whole list of found items
:return: Tree... |
java | public final void drain() {
do {
if (!drainingThread.compareAndSet(null, Thread.currentThread())) {
return;
}
try {
Runnable runnable;
while ((runnable = queue.poll()) != null) {
try {
runnable.run();
} catch (Throwable t) {
uncau... |
java | @DELETE
@Path("me")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
public Response delete(@Context HttpServletRequest request) {
Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID);
return delete(userId);
} |
java | public static TypeDef forClass(final Class<?> typeClass) {
Utils.validateNotNull(typeClass, "Class cannot be null");
Utils.validateIsTrue(!typeClass.isArray(), "Cannot obtain TypeDef from array class");
final TypeDefRegistry typeDefRegistry = TypeDefRegistry.getInstance();
... |
python | def searchRnaQuantificationsInDb(
self, rnaQuantificationId=""):
"""
:param rnaQuantificationId: string restrict search by id
:return an array of dictionaries, representing the returned data.
"""
sql = ("SELECT * FROM RnaQuantification")
sql_args = ()
... |
python | def invisible_canvas():
"""
Context manager yielding a temporary canvas drawn in batch mode, invisible
to the user. Original state is restored on exit.
Example use; obtain X axis object without interfering with anything::
with invisible_canvas() as c:
efficiency.Draw()
... |
python | def set_pubsubhubbub(self):
"""Parses pubsubhubbub and email then sets value"""
self.pubsubhubbub = None
atom_links = self.soup.findAll('atom:link')
for atom_link in atom_links:
rel = atom_link.get('rel')
if rel == "hub":
self.pubsubhubbub = atom_l... |
java | public boolean add(E e)
{
if (queue.size() < maxSize)
{ // 未达到最大容量,直接添加
queue.add(e);
return true;
}
else
{ // 队列已满
E peek = queue.peek();
if (queue.comparator().compare(e, peek) > 0)
{ // 将新元素与当前堆顶元素比较,保留较小的元素
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.