language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def plot_dropout_rate_heterogeneity(
model,
suptitle="Heterogeneity in Dropout Probability",
xlabel="Dropout Probability p",
ylabel="Density",
suptitle_fontsize=14,
**kwargs
):
"""
Plot the estimated gamma distribution of p.
p - (customers' probability of dropping out immediately after a transaction).
Parameters
----------
model: lifetimes model
A fitted lifetimes model, for now only for BG/NBD
suptitle: str, optional
Figure suptitle
xlabel: str, optional
Figure xlabel
ylabel: str, optional
Figure ylabel
kwargs
Passed into the matplotlib.pyplot.plot command.
Returns
-------
axes: matplotlib.AxesSubplot
"""
from matplotlib import pyplot as plt
a, b = model._unload_params("a", "b")
beta_mean = a / (a + b)
beta_var = a * b / ((a + b) ** 2) / (a + b + 1)
rv = stats.beta(a, b)
lim = rv.ppf(0.99)
x = np.linspace(0, lim, 100)
fig, ax = plt.subplots(1)
fig.suptitle(suptitle, fontsize=suptitle_fontsize, fontweight="bold")
ax.set_title("mean: {:.3f}, var: {:.3f}".format(beta_mean, beta_var))
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.plot(x, rv.pdf(x), **kwargs)
return ax |
java | public void updateRecord(final ORecordInternal<?> record) {
if (isEnabled() && record.getIdentity().getClusterId() != excludedCluster && record.getIdentity().isValid()) {
underlying.lock(record.getIdentity());
try {
if (underlying.get(record.getIdentity()) != record)
underlying.put(record);
} finally {
underlying.unlock(record.getIdentity());
}
}
secondary.updateRecord(record);
} |
java | private int typeDepth(Class<?> match, Class<?> actual)
{
if (actual == null) {
return Integer.MAX_VALUE / 2;
}
if (match.equals(Object.class)) {
return Integer.MAX_VALUE / 4;
}
if (match.equals(actual)) {
return 0;
}
int cost = 1 + typeDepth(match, actual.getSuperclass());
for (Class<?> iface : actual.getInterfaces()) {
cost = Math.min(cost, 1 + typeDepth(match, iface));
}
return cost;
} |
python | def filtered(w=250):
"""
In this example we filter the image into several channels using gabor filters. L6 activity is used to select
one of those channels. Only activity selected by those channels burst.
"""
# prepare filter bank kernels
kernels = []
for theta in range(4):
theta = theta / 4. * np.pi
for sigma in (1, 3):
for frequency in (0.05, 0.25):
kernel = np.real(gabor_kernel(frequency, theta=theta,
sigma_x=sigma, sigma_y=sigma))
kernels.append(kernel)
print("Initializing thalamus")
t = Thalamus(
trnCellShape=(w, w),
relayCellShape=(w, w),
inputShape=(w, w),
l6CellCount=128*128,
trnThreshold=15,
)
ff = loadImage(t)
for i,k in enumerate(kernels):
plotActivity(k, "kernel"+str(i)+".jpg", "Filter kernel", vmax=k.max(),
vmin=k.min())
filtered0 = power(ff, k)
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
plotActivity(ft, "filtered"+str(i)+".jpg", "Filtered image", vmax=1.0)
encoder = createLocationEncoder(t, w=17)
trainThalamusLocations(t, encoder)
filtered0 = power(ff, kernels[3])
ft = np.zeros((w, w))
ft[filtered0 > filtered0.mean() + filtered0.std()] = 1.0
# Get a salt and pepper burst ready image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=10))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput = inferThalamus(t, l6Code, ft)
plotActivity(t.burstReadyCells, "relay_burstReady_filtered.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput, "cajal_relay_output_filtered.jpg",
title="Filtered activity",
cmap="Greys")
# Get a more detailed filtered image
print("Getting unions")
l6Code = list(getUnionLocations(encoder, 125, 125, 150, step=3))
print("Num active cells in L6 union:", len(l6Code),"out of", t.l6CellCount)
ffOutput_all = inferThalamus(t, l6Code, ff)
ffOutput_filtered = inferThalamus(t, l6Code, ft)
ffOutput3 = ffOutput_all*0.4 + ffOutput_filtered
plotActivity(t.burstReadyCells, "relay_burstReady_all.jpg",
title="Burst-ready cells",
)
plotActivity(ffOutput3, "cajal_relay_output_filtered2.jpg",
title="Filtered activity",
cmap="Greys") |
python | def count_leases_by_owner(self, leases): # pylint: disable=no-self-use
"""
Returns a dictionary of leases by current owner.
"""
owners = [l.owner for l in leases]
return dict(Counter(owners)) |
java | @VisibleForTesting
protected void initMetadata(HttpHeaders headers) throws IOException {
checkState(
!metadataInitialized,
"can not initialize metadata, it already initialized for '%s'", resourceIdString);
long sizeFromMetadata;
String range = headers.getContentRange();
if (range != null) {
sizeFromMetadata = Long.parseLong(range.substring(range.lastIndexOf('/') + 1));
} else {
sizeFromMetadata = headers.getContentLength();
}
String generation = headers.getFirstHeaderStringValue("x-goog-generation");
initMetadata(headers.getContentEncoding(), sizeFromMetadata, generation);
} |
java | public final void postAggArithOper(PostAggItem postAggItem) throws RecognitionException {
Token arith=null;
try {
// druidG.g:554:2: (arith= ARITH_OPER )
// druidG.g:554:3: arith= ARITH_OPER
{
arith=(Token)match(input,ARITH_OPER,FOLLOW_ARITH_OPER_in_postAggArithOper3606);
postAggItem.fn = (arith!=null?arith.getText():null);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
} |
java | public static URL createURL(String protocol,
String host,
int port,
String file) throws MalformedURLException {
URLStreamHandlerFactory factory = _factories.get(protocol);
// If there is no URLStreamHandlerFactory registered for the
// scheme/protocol, then we just use the regular URL constructor.
if (factory == null) {
return new URL(protocol, host, port, file);
}
// If there is a URLStreamHandlerFactory associated for the
// scheme/protocol, then we create a URLStreamHandler. And, then use
// then use the URLStreamHandler to create a URL.
URLStreamHandler handler = factory.createURLStreamHandler(protocol);
return new URL(protocol, host, port, file, handler);
} |
java | @Override
protected boolean performRequest() {
boolean cancelledDone = false;
// If we were worken up because we have work to do, do it.
Set<SelectionKey> keySet = selector.selectedKeys();
Iterator<SelectionKey> selectedIterator = keySet.iterator();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(this, tc, "performRequest - processing " + keySet.size() + " items");
}
while (selectedIterator.hasNext()) {
SelectionKey selectedKey = selectedIterator.next();
// safely remove key from set while looping
selectedIterator.remove();
ConnectInfo connectInfo = (ConnectInfo) selectedKey.attachment();
connectInfo.setFinish();
if (wqm.dispatchConnect(connectInfo)) {
selectedKey.cancel();
cancelledDone = true;
}
}
return cancelledDone;
} |
java | @Override
public String getBatchAppNameFromInstance(long instanceId) throws NoSuchJobInstanceException, JobSecurityException {
return persistenceManagerService.getJobInstanceAppName(authorizedInstanceRead(instanceId));
} |
java | private Thread getScannerThread() {
return new Thread(() -> {
Scanner scanIn = new Scanner(System.in);
while (true) {
String line = scanIn.nextLine();
if (line.isEmpty()) {
break;
}
ByteBuf buf = ByteBuf.wrapForReading(encodeAscii(line + "\r\n"));
eventloop.execute(() -> socket.write(buf));
}
eventloop.execute(socket::close);
});
} |
python | def _store16(ins):
""" Stores 2nd operand content into address of 1st operand.
store16 a, x => *(&a) = x
Use '*' for indirect store on 1st operand.
"""
output = []
output = _16bit_oper(ins.quad[2])
try:
value = ins.quad[1]
indirect = False
if value[0] == '*':
indirect = True
value = value[1:]
value = int(value) & 0xFFFF
if indirect:
output.append('ex de, hl')
output.append('ld hl, (%s)' % str(value))
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
else:
output.append('ld (%s), hl' % str(value))
except ValueError:
if value[0] == '_':
if indirect:
output.append('ex de, hl')
output.append('ld hl, (%s)' % str(value))
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
else:
output.append('ld (%s), hl' % str(value))
elif value[0] == '#':
value = value[1:]
if indirect:
output.append('ex de, hl')
output.append('ld hl, (%s)' % str(value))
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
else:
output.append('ld (%s), hl' % str(value))
else:
output.append('ex de, hl')
if indirect:
output.append('pop hl')
output.append('ld a, (hl)')
output.append('inc hl')
output.append('ld h, (hl)')
output.append('ld l, a')
else:
output.append('pop hl')
output.append('ld (hl), e')
output.append('inc hl')
output.append('ld (hl), d')
return output |
python | def validate_rpc_sha(repo_dir, commit):
"""Validate/update a SHA given for the rpc-openstack repo."""
# Is the commit valid? Just in case the commit is a
# PR ref, we try both the ref given and the ref prepended
# with the remote 'origin'.
try:
osa_differ.validate_commits(repo_dir, [commit])
except exceptions.InvalidCommitException:
log.debug("The reference {c} cannot be found. Prepending "
"origin remote and retrying.".format(c=commit))
commit = 'origin/' + commit
osa_differ.validate_commits(repo_dir, [commit])
return commit |
java | public static void closeBoth(Closeable first, Closeable second) throws IOException
{
//noinspection EmptyTryBlock
try (Closeable ignore1 = second; Closeable ignore2 = first) {
// piggy-back try-with-resources semantics
}
} |
java | @Override
public void run() {
// Workaround for Issue #4 (http://code.google.com/p/jdiameter/issues/detail?id=4)
// BEGIN WORKAROUND // Give some time to initialization...
int sleepTime = 250;
logger.debug("Sleeping for {}ms before starting transport so that listeners can all be added and ready for messages", sleepTime);
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
// ignore
}
logger.debug("Finished sleeping for {}ms. By now, MutablePeerTableImpl should have added its listener", sleepTime);
logger.debug("Transport is started. Socket is [{}]", socketDescription);
Selector selector = null;
try {
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
while (!stop) {
selector.select(SELECT_TIMEOUT);
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = it.next();
// Remove it from the list to indicate that it is being processed
it.remove();
if (selKey.isValid() && selKey.isReadable()) {
// Get channel with bytes to read
SocketChannel sChannel = (SocketChannel) selKey.channel();
int dataLength = sChannel.read(buffer);
logger.debug("Just read [{}] bytes on [{}]", dataLength, socketDescription);
if (dataLength == -1) {
stop = true;
break;
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
append(data);
buffer.clear();
}
}
}
}
catch (ClosedByInterruptException e) {
logger.error("Transport exception ", e);
}
catch (AsynchronousCloseException e) {
logger.error("Transport is closed");
}
catch (Throwable e) {
logger.error("Transport exception ", e);
}
finally {
try {
clearBuffer();
if (selector != null) {
selector.close();
}
if (socketChannel != null && socketChannel.isOpen()) {
socketChannel.close();
}
getParent().onDisconnect();
}
catch (Exception e) {
logger.error("Error", e);
}
stop = false;
logger.info("Read thread is stopped for socket [{}]", socketDescription);
}
} |
java | private void accumulateNormal(final Element center, final Element pre,
final Element post) {
double cx = center.getDouble("x");
double cy = center.getDouble("y");
double cz = center.getDouble("z");
double ax = post.getDouble("x") - cx;
double ay = post.getDouble("y") - cy;
double az = post.getDouble("z") - cz;
double a = Math.sqrt(ax * ax + ay * ay + az * az);
if (a < EPSILON) {
return;
}
double bx = pre.getDouble("x") - cx;
double by = pre.getDouble("y") - cy;
double bz = pre.getDouble("z") - cz;
double b = Math.sqrt(bx * bx + by * by + bz * bz);
if (b < EPSILON) {
return;
}
double nx = ay * bz - az * by;
double ny = az * bx - ax * bz;
double nz = ax * by - ay * bx;
double n = Math.sqrt(nx * nx + ny * ny + nz * nz);
if (n < EPSILON) {
return;
}
double sin = n / (a * b);
double dot = ax * bx + ay * by + az * bz;
double angle;
if (dot < 0) {
angle = Math.PI - Math.asin(sin);
} else {
angle = Math.asin(sin);
}
double factor = angle / n;
nx *= factor;
ny *= factor;
nz *= factor;
center.setDouble("nx", center.getDouble("nx") + nx);
center.setDouble("ny", center.getDouble("ny") + ny);
center.setDouble("nz", center.getDouble("nz") + nz);
} |
python | def insert(collection_name, docs, check_keys,
safe, last_error_args, continue_on_error, opts):
"""Get an **insert** message."""
options = 0
if continue_on_error:
options += 1
data = struct.pack("<i", options)
data += bson._make_c_string(collection_name)
encoded = [bson.BSON.encode(doc, check_keys, opts) for doc in docs]
if not encoded:
raise InvalidOperation("cannot do an empty bulk insert")
max_bson_size = max(map(len, encoded))
data += _EMPTY.join(encoded)
if safe:
(_, insert_message) = __pack_message(2002, data)
(request_id, error_message, _) = __last_error(collection_name,
last_error_args)
return (request_id, insert_message + error_message, max_bson_size)
else:
(request_id, insert_message) = __pack_message(2002, data)
return (request_id, insert_message, max_bson_size) |
java | public float getFloat(int key)
{
Object value = map.get(key);
if (!(value instanceof Float))
{
return 0.0f;
}
Float result = (Float)value;
return result;
} |
python | def convert(self, blob, **kw):
"""Convert using unoconv converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for my Mac, FIXME later
if Path("/Applications/LibreOffice.app/Contents/program/python").exists():
cmd = [
"/Applications/LibreOffice.app/Contents/program/python",
"/usr/local/bin/unoconv",
] + args
else:
cmd = [self.unoconv] + args
def run_uno():
try:
self._process = subprocess.Popen(
cmd, close_fds=True, cwd=bytes(self.tmp_dir)
)
self._process.communicate()
except Exception as e:
logger.error("run_uno error: %s", bytes(e), exc_info=True)
raise ConversionError("unoconv failed") from e
run_thread = threading.Thread(target=run_uno)
run_thread.start()
run_thread.join(timeout)
try:
if run_thread.is_alive():
# timeout reached
self._process.terminate()
if self._process.poll() is not None:
try:
self._process.kill()
except OSError:
logger.warning("Failed to kill process %s", self._process)
self._process = None
raise ConversionError(f"Conversion timeout ({timeout})")
converted = open(out_fn).read()
return converted
finally:
self._process = None |
java | public void setLCID(Integer newLCID) {
Integer oldLCID = lcid;
lcid = newLCID;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.GSCS__LCID, oldLCID, lcid));
} |
java | public synchronized Object co_resume(Object arg_object,int thisCoroutine,int toCoroutine) throws java.lang.NoSuchMethodException
{
if(!m_activeIDs.get(toCoroutine))
throw new java.lang.NoSuchMethodException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COROUTINE_NOT_AVAIL, new Object[]{Integer.toString(toCoroutine)})); //"Coroutine not available, id="+toCoroutine);
// We expect these values to be overwritten during the notify()/wait()
// periods, as other coroutines in this set get their opportunity to run.
m_yield=arg_object;
m_nextCoroutine=toCoroutine;
notify();
while(m_nextCoroutine != thisCoroutine || m_nextCoroutine==ANYBODY || m_nextCoroutine==NOBODY)
{
try
{
// System.out.println("waiting...");
wait();
}
catch(java.lang.InterruptedException e)
{
// %TBD% -- Declare? Encapsulate? Ignore? Or
// dance deasil about the program counter?
}
}
if(m_nextCoroutine==NOBODY)
{
// Pass it along
co_exit(thisCoroutine);
// And inform this coroutine that its partners are Going Away
// %REVIEW% Should this throw/return something more useful?
throw new java.lang.NoSuchMethodException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COROUTINE_CO_EXIT, null)); //"CoroutineManager recieved co_exit() request");
}
return m_yield;
} |
java | public static CPSpecificationOption fetchByG_K(long groupId, String key,
boolean retrieveFromCache) {
return getPersistence().fetchByG_K(groupId, key, retrieveFromCache);
} |
python | def set_data(self, ids=None):
"""
Set the data for all specified measurements (all if None given).
"""
fun = lambda x: x.set_data()
self.apply(fun, ids=ids, applyto='measurement') |
java | void writeRpcException(final RpcException e, final HttpServletResponse resp)
throws IOException {
String message = e.getMessage() != null ? e.getMessage() : CLIENT_ERROR_MESSAGE;
resp.setStatus(e.getStatus());
resp.setContentType(TEXT_CONTENT_TYPE);
resp.getWriter().write(message);
} |
python | def add_letter_to_axis(ax, let, col, x, y, height):
"""Add 'let' with position x,y and height height to matplotlib axis 'ax'.
"""
if len(let) == 2:
colors = [col, "white"]
elif len(let) == 1:
colors = [col]
else:
raise ValueError("3 or more Polygons are not supported")
for polygon, color in zip(let, colors):
new_polygon = affinity.scale(
polygon, yfact=height, origin=(0, 0, 0))
new_polygon = affinity.translate(
new_polygon, xoff=x, yoff=y)
patch = PolygonPatch(
new_polygon, edgecolor=color, facecolor=color)
ax.add_patch(patch)
return |
java | private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {
// parseAndResolve should only be providing expressions with no leading or trailing chars
assert unresolvedString.startsWith("${") && unresolvedString.endsWith("}");
// Default result is no change from input
String result = unresolvedString;
ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));
// Try plug-in resolution; i.e. vault
resolvePluggableExpression(resolveNode);
if (resolveNode.getType() == ModelType.EXPRESSION ) {
// resolvePluggableExpression did nothing. Try standard resolution
String resolvedString = resolveStandardExpression(resolveNode);
if (!unresolvedString.equals(resolvedString)) {
// resolveStandardExpression made progress
result = resolvedString;
} // else there is nothing more we can do with this string
} else {
// resolvePluggableExpression made progress
result = resolveNode.asString();
}
return result;
} |
python | def close_connection(self):
"""
Close connection kept by :meth:`connection`.
If commit is needed, :meth:`sqlite3.Connection.commit`
is called first and then :meth:`sqlite3.Connection.interrupt`
is called.
A few methods/generators support :meth:`close_connection`:
- :meth:`search_command_record`
- :meth:`select_by_command_record`
"""
if self._db:
db = self._db
try:
if self._need_commit:
db.commit()
finally:
db.interrupt()
self._db = None
self._need_commit = False |
java | public static Predicate[] acceptVisitor(Predicate[] predicates, Visitor visitor, Indexes indexes) {
Predicate[] target = predicates;
boolean copyCreated = false;
for (int i = 0; i < predicates.length; i++) {
Predicate predicate = predicates[i];
if (predicate instanceof VisitablePredicate) {
Predicate transformed = ((VisitablePredicate) predicate).accept(visitor, indexes);
if (transformed != predicate) {
if (!copyCreated) {
copyCreated = true;
target = createCopy(target);
}
target[i] = transformed;
}
}
}
return target;
} |
java | public CachedInstanceQuery getCachedQuery4Request()
{
if (this.query == null) {
try {
this.query = CachedInstanceQuery.get4Request(this.typeUUID)
.setIncludeChildTypes(isIncludeChildTypes())
.setCompanyDependent(isCompanyDependent());
prepareQuery();
} catch (final EFapsException e) {
QueryBuilder.LOG.error("Could not open InstanceQuery for uuid: {}", this.typeUUID);
}
}
return (CachedInstanceQuery) this.query;
} |
python | def _registered(self):
"""
A optional boolean property indidcating whether this job store is registered. The
registry is the authority on deciding if a job store exists or not. If True, this job
store exists, if None the job store is transitioning from True to False or vice versa,
if False the job store doesn't exist.
:type: bool|None
"""
# The weird mapping of the SDB item attribute value to the property value is due to
# backwards compatibility. 'True' becomes True, that's easy. Toil < 3.3.0 writes this at
# the end of job store creation. Absence of either the registry, the item or the
# attribute becomes False, representing a truly absent, non-existing job store. An
# attribute value of 'False', which is what Toil < 3.3.0 writes at the *beginning* of job
# store destruction, indicates a job store in transition, reflecting the fact that 3.3.0
# may leak buckets or domains even though the registry reports 'False' for them. We
# can't handle job stores that were partially created by 3.3.0, though.
registry_domain = self._bindDomain(domain_name='toil-registry',
create=False,
block=False)
if registry_domain is None:
return False
else:
for attempt in retry_sdb():
with attempt:
attributes = registry_domain.get_attributes(item_name=self.namePrefix,
attribute_name='exists',
consistent_read=True)
try:
exists = attributes['exists']
except KeyError:
return False
else:
if exists == 'True':
return True
elif exists == 'False':
return None
else:
assert False |
python | def setup(self, bitdepth=16):
"""Set the client format parameters, specifying the desired PCM
audio data format to be read from the file. Must be called
before reading from the file.
"""
fmt = self.get_file_format()
newfmt = copy.copy(fmt)
newfmt.mFormatID = AUDIO_ID_PCM
newfmt.mFormatFlags = \
PCM_IS_SIGNED_INT | PCM_IS_PACKED
newfmt.mBitsPerChannel = bitdepth
newfmt.mBytesPerPacket = \
(fmt.mChannelsPerFrame * newfmt.mBitsPerChannel // 8)
newfmt.mFramesPerPacket = 1
newfmt.mBytesPerFrame = newfmt.mBytesPerPacket
self.set_client_format(newfmt) |
java | @Override
public void setXYZ(int index, Point3D pt) {
if (index < 0 || index >= getPointCount())
throw new IndexOutOfBoundsException();
addAttribute(Semantics.Z);
_verifyAllStreams();
notifyModified(DirtyFlags.DirtyCoordinates);
AttributeStreamOfDbl v = (AttributeStreamOfDbl) m_vertexAttributes[0];
v.write(index * 2, pt.x);
v.write(index * 2 + 1, pt.y);
m_vertexAttributes[1].writeAsDbl(index, pt.z);
} |
python | def get_degradations(self):
"""Extract Degradation INDRA Statements."""
deg_events = self.tree.findall("EVENT/[type='ONT::CONSUME']")
for event in deg_events:
if event.attrib['id'] in self._static_events:
continue
affected = event.find(".//*[@role=':AFFECTED']")
if affected is None:
msg = 'Skipping degradation event with no affected term.'
logger.debug(msg)
continue
# Make sure the degradation is affecting a molecule type
# Temporarily removed for CwC compatibility with no type tag
#affected_type = affected.find('type')
#if affected_type is None or \
# affected_type.text not in molecule_types:
# continue
affected_id = affected.attrib.get('id')
if affected_id is None:
logger.debug(
'Skipping degradation event with missing affected agent')
continue
affected_agent = self._get_agent_by_id(affected_id,
event.attrib['id'])
if affected_agent is None:
logger.debug(
'Skipping degradation event with missing affected agent')
continue
agent = event.find(".//*[@role=':AGENT']")
if agent is None:
agent_agent = None
else:
agent_id = agent.attrib.get('id')
if agent_id is None:
agent_agent = None
else:
agent_agent = self._get_agent_by_id(agent_id,
event.attrib['id'])
ev = self._get_evidence(event)
location = self._get_event_location(event)
for subj, obj in \
_agent_list_product((agent_agent, affected_agent)):
st = DecreaseAmount(subj, obj, evidence=deepcopy(ev))
_stmt_location_to_agents(st, location)
self.statements.append(st)
self._add_extracted(_get_type(event), event.attrib['id']) |
python | def connect_login(self):
"""
Try to login to the Remote SSH Server.
:return: Response text on successful login
:raise: `AuthenticationFailed` on unsuccessful login
"""
self.client.connect(self.options['server'], self.options['port'], self.options['username'],
self.options['password'])
self.comm_chan = self.client.invoke_shell()
time.sleep(1) # Let the server take some time to get ready.
while not self.comm_chan.recv_ready():
time.sleep(0.5)
login_response = self.comm_chan.recv(2048)
if not login_response.endswith('$ '):
raise AuthenticationFailed
return login_response |
java | public boolean endsWith(CharSequence suffix) {
int suffixLen = suffix.length();
return regionMatches(length() - suffixLen, suffix, 0, suffixLen);
} |
python | def browse(self):
"""
Save response in temporary file and open it in GUI browser.
"""
_, path = tempfile.mkstemp()
self.save(path)
webbrowser.open('file://' + path) |
python | def ipython_only(option):
"""Mark that an option should only be exposed in IPython.
Parameters
----------
option : decorator
A click.option decorator.
Returns
-------
ipython_only_dec : decorator
A decorator that correctly applies the argument even when not
using IPython mode.
"""
if __IPYTHON__:
return option
argname = extract_option_object(option).name
def d(f):
@wraps(f)
def _(*args, **kwargs):
kwargs[argname] = None
return f(*args, **kwargs)
return _
return d |
python | def build_sort():
'''Build sort query paramter from kwargs'''
sorts = request.args.getlist('sort')
sorts = [sorts] if isinstance(sorts, basestring) else sorts
sorts = [s.split(' ') for s in sorts]
return [{SORTS[s]: d} for s, d in sorts if s in SORTS] |
python | def list(self, limit=None, offset=None):
"""Gets a list of all domains, or optionally a page of domains."""
uri = "/%s%s" % (self.uri_base, self._get_pagination_qs(limit, offset))
return self._list(uri) |
java | public String getIconUrl() {
if (FullTextLink_Type.featOkTst && ((FullTextLink_Type)jcasType).casFeat_iconUrl == null)
jcasType.jcas.throwFeatMissing("iconUrl", "de.julielab.jules.types.FullTextLink");
return jcasType.ll_cas.ll_getStringValue(addr, ((FullTextLink_Type)jcasType).casFeatCode_iconUrl);} |
python | def add(self, word):
"""
添加敏感词方法(设置敏感词后,App 中用户不会收到含有敏感词的消息内容,默认最多设置 50 个敏感词。) 方法
@param word:敏感词,最长不超过 32 个字符。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut",
"desc": " http 成功返回结果",
"fields": [{
"name": "code",
"type": "Integer",
"desc": "返回码,200 为正常。"
}, {
"name": "errorMessage",
"type": "String",
"desc": "错误信息。"
}]
}
r = self.call_api(
method=('API', 'POST', 'application/x-www-form-urlencoded'),
action='/wordfilter/add.json',
params={"word": word})
return Response(r, desc) |
java | protected void appendCopiesAfter(PointableRoaringArray highLowContainer, short beforeStart) {
int startLocation = highLowContainer.getIndex(beforeStart);
if (startLocation >= 0) {
startLocation++;
} else {
startLocation = -startLocation - 1;
}
extendArray(highLowContainer.size() - startLocation);
for (int i = startLocation; i < highLowContainer.size(); ++i) {
this.keys[this.size] = highLowContainer.getKeyAtIndex(i);
this.values[this.size] = highLowContainer.getContainerAtIndex(i).clone();
this.size++;
}
} |
python | def section_end_distances(neurites, neurite_type=NeuriteType.all):
'''section end to end distances in a collection of neurites'''
return map_sections(sectionfunc.section_end_distance, neurites, neurite_type=neurite_type) |
java | public M moveUp(int amount)
{
Checks.notNegative(amount, "Provided amount");
if (selectedPosition == -1)
throw new IllegalStateException("Cannot move until an item has been selected. Use #selectPosition first.");
if (ascendingOrder)
{
Checks.check(selectedPosition - amount >= 0,
"Amount provided to move up is too large and would be out of bounds." +
"Selected position: " + selectedPosition + " Amount: " + amount + " Largest Position: " + orderList.size());
}
else
{
Checks.check(selectedPosition + amount < orderList.size(),
"Amount provided to move up is too large and would be out of bounds." +
"Selected position: " + selectedPosition + " Amount: " + amount + " Largest Position: " + orderList.size());
}
if (ascendingOrder)
return moveTo(selectedPosition - amount);
else
return moveTo(selectedPosition + amount);
} |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case XtextPackage.PARSER_RULE__DEFINES_HIDDEN_TOKENS:
setDefinesHiddenTokens((Boolean)newValue);
return;
case XtextPackage.PARSER_RULE__HIDDEN_TOKENS:
getHiddenTokens().clear();
getHiddenTokens().addAll((Collection<? extends AbstractRule>)newValue);
return;
case XtextPackage.PARSER_RULE__PARAMETERS:
getParameters().clear();
getParameters().addAll((Collection<? extends Parameter>)newValue);
return;
case XtextPackage.PARSER_RULE__FRAGMENT:
setFragment((Boolean)newValue);
return;
case XtextPackage.PARSER_RULE__WILDCARD:
setWildcard((Boolean)newValue);
return;
}
super.eSet(featureID, newValue);
} |
java | private void dfs(Visitor visitor, int v, int[] cc, int id) {
visitor.visit(v);
cc[v] = id;
for (int t = 0; t < n; t++) {
if (graph[v][t] != 0.0) {
if (cc[t] == -1) {
dfs(visitor, t, cc, id);
}
}
}
} |
python | def open(self, hostname, port=22, username=None, password=None,
private_key=None, key_passphrase=None,
allow_agent=False, timeout=None):
""" Open a connection to a remote SSH server
In order to connect, either one of these credentials must be
supplied:
* Password
Password-based authentication
* Private Key
Authenticate using SSH Keys.
If the private key is encrypted, it will attempt to
load it using the passphrase
* Agent
Authenticate using the *local* SSH agent. This is the
one running alongside wsshd on the server side.
"""
try:
pkey = None
if private_key:
pkey = self._load_private_key(private_key, key_passphrase)
self._ssh.connect(
hostname=hostname,
port=port,
username=username,
password=password,
pkey=pkey,
timeout=timeout,
allow_agent=allow_agent,
look_for_keys=False)
except socket.gaierror as e:
self._websocket.send(json.dumps({'error':
'Could not resolve hostname {0}: {1}'.format(
hostname, e.args[1])}))
raise
except Exception as e:
self._websocket.send(json.dumps({'error': e.message or str(e)}))
raise |
python | def sort_shells(shells, use_copy=True):
"""
Sort a list of basis set shells into a standard order
The order within a shell is by decreasing value of the exponent.
The order of the shell list is in increasing angular momentum, and then
by decreasing number of primitives, then decreasing value of the largest exponent.
If use_copy is True, the input shells are not modified.
"""
if use_copy:
shells = copy.deepcopy(shells)
# Sort primitives within a shell
# (copying already handled above)
shells = [sort_shell(sh, False) for sh in shells]
# Sort the list by increasing AM, then general contraction level, then decreasing highest exponent
return list(
sorted(
shells,
key=lambda x: (max(x['angular_momentum']), -len(x['exponents']), -len(x['coefficients']), -float(
max(x['exponents']))))) |
java | public static File ensureParentDir(File file) {
if (file != null && !file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) {
throw new IllegalStateException("Can't create directory \"" + file.getParent() + "\".");
}
return file;
} |
java | public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
return Collections.min(coll);
} |
python | def update_association(assc_gene2gos, go2obj):
"""Add the GO parents of a gene's associated GO IDs to the gene's association."""
# Replaces update_association in GODag
goids_avail = set(go2obj)
# Get all assc GO IDs that are current
goid_sets = assc_gene2gos.values()
goids_assoc_all = set.union(*goid_sets)
goids_assoc_cur = goids_assoc_all.intersection(goids_avail)
# Get the subset of GO objects in the association
go2obj_assc = {go:go2obj[go] for go in goids_assoc_cur}
go2parents = get_go2parents_go2obj(go2obj_assc)
# Update the association: update the GO set for each gene
for goids_cur in goid_sets:
parents = set()
for goid in goids_cur.intersection(goids_avail):
parents.update(go2parents[goid])
goids_cur.update(parents)
goids_bad = goids_assoc_all.difference(goids_avail)
if goids_bad:
sys.stderr.write("{N} GO IDs NOT FOUND IN ASSOCIATION: {GOs}\n".format(
N=len(goids_bad), GOs=" ".join(goids_bad))) |
java | public static StreamDecoder forDecoder(ReadableByteChannel ch,
CharsetDecoder dec,
int minBufferCap)
{
return new StreamDecoder(ch, dec, minBufferCap);
} |
python | def get_platform_info():
"""Gets platform info
:return: platform info
"""
try:
system_name = platform.system()
release_name = platform.release()
except:
system_name = "Unknown"
release_name = "Unknown"
return {
'system': system_name,
'release': release_name,
} |
java | public static List<Instance> getAllInstances( AbstractApplication application ) {
List<Instance> result = new ArrayList<> ();
for( Instance instance : application.getRootInstances())
result.addAll( InstanceHelpers.buildHierarchicalList( instance ));
return result;
} |
java | public void set_attribute_info(final DeviceProxy deviceProxy, final AttributeInfoEx[] attr)
throws DevFailed {
checkIfTango(deviceProxy, "set_attribute_config");
build_connection(deviceProxy);
if (deviceProxy.access == TangoConst.ACCESS_READ) {
throwNotAuthorizedException(deviceProxy.devname +
".set_attribute_info()", "DeviceProxy.set_attribute_info()");
}
try {
if (deviceProxy.device_5 != null) {
final AttributeConfig_5[] config = new AttributeConfig_5[attr.length];
for (int i = 0; i < attr.length; i++) {
config[i] = attr[i].get_attribute_config_obj_5();
}
deviceProxy.device_5.set_attribute_config_5(config,
DevLockManager.getInstance().getClntIdent());
}
else if (deviceProxy.device_4 != null) {
final AttributeConfig_3[] config = new AttributeConfig_3[attr.length];
for (int i = 0; i < attr.length; i++) {
config[i] = attr[i].get_attribute_config_obj_3();
}
deviceProxy.device_4.set_attribute_config_4(config,
DevLockManager.getInstance().getClntIdent());
}
else if (deviceProxy.device_3 != null) {
final AttributeConfig_3[] config = new AttributeConfig_3[attr.length];
for (int i = 0; i < attr.length; i++) {
config[i] = attr[i].get_attribute_config_obj_3();
}
deviceProxy.device_3.set_attribute_config_3(config);
}
else {
final AttributeConfig[] config = new AttributeConfig[attr.length];
for (int i = 0; i < attr.length; i++) {
config[i] = attr[i].get_attribute_config_obj();
}
deviceProxy.device.set_attribute_config(config);
}
} catch (final DevFailed e) {
throw e;
} catch (final Exception e) {
ApiUtilDAODefaultImpl.removePendingRepliesOfDevice(deviceProxy);
throw_dev_failed(deviceProxy, e, "set_attribute_info", true);
}
} |
python | def sorts_query(sortables):
""" Turn the Sortables into a SQL ORDER BY query """
stmts = []
for sortable in sortables:
if sortable.desc:
stmts.append('{} DESC'.format(sortable.field))
else:
stmts.append('{} ASC'.format(sortable.field))
return ' ORDER BY {}'.format(', '.join(stmts)) |
python | def setChanged(self,value=1):
"""Set changed flag"""
# set through dictionary to avoid another call to __setattr__
if value:
self.__dict__['flags'] = self.flags | _changedFlag
else:
self.__dict__['flags'] = self.flags & ~_changedFlag |
java | public void setBccAddresses(java.util.Collection<String> bccAddresses) {
if (bccAddresses == null) {
this.bccAddresses = null;
return;
}
this.bccAddresses = new java.util.ArrayList<String>(bccAddresses);
} |
python | def url(self, **urlargs):
'''Build a ``url`` from ``urlargs`` key-value parameters
'''
if self.defaults:
d = self.defaults.copy()
d.update(urlargs)
urlargs = d
url = '/'.join(self._url_generator(urlargs))
if not url:
return '/'
else:
url = '/' + url
return url if self.is_leaf else url + '/' |
java | public Matrix4d scale(Vector3dc xyz, Matrix4d dest) {
return scale(xyz.x(), xyz.y(), xyz.z(), dest);
} |
java | protected void processThreadPoolExecutor(
final Metrics metrics,
final String name,
final ThreadPoolExecutor executorService) {
final String prefix = String.join(
"/",
ROOT_NAMESPACE,
name);
metrics.setGauge(
String.join(
"/",
prefix,
"active_threads"),
executorService.getActiveCount());
metrics.setGauge(
String.join(
"/",
prefix,
"queued_tasks"),
executorService.getQueue().size());
metrics.setGauge(
String.join(
"/",
prefix,
"completed_tasks"),
executorService.getCompletedTaskCount());
metrics.setGauge(
String.join(
"/",
prefix,
"thread_pool_maximum_size"),
executorService.getMaximumPoolSize());
metrics.setGauge(
String.join(
"/",
prefix,
"thread_pool_size"),
executorService.getPoolSize());
} |
java | public void setImageDetails(java.util.Collection<ImageDetail> imageDetails) {
if (imageDetails == null) {
this.imageDetails = null;
return;
}
this.imageDetails = new java.util.ArrayList<ImageDetail>(imageDetails);
} |
python | def glimpse(self, *tags, compact = False):
"""Creates a printable table with the most frequently occurring values of each of the requested _tags_, or if none are provided the top authors, journals and citations. The table will be as wide and as tall as the terminal (or 80x24 if there is no terminal) so `print(RC.glimpse())`should always create a nice looking table. Below is a table created from some of the testing files:
```
>>> print(RC.glimpse())
+RecordCollection glimpse made at: 2016-01-01 12:00:00++++++++++++++++++++++++++
|33 Records from testFile++++++++++++++++++++++++++++++++++++++++++++++++++++++|
|Columns are ranked by num. of occurrences and are independent of one another++|
|-------Top Authors--------+------Top Journals-------+--------Top Cited--------|
|1 Girard, S|1 CANADIAN JOURNAL OF PH.|1 LEVY Y, 1975, OPT COMM.|
|1 Gilles, H|1 JOURNAL OF THE OPTICAL.|2 GOOS F, 1947, ANN PHYS.|
|2 IMBERT, C|2 APPLIED OPTICS|3 LOTSCH HKV, 1970, OPTI.|
|2 Pillon, F|2 OPTICS COMMUNICATIONS|4 RENARD RH, 1964, J OPT.|
|3 BEAUREGARD, OCD|2 NUOVO CIMENTO DELLA SO.|5 IMBERT C, 1972, PHYS R.|
|3 Laroche, M|2 JOURNAL OF THE OPTICAL.|6 ARTMANN K, 1948, ANN P.|
|3 HUARD, S|2 JOURNAL OF THE OPTICAL.|6 COSTADEB.O, 1973, PHYS.|
|4 PURI, A|2 NOUVELLE REVUE D OPTIQ.|6 ROOSEN G, 1973, CR ACA.|
|4 COSTADEB.O|3 PHYSICS REPORTS-REVIEW.|7 Imbert C., 1972, Nouve.|
|4 PATTANAYAK, DN|3 PHYSICAL REVIEW LETTERS|8 HOROWITZ BR, 1971, J O.|
|4 Gazibegovic, A|3 USPEKHI FIZICHESKIKH N.|8 BRETENAKER F, 1992, PH.|
|4 ROOSEN, G|3 APPLIED PHYSICS B-LASE.|8 SCHILLIN.H, 1965, ANN .|
|4 BIRMAN, JL|3 AEU-INTERNATIONAL JOUR.|8 FEDOROV FI, 1955, DOKL.|
|4 Kaiser, R|3 COMPTES RENDUS HEBDOMA.|8 MAZET A, 1971, CR ACAD.|
|5 LEVY, Y|3 CHINESE PHYSICS LETTERS|9 IMBERT C, 1972, CR ACA.|
|5 BEAUREGA.OC|3 PHYSICAL REVIEW B|9 LOTSCH HKV, 1971, OPTI.|
|5 PAVLOV, VI|3 LETTERE AL NUOVO CIMEN.|9 ASHBY N, 1973, PHYS RE.|
|5 BREVIK, I|3 PROGRESS IN QUANTUM EL.|9 BOULWARE DG, 1973, PHY.|
>>>
```
# Parameters
_tags_ : `str, str, ...`
> Any number of tag strings to be made into columns in the output table
# Returns
`str`
> A string containing the table
"""
return _glimpse(self, *tags, compact = compact) |
java | protected void handleAppendRequestFailure(MemberState member, AppendRequest request, Throwable error) {
// Log the failed attempt to contact the member.
failAttempt(member, error);
} |
java | public static byte[] getNTLMv2Response(String target, String user,
String password, byte[] targetInformation, byte[] challenge,
byte[] clientNonce, long time) throws Exception {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
byte[] blob = createBlob(targetInformation, clientNonce, time);
return lmv2Response(ntlmv2Hash, blob, challenge);
} |
python | def publish_twitter(twitter_contact, owner):
""" Publish in twitter the dashboard """
dashboard_url = CAULDRON_DASH_URL + "/%s" % (owner)
tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" \
% (twitter_contact, owner, dashboard_url)
status = quote_plus(tweet)
oauth = get_oauth()
r = requests.post(url="https://api.twitter.com/1.1/statuses/update.json?status=" + status, auth=oauth) |
java | void insertInputGate(final int pos, final ExecutionGate inputGate) {
if (this.inputGates[pos] != null) {
throw new IllegalStateException("Input gate at position " + pos + " is not null");
}
this.inputGates[pos] = inputGate;
} |
java | public Observable<ManagedDatabaseInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).map(new Func1<ServiceResponse<ManagedDatabaseInner>, ManagedDatabaseInner>() {
@Override
public ManagedDatabaseInner call(ServiceResponse<ManagedDatabaseInner> response) {
return response.body();
}
});
} |
python | def save_bd5(
space, filename,
group_index=0, object_name="molecule", spatial_unit="meter", time_unit="second",
trunc=False, with_radius=False):
"""Save a space in the BDML-BD5 format (https://github.com/openssbd/BDML-BD5).
Open file for read/write, if it already exists, and create a new file, otherwise.
If trunc is True, always create a new file.
A new group named `group_name` is created. If the group already exists, returns
an exception.
Parameters
----------
space : Space, str, pathlib.PurePath, list, tuple or set
A Space or World to be saved. If str or pathlib.PurePath is given, a space is
loaded from the given path. If this is an iterable (list, tuple, set), apply
this function to each element of the given.
filename : str
A HDF5 filename.
group_index : int, optional
An index of the group written (0, 1, ..., n). Defaults to 0.
object_name : str, optional
A name of the object. Its length must be less than 128. Defaults to "molecule".
spatial_unit : str, optional
An unit of the length scale. Its length must be less than 16. Defaults to "meter".
time_unit : str, optional
An unit of the time scale. Its length must be less than 16. Defaults to "second".
trunc : bool, optional
Whether truncate file or not. If True, always overwrite the file when open it.
Defaults to False.
with_radius : bool, optional
Whether save the radius of particles. If True, particles are saved as 'sphere',
otherwise, as 'point'. Defaults to False.
"""
if isinstance(space, (list, tuple, set)):
for i, space_ in enumerate(space):
assert not isinstance(space_, (list, tuple, set))
save_bd5(
space_, filename, group_index + i, object_name, spatial_unit, time_unit,
trunc if i == 0 else False, with_radius)
elif isinstance(space, str):
save_bd5(load_world(space), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius)
elif isinstance(space, pathlib.PurePath):
save_bd5(str(space), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius)
else:
# space is expected to be either Space or World.
_save_bd5(space.as_base(), filename, group_index, object_name, spatial_unit, time_unit, trunc, with_radius) |
java | public ArrayList<DensityGrid> getNeighbours()
{
ArrayList<DensityGrid> neighbours = new ArrayList<DensityGrid>();
DensityGrid h;
int[] hCoord = this.getCoordinates();
for (int i = 0 ; i < this.dimensions ; i++)
{
hCoord[i] = hCoord[i]-1;
h = new DensityGrid(hCoord);
neighbours.add(h);
hCoord[i] = hCoord[i]+2;
h = new DensityGrid(hCoord);
neighbours.add(h);
hCoord[i] = hCoord[i]-1;
}
return neighbours;
} |
java | public double optDouble(int index, double fallback) {
Object object = opt(index);
Double result = JSON.toDouble(object);
return result != null ? result : fallback;
} |
java | private void createDataset(String datasetId, @Nullable String location)
throws IOException, InterruptedException {
Dataset dataset = new Dataset();
DatasetReference reference = new DatasetReference();
reference.setProjectId(projectId);
reference.setDatasetId(datasetId);
dataset.setDatasetReference(reference);
if (location != null) {
dataset.setLocation(location);
}
executeWithBackOff(
client.datasets().insert(projectId, dataset),
String.format(
"Error when trying to create the temporary dataset %s in project %s.",
datasetId, projectId));
} |
python | def will_print(level=1):
"""Returns True if the current global status of messaging would print a
message using any of the printing functions in this module.
"""
if level == 1:
#We only affect printability using the quiet setting.
return quiet is None or quiet == False
else:
return ((isinstance(verbosity, int) and level <= verbosity) or
(isinstance(verbosity, bool) and verbosity == True)) |
python | def delete_network(self, network):
'''
Deletes the specified network
'''
net_id = self._find_network_id(network)
ret = self.network_conn.delete_network(network=net_id)
return ret if ret else True |
python | def all(cls, api_key=None, idempotency_key=None,
stripe_account=None, **params):
"""Return a deferred."""
url = cls.class_url()
return make_request(
cls, 'get', url, stripe_acconut=None, params=params) |
java | public static final byte selectRandom(frequency[] a) {
int len = a.length;
double r = random(1.0);
for (int i = 0; i < len; i++)
if (r < a[i].p)
return a[i].c;
return a[len - 1].c;
} |
python | def get_project(self, project_id):
""" Get project info """
try:
result = self._request('/getproject/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] |
python | def get_pfam_details(self, pfam_accession):
'''Returns a dict pdb_id -> chain(s) -> chain and SCOPe details.'''
results = self.execute_select('''
SELECT DISTINCT scop_node.*, scop_node.release_id AS scop_node_release_id,
pfam.release_id AS pfam_release_id, pfam.name AS pfam_name, pfam.accession, pfam.description AS pfam_description, pfam.length AS pfam_length,
pfam_type.description AS pfam_type_description
FROM `link_pfam`
INNER JOIN scop_node on node_id=scop_node.id
INNER JOIN pfam ON link_pfam.pfam_accession = pfam.accession
INNER JOIN pfam_type ON pfam.pfam_type_id = pfam_type.id
WHERE pfam.accession=%s ORDER BY scop_node.release_id DESC''', parameters = (pfam_accession,))
if not results:
return None
# Only consider the most recent Pfam releases and most recent SCOPe records, giving priority to SCOPe revisions over Pfam revisions
most_recent_record = None
for r in results:
accession = r['accession']
if (not most_recent_record) or (r['scop_node_release_id'] > most_recent_record['scop_node_release_id']):
most_recent_record = r
elif r['pfam_release_id'] > most_recent_record['pfam_release_id']:
most_recent_record = r
d = dict(
pfam_accession = most_recent_record['accession'],
pfam_name = most_recent_record['pfam_name'],
pfam_description = most_recent_record['pfam_description'],
pfam_type_description = most_recent_record['pfam_type_description'],
pfam_length = most_recent_record['pfam_length'],
pfam_release_id = most_recent_record['pfam_release_id'],
sunid = most_recent_record['sunid'],
sccs = most_recent_record['sccs'],
sid = most_recent_record['sid'],
scop_release_id = most_recent_record['scop_node_release_id'],
SCOPe_sources = 'SCOPe',
SCOPe_search_fields = 'link_pfam.pfam_accession',
SCOPe_trust_level = 1
)
for k, v in sorted(self.levels.iteritems()):
d[v] = None
level, parent_node_id = most_recent_record['level_id'], most_recent_record['parent_node_id']
# Store the top-level description
d[self.levels[level]] = most_recent_record['description']
# Wind up the level hierarchy and retrieve the descriptions
c = 0
while level > 2 :
parent_details = self.execute_select('SELECT * FROM scop_node WHERE id=%s', parameters = (parent_node_id,))
assert(len(parent_details) <= 1)
if parent_details:
parent_details = parent_details[0]
level, parent_node_id = parent_details['level_id'], parent_details['parent_node_id']
d[self.levels[level]] = parent_details['description']
else:
break
# This should never trigger but just in case...
c += 1
if c > 20:
raise Exception('There is a logical error in the script or database which may result in an infinite lookup loop.')
assert(d['Protein'] == d['Species'] == d['PDB Entry Domain'] == None)
return d |
python | def create_missing(self):
"""Conditionally mark ``docker_upstream_name`` as required.
Mark ``docker_upstream_name`` as required if ``content_type`` is
"docker".
"""
if getattr(self, 'content_type', '') == 'docker':
self._fields['docker_upstream_name'].required = True
super(Repository, self).create_missing() |
java | private LocatedBlock getBlockAt(long offset, boolean updatePosition,
boolean throwWhenNotFound)
throws IOException {
assert (locatedBlocks != null) : "locatedBlocks is null";
// search cached blocks first
locatedBlocks.blockLocationInfoExpiresIfNeeded();
LocatedBlock blk = locatedBlocks.getBlockContainingOffset(offset);
if (blk == null) { // block is not cached
// fetch more blocks
LocatedBlocks newBlocks;
newBlocks = getLocatedBlocks(src, offset, prefetchSize);
if (newBlocks == null) {
if (!throwWhenNotFound) {
return null;
}
throw new IOException("Could not find target position " + offset);
}
locatedBlocks.insertRange(newBlocks.getLocatedBlocks());
locatedBlocks.setFileLength(newBlocks.getFileLength());
}
blk = locatedBlocks.getBlockContainingOffset(offset);
if (blk == null) {
if (!throwWhenNotFound) {
return null;
}
throw new IOException("Failed to determine location for block at "
+ "offset=" + offset);
}
if (updatePosition) {
// update current position
this.pos = offset;
this.blockEnd = blk.getStartOffset() + blk.getBlockSize() - 1;
this.currentBlock = blk.getBlock();
isCurrentBlockUnderConstruction = locatedBlocks
.isUnderConstructionBlock(this.currentBlock);
}
return blk;
} |
python | def media_type_matches(lhs, rhs):
"""
Returns ``True`` if the media type in the first argument <= the
media type in the second argument. The media types are strings
as described by the HTTP spec.
Valid media type strings include:
'application/json; indent=4'
'application/json'
'text/*'
'*/*'
"""
lhs = _MediaType(lhs)
rhs = _MediaType(rhs)
return lhs.match(rhs) |
java | public <TAbstract, TImplementation extends TAbstract> InjectorConfiguration withScopedAlias(
Class scope,
Class<TAbstract> abstractDefinition,
Class<TImplementation> implementationDefinition
) {
if (abstractDefinition.equals(Injector.class)) {
throw new DependencyInjectionFailedException("Cowardly refusing to define a global alias for Injector since that would lead to a Service Locator pattern. If you need the injector, please define it on a per-class or per-method basis.");
}
//noinspection unchecked
return new InjectorConfiguration(
scopes, definedClasses,
factories,
factoryClasses,
sharedClasses,
sharedInstances,
aliases.withModified(scope, (value) -> value.with(abstractDefinition, implementationDefinition)),
collectedAliases,
namedParameterValues
);
} |
python | def K_globe_stop_check_valve_Crane(D1, D2, fd=None, style=0):
r'''Returns the loss coefficient for a globe stop check valve as shown in
[1]_.
If β = 1:
.. math::
K = K_1 = K_2 = N\cdot f_d
Otherwise:
.. math::
K_2 = \frac{K + \left[0.5(1-\beta^2) + (1-\beta^2)^2\right]}{\beta^4}
Style 0 is the standard form; style 1 is angled, with a restrition to force
the flow up through the valve; style 2 is also angled but with a smaller
restriction forcing the flow up. N is 400, 300, and 55 for those cases
respectively.
Parameters
----------
D1 : float
Diameter of the valve seat bore (must be smaller or equal to `D2`), [m]
D2 : float
Diameter of the pipe attached to the valve, [m]
fd : float, optional
Darcy friction factor calculated for the actual pipe flow in clean
steel (roughness = 0.0018 inch) in the fully developed turbulent
region; do not specify this to use the original Crane friction factor!,
[-]
style : int, optional
One of 0, 1, or 2; refers to three different types of angle valves
as shown in [1]_ [-]
Returns
-------
K : float
Loss coefficient with respect to the pipe inside diameter [-]
Notes
-----
This method is not valid in the laminar regime and the pressure drop will
be underestimated in those conditions.
Examples
--------
>>> K_globe_stop_check_valve_Crane(.1, .02, style=1)
4.5235076518969795
References
----------
.. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
2009.
'''
if fd is None:
fd = ft_Crane(D2)
try:
K = globe_stop_check_valve_Crane_coeffs[style]*fd
except KeyError:
raise KeyError('Accepted valve styles are 0, 1, and 2 only')
beta = D1/D2
if beta == 1:
return K
else:
return (K + beta*(0.5*(1 - beta**2) + (1 - beta**2)**2))/beta**4 |
python | def distribute_payoff(self, match_set):
"""Distribute the payoff received in response to the selected
action of the given match set among the rules in the action set
which deserve credit for recommending the action. The match_set
argument is the MatchSet instance which suggested the selected
action and earned the payoff.
Usage:
match_set = model.match(situation)
match_set.select_action()
match_set.payoff = reward
model.algorithm.distribute_payoff(match_set)
Arguments:
match_set: A MatchSet instance for which the accumulated payoff
needs to be distributed among its classifier rules.
Return: None
"""
assert isinstance(match_set, MatchSet)
assert match_set.algorithm is self
assert match_set.selected_action is not None
payoff = float(match_set.payoff)
action_set = match_set[match_set.selected_action]
action_set_size = sum(rule.numerosity for rule in action_set)
# Update the average reward, error, and action set size of each
# rule participating in the action set.
for rule in action_set:
rule.experience += 1
update_rate = max(self.learning_rate, 1 / rule.experience)
rule.average_reward += (
(payoff - rule.average_reward) *
update_rate
)
rule.error += (
(abs(payoff - rule.average_reward) - rule.error) *
update_rate
)
rule.action_set_size += (
(action_set_size - rule.action_set_size) *
update_rate
)
# Update the fitness of the rules.
self._update_fitness(action_set)
# If the parameters so indicate, perform action set subsumption.
if self.do_action_set_subsumption:
self._action_set_subsumption(action_set) |
python | def print_periodic_table(filter_function: callable = None):
"""
A pretty ASCII printer for the periodic table, based on some
filter_function.
Args:
filter_function: A filtering function taking an Element as input
and returning a boolean. For example, setting
filter_function = lambda el: el.X > 2 will print a periodic
table containing only elements with electronegativity > 2.
"""
for row in range(1, 10):
rowstr = []
for group in range(1, 19):
try:
el = Element.from_row_and_group(row, group)
except ValueError:
el = None
if el and ((not filter_function) or filter_function(el)):
rowstr.append("{:3s}".format(el.symbol))
else:
rowstr.append(" ")
print(" ".join(rowstr)) |
python | def months_per_hour(self):
"""A list of tuples representing months per hour in this analysis period."""
month_hour = []
hour_range = xrange(self.st_hour, self.end_hour + 1)
for month in self.months_int:
month_hour.extend([(month, hr) for hr in hour_range])
return month_hour |
java | public Symbol resolveIdent(String name) {
if (name.equals(""))
return syms.errSymbol;
JavaFileObject prev = log.useSource(null);
try {
JCExpression tree = null;
for (String s : name.split("\\.", -1)) {
if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords
return syms.errSymbol;
tree = (tree == null) ? make.Ident(names.fromString(s))
: make.Select(tree, names.fromString(s));
}
JCCompilationUnit toplevel =
make.TopLevel(List.<JCTree.JCAnnotation>nil(), null, List.<JCTree>nil());
toplevel.packge = syms.unnamedPackage;
return attr.attribIdent(tree, toplevel);
} finally {
log.useSource(prev);
}
} |
java | public Object checkRemoteException(Object objData) throws org.jbundle.model.RemoteException
{
if (objData instanceof RemoteException)
throw (RemoteException)objData;
return objData;
} |
java | @Override
public CPInstance findByG_NotST_First(long groupId, int status,
OrderByComparator<CPInstance> orderByComparator)
throws NoSuchCPInstanceException {
CPInstance cpInstance = fetchByG_NotST_First(groupId, status,
orderByComparator);
if (cpInstance != null) {
return cpInstance;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("groupId=");
msg.append(groupId);
msg.append(", status=");
msg.append(status);
msg.append("}");
throw new NoSuchCPInstanceException(msg.toString());
} |
python | def get(self, term):
# type: (Any) -> Type[ChomskyTermNonterminal]
"""
Get nonterminal rewritable to term.
If the rules is not in the grammar, nonterminal and rule rewritable to terminal are add into grammar.
:param term: Term for which get the nonterminal.
:return: ChomskyTermNonterminal class for terminal.
"""
if self._items[term].used is False:
cont = self._items[term]
self._grammar.nonterminals.add(cont.nonterminal)
self._grammar.rules.add(cont.rule)
cont.used = True
return self._items[term].nonterminal |
java | public static void toKMLPolygon(Polygon polygon, ExtrudeMode extrude, int altitudeModeEnum, StringBuilder sb) {
sb.append("<Polygon>");
appendExtrude(extrude, sb);
appendAltitudeMode(altitudeModeEnum, sb);
sb.append("<outerBoundaryIs>");
toKMLLinearRing(polygon.getExteriorRing(), extrude, altitudeModeEnum, sb);
sb.append("</outerBoundaryIs>");
for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
sb.append("<innerBoundaryIs>");
toKMLLinearRing(polygon.getInteriorRingN(i), extrude, altitudeModeEnum, sb);
sb.append("</innerBoundaryIs>");
}
sb.append("</Polygon>");
} |
python | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() |
python | def get_train_err(htfa, data, F):
"""Calcuate training error
Parameters
----------
htfa : HTFA
An instance of HTFA, factor anaysis class in BrainIAK.
data : 2D array
Input data to HTFA.
F : 2D array
HTFA factor matrix.
Returns
-------
float
Returns root mean squared error on training.
"""
W = htfa.get_weights(data, F)
return recon_err(data, F, W) |
java | public String escapeTableName(final String tableName) {
// step 1: to quote or no? how many single quotes?
boolean toQuote = false;
int apostropheCount = 0;
for (int i = 0; i < tableName.length(); i++) {
final char c = tableName.charAt(i);
if (Character.isWhitespace(c) || c == '.') {
toQuote = true;
} else if (c == '\'') {
toQuote = true;
apostropheCount += 1;
}
}
final StringBuilder sb = new StringBuilder(
tableName.length() + (toQuote ? 2 : 0) + apostropheCount);
// step 2: build the string
if (toQuote) {
sb.append(SINGLE_QUOTE);
}
for (int i = 0; i < tableName.length(); i++) {
final char c = tableName.charAt(i);
sb.append(c);
if (c == '\'') {
sb.append(SINGLE_QUOTE);
}
}
if (toQuote) {
sb.append(SINGLE_QUOTE);
}
return sb.toString();
} |
java | @Override
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == S6aSessionState.class ? (E) this.sessionData.getS6aSessionState() : null;
} |
java | public static PdfAction createImportData(String file) {
PdfAction action = new PdfAction();
action.put(PdfName.S, PdfName.IMPORTDATA);
action.put(PdfName.F, new PdfString(file));
return action;
} |
python | def convert_path_to_flask(path):
"""
Converts a Path from an Api Gateway defined path to one that is accepted by Flask
Examples:
'/id/{id}' => '/id/<id>'
'/{proxy+}' => '/<path:proxy>'
:param str path: Path to convert to Flask defined path
:return str: Path representing a Flask path
"""
proxy_sub_path = APIGW_TO_FLASK_REGEX.sub(FLASK_CAPTURE_ALL_PATH, path)
# Replace the '{' and '}' with '<' and '>' respectively
return proxy_sub_path.replace(LEFT_BRACKET, LEFT_ANGLE_BRACKET).replace(RIGHT_BRACKET, RIGHT_ANGLE_BRACKET) |
python | def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.nbr_of_sub_locations()
try:
return self._locations_list[lower_bound:real_upper_bound]
except:
return list() |
java | public void putInWakeUpQueue(SerialMessage serialMessage) {
if (this.wakeUpQueue.contains(serialMessage)) {
logger.debug("Message already on the wake-up queue for node {}. Discarding.", this.getNode().getNodeId());
return;
}
logger.debug("Putting message in wakeup queue for node {}.", this.getNode().getNodeId());
this.wakeUpQueue.add(serialMessage);
} |
java | private void findIntervals(JCas jcas) {
ArrayList<Timex3Interval> newAnnotations = new ArrayList<Timex3Interval>();
FSIterator iterTimex3 = jcas.getAnnotationIndex(Timex3.type).iterator();
while (iterTimex3.hasNext()) {
Timex3Interval annotation=new Timex3Interval(jcas);
Timex3 timex3 = (Timex3) iterTimex3.next();
//DATE Pattern
Pattern pDate = Pattern.compile("(?:BC)?(\\d\\d\\d\\d)(-(\\d+))?(-(\\d+))?(T(\\d+))?(:(\\d+))?(:(\\d+))?");
Pattern pCentury = Pattern.compile("(\\d\\d)");
Pattern pDecate = Pattern.compile("(\\d\\d\\d)");
Pattern pQuarter = Pattern.compile("(\\d+)-Q([1-4])");
Pattern pHalf = Pattern.compile("(\\d+)-H([1-2])");
Pattern pSeason = Pattern.compile("(\\d+)-(SP|SU|FA|WI)");
Pattern pWeek = Pattern.compile("(\\d+)-W(\\d+)");
Pattern pWeekend = Pattern.compile("(\\d+)-W(\\d+)-WE");
Pattern pTimeOfDay = Pattern.compile("(\\d+)-(\\d+)-(\\d+)T(AF|DT|MI|MO|EV|NI)");
Matcher mDate = pDate.matcher(timex3.getTimexValue());
Matcher mCentury= pCentury.matcher(timex3.getTimexValue());
Matcher mDecade = pDecate.matcher(timex3.getTimexValue());
Matcher mQuarter= pQuarter.matcher(timex3.getTimexValue());
Matcher mHalf = pHalf.matcher(timex3.getTimexValue());
Matcher mSeason = pSeason.matcher(timex3.getTimexValue());
Matcher mWeek = pWeek.matcher(timex3.getTimexValue());
Matcher mWeekend= pWeekend.matcher(timex3.getTimexValue());
Matcher mTimeOfDay= pTimeOfDay.matcher(timex3.getTimexValue());
boolean matchesDate=mDate.matches();
boolean matchesCentury=mCentury.matches();
boolean matchesDecade=mDecade.matches();
boolean matchesQuarter=mQuarter.matches();
boolean matchesHalf=mHalf.matches();
boolean matchesSeason=mSeason.matches();
boolean matchesWeek=mWeek.matches();
boolean matchesWeekend=mWeekend.matches();
boolean matchesTimeOfDay=mTimeOfDay.matches();
String beginYear, endYear;
String beginMonth, endMonth;
String beginDay, endDay;
String beginHour, endHour;
String beginMinute, endMinute;
String beginSecond, endSecond;
beginYear=endYear="UNDEF";
beginMonth="01";
endMonth="12";
beginDay="01";
endDay="31";
beginHour="00";
endHour="23";
beginMinute="00";
endMinute="59";
beginSecond="00";
endSecond="59";
if(matchesDate){
//Get Year(1)
beginYear=endYear=mDate.group(1);
//Get Month(3)
if(mDate.group(3)!=null){
beginMonth=endMonth=mDate.group(3);
//Get Day(5)
if(mDate.group(5)==null){
Calendar c=Calendar.getInstance();
c.set(Integer.parseInt(beginYear), Integer.parseInt(beginMonth)-1, 1);
endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH);
beginDay="01";
}else{
beginDay=endDay=mDate.group(5);
//Get Hour(7)
if(mDate.group(7)!=null){
beginHour=endHour=mDate.group(7);
//Get Minute(9)
if(mDate.group(9)!=null){
beginMinute=endMinute=mDate.group(9);
//Get Second(11)
if(mDate.group(11)!=null){
beginSecond=endSecond=mDate.group(11);
}
}
}
}
}
}else if(matchesCentury){
beginYear=mCentury.group(1)+"00";
endYear=mCentury.group(1)+"99";
}else if(matchesDecade){
beginYear=mDecade.group(1)+"0";
endYear=mDecade.group(1)+"9";
}else if(matchesQuarter){
beginYear=endYear=mQuarter.group(1);
int beginMonthI=3*(Integer.parseInt(mQuarter.group(2))-1)+1;
beginMonth=""+beginMonthI;
endMonth=""+(beginMonthI+2);
Calendar c=Calendar.getInstance();
c.set(Integer.parseInt(beginYear), Integer.parseInt(endMonth)-1, 1);
endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH);
}else if(matchesHalf){
beginYear=endYear=mHalf.group(1);
int beginMonthI=6*(Integer.parseInt(mHalf.group(2))-1)+1;
beginMonth=""+beginMonthI;
endMonth=""+(beginMonthI+5);
Calendar c=Calendar.getInstance();
c.set(Integer.parseInt(beginYear), Integer.parseInt(endMonth)-1, 1);
endDay=""+c.getActualMaximum(Calendar.DAY_OF_MONTH);
}else if(matchesSeason){
beginYear=mSeason.group(1);
endYear=beginYear;
if(mSeason.group(2).equals("SP")){
beginMonth="03";
beginDay="21";
endMonth="06";
endDay="20";
}else if(mSeason.group(2).equals("SU")){
beginMonth="06";
beginDay="21";
endMonth="09";
endDay="22";
}else if(mSeason.group(2).equals("FA")){
beginMonth="09";
beginDay="23";
endMonth="12";
endDay="21";
}else if(mSeason.group(2).equals("WI")){
endYear=""+(Integer.parseInt(beginYear)+1);
beginMonth="12";
beginDay="22";
endMonth="03";
endDay="20";
}
}else if(matchesWeek){
beginYear=endYear=mWeek.group(1);
Calendar c=Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.YEAR,Integer.parseInt(beginYear));
c.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(mWeek.group(2)));
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
beginDay=""+c.get(Calendar.DAY_OF_MONTH);
beginMonth=""+(c.get(Calendar.MONTH)+1);
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
endDay=""+(c.get(Calendar.DAY_OF_MONTH));
endMonth=""+(c.get(Calendar.MONTH)+1);
}else if(matchesWeekend){
beginYear=endYear=mWeekend.group(1);
Calendar c=Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.YEAR,Integer.parseInt(beginYear));
c.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(mWeekend.group(2)));
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
beginDay=""+c.get(Calendar.DAY_OF_MONTH);
beginMonth=""+(c.get(Calendar.MONTH)+1);
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
endDay=""+(c.get(Calendar.DAY_OF_MONTH));
endMonth=""+(c.get(Calendar.MONTH)+1);
}else if(matchesTimeOfDay){
beginYear=endYear=mTimeOfDay.group(1);
beginMonth=endMonth=mTimeOfDay.group(2);
beginDay=endDay=mTimeOfDay.group(3);
}
// correct month and days < 10
if (Integer.parseInt(beginDay) < 10){
beginDay = "0" + Integer.parseInt(beginDay);
}
if (Integer.parseInt(beginMonth) < 10){
beginMonth = "0" + Integer.parseInt(beginMonth);
}
if (Integer.parseInt(endDay) < 10){
endDay = "0" + Integer.parseInt(endDay);
}
if (Integer.parseInt(endMonth) < 10){
endMonth = "0" + Integer.parseInt(endMonth);
}
if(!beginYear.equals("UNDEF") && !endYear.equals("UNDEF")){
annotation.setTimexValueEB(beginYear+"-"+beginMonth+"-"+beginDay+"T"+beginHour+":"+beginMinute+":"+beginSecond);
// annotation.setTimexValueLB(beginYear+"-"+beginMonth+"-"+beginDay+"T"+endHour+":"+endMinute+":"+endSecond);
// annotation.setTimexValueEE(endYear+"-"+endMonth+"-"+endDay+"T"+beginHour+":"+beginMinute+":"+beginSecond);
annotation.setTimexValueLE(endYear+"-"+endMonth+"-"+endDay+"T"+endHour+":"+endMinute+":"+endSecond);
annotation.setTimexValueLB(endYear+"-"+endMonth+"-"+endDay+"T"+endHour+":"+endMinute+":"+endSecond);
annotation.setTimexValueEE(beginYear+"-"+beginMonth+"-"+beginDay+"T"+beginHour+":"+beginMinute+":"+beginSecond);
//Copy Values from the Timex3 Annotation
annotation.setTimexFreq(timex3.getTimexFreq());
annotation.setTimexId(timex3.getTimexId());
annotation.setTimexInstance(timex3.getTimexInstance());
annotation.setTimexMod(timex3.getTimexMod());
annotation.setTimexQuant(timex3.getTimexMod());
annotation.setTimexType(timex3.getTimexType());
annotation.setTimexValue(timex3.getTimexValue());
annotation.setSentId(timex3.getSentId());
annotation.setBegin(timex3.getBegin());
annotation.setFoundByRule(timex3.getFoundByRule());
annotation.setEnd(timex3.getEnd());
annotation.setAllTokIds(timex3.getAllTokIds());
annotation.setFilename(timex3.getFilename());
annotation.setBeginTimex(timex3.getTimexId());
annotation.setEndTimex(timex3.getTimexId());
// remember this one for addition to indexes later
newAnnotations.add(annotation);
}
}
// add to indexes
for(Timex3Interval t3i : newAnnotations)
t3i.addToIndexes();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.