language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def create_singlefile_standard (archive, compression, cmd, verbosity, interactive, filenames):
"""Standard routine to create a singlefile archive (like gzip)."""
cmdlist = [util.shell_quote(cmd)]
if verbosity > 1:
cmdlist.append('-v')
cmdlist.extend(['-c', '--'])
cmdlist.extend([util.shell_q... |
python | def get_method(self, method=None):
"""Returns the method to call on this instance as a string. Raises a
HTTP exception if no method can be found. Aborts with a 405 status
code for known methods (based on the :attr:`KNOWN_METHODS` list) and a
501 status code for all other methods.
... |
python | def reopen(args):
"""reopens a closed poll."""
if not args.isadmin:
return "Nope, not gonna do it."
msg = args.msg.split()
if not msg:
return "Syntax: !poll reopen <pollnum>"
if not msg[0].isdigit():
return "Not a valid positve integer."
pid = int(msg[0])
poll = get_o... |
java | public int doSetData(Object vpData, boolean bDisplayOption, int iMoveMode)
{
if ((vpData != null) && (!(vpData instanceof Short)))
return DBConstants.ERROR_RETURN;
return super.doSetData(vpData, bDisplayOption, iMoveMode);
} |
python | def create_upload(self, project_id, filename, content_type, size,
hash_value, hash_alg, storage_provider_id=None, chunked=True):
"""
Post to /projects/{project_id}/uploads to create a uuid for uploading chunks.
NOTE: The optional hash_value and hash_alg parameters are being... |
java | public Observable<Page<ResourceMetricInner>> listMultiRoleMetricsNextAsync(final String nextPageLink) {
return listMultiRoleMetricsNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<ResourceMetricInner>>, Page<ResourceMetricInner>>() {
@Override
... |
python | def create_frame(command):
"""Create and return empty Frame from Command."""
# pylint: disable=too-many-branches,too-many-return-statements
if command == Command.GW_ERROR_NTF:
return FrameErrorNotification()
if command == Command.GW_COMMAND_SEND_REQ:
return FrameCommandSendRequest()
... |
python | def _getGuiSettings(self):
""" Return a dict (ConfigObj) of all user settings found in rcFile. """
# Put the settings into a ConfigObj dict (don't use a config-spec)
rcFile = self._rcDir+os.sep+APP_NAME.lower()+'.cfg'
if os.path.exists(rcFile):
try:
return con... |
python | def sync(self, graph_commons):
"""Synchronize local and remote representations."""
if self['id'] is None:
return
remote_graph = graph_commons.graphs(self['id'])
# TODO: less forceful, more elegant
self.edges = remote_graph.edges
self.nodes = remote_graph.nod... |
python | def get_prev_step(self, step=None):
"""
Returns the previous step before the given `step`. If there are no
steps available, None will be returned. If the `step` argument is
None, the current step will be determined automatically.
"""
if step is None:
step = se... |
java | @BetaApi
public final Operation setUrlMapTargetHttpsProxy(
String targetHttpsProxy, UrlMapReference urlMapReferenceResource) {
SetUrlMapTargetHttpsProxyHttpRequest request =
SetUrlMapTargetHttpsProxyHttpRequest.newBuilder()
.setTargetHttpsProxy(targetHttpsProxy)
.setUrlMapRe... |
java | @SuppressWarnings("static-method")
protected Map<XVariableDeclaration, XFeatureCall> getReferencedLocalVariable(XExpression expression, boolean onlyWritable) {
final Map<XVariableDeclaration, XFeatureCall> localVariables = new TreeMap<>((k1, k2) -> {
return k1.getIdentifier().compareTo(k2.getIdentifier());
});
... |
java | @Override
public CommerceShippingMethod remove(Serializable primaryKey)
throws NoSuchShippingMethodException {
Session session = null;
try {
session = openSession();
CommerceShippingMethod commerceShippingMethod = (CommerceShippingMethod)session.get(CommerceShippingMethodImpl.class,
primaryKey);
... |
java | @Override
public EClass getIfcStructuralActivityAssignmentSelect() {
if (ifcStructuralActivityAssignmentSelectEClass == null) {
ifcStructuralActivityAssignmentSelectEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(1163);
}
return ifcStructuralActi... |
java | public Double averagePrecision()
{
double n = 0;
double sumPrecision = 0;
for (int i=0; i<pairs.length; i++) {
if (correctPair(i)) {
n++;
double precisionAtRankI = n/(i+1.0);
sumPrecision += precisionAtRankI;
}
... |
java | public static <T> VertxCompletableFuture<T> from(Context context, Future<T> future) {
VertxCompletableFuture<T> res = new VertxCompletableFuture<>(Objects.requireNonNull(context));
Objects.requireNonNull(future).setHandler(ar -> {
if (context == Vertx.currentContext()) {
res.completeFromAsyncResul... |
java | public void setCustomDnsServers(java.util.Collection<String> customDnsServers) {
if (customDnsServers == null) {
this.customDnsServers = null;
return;
}
this.customDnsServers = new com.amazonaws.internal.SdkInternalList<String>(customDnsServers);
} |
java | protected CommsByteBuffer jfapExchange(CommsByteBuffer buffer,
int sendSegmentType,
int priority,
boolean canPoolOnReceive)
throws SIConnectionDroppedException, SIConnectionLostException
... |
java | @Override
public ResourceFactory createResourceFactory(Map<String, Object> props) throws Exception {
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(tc, "createResourceFactory", props);
//Holds ConnectionManagerService prope... |
python | def calc_b_value(magnitudes, completeness, max_mag=None, plotvar=True):
"""
Calculate the b-value for a range of completeness magnitudes.
Calculates a power-law fit to given magnitudes for each completeness
magnitude. Plots the b-values and residuals for the fitted catalogue
against the completene... |
python | def json(self):
"""
Serializes json text stream into python dictionary.
:return dict: json
"""
_json = json.loads(self.reader)
if _json.get('error', None):
raise HTTPError(_json['error']['errors'])
return _json |
python | def set_pscale(self):
""" Compute the pixel scale based on active WCS values. """
if self.new:
self.pscale = 1.0
else:
self.pscale = self.compute_pscale(self.cd11,self.cd21) |
python | def iter(self, keyed=False, extended=False):
'''Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each retu... |
java | public boolean isCanceledOrFailed() {
return executionState == ExecutionState.CANCELING ||
executionState == ExecutionState.CANCELED ||
executionState == ExecutionState.FAILED;
} |
python | def save(self):
"""
Save the entire configuration files
"""
self.projects.save()
self.experiments.save()
safe_dump(self.global_config, self._globals_file,
default_flow_style=False) |
python | def to_disk(self, path, **kwargs):
"""Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The ... |
java | private String getRefreshToken(Token accessToken) {
JSONObject rawJson = JSONObject.fromObject(accessToken.getRawResponse());
return rawJson.getString("refresh_token");
} |
java | public static CachedPrintQuery get4Request(final Instance _instance)
throws EFapsException
{
return new CachedPrintQuery(_instance, Context.getThreadContext().getRequestId()).setLifespan(5)
.setLifespanUnit(TimeUnit.MINUTES);
} |
java | @Override
public Set<String> getGroups(String user) throws IOException {
if (cachedGroups.containsKey(user)) {
return cachedGroups.get(user);
}
Set<String> groups = getUnixGroups(user);
if (!groups.isEmpty())
cachedGroups.put(user, groups);
return grou... |
java | public static <T> List<T> asSynchronized(List<T> self) {
return Collections.synchronizedList(self);
} |
python | def register_conversion_handler(self, name, handler):
u"""
Регистрация обработчика конвертирования
:param name: Имя обработчика в таблице соответствия
:param handler: Обработчик
"""
if name in self.conversion_table:
warnings.warn((
u'Конвертир... |
python | def _use_for_model(self, model):
"""
Update the given model to use the current database. Do it also for all
of its subclasses if they share the same database. (so it's easy to
call use_database on an abstract model to use the new database for all
subclasses)
"""
o... |
java | public static boolean isDomainClass(URL url) {
if (url == null) return false;
return KNOWN_DOMAIN_CLASSES.get(url.getFile());
} |
java | private static void setDateHeader(final FullHttpResponse response) {
final SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
final Calendar time = new GregorianCalendar();
response.headers().set(D... |
java | public void add(final FieldDescriptor type, final Message defaultInstance) {
if (type.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new IllegalArgumentException(
"ExtensionRegistry.add() provided a default instance for a " +
"non-message extension.");
}
add(new ExtensionIn... |
java | @PublicEvolving
public <W extends Window> AllWindowedStream<T, W> windowAll(WindowAssigner<? super T, W> assigner) {
return new AllWindowedStream<>(this, assigner);
} |
java | public static void run(VicariousFactory factory) {
// Get the tweets
TweetProvider provider = factory.getTweetProvider();
List<Status> originals = null;
try {
originals = provider.getTweets();
if(originals == null || originals.isEmpty()) {
return;
}
}
catch(TwitterException exception) {
exce... |
java | public boolean stop() {
if (!this.isTailing.get()) {
LogWatchTailingManager.LOGGER.debug("Tailer not running, therefore not terminating.");
return false;
}
/*
* terminate tailer; we stop the scheduler and the task will therefore
* never be started again
... |
python | def continuous_decode(self):
"""Decode from dataset on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode() |
java | public int queryObjJoinCountByCondition(String sql,Object[] paramArray){
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
Integer total=jdbcTemplate.que... |
java | public void index( final ByteBuffer index, final int position) {
index.putInt( tag).putInt( getType()).putInt( position).putInt( count);
} |
python | def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform csv as below.
"title1","/path1","a=1&b=2","header1=1&header2=2"
"title2","/path2","c=1"
"title3","/path3",,"header1=1&header2=2"
"title4","/path4"
Exception:
ValueEr... |
python | def load_routes(self):
"""
Load all routes in project's folder 'controllers'.
Ignore files with leading underscore (for example: controllers/_blog.py)
"""
for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')):
# ignore disabled controllers
... |
java | public void setPullRequestTargets(java.util.Collection<PullRequestTarget> pullRequestTargets) {
if (pullRequestTargets == null) {
this.pullRequestTargets = null;
return;
}
this.pullRequestTargets = new java.util.ArrayList<PullRequestTarget>(pullRequestTargets);
} |
python | def minValue(self, value):
"""gets/sets the min value"""
if isinstance(value, [int, float, long]):
self._rangeMin = value |
java | public static CommerceVirtualOrderItem findByUUID_G(String uuid,
long groupId)
throws com.liferay.commerce.product.type.virtual.order.exception.NoSuchVirtualOrderItemException {
return getPersistence().findByUUID_G(uuid, groupId);
} |
java | public void setCSpace(Integer newCSpace) {
Integer oldCSpace = cSpace;
cSpace = newCSpace;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNIRG__CSPACE, oldCSpace, cSpace));
} |
java | public Observable<ServiceResponse<Image>> addImageUrlInputWithServiceResponseAsync(String listId, String contentType, BodyModelModel imageUrl, Integer tag, String label) {
if (this.client.baseUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot ... |
python | def send_to_azure(instance, data, replace=True, types=None, primary_key=(), sub_commit=True):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"row... |
java | private void populateExpandedExceptions()
{
if (!m_exceptions.isEmpty() && m_expandedExceptions.isEmpty())
{
for (ProjectCalendarException exception : m_exceptions)
{
RecurringData recurring = exception.getRecurring();
if (recurring == null)
{
... |
python | def _set_param_recursive(self, pipeline_steps, parameter, value):
"""Recursively iterate through all objects in the pipeline and set a given parameter.
Parameters
----------
pipeline_steps: array-like
List of (str, obj) tuples from a scikit-learn pipeline or related object
... |
java | public String storeData(String cookieData) {
try {
String token = generateToken();
ensureSpaceExists();
s3StorageProvider.addHiddenContent(this.hiddenSpaceName, token, Constants.MEDIA_TYPE_APPLICATION_JSON,
IOUtil.writeStrin... |
python | def selection(self):
"""
Selection property.
:return: None if no font is selected and font family name if one is selected.
:rtype: None or str
"""
if self._font.get() is "" or self._font.get() not in self._fonts:
return None
else:
... |
python | def append(self, transitions, rows=None):
"""Append a batch of transitions to rows of the memory.
Args:
transitions: Tuple of transition quantities with batch dimension.
rows: Episodes to append to, defaults to all.
Returns:
Operation.
"""
rows = tf.range(self._capacity) if rows ... |
java | public synchronized void storeInteractionForCurrentAppVersion(double timestamp, int versionCode, String versionName, String interactionId) {
EventRecord eventRecord = interactions.get(interactionId);
if (eventRecord == null) {
eventRecord = new EventRecord();
interactions.put(interactionId, eventRecord);
}
... |
java | public void printControlEndForm(PrintWriter out, int iPrintOptions)
{
BasePanel scrDetail = ((BaseGridScreen)this.getScreenField()).getReportDetail();
this.printHeadingFootingControls(out, iPrintOptions | HtmlConstants.FOOTING_SCREEN);
if (scrDetail != null)
{
scrDetail.... |
java | public boolean isMultiSelectable() {
return ((!isInPk() && !isInFk() && !isVersion()) || (isSimplePk() && jpa.isManuallyAssigned())) //
&& (isBoolean() || isEnum() || isString() || isNumeric());
} |
java | public void declineDefaultList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
// The request of the list is an privacy message with an empty list
Privacy request = new Privacy();
request.setDeclineDefaultList(true);
// Send the package to... |
python | def get_user_data_triplet(self, base64=False):
"""( <_user>, <_password verifier>, <salt> )
:param base64:
:rtype: tuple
"""
salt = self.generate_salt()
verifier = self.get_common_password_verifier(self.get_common_password_hash(salt))
verifier = value_encode(ver... |
python | def mangle_name(name):
"""Mangles a column name to a standard form, remoing illegal
characters.
:param name:
:return:
"""
import re
try:
return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_')
except TypeError:
r... |
python | def double_linked_dom(str_or_dom):
"""
Create double linked DOM from input.
In case of string, parse it, make it double-linked. In case of DOM, just
make it double-linked.
Args:
str_or_dom (str/HTMLelement): String or HTMLelement instance.
Returns:
obj: HTMLelement with parsed... |
python | def pull(self):
"""Pull from the origin."""
repo_root = settings.REPO_ROOT
pull_from_origin(join(repo_root, self.name)) |
python | def extract_common_fields(self, data):
"""Extract fields from a basic user query."""
email = None
for curr_email in data.get("emails", []):
email = email or curr_email.get("email")
if curr_email.get("verified", False) and \
curr_email.get("primary", Fa... |
java | private String determineBaseEcosystem(String description) {
if (description == null) {
return null;
}
int idx = StringUtils.indexOfIgnoreCase(description, ".php");
if ((idx > 0 && (idx + 4 == description.length() || !Character.isLetterOrDigit(description.charAt(idx + 4))))
... |
java | @Deprecated
public GeographyPointValue mul(double alpha) {
return GeographyPointValue.normalizeLngLat(getLongitude() * alpha + 0.0,
getLatitude() * alpha + 0.0);
} |
java | public String getAbsoluteUri(String relativeUri, String baseUri) {
if ((relativeUri == null) || (relativeUri.charAt(0) == '/') || (relativeUri.startsWith("#"))) {
return relativeUri;
}
// if we are on a windows system, we must add a ":" in the uri later
String windowsAddit... |
java | @Override
public CommercePriceListUserSegmentEntryRel findByUuid_C_Last(String uuid,
long companyId,
OrderByComparator<CommercePriceListUserSegmentEntryRel> orderByComparator)
throws NoSuchPriceListUserSegmentEntryRelException {
CommercePriceListUserSegmentEntryRel commercePriceListUserSegmentEntryRel =
fet... |
python | def info(self):
''' Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo
'''
return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name)) |
java | public void addEquality(SVar<T> s1, SVar<T> s2) {
this.addInclusion(s1, s2);
this.addInclusion(s2, s1);
} |
java | private static Selector substitute(Identifier id, List[] equatedIds) {
for (int i = 0; i < equatedIds[0].size(); i++)
if (id.getName().equals(equatedIds[0].get(i)))
return new LiteralImpl(equatedIds[1].get(i));
return id;
} |
python | def gen_rnd_prod_CDR3(self, conserved_J_residues = 'FVW'):
"""Generate a productive CDR3 seq from a Monte Carlo draw of the model.
Parameters
----------
conserved_J_residues : str, optional
Conserved amino acid residues defining the CDR3 on the J side (normally
F... |
python | def remove(self, item):
"""
See :meth:`list.remove()` method
Calls observer ``self.observer(UpdateType.DELETED, item, index)`` where
**index** is *item position*
"""
index = self.index(item)
self.real_list.remove(item)
self.observer(UpdateType.DELETED, it... |
python | def scantypes(cls, value, value_type, visitor):
"""Like :py:meth:`normalize.visitor.VisitorPattern.unpack`, but
returns a getter which just returns the property, and a collection
getter which returns a set with a single item in it.
"""
item_type_generator = None
if issub... |
python | def _parse_params(self, params=None):
"""
Parse parameters.
Combine default and user-defined parameters.
"""
prm = self.default_params.copy()
if params is not None:
prm.update(params)
# Background file is essential!
if not prm["background"]... |
java | @Override
public T deletePackages(boolean recursive, Filter<ArchivePath> filter, Package... packages) throws IllegalArgumentException {
Validate.notNullAndNoNullValues(packages, "Packages must be specified and cannot contain null values");
Validate.notNull(filter, "Filter must be specified");
... |
java | public boolean isMultipleSelect()
throws CacheReloadException
{
final boolean ret;
if (isRoot()) {
ret = this.multipleSelect;
} else {
ret = getParentClassification().isMultipleSelect();
}
return ret;
} |
java | public DescribeParametersRequest withParameterFilters(ParameterStringFilter... parameterFilters) {
if (this.parameterFilters == null) {
setParameterFilters(new com.amazonaws.internal.SdkInternalList<ParameterStringFilter>(parameterFilters.length));
}
for (ParameterStringFilter ele : ... |
python | def solar_zenith(self, dateandtime, latitude, longitude):
"""Calculates the solar zenith angle.
:param dateandtime: The date and time for which to calculate
the angle.
:type dateandtime: :class:`~datetime.datetime`
:param latitude: Latitude - Northern latit... |
python | def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently su... |
java | public static Method getSingleSetter(String fieldName, Class<?> clazz) {
String setterName = buildSetterName(fieldName);
try {
// Using getMathods(), getMathod(...) expects exact parameter type
// matching and ignores inheritance-tree.
Method[] methods = clazz.getMethods();
List<Method> ... |
java | @SuppressWarnings("unchecked")
private void processQueue() {
ValueRef<K, V> ref = (ValueRef<K, V>) queue.poll();
while (ref != null) {
// only remove if it is the *exact* same WeakValueRef
if (ref == map.get(ref.getKey()))
map.remove(ref.getKey());
ref = (ValueRef<... |
java | public static FloatProperty wrapFloatProperty(final Property<Float> dolphinProperty) {
Assert.requireNonNull(dolphinProperty, "dolphinProperty");
final FloatProperty property = new SimpleFloatProperty();
FXBinder.bind(property).bidirectionalToNumeric(dolphinProperty);
return property;
... |
java | public static void print(final UnknownFieldSet fields,
final Appendable output)
throws IOException {
DEFAULT_PRINTER.printUnknownFields(fields, new TextGenerator(output));
} |
python | def _export(self, args, **extra_args):
"""
Export is the entry point for exporting docker images.
"""
if not isinstance(args, argparse.Namespace):
raise TypeError(logger.error("args should of an instance of argparse.Namespace"))
# Warn the consumer about unsafe Docke... |
java | public BoxRequestsFile.UpdateFile getMoveRequest(String id, String parentId) {
BoxRequestsFile.UpdateFile request = new BoxRequestsFile.UpdateFile(id, getFileInfoUrl(id), mSession);
request.setParentId(parentId);
return request;
} |
java | @Override
public final OperationEntry getOperationEntry(final PathAddress pathAddress, final String operationName) {
if (parent != null) {
RootInvocation ri = getRootInvocation();
return ri.root.getOperationEntry(ri.pathAddress.append(pathAddress), operationName);
}
... |
java | public static void main(String[] args) {
// Test
RiddersMethod search = new RiddersMethod(-1.0, 5.0);
while(search.getAccuracy() > 1E-13 && !search.isDone()) {
double x = search.getNextPoint();
double y = x - 0.656;
search.setValue(y);
System.out.println(search.getAccuracy());
}
System.out.pri... |
python | def signal_handler(sig, frame):
"""Helper method to shutdown the RedBot if Ctrl-c is pressed"""
print('\nYou pressed Ctrl+C')
if board is not None:
board.send_reset()
board.shutdown()
sys.exit(0) |
java | public Observable<ServerInner> getByResourceGroupAsync(String resourceGroupName, String serverName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() {
@Override
public ServerInner call(ServiceRes... |
python | def preserve_view(*predicates):
""" Raising ViewNotMatched when applied request was not apposite.
preserve_view calls all Predicates and when return values of them was
all True it will call a wrapped view.
It raises ViewNotMatched if this is not the case.
Predicates:
This decorator takes Predi... |
java | @Override
public int doStartTag() throws JspException {
try {
conn = getConnection();
} catch (SQLException e) {
throw new JspException(sql + ": " + e.getMessage(), e);
}
return EVAL_BODY_BUFFERED;
} |
java | public Pipeline pipelineWithPasswordAwareBuildCauseByBuildId(final long buildId) {
Pipeline pipeline = pipelineDao.pipelineWithMaterialsAndModsByBuildId(buildId);
MaterialRevisions scheduledRevs = pipeline.getBuildCause().getMaterialRevisions();
MaterialConfigs knownMaterials = knownMaterials(pi... |
java | public void setIfexists(String elementList) {
if (elementList != null) {
m_elementList = elementList;
m_checkall = false;
m_checknone = false;
}
} |
java | public TagsEnvelope getTagSuggestions(String entityType, String tags, String name, Integer count) throws ApiException {
ApiResponse<TagsEnvelope> resp = getTagSuggestionsWithHttpInfo(entityType, tags, name, count);
return resp.getData();
} |
python | def _add_training_data(self, src, dst, symbol):
"""
Training_data is a dictionary from strings to lists.
- Each string (key) is an access string
- Each list (value) is a list of tuples (target_state, [symbols directed to that
state]). These represent that a transition exists from... |
python | def postParse(self, instring, loc, token_list):
"""Create a list from the tokens
:param instring:
:param loc:
:param token_list:
:return:
"""
cleaned_token_list = [token for tokens in (token.tokens if isinstance(token, ConfigInclude) else [token]
... |
java | public static List<SettingsResult> getSettingsResults(Result r) {
if(r instanceof SettingsResult) {
List<SettingsResult> ors = new ArrayList<>(1);
ors.add((SettingsResult) r);
return ors;
}
if(r instanceof HierarchicalResult) {
return ResultUtil.filterResults(((HierarchicalResult) r)... |
python | def verify_identifiers(identifiers, n_items):
"""Ensure that identifiers has a compatible length and that its elements
are unique"""
if identifiers is None:
return identifiers
identifiers = np.array(identifiers, copy=False)
# Check length for consistency
if len(identifiers) != n_items:... |
java | public TableRef create(Key key, Throughput throughput, OnTableCreation onTableCreation, OnError onError) {
PostBodyBuilder pbb = new PostBodyBuilder(context);
pbb.addObject("table", this.name);
pbb.addObject("provisionType", StorageProvisionType.CUSTOM.getValue());
pbb.addObject("key", key.map());
pbb.addObje... |
java | public T one(String id) {
try {
return baseQuery().one(id).blockingFirst();
} catch (NullPointerException e) {
throw new CDAResourceNotFoundException(type, id);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.