language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def congestionControl(Cause_presence=0):
"""CONGESTION CONTROL Section 9.3.4"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x39) # 00111001
c = CongestionLevelAndSpareHalfOctets()
packet = a / b / c
if Cause_presence is 1:
e = CauseHdr(ieiC=0x08, eightBitC=0x0)
packet = packet / e... |
java | public static CipherUtil buildInstance(PrivateKey privateKey, PublicKey publicKey) {
return new AsymmetricCipher(new String(BASE_64.encrypt(privateKey.getEncoded())) + ":"
+ new String(BASE_64.encrypt(publicKey.getEncoded())),
Algorithms.RSA, privateKey, publicKey... |
java | private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
} |
python | def deploy(self, ids):
"""
Method to deploy vip's
:param vips: List containing vip's desired to be deployed on equipment
:return: None
"""
url = build_uri_with_ids('api/v3/vip-request/deploy/%s/', ids)
return super(ApiVipRequest, self).post(url) |
python | def _spectrogram_mono(self, x):
'''x.shape : (None, 1, len_src),
returns 2D batch of a mono power-spectrogram'''
x = K.permute_dimensions(x, [0, 2, 1])
x = K.expand_dims(x, 3) # add a dummy dimension (channel axis)
subsample = (self.n_hop, 1)
output_real = K.conv2d(x, se... |
python | def log_sum_exp_ab(a, b):
"""log_sum_exp for two scalars.
Parameters
----------
a, b: float
Returns
-------
c: float
c = log(e^a + e^b)
"""
if a > b:
return a + np.log(1. + np.exp(b - a))
else:
return b + np.log(1. + np.exp(a - b)) |
python | def archive_context(filename):
"""
Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after.
"""
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
with ContextualZipFile(fil... |
python | def endpoint_type(self, endpoint_type):
"""
Sets the endpoint_type of this DeviceData.
The endpoint type of the device. For example, the device is a gateway.
:param endpoint_type: The endpoint_type of this DeviceData.
:type: str
"""
if endpoint_type is not None a... |
java | @Override
public int compare(Point pointOne, Point pointTwo) {
if (pointOne == null) {
throw new JMetalException("PointOne is null") ;
} else if (pointTwo == null) {
throw new JMetalException("PointTwo is null") ;
} else if (pointOne.getDimension() != pointTwo.getDimension()) {
throw ne... |
java | protected boolean processSpecTopicInjectionErrors(final BuildData buildData, final BaseTopicWrapper<?> topic,
final List<String> customInjectionErrors) {
boolean valid = true;
if (!customInjectionErrors.isEmpty()) {
final String message = "Topic has referenced Topic/Level(s) " +... |
python | def resolve(self, pid, vendorSpecific=None):
"""See Also: resolveResponse()
Args:
pid:
vendorSpecific:
Returns:
"""
response = self.resolveResponse(pid, vendorSpecific)
return self._read_dataone_type_response(
response, 'ObjectLocationLi... |
python | def as_value(ele):
""" convert the specified element as a python value """
dtype = ele.datatype()
# print '%s = %s' % (ele.name(), dtype)
if dtype in (1, 2, 3, 4, 5, 6, 7, 9, 12):
# BOOL, CHAR, BYTE, INT32, INT64, FLOAT32, FLOAT64, BYTEARRAY, DECIMAL)
return ele.g... |
java | boolean run(Iterable<? extends Archive> archives,
Map<Location, Archive> locationMap)
{
this.locationToArchive.putAll(locationMap);
// traverse and analyze all dependencies
for (Archive archive : archives) {
Dependences deps = new Dependences(archive, type);
... |
java | public RetryTemplateBuilder withListeners(List<RetryListener> listeners) {
for (final RetryListener listener : listeners) {
Assert.notNull(listener, "Listener should not be null");
}
listenersList().addAll(listeners);
return this;
} |
java | private String[] normalize( String[] list, int minlength )
{
if ( list.length < minlength )
{
// Need to do padding
String[] newlist = new String[minlength];
System.arraycopy( list, 0, newlist, 0, list.length );
Arrays.fill( newlist, list.length, newli... |
python | def controlled(num_ptr_bits, U):
"""
Given a one-qubit gate matrix U, construct a controlled-U on all pointer
qubits.
"""
d = 2 ** (1 + num_ptr_bits)
m = np.eye(d)
m[d - 2:, d - 2:] = U
return m |
java | public Set<String> toStringSet(Set<ModificationFeature> set)
{
List<ModificationFeature> list = new ArrayList<ModificationFeature>(set);
Collections.sort(list, new Comparator<ModificationFeature>()
{
@Override
public int compare(ModificationFeature o1, ModificationFeature o2)
{
String t1 = getModif... |
java | @Override
protected void horizontal() {
float[] dataX = derivX.data;
float[] dataY = derivY.data;
float[] hXX = horizXX.data;
float[] hXY = horizXY.data;
float[] hYY = horizYY.data;
final int imgHeight = derivX.getHeight();
final int imgWidth = derivX.getWidth();
int windowWidth = radius * 2 + 1;
... |
java | private JavaColonNamespaceBindings<EJBBinding> getModuleBindingMap(ModuleMetaData mmd) {
@SuppressWarnings("unchecked")
JavaColonNamespaceBindings<EJBBinding> bindingMap = (JavaColonNamespaceBindings<EJBBinding>) mmd.getMetaData(mmdSlot);
if (bindingMap == null) {
bindingMap = new Ja... |
java | private boolean validateSignature(Credentials credentials, String secretKey) {
String clientSignature = credentials.getSignature();
String serverSignature = createSignature(credentials, secretKey);
return MessageDigest.isEqual(clientSignature.getBytes(), serverSignature.getBytes());
} |
java | @Override
public void publish(LogRecord record) {
// Convert Log
Throwable throwable = record.getThrown();
if (throwable != null) {
synchronized (ExceptionRepositoryAsMetrics.INSTANCE) {
// We would not include the message if already exceeded the exceptions limit
if (ExceptionReposit... |
java | public boolean matches(String pattern, String itemName) {
final int index = pattern.indexOf('*');
if (index == -1) {
return itemName.equals(pattern);
}
final String firstPart = pattern.substring(0, index);
if (!itemName.startsWith(firstPart)) {
return fal... |
java | public Observable<Page<VirtualMachineInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<VirtualMachineInner>>, Page<VirtualMachineInner>>() {
@Override
public Page<VirtualMachine... |
java | private void setTypeMappers(TypeMapper[] typeMappers) throws SQLException {
if (typeMappers.length > 0) {
Map<String, Class<?>> mappers = _connection.getTypeMap();
for (TypeMapper t : typeMappers) {
mappers.put(t.UDTName(), t.mapperClass());
}
_co... |
python | def _clear(self):
"""
Clear the current canvas.
"""
# It's orders of magnitude faster to reset with a print like this
# instead of recreating the screen buffers.
(colour, attr, bg) = self.palette["background"]
self._canvas.clear_buffer(colour, attr, bg) |
python | def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset,
max_input_length, max_target_length,
fixed_train_length):
"""Normalize the examples from different tasks so they can be merged.
This function is specific to NLP tasks and normalizes them... |
java | public boolean removeEventListener(IEventListener listener) {
log.debug("removeEventListener - scope: {} {}", getName(), listener);
if (log.isTraceEnabled()) {
log.trace("Listeners - check #1: {}", listeners);
}
boolean removed = listeners.remove(listener);
if (... |
java | protected JavaSource getJavaSourceForClass(String clazzname) {
String resource = clazzname.replaceAll("\\.", "/") + ".java";
FileObject fileObject = classPath.findResource(resource);
if (fileObject == null) {
return null;
}
Project project = FileOwnerQuery.getOwner(fileObject);
if (project... |
java | public static <Head, Tail extends HList> HCons<Head, Tail> cons(Head head, Tail tail) {
return new HCons<>(head, tail);
} |
python | def get_distance_function(distance):
"""
Returns the distance function from the string name provided
:param distance: The string name of the distributions
:return:
"""
# If we provided distance function ourselves, use it
if callable(distance):
return distance
try:
return... |
java | protected final void paintChildren(final Container container,
final WebXmlRenderContext renderContext) {
final int size = container.getChildCount();
for (int i = 0; i < size; i++) {
WComponent child = container.getChildAt(i);
child.paint(renderContext);
}
} |
python | def consume(iterator: Iterator[T], n: Optional[int] = None) -> None:
"""Advance the iterator n-steps ahead. If n is None, consume entirely."""
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxl... |
python | def weather_from_dictionary(d):
"""
Builds a *Weather* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Weather* instance
:... |
java | void setRightChild(final byte b, @NotNull final MutableNode child) {
final ChildReference right = children.getRight();
if (right == null || (right.firstByte & 0xff) != (b & 0xff)) {
throw new IllegalArgumentException();
}
children.setAt(children.size() - 1, new ChildReference... |
python | def remove_context(self, name):
"""Remove a context from the suite.
Args:
name (str): Name of the context to remove.
"""
self._context(name)
del self.contexts[name]
self._flush_tools() |
java | public void marshall(Host host, ProtocolMarshaller protocolMarshaller) {
if (host == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(host.getSourcePath(), SOURCEPATH_BINDING);
} catch (Excepti... |
java | public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)
{
TimeUnit result = defaultValue;
if (value != null)
{
switch (value.intValue())
{
case 3:
case 35:
{
result = TimeUnit.MINUTES;
... |
python | def commit_index(self, message):
"""
Commit the current index.
:param message: str
:return: str the generated commit sha
"""
tree_id = self.write_tree()
args = ['commit-tree', tree_id, '-p', self.ref_head]
# todo, this can end in a race-condition with ot... |
python | def _set_value(self, slot_record):
"""Sets the value of this slot based on its corresponding _SlotRecord.
Does nothing if the slot has not yet been filled.
Args:
slot_record: The _SlotRecord containing this Slot's value.
"""
if slot_record.status == _SlotRecord.FILLED:
self.filled = Tr... |
python | def split_matrix(M, contigs):
"""Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple chromosome matrix to be split
... |
python | def reset(self):
"""Reset the view."""
self.pan = (0., 0.)
self.zoom = self._default_zoom
self.update() |
python | def password_attributes_character_restriction_lower(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa")
character_restriction = ET.SubElement(passwor... |
python | def get(self, task_id):
'''taobao.topats.result.get 获取异步任务结果
使用指南:http://open.taobao.com/doc/detail.htm?id=30
- 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以
- 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态
- 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topat... |
java | MutableBigInteger modInverseMP2(int k) {
if (isEven())
throw new ArithmeticException("Non-invertible. (GCD != 1)");
if (k > 64)
return euclidModInverse(k);
int t = inverseMod32(value[offset+intLen-1]);
if (k < 33) {
t = (k == 32 ? t : t & ((1 << k) ... |
java | public OutlierResult run(Relation<V> relation) {
final int dim = RelationUtil.dimensionality(relation);
final ArrayDBIDs ids = DBIDUtil.ensureArray(relation.getDBIDs());
svm.svm_set_print_string_function(LOG_HELPER);
svm_parameter param = new svm_parameter();
param.svm_type = svm_parameter.ONE_CLA... |
java | public void doAddListener(BaseListener listener)
{
if (m_listener != null)
m_listener.doAddListener((FileListener)listener);
else
m_listener = (FileListener)listener;
boolean bOldState = listener.setEnabledListener(false); // To disable recursive forever loop!
... |
java | public JSONObject element( String key, boolean value ) {
verifyIsNull();
return element( key, value ? Boolean.TRUE : Boolean.FALSE );
} |
python | def connected(self):
"""
Returns :py:data:`True` if the graph's every node can be reached from every
other node.
"""
node_list = self.node_list()
for node in node_list:
bfs_list = self.forw_bfs(node)
if len(bfs_list) != len(node_list):
... |
java | public void verifyAccountWithCode(String verificationCode, String signalingKey, int signalProtocolRegistrationId, boolean fetchesMessages, String pin,
byte[] unidentifiedAccessKey, boolean unrestrictedUnidentifiedAccess)
throws IOException
{
this.pushServiceSocket.verifyA... |
java | static String scrubModel(String manufacturer, String model) {
if (manufacturer == null || model == null) {
return model;
}
if (model.regionMatches(true, 0, manufacturer, 0, manufacturer.length())) {
model = model.substring(manufacturer.length());
}
if (model.length() > 0 && (model.charAt... |
python | def cmd_ip_counter(self):
"""Reports a breakdown of how many requests have been made per IP.
.. note::
To enable this command requests need to provide a header with the
forwarded IP (usually X-Forwarded-For) and be it the only header
being captured.
"""
ip_... |
python | def i4_bit_lo0(n):
"""
I4_BIT_LO0 returns the position of the low 0 bit base 2 in an integer.
Example:
+------+------------+----
| N | Binary | BIT
+------+------------+----
| 0 | 0 | 1
| 1 | 1 | 2
| 2 | 10 | 1
| 3... |
python | def _get_method(method):
"""Return an imported object.
:param method: ``str`` DOT notation for import with Colin used to
separate the class used for the job.
:returns: ``object`` Loaded class object from imported method.
"""
# Split the class out ... |
java | private void build_info_as_str(int index)
{
//
// Convert time to a string
//
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SS");
sdf.setTimeZone(TimeZone.getTimeZone("ECT"));
String da = sdf.format(box[index].when);
elt_str = new StringBuffer(da);
//
// Add request type and comman... |
python | def exists(self, key, **opts):
"""Return if a key exists in the cache."""
key, store = self._expand_opts(key, opts)
data = store.get(key)
# Note that we do not actually delete the thing here as the max_age
# just for this call may have triggered a False.
if not data or se... |
java | protected boolean isFloatingPointNumber(Object val) {
if (val instanceof Float || val instanceof Double) {
return true;
}
if (val instanceof String) {
String string = (String) val;
return string.indexOf('.') != -1 || string.indexOf('e') != -1 || string.indexOf('E') != -1;
}
return ... |
java | public void setSSLSocketFactory(SSLSocketFactory sf) {
if (sf == null) {
throw new IllegalArgumentException(
"no SSLSocketFactory specified");
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkSetFactory();
}
... |
python | def get_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[CitationDict]:
"""Get the citation for a given edge."""
return self._get_edge_attr(u, v, key, CITATION) |
java | public boolean getDefinedHere() {
if (Abbreviation_Type.featOkTst && ((Abbreviation_Type)jcasType).casFeat_definedHere == null)
jcasType.jcas.throwFeatMissing("definedHere", "de.julielab.jules.types.Abbreviation");
return jcasType.ll_cas.ll_getBooleanValue(addr, ((Abbreviation_Type)jcasType).casFeatCode_d... |
java | public ForeignKey<JoinTable<T>> getOrCreateInverseForeignKey()
{
Node node = childNode.getOrCreate("inverse-foreign-key");
ForeignKey<JoinTable<T>> inverseForeignKey = new ForeignKeyImpl<JoinTable<T>>(this, "inverse-foreign-key", childNode, node);
return inverseForeignKey;
} |
python | def _get_ids_from_name_private(self, name):
"""Get private images which match the given name."""
results = self.list_private_images(name=name)
return [result['id'] for result in results] |
python | def to_array(self, variables):
"""
Converts the clamping to a 1-D array with respect to the given variables
Parameters
----------
variables : list[str]
List of variables names
Returns
-------
`numpy.ndarray`_
1-D array where posi... |
python | def change_status(self, **kwargs):
"""
Set name, persona state, flags
.. note::
Changing persona state will also change :attr:`persona_state`
:param persona_state: persona state (Online/Offlane/Away/etc)
:type persona_state: :class:`.EPersonaState`
:param pl... |
java | public int run(String[] args) throws ParseException, IOException,
ClassNotFoundException, InterruptedException {
Configuration hbaseConf = HBaseConfiguration.create(getConf());
hdfs = FileSystem.get(hbaseConf);
// Grab input args and allow for -Dxyz style arguments
String[] otherArgs =
n... |
java | public int codePointConversion(String fontName, int codePoint) {
NonStandardFontFamily nonStandardFontFamily = get(fontName);
if (nonStandardFontFamily == null)
return codePoint;
CodePointSet codePointSet = nonStandardFontFamily.getCodePointSet();
if (codePointSet == null)
... |
java | public static final List<String> getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){
List<String> lst = new ArrayList<String>();
if ( aligPos > 1) {
System.err.println("multiple alignments not supported yet!");
return lst;
}
int blockNum = afpChain.getBlockNum();
int[] optLen = afpChain.getOptLen(... |
java | public DescribeScheduledActionsRequest withScheduledActionNames(String... scheduledActionNames) {
if (this.scheduledActionNames == null) {
setScheduledActionNames(new com.amazonaws.internal.SdkInternalList<String>(scheduledActionNames.length));
}
for (String ele : scheduledActionName... |
java | public EClass getIfcShearModulusMeasure() {
if (ifcShearModulusMeasureEClass == null) {
ifcShearModulusMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(736);
}
return ifcShearModulusMeasureEClass;
} |
python | def getMetadata(self, remote, address, key):
"""Get metadata of device"""
if self._server is not None:
# pylint: disable=E1121
return self._server.getAllMetadata(remote, address, key) |
python | def get_book_hierarchy_design_session(self, proxy):
"""Gets the ``OsidSession`` associated with the book hierarchy design service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.commenting.BookHierarchyDesignSession) - a
``BookHierarchyDesignSession``
raise: Nu... |
python | def add(self, address, topics=None):
"""Add *address* to the subscribing list for *topics*.
It topics is None we will subscibe to already specified topics.
"""
with self._lock:
if address in self.addresses:
return False
topics = self._magickfy_to... |
java | public static UniversalIdIntQueueMessage newInstance(byte[] content) {
UniversalIdIntQueueMessage msg = newInstance();
msg.setContent(content);
return msg;
} |
python | def add_packet(self, packet):
"""Add a packet to this flow"""
# First packet?
if not self.meta['flow_id']:
self.meta['flow_id'] = flow_tuple(packet)
self.meta['src'] = self.meta['flow_id'][0]
self.meta['dst'] = self.meta['flow_id'][1]
self.meta['s... |
python | def process_pending_config_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_config_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-config-topic`` directives.
See also
--------
`config_ref_role`
`ConfigTopicTargetDirective`
`pendin... |
java | public Map<String[], String> getErrors(String entityId) {
return m_errors != null ? m_errors.get(entityId) : null;
} |
python | def view_history_source(name, gitref=None):
"""Serve a page name from git repo (an old version of a page).
then return the reST source code
This function does not use any template it returns only plain text
.. note:: this is a bottle view
* this is a GET only method : you can not change a ... |
java | @Override public void syncCacheToDB(List<Integer> idList) throws IOException {
final SQLiteDatabase database = sqLiteHelper.getWritableDatabase();
database.beginTransaction();
try {
for (Integer id : idList) {
syncCacheToDB(id);
}
database.setT... |
java | private static Channel createChannel() throws IOException {
// dup the file descriptor - we do this so that for two reasons :-
// 1. Avoids any timing issues with FileDescriptor.in being closed
// or redirected while we create the channel.
// 2. Allows streams based on file descripto... |
python | def get_multiple_layers(self, layer_name):
"""
Returns a list of all the layers in the packet that are of the layer type (an incase-sensitive string).
This is in order to retrieve layers which appear multiple times in the same packet (i.e. double VLAN) which cannot be
retrieved by easier... |
python | def _createGeometry(self, session, spatialReferenceID):
"""
Create PostGIS geometric objects
"""
# Flush the current session
session.flush()
# Create geometry for each fluvial link
for link in self.getFluvialLinks():
# Retrieve the nodes for each lin... |
java | public static final int getMaxAllowedKeyLength(String transformation)
throws NoSuchAlgorithmException {
// Android-changed: Remove references to CryptoPermission and throw early
// if transformation == null or isn't valid.
//
// CryptoPermission cp = getConfiguredPermission(t... |
java | public SendMessageBatchResult sendMessageBatch(String queueUrl, List<SendMessageBatchRequestEntry> entries) {
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(queueUrl, entries);
return sendMessageBatch(sendMessageBatchRequest);
} |
java | public static void validateUTF8(byte[] utf8, int start, int len) throws MalformedInputException {
int count = start;
int leadByte = 0;
int length = 0;
int state = LEAD_BYTE;
while (count < start + len) {
int aByte = ((int) utf8[count] & 0xFF);
switch (sta... |
java | public void setRow(int row, DoubleVector values) {
checkIndices(row, 0);
AtomicVector rowEntry = getRow(row, values.length() - 1, true);
denseArrayReadLock.lock();
Vectors.copy(rowEntry, values);
denseArrayReadLock.unlock();
} |
java | void readMetadata(DataInputStream in, VersionAndOpcode versionAndOpcode)
throws IOException {
ReadMetadataHeader readMetadataHeader =
new ReadMetadataHeader(versionAndOpcode);
readMetadataHeader.readFields(in);
final int namespaceId = readMetadataHeader.getNamespaceId();
Block block = new... |
java | public static List<CPMeasurementUnit> toModels(
CPMeasurementUnitSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<CPMeasurementUnit> models = new ArrayList<CPMeasurementUnit>(soapModels.length);
for (CPMeasurementUnitSoap soapModel : soapModels) {
models.add(toModel(soapModel));
}
... |
java | @Override
public DescribeDocumentVersionsResult describeDocumentVersions(DescribeDocumentVersionsRequest request) {
request = beforeClientExecution(request);
return executeDescribeDocumentVersions(request);
} |
python | def totsv(table, source=None, encoding=None, errors='strict',
write_header=True, **csvargs):
"""
Convenience function, as :func:`petl.io.csv.tocsv` but with different
default dialect (tab delimited).
"""
csvargs.setdefault('dialect', 'excel-tab')
return tocsv(table, source=source, en... |
python | def python_2_unicode_compatible(klass):
"""Fix __str__, __unicode__ and __repr__ methods under Python 2."""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("Define __str__() on %s to use @python_2_unicode_compatible" % klass.__name__)
if '__repr__' not in klass.__dic... |
python | def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.state = u'WARNING'
elif self.initial_state == 'u':
self.state = u'UNKNOWN'
elif self.initial_state == 'c':
... |
python | def get_result(self, errors=GRACEFUL, **params):
"""
Get all results, no filtering, etc. by creating and polling the
session.
"""
additional_params = self.get_additional_params(**params)
return self.poll_session(
self.create_session(**params),
erro... |
python | def _add_products(self, tile, show_all=False):
"""Add all products from a tile into our product map."""
products = tile.products
unique_id = tile.unique_id
base_path = tile.output_folder
for prod_path, prod_type in products.items():
# We need to handle include_direc... |
python | def add_node(self, name, desc, layout, node_x, node_y):
"""
Add a node to a network.
"""
existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first()
if existing_node is not None:
raise HydraError("A node with name %s is alre... |
python | def find_op_code_sequence(pattern: list, instruction_list: list) -> Generator:
"""Returns all indices in instruction_list that point to instruction
sequences following a pattern.
:param pattern: The pattern to look for, e.g. [["PUSH1", "PUSH2"], ["EQ"]] where ["PUSH1", "EQ"] satisfies pattern
:param in... |
java | public static double kolmogorov(double z) {
//Kolmogorov distribution. Error<.0000001
if (z<0.27) {
return 0.0;
}
else if (z>3.2) {
return 1.1;
}
double ks=0;
double y=-2*z*z;
for(int i=27;i>=1;i=i-2) {
ks=Math.exp(i*... |
java | public Tree createPingPacket(String id) {
FastBuildTree msg = new FastBuildTree(4);
msg.putUnsafe("ver", PROTOCOL_VERSION);
msg.putUnsafe("sender", nodeID);
msg.putUnsafe("id", id);
msg.putUnsafe("time", System.currentTimeMillis());
return msg;
} |
python | def stft_from_frames(frames, window='hann', dtype=np.complex64):
"""
Variation of the librosa.core.stft function,
that computes the short-time-fourier-transfrom from frames instead from the signal.
See http://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#stft
"""
win_length = f... |
python | def merge_dicts(*ds):
"""Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Notes
-----
http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression
"""
result = ds[0]
for d in ds... |
java | private static byte[] readBytes(BufferedReader reader, String endMarker) throws IOException
{
String line = null;
StringBuilder buf = new StringBuilder();
while ((line = reader.readLine()) != null)
{
if (line.contains(endMarker)) {
return Base6... |
java | @Override
public CreatePlacementGroupResult createPlacementGroup(CreatePlacementGroupRequest request) {
request = beforeClientExecution(request);
return executeCreatePlacementGroup(request);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.