language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _set_xfpe(self, v, load=False):
"""
Setter method for xfpe, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/xfpe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_xfpe is considered as a private
method. Backends lo... |
java | @Override
public java.util.concurrent.Future<CreateTopicResult> createTopicAsync(String name,
com.amazonaws.handlers.AsyncHandler<CreateTopicRequest, CreateTopicResult> asyncHandler) {
return createTopicAsync(new CreateTopicRequest().withName(name), asyncHandler);
} |
java | private MultipartContent createContent(final ProblemInput input, final File output, final File source) throws IOException {
final HttpMediaType type = new HttpMediaType(MEDIA_TYPE);
type.setParameter(BOUNDARY, createBoundary());
// Submission from Chrome through contest website sends fake path for security,
// ... |
python | def print_path(path: Path) -> str:
"""Build string describing the path into the value where error was found"""
path_str = ""
current_path: Optional[Path] = path
while current_path:
path_str = (
f".{current_path.key}"
if isinstance(current_path.key, str)
else f... |
python | def get_interpolation_function(self, times, series):
""" Initializes interpolation model
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy.array
:param series: One dimensional array of time series
:type series: numpy.array
... |
python | def set_text(self, text): # Not abstract.
"""
Shortcut for setting plain text on clipboard.
"""
assert isinstance(text, six.string_types)
self.set_data(ClipboardData(text)) |
python | def _CollectHistoryAgg_(contactHist, fieldHistObj, fieldName):
"""
Return updated history dictionary with new field change
:param dict contactHist: Existing contact history dictionary
:param dict fieldHistObj: Output of _CollectHistory_
:param string fieldName: field name
"""
if fieldHistO... |
java | private void updateUnderFileSystemInputStream(long offset) throws IOException {
if ((mUnderFileSystemInputStream != null) && offset != mInStreamPos) {
mUfsInstreamManager.release(mUnderFileSystemInputStream);
mUnderFileSystemInputStream = null;
mInStreamPos = -1;
}
if (mUnderFileSystemInp... |
python | def secure_filename(path, destiny_os=os.name, fs_encoding=compat.FS_ENCODING):
'''
Get rid of parent path components and special filenames.
If path is invalid or protected, return empty string.
:param path: unsafe path, only basename will be used
:type: str
:param destiny_os: destination opera... |
java | public static String urlEncode(String url, Pattern unsafe, Charset charset) {
StringBuffer sb = new StringBuffer(url.length());
Matcher matcher = unsafe.matcher(url);
while (matcher.find()) {
String str = matcher.group(0);
byte[] bytes = str.getBytes(charset);
... |
java | public static String getZodiac(int month, int day) {
// 在分隔日前为前一个星座,否则为后一个星座
return day < dayArr[month] ? ZODIACS[month] : ZODIACS[month + 1];
} |
java | public Duration extractTopologyTimeout() {
for (TopologyAPI.Config.KeyValue keyValue
: this.getTopology().getTopologyConfig().getKvsList()) {
if (keyValue.getKey().equals("topology.message.timeout.secs")) {
return TypeUtils.getDuration(keyValue.getValue(), ChronoUnit.SECONDS);
}
}
... |
python | def parse_timespan_value(s):
"""Parse a string that contains a time span, optionally with a unit like s.
@return the number of seconds encoded by the string
"""
number, unit = split_number_and_unit(s)
if not unit or unit == "s":
return number
elif unit == "min":
return number * 6... |
java | public void processTimeout(TimeoutEvent timeoutEvent) {
Transaction transaction = null;
if(timeoutEvent.isServerTransaction()) {
transaction = timeoutEvent.getServerTransaction();
if(logger.isDebugEnabled()) {
logger.debug("timeout => " + transaction.getRequest().... |
python | def group_is_client_group(self) -> bool:
"""
Returns: True if this group is a client group
"""
# TODO create test
first_unit = self.get_unit_by_index(1)
if first_unit:
return first_unit.skill == 'Client'
return False |
java | public static com.liferay.commerce.model.CommerceAddressRestriction getCommerceAddressRestriction(
long commerceAddressRestrictionId)
throws com.liferay.portal.kernel.exception.PortalException {
return getService()
.getCommerceAddressRestriction(commerceAddressRestrictionId);
} |
python | def get_class_that_defined_method(fun):
"""
Tries to find the class that defined the specified method. Will not work for nested classes
(locals).
Args:
fun: Function / Method
Returns:
Returns the class which defines the given method / function.
"""
if inspect.ismethod(fun):... |
python | def enable_thread_logging(exception_callback=None):
"""
Monkey-patch the threading.Thread class with our own LoggedThread. Any subsequent imports of threading.Thread
will reference LoggedThread instead.
"""
global logged_thread_enabled, Thread
LoggedThread.exception_callback = exception_callback... |
python | def update(self):
""" updates the configuration settings """
with open(os.path.join(self.config_dir, CONFIG_FILE_NAME), 'w') as config_file:
self.config.write(config_file) |
java | Expression XreadDateTimeValueFunctionOrNull() {
FunctionSQL function = null;
switch (token.tokenType) {
case Tokens.CURRENT_DATE :
case Tokens.CURRENT_TIME :
case Tokens.CURRENT_TIMESTAMP :
case Tokens.LOCALTIME :
case Tokens.LOCALTIMESTAMP ... |
python | def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing ... |
python | def saveSettings(self, settings):
"""
Saves the files for this menu to the settings.
:param settings | <QSettings>
"""
value = wrapVariant(os.path.pathsep.join(self.filenames()))
settings.setValue('recent_files', value) |
python | def _set_overlay_acl_in(self, v, load=False):
"""
Setter method for overlay_acl_in, mapped from YANG variable /overlay_gateway/access_lists/overlay_acl_in (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_acl_in is considered as a private
method. Ba... |
java | public static CommercePriceEntry fetchByCommercePriceListId_First(
long commercePriceListId,
OrderByComparator<CommercePriceEntry> orderByComparator) {
return getPersistence()
.fetchByCommercePriceListId_First(commercePriceListId,
orderByComparator);
} |
python | def execute_get_text(command): # type: (str) ->str
"""
Execute shell command and return stdout txt
:param command:
:return:
"""
try:
_ = subprocess.run
try:
completed = subprocess.run(
command,
check=True,
shell=True,
... |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString ssl_certificate_validator = new MPSString();
ssl_certificate_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
ssl_certificate_validator.setConstraintMinStrLen(MPSConstants.GEN... |
java | public int getRequestSize() {
if (records == null) {
return 1;
}
int size = 1;
for (RecordRequest record : records) {
size += record.getRequestSize();
}
return size;
} |
python | def mutate(self, node, index):
"""Modify the For loop to evaluate to None"""
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
node.children[3] = empty_list
return node |
java | public static String ensureLeft(final String value, final String prefix) {
return ensureLeft(value, prefix, true);
} |
java | public void setJustification(justifyTypes justify) {
if (justify == justifyTypes.BEGIN) mTextView.setGravity(Gravity.LEFT);
else if (justify == justifyTypes.MIDDLE) mTextView.setGravity(Gravity.CENTER);
else if (justify == justifyTypes.END) mTextView.setGravity(Gravity.RIGHT);
else i... |
python | def _expand_paths(path):
"""
Expand wildcarded paths
"""
dir_name = os.path.dirname(path)
paths = []
logger.debug("Attempting to expand %s", path)
if os.path.isdir(dir_name):
files = os.listdir(dir_name)
match = os.path.basename(path)
for file_path in files:
... |
java | public boolean putMany(int key, Collection<Integer> values) {
// Short circuit when adding empty values to avoid adding a key with an
// empty mapping
if (values.isEmpty())
return false;
IntSet vals = map.get(key);
if (vals == null) {
vals = new TroveIntSe... |
python | def export(self, id, exclude_captures=False): # pylint: disable=invalid-name,redefined-builtin
"""Export a result.
:param id: Result ID as an int.
:param exclude_captures: If bool `True`, don't export capture files
:rtype: tuple `(io.BytesIO, 'filename')`
"""
return self... |
java | public Query toQuery() throws UnsupportedEncodingException{
return new Query()
.append("name", name)
.append("path", path)
.appendIf("ldap_cn", ldapCn)
.appendIf("description", description)
.appendIf("membershipLock", membershipLock)
.appendIf("share_wit... |
python | def committees_legislators(self, *args, **kwargs):
'''Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members.
'''
committees = list(self.committees(*args, **kwargs))
le... |
java | public static Codec<double[], DoubleGene> ofVector(
final DoubleRange... domains
) {
if (domains.length == 0) {
throw new IllegalArgumentException("Domains must not be empty.");
}
final ISeq<DoubleChromosome> chromosomes = Stream.of(domains)
.peek(Objects::requireNonNull)
.map(DoubleGene::of)
.map... |
java | public Card bankCode(final Integer bankCode) {
if (bankCode == null) {
this.bankCode = null;
} else {
this.bankCode = String.format("%03d", bankCode);
}
return this;
} |
python | def _get_distance(self, pnt1, pnt2):
"""Get distance in meters between two lat/long points"""
lat1, lon1 = pnt1
lat2, lon2 = pnt2
radius = 6356752 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) * math.sin(dlat / 2) +... |
java | public Predicate<T> negate() {
return new Predicate<T>() {
@Override
public boolean test( T input ) {
return !Predicate.this.test(input);
}
@Override
public Predicate<T> negate() {
return Predicate.this;
}
... |
java | private double getPercent( int idx, double defaultValue, CssFormatter formatter ) {
if( parameters.size() <= idx ) {
return defaultValue;
}
return ColorUtils.getPercent( get( idx ), formatter );
} |
java | private static void copyStream(InputStream is, OutputStream os, int bufferSize)
throws IOException {
Assert.checkNotNullParam("is", is);
Assert.checkNotNullParam("os", os);
byte[] buff = new byte[bufferSize];
int rc;
while ((rc = is.read(buff)) != -1) os.write(buff, 0... |
python | def do_bugout(self, args):
"""bugout [ <logger> ] - remove a console logging handler from a logger"""
args = args.split()
if _debug: ConsoleCmd._debug("do_bugout %r", args)
# get the logger name and logger
if args:
loggerName = args[0]
if loggerName in l... |
python | def verify_signature(message, signature, certs):
"""Verify an RSA cryptographic signature.
Checks that the provided ``signature`` was generated from ``bytes`` using
the private key associated with the ``cert``.
Args:
message (Union[str, bytes]): The plaintext message.
signature (Union[... |
java | public static Object returnField(Object object, String fieldName) throws MjdbcException {
AssertUtils.assertNotNull(object);
Object result = null;
Field field = null;
try {
field = object.getClass().getField(fieldName);
result = field.get(object);
... |
python | def get_url(self, agent_id, media_id):
"""
获取永久素材下载地址
详情请参考
https://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90
:param agent_id: 企业应用的id
:param media_id: 媒体文件 ID
:return: 临时素材下载地址
"""
parts = (
... |
python | def delete(self, uri, default_response=None):
"""
Call DELETE on the Gitlab server
>>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False)
>>> gitlab.login(user='root', password='5iveL!fe')
>>> gitlab.delete('/users/5')
:param uri: String with the URI you w... |
python | def normalize_full_name_true(decl):
"""
Cached variant of normalize
Args:
decl (declaration.declaration_t): the declaration
Returns:
str: normalized name
"""
if decl.cache.normalized_full_name_true is None:
decl.cache.normalized_full_name_true = normalize(
d... |
java | public Event nextEvent () {
while (_next == null && _ds.hasNext())
_next = createEvent((String)_ds.nextToken());
Event current = _next;
if (_ds.hasNext()) {
_next = createEvent((String)_ds.nextToken());
}
else {
_next = null;
}
return current;
} |
python | def _call_numpy(self, x):
"""Return ``self(x)`` using numpy.
See Also
--------
DiscreteFourierTransformBase._call_numpy
"""
assert isinstance(x, np.ndarray)
if self.halfcomplex:
return np.fft.rfftn(x, axes=self.axes)
else:
if self... |
python | def _get_ssh_client(self, host, user, key):
"""Return a connected Paramiko ssh object.
:param str host: The host to connect to.
:param str user: The user to connect as.
:param str key: The private key to authenticate with.
:return: object: A paramiko.SSHClient
:raises: ... |
python | def find_satisfied_condition(conditions, ps):
"""Returns the first element of 'property-sets' which is a subset of
'properties', or an empty list if no such element exists."""
assert is_iterable_typed(conditions, property_set.PropertySet)
assert isinstance(ps, property_set.PropertySet)
for conditio... |
python | def create_concept_scheme(rdf, ns, lname=''):
"""Create a skos:ConceptScheme in the model and return it."""
ont = None
if not ns:
# see if there's an owl:Ontology and use that to determine namespace
onts = list(rdf.subjects(RDF.type, OWL.Ontology))
if len(onts) > 1:
onts... |
java | public Query addValueRefinement(String navigationName, String value, boolean exclude) {
return addRefinement(navigationName, new RefinementValue().setValue(value).setExclude(exclude));
} |
java | public static void readPropertiesToListeners(InputStream source, Encoding encoding, PropertiesParsingListener... listeners)
throws IOException, SyntaxErrorException
{
BufferedReader _reader = new BufferedReader(createReaderForInputStream(source, encoding));
LineByLinePropertyParser _parser = new LineByLinePrope... |
java | @Override
public UpdateConfigurationSetReputationMetricsEnabledResult updateConfigurationSetReputationMetricsEnabled(
UpdateConfigurationSetReputationMetricsEnabledRequest request) {
request = beforeClientExecution(request);
return executeUpdateConfigurationSetReputationMetricsEnabled(re... |
java | public static Logger getL7dLogger(Class<?> cls) {
//Liberty Change for CXF Begin
return createLogger(cls, null, cls.getName() + getClassLoader(cls));
//Liberty Change for CXF End
} |
java | private boolean setPrevious(byte[] sequence, int start, int length) {
if (previous == null || previous.length < length) {
previous = new byte[length];
}
System.arraycopy(sequence, start, previous, 0, length);
previousLength = length;
return true;
} |
java | public static String toLowerCase(String string, Locale locale) {
if (locale == null) {
return toLowerCase(string, STANDARD_LOCALE);
}
return string.toLowerCase(locale);
} |
java | protected static PrimitiveIterator.OfLong createDelayStream(Duration delay, Duration jitter) {
if (jitter.isZero()) {
// No jitter, return an infinite stream of the delay duration
long delayNanos = asClampedNanos(delay);
return LongStream.generate(() -> delayNanos).iterator()... |
java | public String getLocalName(int nodeHandle) {
nodes.readSlot(nodeHandle, gotslot);
short type = (short) (gotslot[0] & 0xFFFF);
String name = "";
if ((type==ELEMENT_NODE) || (type==ATTRIBUTE_NODE)) {
int i=gotslot[3];
name... |
python | def put_tagging(Bucket,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Given a valid config, update the tags for a bucket.
Returns {updated: true} if tags were updated and returns
{updated: False} if tags were not updated.
CLI Example:
.. code-block:: bash
... |
java | private final boolean subparse(
String text, ParsePosition parsePosition, DigitList digits,
boolean status[], Currency currency[], String negPrefix, String negSuffix, String posPrefix,
String posSuffix, boolean parseComplexCurrency, int type) {
int position = parsePosition.getIndex();
... |
python | def get_field_callback(self, field, event):
# type: (str, str) -> Optional[Tuple[Callable, bool]]
"""
Retrieves the registered method for the given event. Returns None if
not found
:param field: Name of the dependency field
:param event: A component life cycle event
... |
python | def trans(self, id, parameters=None, domain=None, locale=None):
"""
Translates the given message.
@type id: str
@param id: The message id
@type parameters: dict
@param parameters: A dict of parameters for the message
@type domain: str
@param domain: The... |
java | @BetaApi
public final Operation deleteForwardingRule(String forwardingRule) {
DeleteForwardingRuleHttpRequest request =
DeleteForwardingRuleHttpRequest.newBuilder().setForwardingRule(forwardingRule).build();
return deleteForwardingRule(request);
} |
java | public CompletableFuture<Object> patchAsync(@DelegatesTo(HttpConfig.class) final Closure closure) {
return CompletableFuture.supplyAsync(() -> patch(closure), getExecutor());
} |
java | public ExchangePublisher<String> createExchangeTextPublisher(final String name)
{
Preconditions.checkState(connectionFactory != null, "connection factory was never injected!");
return new ExchangePublisher<String>(connectionFactory, amqpConfig, name, stringPublisherCallback);
} |
java | public void setRefEdge(Integer newRefEdge) {
Integer oldRefEdge = refEdge;
refEdge = newRefEdge;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FINISHING_OPERATION__REF_EDGE, oldRefEdge, refEdge));
} |
python | def exit(self, code=None, timeout=5):
"""
Wait for process to exit or until timeout (5 sec by default) and asserts
that process exits with ``code``. If ``code`` is ``None``, returns the code
the process exited with.
..note:: In order to ensure that spawned child processes do not... |
python | def cut_for_search(self, sentence, HMM=True):
"""
Finer segmentation for search engines.
"""
words = self.cut(sentence, HMM=HMM)
for w in words:
if len(w) > 2:
for i in xrange(len(w) - 1):
gram2 = w[i:i + 2]
if s... |
python | def sanitize_jid(s):
"""Generates a valid JID node identifier from a string"""
jid = unicode_to_ascii(s).lower()
jid = WHITESPACE.sub('-', jid)
jid = INVALID_JID_CHARS.sub('', jid)
return jid.strip()[:256] |
java | public KamNode resolve(final Kam kam, final KAMStore kAMStore,
final String belTerm, Map<String, String> nsmap,
Equivalencer equivalencer) throws ResolverException {
if (nulls(kam, kAMStore, belTerm, nsmap, equivalencer)) {
throw new InvalidArgument(
"null... |
python | def basic_types(self):
"""Returns non-postgres types referenced in user supplied model """
if not self.foreign_key_definitions:
return self.standard_types
else:
tmp = self.standard_types
tmp.append('ForeignKey')
return tmp |
java | public void getTitleInfo(int[] ids, Callback<List<Title>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getTitleInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} |
java | public NullnessHint analyzeReturnType() {
if (method.getReturnType().isPrimitiveType()) {
LOG(DEBUG, "DEBUG", "Skipping method with primitive return type: " + method.getSignature());
return NullnessHint.UNKNOWN;
}
LOG(DEBUG, "DEBUG", "@ Return type analysis for: " + method.getSignature());
/... |
java | public RosterEntry getEntry(BareJid jid) {
if (jid == null) {
return null;
}
return entries.get(jid);
} |
python | def serialize(input, tree="etree", encoding=None, **serializer_opts):
"""Serializes the input token stream using the specified treewalker
:arg input: the token stream to serialize
:arg tree: the treewalker to use
:arg encoding: the encoding to use
:arg serializer_opts: any options to pass to the... |
python | def noise_power_spectrum(data, ground_truth, radial=False,
radial_binning_factor=2.0):
"""Return the Noise Power Spectrum (NPS).
The NPS is given by the squared magnitude of the Fourier transform of the
noise.
Parameters
----------
data : `DiscreteLpElement` or `array-... |
python | def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
"""
Gradient of the log likelihood function at y, given link(f) w.r.t link(f)
.. math::
\\frac{d \\ln p(y_{i}|\\lambda(f_{i}))}{d\\lambda(f)} = \\beta (\\log \\beta y_{i}) - \\Psi(\\alpha_{i})\\beta\\\\
\\alpha_{i} = \... |
java | @Override
public EClass getIfcComplexNumber() {
if (ifcComplexNumberEClass == null) {
ifcComplexNumberEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1112);
}
return ifcComplexNumberEClass;
} |
java | public NRShape makeShape(Date from, Date to) {
UnitNRShape fromShape = tree.toUnitShape(from);
UnitNRShape toShape = tree.toUnitShape(to);
return tree.toRangeShape(fromShape, toShape);
} |
java | public OvhConferenceWebAccess billingAccount_conference_serviceName_webAccess_POST(String billingAccount, String serviceName, OvhConferenceWebAccessTypeEnum type) throws IOException {
String qPath = "/telephony/{billingAccount}/conference/{serviceName}/webAccess";
StringBuilder sb = path(qPath, billingAccount, serv... |
python | def delete_user_sessions(user):
"""Delete all active user sessions.
:param user: User instance.
:returns: If ``True`` then the session is successfully deleted.
"""
with db.session.begin_nested():
for s in user.active_sessions:
_sessionstore.delete(s.sid_s)
SessionActivi... |
python | def set(self, name, value, autodeclare=False):
"""Set the value of a key.
This method will cause anyone waiting on a key (and any future
waiters) to unblock and be returned the value you pass here.
If the key has not been declared previously, a KeyError() is
raised unless you p... |
python | def _prt_qualifiers(associations, prt=sys.stdout):
"""Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
... |
java | public static boolean exists(String deviceName) throws DevFailed {
// Get full device name (with tango host) to manage multi tango_host
String fullDeviceName = new TangoUrl(deviceName).toString();
// Get it if already exists
DeviceProxy dev = proxy_table.get(fullDeviceName);
ret... |
python | def default_resolve_fn(source, info, **args):
# type: (Any, ResolveInfo, **Any) -> Optional[Any]
"""If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object
of the same name as the field and returns it as the result, or if it's a function, ret... |
python | def _comp_task(inbox, args, kwargs):
"""
(internal) Composes a sequence of functions in the global variable TASK. The
resulting composition is given the input "inbox" and arguments "args",
"kwargs".
"""
# Note. this function uses a global variable which must be defined on the
# remote... |
python | def polyfit2d(x, y, z, order=3 #bounds=None
):
'''
fit unstructured data
'''
ncols = (order + 1)**2
G = np.zeros((x.size, ncols))
ij = itertools.product(list(range(order+1)), list(range(order+1)))
for k, (i,j) in enumerate(ij):
G[:,k] = x**i * y**j
m = np... |
python | def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None):
r"""
Batch normalization.
.. math::
\begin{eqnarray}
\mu &=& \frac{1}{M} \sum x_i \\
\sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri... |
python | def space_cluster(catalog, d_thresh, show=True):
"""
Cluster a catalog by distance only.
Will compute the matrix of physical distances between events and utilize
the :mod:`scipy.clustering.hierarchy` module to perform the clustering.
:type catalog: obspy.core.event.Catalog
:param catalog: Cata... |
python | def style_checkboxes(widget):
"""
Iterates over widget children to change checkboxes stylesheet.
The default rendering of checkboxes does not allow to tell a focused one
from an unfocused one.
"""
ww = widget.findChildren(QCheckBox)
for w in ww:
w.setStyleSheet("QCheckBox... |
java | public static String openTagStyleHtmlContent(String tag, String style, String... content) {
return openTagHtmlContent(tag, null, style, content);
} |
python | def parse_reqtype(self):
"""Return the authentication body."""
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
'username': self.job_args.get('os_user')
}
# Check if any prefix items are set. A prefix s... |
python | def attention(q,
k,
v,
memory_length_dim,
key_dim,
value_dim,
mask=None,
dropout_rate=0.0,
dropout_broadcast_dims=None,
extra_logit=None):
"""Dot-product attention - doesn't use positional dim... |
python | def set_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):
"""Set the key value based on it's storage type."""
if isinstance(value, dict):
if PUBLIC_KEY_STORE_TYPE_HEX in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_HEX], PUBLIC_KEY_STORE_TYPE_HEX)
... |
python | def clear_all(self):
"""
Deletes all ``sandsnake`` related data from redis.
.. warning::
Very expensive and destructive operation. Use with causion
"""
keys = self._analytics_backend.keys()
for key in itertools.chain(*keys):
with self._analytics... |
java | private static int nextPowerOfTwo(int v) {
assert v >= 0;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
} |
java | private Object search(Collection<?> collection, String hashKey) {
int hash = Integer.valueOf(hashKey);
for (Object o : collection) {
if (o.hashCode() == hash)
return o;
}
//nothing found
return null;
} |
java | public static void waitFor(File aFile)
{
if(aFile == null)
return;
String path =aFile.getAbsolutePath();
long previousSize = IO.getFileSize(path);
long currentSize = previousSize;
long sleepTime = Config.getPropertyLong("file.monitor.file.wait.t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.