language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def adam(f, x, learning_rate=1e-3, beta1=0.9, beta2=0.999, eps=1e-8,
maxiter=1000, tol=1e-16, callback=None):
r"""ADAM method to minimize an objective function.
General implementation of ADAM for solving
.. math::
\min f(x)
where :math:`f` is a differentiable functional.
The alg... |
java | public long factMatching(long n) {
return match(n)
.when(caseLong(0)).get(() -> 1L)
.when(caseLong(any())).get(i -> i * factMatching(i - 1))
.getMatch();
} |
python | def _get_auth(self):
"""Return the authorization data for an SNMP request.
:returns: A
:class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData`
object.
"""
if self.version == SNMP_V3:
# Handling auth/encryption credentials is not (yet) supported.
... |
python | def listify(values, N=1, delim=None):
"""Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if re... |
python | def execute_r(prog, quiet):
"""Run the R code prog an R subprocess
@raises ValueError if the subprocess exits with non-zero status
"""
FNULL = open(os.devnull, 'w') if quiet else None
try:
input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE)
status = subprocess.call... |
java | public void extendedGet(String remoteFileName,
long size,
DataSink sink,
MarkerListener mListener)
throws IOException,
ClientException,
ServerException {
extendedGet(remoteFileName,
... |
java | private void lexicalDescend(PageCompilingContext pc, Element element, boolean shouldPopScope) {
//pop form
if ("form".equals(element.tagName()))
pc.form = null;
//pop compiler if the scope ends
if (shouldPopScope) {
pc.lexicalScopes.pop();
}
} |
java | public void resetRow(int filepos, int rowsize) throws IOException {
mark = 0;
reset();
if (buf.length < rowsize) {
buf = new byte[rowsize];
}
filePos = filepos;
size = count = rowsize;
pos = 4;
buf[0] = (byte) ((rowsize >>> 24) & 0x... |
java | public void reinitializeClientDefaultSSLProperties() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "reinitializeClientDefaultSSLProperties");
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "reinitializeClientDefault... |
python | def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
... |
java | public Observable<TransformationInner> updateAsync(String resourceGroupName, String jobName, String transformationName, TransformationInner transformation, String ifMatch) {
return updateWithServiceResponseAsync(resourceGroupName, jobName, transformationName, transformation, ifMatch).map(new Func1<ServiceRespon... |
java | protected void updateTransientActions() {
Vector<Action> ta = new Vector<>();
for (LabelAtomProperty p : properties)
ta.addAll(p.getActions(this));
transientActions = ta;
} |
java | protected static void invalidateSwitchPoints() {
if (LOG_ENABLED) {
LOG.info("invalidating switch point");
}
SwitchPoint old = switchPoint;
switchPoint = new SwitchPoint();
synchronized(IndyInterface.class) { SwitchPoint.invalidateAll(new SwitchP... |
python | def _merge(self, value):
""" Returns a list based on `value`:
* missing required value is converted to an empty list;
* missing required items are never created;
* nested items are merged recursively.
"""
if not value:
return []
if value is not None... |
python | def process_header(self, data):
"""
Reads the first part of the file to get some essential metadata
# Returns
return (dict): the metadata in the header
"""
metadata = {
"datacolumns": data.read_chunk("I"),
"firstyear": data.read_chunk("I"),
... |
python | async def start(self):
"""Start process execution."""
# arguments passed to the Docker command
command_args = {
'command': self.command,
'container_image': self.requirements.get('image', constants.DEFAULT_CONTAINER_IMAGE),
}
# Get limit defaults.
... |
python | def draft(self, **kwargs):
'''Allows for easily re-drafting a policy
After a policy has been created, it was not previously possible
to re-draft the published policy. This method makes it possible
for a user with existing, published, policies to create drafts
from them so that t... |
python | def extract_now_state(self):
'''
Extract now map state.
Returns:
`np.ndarray` of state.
'''
x, y = self.__agent_pos
state_arr = np.zeros(self.__map_arr.shape)
state_arr[x, y] = 1
return np.expand_dims(state_arr, axis=0) |
python | def redraw(self, whence=0):
"""Redraw the canvas.
Parameters
----------
whence
See :meth:`get_rgb_object`.
"""
with self._defer_lock:
whence = min(self._defer_whence, whence)
if not self.defer_redraw:
if self._hold_re... |
java | protected long getBlockSize(final int idNamespace) {
Preconditions.checkArgument(blockSizer != null, "Blocksizer has not yet been initialized");
isActive = true;
long blockSize = blockSizer.getBlockSize(idNamespace);
Preconditions.checkArgument(blockSize>0,"Invalid block size: %s",blockS... |
python | def register_task_with_maintenance_window(WindowId=None, Targets=None, TaskArn=None, ServiceRoleArn=None, TaskType=None, TaskParameters=None, Priority=None, MaxConcurrency=None, MaxErrors=None, LoggingInfo=None, ClientToken=None):
"""
Adds a new task to a Maintenance Window.
See also: AWS API Documentation
... |
java | public ResultList<MovieBasic> getGenreMovies(int genreId, String language, Integer page, Boolean includeAllMovies, Boolean includeAdult) throws MovieDbException {
return tmdbGenre.getGenreMovies(genreId, language, page, includeAllMovies, includeAdult);
} |
java | @Override
public OutputStream getOutputStream() throws IOException {
URLConnection connection = url.openConnection();
if (connection == null) return null;
connection.setDoOutput(true); // is it necessary?
return connection.getOutputStream();
} |
python | def _format_operation_dict(operation, parameters):
"""Formats parameters in operation in the way BigQuery expects.
The input operation will be a query like ``SELECT %(namedparam)s`` and
the output will be a query like ``SELECT @namedparam``.
:type operation: str
:param operation: A Google BigQuery... |
python | def _pfp__process_metadata(self):
"""Process the metadata once the entire struct has been
declared.
"""
if self._pfp__metadata_processor is None:
return
metadata_info = self._pfp__metadata_processor()
if isinstance(metadata_info, list):
for metada... |
java | private static <T> T[] grow(T[] array, int required) {
int oldCapacity = array.length;
// x1.5: 20, 30, 45, 67, 100, 150, 225, 337, 505, etc
int newCapacity = oldCapacity == 0 ? DEFAULT_CAPACITY
: oldCapacity + (oldCapacity >> 1);
if (newCapacit... |
java | @Override
public IIOMetadata getImageMetadata(final int imageIndex) throws IOException {
checkBounds(imageIndex);
readHeader();
return new TGAMetadata(header, extensions);
} |
java | public void marshall(DescribeConfigurationsRequest describeConfigurationsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeConfigurationsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.m... |
python | def _parse_siz_segment(cls, fptr):
"""Parse the SIZ segment.
Parameters
----------
fptr : file
Open file object.
Returns
-------
SIZSegment
The current SIZ segment.
"""
offset = fptr.tell() - 2
read_buffer = fptr.... |
python | def dismiss(self, userId, groupId):
"""
解散群组方法。(将该群解散,所有用户都无法再接收该群的消息。) 方法
@param userId:操作解散群的用户 Id。(必传)
@param groupId:要解散的群 Id。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut",
... |
java | public Matrix3x2d scaleAround(double factor, double ox, double oy, Matrix3x2d dest) {
return scaleAround(factor, factor, ox, oy, this);
} |
java | private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (U.compareAndSwapObject(this, WAITERS, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.... |
python | def commit(self):
"""
Commit this transaction.
"""
if not self._parent._is_active:
raise exc.InvalidRequestError("This transaction is inactive")
yield from self._do_commit()
self._is_active = False |
java | protected void loadBasicStyle()
{
ctx.updateForGraphics(style, g);
display = style.getProperty("display");
if (display == null) display = CSSProperty.Display.INLINE;
CSSProperty.Float floating = style.getProperty("float");
if (floating == null) floating = Bl... |
java | @Override
public IPromise timeoutIn(long millis) {
final Actor actor = Actor.sender.get();
if ( actor != null )
actor.delayed(millis, ()-> timedOut(Timeout.INSTANCE));
else {
Actors.delayedCalls.schedule( new TimerTask() {
@Override
pub... |
java | public static AtomixConfig config(AtomixRegistry registry) {
return config(Thread.currentThread().getContextClassLoader(), null, registry);
} |
java | @Override
public void sawOpcode(int seen) {
if ((seen == Const.INVOKEVIRTUAL) && "printStackTrace".equals(getNameConstantOperand())
&& SignatureBuilder.SIG_VOID_TO_VOID.equals(getSigConstantOperand())) {
bugReporter
.reportBug(new BugInstance(this, BugType.IMC_IMMATURE_CLASS_PRINTSTACKTRACE.name(),... |
python | def getWinner(self, type = 'activation'):
"""
Returns the winner of the type specified {'activation' or
'target'}.
"""
maxvalue = -10000
maxpos = -1
ttlvalue = 0
if type == 'activation':
ttlvalue = Numeric.add.reduce(self.activation)
... |
java | public <R> R withCommitTransaction(TransFunc<R> transFunc) throws IOException {
return withTransaction(transFunc, true);
} |
python | def press_enter(multiple=False, silent=False):
"""Return a generator function which yields every time the user presses
return."""
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press ent... |
java | public static String convertFormat(String format) {
if (format == null)
return null;
else {
// day of week
format = format.replaceAll("EEE", "D");
// year
format = format.replaceAll("yy", "y");
// month
if (format.indexOf("MMM") != -1) {
format = format.replaceAll("MMM", "M");
} else {
... |
java | private void addJSONElement(Map<String, Object> siteData, JSONElement data) {
if(EdenUtils.elementIsObject(data)) {
addJSONObject(siteData, (JSONObject) data.getElement());
}
else if(EdenUtils.elementIsArray(data)) {
addJSONArray(siteData, (JSONArray) data.getElement());
... |
python | def write_or_delete_file(self, what, filename, data, force=False):
"""Write `data` to `filename` or delete if empty
If `data` is non-empty, this routine is the same as ``write_file()``.
If `data` is empty but not ``None``, this is the same as calling
``delete_file(filename)`. If `data`... |
java | public void setName(String name)
{
super.setName(name);
m_tf.setName(name);
if (m_button != null)
m_button.setName(name);
if (m_buttonTime != null)
m_buttonTime.setName(name);
} |
java | public void objectAvailable (ConfigObject object)
{
// keep this for later
_object = object;
// create our field editors
try {
Field[] fields = object.getClass().getFields();
for (Field field : fields) {
// if the field is anything but a plain... |
java | private void addPostParams(final Request request) {
if (from != null) {
request.addPostParam("From", from.toString());
}
if (to != null) {
request.addPostParam("To", to.toString());
}
if (statusCallback != null) {
request.addPostParam("Status... |
python | def _inherited_row(row, base_rows_from_pillar, ret):
'''Return a row with properties from parents.'''
base_rows = []
for base_row_from_pillar in base_rows_from_pillar:
base_row = __salt__['pillar.get'](base_row_from_pillar)
if base_row:
base_rows.append(base_row)
elif bas... |
java | public void trigger(String vaultName, String resourceGroupName, String fabricName, String containerName, String protectedItemName, String recoveryPointId, RestoreRequestResource resourceRestoreRequest) {
triggerWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, ... |
python | def manifest(self):
"""The manifest definition of the stencilset as a dict."""
if not self._manifest:
with open(self.manifest_path) as man:
self._manifest = json.load(man)
return self._manifest |
java | @Override
public EClass getPercentageChange() {
if (percentageChangeEClass == null) {
percentageChangeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(85);
}
return percentageChangeEClass;
} |
java | @Override
public int getOffset(int era, int year, int month, int day, int dayOfWeek,
int milliseconds) {
if (era == GregorianCalendar.BC) {
// Convert to extended year
year = 1 - year;
}
long time = Grego.fieldsToDay(year, month, day) * Grego.MILLIS_PER_DA... |
python | def cat_adb_log(self, tag, begin_time):
"""Takes an excerpt of the adb logcat log from a certain time point to
current time.
Args:
tag: An identifier of the time period, usualy the name of a test.
begin_time: Logline format timestamp of the beginning of the time
... |
java | private static MonetaryRoundingsSingletonSpi monetaryRoundingsSingletonSpi() {
try {
return Optional.ofNullable(Bootstrap
.getService(MonetaryRoundingsSingletonSpi.class))
.orElseGet(DefaultMonetaryRoundingsSingletonSpi::new);
} catch (Exception e) {
... |
java | private void parse(Reader reader, char separator) throws IOException, ParseException {
LOG.info("Parsing CSV file...");
/*
* Ideally one would configure the format using withHeader(String ...) but since the master column is optional
* this is of no use. Therefore, you'll get null if you were to call g... |
python | def render(self, template, context_stack, delimiters=None):
"""
Render a unicode template string, and return as unicode.
Arguments:
template: a template string of type unicode (but not a proper
subclass of unicode).
context_stack: a ContextStack instance.
... |
java | public void reference (Object object) {
if (copyDepth > 0) {
if (needsCopyReference != null) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
originalToCopy.put(needsCopyReference, object);
needsCopyReference = null;
}
} else if (references && object != nu... |
python | def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars):
""" Find and return continuum pixels given the flux and sigma cut
Parameters
----------
f_cut: float
the upper limit imposed on the quantity (fbar-1)
sig_cut: float
the upper limit imposed on the quantity (f_sig)
w... |
java | public OvhMigration project_serviceName_migration_migrationId_GET(String serviceName, String migrationId) throws IOException {
String qPath = "/cloud/project/{serviceName}/migration/{migrationId}";
StringBuilder sb = path(qPath, serviceName, migrationId);
String resp = exec(qPath, "GET", sb.toString(), null);
r... |
python | def rebuild(mode=''):
"""Rebuild the site with a nice UI."""
scan_site() # for good measure
if not current_user.can_rebuild_site:
return error('You are not permitted to rebuild the site.</p>'
'<p class="lead">Contact an administartor for '
'more information... |
java | public XAnnotation<javax.persistence.OneToOne> createOneToOne(
OneToOne cOneToOne) {
return cOneToOne == null ? null :
//
new XAnnotation<javax.persistence.OneToOne>(
javax.persistence.OneToOne.class,
//
cOneToOne.getTargetEntity() == null ? null :
new XSingleAnnotationField<Class<Ob... |
java | public static void doByteBufferPutCompressed(INDArray arr, ByteBuffer allocated, boolean rewind) {
CompressedDataBuffer compressedDataBuffer = (CompressedDataBuffer) arr.data();
CompressionDescriptor descriptor = compressedDataBuffer.getCompressionDescriptor();
ByteBuffer codecByteBuffer = descr... |
java | public void invokeRequest (byte[] arg1, InvocationService.ResultListener arg2)
{
InvocationMarshaller.ResultMarshaller listener2 = new InvocationMarshaller.ResultMarshaller();
listener2.listener = arg2;
sendRequest(INVOKE_REQUEST, new Object[] {
arg1, listener2
});
} |
python | def fail_api(channel):
"""Creates an embed UI for when the API call didn't work
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
"""
gui = ui_embed.UI(
channel,
"Couldn't get stats off RLTracke... |
java | public void setDeclaringType(JvmDeclaredType newDeclaringType)
{
if (newDeclaringType != eInternalContainer() || (eContainerFeatureID() != TypesPackage.JVM_MEMBER__DECLARING_TYPE && newDeclaringType != null))
{
if (EcoreUtil.isAncestor(this, newDeclaringType))
throw new IllegalArgumentException("Recursive c... |
python | def _parseBoundImportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.... |
python | def get_nulldata(self, rawtx):
"""Returns nulldata from <rawtx> as hexdata."""
tx = deserialize.tx(rawtx)
index, data = control.get_nulldata(tx)
return serialize.data(data) |
python | def match_filename( filename ):
"""
Checks whether a file exists, either as named, or as a a gzippped file (filename.gz)
Args:
(Str): The root filename.
Returns:
(Str|None): if the file exists (either as the root filename, or gzipped), the return
value will be the actual fi... |
java | private void deleteFiles(Predicate<File> predicate) {
directory.mkdirs();
// Iterate through all files in the storage directory.
for (File file : directory.listFiles(f -> f.isFile() && predicate.test(f))) {
try {
Files.delete(file.toPath());
} catch (IOException e) {
// Ignore t... |
python | def ext(self):
"""
Canonical file extension for this image e.g. ``'png'``. The returned
extension is all lowercase and is the canonical extension for the
content type of this image, regardless of what extension may have
been used in its filename, if any.
"""
ext_m... |
python | def list_from_content(cls, content):
"""
Gets a list of guilds from the HTML content of the world guilds' page.
Parameters
----------
content: :class:`str`
The HTML content of the page.
Returns
-------
:class:`list` of :class:`ListedGuild`
... |
java | private void addDependencyToGraph(final DbDependency dependency, final AbstractGraph graph, final int depth, final String parentId) {
// In that case of Axway artifact we will add a module to the graph
if (filters.getCorporateFilter().filter(dependency)) {
final DbModule dbTarget = repoHandl... |
python | def surfacemass(self,R,log=False):
"""
NAME:
surfacemass
PURPOSE:
return the surface density profile at this R
INPUT:
R - Galactocentric radius (/ro)
log - if True, return the log (default: False)
OUTPUT:
Sigma(R)
HIS... |
python | def file_copy(filename, settings):
"""
Copies a file. {'_file_copy': {'dest': 'new_file_name'}}
Args:
filename (str): Filename.
settings (dict): Must be {"dest": path of new file}
"""
for k, v in settings.items():
if k.startswith("dest"):
... |
java | public Annotation createAnnotation(@NonNull AnnotationType type, int start, int end, @NonNull Map<AttributeType, ?> attributeMap) {
Preconditions.checkArgument(start >= start(),
"Annotation must have a starting position >= the start of the document");
Preconditions.checkArg... |
python | def paging(self):
""" Gets the pagination type; compatible with entry.archive(page_type=...) """
if 'date' in self.spec:
_, date_span, _ = utils.parse_date(self.spec['date'])
return date_span
return 'offset' |
java | public static <W extends WitnessType<W>,A> EvalT<W,A> of(final AnyM<W,Eval<A>> monads) {
return new EvalT<>(
monads);
} |
java | public static Object getFor(int status, Request request, Response response) {
Object customRenderer = CustomErrorPages.getInstance().customPages.get(status);
Object customPage = CustomErrorPages.getInstance().getDefaultFor(status);
if (customRenderer instanceof String) {
customPage... |
python | def ignore(code):
"""Should this code be ignored.
:param str code: Error code (e.g. D201).
:return: True if code should be ignored, False otherwise.
:rtype: bool
"""
if code in Main.options['ignore']:
return True
if any(c in code for c in Main.options['ignore']):
return Tru... |
python | def done(self, *args, **kwargs):
"""Mark the whole ProgressSection as done"""
kwargs['state'] = 'done'
pr_id = self.add(*args, log_action='done', **kwargs)
self._session.query(Process).filter(Process.group == self._group).update({Process.state: 'done'})
self.start.state = 'done'... |
java | public final Boolean evaluateBoolean( Message message ) throws JMSException
{
Object value = evaluate(message);
if (value == null)
return null;
if (value instanceof Boolean)
return (Boolean)value;
throw new FFMQException("Expected a boolean b... |
java | public ByteArrayInputStream output2InputStream(final OutputStream out) {
if (out == null) return null;
return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
} |
python | def ynticks(self, nticks, index=1):
"""Set the number of ticks."""
self.layout['yaxis' + str(index)]['nticks'] = nticks
return self |
java | @SuppressWarnings("unchecked")
public static <E, C extends Counter<E>> C scale(C c, double s) {
C scaled = (C) c.getFactory().create();
for (E key : c.keySet()) {
scaled.setCount(key, c.getCount(key) * s);
}
return scaled;
} |
java | public static JTextComponent textComponentAsLabel(JTextComponent textcomponent) {
// Make the text component non editable
textcomponent.setEditable(false);
// Make the text area look like a label
textcomponent.setBackground((Color)UIManager.get("Label.background"));
textcomponen... |
python | def parse(s):
r"""
Returns a list of strings or format dictionaries to describe the strings.
May raise a ValueError if it can't be parsed.
>>> parse(">>> []")
['>>> []']
>>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\... |
java | public <E> Concatenator NOT_EQUALS(E value) {
getBooleanOp().setOperator(Operator.NOT_EQUALS);
return this.operateOn(value);
} |
java | public static <T, IV> int detectIndexWith(
T[] objectArray,
Predicate2<? super T, IV> predicate,
IV injectedValue)
{
if (objectArray == null)
{
throw new IllegalArgumentException("Cannot perform a detectIndexWith on null");
}
for (int i... |
python | def _norm_include(self, record, hist=None):
"""
Normalization 'normIncludes' replace 'almost' values based on at least
one of the following: includes strings, excludes strings, starts with
string, ends with string
:param dict record: dictionary of values to validate
:par... |
java | public static Single<String> read(String path) {
return SingleRxXian.call("cosService", "cosRead", new JSONObject() {{
put("path", path);
}}).flatMap(response -> {
response.throwExceptionIfNotSuccess();
return Single.just(Objects.requireNonNull(response.dataToStr()));... |
java | private EndPointInfoImpl updateEndpointMBean(String name, String host, int port) {
EndPointInfoImpl existingEP = endpoints.get(name);
existingEP.updateHost(host);
existingEP.updatePort(port);
return existingEP;
} |
python | def list_extensions(request):
"""List all nova extensions, except the ones in the blacklist."""
blacklist = set(getattr(settings,
'OPENSTACK_NOVA_EXTENSIONS_BLACKLIST', []))
nova_api = _nova.novaclient(request)
return tuple(
extension for extension in
nova_lis... |
java | @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (getEmbeddedHttp2Exception(cause) != null) {
// Some exception in the causality chain is an Http2Exception - handle it.
onError(ctx, false, cause);
} else {
sup... |
python | def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""Link to a GitHub user.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be
empty.
:param name: The role name used in the document.
:par... |
python | def _get_element_attr_or_none(document, selector, attribute):
"""
Using a CSS selector, get the element and return the given attribute value, or None if no element.
Args:
document (HTMLElement) - HTMLElement document
selector (str) - CSS selector
attribute (str) - The attribute to g... |
java | public void updateContentList(List<CmsTreeItem> treeItemsToShow) {
m_scrollList.clearList();
if ((treeItemsToShow != null) && !treeItemsToShow.isEmpty()) {
for (CmsTreeItem dataValue : treeItemsToShow) {
dataValue.removeOpener();
m_scrollList.add(dataVa... |
python | def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
"""
if weekday:
c = [dee... |
java | public static Response getExceptionResponse(final int status, final String msg) {
return Response.status(status).entity(new LinkedHashMap<String, Object>() {
private static final long serialVersionUID = 1L;
{
put("code", status);
put("message", msg);
}
}).type(MediaType.APPLICATION_JSON).build();
... |
java | public int executeUpdateDeleteQuery(String cqlQuery) {
if (log.isDebugEnabled()) {
log.debug("Executing cql query {}.", cqlQuery);
}
try {
CqlResult result = (CqlResult) executeCQLQuery(cqlQuery, true);
return result.getNum();
} catch (Exception e) {
... |
python | def unzip(archive, destination, filenames=None):
"""Unzip a zip archive into destination directory.
It unzips either the whole archive or specific file(s) from the archive.
Usage:
>>> output = os.path.join(os.getcwd(), 'output')
>>> # Archive can be an instance of a ZipFile class
>... |
java | private Query getQueryBySqlCount(QueryBySQL aQuery)
{
String countSql = aQuery.getSql();
int fromPos = countSql.toUpperCase().indexOf(" FROM ");
if(fromPos >= 0)
{
countSql = "select count(*)" + countSql.substring(fromPos);
}
int orderPos = cou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.