language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def humanize_bytes(b, precision=1):
"""Return a humanized string representation of a number of b.
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byte'
>>> humanize_bytes(1024)
'1.0 kB'
>>> humanize_bytes(1024*123)
'123.0 kB'
>>> humanize_bytes(1024*12342)
'12.1 MB'
>>> humanize_bytes(1024*12342,2)
'12.05 MB'
>>> humanize_bytes(1024*1234,2)
'1.21 MB'
>>> humanize_bytes(1024*1234*1111,2)
'1.31 GB'
>>> humanize_bytes(1024*1234*1111,1)
'1.3 GB'
"""
# abbrevs = (
# (1 << 50L, 'PB'),
# (1 << 40L, 'TB'),
# (1 << 30L, 'GB'),
# (1 << 20L, 'MB'),
# (1 << 10L, 'kB'),
# (1, 'b')
# )
abbrevs = (
(1 << 50, 'PB'),
(1 << 40, 'TB'),
(1 << 30, 'GB'),
(1 << 20, 'MB'),
(1 << 10, 'kB'),
(1, 'b')
)
if b == 1:
return '1 byte'
for factor, suffix in abbrevs:
if b >= factor:
break
# return '%.*f %s' % (precision, old_div(b, factor), suffix)
return '%.*f %s' % (precision, b // factor, suffix) |
python | def receive(self,message_type):
"""
Receive the message of the specified type and retun
Args:
- message_type: the type of the message to receive
Returns:
- the topic of the message
- the message received from the socket
"""
topic = None
message = None
if message_type == RAW:
message = self._sock.recv(flags=zmq.NOBLOCK)
elif message_type == PYOBJ:
message = self._sock.recv_pyobj(flags=zmq.NOBLOCK)
elif message_type == JSON:
message = self._sock.recv_json(flags=zmq.NOBLOCK)
elif message_type == MULTIPART:
data = self._sock.recv_multipart(flags=zmq.NOBLOCK)
message = data[1]
topic = data[0]
elif message_type == STRING:
message = self._sock.recv_string(flags=zmq.NOBLOCK)
elif message_type == UNICODE:
message = self._sock.recv_unicode(flags=zmq.NOBLOCK)
else:
raise Exception("Unknown message type %s"%(self._message_type,))
return (topic, message) |
python | def apply(self, cls, originalMemberNameList, memberName, classNamingConvention, getter, setter):
"""
:type cls: type
:type originalMemberNameList: list(str)
:type memberName: str
:type classNamingConvention: INamingConvention|None
"""
accessorDict = self._accessorDict(memberName, classNamingConvention, getter, setter)
for accessorName, accessor in accessorDict.items():
if accessorName not in originalMemberNameList and accessor is not None:
setattr(cls, accessorName, accessor) |
python | def get_armbian_release_field(self, field):
"""
Search /etc/armbian-release, if it exists, for a field and return its
value, if found, otherwise None.
"""
field_value = None
pattern = r'^' + field + r'=(.*)'
try:
with open("/etc/armbian-release", 'r') as release_file:
armbian = release_file.read().split('\n')
for line in armbian:
match = re.search(pattern, line)
if match:
field_value = match.group(1)
except FileNotFoundError:
pass
return field_value |
python | def registerContract(self, contract):
""" used for when callback receives a contract
that isn't found in local database """
if contract.m_exchange == "":
return
"""
if contract not in self.contracts.values():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
if self.tickerId(contract) not in self.contracts.keys():
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple)
"""
if self.getConId(contract) == 0:
contract_tuple = self.contract_to_tuple(contract)
self.createContract(contract_tuple) |
python | def setslice_with_length(self, startindex, endindex, fs, length):
"""Shim for easily converting old __setitem__ calls"""
if len(self) < startindex:
fs = ' '*(startindex - len(self)) + fs
if len(self) > endindex:
fs = fs + ' '*(endindex - startindex - len(fs))
assert len(fs) == endindex - startindex, (len(fs), startindex, endindex)
result = self.splice(fs, startindex, endindex)
assert len(result) <= length
return result |
java | static JSType createType(boolean shouldCreate, JSTypeRegistry registry, JSTypeNative typeName) {
if (!shouldCreate) {
return null;
}
return registry.getNativeType(typeName);
} |
python | def byte_to_channels(self, byte):
"""
:return: list(int)
"""
# pylint: disable-msg=R0201
assert isinstance(byte, int)
assert byte >= 0
assert byte < 256
result = []
for offset in range(0, 8):
if byte & (1 << offset):
result.append(offset + 1)
return result |
java | public static MozuUrl deletePublishSetUrl(String code, String responseFields, Boolean shouldDiscard)
{
UrlFormatter formatter = new UrlFormatter("/api/content/publishsets/{code}?shouldDiscard={shouldDiscard}&responseFields={responseFields}");
formatter.formatUrl("code", code);
formatter.formatUrl("responseFields", responseFields);
formatter.formatUrl("shouldDiscard", shouldDiscard);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} |
java | public void add(IdentityByState param) {
for (int i = 0; i < ibs.length; i++) {
ibs[i] += param.ibs[i];
}
} |
java | public void setValidator(AutoCompleteTextView.Validator validator) {
if(mAutoCompleteMode == AUTOCOMPLETE_MODE_NONE)
return;
((AutoCompleteTextView)mInputView).setValidator(validator);
} |
python | def check_garden_requirements(self):
'''Ensure required garden packages are available to be included.
'''
garden_requirements = self.config.getlist('app',
'garden_requirements', '')
# have we installed the garden packages?
if exists(self.gardenlibs_dir) and \
self.state.get('cache.gardenlibs', '') == garden_requirements:
self.debug('Garden requirements already installed, pass')
return
# we're going to reinstall all the garden libs.
self.rmdir(self.gardenlibs_dir)
# but if we don't have requirements, or if the user removed everything,
# don't do anything.
if not garden_requirements:
self.state['cache.gardenlibs'] = garden_requirements
return
self._ensure_virtualenv()
self.cmd('pip install Kivy-Garden==0.1.1', env=self.env_venv)
# recreate gardenlibs
self.mkdir(self.gardenlibs_dir)
for requirement in garden_requirements:
self._install_garden_package(requirement)
# save gardenlibs state
self.state['cache.gardenlibs'] = garden_requirements |
java | private DataSink<T> setResources(ResourceSpec minResources, ResourceSpec preferredResources) {
Preconditions.checkNotNull(minResources, "The min resources must be not null.");
Preconditions.checkNotNull(preferredResources, "The preferred resources must be not null.");
Preconditions.checkArgument(minResources.isValid() && preferredResources.isValid() && minResources.lessThanOrEqual(preferredResources),
"The values in resources must be not less than 0 and the preferred resources must be greater than the min resources.");
this.minResources = minResources;
this.preferredResources = preferredResources;
return this;
} |
java | public static Object callMethod(Object object, String methodName, Object[] parameters)
throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
MethodParameterPair pair = getMethodParameterPairIgnoreCase(object.getClass(), methodName, parameters);
return pair.getMethod().invoke(object, pair.getParameters());
} |
java | protected TransportResult doit(String method, URI uri, String payload){
HttpURLConnection httpConnection = null;
try {
URL url = uri.toURL();
URLConnection connection = url.openConnection();
if (connection instanceof HttpURLConnection) {
httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod(method);
// httpConnection.setRequestProperty("Content-Language", "en-US");
httpConnection.setRequestProperty(apiAuthHeaderKey, getApitraryApi().getApiKey());
httpConnection.setRequestProperty("Accept", contentType);
httpConnection.setRequestProperty("Content-Type", contentType);
httpConnection.setUseCaches(false);
httpConnection.setDoInput(true);
httpConnection.setDoOutput(payload!=null);
log.debug(method+" "+ httpConnection.getURL()+(payload!=null?"application/json: "+payload:""));
if(payload!=null){
byte[] bytes = payload.getBytes();
httpConnection.setRequestProperty("Content-Length", "" + Integer.toString(bytes.length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
wr.flush();
wr.close();
}
return new JavaNetClientTransportResult(httpConnection);
} else {
throw new ApiTransportException("Connection is not an HTTPConnection");
}
} catch (IOException ioe) {
throw new ApiTransportException(ioe);
}
} |
java | public static Properties createPropertiesFromResource(Class<?> classObj,
String resourceName) throws IOException {
Properties result = new Properties();
readPropertiesFromResource(result, classObj, resourceName);
return result;
} |
java | public static void assertTrueOrInvalidKindForAnnotationException(boolean expression, Element element,
Class<? extends Annotation> annotationClazz) {
if (!expression) {
String msg = String.format("%s %s, only class can be annotated with @%s annotation", element.getKind(),
element, annotationClazz.getSimpleName());
throw (new InvalidKindForAnnotationException(msg));
}
} |
python | def global_logout(self, name_id, reason="", expire=None, sign=None,
sign_alg=None, digest_alg=None):
""" More or less a layer of indirection :-/
Bootstrapping the whole thing by finding all the IdPs that should
be notified.
:param name_id: The identifier of the subject that wants to be
logged out.
:param reason: Why the subject wants to log out
:param expire: The latest the log out should happen.
If this time has passed don't bother.
:param sign: Whether the request should be signed or not.
This also depends on what binding is used.
:return: Depends on which binding is used:
If the HTTP redirect binding then a HTTP redirect,
if SOAP binding has been used the just the result of that
conversation.
"""
if isinstance(name_id, six.string_types):
name_id = decode(name_id)
logger.info("logout request for: %s", name_id)
# find out which IdPs/AAs I should notify
entity_ids = self.users.issuers_of_info(name_id)
return self.do_logout(name_id, entity_ids, reason, expire, sign,
sign_alg=sign_alg, digest_alg=digest_alg) |
java | public Reliability getMaxReliability()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getMaxReliability");
Reliability maxRel = aliasDest.getMaxReliability();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "getMaxReliability", maxRel);
return maxRel;
} |
java | protected Object readResolve() throws InvalidObjectException {
if (this.getClass() != TextAttribute.class) {
throw new InvalidObjectException(
"subclass didn't correctly implement readResolve");
}
TextAttribute instance = (TextAttribute) instanceMap.get(getName());
if (instance != null) {
return instance;
} else {
throw new InvalidObjectException("unknown attribute name");
}
} |
python | def after_request(self, func: Callable, name: AppOrBlueprintKey=None) -> Callable:
"""Add an after request function.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_request
def func(response):
return response
Arguments:
func: The after request function itself.
name: Optional blueprint key name.
"""
handler = ensure_coroutine(func)
self.after_request_funcs[name].append(handler)
return func |
java | protected void createDtdSchema(final LmlParser parser, final Appendable appendable) throws Exception {
Dtd.saveSchema(parser, appendable);
} |
java | public IfcConstraintEnum createIfcConstraintEnumFromString(EDataType eDataType, String initialValue) {
IfcConstraintEnum result = IfcConstraintEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
} |
java | public void setVerboseDebug(final int level) {
debugLevel = level;
for (final String logName : logs.keySet()) {
logs.get(logName).setVerboseDebug(level);
}
} |
java | @Nonnull
public static <T> LObjIntPredicateBuilder<T> objIntPredicate(Consumer<LObjIntPredicate<T>> consumer) {
return new LObjIntPredicateBuilder(consumer);
} |
python | def depth_texture(self, size, data=None, *, samples=0, alignment=4) -> 'Texture':
'''
Create a :py:class:`Texture` object.
Args:
size (tuple): The width and height of the texture.
data (bytes): Content of the texture.
Keyword Args:
samples (int): The number of samples. Value 0 means no multisample format.
alignment (int): The byte alignment 1, 2, 4 or 8.
Returns:
:py:class:`Texture` object
'''
res = Texture.__new__(Texture)
res.mglo, res._glo = self.mglo.depth_texture(size, data, samples, alignment)
res._size = size
res._components = 1
res._samples = samples
res._dtype = 'f4'
res._depth = True
res.ctx = self
res.extra = None
return res |
java | public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("suspensionState", this.suspensionState);
persistentState.put("historyTimeToLive", this.historyTimeToLive);
return persistentState;
} |
java | protected void configureCommandIcons(CommandIconConfigurable configurable, String objectName) {
Assert.notNull(configurable, "configurable");
Assert.notNull(objectName, "objectName");
setIconInfo(configurable, objectName, false);
setIconInfo(configurable, objectName, true);
} |
java | protected Point getTextBasePoint(String text, double xCoord, double yCoord, Graphics2D graphics) {
FontMetrics fontMetrics = graphics.getFontMetrics();
Rectangle2D stringBounds = fontMetrics.getStringBounds(text, graphics);
int[] point = this.transformPoint(xCoord, yCoord);
int baseX = (int) (point[0] - (stringBounds.getWidth() / 2));
// correct the baseline by the ascent
int baseY = (int) (point[1] + (fontMetrics.getAscent() - stringBounds.getHeight() / 2));
return new Point(baseX, baseY);
} |
python | def _update_imageinfo(self):
"""
calls get_imageinfo() if data image missing info
"""
missing = self._missing_imageinfo()
deferred = self.flags.get('defer_imageinfo')
continuing = self.data.get('continue')
if missing and not deferred and not continuing:
self.get_imageinfo(show=False) |
java | public void marshall(RaidArray raidArray, ProtocolMarshaller protocolMarshaller) {
if (raidArray == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(raidArray.getRaidArrayId(), RAIDARRAYID_BINDING);
protocolMarshaller.marshall(raidArray.getInstanceId(), INSTANCEID_BINDING);
protocolMarshaller.marshall(raidArray.getName(), NAME_BINDING);
protocolMarshaller.marshall(raidArray.getRaidLevel(), RAIDLEVEL_BINDING);
protocolMarshaller.marshall(raidArray.getNumberOfDisks(), NUMBEROFDISKS_BINDING);
protocolMarshaller.marshall(raidArray.getSize(), SIZE_BINDING);
protocolMarshaller.marshall(raidArray.getDevice(), DEVICE_BINDING);
protocolMarshaller.marshall(raidArray.getMountPoint(), MOUNTPOINT_BINDING);
protocolMarshaller.marshall(raidArray.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
protocolMarshaller.marshall(raidArray.getCreatedAt(), CREATEDAT_BINDING);
protocolMarshaller.marshall(raidArray.getStackId(), STACKID_BINDING);
protocolMarshaller.marshall(raidArray.getVolumeType(), VOLUMETYPE_BINDING);
protocolMarshaller.marshall(raidArray.getIops(), IOPS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public static void setPersonEmail(final String email) {
dispatchConversationTask(new ConversationDispatchTask() {
@Override
protected boolean execute(Conversation conversation) {
ApptentiveInternal.getInstance().getConversationProxy().setPersonEmail(email);
return true;
}
}, "set person email");
} |
java | public static Forest[] gets(Collection<String> keys) {
return gets(keys.toArray(new String[keys.size()]));
} |
java | @Override
public void removeAllResourses() throws Exception {
synchronized (this) {
if (!this.started) {
throw new Exception(String.format("Management=%s not started", this.name));
}
if (this.associations.size() == 0 && this.servers.size() == 0)
// no resources allocated - nothing to do
return;
if (logger.isInfoEnabled()) {
logger.info(String.format("Removing allocated resources: Servers=%d, Associations=%d", this.servers.size(),
this.associations.size()));
}
// Remove all associations
ArrayList<String> lst = new ArrayList<String>();
for (FastMap.Entry<String, Association> n = this.associations.head(), end = this.associations.tail(); (n = n
.getNext()) != end;) {
lst.add(n.getKey());
}
for (String n : lst) {
this.stopAssociation(n);
this.removeAssociation(n);
}
// Remove all servers
lst.clear();
for (FastList.Node<Server> n = this.servers.head(), end = this.servers.tail(); (n = n.getNext()) != end;) {
lst.add(n.getValue().getName());
}
for (String n : lst) {
this.stopServer(n);
this.removeServer(n);
}
// We store the cleared state
this.store();
for (ManagementEventListener lstr : managementEventListeners) {
try {
lstr.onRemoveAllResources();
} catch (Throwable ee) {
logger.error("Exception while invoking onRemoveAllResources", ee);
}
}
}
} |
python | def generate_p_star(num_groups):
"""Describe the order in which groups move
Arguments
---------
num_groups : int
Returns
-------
np.ndarray
Matrix P* - size (g-by-g)
"""
p_star = np.eye(num_groups, num_groups)
rd.shuffle(p_star)
return p_star |
java | public <C extends Collection<? super T>> C into(C collection) {
if (isParallel()) {
@SuppressWarnings("unchecked")
List<T> list = Arrays.asList((T[]) toArray());
collection.addAll(list);
} else {
Spliterator<T> spltr = spliterator();
if (collection instanceof ArrayList) {
long size = spltr.getExactSizeIfKnown();
if (size >= 0 && size < Integer.MAX_VALUE - collection.size())
((ArrayList<?>) collection).ensureCapacity((int) (collection.size() + size));
}
spltr.forEachRemaining(collection::add);
}
return collection;
} |
java | private DeviceData checkWithHostAddress(DeviceData deviceData, DeviceProxy deviceProxy) throws DevFailed {
// ToDo
DevVarLongStringArray lsa = deviceData.extractLongStringArray();
try {
java.net.InetAddress iadd =
java.net.InetAddress.getByName(deviceProxy.get_host_name());
String hostAddress = iadd.getHostAddress();
System.err.println("Host address is " + hostAddress);
System.err.println("Server returns " + lsa.svalue[0]);
if (! lsa.svalue[0].startsWith("tcp://"+hostAddress)) { // Addresses are different
String wrongAdd = lsa.svalue[0];
int idx = lsa.svalue[0].lastIndexOf(':'); // get port
if (idx>0) {
lsa.svalue[0] = "tcp://" + hostAddress + lsa.svalue[0].substring(idx);
lsa.svalue[1] = "tcp://" + hostAddress + lsa.svalue[1].substring(idx);
System.out.println(wrongAdd + " ---> "+lsa.svalue[0]);
deviceData = new DeviceData();
deviceData.insert(lsa);
isEndpointAvailable(lsa.svalue[0]);
}
}
} catch (UnknownHostException e) {
Except.throw_exception("UnknownHostException",
e.toString(), "ZmqEventConsumer.checkZmqAddress()");
}
//System.out.println("---> Connect on "+deviceData.extractLongStringArray().svalue[0]);
return deviceData;
} |
python | def image_to_data(image,
lang=None,
config='',
nice=0,
output_type=Output.STRING):
'''
Returns string containing box boundaries, confidences,
and other information. Requires Tesseract 3.05+
'''
if get_tesseract_version() < '3.05':
raise TSVNotSupported()
config = '{} {}'.format('-c tessedit_create_tsv=1', config.strip()).strip()
args = [image, 'tsv', lang, config, nice]
return {
Output.BYTES: lambda: run_and_get_output(*(args + [True])),
Output.DATAFRAME: lambda: get_pandas_output(args + [True]),
Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '\t', -1),
Output.STRING: lambda: run_and_get_output(*args),
}[output_type]() |
python | def printer(self, message, color_level='info'):
"""Print Messages and Log it.
:param message: item to print to screen
"""
if self.job_args.get('colorized'):
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) |
python | def has_subkey(self, subkey):
"""
Return True if this AdfKey contains the given subkey.
Parameters
----------
subkey : str or AdfKey
A key name or an AdfKey object.
Returns
-------
has : bool
True if this key contains the given key. Otherwise False.
"""
if isinstance(subkey, str):
key = subkey
elif isinstance(subkey, AdfKey):
key = subkey.key
else:
raise ValueError("The subkey should be an AdfKey or a string!")
if len(self.subkeys) > 0:
if key in map(lambda k: k.key, self.subkeys):
return True
return False |
python | def analyze(self, handle, filename):
"""Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File hash as a string
"""
# multipart post files.
files = {"file" : (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
response = self._request("/submit/file", method='POST', files=files)
try:
if response.status_code == 201:
# good response
return response.json()['job_id']
else:
raise sandboxapi.SandboxError("api error in analyze: {r}".format(r=response.content.decode('utf-8')))
except (ValueError, KeyError) as e:
raise sandboxapi.SandboxError("error in analyze: {e}".format(e=e)) |
python | def assign_charge(mol, force_recalc=False):
"""Assign charges in physiological condition"""
# TODO: not implemented yet
mol.require("Aromatic")
for i, nbrs in mol.neighbors_iter():
atom = mol.atom(i)
nbrcnt = len(nbrs)
if atom.symbol == "N":
if not atom.pi:
# non-conjugated amines are anion
mol.atom(i).charge_phys = 1
elif nbrcnt == 1 and atom.pi == 2:
# amidine, guanidine are conjugated cation
ni = list(nbrs.keys())[0]
conj = False
sp2n = None
for nni, nnb in mol.neighbors(ni).items():
if mol.atom(nni).symbol == "N" and nnb.order == 2 \
and not mol.atom(nni).aromatic:
mol.atom(nni).charge_conj = 1
conj = True
elif mol.atom(nni).symbol == "N" and nni != i:
sp2n = nni
if conj:
mol.atom(i).charge_phys = 1
if sp2n is not None:
mol.atom(sp2n).charge_conj = 1
elif atom.symbol == "O" and nbrcnt == 1 and atom.pi == 2:
# oxoacid are conjugated anion
ni = list(nbrs.keys())[0]
conj = False
if mol.atom(ni).symbol == "N":
mol.atom(i).n_oxide = True
mol.atom(ni).n_oxide = True
for nni, nnb in mol.neighbors(ni).items():
if mol.atom(nni).symbol in ("O", "S") \
and nnb.order == 2 and not mol.atom(ni).n_oxide:
mol.atom(nni).charge_conj = -1
conj = True
if conj:
mol.atom(i).charge_phys = -1
elif atom.symbol == "S" and nbrcnt == 1:
# thiophenols are anion
ni = list(nbrs.keys())[0]
if mol.atom(ni).aromatic:
mol.atom(i).charge_phys = -1
mol.charge_assigned = True
mol.descriptors.add("Phys_charge") |
python | def path(
self, path=None, operations=None, summary=None, description=None, **kwargs
):
"""Add a new path object to the spec.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#path-item-object
:param str|None path: URL path component
:param dict|None operations: describes the http methods and options for `path`
:param str summary: short summary relevant to all operations in this path
:param str description: long description relevant to all operations in this path
:param dict kwargs: parameters used by any path helpers see :meth:`register_path_helper`
"""
operations = operations or OrderedDict()
# Execute path helpers
for plugin in self.plugins:
try:
ret = plugin.path_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
if ret is not None:
path = ret
if not path:
raise APISpecError("Path template is not specified.")
# Execute operation helpers
for plugin in self.plugins:
try:
plugin.operation_helper(path=path, operations=operations, **kwargs)
except PluginMethodNotImplementedError:
continue
clean_operations(operations, self.openapi_version.major)
self._paths.setdefault(path, operations).update(operations)
if summary is not None:
self._paths[path]["summary"] = summary
if description is not None:
self._paths[path]["description"] = description
return self |
java | public static PactDslJsonBody arrayMinLike(int minSize, int numberExamples) {
if (numberExamples < minSize) {
throw new IllegalArgumentException(String.format("Number of example %d is less than the minimum size of %d",
numberExamples, minSize));
}
PactDslJsonArray parent = new PactDslJsonArray("", "", null, true);
parent.setNumberExamples(numberExamples);
parent.matchers.addRule("", parent.matchMin(minSize));
return new PactDslJsonBody(".", "", parent);
} |
java | @Override
public V putIfAbsentFailure(K key, V value, StoreAccessException e) {
// FIXME: Should I care about useLoaderInAtomics?
try {
try {
V loaded = loaderWriter.load(key);
if (loaded != null) {
return loaded;
}
} catch (Exception e1) {
throw ExceptionFactory.newCacheLoadingException(e1, e);
}
try {
loaderWriter.write(key, value);
} catch (Exception e1) {
throw ExceptionFactory.newCacheWritingException(e1, e);
}
} finally {
cleanup(key, e);
}
return null;
} |
python | def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color)) |
java | public boolean recordExpose() {
if (!currentInfo.isExpose()) {
currentInfo.setExpose(true);
populated = true;
return true;
} else {
return false;
}
} |
java | public Context duplicate() {
Context newContext = new Context(session, getIndex());
newContext.description = this.description;
newContext.name = this.name;
newContext.includeInRegexs = new ArrayList<>(this.includeInRegexs);
newContext.includeInPatterns = new ArrayList<>(this.includeInPatterns);
newContext.excludeFromRegexs = new ArrayList<>(this.excludeFromRegexs);
newContext.excludeFromPatterns = new ArrayList<>(this.excludeFromPatterns);
newContext.inScope = this.inScope;
newContext.techSet = new TechSet(this.techSet);
newContext.authenticationMethod = this.authenticationMethod.clone();
newContext.sessionManagementMethod = this.sessionManagementMethod.clone();
newContext.urlParamParser = this.urlParamParser.clone();
newContext.postParamParser = this.postParamParser.clone();
newContext.authorizationDetectionMethod = this.authorizationDetectionMethod.clone();
newContext.dataDrivenNodes = this.getDataDrivenNodes();
return newContext;
} |
java | public boolean fitsInside3D(Dimension dimension) {
return fitsInside3D(dimension.getWidth(), dimension.getDepth(), dimension.getHeight());
} |
python | def with_timeout(timeout, future, quiet_exceptions=()):
"""Wraps a `.Future` (or other yieldable object) in a timeout.
Raises `tornado.util.TimeoutError` if the input future does not
complete before ``timeout``, which may be specified in any form
allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or
an absolute time relative to `.IOLoop.time`)
If the wrapped `.Future` fails after it has timed out, the exception
will be logged unless it is of a type contained in ``quiet_exceptions``
(which may be an exception type or a sequence of types).
Does not support `YieldPoint` subclasses.
.. versionadded:: 4.0
.. versionchanged:: 4.1
Added the ``quiet_exceptions`` argument and the logging of unhandled
exceptions.
.. versionchanged:: 4.4
Added support for yieldable objects other than `.Future`.
"""
# TODO: allow YieldPoints in addition to other yieldables?
# Tricky to do with stack_context semantics.
#
# It's tempting to optimize this by cancelling the input future on timeout
# instead of creating a new one, but A) we can't know if we are the only
# one waiting on the input future, so cancelling it might disrupt other
# callers and B) concurrent futures can only be cancelled while they are
# in the queue, so cancellation cannot reliably bound our waiting time.
future = convert_yielded(future)
result = Future()
chain_future(future, result)
io_loop = IOLoop.current()
def error_callback(future):
try:
future.result()
except Exception as e:
if not isinstance(e, quiet_exceptions):
app_log.error("Exception in Future %r after timeout",
future, exc_info=True)
def timeout_callback():
result.set_exception(TimeoutError("Timeout"))
# In case the wrapped future goes on to fail, log it.
future.add_done_callback(error_callback)
timeout_handle = io_loop.add_timeout(
timeout, timeout_callback)
if isinstance(future, Future):
# We know this future will resolve on the IOLoop, so we don't
# need the extra thread-safety of IOLoop.add_future (and we also
# don't care about StackContext here.
future.add_done_callback(
lambda future: io_loop.remove_timeout(timeout_handle))
else:
# concurrent.futures.Futures may resolve on any thread, so we
# need to route them back to the IOLoop.
io_loop.add_future(
future, lambda future: io_loop.remove_timeout(timeout_handle))
return result |
java | @Override
public String getLocalHost()
{
if (_localName == null) {
byte []localAddrBuffer = _localAddrBuffer;
char []localAddrCharBuffer = _localAddrCharBuffer;
if (_localAddrLength <= 0) {
_localAddrLength = InetAddressUtil.createIpAddress(localAddrBuffer,
localAddrCharBuffer);
}
_localName = new String(localAddrCharBuffer, 0, _localAddrLength);
}
return _localName;
} |
python | def runExperiment():
"""
Experiment 1: Calculate error rate as a function of training sequence numbers
:return:
"""
trainSeqN = [5, 10, 20, 50, 100, 200]
rptPerCondition = 5
correctRateAll = np.zeros((len(trainSeqN), rptPerCondition))
missRateAll = np.zeros((len(trainSeqN), rptPerCondition))
fpRateAll = np.zeros((len(trainSeqN), rptPerCondition))
for i in xrange(len(trainSeqN)):
for rpt in xrange(rptPerCondition):
train_seed = 1
numTrainSequence = trainSeqN[i]
net = initializeLSTMnet()
net = trainLSTMnet(net, numTrainSequence, seedSeq=train_seed)
(correctRate, missRate, fpRate) = testLSTMnet(net, numTestSequence, seedSeq=train_seed+rpt)
correctRateAll[i, rpt] = correctRate
missRateAll[i, rpt] = missRate
fpRateAll[i, rpt] = fpRate
np.savez('result/reberSequenceLSTM.npz',
correctRateAll=correctRateAll, missRateAll=missRateAll,
fpRateAll=fpRateAll, trainSeqN=trainSeqN)
plt.figure()
plt.subplot(2,2,1)
plt.semilogx(trainSeqN, 100*np.mean(correctRateAll,1),'-*')
plt.xlabel(' Training Sequence Number')
plt.ylabel(' Hit Rate - Best Match (%)')
plt.subplot(2,2,2)
plt.semilogx(trainSeqN, 100*np.mean(missRateAll,1),'-*')
plt.xlabel(' Training Sequence Number')
plt.ylabel(' Miss Rate (%)')
plt.subplot(2,2,3)
plt.semilogx(trainSeqN, 100*np.mean(fpRateAll,1),'-*')
plt.xlabel(' Training Sequence Number')
plt.ylabel(' False Positive Rate (%)')
plt.savefig('result/ReberSequence_LSTMperformance.pdf') |
java | void isLegal(boolean checkCdDaSubset) throws Violation {
if (checkCdDaSubset) {
if (leadIn < 2 * 44100) {
throw new Violation("CD-DA cue sheet must have a lead-in length of at least 2 seconds");
}
if (leadIn % 588 != 0) {
throw new Violation("CD-DA cue sheet lead-in length must be evenly divisible by 588 samples");
}
}
if (numTracks == 0) {
throw new Violation("cue sheet must have at least one track (the lead-out)");
}
if (checkCdDaSubset && tracks[numTracks - 1].number != 170) {
throw new Violation("CD-DA cue sheet must have a lead-out track number 170 (0xAA)");
}
for (int i = 0; i < numTracks; i++) {
if (tracks[i].number == 0) {
throw new Violation("cue sheet may not have a track number 0");
}
if (checkCdDaSubset) {
if (!((tracks[i].number >= 1 && tracks[i].number <= 99) || tracks[i].number == 170)) {
throw new Violation("CD-DA cue sheet track number must be 1-99 or 170");
}
}
if (checkCdDaSubset && tracks[i].offset % 588 != 0) {
throw new Violation("CD-DA cue sheet track offset must be evenly divisible by 588 samples");
}
if (i < numTracks - 1) {
if (tracks[i].numIndices == 0) {
throw new Violation("cue sheet track must have at least one index point");
}
if (tracks[i].indices[0].number > 1) {
throw new Violation("cue sheet track's first index number must be 0 or 1");
}
}
for (int j = 0; j < tracks[i].numIndices; j++) {
if (checkCdDaSubset && tracks[i].indices[j].offset % 588 != 0) {
throw new Violation("CD-DA cue sheet track index offset must be evenly divisible by 588 samples");
}
if (j > 0) {
if (tracks[i].indices[j].number != tracks[i].indices[j - 1].number + 1) {
throw new Violation("cue sheet track index numbers must increase by 1");
}
}
}
}
} |
java | @SuppressWarnings("restriction")
public static long[] hash(final Memory mem, final long offsetBytes, final long lengthBytes,
final long seed, final long[] hashOut) {
if ((mem == null) || (mem.getCapacity() == 0L)) {
return emptyOrNull(seed, hashOut);
}
final Object uObj = ((WritableMemory) mem).getArray(); //may be null
long cumOff = mem.getCumulativeOffset() + offsetBytes;
long h1 = seed;
long h2 = seed;
long rem = lengthBytes;
// Process the 128-bit blocks (the body) into the hash
while (rem >= 16L) {
final long k1 = unsafe.getLong(uObj, cumOff); //0, 16, 32, ...
final long k2 = unsafe.getLong(uObj, cumOff + 8); //8, 24, 40, ...
cumOff += 16L;
rem -= 16L;
h1 ^= mixK1(k1);
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = (h1 * 5) + 0x52dce729L;
h2 ^= mixK2(k2);
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = (h2 * 5) + 0x38495ab5L;
}
// Get the tail (if any): 1 to 15 bytes
if (rem > 0L) {
long k1 = 0;
long k2 = 0;
switch ((int) rem) {
case 15: {
k2 ^= (unsafe.getByte(uObj, cumOff + 14) & 0xFFL) << 48;
}
//$FALL-THROUGH$
case 14: {
k2 ^= (unsafe.getShort(uObj, cumOff + 12) & 0xFFFFL) << 32;
k2 ^= (unsafe.getInt(uObj, cumOff + 8) & 0xFFFFFFFFL);
k1 = unsafe.getLong(uObj, cumOff);
break;
}
case 13: {
k2 ^= (unsafe.getByte(uObj, cumOff + 12) & 0xFFL) << 32;
}
//$FALL-THROUGH$
case 12: {
k2 ^= (unsafe.getInt(uObj, cumOff + 8) & 0xFFFFFFFFL);
k1 = unsafe.getLong(uObj, cumOff);
break;
}
case 11: {
k2 ^= (unsafe.getByte(uObj, cumOff + 10) & 0xFFL) << 16;
}
//$FALL-THROUGH$
case 10: {
k2 ^= (unsafe.getShort(uObj, cumOff + 8) & 0xFFFFL);
k1 = unsafe.getLong(uObj, cumOff);
break;
}
case 9: {
k2 ^= (unsafe.getByte(uObj, cumOff + 8) & 0xFFL);
}
//$FALL-THROUGH$
case 8: {
k1 = unsafe.getLong(uObj, cumOff);
break;
}
case 7: {
k1 ^= (unsafe.getByte(uObj, cumOff + 6) & 0xFFL) << 48;
}
//$FALL-THROUGH$
case 6: {
k1 ^= (unsafe.getShort(uObj, cumOff + 4) & 0xFFFFL) << 32;
k1 ^= (unsafe.getInt(uObj, cumOff) & 0xFFFFFFFFL);
break;
}
case 5: {
k1 ^= (unsafe.getByte(uObj, cumOff + 4) & 0xFFL) << 32;
}
//$FALL-THROUGH$
case 4: {
k1 ^= (unsafe.getInt(uObj, cumOff) & 0xFFFFFFFFL);
break;
}
case 3: {
k1 ^= (unsafe.getByte(uObj, cumOff + 2) & 0xFFL) << 16;
}
//$FALL-THROUGH$
case 2: {
k1 ^= (unsafe.getShort(uObj, cumOff) & 0xFFFFL);
break;
}
case 1: {
k1 ^= (unsafe.getByte(uObj, cumOff) & 0xFFL);
break;
}
//default: break; //can't happen
}
h1 ^= mixK1(k1);
h2 ^= mixK2(k2);
}
return finalMix128(h1, h2, lengthBytes, hashOut);
} |
java | private void fireOnMessage(ChannelEvent e) {
List<EventListener> listeners = changes.getListenerList(AMQP);
for (EventListener listener : listeners) {
ChannelListener amqpListener = (ChannelListener)listener;
amqpListener.onMessage(e);
}
} |
java | @Override
public void removeByCommerceNotificationTemplateId(
long commerceNotificationTemplateId) {
for (CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel : findByCommerceNotificationTemplateId(
commerceNotificationTemplateId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(commerceNotificationTemplateUserSegmentRel);
}
} |
java | public void putObject(String bucketName, String objectName, String fileName)
throws InvalidBucketNameException, NoSuchAlgorithmException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException,
InvalidArgumentException, InsufficientDataException {
putObject(bucketName, objectName, fileName, null);
} |
python | def predict(self,function,args):
"""Make a prediction for the function, to which we will pass the additional arguments"""
param = self.model.param_array
fs = []
for p in self.chain:
self.model.param_array = p
fs.append(function(*args))
# reset model to starting state
self.model.param_array = param
return fs |
java | @Override
public void addField(final SchemaField field) {
if (field instanceof FieldDefinition) {
addField((FieldDefinition) field);
} else if (field instanceof CopyFieldDefinition) {
addCopyField((CopyFieldDefinition) field);
}
} |
python | def filter_record(self, record):
"""
Filter a record, truncating or dropping at an 'N'
"""
nloc = record.seq.find('N')
if nloc == -1:
return record
elif self.action == 'truncate':
return record[:nloc]
elif self.action == 'drop':
raise FailedFilter()
else:
assert False |
java | Rule Mixolydian() {
return Sequence(IgnoreCase("mix"),
Optional(Sequence(IgnoreCase("o"),
Optional(Sequence(IgnoreCase("l"),
Optional(Sequence(IgnoreCase("y"),
Optional(Sequence(IgnoreCase("d"),
Optional(Sequence(IgnoreCase("i"),
Optional(Sequence(IgnoreCase("a"),
Optional(IgnoreCase("n"))
))
))
))
))
))
))
).label(Mixolydian).suppressSubnodes();
} |
java | public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
String keyBytes = Base64Utils.encode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicK = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(data);
return signature.verify(Base64Utils.decode(sign).getBytes());
} |
java | public static boolean doCheck(String noSignStr, String sign, String publicKey) {
if (sign == null || noSignStr == null || publicKey == null) {
return false;
}
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
signature.update(noSignStr.getBytes(CHARSET));
return signature.verify(Base64.decode(sign, Base64.DEFAULT));
} catch (Exception e) {
// 这里是安全算法,为避免出现异常时泄露加密信息,这里不打印具体日志
HMSAgentLog.e("doCheck error");
}
return false;
} |
java | public SubnetInner get(String resourceGroupName, String virtualNetworkName, String subnetName, String expand) {
return getWithServiceResponseAsync(resourceGroupName, virtualNetworkName, subnetName, expand).toBlocking().single().body();
} |
java | @Override
public final PurchaseInvoiceLine process(
final Map<String, Object> pReqVars,
final PurchaseInvoiceLine pEntity,
final IRequestData pRequestData) throws Exception {
if (pEntity.getIsNew()) {
// Beige-Orm refresh:
pReqVars.put("DebtorCreditortaxDestinationdeepLevel", 2);
Set<String> ndFlDc = new HashSet<String>();
ndFlDc.add("itsId");
ndFlDc.add("isForeigner");
ndFlDc.add("taxDestination");
pReqVars.put("DebtorCreditorneededFields", ndFlDc);
pEntity.setItsOwner(getSrvOrm()
.retrieveEntity(pReqVars, pEntity.getItsOwner()));
pReqVars.remove("DebtorCreditorneededFields");
pReqVars.remove("DebtorCreditortaxDestinationdeepLevel");
AccSettings as = getSrvAccSettings().lazyGetAccSettings(pReqVars);
TaxDestination txRules = this.utlInvLine.revealTaxRules(pReqVars,
pEntity.getItsOwner(), as, as.getIsExtractSalesTaxFromPurchase());
if (pEntity.getReversedId() != null) {
PurchaseInvoiceLine reversed = getSrvOrm().retrieveEntityById(
pReqVars, PurchaseInvoiceLine.class, pEntity.getReversedId());
if (reversed.getReversedId() != null) {
throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
"attempt_to_reverse_reversed::" + pReqVars.get("user"));
}
if (!reversed.getItsQuantity().equals(reversed.getTheRest())) {
throw new ExceptionWithCode(ExceptionWithCode
.WRONG_PARAMETER, "where_is_withdrawals_from_this_source::"
+ pReqVars.get("user"));
}
pEntity.setTheRest(BigDecimal.ZERO);
pEntity.setInvItem(reversed.getInvItem());
pEntity.setUnitOfMeasure(reversed.getUnitOfMeasure());
pEntity.setWarehouseSite(reversed.getWarehouseSite());
pEntity.setTaxCategory(reversed.getTaxCategory());
pEntity.setTaxesDescription(reversed.getTaxesDescription());
pEntity.setTotalTaxes(reversed.getTotalTaxes().negate());
pEntity.setItsQuantity(reversed.getItsQuantity().negate());
pEntity.setItsCost(reversed.getItsCost());
pEntity.setSubtotal(reversed.getSubtotal().negate());
pEntity.setItsTotal(reversed.getItsTotal().negate());
pEntity.setForeignPrice(reversed.getForeignPrice());
pEntity.setForeignSubtotal(reversed.getForeignSubtotal().negate());
pEntity.setForeignTotalTaxes(reversed.getForeignTotalTaxes().negate());
pEntity.setForeignTotal(reversed.getForeignTotal().negate());
getSrvOrm().insertEntity(pReqVars, pEntity);
pEntity.setIsNew(false);
reversed.setTheRest(BigDecimal.ZERO);
reversed.setReversedId(pEntity.getItsId());
getSrvOrm().updateEntity(pReqVars, reversed);
getSrvOrm().deleteEntityWhere(pReqVars,
PurchaseInvoiceGoodsTaxLine.class, "ITSOWNER=" + reversed.getItsId());
} else {
if (pEntity.getItsQuantity().doubleValue() <= 0) {
throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
"quantity_less_or_equal_zero::" + pReqVars.get("user"));
}
if (!(pEntity.getItsCost().compareTo(BigDecimal.ZERO) > 0
|| pEntity.getForeignPrice().compareTo(BigDecimal.ZERO) > 0)) {
throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
"cost_less_or_eq_zero::" + pReqVars.get("user"));
}
// Beige-Orm refresh:
pEntity.setInvItem(getSrvOrm()
.retrieveEntity(pReqVars, pEntity.getInvItem()));
if (!(InvItem.MATERIAL_ID.equals(pEntity.getInvItem().getItsType()
.getItsId()) || InvItem.MERCHANDISE_ID.equals(pEntity.getInvItem()
.getItsType().getItsId()))) {
throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
"type_must_be_material_or_merchandise::" + pReqVars.get("user"));
}
pEntity.setTheRest(pEntity.getItsQuantity());
BigDecimal exchRate = pEntity.getItsOwner().getExchangeRate();
if (exchRate != null && exchRate.compareTo(BigDecimal.ZERO) == -1) {
exchRate = BigDecimal.ONE.divide(exchRate.negate(), 15,
RoundingMode.HALF_UP);
}
if (pEntity.getInvItem().getKnownCost() != null
&& pEntity.getInvItem().getKnownCost().compareTo(BigDecimal.ZERO) == 1) {
if (pEntity.getItsOwner().getForeignCurrency() != null) {
pEntity.setForeignPrice(pEntity.getInvItem().getKnownCost());
if (txRules == null || pEntity.getItsOwner().getPriceIncTax()) {
pEntity.setForeignTotal(pEntity.getItsQuantity().multiply(pEntity
.getForeignPrice()).setScale(as.getPricePrecision(), as.getRoundingMode()));
} else {
pEntity.setForeignSubtotal(pEntity.getItsQuantity().multiply(pEntity
.getForeignPrice()).setScale(as.getPricePrecision(), as.getRoundingMode()));
}
pEntity.setItsCost(pEntity.getForeignPrice().multiply(exchRate)
.setScale(as.getPricePrecision(), as.getRoundingMode()));
} else {
pEntity.setItsCost(pEntity.getInvItem().getKnownCost());
}
if (txRules == null || pEntity.getItsOwner().getPriceIncTax()) {
pEntity.setItsTotal(pEntity.getItsQuantity().multiply(pEntity
.getItsCost()).setScale(as.getPricePrecision(), as.getRoundingMode()));
} else {
pEntity.setSubtotal(pEntity.getItsQuantity().multiply(pEntity
.getItsCost()).setScale(as.getPricePrecision(), as.getRoundingMode()));
}
} else {
//using user passed values:
if (pEntity.getItsOwner().getForeignCurrency() != null) {
pEntity.setItsCost(pEntity.getForeignPrice().multiply(exchRate)
.setScale(as.getPricePrecision(), as.getRoundingMode()));
if (txRules == null || pEntity.getItsOwner().getPriceIncTax()) {
pEntity.setItsTotal(pEntity.getForeignTotal().multiply(exchRate)
.setScale(as.getPricePrecision(), as.getRoundingMode()));
} else {
pEntity.setSubtotal(pEntity.getForeignSubtotal().multiply(
exchRate).setScale(as.getPricePrecision(), as.getRoundingMode()));
}
}
}
this.utlInvLine.makeLine(pReqVars, pEntity, as, txRules);
}
//draw or reverse warehouse entries:
srvWarehouseEntry.load(pReqVars, pEntity, pEntity.getWarehouseSite());
// optimistic locking (dirty check):
Long ownerVersion = Long.valueOf(pRequestData
.getParameter(PurchaseInvoice.class.getSimpleName() + ".ownerVersion"));
pEntity.getItsOwner().setItsVersion(ownerVersion);
this.utlInvLine.makeTotals(pReqVars, pEntity, as, txRules);
pReqVars.put("nextEntity", pEntity.getItsOwner());
pReqVars.put("nameOwnerEntity", PurchaseInvoice.class.getSimpleName());
return null;
} else {
throw new ExceptionWithCode(ExceptionWithCode.FORBIDDEN,
"edit_not_allowed::" + pReqVars.get("user"));
}
} |
java | void choose_smartly(int ndocs, List<Document> docs)
{
int siz = size();
double[] closest = new double[siz];
if (siz < ndocs)
ndocs = siz;
int index, count = 0;
index = random.nextInt(siz); // initial center
docs.add(documents_.get(index));
++count;
double potential = 0.0;
for (int i = 0; i < documents_.size(); i++)
{
double dist = 1.0 - SparseVector.inner_product(documents_.get(i).feature(), documents_.get(index).feature());
potential += dist;
closest[i] = dist;
}
// choose each center
while (count < ndocs)
{
double randval = random.nextDouble() * potential;
for (index = 0; index < documents_.size(); index++)
{
double dist = closest[index];
if (randval <= dist)
break;
randval -= dist;
}
if (index == documents_.size())
index--;
docs.add(documents_.get(index));
++count;
double new_potential = 0.0;
for (int i = 0; i < documents_.size(); i++)
{
double dist = 1.0 - SparseVector.inner_product(documents_.get(i).feature(), documents_.get(index).feature());
double min = closest[i];
if (dist < min)
{
closest[i] = dist;
min = dist;
}
new_potential += min;
}
potential = new_potential;
}
} |
python | def sense_tta(self, target):
"""Activate the RF field and probe for a Type A Target.
The PN531 can discover some Type A Targets (Type 2 Tag and
Type 4A Tag) at 106 kbps. Type 1 Tags (Jewel/Topaz) are
completely unsupported. Because the firmware does not evaluate
the SENS_RES before sending SDD_REQ, it may be that a warning
message about missing Type 1 Tag support is logged even if a
Type 2 or 4A Tag was present. This typically happens when the
SDD_RES or SEL_RES are lost due to communication errors
(normally when the tag is moved away).
"""
target = super(Device, self).sense_tta(target)
if target and target.sdd_res and len(target.sdd_res) > 4:
# Remove the cascade tag(s) from SDD_RES, only the PN531
# has them included and we've set the policy that cascade
# tags are not part of the sel_req/sdd_res parameters.
if len(target.sdd_res) == 8:
target.sdd_res = target.sdd_res[1:]
elif len(target.sdd_res) == 12:
target.sdd_res = target.sdd_res[1:4] + target.sdd_res[5:]
# Also the SENS_RES bytes are reversed compared to PN532/533
target.sens_res = bytearray(reversed(target.sens_res))
return target |
python | def marginal_zero(repertoire, node_index):
"""Return the marginal probability that the node is OFF."""
index = [slice(None)] * repertoire.ndim
index[node_index] = 0
return repertoire[tuple(index)].sum() |
python | def __init_go2nt_w_usr(self, gos_all, usr_go2nt, prt_flds_all):
"""Combine GO object fields and format_txt."""
assert usr_go2nt, "go2nt HAS NO ELEMENTS"
from goatools.nt_utils import get_unique_fields
go2nts = [usr_go2nt, self.gosubdag.go2nt, self._get_go2nthdridx(gos_all)]
usr_nt_flds = next(iter(usr_go2nt.values()))._fields # Get any single value from a dict
flds = get_unique_fields([usr_nt_flds, prt_flds_all])
go2nt = get_dict_w_id2nts(gos_all, go2nts, flds)
return self._init_go2nt_aug(go2nt) |
python | def _ep_pairwise(
n_items, comparisons, alpha, match_moments, max_iter, initial_state):
"""Compute a distribution of model parameters using the EP algorithm.
Raises
------
RuntimeError
If the algorithm does not converge after ``max_iter`` iterations.
"""
# Static variable that allows to check the # of iterations after the call.
_ep_pairwise.iterations = 0
m = len(comparisons)
prior_inv = alpha * np.eye(n_items)
if initial_state is None:
# Initially, mean and covariance come from the prior.
mean = np.zeros(n_items)
cov = (1 / alpha) * np.eye(n_items)
# Initialize the natural params in the function space.
tau = np.zeros(m)
nu = np.zeros(m)
# Initialize the natural params in the space of thetas.
prec = np.zeros((n_items, n_items))
xs = np.zeros(n_items)
else:
tau, nu = initial_state
mean, cov, xs, prec = _init_ws(
n_items, comparisons, prior_inv, tau, nu)
for _ in range(max_iter):
_ep_pairwise.iterations += 1
# Keep a copy of the old parameters for convergence testing.
tau_old = np.array(tau, copy=True)
nu_old = np.array(nu, copy=True)
for i in nprand.permutation(m):
a, b = comparisons[i]
# Update mean and variance in function space.
f_var = cov[a,a] + cov[b,b] - 2 * cov[a,b]
f_mean = mean[a] - mean[b]
# Cavity distribution.
tau_tot = 1.0 / f_var
nu_tot = tau_tot * f_mean
tau_cav = tau_tot - tau[i]
nu_cav = nu_tot - nu[i]
cov_cav = 1.0 / tau_cav
mean_cav = cov_cav * nu_cav
# Moment matching.
logpart, dlogpart, d2logpart = match_moments(mean_cav, cov_cav)
# Update factor params in the function space.
tau[i] = -d2logpart / (1 + d2logpart / tau_cav)
delta_tau = tau[i] - tau_old[i]
nu[i] = ((dlogpart - (nu_cav / tau_cav) * d2logpart)
/ (1 + d2logpart / tau_cav))
delta_nu = nu[i] - nu_old[i]
# Update factor params in the weight space.
prec[(a, a, b, b), (a, b, a, b)] += delta_tau * MAT_ONE_FLAT
xs[a] += delta_nu
xs[b] -= delta_nu
# Update mean and covariance.
if abs(delta_tau) > 0:
phi = -1.0 / ((1.0 / delta_tau) + f_var) * MAT_ONE
upd_mat = cov.take([a, b], axis=0)
cov = cov + upd_mat.T.dot(phi).dot(upd_mat)
mean = cov.dot(xs)
# Recompute the global parameters for stability.
cov = inv_posdef(prior_inv + prec)
mean = cov.dot(xs)
if _converged((tau, nu), (tau_old, nu_old)):
return mean, cov
raise RuntimeError(
"EP did not converge after {} iterations".format(max_iter)) |
java | public Observable<List<SimilarFace>> findSimilarAsync(UUID faceId, FindSimilarOptionalParameter findSimilarOptionalParameter) {
return findSimilarWithServiceResponseAsync(faceId, findSimilarOptionalParameter).map(new Func1<ServiceResponse<List<SimilarFace>>, List<SimilarFace>>() {
@Override
public List<SimilarFace> call(ServiceResponse<List<SimilarFace>> response) {
return response.body();
}
});
} |
java | public void putUnsignedInt(long i) {
_buffer[_offset++] = (byte) (i >>> 24 & 0xff);
_buffer[_offset++] = (byte) (i >> 16);
_buffer[_offset++] = (byte) (i >> 8);
_buffer[_offset++] = (byte) i;
} |
python | def enable_glut(self, app=None):
""" Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from pydev_ipython.inputhookglut import glut_display_mode, \
glut_close, glut_display, \
glut_idle, inputhook_glut
if GUI_GLUT not in self._apps:
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut_display_mode)
# This is specific to freeglut
if bool(glut.glutSetOption):
glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
glut.glutCreateWindow(sys.argv[0])
glut.glutReshapeWindow(1, 1)
glut.glutHideWindow()
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
else:
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
self.set_inputhook(inputhook_glut)
self._current_gui = GUI_GLUT
self._apps[GUI_GLUT] = True |
python | def randomdate(year: int) -> datetime.date:
""" gives random date in year"""
if calendar.isleap(year):
doy = random.randrange(366)
else:
doy = random.randrange(365)
return datetime.date(year, 1, 1) + datetime.timedelta(days=doy) |
python | def meaning(phrase, source_lang="en", dest_lang="en", format="json"):
"""
make calls to the glosbe API
:param phrase: word for which meaning is to be found
:param source_lang: Defaults to : "en"
:param dest_lang: Defaults to : "en" For eg: "fr" for french
:param format: response structure type. Defaults to: "json"
:returns: returns a json object as str, False if invalid phrase
"""
base_url = Vocabulary.__get_api_link("glosbe")
url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang)
json_obj = Vocabulary.__return_json(url)
if json_obj:
try:
tuc_content = json_obj["tuc"] # "tuc_content" is a "list"
except KeyError:
return False
'''get meanings'''
meanings_list = Vocabulary.__parse_content(tuc_content, "meanings")
return Response().respond(meanings_list, format)
# print(meanings_list)
# return json.dumps(meanings_list)
else:
return False |
python | def sample_indexes(segyfile, t0=0.0, dt_override=None):
"""
Creates a list of values representing the samples in a trace at depth or time.
The list starts at *t0* and is incremented with am*dt* for the number of samples.
If a *dt_override* is not provided it will try to find a *dt* in the file.
Parameters
----------
segyfile : segyio.SegyFile
t0 : float
initial sample, or delay-recording-time
dt_override : float or None
Returns
-------
samples : array_like of float
Notes
-----
.. versionadded:: 1.1
"""
if dt_override is None:
dt_override = dt(segyfile)
return [t0 + t * dt_override for t in range(len(segyfile.samples))] |
python | def rmatrixquaternion(q):
"""Create a rotation matrix from q quaternion rotation.
Quaternions are typed as Numeric Python numpy.arrays of length 4.
"""
assert np.allclose(math.sqrt(np.dot(q,q)), 1.0)
x, y, z, w = q
xx = x*x
xy = x*y
xz = x*z
xw = x*w
yy = y*y
yz = y*z
yw = y*w
zz = z*z
zw = z*w
r00 = 1.0 - 2.0 * (yy + zz)
r01 = 2.0 * (xy - zw)
r02 = 2.0 * (xz + yw)
r10 = 2.0 * (xy + zw)
r11 = 1.0 - 2.0 * (xx + zz)
r12 = 2.0 * (yz - xw)
r20 = 2.0 * (xz - yw)
r21 = 2.0 * (yz + xw)
r22 = 1.0 - 2.0 * (xx + yy)
R = np.array([[r00, r01, r02],
[r10, r11, r12],
[r20, r21, r22]], float)
assert np.allclose(np.linalg.det(R), 1.0)
return R |
java | @SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Map<String, String> argsMap = new HashMap<>();
for (int i = 0; i < args.length; i++) {
if (args[i].equals("help")) {
printHelp();
}
System.out.print("Argument: " + args[i]);
String[] splitArg = args[i].split("=");
if (splitArg.length == 2) {
System.out.println(" is valid");
argsMap.put(splitArg[0], splitArg[1]);
} else {
System.out.println(" is invalid");
}
}
StorageConfiguration config;
File configFile;
Class<? extends IBackend> backendClass;
Class<? extends IRevisioning> revisioningClass;
boolean create = false;
System.out.println("\nThis system provides more than one IP Address to advertise.\n");
Enumeration<NetworkInterface> interfaceEnum = NetworkInterface.getNetworkInterfaces();
NetworkInterface i;
int addressCounter = 0;
List<InetAddress> addresses = new ArrayList<InetAddress>();
while (interfaceEnum.hasMoreElements()) {
i = interfaceEnum.nextElement();
Enumeration<InetAddress> addressEnum = i.getInetAddresses();
InetAddress address;
while (addressEnum.hasMoreElements()) {
address = addressEnum.nextElement();
System.out.println("[" + addressCounter + "] " + address.getHostAddress());
addresses.add(address);
addressCounter++;
}
}
/*
* Getting the desired address from the command line.
* You can't automatically make sure to always use the correct
* host address.
*/
System.out.print("\nWhich one should be used?\nType in the number: ");
Integer chosenIndex = null;
while (chosenIndex == null) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
try {
chosenIndex = Integer.parseInt(line);
} catch (NumberFormatException nfe) {
chosenIndex = null;
}
}
String targetAddress = addresses.get(chosenIndex).getHostAddress();
System.out.println("Using ip address " + addresses.get(chosenIndex).getHostAddress());
if (argsMap.get("storagePath") != null) {
File file = new File(argsMap.get("storagePath"));
config = new StorageConfiguration(file);
} else {
// String file = Files.createTempDir().getAbsolutePath();
String file = "/tmp/tttarget";
config =
new StorageConfiguration(new File(new StringBuilder(file).append(File.separator)
.append("tnk").append(File.separator).append("path1").toString()));
}
if (argsMap.get("targetConfiguration") != null) {
configFile = new File(argsMap.get("targetConfiguration"));
} else {
configFile = TreetankConfiguration.CONFIGURATION_CONFIG_FILE;
}
if (argsMap.get("backendImplementation") != null) {
backendClass = (Class<? extends IBackend>)Class.forName(argsMap.get("backendImplementation"));
} else {
backendClass = CombinedStorage.class;
}
if (argsMap.get("revisioningImplementation") != null) {
revisioningClass =
(Class<? extends IRevisioning>)Class.forName(argsMap.get("revisioningImplementation"));
} else {
revisioningClass = SlidingSnapshot.class;
}
if (argsMap.get("create") != null) {
if(argsMap.get("create").toLowerCase().equals("true")){
create = true;
}
}
if(create){
Storage.truncateStorage(config);
IOUtils.recursiveDelete(config.mFile);
Storage.createStorage(config);
}
final String resourceName = "bench53473ResourcegraveISCSI9284";
// Guice Stuff for building the module
final Properties props = StandardSettings.getProps(config.mFile.getAbsolutePath(), resourceName);
final Injector injector =
Guice.createInjector(new ModuleSetter().setDataFacClass(BlockDataElementFactory.class)
.setMetaFacClass(ISCSIMetaPageFactory.class).setBackendClass(backendClass)
.setRevisioningClass(revisioningClass).createModule());
final IResourceConfigurationFactory resFac =
injector.getInstance(IResourceConfigurationFactory.class);
final ResourceConfiguration resConf = resFac.create(props);
final IStorage db = Storage.openStorage(config.mFile);
db.createResource(resConf);
final ISession session = db.getSession(new SessionConfiguration(resourceName, StandardSettings.KEY));
TargetServer target =
new TargetServer(TreetankConfiguration.create(TreetankConfiguration.CONFIGURATION_SCHEMA_FILE,
configFile, session, targetAddress));
target.call();
} |
java | @Override
public RotateIngestEndpointCredentialsResult rotateIngestEndpointCredentials(RotateIngestEndpointCredentialsRequest request) {
request = beforeClientExecution(request);
return executeRotateIngestEndpointCredentials(request);
} |
python | def power(attrs, inputs, proto_obj):
"""Returns element-wise result of base element raised to powers from exp element."""
new_attrs = translation_utils._fix_attribute_names(attrs, {'exponent':'exp'})
if 'broadcast' in attrs:
new_attrs = translation_utils._remove_attributes(new_attrs, ['broadcast'])
if attrs['broadcast'] == 1:
return 'broadcast_power', new_attrs, inputs
else:
mxnet_op = symbol.pow(inputs[0], inputs[1])
return mxnet_op, new_attrs, inputs
mxnet_op = symbol.broadcast_power(inputs[0], inputs[1])
return mxnet_op, new_attrs, inputs |
java | public static Database change_db_obj(final String host, final String port) throws DevFailed {
return apiutilDAO.change_db_obj(host, port);
} |
python | def make_plot(
self, count, plot=None, show=False, plottype='probability',
bar=dict(alpha=0.15, color='b', linewidth=1.0, edgecolor='b'),
errorbar=dict(fmt='b.'),
gaussian=dict(ls='--', c='r')
):
""" Convert histogram counts in array ``count`` into a plot.
Args:
count (array): Array of histogram counts (see
:meth:`PDFHistogram.count`).
plot (plotter): :mod:`matplotlib` plotting window. If ``None``
uses the default window. Default is ``None``.
show (boolean): Displayes plot if ``True``; otherwise returns
the plot. Default is ``False``.
plottype (str): The probabilities in each bin are plotted if
``plottype='probability'`` (default). The average probability
density is plot if ``plottype='density'``. The
cumulative probability is plotted if ``plottype=cumulative``.
bar (dictionary): Additional plotting arguments for the bar graph
showing the histogram. This part of the plot is omitted
if ``bar=None``.
errorbar (dictionary): Additional plotting arguments for the
errorbar graph, showing error bars on the histogram. This
part of the plot is omitted if ``errorbar=None``.
gaussian (dictionary): Additional plotting arguments for the
plot of the Gaussian probability for the |GVar| (``g``)
specified in the initialization. This part of the plot
is omitted if ``gaussian=None`` or if no ``g`` was
specified.
"""
if numpy.ndim(count) != 1:
raise ValueError('count must have dimension 1')
if plot is None:
import matplotlib.pyplot as plot
if len(count) == len(self.midpoints) + 2:
norm = numpy.sum(count)
data = numpy.asarray(count[1:-1]) / norm
elif len(count) != len(self.midpoints):
raise ValueError(
'wrong data length: %s != %s'
% (len(count), len(self.midpoints))
)
else:
data = numpy.asarray(count)
if plottype == 'cumulative':
data = numpy.cumsum(data)
data = numpy.array([0.] + data.tolist())
data_sdev = sdev(data)
if not numpy.all(data_sdev == 0.0):
data_mean = mean(data)
plot.errorbar(self.bins, data_mean, data_sdev, **errorbar)
if bar is not None:
plot.fill_between(self.bins, 0, data_mean, **bar)
# mean, +- 1 sigma lines
plot.plot([self.bins[0], self.bins[-1]], [0.5, 0.5], 'k:')
plot.plot([self.bins[0], self.bins[-1]], [0.158655254, 0.158655254], 'k:')
plot.plot([self.bins[0], self.bins[-1]], [0.841344746, 0.841344746], 'k:')
else:
if plottype == 'density':
data = data / self.widths
if errorbar is not None:
data_sdev = sdev(data)
if not numpy.all(data_sdev == 0.0):
data_mean = mean(data)
plot.errorbar(self.midpoints, data_mean, data_sdev, **errorbar)
if bar is not None:
plot.bar(self.bins[:-1], mean(data), width=self.widths, align='edge', **bar)
if gaussian is not None and self.g is not None:
# spline goes through the errorbar points for gaussian stats
if plottype == 'cumulative':
x = numpy.array(self.bins.tolist() + self.midpoints.tolist())
x.sort()
dx = (x - self.g.mean) / self.g.sdev
y = (erf(dx / 2**0.5) + 1) / 2.
yspline = cspline.CSpline(x, y)
plot.ylabel('cumulative probability')
plot.ylim(0, 1.0)
elif plottype in ['density', 'probability']:
x = self.bins
dx = (x - self.g.mean) / self.g.sdev
y = (erf(dx / 2**0.5) + 1) / 2.
x = self.midpoints
y = (y[1:] - y[:-1])
if plottype == 'density':
y /= self.widths
plot.ylabel('probability density')
else:
plot.ylabel('probability')
yspline = cspline.CSpline(x, y)
else:
raise ValueError('unknown plottype: ' + str(plottype))
if len(x) < 100:
ny = int(100. / len(x) + 0.5) * len(x)
else:
ny = len(x)
xplot = numpy.linspace(x[0], x[-1], ny)
plot.plot(xplot, yspline(xplot), **gaussian)
if show:
plot.show()
return plot |
python | def has_module (name, without_error=True):
"""Test if given module can be imported.
@param without_error: True if module must not throw any errors when importing
@return: flag if import is successful
@rtype: bool
"""
try:
importlib.import_module(name)
return True
except ImportError:
return False
except Exception:
# some modules raise errors when intitializing
return not without_error |
java | public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {
return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);
} |
python | def poll(self, poll_rate=None, timeout=None):
"""Return the status of a task or timeout.
There are several API calls that trigger asynchronous tasks, such as
synchronizing a repository, or publishing or promoting a content view.
It is possible to check on the status of a task if you know its UUID.
This method polls a task once every ``poll_rate`` seconds and, upon
task completion, returns information about that task.
:param poll_rate: Delay between the end of one task check-up and
the start of the next check-up. Defaults to
``nailgun.entity_mixins.TASK_POLL_RATE``.
:param timeout: Maximum number of seconds to wait until timing out.
Defaults to ``nailgun.entity_mixins.TASK_TIMEOUT``.
:returns: Information about the asynchronous task.
:raises: ``nailgun.entity_mixins.TaskTimedOutError`` if the task
completes with any result other than "success".
:raises: ``nailgun.entity_mixins.TaskFailedError`` if the task finishes
with any result other than "success".
:raises: ``requests.exceptions.HTTPError`` If the API returns a message
with an HTTP 4XX or 5XX status code.
"""
# See nailgun.entity_mixins._poll_task for an explanation of why a
# private method is called.
return _poll_task(
self.id, # pylint:disable=no-member
self._server_config,
poll_rate,
timeout
) |
python | def _ensure_session(self, session=None):
"""If provided session is None, lend a temporary session."""
if session:
return session
try:
# Don't make implicit sessions causally consistent. Applications
# should always opt-in.
return self.__start_session(True, causal_consistency=False)
except (ConfigurationError, InvalidOperation):
# Sessions not supported, or multiple users authenticated.
return None |
java | public void set(int left, int top, int right, int bottom) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
} |
java | public static Path get(String appName) {
final Path applicationDataDirectory = getPath(appName);
try {
Files.createDirectories(applicationDataDirectory);
} catch (IOException ioe) {
throw new RuntimeException("Couldn't find/create AppDataDirectory", ioe);
}
return applicationDataDirectory;
} |
java | @Nonnull
public static <T> T checkNotNull(T object, @Nonnull String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
} |
java | public ClusterListener createClusterListener(boolean localOnly) {
if (localOnly) return new NoClusterListener();
HazelcastInstance hazelcast = getHazelcastInstance(vertx);
if (hazelcast != null) {
return new HazelcastClusterListener(hazelcast, vertx);
} else {
return new NoClusterListener();
}
} |
python | def _start_watching_events(self, replace=False):
"""Start the events reflector
If replace=False and the event reflector is already running,
do nothing.
If replace=True, a running pod reflector will be stopped
and a new one started (for recovering from possible errors).
"""
return self._start_reflector(
"events",
EventReflector,
fields={"involvedObject.kind": "Pod"},
replace=replace,
) |
java | @Override
public void sendSubscriptionRequest(String fromParticipantId,
Set<DiscoveryEntryWithMetaInfo> toDiscoveryEntries,
SubscriptionRequest subscriptionRequest,
MessagingQos messagingQos) {
for (DiscoveryEntryWithMetaInfo toDiscoveryEntry : toDiscoveryEntries) {
MutableMessage message = messageFactory.createSubscriptionRequest(fromParticipantId,
toDiscoveryEntry.getParticipantId(),
subscriptionRequest,
messagingQos);
message.setLocalMessage(toDiscoveryEntry.getIsLocal());
if (subscriptionRequest instanceof MulticastSubscriptionRequest) {
String multicastId = ((MulticastSubscriptionRequest) subscriptionRequest).getMulticastId();
messageRouter.addMulticastReceiver(multicastId, fromParticipantId, toDiscoveryEntry.getParticipantId());
}
logger.debug("Send SubscriptionRequest: subscriptionId: {}, messageId: {}, proxy participantId: {}, provider participantId: {}",
subscriptionRequest.getSubscriptionId(),
message.getId(),
fromParticipantId,
toDiscoveryEntry.getParticipantId());
messageSender.sendMessage(message);
}
} |
java | public static <K, V> KeyValueSink<K, V> asMapSink(ImmutableMultimap.Builder<K, V> multimapB) {
return new ImmutableMultimapBuilderSink<>(multimapB);
} |
python | def variant(case_id, variant_id):
"""Show a single variant."""
case_obj = app.db.case(case_id)
variant = app.db.variant(case_id, variant_id)
if variant is None:
return abort(404, "variant not found")
comments = app.db.comments(variant_id=variant.md5)
template = 'sv_variant.html' if app.db.variant_type == 'sv' else 'variant.html'
return render_template(template, variant=variant, case_id=case_id,
comments=comments, case=case_obj) |
java | public BuildPhase withContexts(PhaseContext... contexts) {
if (this.contexts == null) {
setContexts(new java.util.ArrayList<PhaseContext>(contexts.length));
}
for (PhaseContext ele : contexts) {
this.contexts.add(ele);
}
return this;
} |
java | @Override
public Trigger.TriggerState getTriggerState(TriggerKey triggerKey, Jedis jedis){
final String triggerHashKey = redisSchema.triggerHashKey(triggerKey);
Pipeline pipe = jedis.pipelined();
Map<RedisTriggerState, Response<Double>> scores = new HashMap<>(RedisTriggerState.values().length);
for (RedisTriggerState redisTriggerState : RedisTriggerState.values()) {
scores.put(redisTriggerState, pipe.zscore(redisSchema.triggerStateKey(redisTriggerState), triggerHashKey));
}
pipe.sync();
for (Map.Entry<RedisTriggerState, Response<Double>> entry : scores.entrySet()) {
if(entry.getValue().get() != null){
return entry.getKey().getTriggerState();
}
}
return Trigger.TriggerState.NONE;
} |
python | async def xgroup_destroy(self, name: str, group: str) -> int:
"""
[NOTICE] Not officially released yet
XGROUP is used in order to create, destroy and manage consumer groups.
:param name: name of the stream
:param group: name of the consumer group
"""
return await self.execute_command('XGROUP DESTROY', name, group) |
java | @Override
public EClass getIfcAirTerminalBoxType() {
if (ifcAirTerminalBoxTypeEClass == null) {
ifcAirTerminalBoxTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(12);
}
return ifcAirTerminalBoxTypeEClass;
} |
java | public Stream<BASE> getUnmatchedBases() {
return bases.stream().filter(base -> !baseToRaw.containsKey(base));
} |
java | public AptField getField(String name)
{
for (AptField field : _controls)
if (field.getName().equals(name))
return field;
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.