language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @GetMapping(path = {"/otp/qrgen"})
public void generate(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
response.setContentType("image/png");
val key = request.getParameter("key");
QRUtils.generateQRCode(response.getOutputStream(), key, QRUtils.WIDTH_... |
python | def _encode_time(mtime: float):
"""Encode a mtime float as a 32-bit FAT time"""
dt = arrow.get(mtime)
dt = dt.to("local")
date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day
secs = dt.second + dt.microsecond / 10**6
time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2)
... |
python | def list_projects(root, backend=os.listdir):
"""List projects at `root`
Arguments:
root (str): Absolute path to the `be` root directory,
typically the current working directory.
"""
projects = list()
for project in sorted(backend(root)):
abspath = os.path.join(root, pro... |
java | public Boolean deleteEntityPost(DeleteEntityRequest request) throws ApiException {
ApiResponse<Boolean> resp = deleteEntityPostWithHttpInfo(request);
return resp.getData();
} |
java | public static Descriptor getDescriptor(Class<?> cls) throws IOException {
String idl = ProtobufIDLGenerator.getIDL(cls);
ProtoFile file = ProtoParser.parse(ProtobufIDLProxy.DEFAULT_FILE_NAME, idl);
FileDescriptorProtoPOJO fileDescriptorProto = new FileDescriptorProtoPOJO();
fil... |
python | def draw_axes(self):
"""
Removes all existing series and re-draws the axes.
:return: None
"""
self.canvas.delete('all')
rect = 50, 50, self.w - 50, self.h - 50
self.canvas.create_rectangle(rect, outline="black")
for x in self.frange(0, self.x_max - self... |
java | public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
try {
if (com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerServiceInterface.class.isAssignableFrom(serviceEndpointInterface)) {
com.google.api.ads.adwords.axis.v201809.mcm... |
python | def not_as_alias_handler(names_list):
"""Returns a list of names ignoring any aliases."""
list_ = list()
for alias in names_list:
list_.append(alias.name)
return list_ |
python | def register_pb_devices(num_pbs: int = 100):
"""Register PBs devices.
Note(BMo): Ideally we do not want to register any devices here. There
does not seem to be a way to create a device server with no registered
devices in Tango. This is (probably) because Tango devices must have been
registered bef... |
java | public Connection<?> completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
if (connectionFactory.supportsStateParameter()) {
verifyStateParameter(request);
}
String code = request.getParameter("code");
try {
AccessGrant accessGrant = connectionFactory.getOAuthOper... |
java | public Object deserialize(String data) {
if ((data == null) || (data.length() == 0)) {
return null;
}
ObjectInputStream ois = null;
ByteArrayInputStream bis = null;
try {
bis = new ByteArrayInputStream(Base64.decodeBase64(data.getBytes()));
ois = new ObjectInputStream(bis);
return ois.readObject()... |
python | def find_ds_mapping(data_source, es_major_version):
"""
Find the mapping given a perceval data source
:param data_source: name of the perceval data source
:param es_major_version: string with the major version for Elasticsearch
:return: a dict with the mappings (raw and enriched)
"""
mappin... |
java | public boolean add(AbstractRslNode node) {
if (_specifications == null) _specifications = new LinkedList();
return _specifications.add(node);
} |
java | @Override
public final void requestUpdate(final Transaction transaction) throws ProtocolException, TransactionException, SevereMessageStoreException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "requestUpdate", transaction);
PersistentTran... |
java | public void newName2ndData(String fieldName, String newFieldName, Object newFieldValue)throws Exception{
this.addFieldValue(newFieldName,newFieldValue);//将long类型的时间戳转换为Date类型
//忽略旧的名称
if(!fieldName.equals(newFieldName))
this.addIgnoreFieldMapping(fieldName);
} |
python | def run(self, switch_queue):
"""
每个controller需要提供run方法, 来提供启动
"""
self.switch_queue = switch_queue
self.quit = False
Thread(target=self._watchdog_queue).start()
Thread(target=self._watchdog_time).start() |
python | def parse_binary_descriptor(bindata, sensor_log=None):
"""Convert a binary streamer descriptor into a string descriptor.
Binary streamer descriptors are 20-byte binary structures that encode all
information needed to create a streamer. They are used to communicate
that information to an embedded devic... |
java | private void insertDefaultDifferentialListServers()
{
listeFilmlistenUrls_diff.add(new DatenFilmlisteUrl("http://m.picn.de/f/Filmliste-diff.xz", DatenFilmlisteUrl.SERVER_ART_DIFF));
listeFilmlistenUrls_diff.add(new DatenFilmlisteUrl("http://m1.picn.de/f/Filmliste-diff.xz", DatenFilmlisteUrl.SERVER_A... |
python | def set_flagged(self, *, start_date=None, due_date=None):
""" Sets this message as flagged
:param start_date: the start datetime of the followUp
:param due_date: the due datetime of the followUp
"""
self.__status = Flag.Flagged
start_date = start_date or dt.datetime.now()... |
python | def simulate_one(fw, name, size):
"""
Simulate a random sequence with name and size
"""
from random import choice
seq = Seq(''.join(choice('ACGT') for _ in xrange(size)))
s = SeqRecord(seq, id=name, description="Fake sequence")
SeqIO.write([s], fw, "fasta") |
python | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FieldContext for this FieldInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.field.FieldCo... |
python | def get_nameserver_detail_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
input = ET.SubElement(get_nameserver_detail, "input")
rb... |
java | public Object remove(Object key)
{
Object retVal = null;
if (null == key) throw new IllegalArgumentException("key must not be null");
if (this.containsKey(key))
{
retVal = super.remove(key);
for (int i = 0; i < this.order.size(); i++)
{
... |
python | def default_parser() -> argparse.ArgumentParser:
"""Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser(
prog=CONSOLE_SCRIPT,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
build_parser(parser)
return parser |
python | def to_sif(graph, output_path):
"""
Generates Simple Interaction Format output file from provided graph.
The SIF specification is described
`here <http://wiki.cytoscape.org/Cytoscape_User_Manual/Network_Formats>`_.
:func:`.to_sif` will generate a .sif file describing the network, and a few
.ed... |
java | protected String calculatePropertyName(String propertyName) {
String lastAlias = getLastAlias();
if (lastAlias != null) {
return lastAlias +'.'+propertyName;
}
return propertyName;
} |
python | def get_classes(module_label, classnames):
""" Imports a set of classes from a given module.
Usage::
get_classes('forum.models', ['Forum', 'ForumReadTrack', ])
"""
app_label = module_label.split('.')[0]
app_module_path = _get_app_module_path(module_label)
if not app_module_path:
... |
java | public PublicIPPrefixInner updateTags(String resourceGroupName, String publicIpPrefixName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, publicIpPrefixName).toBlocking().last().body();
} |
java | @Nullable
public final Folder findTargetFolder(@NotEmpty final String generatorName, @NotEmpty final String artifactName) {
Contract.requireArgNotEmpty("generatorName", generatorName);
Contract.requireArgNotEmpty("artifactName", artifactName);
if (parent == null) {
throw new... |
java | public static Reader uriReader(URI uri) throws IOException {
return new BufferedReader(new InputStreamReader(uri.toURL().openStream(), StandardCharsets.UTF_8));
} |
java | public int delete(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {
if (mappedDelete == null) {
mappedDelete = MappedDelete.build(dao, tableInfo);
}
int result = mappedDelete.delete(databaseConnection, data, objectCache);
if (dao != null && !localIsInBatchMode.get(... |
java | @Override
public int getInt(final int index) {
final int i = this.lowerBoundary + index;
checkIndex(i);
checkIndex(i + 3);
return (this.buffer[i] & 0xff) << 24 | (this.buffer[i + 1] & 0xff) << 16
| (this.buffer[i + 2] & 0xff) << 8 | (this.buffer[i + 3] & 0xff) << 0;
... |
java | synchronized void line(String line, long arrivalTime) {
if (count.incrementAndGet() % logCountFrequency == 0)
log.info("count=" + count.get() + ",buffer size=" + lines.size());
NmeaMessage nmea;
try {
nmea = NmeaUtil.parseNmea(line);
} catch (NmeaMessageParseException e) {
listener.invalidNmea(line, ... |
python | def nowrange(self, col, timeframe):
"""
Set the main dataframe with rows within a date range from now
ex: ds.nowrange("Date", "3D") for a 3 days range. Units are: S,
H, D, W, M, Y
"""
df = self._nowrange(col, timeframe)
if df is None:
self.err("Can not... |
python | def to_astropy_table(llwtable, apytable, copy=False, columns=None,
use_numpy_dtypes=False, rename=None):
"""Convert a :class:`~ligo.lw.table.Table` to an `~astropy.tableTable`
This method is designed as an internal method to be attached to
:class:`~ligo.lw.table.Table` objects as `__as... |
java | public MPSRGLength createMPSRGLengthFromString(EDataType eDataType, String initialValue) {
MPSRGLength result = MPSRGLength.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
} |
java | @Override
public void set( int row , int col , double value ) {
if( col < 0 || col >= numCols || row < 0 || row >= numRows ) {
throw new IllegalArgumentException("Specified element is out of bounds: ("+row+" , "+col+")");
}
data[ row * numCols + col ] = value;
} |
python | def log_stats(self):
"""Output the stats to the LOGGER."""
if not self.stats.get('counts'):
if self.consumers:
LOGGER.info('Did not receive any stats data from children')
return
if self.poll_data['processes']:
LOGGER.warning('%i process(es) di... |
java | @Deprecated
public static BoundingBox fromCoordinates(
@FloatRange(from = MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double west,
@FloatRange(from = MIN_LATITUDE, to = GeoJsonConstants.MAX_LATITUDE) double south,
@FloatRange(from = MIN_LONGITUDE, to = GeoJsonConstants.MAX_LONGITUDE) double east,
... |
java | @Override
public int compareTo(NodeInfo o) {
if (o == null) {
return 1;
} else {
return this.getHost().compareTo(o.getHost());
}
} |
python | def plot(self, axis=None, truncate_mode=None, p=0, vary_line_width=True,
cmap='viridis', colorbar=True):
"""Plot a dendrogram of the single linkage tree.
Parameters
----------
truncate_mode : str, optional
The dendrogram can be hard to read when the ... |
java | public void reset() {
// reset all offsets
this.numRecords = 0;
this.currentSortIndexOffset = 0;
this.currentDataBufferOffset = 0;
this.sortIndexBytes = 0;
// return all memory
returnToSegmentPool();
// grab first buffers
this.currentSortIndexSegment = nextMemorySegment();
this.sortIndex.add(this... |
java | private static Map<String, String> convertAdHocMonomersIntoSMILES(Map<String, String> monomersList) throws HELM1FormatException, ChemistryException {
Map<String, String> convert = new HashMap<String, String>();
try {
for (Map.Entry<String, String> element : monomersList.entrySet()) {
Monomer... |
java | public void setSubEntries(List<CmsClientSitemapEntry> children, I_CmsSitemapController controller) {
m_childrenLoadedInitially = true;
m_subEntries.clear();
if (children != null) {
m_subEntries.addAll(children);
for (CmsClientSitemapEntry child : children) {
... |
java | protected Future<?> callOnMessages(final List<? extends Message> messages) throws IllegalStateException {
if(isClosed()) throw new IllegalStateException("Socket is closed");
if(messages.isEmpty()) throw new IllegalArgumentException("messages may not be empty");
return listenerManager.enqueueEvent(
new Concurre... |
java | public long getTotalDomLoadTime(final String intervalName, final TimeUnit unit) {
return unit.transformMillis(totalDomLoadTime.getValueAsLong(intervalName));
} |
java | @Bean
public Config hazelcastConfig() {
MapConfig mapConfig = new MapConfig("spring-boot-admin-event-store").setInMemoryFormat(InMemoryFormat.OBJECT)
.setBackupCount(1)
... |
python | def mapped(args):
"""
%prog mapped sam/bamfile
Given an input sam/bam file, output a sam/bam file containing only the mapped reads.
Optionally, extract the unmapped reads into a separate file
"""
import pysam
from jcvi.apps.grid import Jobs
p = OptionParser(mapped.__doc__)
p.set_sa... |
java | @Override
public EList<JvmParameterizedTypeReference> getImplements()
{
if (implements_ == null)
{
implements_ = new EObjectContainmentEList<JvmParameterizedTypeReference>(JvmParameterizedTypeReference.class, this, SarlPackage.SARL_SKILL__IMPLEMENTS);
}
return implements_;
} |
java | protected synchronized Class loadClass(String classname, boolean resolve)
throws ClassNotFoundException {
// 'sync' is needed - otherwise 2 threads can load the same class
// twice, resulting in LinkageError: duplicated class definition.
// findLoadedClass avoids that, but without sy... |
python | def as_dict(self):
"""
Return a Listing object as Dictionary
:return: dict
"""
return {
'search_type': self.search_type,
'agent_id': self.agent_id,
'id': self.id,
'price': self.price,
'price_change': self.price_change,
... |
java | private ClassLoader getDelegationClassLoader(String docletClassName) {
ClassLoader ctxCL = Thread.currentThread().getContextClassLoader();
ClassLoader sysCL = ClassLoader.getSystemClassLoader();
if (sysCL == null)
return ctxCL;
if (ctxCL == null)
return sysCL;
... |
java | public static DynamicDataSet createDynamicDataSet(
File homeDir,
int initialCapacity,
int segmentFileSizeMB,
SegmentFactory segmentFactory) throws Exception {
int batchSize = StoreParams.BATCH_SIZE_DEFAULT;
int numSyncBatches = StoreParams.NUM_SYNC_BATCHES... |
java | public static void cut(Image srcImage, ImageOutputStream destImageStream, Rectangle rectangle) throws IORuntimeException {
writeJpg(cut(srcImage, rectangle), destImageStream);
} |
java | private static int get16(byte[] b, int off) {
return Byte.toUnsignedInt(b[off]) | ( Byte.toUnsignedInt(b[off+1]) << 8);
} |
python | def parse_image_json(text):
"""
parses response output of AWS describe commands and returns the first (and only) item in array
:param text: describe output
:return: image json
"""
image_details = json.loads(text)
if image_details.get('Images') is not None:
try:
image_deta... |
python | def choose_username(metadata, config):
"""
Choose the database username to use.
Because databases should not be shared between services, database usernames should be
the same as the service that uses them.
"""
if config.username is not None:
# we allow -- but do not encourage -- databa... |
python | def upload_server_cert(self, cert_name, cert_body, private_key,
cert_chain=None, path=None):
"""
Uploads a server certificate entity for the AWS Account.
The server certificate entity includes a public key certificate,
a private key, and an optional certificate... |
python | def packet_get_samples_per_frame(data, fs):
"""Gets the number of samples per frame from an Opus packet"""
data_pointer = ctypes.c_char_p(data)
result = _packet_get_nb_frames(data_pointer, ctypes.c_int(fs))
if result < 0:
raise OpusError(result)
return result |
python | def warning(title="", text="", width=DEFAULT_WIDTH,
height=DEFAULT_HEIGHT, timeout=None):
"""
Display a simple warning
:param text: text inside the window
:type text: str
:param title: title of the window
:type title: str
:param width: window width
:type width: int
:para... |
python | def abstractclass(cls):
"""abstractclass - class decorator.
make sure the class is abstract and cannot be used on it's own.
@abstractclass
class A(object):
def __init__(self, *args, **kwargs):
# logic
pass
class B(A):
pass
a = A() # results in an Ass... |
java | private boolean isWindowLimitExceeded(FrameData dataFrame) {
if (streamWindowUpdateWriteLimit - dataFrame.getPayloadLength() < 0 ||
muxLink.getWorkQ().getConnectionWriteLimit() - dataFrame.getPayloadLength() < 0) {
// would exceed window update limit
String s = "Cannot write ... |
python | def _advance_to_next_stage(self, config_ids, losses):
"""
SuccessiveHalving simply continues the best based on the current loss.
"""
ranks = np.argsort(np.argsort(losses))
return(ranks < self.num_configs[self.stage]) |
java | public Ast parse(String expression)
{
Ast ast=new Ast();
if(expression==null || expression.length()==0)
return ast;
SeekableStringReader sr = new SeekableStringReader(expression);
if(sr.peek()=='#')
sr.readUntil('\n'); // skip comment line
try {
ast.root = parseExpr(sr);
sr.skipWhitespace(... |
java | public void marshall(ListImagesRequest listImagesRequest, ProtocolMarshaller protocolMarshaller) {
if (listImagesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listImagesRequest.getRegistr... |
python | def getList(self):
"""
查询敏感词列表方法 方法
@return code:返回码,200 为正常。
@return word:敏感词内容。
@return errorMessage:错误信息。
"""
desc = {
"name": "ListWordfilterReslut",
"desc": "listWordfilter返回结果",
"fields": [{
"name": "code"... |
java | public static byte[] uncompress(byte[] input)
throws IOException
{
byte[] result = new byte[Snappy.uncompressedLength(input)];
Snappy.uncompress(input, 0, input.length, result, 0);
return result;
} |
java | private void readTableData(List<SynchroTable> tables, InputStream is) throws IOException
{
for (SynchroTable table : tables)
{
if (REQUIRED_TABLES.contains(table.getName()))
{
readTable(is, table);
}
}
} |
java | public void updateBackupElements(Map<String, CmsContainerElementData> updateElements) {
ArrayList<CmsContainerPageElementPanel> updatedList = new ArrayList<CmsContainerPageElementPanel>();
String containerId = m_groupContainer.getContainerId();
for (CmsContainerPageElementPanel element : m_back... |
python | def get_clean_content(self):
"""Implementation of the clean() method."""
fill_chars = {'BLANK_TEMPLATE': ' ', 'ECHO_TEMPLATE': '0'}
for match in self.pattern.finditer(self.html_content):
start, end = match.start(), match.end()
tag = _get_tag(match)
if tag == '... |
java | public static File getResourceAsFile(String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
return new File(URLDecoder.decode(cl.getResource(resource)
.getFile(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
... |
java | public static <P extends ICallbackPredicate> CallbackOption<P> of(P predicate)
{
return new CallbackOption<>(checkNotNull(predicate), Priority.NORMAL);
} |
java | public Object doRemoteCommand(String strCommand, Map<String, Object> properties)
{
if (SET_DEFAULT_COMMAND.equalsIgnoreCase(strCommand))
if (properties != null)
if (properties.get(DBConstants.SYSTEM_NAME) != null)
{
if (this.getTask() != null)
if (... |
java | public void send(RoxPayload payload) {
try {
if (isStarted()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new JsonSerializer().serializePayload(new OutputStreamWriter(baos), payload, false);
socket.emit("payload", new String(baos.toByteArray()));
}
else {
LOGGER.warn("Mini... |
java | public static String getFormattedName(final String orgText) {
return trimAndNullIfEmpty(orgText) == null ? SPUIDefinitions.SPACE : orgText;
} |
python | def interpret(self, infile):
""" Process a file of rest and return list of dicts """
data = []
for record in self.generate_records(infile):
data.append(record)
return data |
python | def namedb_get_name_at(cur, name, block_number, include_expired=False):
"""
Get the sequence of states that a name record was in at a particular block height.
There can be more than one if the name changed during the block.
Returns only unexpired names by default. Can return expired names with include... |
java | @Override
public void glVertexAttribPointer(int arrayId, int size, int type, boolean normalize,
int byteStride, Buffer nioBuffer) {
VertexAttribArrayState data = vertexAttribArrayState[arrayId];
// HtmlPlatform.log.info("glVertexAttribPointer Data size: " + nioBu... |
python | def from_timestamp(timestamp, tz_offset):
"""Converts a timestamp + tz_offset into an aware datetime instance."""
utc_dt = datetime.fromtimestamp(timestamp, utc)
try:
local_dt = utc_dt.astimezone(tzoffset(tz_offset))
return local_dt
except ValueError:
return utc_dt |
java | public Optional<T> tryFind(Predicate<T> decision) {
return Iterables.tryFind(result(), decision);
} |
python | def mute(self):
"""bool: The speaker's mute state.
True if muted, False otherwise.
"""
response = self.renderingControl.GetMute([
('InstanceID', 0),
('Channel', 'Master')
])
mute_state = response['CurrentMute']
return True if int(mute_sta... |
python | def from_plugin_classname(plugin_classname, exclude_lines_regex=None, **kwargs):
"""Initializes a plugin class, given a classname and kwargs.
:type plugin_classname: str
:param plugin_classname: subclass of BasePlugin.
:type exclude_lines_regex: str|None
:param exclude_lines_regex: optional regex ... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/bridge/2.0", name = "_GenericApplicationPropertyOfBridgeInstallation")
public JAXBElement<Object> create_GenericApplicationPropertyOfBridgeInstallation(Object value) {
return new JAXBElement<Object>(__GenericApplicationPropertyOfBridgeInstallation_... |
java | @SafeVarargs
public static Double[] box(final double... a) {
if (a == null) {
return null;
}
return box(a, 0, a.length);
} |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.PPORG__RG_LENGTH:
setRGLength((Integer)newValue);
return;
case AfplibPackage.PPORG__OBJ_TYPE:
setObjType((Integer)newValue);
return;
case AfplibPackage.PPORG__... |
python | def untokenize(words):
"""
Untokenizing a text undoes the tokenizing operation, restoring
punctuation and spaces to the places that people expect them to be.
Ideally, `untokenize(tokenize(text))` should be identical to `text`,
except for line breaks.
"""
text = ' '.join(words)
step1 = t... |
python | def process_forever(self, timeout=0.2):
"""Run an infinite loop, processing data from connections.
This method repeatedly calls process_once.
:param timeout: Parameter to pass to
:meth:`irc.client.Reactor.process_once`
:type timeout: :class:`float`
"""
... |
python | def policy_map_clss_priority_mapping_table_imprt_cee(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
... |
python | def print_colored_columns(printer, rows, padding=2):
"""Like `columnise`, but with colored rows.
Args:
printer (`colorize.Printer`): Printer object.
Note:
The last entry in each row is the row color, or None for no coloring.
"""
rows_ = [x[:-1] for x in rows]
colors = [x[-1] fo... |
python | def lag(expr, offset, default=None, sort=None, ascending=True):
"""
Get value in the row ``offset`` rows prior to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
... |
python | def get_filtered_values_by_selector(self, selector, regex=None, group=1):
"""Return the text content of @selector.
Filter text content by @regex and @group.
"""
data = [
self.get_text_from_node(node, regex, group)
for node in self.get_nodes_by_selector(selector)
... |
python | def types(**typefuncs):
"""
Decorate a function that takes strings to one that takes typed values.
The decorator's arguments are functions to perform type conversion.
The positional and keyword arguments will be mapped to the positional and
keyword arguments of the decoratored function. This allow... |
java | public static AztecCode encode(byte[] data, int minECCPercent, int userSpecifiedLayers) {
// High-level encode
BitArray bits = new HighLevelEncoder(data).encode();
// stuff bits and choose symbol size
int eccBits = bits.getSize() * minECCPercent / 100 + 11;
int totalSizeBits = bits.getSize() + eccB... |
java | public List<SpecNode> getAllSpecNodes() {
final ArrayList<SpecNode> retValue = new ArrayList<SpecNode>();
// Add all the levels
retValue.addAll(levels);
// Add all the topics
for (final Entry<Integer, List<ITopicNode>> topicEntry : topics.entrySet()) {
for (final IT... |
python | def get_blockchain_data(self):
"""
Finalize tree and return byte array to issue on blockchain
:return:
"""
self.tree.make_tree()
merkle_root = self.tree.get_merkle_root()
return h2b(ensure_string(merkle_root)) |
python | def _get_choices(self):
"""
Redefine standard method.
"""
if not self._choices:
self._choices = tuple(
(x.name, getattr(x, 'verbose_name', x.name) or x.name)
for x in self.choices_class.constants()
)
return self._choices |
java | private void closeStream(InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception ex) {
LOG.error(ex.getLocalizedMessage(), ex);
}
}
} |
java | public EntryRecord getRecord(Object key, byte[] serializedKey) throws IOException {
int segment = (key.hashCode() & Integer.MAX_VALUE) % segments.length;
lock.readLock().lock();
try {
return IndexNode.applyOnLeaf(segments[segment], serializedKey, segments[segment].rootReadLock(), IndexNode.Re... |
python | def parse_term(s):
"""Parse single s-expr term from bytes."""
size, s = s.split(b':', 1)
size = int(size)
return s[:size], s[size:] |
java | public ASTMethod getMethod(ExecutableElement executableElement) {
ImmutableList<ASTParameter> parameters = getParameters(executableElement.getParameters());
ASTAccessModifier modifier = buildAccessModifier(executableElement);
ImmutableSet<ASTType> throwsTypes = buildASTElementTypes(executableEl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.