language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private void removeOldBackups(long daysToKeep) {
long maxAge = (System.currentTimeMillis() - (daysToKeep * 24 * 60 * 60 * 1000));
File[] files = m_backupFolder.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
long lastMod = file.lastModified();... |
python | def __get_model_for_portfolio_value(input_model: PortfolioValueInputModel
) -> PortfolioValueViewModel:
""" loads the data for portfolio value """
result = PortfolioValueViewModel()
result.filter = input_model
ref_datum = Datum()
ref_datum.from_datetime(input_model.as_of_date)
ref_date ... |
python | def get_statistics(self):
"""Get all statistics as a dictionary.
Returns
-------
statistics : Dict[str, List]
"""
return {
'cumulative_elapsed_time': self.get_cumulative_elapsed_time(),
'percentage': self.get_percentage(),
'n_splits': ... |
python | def findalliter(string, sub, regex=False, case_sensitive=False,
whole_word=False):
"""
Generator that finds all occurrences of ``sub`` in ``string``
:param string: string to parse
:param sub: string to search
:param regex: True to search using regex
:param case_sensitive: True t... |
python | def context_notify_cb(self, context, _):
"""Checks wether the context is ready
-Queries server information (server_info_cb is called)
-Subscribes to property changes on all sinks (update_cb is called)
"""
state = pa_context_get_state(context)
if state == PA_CONTEXT_READ... |
java | public static String[] strListToArray(List<String> list) {
if (list == null)
return new String[0];
return list.toArray(new String[list.size()]);
} |
python | def namedb_get_num_blockstack_ops_at( db, block_id ):
"""
Get the number of name/namespace/token operations that occurred at a particular block.
"""
cur = db.cursor()
# preorders at this block
preorder_count_rows_query = "SELECT COUNT(*) FROM preorders WHERE block_number = ?;"
preorder_coun... |
python | def tls_set(self, ca_certs, certfile=None, keyfile=None, cert_reqs=cert_reqs, tls_version=tls_version, ciphers=None):
"""Configure network encryption and authentication options. Enables SSL/TLS support.
ca_certs : a string path to the Certificate Authority certificate files
that are to be treat... |
python | def clear_job_cache(hours=24):
'''
Forcibly removes job cache folders and files on a minion.
.. versionadded:: 2018.3.0
WARNING: The safest way to clear a minion cache is by first stopping
the minion and then deleting the cache files before restarting it.
CLI Example:
.. code-block:: bas... |
python | def get_single_review_comments(self, id):
"""
:calls: `GET /repos/:owner/:repo/pulls/:number/review/:id/comments <https://developer.github.com/v3/pulls/reviews/>`_
:param id: integer
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestComment.PullRequestComme... |
java | public void marshall(UpdateDataSourceRequest updateDataSourceRequest, ProtocolMarshaller protocolMarshaller) {
if (updateDataSourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateData... |
python | def firing_rate(spike_times, window_size=None):
"""Calculate the firing rate of spikes
:param spike_times: times of spike instances
:type spike_times: list
:param window_size: length of time to use to determine rate.
If none, uses time from first to last spike in spike_times
:type window_size: ... |
python | def parse_lookup_expression(element):
""" This syntax parses lookups that are defined with their own element """
lookup_grammar = r"""
lookup = _ "(" range? _ ( "(" _ number _ "," _ number _ ")" _ ","? _ )+ ")"
number = ("+"/"-")? ~r"\d+\.?\d*(e[+-]\d+)?"
_ = ~r"[\s\\]*" # whitespace character
ra... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.FONT_FIDELITY__STP_FNT_EX:
return STP_FNT_EX_EDEFAULT == null ? stpFntEx != null : !STP_FNT_EX_EDEFAULT.equals(stpFntEx);
}
return super.eIsSet(featureID);
} |
python | def welcome_if_new(self, node):
"""
Given a new node, send it all the keys/values it should be storing,
then add it to the routing table.
@param node: A new node that just joined (or that we just found out
about).
Process:
For each key in storage, get k closest ... |
python | def create_namespaced_service(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service # noqa: E501
create a Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> t... |
python | def stats(data):
'''Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data
'''
return {'len': len(data),
'mean': np.mean(data),
'sum': np.sum(data),
'std': np.std(data),
... |
java | public static <V> V wrapCheckedException(StatementWithReturnValue<V> statement) {
try {
return statement.evaluate();
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Throwable e) {
throw new WrappedException(e);... |
python | def Ez(self,*args,**kwargs):
"""
NAME:
Ez
PURPOSE:
calculate the vertical energy
INPUT:
t - (optional) time at which to get the vertical energy (can be Quantity)
pot= Potential instance or list of such instances
vo= (Object-wi... |
python | def solve(self, neigs=4, tol=0, guess=None, mode_profiles=True, initial_mode_guess=None):
"""
This function finds the eigenmodes.
Parameters
----------
neigs : int
number of eigenmodes to find
tol : float
Relative accuracy for eigenvalues. The def... |
java | public boolean isWrapperFor(ServletResponse wrapped) {
if (response == wrapped) {
return true;
} else if (response instanceof ServletResponseWrapper) {
return ((ServletResponseWrapper) response).isWrapperFor(wrapped);
} else {
return false;
}
} |
java | @Override
public int readInt() {
final char[] text0 = this.text;
final int eof = this.limit;
int currpos = this.position;
char firstchar = text0[++currpos];
if (firstchar <= ' ') {
for (;;) {
firstchar = text0[++currpos];
i... |
java | void construct(Class<X> clazz, Field attribute)
{
TypeBuilder<X> typeBuilder = new TypeBuilder<X>(attribute);
typeBuilder.build((AbstractManagedType) managedTypes.get(clazz), attribute.getType());
} |
java | protected <T extends BasicInclude> List<T> aggregateBasicIncludes(List<T> original, AggregatorCallback<T> callback) throws IOException {
final List<T> result = new LinkedList<T>();
final Deque<T> currentAggregateList = new LinkedList<T>();
for (final T originalElement : original) {
/... |
java | public List<SDVariable> multiHeadDotProductAttention(String name, SDVariable queries, SDVariable keys, SDVariable values, SDVariable Wq, SDVariable Wk, SDVariable Wv, SDVariable Wo, SDVariable mask, boolean scaled, boolean withWeights){
List<SDVariable> result = f().multiHeadDotProductAttention(queries, keys, v... |
python | def _metadata_endpoint(self, context):
"""
Endpoint for retrieving the backend metadata
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response with metadata
"""
satosa_logging(logger, l... |
java | public static List<SuspensionRecord> findByUser(EntityManager em, PrincipalUser user) {
TypedQuery<SuspensionRecord> query = em.createNamedQuery("SuspensionRecord.findByUser", SuspensionRecord.class);
try {
query.setParameter("user", user);
return query.getResultList();
... |
python | def _shutdown(self, libvirt_cmd, ssh_cmd, msg):
"""
Choose the invoking method (using libvirt or ssh)
to shutdown / poweroff the domain.
If acpi is defined in the domain use libvirt, otherwise use ssh.
Args:
libvirt_cmd (function): Libvirt function the invoke
... |
java | private static void loadClientProperties(String propertiesPath, String clazzName,
Map<?, Map<String, String>> clientProperties, Map<String, Map<String, String>> entityConfigurations)
{
InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(propertiesPath);
c... |
python | def show_yticklabels(self, row, column):
"""Show the y-axis tick labels for a subplot.
:param row,column: specify the subplot.
"""
subplot = self.get_subplot_at(row, column)
subplot.show_yticklabels() |
java | public static int cs_scatter(DZcs A, int j, double[] beta, int[] w, DZcsa x, int mark, DZcs C, int nz)
{
int i, p, Ap[], Ai[], Ci[] ;
DZcsa Ax = new DZcsa() ;
if (!CS_CSC(A) || (w == null) || !CS_CSC(C)) return (-1) ; /* check inputs */
Ap = A.p ; Ai = A.i ; Ax.x = A.x ; Ci = C.i ;
for (p = Ap [j]; p <... |
python | def _loadSubcatRelations( self, inputFile ):
''' Laeb sisendfailist (inputFile) verb-nom/adv-vinf rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(verbikirjeldus)\TAB(nom/adv-kirjeldus)\TAB(vinfkirjeldus)
nt
leid NEG aeg;S;(... |
python | def get_fixers(self):
"""Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.
"""
... |
java | protected void initJsonWriter() {
String writerList = config.getJsonWriters();
if (writerList != null) {
String[] writers = writerList.split(",");
Set<String> supportedWriters = TreeWriterRegistry.getWritersByFormat("json");
TreeWriter selectedWriter = null;
for (String writer : writers) {
writer = ... |
python | def set_card_standard(self, title, text, smallImageUrl=None,
largeImageUrl=None):
"""Set response card as standard type.
title, text, and image cannot exceed 8,000 characters.
Args:
title: str. Title of Simple or Standard type card.
text: str. ... |
python | def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matchin... |
python | def reverseCommit(self):
"""
Put the document into the 'before' state.
"""
# Put the document into the 'before' state.
self.baseClass.setText(self.textBefore)
self.qteWidget.SCISetStylingEx(0, 0, self.styleBefore) |
java | public void assign(DoubleVector dv) {
for (int i = 0; i < len; i++) {
vect[i] = dv.vect[i];
}
} |
python | def _ReadPaddingDataTypeDefinition(
self, definitions_registry, definition_values, definition_name,
is_member=False):
"""Reads a padding data type definition.
Args:
definitions_registry (DataTypeDefinitionsRegistry): data type definitions
registry.
definition_values (dict[str,... |
python | def CallState(self, next_state="", start_time=None):
"""This method is used to schedule a new state on a different worker.
This is basically the same as CallFlow() except we are calling
ourselves. The state will be invoked at a later time.
Args:
next_state: The state in this flow to be invoked.... |
java | @Override
public void purgeLogsOlderThan(long minTxIdToKeep) throws IOException {
checkEnv();
Collection<EditLogLedgerMetadata> ledgers =
metadataManager.listLedgers(false); // Don't list in-progress ledgers
for (EditLogLedgerMetadata ledger : ledgers) {
if (ledger.getFirstTxId() < minTxId... |
java | public com.squareup.okhttp.Call getSovereigntyStructuresAsync(String datasource, String ifNoneMatch,
final ApiCallback<List<SovereigntyStructuresResponse>> callback) throws ApiException {
com.squareup.okhttp.Call call = getSovereigntyStructuresValidateBeforeCall(datasource, ifNoneMatch, callback);
... |
python | def _assert_is_type(name, value, value_type):
"""Assert that a value must be a given type."""
if not isinstance(value, value_type):
if type(value_type) is tuple:
types = ', '.join(t.__name__ for t in value_type)
raise ValueError('{0} must be one of ({1})'.format(name, types))
... |
python | def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Reassign Storage Adapter Port (requires DPM mode)."""
assert wait_for_completion is True # async not supported yet
partition_oid = uri_parms[0]
partition_uri = '/api/partitions/'... |
java | protected String getStyleSheetName(final HttpServletRequest request, PreferencesScope scope) {
final String stylesheetNameFromRequest;
if (scope.equals(PreferencesScope.STRUCTURE)) {
stylesheetNameFromRequest =
(String) request.getAttribute(STYLESHEET_STRUCTURE_OVERRIDE_... |
python | def read(file):
"""Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYW... |
python | def createfile(self, project_id, file_path, branch_name, encoding, content, commit_message):
"""
Creates a new file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param con... |
java | protected void processField(Row row, String fieldIDColumn, Integer entityID, Object value)
{
int fieldID = row.getInt(fieldIDColumn);
int prefix = fieldID & 0xFFFF0000;
int index = fieldID & 0x0000FFFF;
switch (prefix)
{
case MPPTaskField.TASK_FIELD_BASE:
{
... |
python | def artboards(src_path):
''' Return artboards as a flat list '''
pages = list_artboards(src_path)
artboards = []
for page in pages:
artboards.extend(page.artboards)
return artboards |
python | def find_by_ref(self, ref_type, ref_id):
"""
Returns an object of type "item", "status" or "task" as a
stream object. This is useful when a new status has been
posted and should be rendered directly in the stream without
reloading the entire stream.
For details, see: htt... |
java | public void trainC(ClassificationDataSet dataSet, Set<Integer> categoriesToUse)
{
if(categoriesToUse.size() > dataSet.getNumFeatures()+1)
throw new FailedToFitException("CPT can not train on a number of features greater then the dataset's feature count. "
+ "Specified " + cat... |
python | def prior_predictive_to_xarray(self):
"""Convert prior_predictive samples to xarray."""
prior = self.prior
prior_predictive = self.prior_predictive
data = get_draws(prior, variables=prior_predictive)
return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=... |
python | async def get_mailbox(self, name: str, selected: SelectedMailbox = None) \
-> Tuple[MailboxInterface, Optional[SelectedMailbox]]:
"""Retrieves a :class:`~pymap.interfaces.mailbox.MailboxInterface`
object corresponding to an existing mailbox owned by the user. Raises
an exception if t... |
python | def get_filename(request, date, size_x, size_y):
""" Get filename location
Returns the filename's location on disk where data is or is going to be stored.
The files are stored in the folder specified by the user when initialising OGC-type
of request. The name of the file has the followi... |
python | def get_log(self, log_type, size=0):
"""
Get logs from worker.
:param log_type: type of logs. Possible log types contains {log_types}
:param size: length of the log to retrieve
:return: log content
"""
return self.parent.get_worker_log(self.log_id, log_type, size... |
java | public static void main(final String[] args) throws InjectionException, IOException {
final Configuration partialConfiguration = getEnvironmentConfiguration();
final Injector injector = Tang.Factory.getTang().newInjector(partialConfiguration);
final AzureBatchRuntimeConfigurationProvider runtimeConfigurati... |
java | private void resetValues(FacesContext context) {
Object resetValuesObject = context.getExternalContext().getRequestParameterMap().get(Constants.RequestParams.RESET_VALUES_PARAM);
boolean resetValues = (null != resetValuesObject && "true".equals(resetValuesObject));
if (resetValues) {
... |
java | @GwtIncompatible
public RETokenizer tokenizer(Reader in, int length) throws IOException {
return new RETokenizer(this, in, length);
} |
python | def configure_processes(agent_metadata_map, logger):
"""
This will update the priority and CPU affinity of the processes owned by bots to try to achieve fairness and
good performance.
:param agent_metadata_map: A mapping of player index to agent metadata, including a list of owned process ids.
"""
... |
java | public String getBigIconPath(CmsObject cms, CmsUser user) {
return getIconPath(cms, user, IconSize.Big);
} |
python | def publish(self,topic,options=None,args=None,kwargs=None):
""" Publishes a messages to the server
"""
topic = self.get_full_uri(topic)
if options is None:
options = {'acknowledge':True}
if options.get('acknowledge'):
request = PUBLISH(
... |
python | def missing(self, field):
"""*Asserts the field does not exist.*
The field consists of parts separated by spaces, the parts being
object property names or array indices starting from 0, and the root
being the instance created by the last request (see `Output` for it).
For asser... |
python | def deprecated(msg):
"""Marks a function / method as deprecated.
Takes one argument, a message to be logged with information on future usage of the function or alternative methods
to call.
Args:
msg (str): Deprecation message to be logged
Returns:
`callable`
"""
def decora... |
python | def authenticate(db, user, password):
"""
Return True / False on authentication success.
PyMongo 2.6 changed the auth API to raise on Auth failure.
"""
try:
logger.debug("Authenticating {} with {}".format(db, user))
return db.authenticate(user, password)
except OperationFailure ... |
python | async def mount(self, mount_point, *, mount_options=None):
"""Mount this partition."""
self._data = await self._handler.mount(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id,
mount_point=mount_point,
mount_options=mo... |
java | public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes,
Object... arguments) throws Exception {
return doExpectNew(type, new DefaultMockStrategy(), parameterTypes, arguments);
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.MCDRG__RG_LENGTH:
return getRGLength();
case AfplibPackage.MCDRG__TRIPLETS:
return getTriplets();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public void resolveBeanClass(Token[] tokens) throws IllegalRuleException {
if (tokens != null) {
for (Token token : tokens) {
resolveBeanClass(token);
}
}
} |
python | def score(self, X, y, **kwargs):
"""
Simply returns the score of the underlying CV model
"""
return self.estimator.score(X, y, **kwargs) |
python | def _update_python_paths(self):
""" Append the workflow and libraries paths to the PYTHONPATH. """
for path in self._config['workflows'] + self._config['libraries']:
if os.path.isdir(os.path.abspath(path)):
if path not in sys.path:
sys.path.append(path)
... |
java | @SuppressWarnings("unchecked")
private void doMessage(final JsonObject message) {
Object value = deserializer.deserialize(message);
if (value != null && messageHandler != null) {
if (log.isDebugEnabled()) {
log.debug(String.format("%s - Received: Message[id=%d, value=%s]", this, message.getLong(... |
java | public static void writeUpdateCenterProperties(JsonWriter json, Optional<UpdateCenter> updateCenter) {
if (updateCenter.isPresent()) {
json.propDateTime(PROPERTY_UPDATE_CENTER_REFRESH, updateCenter.get().getDate());
}
} |
python | def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor |
java | @Override
public String getCompleteURL() {
ServletRESTRequestImpl ret = castRequest();
if (ret != null)
return ret.getCompleteURL();
return null;
} |
java | public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
handleRequest(getRequestContent(request));
return true;
} |
java | private static MethodRef getBuildMethod(Descriptor descriptor) {
TypeInfo message = messageRuntimeType(descriptor);
TypeInfo builder = builderRuntimeType(descriptor);
return MethodRef.createInstanceMethod(
builder, new Method("build", message.type(), NO_METHOD_ARGS))
.asNonNullable();
... |
java | public static <K,V> Set<K> keysDifference(Map<K,V> left, Map<K,V> right) {
if (left == null){
return Collections.emptySet();
}
if (right == null){
return left.keySet();
}
return Sets.difference(left.keySet(), right.keySet());
} |
java | public CfgParseTree multiplyProbability(double amount) {
if (isTerminal()) {
return new CfgParseTree(root, ruleType, terminal, getProbability() * amount, spanStart, spanEnd);
} else {
return new CfgParseTree(root, ruleType, left, right, getProbability() * amount);
}
} |
java | private static Predicate<Triple> inDomainRangeFilter(final String domain) {
return triple -> propertiesWithInDomainRange.contains(triple.getPredicate()) &&
!triple.getObject().ntriplesString().startsWith("<" + domain);
} |
python | def _begin(self, client=None, retry=DEFAULT_RETRY):
"""API call: begin the job via a POST request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param c... |
python | def email_embed_image(email, img_content_id, img_data):
"""
email is a django.core.mail.EmailMessage object
"""
img = MIMEImage(img_data)
img.add_header('Content-ID', '<%s>' % img_content_id)
img.add_header('Content-Disposition', 'inline')
email.attach(img) |
java | public synchronized ReturnCode waitForStop() {
// if the lock is null or is invalid, the lock could not be obtained within the timeout
if (!getServerLock()) {
serverLock = null;
lockFileChannel = null;
System.out.println(MessageFormat.format(BootstrapConstants.messag... |
python | def generate_index(credentials, instance_config, instance_name,
script_dir, genome_file, output_dir, annotation_file=None,
splice_overhang=100,
num_threads=8, chromosome_bin_bits=18,
genome_memory_limit=31000000000,
self_dest... |
java | public static auditnslogpolicy_aaagroup_binding[] get(nitro_service service, String name) throws Exception{
auditnslogpolicy_aaagroup_binding obj = new auditnslogpolicy_aaagroup_binding();
obj.set_name(name);
auditnslogpolicy_aaagroup_binding response[] = (auditnslogpolicy_aaagroup_binding[]) obj.get_resources(se... |
java | public ApiResponse<FleetSquadCreatedResponse> postFleetsFleetIdWingsWingIdSquadsWithHttpInfo(Long fleetId,
Long wingId, String datasource, String token) throws ApiException {
com.squareup.okhttp.Call call = postFleetsFleetIdWingsWingIdSquadsValidateBeforeCall(fleetId, wingId,
datasou... |
java | private void updateEffectiveLevel() {
// assert Thread.holdsLock(treeLock);
// Figure out our current effective level.
int newLevelValue;
if (levelObject != null) {
newLevelValue = levelObject.intValue();
} else {
if (parent != null) {
new... |
java | private Registry startRmiRegistryProcess(Configuration configuration, final int port) {
try {
final String javaHome = System.getProperty(JAVA_HOME);
String command = null;
if (javaHome == null) {
command = "rmiregistry";
} else {
i... |
python | def run_as(self, identifiers):
"""
:type identifiers: subject_abcs.IdentifierCollection
"""
if (not self.has_identifiers):
msg = ("This subject does not yet have an identity. Assuming the "
"identity of another Subject is only allowed for Subjects "
... |
java | static boolean isCommutative(Token type) {
switch (type) {
case MUL:
case BITOR:
case BITXOR:
case BITAND:
return true;
default:
return false;
}
} |
java | public static Message buildSnapshotDone(String filePath) {
ZabMessage.SnapshotDone done =
ZabMessage.SnapshotDone.newBuilder().setFilePath(filePath).build();
return Message.newBuilder().setType(MessageType.SNAPSHOT_DONE)
.setSnapshotDone(done).build();
} |
java | public static GlobalApp ensureGlobalApp( HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext )
{
GlobalApp ga = getGlobalApp( request );
if ( ga != null )
{
ga.reinitialize( request, respons... |
java | public void marshall(ReservationPlanSettings reservationPlanSettings, ProtocolMarshaller protocolMarshaller) {
if (reservationPlanSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(reservatio... |
python | def p_print_list(p):
""" print_list : print_list SC print_elem
"""
p[0] = p[1]
p[0].eol = (p[3] is not None)
if p[3] is not None:
p[0].appendChild(p[3]) |
python | def words(text):
"""
Extracts a list of words from the inputted text, parsing
out non-alphanumeric characters and splitting camel
humps to build the list of words
:param text <str>
:return <str>
:usage |import projex.text
|print projex... |
python | def add_timing_signal_nd(x, min_timescale=1.0, max_timescale=1.0e4):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase in one of the positional dimensions.
This allows attention to learn to use ab... |
java | public static <T> T instantiate(Class<T> anInterface, String className) throws CmsException {
try {
Class<?> cls = Class.forName(className, false, anInterface.getClassLoader());
if (!anInterface.isAssignableFrom(cls)) {
// class was found, but does not implement the inte... |
java | public DiscreteInterval minus(DiscreteInterval other) {
return new DiscreteInterval(this.min - other.max, this.max - other.min);
} |
python | def application(self, id=None, manifest=None, name=None):
""" Smart method. Creates, picks or modifies application.
If application found by name or id and manifest not changed: return app.
If app found by id, but other parameters differs: change them.
If no application found, create.
... |
python | def __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
master_key):
"""Gets the authorization token using `mas... |
python | def asDictionary(self):
""" returns the object as a dictionary """
template = {
"type" : "esriSMS",
"style" : self._style,
"color" : self._color,
"size" : self._size,
"angle" : self._angle,
"xoffset" : self._xoffset,
"yo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.