language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void printBody(final OutputStream output) throws IOException {
//@checkstyle MagicNumberCheck (1 line)
final byte[] buf = new byte[4096];
try (InputStream body = this.body()) {
while (true) {
final int bytes = body.read(buf);
if (bytes < 0) {
... |
java | public CommandArgs<K, V> add(byte[] value) {
singularArguments.add(BytesArgument.of(value));
return this;
} |
python | def generate_csv(src, out):
"""\
Walks through `src` and generates the CSV file `out`
"""
writer = UnicodeWriter(open(out, 'wb'), delimiter=';')
writer.writerow(('Reference ID', 'Created', 'Origin', 'Subject'))
for cable in cables_from_source(src, predicate=pred.origin_filter(pred.origin_germany... |
java | public static String unwrapProxyClassName(Class<?> type)
{
String typeName = null;
if (type != null)
{
if (type.getName().contains("$$EnhancerByCGLIB$$"))
{
typeName = CGLIB_CLASSNAME_REGEXP.matcher(type.getName()).replaceAll("$1");
}
else if (type.ge... |
python | def compute_checksum(stream, algo, message_digest, chunk_size=None,
progress_callback=None):
"""Get helper method to compute checksum from a stream.
:param stream: File-like object.
:param algo: Identifier for checksum algorithm.
:param messsage_digest: A message digest instance.
... |
python | def _wait_for_response(self, requests):
"""Issues a batch of requests and waits for the responses.
If some of the requests fail it will retry the failed ones up to `_max_retry` times.
Args:
requests - A list of requests
Returns:
A list of `requests.models.Respons... |
python | def _autoscript(self):
"""
Automatically generates a python script for plotting.
"""
# This should never happen unless I screwed up.
if self.combo_autoscript.get_index() == 0: return "ERROR: Ask Jack."
# if there is no data, leave it blank
if len(self)... |
java | public final static String cleanSequence(String sequence, Set<Character> cSet){
Set<Character> invalidCharSet = new HashSet<Character>();
StringBuilder cleanSeq = new StringBuilder();
if(cSet == null) cSet = PeptideProperties.standardAASet;
for(char c:sequence.toCharArray()){
if(!cSet.contains(c)){
clean... |
python | def run_simulations(self, parameter_list, data_folder):
"""
This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders.
"""
self... |
python | def __create_map(self, map_size):
'''
Create map.
References:
- https://qiita.com/kusano_t/items/487eec15d42aace7d685
'''
import random
import numpy as np
from itertools import product
news = ['n', 'e', 'w', 's']
m, n = map_s... |
java | private void gossip() {
List<Member> members = membershipService.getMembers()
.stream()
.filter(node -> !localMemberId.equals(node.id()))
.filter(node -> node.isReachable())
.collect(Collectors.toList());
if (!members.isEmpty()) {
Collections.shuffle(members);
Member... |
java | @Override
protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)
throws JsonMappingException
{
JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);
if (v2 != null) {
v2.numberType(JsonParser.NumberType.LONG);
}
... |
python | def _build_gene_disease_model(
self,
gene_id,
relation_id,
disease_id,
variant_label,
consequence_predicate=None,
consequence_id=None,
allelic_requirement=None,
pmids=None):
"""
Builds gene varian... |
java | public void close(int requestNumber)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "close", requestNumber);
try
{
ConsumerSession cs = getConsumerSession();
if (cs !=null) cs.close();
try
{
getConversation().sen... |
java | public MockResponse throttleBody(long bytesPerPeriod, long period, TimeUnit unit) {
this.throttleBytesPerPeriod = bytesPerPeriod;
this.throttlePeriodAmount = period;
this.throttlePeriodUnit = unit;
return this;
} |
java | public void applyVerticalAlign(int origHeight, int newHeight, int baseline)
{
int yofs = 0;
CSSProperty.VerticalAlign valign = style.getProperty("vertical-align");
if (valign == null) valign = CSSProperty.VerticalAlign.MIDDLE;
switch (valign)
{
case TOP: yofs = 0;... |
java | @Override
public boolean databaseExists(String directory) {
if (new File(directory, kDBFilename).exists())
return true;
// If "db.forest" doesn't exist (auto-compaction will add numeric suffixes), check for meta:
return new File(directory, kDBFilename + ".meta").exists();
} |
python | def multi_exposure_analysis_summary_report(feature, parent):
"""Retrieve an HTML multi exposure analysis table report.
"""
_ = feature, parent # NOQA
analysis_dir = get_analysis_dir()
if analysis_dir:
return get_impact_report_as_string(analysis_dir)
return None |
java | private boolean isSparkOrigin(String objectName) {
LOG.trace("Check if created by Stocator: {}", objectName);
if (cachedSparkOriginated.containsKey(objectName)) {
return cachedSparkOriginated.get(objectName).booleanValue();
}
String obj = objectName;
Boolean sparkOriginated = Boolean.FALSE;
... |
python | def from_columns(columns):
"""Parses raw columns
:param columns: matrix divided into columns
:return: Matrix: Merge the columns to form a matrix
"""
data = [
[
column[i]
for i in range(len(column))
]
for column ... |
python | def operator(self, lhs, min_precedence):
"""Climb operator precedence as long as there are operators.
This function implements a basic precedence climbing parser to deal
with binary operators in a sane fashion. The outer loop will keep
spinning as long as the next token is an operator w... |
python | def _poll(self, future):
"""Enqueue a problem to poll the server for status."""
if future._poll_backoff is None:
# on first poll, start with minimal back-off
future._poll_backoff = self._POLL_BACKOFF_MIN
# if we have ETA of results, schedule the first poll for then
... |
java | public ListDomainStatisticsResponse listDomainStatistics(ListDomainStatisticsRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getStartTime(), "startTime should NOT be empty");
InternalRequest internalRequest = createRequest(Http... |
python | def config_put(args):
'''Install a valid method configuration into a workspace, in one of several
ways: from a JSON file containing a config definition (both file names
and objects are supported); as a string representing the content of such
a JSON file; or as a dict generated from such JSON co... |
python | def get_occupation_updates(self, offset=0, count=1000):
""" Returns <count> occupation updates from <offset>.
An occupation update is a quadrupel
(pc, source, timestamp, occupation) """
ret = []
c = self.conn.cursor()
for pc_id, source_id, datetime, ... |
python | def _bucket_exists(self):
"""Check if the bucket exists."""
try:
self.s3client.get_bucket_location(Bucket=self.bucket)
return True
except ClientError as error:
LOG.error(error)
return False |
java | public void addLiteralResultAttribute(String att)
{
if (null == m_xslAttr)
m_xslAttr = new ArrayList();
m_xslAttr.add(att);
} |
java | public void setUnprocessedAccounts(java.util.Collection<Result> unprocessedAccounts) {
if (unprocessedAccounts == null) {
this.unprocessedAccounts = null;
return;
}
this.unprocessedAccounts = new java.util.ArrayList<Result>(unprocessedAccounts);
} |
python | def handle_symbol_info(self, call_id, payload):
"""Handler for response `SymbolInfo`."""
with catch(KeyError, lambda e: self.editor.message("unknown_symbol")):
decl_pos = payload["declPos"]
f = decl_pos.get("file")
call_options = self.call_options[call_id]
... |
java | public Matrix4f lookAtPerspective(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ, Matrix4f dest) {
// Compute direction from position to lookAt
float dirX, dirY, dirZ;
dirX = eyeX - centerX;
dirY = ... |
java | protected void sequence_XtendEnumLiteral(ISerializationContext context, SarlEnumLiteral semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, XtendPackage.Literals.XTEND_ENUM_LITERAL__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatur... |
python | def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5):
"Crop and pad tfm - `row_pct`,`col_pct` sets focal point."
padding_mode = _pad_mode_convert[padding_mode]
size = tis2hw(size)
if x.shape[1:] == torch.Size(size): return x
rows,cols = size
row... |
java | protected void parseRootElement() {
JobExecutorXmlImpl jobExecutor = new JobExecutorXmlImpl();
List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>();
for (Element element : rootElement.elements()) {
if(JOB_EXECUTOR.equals(element.getTagName())) {
parseJobExecutor(element... |
java | public void changeSubject(String subject)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
MUCLightSetConfigsIQ mucLightSetConfigIQ = new MUCLightSetConfigsIQ(room, null, subject, null);
connection.createStanzaCollectorAndSend(mucLightSetConfigIQ)... |
python | def on(self):
"""!
\~english
Open Audio output. set pin mode to ALT0
@return a boolean value. if True means open audio output is OK otherwise failed to open.
\~chinese
打开音频输出。 将引脚模式设置为ALT0
@return 布尔值。 如果 True 表示打开音频输出成功,否则不成功。
"""
isOK = True
... |
java | String encodePath(String in) {
try {
String encodedString = HierarchicalUriComponents.encodeUriComponent(in, "UTF-8",
HierarchicalUriComponents.Type.PATH_SEGMENT);
if (encodedString.startsWith(_design_prefix_encoded) ||
encodedString.startsWith(_lo... |
java | public static double deriv(double pred, double y)
{
final double x = y * pred;
if (x >= 30)
return 0;
else if (x <= -30)
return y;
return -y / (1 + exp(y * pred));
} |
java | public String prepareStatementString() throws SQLException {
List<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();
return buildStatementString(argList);
} |
java | public ResultList<MovieBasic> getGuestRatedMovies(String guestSessionId, String language, Integer page, SortBy sortBy) throws MovieDbException {
return tmdbAccount.getGuestRatedMovies(guestSessionId, language, page, sortBy);
} |
java | protected Model getModel(EnforcerRuleHelper helper) throws EnforcerRuleException
{
MavenProject project = getMavenProject(helper);
Model model;
Reader reader = null;
try {
reader = new FileReader(project.getFile());
MavenXpp3Reader xpp3Reader = new MavenXpp3Re... |
python | def today_as_utc_datetime():
"""Datetime/Date comparisons aren't great, and someone might configure TODAY, to be a date."""
now = today()
if not isinstance(now, datetime) and isinstance(now, date):
now = datetime.combine(now, datetime.min.time())
now = now.replace(tzinfo=tz.gettz('UTC'))
... |
java | public final void mOPEN_PAREN() throws RecognitionException {
try {
int _type = OPEN_PAREN;
int _channel = DEFAULT_TOKEN_CHANNEL;
// BELScript.g:285:11: ( '(' )
// BELScript.g:286:5: '('
{
match('(');
}
state.type... |
java | public void rollbackThis() throws XAException {
if (state != XA_STATE_PREPARED) {
throw new XAException("Invalid XAResource state");
}
try {
/**
* @todo: Determine if work was committed, rolled back, or both,
* and return appropriate Heuristi... |
python | def calc_targetedrelease_v1(self):
"""Calculate the targeted water release for reducing drought events,
taking into account both the required water release and the actual
inflow into the dam.
Some dams are supposed to maintain a certain degree of low flow
variability downstream. In case parameter ... |
java | public static final String replacePossiblePassword(boolean password, Object o)
{
if (password)
return replaceNonNullObject(o);
else if (o == null)
return null;
else
return o.toString();
} |
java | public static MetadataBuilder forProvider(Class<? extends RuleProvider> implementationType, String providerId)
{
Assert.notNull(implementationType, "Rule provider Implementation type must not be null.");
Assert.notNull(providerId, "Rule provider ID must not be null.");
MetadataBuilder build... |
python | def Pull(cls, connection, filename, dest_file, progress_callback):
"""Pull a file from the device into the file-like dest_file."""
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, curr... |
java | public SIMPIterator getQueueIterator()
{
DestinationTypeFilter filter = new DestinationTypeFilter();
filter.QUEUE = Boolean.TRUE;
SIMPIterator queuesItr = destinationIndex.iterator(filter);
return new ControllableIterator(queuesItr);
} |
java | @CheckReturnValue
public AuditableRestAction<Void> ban(User user, int delDays)
{
return ban(user, delDays, null);
} |
python | def apply_policy(self, sp_entity_id, policy, metadata=None):
""" Apply policy to the assertion I'm representing
:param sp_entity_id: The SP entity ID
:param policy: The policy
:param metadata: Metadata to use
:return: The resulting AVA after the policy is applied
"""
... |
python | def apply(self, byte, value, data, i, count):
"""
Apply mask, compare to expected value, shift and return result.
Eventually, this could become a ``reduce`` function.
:param byte: The byte to compare
:param value: The currently accumulated value.
:param data: The data bu... |
python | def get_route(self, file_id):
''' a method to retrieve route information for file on telegram api
:param file_id: string with id of file in a message send to bot
:return: dictionary of response details with route details in [json][result]
'''
title = '%s.get_route' % s... |
java | @Override
public boolean performOk() {
reportConfigurationTab.performOk();
boolean analysisSettingsChanged = false;
boolean reporterSettingsChanged = false;
boolean needRedisplayMarkers = false;
if (workspaceSettingsTab != null) {
workspaceSettingsTab.performOK();... |
java | private static AFPChain buildAlignment(Atom[] ca1, Atom[] ca2, ResidueNumber[] residues1, ResidueNumber[] residues2)
throws StructureException {
// remove any gap
// this includes the ones introduced by the nullifying above
List<ResidueNumber> alignedResiduesList1 = new ArrayList<ResidueNumber>();
List<Resi... |
python | def _export_profiles(self, profile_name, user_pageviews, user_downloads,
ip_user=False):
"""Filter and export the user profiles."""
views_min = self.config.get('user_views_min')
views_max = self.config.get('user_views_max')
ip_user_id = 500000000000
add_u... |
java | @Override
public URL getURL(int columnIndex) throws SQLException {
checkColumnBounds(columnIndex);
try {
return new URL(table.getString(columnIndex - 1));
} catch (Exception x) {
throw SQLError.get(x);
}
} |
java | public static DMatrixRMaj createProjectiveToMetric( DMatrixRMaj K ,
double v1 , double v2 , double v3 ,
double lambda,
@Nullable DMatrixRMaj H )
{
if( H == null )
H = new DMatrixRMaj(4,4);
else
H.reshape(4,4);
CommonOps_DDRM.insert(K,H,0,0);
H.set(0,3,0);
H.se... |
python | def _send_data(self, data):
"""
Try to send all data in buffer.
"""
try:
self.socket.sendall(data)
self._reset_errors()
except:
self._close()
self._throttle_error("GraphiteHandler: Socket error, "
"t... |
java | public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){
for(T c: toCheck){
if(collection.contains(c))
return true;
}
return false;
} |
python | def reqMktDepth(
self, contract: Contract, numRows: int = 5,
isSmartDepth: bool = False, mktDepthOptions=None) -> Ticker:
"""
Subscribe to market depth data (a.k.a. DOM, L2 or order book).
https://interactivebrokers.github.io/tws-api/market_depth.html
Args:
... |
java | public final int needArgumentsNumber() {
int number = 0;
for (int i : needArgument) {
number = Math.max(number, (i + 1));
}
return number;
} |
java | public void marshall(LoadBasedAutoScalingConfiguration loadBasedAutoScalingConfiguration, ProtocolMarshaller protocolMarshaller) {
if (loadBasedAutoScalingConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocol... |
python | def cmd_scale(self, x=None, y=None, ch=None):
"""scale x=scale_x y=scale_y ch=chname
Scale the image for the given viewer/channel by the given amounts.
If only one scale value is given, the other is assumed to be the
same. If no value is given, reports the current scale.
"""
... |
python | def remove_hook(self, name, func):
''' Remove a callback from a hook. '''
if name in self._hooks and func in self._hooks[name]:
self._hooks[name].remove(func)
return True |
python | def reg(self):
"""Name of the register used in the operand."""
if self.type.is_displ or self.type.is_phrase:
size = core.get_native_size()
return base.get_register_name(self.reg_id, size)
if self.type.is_reg:
return base.get_register_name(self.reg_id, self.si... |
python | def create_from_cellranger(indir: str, outdir: str = None, genome: str = None) -> str:
"""
Create a .loom file from 10X Genomics cellranger output
Args:
indir (str): path to the cellranger output folder (the one that contains 'outs')
outdir (str): output folder wher the new loom file should be saved (default to... |
python | def add_new_amendment(self,
json_repr,
auth_info,
commit_msg=''):
"""Validate and save this JSON. Ensure (and return) a unique amendment id"""
amendment = self._coerce_json_to_amendment(json_repr)
if amendment is None:... |
python | def data_spec(cls, name):
"""
Return the fileset_spec, i.e. the template of the fileset expected to
be supplied or generated corresponding to the fileset_spec name.
Parameters
----------
name : Str
Name of the fileset_spec to return
"""
# If t... |
java | @Override
public CircuitBreaker circuitBreaker(String name, CircuitBreakerConfig config) {
return computeIfAbsent(name, () -> CircuitBreaker.of(name, Objects.requireNonNull(config, CONFIG_MUST_NOT_BE_NULL)));
} |
python | def _onImport( self, name, line, pos, absPosition ):
" Memorizes an import "
if self.__lastImport is not None:
self.imports.append( self.__lastImport )
self.__lastImport = Import( name, line, pos, absPosition )
return |
python | def current_item(self):
"""Return the current element."""
if self._history and self._index >= 0:
self._check_index()
return self._history[self._index] |
python | def setup_project_view(self):
"""Setup view for projects"""
for i in [1, 2, 3]:
self.hideColumn(i)
self.setHeaderHidden(True)
# Disable the view of .spyproject.
self.filter_directories() |
python | def _self_pipe(self):
"""
This sets up a self-pipe so we can hand back an fd to the caller
allowing the object to manage event triggers. The ends of the pipe are
set non-blocking so it doesn't really matter if a bunch of events fill
the pipe buffer.
"""
import fcntl
... |
java | @Override
public void encode(T value, OutputStream outStream) throws CoderException, IOException {
Serializer<T> serializer = this.serialization.getSerializer(type);
serializer.open(new UncloseableOutputStream(outStream));
try {
serializer.serialize(value);
} finally {
serializer.close();
... |
java | @SuppressWarnings("squid:S2201") // ignore return values
private LoadingCache<Object, Optional<Map<String, Object>>> getEntityCache(
Repository<Entity> repository) {
String id = repository.getEntityType().getId();
if (!caches.containsKey(id)) {
caches.putIfAbsent(id, createEntityCache(repository))... |
java | public Optional<VesselPosition> predict(long t) {
if (!speedMetresPerSecond.isPresent() || !cogDegrees.isPresent()
|| navigationalStatus == NavigationalStatus.AT_ANCHOR
|| navigationalStatus == NavigationalStatus.MOORED)
return Optional.absent();
else {
... |
python | def validate_request_token_request(self, request):
"""Validate a request token request.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:raises: OAuth1Error if the request is invalid.
:returns: A tuple of 2 elements.
1. The validation r... |
java | public synchronized MucCreateConfigFormHandle createOrJoin(MucEnterConfiguration mucEnterConfiguration)
throws NoResponseException, XMPPErrorException, InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException {
if (joined) {
throw new MucAlr... |
java | public static void clear(){
clipboard().setContents(new Transferable(){
public DataFlavor[] getTransferDataFlavors(){
return new DataFlavor[0];
}
public boolean isDataFlavorSupported(DataFlavor flavor){
return false;
}
... |
java | public int read(User registrar) throws IdentityException, InvalidArgumentException {
if (registrar == null) {
throw new InvalidArgumentException("Registrar should be a valid member");
}
String readIdURL = "";
try {
readIdURL = HFCA_IDENTITY + "/" + enrollmentID;
... |
python | def validate_line_list(dist, attr, value):
"""
Validate that the value is compatible
"""
# does not work as reliably in Python 2.
if isinstance(value, str):
value = value.split()
value = list(value)
try:
check = (' '.join(value)).split()
if check == value:
... |
java | public boolean isToBeUninstalled(String name, List<UninstallAsset> list) {
for (UninstallAsset asset : list) {
String fixName = asset.getIFixInfo().getId();
if (fixName != null && fixName.equals(name)) {
return true;
}
}
return false;
} |
python | async def handle_frame(self, frame):
"""Handle incoming API frame, return True if this was the expected frame."""
if isinstance(frame, FrameGetSceneListConfirmation):
self.count_scenes = frame.count_scenes
if self.count_scenes == 0:
self.success = True
... |
python | def fold_joint_sfs(s, n1, n2):
"""Fold a joint site frequency spectrum.
Parameters
----------
s : array_like, int, shape (m_chromosomes, n_chromosomes)
Joint site frequency spectrum.
n1, n2 : int, optional
The total number of chromosomes called in each population.
Returns
-... |
python | def _references(self, i, sequence=False):
"""Handle references."""
c = next(i)
if c == '\\':
# \\
if sequence and self.bslash_abort:
raise PathNameException
elif c == '/':
# \/
if sequence and self.pathname:
... |
java | public void onCompleted() {
mSerializingExecutor.execute(() -> {
Preconditions.checkState(mContext != null);
try {
completeRequest(mContext);
replySuccess();
} catch (Exception e) {
LogUtils.warnWithException(LOG, "Exception occurred while completing write request {}.",
... |
python | def new_multigraph(self, name, data=None, **attr):
"""Return a new instance of type MultiGraph, initialized with the given
data if provided.
:arg name: a name for the graph
:arg data: dictionary or NetworkX graph object providing initial state
"""
self._init_graph(name,... |
java | private int readVersion(@Nullable final BluetoothGattCharacteristic characteristic) {
// The value of this characteristic has been read before by LegacyButtonlessDfuImpl
return characteristic != null ? characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0) : 0;
} |
java | public static String filterNormalizeMediaUri(String value) {
if (EscapingConventions.FilterNormalizeMediaUri.INSTANCE
.getValueFilter()
.matcher(value)
.find()) {
return EscapingConventions.FilterNormalizeMediaUri.INSTANCE.escape(value);
}
logger.log(Level.WARNING, "|filterNorm... |
java | public static boolean isSelfIssued(X509Certificate cert) {
X500Principal subject = cert.getSubjectX500Principal();
X500Principal issuer = cert.getIssuerX500Principal();
return subject.equals(issuer);
} |
python | def download_file(filename: str):
""" downloads the specified project file if it exists """
project = cd.project.get_internal_project()
source_directory = project.source_directory if project else None
if not filename or not project or not source_directory:
return '', 204
path = os.path.re... |
java | public static void foreachRandomInt(int streamSize, int inclusiveLowerBound,
int exclusiveUpperBound, IntConsumer eachRandomIntConsumer) {
foreachRandomInt(streamSize, new Random(), inclusiveLowerBound,
exclusiveUpperBound, eachRandomIntConsumer);
} |
python | def _z2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_z2deriv
PURPOSE:
evaluate the second vertical derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t- time
... |
python | def _handle_func(self, value, rule, path, done=None):
"""
Helper function that should check if func is specified for this rule and
then handle it for all cases in a generic way.
"""
func = rule.func
# func keyword is not defined so nothing to do
if not func:
... |
java | private String getBetterToken( Token token ) {
if ( token == null ) {
return "";
}
return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel);
} |
java | public static byte[] bufferedImageToJPGByteArray(BufferedImage image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, "jpg", baos);
//baos.flush();
byte[] imageInByte = baos.toByteArray();
//baos.close();
... |
java | public static Matcher<ExpressionTree> ignoreParens(final Matcher<ExpressionTree> innerMatcher) {
return new Matcher<ExpressionTree>() {
@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
return innerMatcher.matches((ExpressionTree) stripParentheses(expressionTr... |
java | public void process(InputStream input) throws IOException, ConverterException {
while (0 != input.available()) {
Tag tag = ParserUtils.parseTag(input);
TagHandler handler = getHandler(tag);
if (null == handler) {
skipHandler.handle(tag, input);
} e... |
python | def db(self):
"""
Get a loaded database session
"""
if self.database is NotImplemented:
self.database = Session
return self.database |
python | def _config_from_url(self):
""" Manage block configuration from requests.args (url params)
"""
config = {
"name": self._blk.name,
"options": {}
}
for key, value in six.iteritems(request.args):
if isinstance(value, list) and len(value) == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.