language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void setInput(final byte[] input)
{
if (input[0] == -128) {
r = new BitReader(inflateInput(input, 1));
}
else {
r = new BitReader(input);
}
} |
java | public static ICommentProcessor wrap(final ICommentProcessor processor, final IProcessorDialect dialect) {
Validate.notNull(dialect, "Dialect cannot be null");
if (processor == null) {
return null;
}
return new CommentProcessorWrapper(processor, dialect);
} |
python | def write(self, session, data):
"""Writes data to device or interface synchronously.
Corresponds to viWrite function of the VISA library.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:type data: str
:return: Number of bytes ac... |
python | def get_type_of_fields(fields, table):
"""
Return data types of `fields` that are in `table`. If a given
parameter is empty return primary key.
:param fields: list - list of fields that need to be returned
:param table: sa.Table - the current table
:return: list - list o... |
java | public Hessian2Output createHessian2Output(OutputStream os)
{
Hessian2Output out = createHessian2Output();
out.init(os);
return out;
} |
python | def dim(self, dim):
"""Adjusts contrast to dim the display if dim is True, otherwise sets the
contrast to normal brightness if dim is False.
"""
# Assume dim display.
contrast = 0
# Adjust contrast based on VCC if not dimming.
if not dim:
if self._vccs... |
java | public void marshall(RemoveTagsFromVaultRequest removeTagsFromVaultRequest, ProtocolMarshaller protocolMarshaller) {
if (removeTagsFromVaultRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(r... |
java | public WellRestedRequest build() {
return new WellRestedRequest(this.uri, this.credentials, this.proxy, this.dateSerializer, this.dateDeserializer,
this.dateFormat, this.exclusionStrategy, this.excludedFieldNames, this.excludedClassNames,
... |
java | public char[] readAsCharArray()
{
int currentSize = size();
if (currentSize == 0)
{
return new char[0];
}
FixedCharArrayWriter target = new FixedCharArrayWriter(currentSize);
try
{
writeTo(target);
}
catch (IOException ... |
java | @XmlElementDecl(namespace = "http://www.citygml.org/ade/sub/0.9.0", name = "HollowSpace", substitutionHeadNamespace = "http://www.opengis.net/citygml/1.0", substitutionHeadName = "_CityObject")
public JAXBElement<HollowSpaceType> createHollowSpace(HollowSpaceType value) {
return new JAXBElement<HollowSpaceT... |
python | def p_program_tokenstring(p):
""" program : defs NEWLINE
"""
try:
tmp = [str(x()) if isinstance(x, MacroCall) else x for x in p[1]]
except PreprocError as v:
error(v.lineno, v.message)
tmp.append(p[2])
p[0] = tmp |
python | def find_contig_distribution(contig_lengths_dict):
"""
Determine the frequency of different contig size ranges for each strain
:param contig_lengths_dict:
:return: contig_len_dist_dict: dictionary of strain name: tuple of contig size range frequencies
"""
# Initialise the dictionary
contig_l... |
java | private void unprotectedMkdir(long inodeId, INode[] inodes, int pos,
byte[] name, PermissionStatus permission, boolean inheritPermission,
long timestamp) throws QuotaExceededException {
inodes[pos] = addChild(inodes, pos,
new INodeDirectory(inodeId, name, permission, timestamp),
-1, inhe... |
python | def set_text(self, text):
"""Sets the text.
arg: text (string): the new text
raise: InvalidArgument - ``text`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``text`` is ``null``
*compliance: mandatory -- This method must b... |
python | def task_absent(name):
'''
Ensure that a task is absent from Kapacitor.
name
Name of the task.
'''
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
if task:
if __opts__['test']:
ret['result'] = None
... |
java | void formatEra(StringBuilder b, ZonedDateTime d, int width, FieldVariants eras) {
int year = d.getYear();
int index = year < 0 ? 0 : 1;
switch (width) {
case 5:
b.append(eras.narrow[index]);
break;
case 4:
b.append(eras.wide[index]);
break;
case 3:
c... |
java | @SuppressWarnings("unchecked")
public EList<IfcReinforcementBarProperties> getCrossSectionReinforcementDefinitions() {
return (EList<IfcReinforcementBarProperties>) eGet(
Ifc2x3tc1Package.Literals.IFC_SECTION_REINFORCEMENT_PROPERTIES__CROSS_SECTION_REINFORCEMENT_DEFINITIONS,
true);
} |
java | protected void init(Class<T> cls, Key ... keys) {
// get the columns
List<String> targetColumns = new ArrayList<String>();
Class<?> clazz = cls;
while( clazz != null && !clazz.equals(Object.class) ) {
Field[] fields = clazz.getDeclaredFields();
for( ... |
java | public String getProjectName( MavenProject project )
{
File dotProject = new File( project.getBasedir(), ".project" );
try
{
Xpp3Dom dom = Xpp3DomBuilder.build( ReaderFactory.newXmlReader( dotProject ) );
return dom.getChild( "name" ).getValue();
}
cat... |
python | def replace_query_parameters(request, replacements):
"""
Replace query parameters in request according to replacements. The
replacements should be a list of (key, value) pairs where the value can be
any of:
1. A simple replacement string value.
2. None to remove the given header.
3. A ... |
python | def diskstats():
'''
.. versionchanged:: 2016.3.2
Return the disk stats for this minion
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' status.diskstats
'''
def linux_diskstats():
'''
linux specific im... |
python | def _compress(self):
"""Prunes the cataloged observations."""
rank = 0.0
current = self._head
while current and current._successor:
if current._rank + current._successor._rank + current._successor._delta <= self._invariant(rank, self._observations):
removed =... |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.GCMRK__RG:
getRg().clear();
return;
}
super.eUnset(featureID);
} |
java | public void render(Template template, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException {
newInterpreter(extraGlobalScopes).declare(parameters).process((TemplateImpl) template, out);
} |
python | def update(self):
"""Updates the dictionary of the device"""
if "tag_groups" not in self._device_dict:
return
for group in self.tag_groups:
group.update()
for i in range(len(self._device_dict["tag_groups"])):
tag_group_dict = self._device_dict["tag_gro... |
python | def visit_ListComp(self, node: AST, dfltChaining: bool = True) -> str:
"""Return `node`s representation as list comprehension."""
return f"[{self.visit(node.elt)} " \
f"{' '.join(self.visit(gen) for gen in node.generators)}]" |
java | public static String link(Key k, String content) {
return link(k, content, null, null, null);
} |
python | async def disable(self, reason=None):
"""Enters maintenance mode
Parameters:
reason (str): Reason of disabling
Returns:
bool: ``True`` on success
"""
params = {"enable": True, "reason": reason}
response = await self._api.put("/v1/agent/maintenance... |
java | public Map<String, DeleteOperation> getDeleteOperations() {
Map<String, DeleteOperation> delOperations = new TreeMap<String, DeleteOperation>();
for (Entry<String, IOperation> entry : collectionUpdateData.entrySet()) {
String key = entry.getKey();
IOperation op = entry.getValue();
if (op.getOp... |
java | public URLConnection connectWithRedirect(URL theURL) throws IOException {
URLConnection conn = null;
String accept_header = buildAcceptHeader();
int redirect_count = 0;
boolean done = false;
while (!done) {
if (theURL.getProtocol().equals("file")) {
... |
java | public Observable<CertificateBundle> updateCertificateAsync(String vaultBaseUrl, String certificateName, String certificateVersion, CertificatePolicy certificatePolicy, CertificateAttributes certificateAttributes, Map<String, String> tags) {
return updateCertificateWithServiceResponseAsync(vaultBaseUrl, certifi... |
python | def get_prefix(self, key_prefix, sort_order=None, sort_target=None):
"""Get a range of keys with a prefix.
:param sort_order: 'ascend' or 'descend' or None
:param key_prefix: first key in range
:returns: sequence of (value, metadata) tuples
"""
return self.get(key_prefi... |
python | def truncated_exponential_backoff(
slot_delay, collision=0, max_collisions=5,
op=operator.mul, in_range=True):
"""Truncated Exponential Backoff
see https://en.wikipedia.org/wiki/Exponential_backoff
"""
truncated_collision = collision % max_collisions
if in_range:
slots = random.randi... |
java | public void setStreamInfo(Stream stream, final KickflipCallback cb) {
if (!assertActiveUserAvailable(cb)) return;
GenericData data = new GenericData();
data.put("stream_id", stream.getStreamId());
data.put("uuid", getActiveUser().getUUID());
if (stream.getTitle() != null) {
... |
python | def align_pipe(fastq_file, pair_file, ref_file, names, align_dir, data):
"""Perform piped alignment of fastq input files, generating sorted output BAM.
"""
pair_file = pair_file if pair_file else ""
# back compatible -- older files were named with lane information, use sample name now
if names["lane... |
python | def lorentz_deriv((x, y, z), t0, sigma=10., beta=8./3, rho=28.0):
"""Compute the time-derivative of a Lorentz system."""
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z] |
python | def expand(conf, output_requirements_filename, input_requirements_filename):
"""Expand given requirements file by extending it using pip freeze
args:
input_requirements_filename: the requirements filename to expand
output_requirements_filename: the output filename for the expanded
requirements fi... |
python | def parenthesize(self, expr, level, *args, strict=False, **kwargs):
"""Render `expr` and wrap the result in parentheses if the precedence
of `expr` is below the given `level` (or at the given `level` if
`strict` is True. Extra `args` and `kwargs` are passed to the internal
`doit` rendere... |
python | def serialize_list(self, tag):
"""Return the literal representation of a list tag."""
separator, fmt = self.comma, '[{}]'
with self.depth():
if self.should_expand(tag):
separator, fmt = self.expand(separator, fmt)
return fmt.format(separator.join(map(sel... |
python | def image_embedding_column(key, module_spec):
"""Uses a Module to get a dense 1-D representation from the pixels of images.
This feature column can be used on images, represented as float32 tensors of
RGB pixel data in the range [0,1]. This can be read from a numeric_column()
if the tf.Example input data happe... |
java | public void delete(RecordId nextDeletedSlot) {
Constant flag = EMPTY_CONST;
setVal(currentPos(), flag);
setNextDeletedSlotId(nextDeletedSlot);
} |
java | public static void unregisterIdlingResource(@NonNull String name) {
throwIfAbsent(name);
CappuccinoIdlingResource idlingResource = mIdlingResourceRegistry.get(name);
Espresso.unregisterIdlingResources(idlingResource);
mIdlingResourceRegistry.remove(name);
} |
python | def get_file(hash):
"""Return the contents of the file as a ``memoryview``."""
stmt = _get_sql('get-file.sql')
args = dict(hash=hash)
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
cursor.execute(stmt, args)
try:
file, _ = cursor.fetchone(... |
python | def run_gerrit_command(self, command):
""" Run the given command.
Make sure we're connected to the remote server, and run `command`.
Return the results as a `GerritSSHCommandResult`.
Raise `ValueError` if `command` is not a string, or `GerritError` if
command execution fails.
... |
python | def _remove_none_values(dictionary):
""" Remove dictionary keys whose value is None """
return list(map(dictionary.pop,
[i for i in dictionary if dictionary[i] is None])) |
python | def translate_query_params(cls, **kwargs):
"""
Translate an arbirtary keyword argument to the expected query.
TODO: refactor this into something less insane.
XXX: Clean this up. It's *too* flexible.
In the v2 API, many endpoints expect a particular query argument to be
... |
java | public int getUnique() {
TIntHashSet inUse = new TIntHashSet();
for (int i = 0; i < length; i++) {
inUse.add(get(i));
}
return inUse.size();
} |
python | def volume(self, value=None):
"""Get/set the volume occupied by actor."""
mass = vtk.vtkMassProperties()
mass.SetGlobalWarningDisplay(0)
mass.SetInputData(self.polydata())
mass.Update()
v = mass.GetVolume()
if value is not None:
if not v:
... |
java | public OvhVoicemailMessages billingAccount_voicemail_serviceName_directories_id_GET(String billingAccount, String serviceName, Long id) throws IOException {
String qPath = "/telephony/{billingAccount}/voicemail/{serviceName}/directories/{id}";
StringBuilder sb = path(qPath, billingAccount, serviceName, id);
Strin... |
java | public String [] availableFlags(){
Iterator<String> it = flags.keySet().iterator();
String [] out = new String[(flags.keySet().size())];
int i = 0;
while(it.hasNext()){
out[i] = it.next();
i++;
}
return out;
} |
python | def to_dict(self):
"""
Returns:
dict: Concise represented as a dictionary.
"""
final_res = {
"param": self._param,
"unused_param": self.unused_param,
"execution_time": self._exec_time,
"output": {"accuracy": self.get_accuracy(),... |
python | def check_gcdt_update():
"""Check whether a newer gcdt is available and output a warning.
"""
try:
inst_version, latest_version = get_package_versions('gcdt')
if inst_version < latest_version:
log.warn('Please consider an update to gcdt version: %s' %
... |
python | def _deployment_menu_entry(deployment):
"""Build a string to display in the 'select deployment' menu."""
paths = ", ".join([_module_name_for_display(module) for module in deployment['modules']])
regions = ", ".join(deployment.get('regions', []))
return "%s - %s (%s)" % (deployment.get('name'), paths, re... |
java | public static <T> List<T> minList (Iterable<T> iterable, Comparator<? super T> comp)
{
return maxList(iterable, java.util.Collections.reverseOrder(comp));
} |
java | public void setTimestampProperty(String pstrSection, String pstrProp,
Timestamp ptsVal, String pstrComments)
{
INISection objSec = null;
objSec = (INISection) this.mhmapSections.get(pstrSection);
if (objSec == null)
{
objSec = new INIS... |
python | def decrypt_result(self, *args, **kwargs):
"""
Decrypts ProcessData result with comm keys
:param args:
:param kwargs:
:return:
"""
if self.response is None:
raise ValueError('Empty response')
if self.response.response is None \
... |
python | def _calculate_ms_from_base(self, size):
"""Calculates the rotated minimum size from the given base minimum
size."""
hw = size.x * 0.5
hh = size.y * 0.5
a = datatypes.Point(hw, hh).get_rotated(self.angle)
b = datatypes.Point(-hw, hh).get_rotated(self.angle)
c = d... |
python | def validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False):
"""
Validates a signature of a EntityDescriptor.
:param xml: The element we should validate
:type: string | Document
:param cert: The pubic cert
:type: ... |
java | public Image getImage(GraphicsConfiguration config, int w, int h, Object... args) {
lock.readLock().lock();
try {
PixelCountSoftReference ref = map.get(hash(config, w, h, args));
// check reference has not been lost and the key truly matches, in
// case of false pos... |
python | def calculate_generalized_advantage_estimator(
reward, value, done, gae_gamma, gae_lambda):
# pylint: disable=g-doc-args
"""Generalized advantage estimator.
Returns:
GAE estimator. It will be one element shorter than the input; this is
because to compute GAE for [0, ..., N-1] one needs V for [1, ...,... |
python | def Extract_Checkpoints(self):
'''
Extract the checkpoints and store in self.tracking_data
'''
# Make sure page is available
if self.page is None:
raise Exception("The HTML data was not fetched due to some reasons")
soup = BeautifulSoup(self.page,'html.parser')
# Check for invalid tracking number b... |
python | def security_iter(nodearr):
""" provide a security data iterator by returning a tuple of (Element, SecurityError) which are mutually exclusive """
assert nodearr.Name == 'securityData' and nodearr.IsArray
for i in range(nodearr.NumValues):
node = nodearr.GetValue(i)
err =... |
java | private int writeUTF8Slow(final CharSequence chars, int off, int len)
{
int octets = 0;
while (len > 0)
{
final char ch = chars.charAt(off);
if (ch >= LOW_SURROGATE_FIRST && ch <= LOW_SURROGATE_LAST)
{
throw new IllegalArgumentException("Un... |
java | private void removeDuplicateRow(DoubleMatrix1D c,
DoubleMatrix2D A, DoubleMatrix1D b,
DoubleMatrix1D lb, DoubleMatrix1D ub,
DoubleMatrix1D ylb, DoubleMatrix1D yub,
DoubleMatrix1D zlb, DoubleMatrix1D zub) {
//the position 0 is for empty rows, 1 is for row singleton and 2 for row doubleton
int sta... |
python | def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args... |
java | public static xen_brvpx_image delete(nitro_service client, xen_brvpx_image resource) throws Exception
{
resource.validate("delete");
return ((xen_brvpx_image[]) resource.delete_resource(client))[0];
} |
java | public void inlinePrintNoQuotes(Object o) {
if(inline.length() > 0) {
inline.append(SEPARATOR);
}
// remove newlines
String str = o.toString().replace(NEWLINE, " ");
// escaping
str = str.replace("\\", "\\\\").replace("\"", "\\\"");
inline.append(str);
} |
python | def main():
"""Main function of the converter command-line tool,
``convert2h5features --help`` for a more complete doc."""
args = parse_args()
converter = h5f.Converter(args.output, args.group, args.chunk)
for infile in args.file:
converter.convert(infile) |
java | public Curve25519KeyPair generateKeyPair() {
byte[] privateKey = provider.generatePrivateKey();
byte[] publicKey = provider.generatePublicKey(privateKey);
return new Curve25519KeyPair(publicKey, privateKey);
} |
java | public List<CharacterOrdersHistoryResponse> getCharactersCharacterIdOrdersHistory(Integer characterId,
String datasource, String ifNoneMatch, Integer page, String token) throws ApiException {
ApiResponse<List<CharacterOrdersHistoryResponse>> resp = getCharactersCharacterIdOrdersHistoryWithHttpInfo(
... |
java | @Override
public Collection<Metric> deserialize(JsonElement element, Type type, JsonDeserializationContext context)
throws JsonParseException
{
JsonObject obj = element.getAsJsonObject();
JsonArray metrics = obj.getAsJsonArray("metrics");
List<Metric> values = new ArrayList<Metri... |
python | def _histplot_op(values, values2, rotated, ax, hist_kwargs):
"""Add a histogram for the data to the axes."""
if values2 is not None:
raise NotImplementedError("Insert hexbin plot here")
bins = hist_kwargs.pop("bins")
if bins is None:
bins = get_bins(values)
ax.hist(values, bins=bins... |
python | def nested_assign(self, key_list, value):
""" Set the value of nested LIVVDicts given a list """
if len(key_list) == 1:
self[key_list[0]] = value
elif len(key_list) > 1:
if key_list[0] not in self:
self[key_list[0]] = LIVVDict()
self[key_list[0... |
python | def template_tag(self,
arg: Optional[Callable] = None,
*,
name: Optional[str] = None,
pass_context: bool = False,
inject: Optional[Union[bool, Iterable[str]]] = None,
safe: bool = False,
... |
java | public static Object getField(Object obj, String prop) throws PageException {
try {
return getFieldsIgnoreCase(obj.getClass(), prop)[0].get(obj);
}
catch (Throwable e) {
ExceptionUtil.rethrowIfNecessary(e);
throw Caster.toPageException(e);
}
} |
python | def send_mail(subject, message, from_email, recipient_list, html_message='',
scheduled_time=None, headers=None, priority=PRIORITY.medium):
"""
Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method.
"""
subject = force_text(subject)
... |
java | protected void increaseRefreshInterval() {
refreshInterval = Math.min(REFRESH_INTERVALS.size() - 1, refreshInterval + 1);
// reset view
resetAllParts();
synchronized (refreshThread) {
refreshThread.notify();
}
} |
python | def convert_index_to_keys(d, item):
# use a separate function rather than a method inside the class IndexDict
'''
Convert ``item`` in various types (int, tuple/list, slice, or a normal key)
to a single key or a list of keys.
'''
keys = force_list(d.keys())
# use KeyError for compatibility o... |
java | public UPnPStateVariable getStateVariable(String name) {
if (name.equals("Time"))
return time;
else if (name.equals("Result"))
return result;
else return null;
} |
python | def slice_hidden(self, x):
"""Slice encoder hidden state into block_dim.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
Returns:
Sliced states of shape [-1, num_blocks, block_dim].
"""
x_sliced = tf.reshape(
x, shape=[-1, self.hparams.num_blocks, self.hparams.blo... |
java | public void write(OutputStream out) throws IOException {
DataOutputStream dos = new DataOutputStream(out);
// Write out the main attributes for the manifest
attr.writeMain(dos);
// Now write out the pre-entry attributes
Iterator<Map.Entry<String, Attributes>> it = entries.entrySe... |
python | def hit_count(self, request, hitcount):
"""
Called with a HttpRequest and HitCount object it will return a
namedtuple:
UpdateHitCountResponse(hit_counted=Boolean, hit_message='Message').
`hit_counted` will be True if the hit was counted and False if it was
not. `'hit_m... |
java | Collection<URL> getURLs(String path) {
// Go through all of the items that match this path and get the URIs for them
Collection<URL> urls = new HashSet<URL>();
for (EntryInfo ei : _entries) {
if (ei.matches(path)) {
urls.addAll(ei.getURLs(path));
}
... |
python | def create_poi_gdf(polygon=None, amenities=None, north=None, south=None, east=None, west=None):
"""
Parse GeoDataFrames from POI json that was returned by Overpass API.
Parameters
----------
polygon : shapely Polygon or MultiPolygon
geographic shape to fetch the POIs within
amenities: l... |
java | public Quaternionf fromAxisAngleRad(Vector3fc axis, float angle) {
return fromAxisAngleRad(axis.x(), axis.y(), axis.z(), angle);
} |
python | def info(self):
"""Show IANA allocation information for the current IP address.
>>> ip = IP("127.0.0.1")
>>> print(ip.info())
LOOPBACK
"""
b = self.bin()
for i in range(len(b), 0, -1):
if b[:i] in self._range[self.v]:
return self._rang... |
java | @JsonProperty("labels")
@JsonInclude(Include.NON_EMPTY)
public Map<String, TermImpl> getLabelUpdates() {
return getMonolingualUpdatedValues(newLabels);
} |
python | def set_timeout(self, delay, err=TimeoutError):
"""Called to set a transaction timer."""
if _debug: IOCB._debug("set_timeout(%d) %r err=%r", self.ioID, delay, err)
# if one has already been created, cancel it
if self.ioTimeout:
self.ioTimeout.suspend_task()
else:
... |
java | @Deprecated
public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods(
TypeElement type, Elements elementUtils) {
Overrides overrides = new Overrides.NativeOverrides(elementUtils);
return getLocalAndInheritedMethods(type, overrides);
} |
python | def issuer_serial(self):
"""
:return:
A byte string of the SHA-256 hash of the issuer concatenated with
the ascii character ":", concatenated with the serial number as
an ascii string
"""
if self._issuer_serial is None:
self._issuer_serial... |
java | public final KeyStore createPkcs12KeyStore(String keyName, char[] password, PrivateKey privateKey, X509Certificate certificate) {
logger.entry();
List<X509Certificate> certificates = new ArrayList<>();
certificates.add(certificate);
KeyStore keyStore = createPkcs12KeyStore(keyName, p... |
java | public com.squareup.okhttp.Call getFleetsFleetIdWingsAsync(Long fleetId, String acceptLanguage, String datasource,
String ifNoneMatch, String language, String token, final ApiCallback<List<FleetWingsResponse>> callback)
throws ApiException {
com.squareup.okhttp.Call call = getFleetsFlee... |
python | async def update_data(self, *,
chat: typing.Union[str, int, None] = None,
user: typing.Union[str, int, None] = None,
data: typing.Dict = None,
**kwargs):
"""
Update data for user in chat
You ... |
python | def more_like_this(self, query, fields, columns=None, start=0, rows=30):
"""
Retrieves "more like this" results for a passed query document
query - query for a document on which to base similar documents
fields - fields on which to base similarity estimation (either comma delimited stri... |
python | def ptb_producer(raw_data, batch_size, num_steps, name=None):
"""Iterate on the raw PTB data.
This chunks up raw_data into batches of examples and returns Tensors that
are drawn from these batches.
Args:
raw_data: one of the raw data outputs from ptb_raw_data.
batch_size: int, the batch size.
num_... |
java | public void stop() {
try {
mRMClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "", "");
} catch (YarnException e) {
LOG.error("Failed to unregister application", e);
} catch (IOException e) {
LOG.error("Failed to unregister application", e);
}
mRMClient.stop();
... |
python | def parse_prokka(self, f):
""" Parse prokka txt summary files.
Prokka summary files are difficult to identify as there are practically
no distinct prokka identifiers in the filenames or file contents. This
parser makes an attempt using the first three lines, expected to contain
... |
java | public ConfigurationBuilder withSerialPort(String serialPort, int baudRate) {
configuration.connector = new SerialConnector();
configuration.address = new SerialAddress(serialPort, baudRate, DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE, FlowControl.NONE );
return this;
} |
java | @NonNull
public IconicsDrawable icon(@NonNull String icon) {
try {
ITypeface font = Iconics.findFont(mContext, icon.substring(0, 3));
icon = icon.replace("-", "_");
icon(font.getIcon(icon));
} catch (Exception ex) {
Log.e(Iconics.TAG, "Wrong icon name:... |
java | public UserRealm addRealm(UserRealm realm)
{
return (UserRealm)_realmMap.put(realm.getName(),realm);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.