language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | protected void queueFrame(FrameCallBack callback, ByteBuffer... data) {
queuedData += Buffers.remaining(data);
bufferCount += data.length;
frameQueue.add(new Frame(callback, data, 0, data.length));
} |
java | public static String findCodeBaseInClassPath(@Nonnull String codeBaseName, String classPath) {
if (classPath == null) {
return null;
}
StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
while (tok.hasMoreTokens()) {
String t = tok.nextToken... |
python | def v1_subfolder_add(request, response, kvlclient,
fid, sfid, cid, subid=None):
'''Adds a subtopic to a subfolder for the current user.
The route for this endpoint is:
``PUT /dossier/v1/folder/<fid>/subfolder/<sfid>/<cid>/<subid>``.
``fid`` is the folder identifier, e.g., ``My_Fol... |
python | def libvlc_set_user_agent(p_instance, name, http):
'''Sets the application name. LibVLC passes this as the user agent string
when a protocol requires it.
@param p_instance: LibVLC instance.
@param name: human-readable application name, e.g. "FooBar player 1.2.3".
@param http: HTTP User Agent, e.g. "... |
java | @Override
public void eUnset(int featureID)
{
switch (featureID)
{
case TypesPackage.JVM_INNER_TYPE_REFERENCE__OUTER:
setOuter((JvmParameterizedTypeReference)null);
return;
}
super.eUnset(featureID);
} |
java | protected final void setKetamaNodes(List<MemcachedNode> nodes) {
TreeMap<Long, MemcachedNode> newNodeMap = new TreeMap<Long, MemcachedNode>();
final int numReps = config.getNodeRepetitions();
for (MemcachedNode node : nodes) {
// Ketama does some special work with md5 where it reuses... |
python | def get_md5(path):
"""获取文件的 MD5 值。
:param str path: 文件路径。
:returns: MD5 值。
:rtype: str
"""
with open(path,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
return md5obj.hexdigest()
raise FileNotFoundError("Error when get md5 for %s!"%path) |
python | def vectored_io_from_metadata(md):
# type: (dict) -> collections.namedtuple
"""Convert vectored io metadata in json metadata
:param dict md: metadata dictionary
:rtype: VectoredStripe or None
:return: vectored io metadata
"""
try:
mdattr = json.loads(
md[JSON_KEY_BLOBXFER... |
java | public Object marshalRootElement() {
if (justRoutes) {
RoutesDefinition routes = new RoutesDefinition();
routes.setRoutes(contextElement.getRoutes());
return routes;
} else {
return contextElement;
}
} |
java | public Interaction getApplicableInteraction(String eventLabel, boolean verbose) {
String targetsString = getTargets();
if (targetsString != null) {
try {
Targets targets = new Targets(getTargets());
String interactionId = targets.getApplicableInteraction(eventLabel, verbose);
if (interactionId != nul... |
java | public static Optional<String> getOptional(String string) {
return Optional.ofNullable(string).filter(getIsEmpty().negate());
} |
python | def _add_args(parser, args, required):
"""
Add new arguments to an ArgumentParser.
:param argparse.ArgumentParser parser: instance to update with new arguments
:param Iterable[str] args: Collection of names of arguments to add.
:param Iterable[str] required: Collection of arguments to designate as ... |
python | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
... |
python | async def get_tracks(self, query) -> Tuple[Track, ...]:
"""
Gets tracks from lavalink.
Parameters
----------
query : str
Returns
-------
Tuple[Track, ...]
"""
if not self._warned:
log.warn("get_tracks() is now deprecated. Plea... |
python | def unindex_template(self, tpl):
"""
Unindex a template from the `templates` container.
:param tpl: The template to un-index
:type tpl: alignak.objects.item.Item
:return: None
"""
name = getattr(tpl, 'name', '')
try:
del self.name_to_template[... |
python | def record_tx(self, origin, destination, amount,
outcome, destination_id=None):
"""Records a transaction in the database.
Args:
origin (str): user_id of the sender
destination (str): coin address or user_id of the recipient
amount (str, Decimal, number): ... |
python | def wait_for_task(self, task, logger, action_name='job', hide_result=False, cancellation_context=None):
"""
Waits and provides updates on a vSphere task
:param cancellation_context: package.cloudshell.cp.vcenter.models.QualiDriverModels.CancellationContext
:param task:
:param act... |
python | def find_users_by_email(self, email, user_base='active'):
"""Return list of users with given email address"""
users = []
for user in getattr(self, 'users')(user_base).values():
mail = user.mail
if mail and email in mail:
users.append(user)
log.debu... |
java | @Override
public String doOCR(int xsize, int ysize, ByteBuffer buf, String filename, Rectangle rect, int bpp) throws TesseractException {
init();
setTessVariables();
try {
setImage(xsize, ysize, buf, rect, bpp);
return getOCRText(filename, 1);
} catch (Except... |
java | static String getBuiltInBindingsKey(String key) {
int start = startOfType(key);
if (substringStartsWith(key, start, PROVIDER_PREFIX)) {
return extractKey(key, start, key.substring(0, start), PROVIDER_PREFIX);
} else if (substringStartsWith(key, start, MEMBERS_INJECTOR_PREFIX)) {
return extractKe... |
java | public static Constructor<?>[] getAllConstructorsOfClass(final Class<?> clazz, boolean accessible) {
if (clazz == null) {
return null;
}
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
if (constructors != null && constructors.length > 0) {
Accessi... |
java | @Override
public List<AdminObject> getAdminObjects()
{
return adminObjects == null ? null : Collections.unmodifiableList(adminObjects);
} |
java | static void parse(String path, DbConn cnx, String overrideJarBasePath) throws JqmXmlException
{
// Argument checks
jqmlogger.trace(path);
if (path == null || path.isEmpty())
{
throw new IllegalArgumentException("XML file path cannot be empty");
}
if (cnx =... |
python | def recvServerInit(self, data):
"""
Read server init packet
@param data: Stream that contains well formed packet
"""
data.readType(self._serverInit)
self.expectWithHeader(4, self.recvServerName) |
python | def run_command(self, command, arg=None, is_eval=False):
"""run command on the server
Args:
command - command string
arg - command argument
is_eval - if True execute command as eval
return command's result
"""
mode = is_eval and 'eval' or 'co... |
python | def create(cls, paas_info, vhost, alter_zone, background):
""" Create a new vhost. """
if not background and not cls.intty():
background = True
params = {'paas_id': paas_info['id'],
'vhost': vhost,
'zone_alter': alter_zone}
result = cls.ca... |
java | public Polygon toPolygon(List<LatLng> latLngs, List<List<LatLng>> holes) {
return toPolygon(latLngs, holes, false, false);
} |
python | def acquire_writer(self):
"""
Acquire a write lock, only one thread can hold this lock
and only when no read locks are also held.
"""
with self.mutex:
while self.rwlock != 0:
self._writer_wait()
self.rwlock = -1 |
java | private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
if (null == redisHost || redisPort < 1) {
LOGGER.error("没有指定redis服务器配置!");
return;
}
Thread thread = new Thread(new Runnable() {
@Override
public voi... |
java | @Override
public @Nullable BinaryResource getResource(final CacheKey key) {
String resourceId = null;
SettableCacheEvent cacheEvent = SettableCacheEvent.obtain()
.setCacheKey(key);
try {
synchronized (mLock) {
BinaryResource resource = null;
List<String> resourceIds = CacheKe... |
java | public List<String> load(String[] args) throws IOException {
setLogLevel(Level.WARNING);
mappings.addJreMappings();
// Create a temporary directory as the sourcepath's first entry, so that
// modified sources will take precedence over regular files.
fileUtil.setSourcePathEntries(new ArrayList<>())... |
python | def populateCsv(self):
"""
Writes data from streams into CSV in working directory.
:return:
"""
workingDirPath = createDir(self._workingDir)
csvPath = os.path.join(workingDirPath, "data.csv")
self.writeCsv(csvPath)
return csvPath, workingDirPath |
java | private Schema readUnion(JsonReader reader, Set<String> knownRecords) throws IOException {
ImmutableList.Builder<Schema> unionSchemas = ImmutableList.builder();
reader.beginArray();
while (reader.peek() != JsonToken.END_ARRAY) {
unionSchemas.add(read(reader, knownRecords));
}
reader.endArray()... |
java | public void logv(Level level, String format, Object... params) {
doLog(level, FQCN, format, params, null);
} |
java | public static Status fromThrowable(Throwable t) {
Throwable cause = checkNotNull(t, "t");
while (cause != null) {
if (cause instanceof StatusException) {
return ((StatusException) cause).getStatus();
} else if (cause instanceof StatusRuntimeException) {
return ((StatusRuntimeExceptio... |
python | def from_obj(cls, cls_obj):
"""Parse the generateDS object and return an Entity instance.
This will attempt to extract type information from the input
object and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_obj: A generateDS object.
... |
java | public RiakNode setMaxConnections(int maxConnections)
{
stateCheck(State.CREATED, State.RUNNING, State.HEALTH_CHECKING);
if (maxConnections >= getMinConnections())
{
permits.setMaxPermits(maxConnections);
}
else
{
throw new IllegalArgumentExcep... |
python | def after_this_request(func: Callable) -> Callable:
"""Schedule the func to be called after the current request.
This is useful in situations whereby you want an after request
function for a specific route or circumstance only, for example,
.. code-block:: python
def index():
@aft... |
java | public final EObject entryRuleFullJvmFormalParameter() throws RecognitionException {
EObject current = null;
EObject iv_ruleFullJvmFormalParameter = null;
try {
// InternalSARL.g:8251:63: (iv_ruleFullJvmFormalParameter= ruleFullJvmFormalParameter EOF )
// InternalSARL.... |
python | def profile_create(name, config=None, devices=None, description=None,
remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Creates a profile.
name :
The name of the profile to get.
config :
A config dict or None (None = unset).... |
python | def wrap_text(text, width):
"""
Wrap text paragraphs to the given character width while preserving
newlines.
"""
out = []
for paragraph in text.splitlines():
# Wrap returns an empty list when paragraph is a newline. In order
# to preserve newlines ... |
python | def list(self, params={}):
"""
Required Parameters:
* searchType (str)
- cardExpiringThisMonth
- subscriptionActive
- subscriptionInactive
- subscriptionExpiringThisMonth
Optional Parameters:
* sorting
* orderBy (string... |
java | @XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "postalAddress")
public JAXBElement<String> createPostalAddress(String value) {
return new JAXBElement<String>(_PostalAddress_QNAME, String.class, null, value);
} |
java | public static TagModel getSingleParent(TagModel tag)
{
final Iterator<TagModel> parents = tag.getDesignatedByTags().iterator();
if (!parents.hasNext())
throw new WindupException("Tag is not designated by any tags: " + tag);
final TagModel maybeOnlyParent = parents.next();
... |
python | def safe_str(unicode_, to_encoding=None):
"""
safe str function. Does few trick to turn unicode_ into string
In case of UnicodeEncodeError we try to return it with encoding detected
by chardet library if it fails fallback to string with errors replaced
:param unicode_: unicode to encode
:rtype... |
java | @Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) {
final List<String> serializedHeaders = responseContext.getHeaders().get(TraceeConstants.TPIC_HEADER);
if (serializedHeaders != null && backend.getConfiguration().shouldProcessContext(IncomingRespo... |
java | public <K, V> StatefulRedisPubSubConnection<K, V> connectPubSub(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectPubSubAsync(codec, redisURI, timeout));
} |
python | def _find_complete_block_bounds(self, table, used_cells, possible_block_start,
start_pos, end_pos):
'''
Finds the end of a block from a start location and a suggested end location.
'''
block_start = list(possible_block_start)
block_end = list(p... |
java | @SuppressWarnings("UnnecessaryLocalVariable")
public static boolean isJsonApiRequest(HttpRequestContext requestContext, boolean acceptPlainJson) {
String method = requestContext.getMethod().toUpperCase();
boolean isPatch = method.equals(HttpMethod.PATCH.toString());
boolean isPost = method.equals(HttpMethod.POST... |
python | def load_csv_stream(ctx, model, data,
header=None, header_exclude=None, **fmtparams):
"""Load a CSV from a stream.
:param ctx: current anthem context
:param model: model name as string or model klass
:param data: csv data to load
:param header: csv fieldnames whitelist
:para... |
python | def Nu_Yamagata(Re, Pr, Pr_pc=None, Cp_avg=None, Cp_b=None, T_b=None,
T_w=None, T_pc=None):
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.0138 Re_b^{0.85}Pr_b... |
python | def delta_ps(prev, curr, counters):
""" calculate the delta per second of one counter
formula: (curr - prev) / delta_time
:param prev: previous resource
:param curr: current resource
:param counters: the counter to do delta and per second, one only
:return: value, NaN if invalid.
"""
co... |
python | def write(self, transport, protocol, *data):
"""Generates and sends a command message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message.
:param protocol: An object implementing the `.Protocol` interface.
... |
java | public ArrayList<OvhSnapshotEnum> serviceName_partition_partitionName_snapshot_GET(String serviceName, String partitionName) throws IOException {
String qPath = "/dedicated/nasha/{serviceName}/partition/{partitionName}/snapshot";
StringBuilder sb = path(qPath, serviceName, partitionName);
String resp = exec(qPath... |
python | def search_archive(pattern, archive, verbosity=0, interactive=True):
"""Search pattern in archive members."""
if not pattern:
raise util.PatoolError("empty search pattern")
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Searching %r in %s ..." % (pattern, archive... |
java | @Nullable
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Size optSize(@Nullable Bundle bundle, @Nullable String key, @Nullable Size fallback) {
if (bundle == null) {
return fallback;
}
return bundle.getSize(key);
} |
java | @Override
public AdminListUserAuthEventsResult adminListUserAuthEvents(AdminListUserAuthEventsRequest request) {
request = beforeClientExecution(request);
return executeAdminListUserAuthEvents(request);
} |
java | @Override
public INDArray getTad(int idx, int... dimensions) {
return arr.get().tensorAlongDimension(idx, dimensions);
} |
java | private void printHelp() {
String summary =
"Usage: bin/hdfs oev [OPTIONS] -i INPUT_FILE -o OUTPUT_FILE\n" +
"Offline edits viewer\n" +
"Parse a Hadoop edits log file INPUT_FILE and save results\n" +
"in OUTPUT_FILE.\n" +
"Required command line arguments:\n" +
"-i,--inputFile <ar... |
java | public double getLength() {
double len = 0;
if (!isEmpty()) {
for (Polygon polygon : polygons) {
len += polygon.getLength();
}
}
return len;
} |
python | def setEditable( self, state ):
"""
Sets whether or not this combobox will be editable, updating its \
line edit to an XLineEdit if necessary.
:param state | <bool>
"""
super(XComboBox, self).setEditable(state)
if state:
edit = s... |
python | def run_wrap(self, args):
""" Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression should happen in the `session.... |
python | def cudnnDestroy(handle):
"""
Release cuDNN resources.
Release hardware resources used by cuDNN.
Parameters
----------
handle : cudnnHandle
cuDNN context.
"""
status = _libcudnn.cudnnDestroy(ctypes.c_void_p(handle))
cudnnCheckStatus(status) |
java | public SimpleBitSet get(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
checkInvariants();
int len = length();
// If no set bits in range return empty bitset
if (len <= fromIndex || fromIndex == toIndex)
return new SimpleBitSet(0);
// An optimization
if (toIndex > len)
toIndex = le... |
python | def remove_plus(orig):
"""Remove a fils, including biological index files.
"""
for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]:
if os.path.exists(orig + ext):
remove_safe(orig + ext) |
java | private static void throwCause(final ExecutionException ex) {
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
}
if (ex.getCause() instanceof Error) {
throw (Error) ex.getCause();
}
} |
java | public Encoding getEncoding() {
String value = first(ENCODING);
return (value == null) ? null : Encoding.get(value);
} |
java | protected static void removeFromContext(CmsObject cms, CmsPublishedResource pubRes) {
cms.getRequestContext().removeAttribute(getAttributeKey(pubRes.getRootPath()));
} |
python | def _void_array_to_list(restuple, _func, _args):
""" Convert the FFI result to Python data structures """
shape = (restuple.e.len, 1)
array_size = np.prod(shape)
mem_size = 8 * array_size
array_str_e = string_at(restuple.e.data, mem_size)
array_str_n = string_at(restuple.n.data, mem_size)
... |
java | public Node getViewWithoutRootContainer() {
final ObservableList<Node> children = getView().getChildrenUnmodifiable();
if (children.isEmpty()) {
return null;
}
return children.listIterator().next();
} |
python | def set_working_directory(self, dirname):
"""Set current working directory.
In the workingdirectory and explorer plugins.
"""
if dirname:
self.main.workingdirectory.chdir(dirname, refresh_explorer=True,
refresh_console=False) |
java | FacesContext getFacesContextWithoutServletContextLookup() {
FacesContext result = facesContextCurrentInstance.get();
if (null == result) {
if (null != facesContextThreadInitContextMap && !facesContextThreadInitContextMap.isEmpty()) {
result = facesContextThreadInitContextMap.... |
java | @SafeVarargs
public static short[] removeAll(final short[] a, final short... elements) {
if (N.isNullOrEmpty(a)) {
return N.EMPTY_SHORT_ARRAY;
} else if (N.isNullOrEmpty(elements)) {
return a.clone();
} else if (elements.length == 1) {
return remove... |
python | def _from_string(cls, serialized):
"""
Return an instance of `cls` parsed from its `serialized` form.
Args:
cls: The :class:`OpaqueKey` subclass.
serialized (unicode): A serialized :class:`OpaqueKey`, with namespace already removed.
Raises:
InvalidKe... |
python | def upload(self, num_iid, properties, session, id=None, image=None, position=None):
'''taobao.item.propimg.upload 添加或修改属性图片
添加一张商品属性图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 图片的属性必须要是颜色的属性,这个在前台显示的时候需要和sku进行关联的 商品属性图片只有享有服务的卖家(如:淘宝大卖家、订购了淘宝多图服务的卖家)才能上传 商品属性图片有数量和大小上的限制,最多不能超过24张(每个颜色属性都有一张)。... |
java | public static byte kuz_mul_gf256_fast(byte a, byte b) {
if (a == 0 || b == 0) return 0;
int t = (KuznechikTables.gf256_L[(a & 0xff)] & 0xff) + (KuznechikTables.gf256_L[(b & 0xff)] & 0xff);
if (t > 255) t = t - 255;
return KuznechikTables.gf256_E[(t & 0xff)];
} |
java | @SuppressWarnings("checkstyle:avoidhidingcauseexception")
public static ConfigurationBuilder parseToConfigurationBuilder(final String[] args,
final Class<? extends Name<?>>... argClasses)
throws ParseException {
final CommandLine commandLine;
... |
java | public void setUP3iDat(byte[] newUP3iDat) {
byte[] oldUP3iDat = up3iDat;
up3iDat = newUP3iDat;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.UP_3I_FINISHING_OPERATION__UP_3I_DAT, oldUP3iDat, up3iDat));
} |
java | public static String sha512(final String data) {
return digest(MessageDigestAlgorithms.SHA_512, data.getBytes(StandardCharsets.UTF_8));
} |
java | public Set<OrganizationSet> createCompactionSets(Table tableInfo, Collection<ShardIndexInfo> shards)
{
Collection<Collection<ShardIndexInfo>> shardsByDaysBuckets = getShardsByDaysBuckets(tableInfo, shards, temporalFunction);
ImmutableSet.Builder<OrganizationSet> compactionSets = ImmutableSet.builde... |
java | public static void generateParamSerializer(BindTypeContext context, String propertyName, TypeName parameterTypeName, PersistType persistType) {
propertyName = SQLiteDaoDefinition.PARAM_SERIALIZER_PREFIX + propertyName;
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(propertyName).addJavadoc("for param ... |
python | def create_masks(input_dim,
hidden_dims,
input_order='left-to-right',
hidden_order='left-to-right'):
"""Returns a list of binary mask matrices respecting autoregressive ordering.
Args:
input_dim: Number of inputs.
hidden_dims: list with the number of hidde... |
python | def store_many_vectors(self, vs, data=None):
"""
Store a batch of vectors.
Hashes vector vs and stores them in all matching buckets in the storage.
The data argument must be either None or a list of JSON-serializable
object. It is stored with the vector and will be returned in se... |
java | @Nullable
public static AnnotationTree getAnnotationWithSimpleName(
List<? extends AnnotationTree> annotations, String name) {
for (AnnotationTree annotation : annotations) {
if (hasSimpleName(annotation, name)) {
return annotation;
}
}
return null;
} |
java | private void checkTransactions(final int height, final EnumSet<VerifyFlag> flags)
throws VerificationException {
// The first transaction in a block must always be a coinbase transaction.
if (!transactions.get(0).isCoinBase())
throw new VerificationException("First tx is not coin... |
java | @Nullable
@CheckReturnValue
public static String trimStart (@Nullable final String sSrc, @Nullable final String sLead)
{
return startsWith (sSrc, sLead) ? sSrc.substring (sLead.length (), sSrc.length ()) : sSrc;
} |
python | def _get_delivery_date(row):
"""Get delivery date (estimated or actual)."""
try:
month = row.find('div', {'class': 'date-small'}).string
day = row.find('div', {'class': 'date-num-large'}).string
except AttributeError:
return None
try:
return parse('{} {}'.format(month, da... |
python | def publish(self, topic, data, defer=None, block=True, timeout=None,
raise_error=True):
"""Publish a message to the given topic.
:param topic: the topic to publish to
:param data: bytestring data to publish
:param defer: duration in milliseconds to defer before publish... |
python | def get(self, fmt, offset):
"""
Get the value of a given bitfield.
:param fmt: format-string for the bitfield being read, e.g. u8 for an
unsigned 8-bit integer.
:param int offset: offset (in number of bits).
:returns: a :py:class:`BitFieldOperation` instance.
... |
java | public void adoptParent(ElementBox parent)
{
if (parent instanceof BlockBox)
setContainingBlockBox(parent);
else
setContainingBlockBox(parent.getContainingBlockBox());
setParent(parent);
setViewport(parent.getViewport());
setClipBlock(parent.getClipBlo... |
python | def type(self):
"""Retrieves the type of the incident/incidents from the output
response
Returns:
type(namedtuple): List of named tuples of type of the
incident/incidents
"""
resource_list = self.traffic_incident()
type = namedtuple('type', 'type'... |
python | def _B(self, x, a, b):
"""
incomplete Beta function as described in Mamon&Lokas A13
:param x:
:param a:
:param b:
:return:
"""
return special.betainc(a, b, x) * special.beta(a, b) |
java | @Override
public String tagValue(String value) {
return StringEscapeUtils.escapeJson(delegate.tagValue(value));
} |
java | public String getFragmentAdminURL(HttpServletRequest request) {
IPortalUrlBuilder builder =
urlProvider.getPortalUrlBuilderByPortletFName(
request, PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET, UrlType.RENDER);
IPortletUrlBuilder portletUrlBuilder = builder.getTargetedPor... |
java | public static Instant randomInstantBefore(Instant before) {
checkArgument(before != null, "Before must be non-null");
checkArgument(before.isAfter(MIN_INSTANT), "Cannot produce date before %s", MIN_INSTANT);
return randomInstant(MIN_INSTANT, before);
} |
java | public static Iterable<Class<?>> getAnnotated(Class<? extends Annotation> annotation) {
return getAnnotated(annotation, Thread.currentThread().getContextClassLoader());
} |
python | def analytic_2d (f, df, x0, y0,
maxiters=5000,
defeta=0.05,
netastep=12,
vtol1=1e-3,
vtol2=1e-8,
maxnewt=20,
dorder=7,
goright=False):
"""Sample a contour in a 2D analytic function... |
python | def elliot_function( signal, derivative=False ):
""" A fast approximation of sigmoid """
s = 1 # steepness
abs_signal = (1 + np.abs(signal * s))
if derivative:
return 0.5 * s / abs_signal**2
else:
# Return the activation signal
return 0.5*(signal * s) / abs_signal + 0.5 |
java | public static boolean verifySignatureWithPublicKey(byte[] keyData, byte[] message,
byte[] signature) throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException, SignatureException {
return verifySignatureWithPublicKey(keyData, message, signature,
DEFAUL... |
python | def left_release(self, event):
"""
Callback for the release of the left button.
:param event: Tkinter event
"""
self.config(cursor="")
if len(self.canvas.find_withtag("current")) != 0 and self.current is not None:
self.canvas.itemconfigure(tk.CURRENT, fill=se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.