language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def rotateAboutVectorMatrix(vec, theta_deg):
"""Construct the matrix that rotates vector a about
vector vec by an angle of theta_deg degrees
Taken from
http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
Input:
theta_deg (float) Angle through which vectors should... |
python | def show_all(self, as_string=True):
""", python2 will not show flags"""
result = []
for item in self.container:
pattern = str(item[0])[10:] if PY3 else item[0].pattern
instances = item[2] or []
value = (
'%s "%s"' % (item[1].__name__, (item[1].... |
python | def ExecQuery(self, QueryLanguage, Query, namespace=None, **extra):
# pylint: disable=invalid-name
"""
Execute a query in a namespace.
This method performs the ExecQuery operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a list of all
methods performing such... |
java | @Deprecated
public void delete(String job, String instance) throws IOException {
delete(job, Collections.singletonMap("instance", instance));
} |
python | def delete(context, force, yes, analysis_id):
"""Delete an analysis log from the database."""
analysis_obj = context.obj['store'].analysis(analysis_id)
if analysis_obj is None:
print(click.style('analysis log not found', fg='red'))
context.abort()
print(click.style(f"{analysis_obj.famil... |
java | void notifyListenersOnStateChange() {
LOGGER.debug("Notifying connection listeners about state change to {}", state);
for (ConnectionListener listener : connectionListeners) {
switch (state) {
case CONNECTED:
listener.onConnectionEstablished... |
java | public CmsClientSitemapEntry removeSubEntry(CmsUUID entryId) {
CmsClientSitemapEntry removed = null;
int position = -1;
if (!m_subEntries.isEmpty()) {
for (int i = 0; i < m_subEntries.size(); i++) {
if (m_subEntries.get(i).getId().equals(entryId)) {
... |
java | @NullSafe
public static boolean isWaiting(Thread thread) {
return (thread != null && Thread.State.WAITING.equals(thread.getState()));
} |
python | def register_transport_ready_event(self, user_cb, user_arg):
"""
Register for transport ready events. The `transport ready`
event is raised via a user callback. If the endpoint
is configured as a source, then the user may then
call :py:meth:`write_transport` in order to send da... |
java | public String getString(String name, String defaultValue) {
JsonValue value = get(name);
return value != null ? value.asString() : defaultValue;
} |
python | def tandem(args):
"""
%prog tandem blast_file cds_file bed_file [options]
Find tandem gene clusters that are separated by N genes, based on filtered
blast_file by enforcing alignments between any two genes at least 50%
(or user specified value) of either gene.
pep_file can also be used in same... |
java | protected String toBase64(String user, String password) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(user);
stringBuffer.append(":");
stringBuffer.append(password);
return Base64Utility.encode(stringBuffer.toString().getBytes());
} |
java | public static Calendar popCalendar()
{
Calendar result;
Deque<Calendar> calendars = CALENDARS.get();
if (calendars.isEmpty())
{
result = Calendar.getInstance();
}
else
{
result = calendars.pop();
}
return result;
} |
java | @Conditioned
@Lorsque("Je mets à jour la case à cocher '(.*)-(.*)' avec '(.*)'[\\.|\\?]")
@Then("I update checkbox '(.*)-(.*)' with '(.*)'[\\.|\\?]")
public void selectCheckbox(String page, String elementKey, boolean value, List<GherkinStepCondition> conditions) throws TechnicalException, FailureExceptio... |
java | public static Runnable writeTerminusMarker(final String nonce, final NodeSettings paths, final VoltLogger logger) {
final File f = new File(paths.getVoltDBRoot(), VoltDB.TERMINUS_MARKER);
return new Runnable() {
@Override
public void run() {
try(PrintWriter pw = n... |
java | public static CmsEntityAttribute createEntityAttribute(String name, List<CmsEntity> values) {
CmsEntityAttribute result = new CmsEntityAttribute();
result.m_name = name;
result.m_entityValues = Collections.unmodifiableList(values);
return result;
} |
java | private AbstractPlanNode addProjection(AbstractPlanNode rootNode) {
assert (m_parsedSelect != null);
assert (m_parsedSelect.m_displayColumns != null);
// Build the output schema for the projection based on the display columns
NodeSchema proj_schema = m_parsedSelect.getFinalProjectionSch... |
java | private static void formatBadLogData(LogData data, StringBuilder out) {
out.append(" original message: ");
if (data.getTemplateContext() == null) {
out.append(data.getLiteralArgument());
} else {
// We know that there's at least one argument to display here.
out.append(data.getTemplateCon... |
python | def from_string(contents):
"""
Creates GaussianInput from a string.
Args:
contents: String representing an Gaussian input file.
Returns:
GaussianInput object
"""
lines = [l.strip() for l in contents.split("\n")]
link0_patt = re.compile(r... |
python | def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME):
"""
View decorator that checks for the given permissions before allowing the
view to execute. Use it like this::
from django.shortcuts import get_object_or_404
from rules.... |
java | public final Intent updateIntent(Intent intent, String languageCode, FieldMask updateMask) {
UpdateIntentRequest request =
UpdateIntentRequest.newBuilder()
.setIntent(intent)
.setLanguageCode(languageCode)
.setUpdateMask(updateMask)
.build();
return updat... |
java | public static boolean isAllBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css) {
if (isNotBlank(cs)) {
return false;
}
}
return true;
} |
java | public Set<TypedEdge<T>> getAdjacencyList(int vertex) {
SparseTypedEdgeSet<T> edges = vertexToEdges.get(vertex);
return (edges == null)
? Collections.<TypedEdge<T>>emptySet()
: new EdgeListWrapper(edges);
} |
java | public static String unpackString(Object obj) {
Object value = unpack(obj);
return value == null ? null : value.toString();
} |
java | void rbbiSymtablePrint() {
System.out
.print("Variable Definitions\n"
+ "Name Node Val String Val\n"
+ "----------------------------------------------------------------------\n");
RBBISymbolTableEntry[] syms = fHashTable.... |
java | @PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
protected void handlePostRequest(final HttpServletResponse response,
final HttpServletRequest request) {
val ctx = decodeSoapRequest(request);
val query = (AttributeQuery) ctx.getMessage()... |
java | static int parseEtcResolverFirstNdots(File etcResolvConf) throws IOException {
FileReader fr = new FileReader(etcResolvConf);
BufferedReader br = null;
try {
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
if ... |
python | def parse_attrlist_0(str_, avs_sep=":", vs_sep=",", as_sep=";"):
"""
Simple parser to parse expressions in the form of
[ATTR1:VAL0,VAL1,...;ATTR2:VAL0,VAL2,..].
:param str_: input string
:param avs_sep: char to separate attribute and values
:param vs_sep: char to separate values
:param as... |
java | @SuppressWarnings("unchecked")
@SneakyThrows
public void init(final SQLStatementRuleDefinitionEntity dialectRuleDefinitionEntity, final ExtractorRuleDefinition extractorRuleDefinition) {
for (SQLStatementRuleEntity each : dialectRuleDefinitionEntity.getRules()) {
SQLStatementRule sqlStatemen... |
java | public Map getAsMap() {
if (mMap != null) {
return mMap;
} else {
Map m = convertToMap();
if (!isMutable()) {
mMap = m;
}
return m;
}
} |
python | def com_google_fonts_check_metadata_subsets_order(family_metadata):
"""METADATA.pb subsets should be alphabetically ordered."""
expected = list(sorted(family_metadata.subsets))
if list(family_metadata.subsets) != expected:
yield FAIL, ("METADATA.pb subsets are not sorted "
"in alphabetical o... |
java | public static FilesIterator<File> getRelativeIterator(String baseDir) {
return new FilesIterator<File>(new File(baseDir), Strategy.RELATIVE_FILES);
} |
python | def parse(self, data, extent, desc_tag):
# type: (bytes, int, UDFTag) -> None
'''
Parse the passed in data into a UDF Implementation Use Volume
Descriptor.
Parameters:
data - The data to parse.
extent - The extent that this descriptor currently lives at.
... |
python | def add_scene(self, animation_id, name, color, velocity, config):
"""Add a new scene, returns Scene ID"""
# check arguments
if animation_id < 0 or animation_id >= len(self.state.animationClasses):
err_msg = "Requested to register scene with invalid Animation ID. Out of range."
... |
java | public DMatrixRMaj getQ() {
Equation eq = new Equation();
DMatrixRMaj Q = CommonOps_DDRM.identity(QR.numRows);
DMatrixRMaj u = new DMatrixRMaj(QR.numRows,1);
int N = Math.min(QR.numCols,QR.numRows);
eq.alias(u,"u",Q,"Q",QR,"QR",QR.numRows,"r");
// compute Q by first e... |
python | def check_resource(resource):
'''
Check a resource availability against a linkchecker backend
The linkchecker used can be configured on a resource basis by setting
the `resource.extras['check:checker']` attribute with a key that points
to a valid `udata.linkcheckers` entrypoint. If not set, it will... |
python | def _reduce_data(self):
"""Private method to reduce data dimension.
If data is dense, uses randomized PCA. If data is sparse, uses
randomized SVD.
TODO: should we subtract and store the mean?
Returns
-------
Reduced data matrix
"""
if self.n_pca ... |
python | def make_symbol_table(use_numpy=True, **kws):
"""Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Retu... |
python | def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
url = '{}/userinfo'.format(self.BASE_URL)
response = self.get_json(
url,
headers={'Authorization': 'Bearer ' + access_token},
)
self.check_correct_audience(response['aud... |
python | def get_or_create(self, log_name, bucket_size):
"""
Gets or creates a log.
:rtype: Timebucketedlog
"""
try:
return self[log_name]
except RepositoryKeyError:
return start_new_timebucketedlog(log_name, bucket_size=bucket_size) |
python | def _reset_build(self, sources):
"""Remove partition datafiles and reset the datafiles to the INGESTED state"""
from ambry.orm.exc import NotFoundError
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
self.log("Removing old segment partition: {}".format... |
java | private static ActivationFunction natural(ErrorFunction error, int k) {
if (error == ErrorFunction.CROSS_ENTROPY) {
if (k == 1) {
return ActivationFunction.LOGISTIC_SIGMOID;
} else {
return ActivationFunction.SOFTMAX;
}
} else {
... |
java | static void init(ServletContext servletContext) {
String webPath = servletContext.getRealPath("/");
if (webPath == null) {
try {
// 支持 weblogic: http://www.jfinal.com/feedback/1994
webPath = servletContext.getResource("/").getPath();
} catch (java.net.MalformedURLException e) {
com.jfinal.k... |
java | public void enableBlending()
{
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GlStateManager.alphaFunc(GL11.GL_GREATER, 0.0F);
GlStateManager.shadeModel(GL11.GL_SMOOTH);
GlStateManager.enableColorMaterial();
} |
python | def tau_from_final_mass_spin(final_mass, final_spin, l=2, m=2, nmodes=1):
"""Returns QNM damping time for the given mass and spin and mode.
Parameters
----------
final_mass : float or array
Mass of the black hole (in solar masses).
final_spin : float or array
Dimensionless spin of t... |
python | async def _connect(self):
"""Start asynchronous reconnect loop."""
self.waiting = True
await self.client.start(self.ip)
self.waiting = False
if self.client.protocol is None:
raise IOError("Could not connect to '{}'.".format(self.ip))
self.open = True |
java | public com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.NumericalStatsResult
getNumericalStatsResult() {
if (resultCase_ == 3) {
return (com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.NumericalStatsResult) result_;
}
return com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.Num... |
java | public ServiceFuture<List<OutputInner>> listByStreamingJobAsync(final String resourceGroupName, final String jobName, final ListOperationCallback<OutputInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByStreamingJobSinglePageAsync(resourceGroupName, jobName),
new... |
python | def weld_str_get(array, i):
"""Retrieve character at index i.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
i : int
Index of character to retrieve. If greater than length of string, returns None.
Returns
-------
WeldObject
Representation ... |
python | def _create_sequences(self):
'''Get all of the Sequences - Rosetta, ATOM, SEQRES, FASTA, UniParc.'''
# Create the Rosetta sequences and the maps from the Rosetta sequences to the ATOM sequences
try:
self.pdb.construct_pdb_to_rosetta_residue_map(self.rosetta_scripts_path, rosetta_dat... |
python | def project_add_tags(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /project-xxxx/addTags API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2FaddTags
"""
return DXHTTPRequest('/%s/addTags' % object_id... |
python | def collapse_substrings(variant_sequences):
"""
Combine shorter sequences which are fully contained in longer sequences.
Parameters
----------
variant_sequences : list
List of VariantSequence objects
Returns a (potentially shorter) list without any contained subsequences.
"""
if... |
python | def val_to_mrc(code, val):
"""
Convert one single `val` to MRC.
This function may be used for control fields in MARC records.
Args:,
code (str): Code of the field.
val (str): Value of the field.
Returns:
str: Correctly padded MRC line with field.
"""
code = str(cod... |
python | def change_format(self, new_format):
"""Change the format label of this content.
Note that this does NOT actually alter the format of the content, only
the label.
"""
self._load_raw_content()
self._format = new_format
self.get_filename(renew=True)
self.ge... |
java | @FromString
public static Days parseDays(String periodStr) {
if (periodStr == null) {
return Days.ZERO;
}
Period p = PARSER.parsePeriod(periodStr);
return Days.days(p.getDays());
} |
python | def tidied(name,
age=0,
matches=None,
rmdirs=False,
size=0,
**kwargs):
'''
Remove unwanted files based on specific criteria. Multiple criteria
are OR’d together, so a file that is too large but is not old enough
will still get tidied.
If neithe... |
python | def mode(dev, target):
""" Gets or sets the active mode. """
click.echo("Current mode: %s" % dev.mode_readable)
if target:
click.echo("Setting mode: %s" % target)
dev.mode = target |
java | private int compareStarts(Interval<T> other){
if (start == null && other.start == null)
return 0;
if (start == null)
return -1;
if (other.start == null)
return 1;
int compare = start.compareTo(other.start);
if (compare != 0)
return compare;
if (isStartInclusive ^ other.isStartInclusive)
retur... |
java | public static String escapeName(String name) {
if (StringUtils.isBlank(name)) {
throw new IllegalArgumentException("Blank or null is not a valid name.");
} else if (java.util.regex.Pattern.matches(NAME, name)) {
return name;
} else {
return name.replaceAll("[^... |
python | def dir2fn(ofn, ifn, suffix) -> Union[None, Path]:
"""
ofn = filename or output directory, to create filename based on ifn
ifn = input filename (don't overwrite!)
suffix = desired file extension e.g. .h5
"""
if not ofn: # no output file desired
return None
ofn = Path(ofn).expanduse... |
python | def _create_syns(b, needed_syns):
"""
Create empty synthetics
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter list needed_syns: list of dictionaries containing kwargs to access
the dataset (dataset, component, kind)
:return: :class:`phoebe.parameters.parameters.Parameter... |
java | public int convertExternalToInternal(Object recordOwner)
{
// Step 4 - Convert the JAXB objects to my internal format
Object root = this.convertToMessage();
if (root == null)
return DBConstants.ERROR_RETURN;
return this.getConvertToMessage().convertMarshallableObjectToInt... |
python | def variable_device(device, name):
"""Fix the variable device to colocate its ops."""
if callable(device):
var_name = tf.get_variable_scope().name + '/' + name
var_def = tf.NodeDef(name=var_name, op='Variable')
device = device(var_def)
if device is None:
device = ''
return device |
java | public void setScope(java.util.Collection<String> scope) {
if (scope == null) {
this.scope = null;
return;
}
this.scope = new com.amazonaws.internal.SdkInternalList<String>(scope);
} |
java | public static SimpleFeatureSource readFeatureSource( String path ) throws Exception {
File shapeFile = new File(path);
FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
SimpleFeatureSource featureSource = store.getFeatureSource();
return featureSource;
} |
python | def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None):
"""
Returns an estimate of the marginal distribution of a given model parameter, based on
taking the derivative of the interpolated cdf.
:param int idx_param: Index of parameter to be margin... |
python | def full_name(self):
"""Get the name of the day of the week.
Returns
-------
StringValue
The name of the day of the week
"""
import ibis.expr.operations as ops
return ops.DayOfWeekName(self.op().arg).to_expr() |
python | def advance(self, height, ignore_overflow=False):
"""Advance the cursor by `height`. If this would cause the cursor to
point beyond the bottom of the container, an :class:`EndOfContainer`
exception is raised."""
if height <= self.remaining_height:
self._self_cursor.grow(heigh... |
java | @Override
public CPDefinitionLocalization findByCPDefinitionId_Last(
long CPDefinitionId,
OrderByComparator<CPDefinitionLocalization> orderByComparator)
throws NoSuchCPDefinitionLocalizationException {
CPDefinitionLocalization cpDefinitionLocalization = fetchByCPDefinitionId_Last(CPDefinitionId,
orderByCom... |
java | private void addEntryTableToLayout(
List<CmsAccessControlEntry> entries,
VerticalLayout layout,
boolean editable,
boolean inheritedRes) {
final CmsPermissionViewTable table = new CmsPermissionViewTable(
m_cms,
entries,
editable,
in... |
python | def hide(*keys):
"""
Hide a set of request and/or response fields from logs.
Example:
@hide("id")
def create_foo():
return Foo(id=uuid4())
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
g.hide_request_fields = keys
... |
java | private void loadStaticField(XField staticField, Instruction obj) {
if (RLE_DEBUG) {
System.out.println("[loadStaticField for field " + staticField + " in instruction " + handle);
}
ValueNumberFrame frame = getFrame();
AvailableLoad availableLoad = new AvailableLoad(staticF... |
python | def write(self, session, directory, name, replaceParamFile=None, **kwargs):
"""
Wrapper for GsshaPyFileObjectBase write method
"""
if self.raster is not None or self.rasterText is not None:
super(RasterMapFile, self).write(session, directory, name, replaceParamFile, **kwargs... |
python | def beginningPage(R):
"""As pages may not be given as numbers this is the most accurate this function can be"""
p = R['PG']
if p.startswith('suppl '):
p = p[6:]
return p.split(' ')[0].split('-')[0].replace(';', '') |
java | public static Locale parseLocale(String localeString) {
if (localeString == null || localeString.length() == 0) {
return Locale.getDefault();
}
localeString = localeString.trim();
if (localeString == null) {
return null;
}
String language = "";
... |
python | def remove_members_outside_rank_in(self, leaderboard_name, rank):
'''
Remove members from the named leaderboard in a given rank range.
@param leaderboard_name [String] Name of the leaderboard.
@param rank [int] the rank (inclusive) which we should keep.
@return the total member ... |
java | public static long queryNumEntries(SQLiteDatabase db, String table, String selection) {
return queryNumEntries(db, table, selection, null);
} |
python | def unmap_volume_from_sdc(self, volObj, sdcObj=None, **kwargs):
"""
Unmap a Volume from SDC or all SDCs
:param volObj: ScaleIO Volume object
:param sdcObj: ScaleIO SDC object
:param \**kwargs:
:Keyword Arguments:
*disableMapAllSdcs* (``bool``) -- True to disable a... |
python | def _confirm_prompt(message, prompt="\nAre you sure? [y/yes (default: no)]: ",
affirmations=("Y", "Yes", "yes", "y")):
"""
Display a message, then confirmation prompt, and return true
if the user responds with one of the affirmations.
"""
answer = input(message + prompt)
retu... |
java | @Override
public void deserialize(String jsonString) {
final GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
final Gson gson = builder.create();
Logo w = gson.fromJson(jsonString, Logo.class);
this.nid = w.nid;
this.brand = w.b... |
python | def is_multi_target(target):
"""
Determine if pipeline manager's run target is multiple.
:param None or str or Sequence of str target: 0, 1, or multiple targets
:return bool: Whether there are multiple targets
:raise TypeError: if the argument is neither None nor string nor Sequence
"""
if ... |
java | public String n1qlToRawJson(N1qlQuery query) {
return Blocking.blockForSingle(async.n1qlToRawJson(query), env.queryTimeout(), TimeUnit.MILLISECONDS);
} |
python | def swf2png(swf_path, png_path, swfrender_path="swfrender"):
"""Convert SWF slides into a PNG image
Raises:
OSError is raised if swfrender is not available.
ConversionError is raised if image cannot be created.
"""
# Currently rely on swftools
#
# Would be great to have a native... |
java | private void processChildEvent(WatchedEvent event) throws Exception {
HashMap<Integer, LeaderCallBackInfo> cacheCopy = new HashMap<Integer, LeaderCallBackInfo>(m_publicCache);
ByteArrayCallback cb = new ByteArrayCallback();
m_zk.getData(event.getPath(), m_childWatch, cb, null);
try {
... |
python | def get_item(self, **kwargs):
""" Get collection item taking into account generated queryset
of parent view.
This method allows working with nested resources properly. Thus an item
returned by this method will belong to its parent view's queryset, thus
filtering out objects that... |
python | def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
try:
if not isinstance(params[key], list): params[key] = [params[key]]
params[key] += [par... |
java | public static <T> T getBundle(Class<T> type) {
return getBundle(type, Locale.getDefault());
} |
java | Expression XreadAllTypesValueExpressionPrimary(boolean boole) {
Expression e = null;
switch (token.tokenType) {
case Tokens.EXISTS :
case Tokens.UNIQUE :
if (boole) {
return XreadPredicate();
}
break;
... |
python | def unset(self, section, option):
"""Remove option from section."""
with self._lock:
if not self._config.has_section(section):
return
if self._config.has_option(section, option):
self._config.remove_option(section, option)
self._dir... |
python | def to_utf8(path, output_path=None):
"""Convert any text file to utf8 encoding.
"""
if output_path is None:
basename, ext = os.path.splitext(path)
output_path = basename + "-UTF8Encode" + ext
text = smartread(path)
write(text, output_path) |
java | public void add(final String string) {
checkNotNull(string);
candidates.put(string, candidate(string));
} |
java | public final EObject entryRuleNotExpression() throws RecognitionException {
EObject current = null;
EObject iv_ruleNotExpression = null;
try {
// InternalSimpleAntlr.g:1078:2: (iv_ruleNotExpression= ruleNotExpression EOF )
// InternalSimpleAntlr.g:1079:2: iv_ruleNotExp... |
java | private Iterator detailChildrenIterator(Detail detail) {
/*
sb.append("<ns2:AccessDeniedWebServiceException xmlns:ns2=\"http://exceptionthrower.system.services.v4_0.soap.server.nameapi.org/\">");
sb.append("<blame>CLIENT</blame>");
sb.append("<errorCode>2101</errorCode>");
sb.app... |
java | public static double matthewsCorrelation(long tp, long fp, long fn, long tn) {
double numerator = ((double) tp) * tn - ((double) fp) * fn;
double denominator = Math.sqrt(((double) tp + fp) * (tp + fn) * (tn + fp) * (tn + fn));
return numerator / denominator;
} |
python | def _clone(self):
"""Make a (shallow) copy of the set.
There is a 'clone protocol' that subclasses of this class
should use. To make a copy, first call your super's _clone()
method, and use the object returned as the new instance. Then
make shallow copies of the attributes def... |
java | @Override
protected I_CmsSearchDocument appendCategories(
I_CmsSearchDocument document,
CmsObject cms,
CmsResource resource,
I_CmsExtractionResult extractionResult,
List<CmsProperty> properties,
List<CmsProperty> propertiesSearched) {
Document doc = (Document... |
python | def fasta_verifier(entries, ambiguous=False):
"""Raises error if invalid FASTA format detected
Args:
entries (list): A list of FastaEntry instances
ambiguous (bool): Permit ambiguous bases, i.e. permit non-ACGTU bases
Raises:
FormatError: Error when FASTA format incorrect with des... |
java | public static void runPipeline(File scriptFile, List<String> cliArgs)
throws IOException, UIMAException, ParseException {
if (!scriptFile.exists()) {
throw new IOException("Script file does not exist ("
+ scriptFile.getAbsolutePath() + ")");
}
LOG.inf... |
python | def load(cls, path_to_file):
"""
Loads the image data from a file on disk and tries to guess the image MIME type
:param path_to_file: path to the source file
:type path_to_file: str
:return: a `pyowm.image.Image` instance
"""
import mimetypes
mimetypes.in... |
java | @Override
public CacheConfiguration<K, V> setTypes(Class<K> keyType, Class<V> valueType) {
if (keyType == null || valueType == null) {
throw new NullPointerException("keyType and/or valueType can't be null");
}
setKeyType(keyType);
setValueType(valueType);
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.