language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def revoke_tokens(self):
"""
Revoke the authorization token and all tokens that were generated using it.
"""
self.is_active = False
self.save()
self.refresh_token.revoke_tokens() |
java | public void setSentId(int v) {
if (Token_Type.featOkTst && ((Token_Type)jcasType).casFeat_sentId == null)
jcasType.jcas.throwFeatMissing("sentId", "de.unihd.dbs.uima.types.heideltime.Token");
jcasType.ll_cas.ll_setIntValue(addr, ((Token_Type)jcasType).casFeatCode_sentId, v);} |
python | def get_statements_for_paper(ids, ev_limit=10, best_first=True, tries=2,
max_stmts=None):
"""Get the set of raw Statements extracted from a paper given by the id.
Parameters
----------
ids : list[(<id type>, <id value>)]
A list of tuples with ids and their type. The... |
python | def try_datetime(obj) -> Optional[datetime.datetime]:
"""Attempts to convert an object into a datetime.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`dict`, :class:`date... |
python | def start_monitoring(self) -> None:
"""
The recommended way of using Monitor is opening it with the `with` statement. In this case
the user doesn't need to call this function explicitly. Otherwise, the function should be
called before starting the optimiser.
The function evaluat... |
java | public <S, T> Binding<S,T> findBinding(ConverterKey<S,T> key) {
return BINDING.findBinding(key);
} |
python | def config_logger(name='andes',
log_file='andes.log',
log_path='',
stream=True,
stream_level=logging.INFO
):
"""
Configure a logger for the andes package with options for a `FileHandler`
and a `StreamHandler`. This fun... |
python | def register_postloop_hook(self, func: Callable[[None], None]) -> None:
"""Register a function to be called at the end of the command loop."""
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) |
java | private int parseOffsetLocalizedGMTPattern(String text, int start, boolean isShort, int[] parsedLen) {
int idx = start;
int offset = 0;
boolean parsed = false;
do {
// Prefix part
int len = _gmtPatternPrefix.length();
if (len > 0 && !text.regionMatche... |
python | def parse_transform(transform, direction='forward'):
"""
direction : 'forward' | 'inverse'
"""
if hasattr(transform, '__call__'):
tfun = transform
tname = None
elif hasattr(transform, 'lower'):
tname = _get_canonical_name(transform)
if tname is None:
raise... |
python | def get_setter(cls, prop_name, # @NoSelf
user_setter=None, setter_takes_name=False,
user_getter=None, getter_takes_name=False):
"""The setter follows the rules of the getter. First search
for property variable, then logical custom setter. If no setter
i... |
python | def public_dsn(dsn):
'''Transform a standard Sentry DSN into a public one'''
m = RE_DSN.match(dsn)
if not m:
log.error('Unable to parse Sentry DSN')
public = '{scheme}://{client_id}@{domain}/{site_id}'.format(
**m.groupdict())
return public |
java | public String getMessage(final Locale local, final String code, final Object... args) {
try {
return source.getMessage(code, args, local);
} catch (final NoSuchMessageException ex) {
LOG.error("Failed to retrieve message!", ex);
return code;
}
} |
python | def tmpdir(prefix='npythy_tempdir_', delete=True):
'''
tmpdir() creates a temporary directory and yields its path. At python exit, the directory and
all of its contents are recursively deleted (so long as the the normal python exit process is
allowed to call the atexit handlers).
tmpdir(prefix) ... |
java | public static Pipe newPipe(byte[] data, boolean numeric) throws IOException
{
return newPipe(data, 0, data.length, numeric);
} |
java | private UUID nextUUID(boolean secure) {
byte[] raw = new byte[UUID_BYTE_LENGTH];
if (secure) {
//Initialize the secure random if null.
if (secureRandom == null) {
try {
if (usePRNGPackage != null) {
... |
java | @Override
public void put(String name, Object value) {
emulatedFields.put(name, value);
} |
python | def bandwidth(self, subid, params=None):
''' /v1/server/bandwidth
GET - account
Get the bandwidth used by a virtual machine
Link: https://www.vultr.com/api/#server_bandwidth
'''
params = update_params(params, {'SUBID': subid})
return self.request('/v1/server/band... |
java | @Override
public void init(Collection<File> baseline) {
// Baseline: we haven't found this file before.
exists = monitoredFile.isFile();
performScan(monitoredFile);
// Always return the file being monitored as part of the
// baseline so the caller can verify against informati... |
java | @Override
public DBInstance startDBInstance(StartDBInstanceRequest request) {
request = beforeClientExecution(request);
return executeStartDBInstance(request);
} |
java | public boolean hasRemote()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "hasRemote");
boolean hasRemote = _localisationManager.hasRemote();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "hasRemote", new B... |
java | private void setTargets(TrellisNode[][] trellis, double[] scaling, int[] label) {
TrellisNode[] t0 = trellis[0];
// Finding the normalizer for our first 'column' in the matrix
double normalizer = 0.0;
for (int i = 0; i < numClasses; i++) {
normalizer += t0[i].expScores[0] * ... |
python | def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
... |
java | private AbstractTransform getTransform(String fileName) {
File file = new File(fileName);
for (Transform transform : transforms) {
if (transform.filter.accept(file)) {
return transform.transform;
}
}
return null;
} |
java | public YarnSubmissionHelper setPreserveEvaluators(final boolean preserveEvaluators) {
if (preserveEvaluators) {
// when supported, set KeepContainersAcrossApplicationAttempts to be true
// so that when driver (AM) crashes, evaluators will still be running and we can recover later.
if (YarnTypes.is... |
java | @Override
public void relocate()
{
int w = 200, h = 235;
int x = (this.getWidth() - w) / 2;
int y = (this.getHeight() - h) / 2;
enableSQLDatabaseConnection.setLocation(x, y);
sqlHostLabel.setLocation(x, y + 40);
sqlHostField.setLocation(x + 110, y + 40);
sqlDatabaseLabel.setLocation(x, y + 70);
sql... |
python | def _parse_username(self, config):
"""Scans the config block and returns the username as a dict
Args:
config (str): The config block to parse
Returns:
dict: A resource dict that is intended to be merged into the
user resource
"""
(usernam... |
python | def delete_group(group_id, tasks=False, cached=Conf.CACHED):
"""
Delete a group.
:param str group_id: the group id
:param bool tasks: If set to True this will also delete the group tasks.
Otherwise just the group label is removed.
:param bool cached: run this against the cache backend
:retu... |
python | def get_monochrome_handler(
extranames: List[str] = None,
with_process_id: bool = False,
with_thread_id: bool = False,
stream: TextIO = None) -> logging.StreamHandler:
"""
Gets a monochrome log handler using a standard format.
Args:
extranames: additional names to ap... |
python | def localtime(dt=None, isdst=-1):
"""Return local time as an aware datetime object.
If called without arguments, return current time. Otherwise *dt*
argument should be a datetime instance, and it is converted to the
local time zone according to the system time zone database. If *dt* is
naive (tha... |
python | def admm(X, prox_f, step_f, prox_g=None, step_g=None, L=None, e_rel=1e-6, e_abs=0, max_iter=1000, traceback=None):
"""Alternating Direction Method of Multipliers
This method implements the linearized ADMM from Parikh & Boyd (2014).
Args:
X: initial X will be updated
prox_f: proxed function... |
python | def show(self):
"""
Plot the result of the simulation once it's been intialized
"""
from matplotlib import pyplot as plt
if self.already_run:
for ref in self.volts.keys():
plt.plot(self.t, self.volts[ref], label=ref)
plt... |
java | public Optional<SQLSegmentFiller> findSQLSegmentFiller(final DatabaseType databaseType, final Class<? extends SQLSegment> sqlSegmentClass) {
return Optional.fromNullable(parserRuleDefinitions.get(DatabaseType.H2 == databaseType ? DatabaseType.MySQL : databaseType).getFillerRuleDefinition().getRules().get(sqlSeg... |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "includeAllowableActions", scope = GetObjectByPath.class)
public JAXBElement<Boolean> createGetObjectByPathIncludeAllowableActions(
Boolean value) {
return new JAXBElement<Boolean>(
_GetObjectOfLatestVersionIncludeA... |
python | def class_wise_accuracy(self, event_label, factor=0.5):
"""Class-wise accuracy metrics (sensitivity, specificity, accuracy, and balanced_accuracy)
Returns
-------
dict
results in a dictionary format
"""
sensitivity = metric.sensitivity(
Ntp=self... |
java | public void validate() throws OValidationException {
if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && !getDatabase().isValidationEnabled())
return;
checkForLoading();
checkForFields();
if (_clazz != null) {
if (_clazz.isStrictMode()) {
// CHECK IF ALL FIELDS ARE DEFI... |
python | def reverse_collections(self, key, value):
"""Reverse colections field to custom MARC tag 980."""
return {
'a': value.get('primary'),
'b': value.get('secondary'),
'c': value.get('deleted'),
} |
java | public ArrayList<String> spare_brands_GET() throws IOException {
String qPath = "/telephony/spare/brands";
StringBuilder sb = path(qPath);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, t4);
} |
python | def generate_rpn_proposals(boxes, scores, img_shape,
pre_nms_topk, post_nms_topk=None):
"""
Sample RPN proposals by the following steps:
1. Pick top k1 by scores
2. NMS them
3. Pick top k2 by scores. Default k2 == k1, i.e. does not filter the NMS output.
Args:
... |
python | def _slice(self, view):
"""
Send view to remote server and do slicing there.
"""
if self._data is not None:
return self._data[view]
return self._proxy.get_view(self.id, view) |
python | def _get_parent(root):
"""Returns root element for a list.
:Args:
root (Element): lxml element of current location
:Returns:
lxml element representing list
"""
elem = root
while True:
elem = elem.getparent()
if elem.tag in ['ul', 'ol']:
return e... |
python | def absrange_fltr(dem, rangelim):
"""Absolute range filter
"""
out = range_fltr(np.ma.abs(dem), *rangelim)
#Apply mask to original input
out = np.ma.array(dem, mask=np.ma.getmaskarray(out))
out.set_fill_value(dem.fill_value)
return out |
java | public java.lang.String getCharset() {
return (java.lang.String) getStateHelper().eval(PropertyKeys.charset);
} |
java | public List<OntologyTerm> findExcatOntologyTerms(
List<String> ontologyIds, Set<String> terms, int pageSize) {
List<OntologyTerm> findOntologyTerms = findOntologyTerms(ontologyIds, terms, pageSize);
return findOntologyTerms
.stream()
.filter(ontologyTerm -> isOntologyTermExactMatch(terms, ... |
java | public MedicationStatement addSupportingInformation(Reference t) { //3
if (t == null)
return this;
if (this.supportingInformation == null)
this.supportingInformation = new ArrayList<Reference>();
this.supportingInformation.add(t);
return this;
} |
python | def _load_results(self, container_id):
"""
load results from recent build
:return: BuildResults
"""
if self.temp_dir:
dt = DockerTasker()
# FIXME: load results only when requested
# results_path = os.path.join(self.temp_dir, RESULTS_JSON)
... |
java | private void populateMemberData(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException
{
m_reader = reader;
m_file = file;
m_eventManager = file.getEventManager();
m_root = root;
//
// Retrieve the high level document properties (never encoded)... |
java | public void registerDeployer(CamelEndpointDeployerService deploymentService) {
synchronized (scheduledHandlers) {
/* Deploy the endpoints scheduled so far */
for (Iterator<Entry<URI, Object>> it = scheduledHandlers.entrySet().iterator(); it
.hasNext();) {
... |
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: MemberContext for this MemberInstance
:rtype: twilio.rest.api.v2010.account.queue.member.MemberCo... |
python | def avl_release_kids(node):
"""
splits a node from its kids maintaining parent pointers
"""
left, right = node.left, node.right
if left is not None:
# assert left.parent is node
left.parent = None
if right is not None:
# assert right.parent is node
right.parent = ... |
java | public Observable<Page<OutboundRuleInner>> listAsync(final String resourceGroupName, final String loadBalancerName) {
return listWithServiceResponseAsync(resourceGroupName, loadBalancerName)
.map(new Func1<ServiceResponse<Page<OutboundRuleInner>>, Page<OutboundRuleInner>>() {
@Overri... |
python | def next_update(self):
"""Compute the next expected update date,
given the frequency and last_update.
Return None if the frequency is not handled.
"""
delta = None
if self.frequency == 'daily':
delta = timedelta(days=1)
elif self.frequency == 'weekly'... |
python | def theta_join(self):
"""
select_expr ::= select param_start conditions param_stop expression
"""
long = self.parametrize(self.syntax.theta_join_op, self.conditions)
short = self.parametrize(self.syntax.join_op, self.conditions).\
setParseAction(self.theta_parse_actio... |
python | def _parse_requestline(line):
"""
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5
>>> Entry._parse_requestline('GET / HTTP/1.0') == ('GET', '/', '1.0')
True
>>> Entry._parse_requestline('post /testurl htTP/1.1') == ('POST', '/testurl', '1.1')
True
>>> ... |
java | public final Method getTargetMethod() {
Method method = initialize();
if (method == null) {
if (LOG.isWarnEnabled()) {
if (LOG.isWarnEnabled()) {
LOG.warn("Type [{}] previously declared a method [{}] which has been removed or changed. It is recommended you... |
java | public List<I_CmsHistoryResource> readAllAvailableVersions(String resourceName) throws CmsException {
CmsResource resource = readResource(resourceName, CmsResourceFilter.ALL);
return m_securityManager.readAllAvailableVersions(m_context, resource);
} |
python | def available_resource_group_delegations(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`AvailableResourceGroupDelegationsOperations<azure.mgmt.network.v2018_08_01.operations.AvailableResourceGroupDelegationsOperations>`
"""
api_version = self._get_api_version('a... |
python | def _default_out_of_place(func, x, **kwargs):
"""Default in-place evaluation method."""
if is_valid_input_array(x, func.domain.ndim):
scalar_out_shape = out_shape_from_array(x)
elif is_valid_input_meshgrid(x, func.domain.ndim):
scalar_out_shape = out_shape_from_meshgrid(x)
else:
... |
python | def portalServerHandler(self, serverUrl, username=None):
"""
returns a handler to access a federated server
serverUrl - url to the server. Example:
https://server.site.com/arcgis
username - the portal site username. if None is passed, it obtains
it from the ... |
python | def locked_repository(
self, with_dev_reqs=False
): # type: (bool) -> poetry.repositories.Repository
"""
Searches and returns a repository of locked packages.
"""
if not self.is_locked():
return poetry.repositories.Repository()
lock_data = self.lock_data... |
python | def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD):
"""
Generate binary Morse code of message at a given code speed wpm and framerate
Parameters
----------
word : string
wpm : int or float - word per minute
framera... |
java | public long skip(long n) throws IOException {
long remaining = n;
int nr;
if (n <= 0) {
return 0;
}
int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining);
byte[] skipBuffer = new byte[size];
while (remaining > 0) {
nr = read(skipBuff... |
java | public ChainCodeResponse query(QueryRequest queryRequest) throws ChainCodeException, NoAvailableTCertException, CryptoException, IOException {
logger.debug("Member.query");
if (getChain().getPeers().isEmpty()) {
throw new NoValidPeerException(String.format("chain %s has no peers", getChain().g... |
java | public void initialize()
{
super.initialize();
//
// Register the ServletService classes associated with the ServletServiceProvider
//
ServletServiceProvider ssp = ServletServiceProvider.getProvider();
addService(ServletContext.class, ssp);
addService(Servlet... |
python | def authenticate(self, username, password):
"""
Uses a Smappee username and password to request an access token,
refresh token and expiry date.
Parameters
----------
username : str
password : str
Returns
-------
requests.Response
... |
java | public AppendObjectResponse appendObject(String bucketName, String key, String value, ObjectMetadata metadata) {
try {
return this.appendObject(bucketName, key, value.getBytes(DEFAULT_ENCODING), metadata);
} catch (UnsupportedEncodingException e) {
throw new BceClientException("F... |
python | def cli(ctx, config, quiet):
"""AWS ECS Docker Deployment Tool"""
ctx.obj = {}
ctx.obj['config'] = load_config(config.read()) # yaml.load(config.read())
ctx.obj['quiet'] = quiet
log(ctx, ' * ' + rnd_scotty_quote() + ' * ') |
java | public final EObject ruleAssignableTerminal() throws RecognitionException {
EObject current = null;
EObject this_Keyword_0 = null;
EObject this_RuleCall_1 = null;
EObject this_ParenthesizedAssignableElement_2 = null;
EObject this_CrossReference_3 = null;
enterRule... |
python | def get_single_child_from_xml(elem, tag):
"""
Get a single child tag from an XML element.
Similar to "elem.find(tag)", but warns if there are multiple child tags with the given name.
"""
children = elem.findall(tag)
if not children:
return None
if len(children) > 1:
logging.w... |
python | async def send_media_group(self, chat_id: typing.Union[base.Integer, base.String],
media: typing.Union[types.MediaGroup, typing.List],
disable_notification: typing.Union[base.Boolean, None] = None,
reply_to_message_id: typing.U... |
java | public ConfigRenderOptions setFormatted(boolean value) {
if (value == formatted)
return this;
else
return new ConfigRenderOptions(originComments, comments, value, json);
} |
python | def get_system_uptime_output_show_system_uptime_hours(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_system_uptime = ET.Element("get_system_uptime")
config = get_system_uptime
output = ET.SubElement(get_system_uptime, "output")
show_... |
java | public OvhOrder email_exchange_organizationName_service_exchangeService_accountUpgrade_duration_POST(String organizationName, String exchangeService, String duration, OvhAccountQuotaEnum newQuota, String primaryEmailAddress) throws IOException {
String qPath = "/order/email/exchange/{organizationName}/service/{exchan... |
java | protected Map<String, String> attributesByBeanRef(String beanRef) {
Map<String, String> result = null;
for (Entry<String, String> e : map.entrySet()) {
final String k = e.getKey();
if (k.startsWith(beanRef) && k.startsWith(DOT, beanRef.length())) {
if (result == null) {
... |
java | public QueryFilter withPage(int pageNumber, int amountPerPage) {
parameters.put("page", pageNumber);
parameters.put("per_page", amountPerPage);
return this;
} |
python | def libvlc_media_list_player_get_state(p_mlp):
'''Get current libvlc_state of media list player.
@param p_mlp: media list player instance.
@return: libvlc_state_t for media list player.
'''
f = _Cfunctions.get('libvlc_media_list_player_get_state', None) or \
_Cfunction('libvlc_media_list_pla... |
java | @Indexable(type = IndexableType.REINDEX)
@Override
public CommerceShippingFixedOption updateCommerceShippingFixedOption(
CommerceShippingFixedOption commerceShippingFixedOption) {
return commerceShippingFixedOptionPersistence.update(commerceShippingFixedOption);
} |
python | def reset(self, index=None):
'''
Reset the points for the specified index position. If no index is
specified, reset points for all point handlers.
'''
points_handler_count = len(self.registration_view.points)
if index is None:
indexes = range(points_handler_c... |
java | int getNumBranches(int lineNumber) {
Integer numBranches = branchesInLine.get(lineNumber - 1);
if (numBranches == null) {
return 0;
} else {
return numBranches;
}
} |
java | @SuppressWarnings({"checkstyle:npathcomplexity"})
protected void fireAgentDestroyed(Agent agent) {
final ListenerCollection<SpawnServiceListener> list;
synchronized (getAgentLifecycleListenerMutex()) {
list = this.agentLifecycleListeners.get(agent.getID());
}
final SpawnServiceListener[] ilisteners;
if (l... |
python | def _make_graph(bsname, version=None, data_dir=None):
'''
Create a DOT graph file of the files included in a basis set
'''
if not graphviz_avail:
raise RuntimeError("graphviz package is not installed")
data_dir = api.fix_data_dir(data_dir)
md = api._get_basis_metadata(bsname, data_dir... |
java | public UserListResult getUserList(int start, int count)
throws APIConnectionException, APIRequestException {
if (start < 0 || count <= 0 || count > 500) {
throw new IllegalArgumentException("negative index or count must more than 0 and less than 501");
}
ResponseWrapper ... |
java | public <T extends Message> ObjectOrStatus<T> request(
T.Builder builder, String path, String method, T body, String apiVersion, String kind)
throws ApiException, IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", MEDIA_TYPE);
headers.put("Accept", MEDIA_... |
python | def vertex_to_entity_path(vertex_path,
graph,
entities,
vertices=None):
"""
Convert a path of vertex indices to a path of entity indices.
Parameters
----------
vertex_path : (n,) int
Ordered list of vertex indices... |
python | def cleanup_defenses(self):
"""Cleans up all data about defense work in current round."""
print_header('CLEANING UP DEFENSES DATA')
work_ancestor_key = self.datastore_client.key('WorkType', 'AllDefenses')
keys_to_delete = [
e.key
for e in self.datastore_client.query_fetch(kind=u'Classifi... |
python | def xpnsl(h1, h2, use_threads=True):
"""Cross-population version of the NSL statistic.
Parameters
----------
h1 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for the first population.
h2 : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array for th... |
python | def init(cls, *args, **kwargs):
"""Initialize the config like as you would a regular dict."""
instance = cls()
instance._values.update(dict(*args, **kwargs))
return instance |
java | public void setPhoneNumbers(java.util.Collection<PhoneNumber> phoneNumbers) {
if (phoneNumbers == null) {
this.phoneNumbers = null;
return;
}
this.phoneNumbers = new java.util.ArrayList<PhoneNumber>(phoneNumbers);
} |
java | public static void main(String[] args) {
ArrayList<String> tmpArgs = new ArrayList<String>(Arrays.asList(args));
// Get number of threads for multithreading mode
int numThreads = 1;
for (int i=0; i<tmpArgs.size()-1; i++) {
if (tmpArgs.get(i).equals("-t")) {
t... |
python | def reset(self):
"""Reset the solver, removing any current solve."""
if not self.request_list.conflict:
phase = _ResolvePhase(self.request_list.requirements, solver=self)
self.pr("resetting...")
self._init()
self._push_phase(phase) |
java | private void copyInParts() throws Exception {
multipartUploadId = initiateMultipartUpload(copyObjectRequest);
long optimalPartSize = getOptimalPartSize(metadata.getContentLength());
try {
CopyPartRequestFactory requestFactory = new CopyPartRequestFactory(
copyOb... |
java | public String getTrigger() {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "getTrigger returning " + trigger);
return this.trigger;
} |
java | public double f(double[] x) {
double result = 0.0;
Benchmark.shift(m_z, x, m_o);
result = Benchmark.schwefel_102(m_z);
// NOISE
// Comment the next line to remove the noise
result *= (1.0 + 0.4 * Math.abs(Benchmark.random.nextGaussian()));
result += mBias;
return (result);
} |
python | def parse_timestamp(timestamp):
"""Parse ISO8601 timestamps given by github API."""
dt = dateutil.parser.parse(timestamp)
return dt.astimezone(dateutil.tz.tzutc()) |
java | public static Tuple<String, String> substring(String strColumn, int pos, int len, String valueName) {
String name = "substring_" + random();
if (valueName == null) {
return new Tuple(name, "def " + name + " = doc['" + strColumn + "'].value.substring(" + pos + "," + len + ")");
} else... |
java | public String signDataWithBase64(byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
String res = null;
byte[] signature = this.signData(data);
// to base64
res = Base64.toBase64String(signature);
return res... |
java | public int levenshteinDistance(UTF8String other) {
// Implementation adopted from org.apache.common.lang3.StringUtils.getLevenshteinDistance
int n = numChars();
int m = other.numChars();
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
UTF8String s, t;
if (n <= m)... |
python | def is_transformed(fastq):
"""
check the first 100 reads to see if a FASTQ file has already been transformed
by umis
"""
with open_fastq(fastq) as in_handle:
for line in islice(in_handle, 400):
if "UMI_" in line:
return True
return False |
java | public static List<List<Term>> seg2sentence(String text, boolean shortest)
{
return ANALYZER.seg2sentence(text, shortest);
} |
python | def obj_from_file(filename='annotation.yaml', filetype='auto'):
''' Read object from file '''
if filetype == 'auto':
_, ext = os.path.splitext(filename)
filetype = ext[1:]
if filetype in ('yaml', 'yml'):
from ruamel.yaml import YAML
yaml = YAML(typ="unsafe")
with op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.