language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def do_format(self, format):
"""Apply format selection.
Assume that for tiling applications we want jpg so return
that unless an explicit format is requested.
"""
fmt = ('jpg' if (format is None) else format)
if (fmt == 'png'):
self.logger.debug("format: png"... |
java | public void disconnect(Destination d) throws KNXLinkClosedException
{
if (detached)
throw new KNXIllegalStateException("TL detached");
if (d.getState() != Destination.DESTROYED
&& d.getState() != Destination.DISCONNECTED)
disconnectIndicate(getProxy(d), true);
} |
java | protected void handshakeReceived(IoSession session,
HandshakeMessage handshakeMessage) {
log.debug("Received {}", handshakeMessage);
this.receivedHandshake = handshakeMessage;
Boolean handshakeCheck = this.checkHandshake();
if (handshakeCheck == null) {
return;
}
if (Boolean.FALSE.equals(handshakeChe... |
python | def delete_user(self, user, group):
""" Deletes user from group """
if not self.__contains__(group):
raise GroupNotExists
if not self.is_user_in(user, group):
raise UserNotInAGroup
self.new_groups.popvalue(group, user) |
python | def _maybe_remove_pool(cls, pid):
"""If the pool has no open connections, remove it
:param str pid: The pool id to clean
"""
if not len(cls._pools[pid]):
del cls._pools[pid] |
java | private void combineHydrogenPositions(List<Integer> taken, List<List<Integer>> combinations,
IAtomContainer skeleton, int totalMobHydrCount, List<Integer> mobHydrAttachPositions) {
if (taken.size() != totalMobHydrCount) {
for (int i = 0; i < mobHydrAttachPositions.size(); i++) {
... |
python | def wait_for_stable_cluster(
hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
):
"""
Block the caller until the cluster can be considered stable.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_por... |
python | def get_single_int_autoincrement_colname(table_: Table) -> Optional[str]:
"""
If a table has a single integer ``AUTOINCREMENT`` column, this will
return its name; otherwise, ``None``.
- It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but
we should check.
- SQL Server's ``... |
java | public void marshall(OperatingSystemConfigurationManager operatingSystemConfigurationManager, ProtocolMarshaller protocolMarshaller) {
if (operatingSystemConfigurationManager == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
pr... |
python | def Create(self, parent, id, evtHandler):
"""
Called to create the control, which must derive from wx.Control.
*Must Override*
"""
style = wx.TE_MULTILINE
self._tc = wx.TextCtrl(parent, id, "", style=style)
# Disable if cell is clocked, enable if cell is not loc... |
python | def list_traces(
self,
project_id=None,
view=None,
page_size=None,
start_time=None,
end_time=None,
filter_=None,
order_by=None,
page_token=None,
):
"""
Returns of a list of traces that match the filter conditions.
Args:... |
java | public final ListEventsPagedResponse listEvents(ProjectName projectName, String groupId) {
ListEventsRequest request =
ListEventsRequest.newBuilder()
.setProjectName(projectName == null ? null : projectName.toString())
.setGroupId(groupId)
.build();
return listEvents(... |
python | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
j = m... |
python | def add_table_ends(para, oformat='latex', caption="caption-text", label="table"):
"""
Adds the latex table ends
:param para:
:param oformat:
:param caption:
:param label:
:return:
"""
fpara = ""
if oformat == 'latex':
fpara += "\\begin{table}[H]\n"
fpara += "\\ce... |
python | def tabular2html(fname=None, X=None, fin=None, title=None, printheader=False,
split=True, usecss=None, writecss=None, SERVERNAME=None,
SERVER_FROM_CURDIR='../', ROWS_PER_PAGE=1000,
returnstring = False, **kwargs):
"""
Creates an html representation of tabula... |
java | public void marshall(GetBasePathMappingsRequest getBasePathMappingsRequest, ProtocolMarshaller protocolMarshaller) {
if (getBasePathMappingsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(g... |
java | public String getCurrentDir() throws IOException, ServerException {
Reply reply = null;
try {
reply = controlChannel.execute(Command.PWD);
} catch (FTPReplyParseException rpe) {
throw ServerException.embedFTPReplyParseException(rpe);
} catch (UnexpectedReplyCodeEx... |
python | def showPopup(self):
"""
Overloads the popup method from QComboBox to display an ORB tree widget
when necessary.
:sa setShowTreePopup
"""
if not self.showTreePopup():
return super(XOrbRecordBox, self).showPopup()
tree = ... |
python | def writeQuotes(self, quotes):
''' write quotes '''
tName = self.tableName(HBaseDAM.QUOTE)
if tName not in self.__hbase.getTableNames():
self.__hbase.createTable(tName, [ColumnDescriptor(name=HBaseDAM.QUOTE, maxVersions=5)])
for quote in quotes:
self.__hba... |
java | @SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
if (MESSAGE_LOCALE.equals(key)) {
if (value instanceof Locale) {
locale = (Locale) value;
data.put(MESSAGE_LOCALE, value);
} else {
throw new Ill... |
java | public void setVal(int offset, Constant val, long txNum, LogSeqNum lsn) {
internalLock.writeLock().lock();
try {
modifiedBy.add(txNum);
if (lsn != null && lsn.compareTo(lastLsn) > 0)
lastLsn = lsn;
// Put the last LSN in front of the data
lastLsn.writeToPage(contents, LAST_LSN_OFFSET);
... |
python | def get_fragment_lengths(fastafile):
"""Returns dictionary of sequence fragment lengths, keyed by fragment ID.
Biopython's SeqIO module is used to parse all sequences in the FASTA
file.
NOTE: ambiguity symbols are not discounted.
"""
fraglengths = {}
for seq in SeqIO.parse(fastafile, "fast... |
java | public static BtcFormat getCoinInstance(int minFractionPlaces, int... groups) {
return getInstance(COIN_SCALE, defaultLocale(), minFractionPlaces, boxAsList(groups));
} |
java | @Conditioned
@Lorsque("J'utilise l'élément '(.*)-(.*)' pour uploader le fichier '(.*)'[\\.|\\?]")
@Then("I use '(.*)-(.*)' element to upload '(.*)' file[\\.|\\?]")
public void uploadFile(String page, String element, String filename, List<GherkinStepCondition> conditions) throws FailureException, TechnicalEx... |
java | public void writeConfiguration(final OperationContext context) {
final String loggingConfig;
switch (context.getProcessType()) {
case DOMAIN_SERVER: {
loggingConfig = FileResolver.resolvePath(context, "jboss.server.data.dir", PROPERTIES_FILE);
break;
... |
java | public static boolean doesResourceExist(final String location) {
try {
return getResourceFrom(location) != null;
} catch (final Exception e) {
LOGGER.trace(e.getMessage(), e);
}
return false;
} |
python | def section(rows, columns, items, label=None):
"""A section consisting of rows and columns"""
# TODO: Integrate label
sections = []
column_class = "section-column col-sm-%i" % (12 / columns)
for vertical in range(columns):
column_items = []
for horizontal in range(rows):
... |
python | def add_resource(
self,
base_rule,
base_view,
alternate_view=None,
alternate_rule=None,
id_rule=None,
app=None,
):
"""Add route or routes for a resource.
:param str base_rule: The URL rule for the resource. This will be
prefixed by... |
java | public static String reader2String(Reader source) throws IOException {
char[] cbuf = new char[65535];
StringBuffer stringbuf = new StringBuffer();
int count = 0;
while ((count = source.read(cbuf, 0, 65535)) != -1) {
stringbuf.append(cbuf, 0, count);
}
return stringbuf.toString();
} |
java | public static double norm1(double[] x) {
double norm = 0.0;
for (double n : x) {
norm += Math.abs(n);
}
return norm;
} |
python | def strip_text_after_string(txt, junk):
""" used to strip any poorly documented comments at the end of function defs """
if junk in txt:
return txt[:txt.find(junk)]
else:
return txt |
python | def package_roles(request, package_name):
"""
Retrieve a list of users and their attributes roles for a given
package_name. Role is either 'Maintainer' or 'Owner'.
"""
session = DBSession()
package = Package.by_name(session, package_name)
owners = [('Owner', o.name) for o in package.owners]
... |
python | def split_line(line: str) -> typing.Tuple[str, str]:
"""
Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:return:
"""
index = line.find(' ')
if index == -1:
return line.lower(), ''
return line[:index].lower(), lin... |
python | def _run_command(self, ssh, cmd, pty=True):
"""Run a command remotely via SSH.
:param object ssh: The SSHClient
:param str cmd: The command to execute
:param list cmd: The `shlex.split` command to execute
:param bool pty: Whether to allocate a pty
:return: tuple: The st... |
java | public void update (int timeout) throws IOException {
updateThread = Thread.currentThread();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
long startTime = System.currentTimeMillis();
int select = 0;
if (timeout > 0) {
select = selecto... |
java | private String getActual(String actual, double timeTook) {
if (timeTook > 0) {
String lowercase = actual.substring(0, 1).toLowerCase();
actual = "After waiting for " + timeTook + " seconds, " + lowercase + actual.substring(1);
}
return actual;
} |
java | public void marshall(GetTopicRuleRequest getTopicRuleRequest, ProtocolMarshaller protocolMarshaller) {
if (getTopicRuleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getTopicRuleRequest.ge... |
java | @Deprecated
public PackageDoc[] importedPackages() {
// information is not available for binary classfiles
if (tsym.sourcefile == null) return new PackageDoc[0];
ListBuffer<PackageDocImpl> importedPackages = new ListBuffer<>();
//### Add the implicit "import java.lang.*" to the res... |
java | protected List<?> createPatterns(Set<String> literals, Set<String> expressionKeywords,
Set<String> modifiers, Set<String> primitiveTypes, Set<String> punctuation, Set<String> ignored,
Set<String> specialKeywords, Set<String> typeDeclarationKeywords) {
final List<Map<String, ?>> patterns = new ArrayList<>();
... |
java | @Override
public String getLocalName(int index) {
if (index < 0 || index >= attributesList.size()) {
return null;
}
Attribute attr = attributesList.get(index);
// FIXME attr.localName is sometimes null, why?
if (namespaces && attr.localName == null) {
... |
python | def count_divisors(n):
""" Count the number of divisors of an integer n
Args:
n (int): strictly positive integer
Returns:
The number of distinct divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative
"""
if not isinstance(n, int... |
java | public boolean closeIfCached(T geoPackage) {
boolean closed = false;
if (geoPackage != null) {
T cached = get(geoPackage.getName());
if (cached != null && cached == geoPackage) {
closed = close(geoPackage.getName());
}
}
return closed;
} |
python | def main():
'''Main function to run the sensor with passed arguments'''
trig, echo, speed, samples = get_args()
print('trig pin = gpio {}'.format(trig))
print('echo pin = gpio {}'.format(echo))
print('speed = {}'.format(speed))
print('samples = {}'.format(samples))
print('')
va... |
java | @Override
public InjectiveVar2VarSubstitution generateNotConflictingRenaming(VariableGenerator variableGenerator,
ImmutableSet<Variable> variables) {
ImmutableMap<Variable, Variable> newMap = variables.stream()
.map(v -> ... |
python | def on_startup(self):
"""
Defines the slot triggered on Framework startup.
"""
LOGGER.debug("> Calling '{0}' Component Framework 'on_startup' method.".format(self.__class__.__name__))
factory_default_script_editor_file = umbra.ui.common.get_resource_path(
self.__fac... |
java | static <T> Optional<T> findFirst(final Class<T> service) {
final ServiceLoader<T> loader = load(service);
if (loader == null) return empty();
final Iterator<T> services = loader.iterator();
return services.hasNext() ? of(services.next()) : empty();
} |
python | def _sample_oat(problem, N, num_levels=4):
"""Generate trajectories without groups
Arguments
---------
problem : dict
The problem definition
N : int
The number of samples to generate
num_levels : int, default=4
The number of grid levels
"""
group_membership = np.... |
python | def formula_dual(input_formula: str) -> str:
""" Returns the dual of the input formula.
The dual operation on formulas in :math:`B^+(X)` is defined as:
the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by
switching :math:`∧` and :math:`∨`, and
by switching :math:`true` and :ma... |
java | public Date getFrom() {
final TimeInterval first = intervals.first();
if (first != null) {
return new Date(first.getFrom());
}
return null;
} |
java | private int next(boolean justOneToken) throws IOException, KriptonRuntimeException {
if (reader == null) {
throw new KriptonRuntimeException("setInput() must be called first.", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null);
}
if (type == END_TAG) {
depth--;
}
// d... |
python | def remove_attribute_listener(self, attr_name, *args, **kwargs):
"""
Remove a paremeter listener that was previously added using :py:func:`add_attribute_listener`.
For example to remove the ``thr_min_callback()`` callback function:
.. code:: python
vehicle.parameters.remov... |
java | public static boolean isPublicMethodFinal(Class clazz, String name,
TypeDesc retType, TypeDesc[] params)
{
if (!clazz.isInterface()) {
Class[] paramClasses;
if (params == null || params.length == 0) {
paramClasses = ... |
java | @Override
public EClass getIfcElectricCapacitanceMeasure() {
if (ifcElectricCapacitanceMeasureEClass == null) {
ifcElectricCapacitanceMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(799);
}
return ifcElectricCapacitanceMeasureEClass;
} |
java | @Override
public DescribeAuthorizerResult describeAuthorizer(DescribeAuthorizerRequest request) {
request = beforeClientExecution(request);
return executeDescribeAuthorizer(request);
} |
java | private List<DummyItem> loadXmlFromNetwork(String urlString) throws IOException {
String jString;
// Instantiate the parser
List<Entry> entries = null;
List<DummyItem> rtnArray = new ArrayList<DummyItem>();
BufferedReader streamReader = null;
try {
streamReade... |
java | public static int writeDelimitedTo(DataOutput out, Object message, Schema schema)
throws IOException
{
final LinkedBuffer buffer = new LinkedBuffer(LinkedBuffer.MIN_BUFFER_SIZE);
final ProtobufOutput output = new ProtobufOutput(buffer);
schema.writeTo(output, message);
fin... |
java | public String convertIfcFilterTypeEnumToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
python | def OverwriteAndClose(self, compressed_data, size):
"""Directly overwrite the current contents.
Replaces the data currently in the stream with compressed_data,
and closes the object. Makes it possible to avoid recompressing
the data.
Args:
compressed_data: The data to write, must be zlib comp... |
python | def volume_change_correlation(results, references):
r"""
Volume change correlation.
Computes the linear correlation of change in binary object volume between
the contents of the successive binary images supplied. Measured through
the Pearson product-moment correlation coefficient.
Par... |
java | @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String PID = null;
String sDefPID = null;
String methodName = null;
String dsID = null;
Date asOfDateTime = null;
Date versDateTime... |
java | @Override
protected void doHandle(CommandContext ctx) throws CommandFormatException {
String argsStr = ctx.getArgumentsString();
if(argsStr == null) {
throw new CommandFormatException("Missing the command or operation to translate to DMR.");
}
argsStr = clearCmd(argsStr);... |
python | def emit(event, *args, **kwargs):
"""Emit a SocketIO event.
This function emits a SocketIO event to one or more connected clients. A
JSON blob can be attached to the event as payload. This is a function that
can only be called from a SocketIO event handler, as in obtains some
information from the c... |
python | def getParameters(self, postalAddress):
"""
Return a C{list} of one L{LiveForm} parameter for editing a
L{PostalAddress}.
@type postalAddress: L{PostalAddress} or C{NoneType}
@param postalAddress: If not C{None}, an existing contact item from
which to get the postal... |
python | def to_distance(matrix, alpha=1):
"""Compute distance matrix from contact data by applying a negative power
law (alpha) to its nonzero pixels, then interpolating on the zeroes using a
shortest-path algorithm.
"""
matrix = np.array(matrix)
try:
import scipy.sparse
except ImportError a... |
java | @CallSuper
protected void onHandleIntent(Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
// TODO: permissions?
if (ACTION_SUBSCRIBE.equals(action)) {
processSubscribe(
(ComponentName) intent.get... |
java | public T text(Intent intent, String extraName) {
if (intent!=null) {
return text(intent.getStringExtra(extraName));
}
return self();
} |
python | def _parseExceptionDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_EXCEPTION_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_EXCEPTION_DIRECTORY} starts.
@type size: int
@param size: The size of the C{I... |
python | def _set_alarm_owner(self, v, load=False):
"""
Setter method for alarm_owner, mapped from YANG variable /rmon/alarm_entry/alarm_owner (owner-string)
If this variable is read-only (config: false) in the
source YANG file, then _set_alarm_owner is considered as a private
method. Backends looking to pop... |
python | def dropStudyFromISA(studyNum, pathToISATABFile):
"""
This function removes a study from an ISA file
Typically, you should use the exploreISA function to check the contents
of the ISA file and retrieve the study number you are interested in!
Warning: this function deletes the given study and all its... |
java | private Set<String> getConditionsSet(List<Function> atoms, AliasIndex index, boolean processShared) {
Set<String> conditions = new LinkedHashSet<>();
if (processShared) {
// guohui: After normalization, do we have shared variables?
// TODO: should we remove this ??
Set<Variable> currentLevelVariables = ne... |
java | private void setCurrentName(final String original_value,
final String extracted_value) {
// now parse and set the display name. If the formatter is empty, we just
// set it to the parsed value and exit
String format = rule.getDisplayFormat();
if (format == null || format.isEmpty()) {
curr... |
python | def latinize_text(text, ascii=False):
"""Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script.
"""
if text is None or not isinstance(text, six.string_types) or not len(text):
... |
python | def mll(y_true, y_pred, y_var):
"""
Mean log loss under a Gaussian distribution.
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
y_var: float or ndarray
predicted variances
Returns
-------
float:
... |
python | def run_study(self, study, **kws):
"""Run Gene Ontology Enrichment Study (GOEA) on study ids."""
if not study:
return []
# Key-word arguments:
methods = Methods(kws['methods']) if 'methods' in kws else self.methods
alpha = kws['alpha'] if 'alpha' in kws else self.alph... |
java | @Override
public void setValue(final double VALUE) {
if (isEnabled()) {
super.setValue(VALUE);
this.stepValue = 2 * ((int) (Math.abs(VALUE) * 10) % 10);
if (stepValue > 10) {
stepValue -= 20;
}
if (VALUE == 0) {
th... |
python | def _parse_description(details):
"""
Parse description of the book.
Args:
details (obj): HTMLElement containing slice of the page with details.
Returns:
str/None: Details as string with currency or None if not found.
"""
description = details.find("div", {"class": "detailPopis"... |
python | def seek(self, offset, whence=0, mode='rw'):
"""similar to python seek function, taking only in account audio data.
:Parameters:
offset : int
the number of frames (eg two samples for stereo files) to move
relatively to position set by whence.
when... |
python | def zhang_huang_solar_split(altitudes, doys, cloud_cover, relative_humidity,
dry_bulb_present, dry_bulb_t3_hrs, wind_speed,
atm_pressure, use_disc=False):
"""Calculate direct and diffuse solar irradiance using the Zhang-Huang model.
By default, this funct... |
java | public static void setVerificationHeaders(HttpServletResponse response, File file)
throws IOException {
response.setHeader(TransferFsImage.CONTENT_LENGTH,
String.valueOf(file.length()));
MD5Hash hash = MD5FileUtils.readStoredMd5ForFile(file);
if (hash != null) {
response.setHeader(TransferFs... |
java | public static double distance(@NonNull Point point1, @NonNull Point point2,
@NonNull @TurfConstants.TurfUnitCriteria String units) {
double difLat = degreesToRadians((point2.latitude() - point1.latitude()));
double difLon = degreesToRadians((point2.longitude() - point1.longitude(... |
python | def create_virtualenv(srcdir, datadir, preload_image, get_container_name):
"""
Populate venv from preloaded image
"""
try:
if docker.is_boot2docker():
docker.data_only_container(
get_container_name('venv'),
['/usr/lib/ckan'],
)
... |
python | def adjust_logging(self, context):
"""
Adjust logging configuration.
:param context:
The guacamole context object.
This method uses the context and the results of early argument parsing
to adjust the configuration of the logging subsystem. In practice the
va... |
java | @SuppressWarnings("PMD.UseVarargs")
public void disableBundle(final Class<? extends GuiceyBundle>[] bundles) {
for (Class<? extends GuiceyBundle> bundle : bundles) {
registerDisable(ConfigItem.Bundle, bundle);
}
} |
python | def _clone_node(self) -> 'Tag':
"""Need to copy class, not tag.
So need to re-implement copy.
"""
clone = type(self)()
for attr in self.attributes:
clone.setAttribute(attr, self.getAttribute(attr))
for c in self.classList:
clone.addClass(c)
... |
python | def _parseTlsDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the TLS directory.
@type rva: int
@param rva: The RVA where the TLS directory starts.
@type size: int
@param size: The size of the TLS directory.
@type magic: int
... |
python | def get_similar_donors(self, client_data):
"""Computes a set of :float: similarity scores between a client and a set of candidate
donors for which comparable variables have been measured.
A custom similarity metric is defined in this function that combines the Hamming distance
for categ... |
java | public static Study readStudy(final InputStream inputStream) throws IOException {
checkNotNull(inputStream);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
return readStudy(reader);
}
} |
python | def NewFromXyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF):
'''Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The c... |
python | def _ss(self, class_def):
"""calculates sum of squares for a class"""
yc = self.y[class_def]
css = yc - yc.mean()
css *= css
return sum(css) |
java | @SuppressWarnings({"unused", "WeakerAccess"})
public void setMultiValuesForKey(final String key, final ArrayList<String> values) {
postAsyncSafely("setMultiValuesForKey", new Runnable() {
@Override
public void run() {
_handleMultiValues(values, key, Constants.COMMAND_... |
python | def runningstd(t, data, width):
"""Compute the running standard deviation of a time series.
Returns `t_new`, `std_r`.
"""
ne = len(t) - width
t_new = np.zeros(ne)
std_r = np.zeros(ne)
for i in range(ne):
t_new[i] = np.mean(t[i:i+width+1])
std_r[i] = scipy.stats.nan... |
java | public static List<Bitmap> findCachedBitmapsForImageUri(String imageUri, MemoryCache memoryCache) {
List<Bitmap> values = new ArrayList<Bitmap>();
for (String key : memoryCache.keys()) {
if (key.startsWith(imageUri)) {
values.add(memoryCache.get(key));
}
}
return values;
} |
python | def _fastp_trim(fastq_files, adapters, out_dir, data):
"""Perform multicore trimming with fastp (https://github.com/OpenGene/fastp)
"""
report_file = os.path.join(out_dir, "%s-report.json" % utils.splitext_plus(os.path.basename(fastq_files[0]))[0])
out_files = [os.path.join(out_dir, "%s-trimmed.fq.gz" %... |
java | @SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
protected void assignToUserObjectInDb(final Type _assignType,
final JAASSystem _jaasSystem,
final AbstractUserObject _object)
throws EFapsExcept... |
python | def _read_data_handler(length, whence, ctx, skip=False, stream_event=ION_STREAM_INCOMPLETE_EVENT):
"""Creates a co-routine for retrieving data up to a requested size.
Args:
length (int): The minimum length requested.
whence (Coroutine): The co-routine to return to after the data is satisfied.
... |
java | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1975")
public static Status statusFromCancelled(Context context) {
Preconditions.checkNotNull(context, "context must not be null");
if (!context.isCancelled()) {
return null;
}
Throwable cancellationCause = context.cancellationCause();
... |
java | public static ModbusResponse createModbusResponse(int functionCode) {
ModbusResponse response;
switch (functionCode) {
case Modbus.READ_COILS:
response = new ReadCoilsResponse();
break;
case Modbus.READ_INPUT_DISCRETES:
response = ... |
java | @Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
Object value = returnValue;
if (returnValue instanceof HttpEntity) {
value = ... |
python | def zip(value=data, mu=mu, psi=psi):
""" Zero-inflated Poisson likelihood """
# Initialize likeihood
like = 0.0
# Loop over data
for x in value:
if not x:
# Zero values
like += np.log((1. - psi) + psi * np.exp(-mu))
else:
# Non-zero values
... |
java | public static dnszone[] get(nitro_service service) throws Exception{
dnszone obj = new dnszone();
dnszone[] response = (dnszone[])obj.get_resources(service);
return response;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.