language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def get_diff(self, rev1, rev2, path=None, ignore_whitespace=False,
context=3):
"""
Returns (git like) *diff*, as plain text. Shows changes introduced by
``rev2`` since ``rev1``.
:param rev1: Entry point from which diff is shown. Can be
``self.EMPTY_CHANGESET``... |
java | boolean registerAddOn(AddOn pAddOn) {
if (!mRegisteredAddOns.containsKey(pAddOn.getAddOnId())) {
mRegisteredAddOns.put(pAddOn.getAddOnId(), pAddOn);
if (pAddOn.hasConfiguration()) {
addConfiguration(pAddOn.getAddOnId(), pAddOn.getConfigurationPane());
}
... |
java | private void setChildObjects(Object pParent, ObjectMapper pOM)
throws SQLException {
if (pOM == null) {
throw new NullPointerException("ObjectMapper in readChildObjects "
+ "cannot be null!!");
}
for (Enumeration keys = pOM.m... |
python | def configure(self, sbi_config: str):
"""Configure an SBI for this subarray.
Args:
sbi_config (str): SBI configuration JSON
Returns:
str,
"""
# print(sbi_config)
config_dict = json.loads(sbi_config)
self.debug_stream('SBI configuration:\... |
python | def lookup(command):
"""
Lookup a command in PATH. For example::
>>> lookup('ls')
'/usr/bin/ls'
>>> lookup('usermod')
'/usr/sbin/usermod'
>>> lookup('foobar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Inv... |
java | public void setAddLicenseSpecifications(java.util.Collection<LicenseSpecification> addLicenseSpecifications) {
if (addLicenseSpecifications == null) {
this.addLicenseSpecifications = null;
return;
}
this.addLicenseSpecifications = new java.util.ArrayList<LicenseSpecifica... |
java | @Override
public int read(long pos, byte []buf, int offset, int length)
{
if (pos < 0) {
throw new IllegalArgumentException();
}
if (_length <= pos) {
return -1;
}
int bufOffset = (int) (_offset + pos);
int sublen = (int) Math.min(length, _length - pos);
System... |
java | public void attachUserData(String connId, KeyValueCollection userData) throws WorkspaceApiException {
try {
VoicecallsidcompleteData completeData = new VoicecallsidcompleteData();
completeData.setUserData(Util.toKVList(userData));
UserDataOperationId data = new UserDataOp... |
python | def humansorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
"""
Convenience function to properly sort non-numeric characters.
This is a wrapper around ``natsorted(seq, alg=ns.LOCALE)``.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A k... |
python | def _combine_attr_fast_update(self, attr, typ):
'''Avoids having to call _update for each intermediate base. Only
works for class attr of type UpdateDict.
'''
values = dict(getattr(self, attr, {}))
for base in self._class_data.bases:
vals = dict(getattr(bas... |
python | def get_departures(self, stop_id, route, destination, api_key):
"""Get the latest data from Transport NSW."""
self.stop_id = stop_id
self.route = route
self.destination = destination
self.api_key = api_key
# Build the URL including the STOP_ID and the API key
url... |
python | def encode(self, val):
"""
Encode the python datetime value into the bytes needed for database format.
:param val: The datetime object.
:type val: :class:`datetime.datetime`
:returns: Bytes for data.
:rtype: str
"""
# Just copied from original K... |
java | protected void bindWebSecurityManager(AnnotatedBindingBuilder<? super WebSecurityManager> bind) {
try {
bind.toConstructor(DefaultWebSecurityManager.class.getConstructor(Collection.class)).asEagerSingleton();
} catch (NoSuchMethodException e) {
throw new ConfigurationException("T... |
python | def getLogger(*args, **kwargs):
"""
Summary:
custom format logger
Args:
mode (str): The Logger module supprts the following log modes:
- log to console / stdout. Log_mode = 'stream'
- log to file
- log to system logger (syslog)
Returns:
log... |
python | def search(self, read_cache=True, ssl_verify=True, recid=None, **kwparams):
"""
Returns records corresponding to the given search query.
See docstring of invenio.legacy.search_engine.perform_request_search()
for an overview of available parameters.
"""
parse_results = Fa... |
python | def resend_invitations(self):
"""
Resends invites for an event. ::
event = service.calendar().get_event(id='KEY HERE')
event.resend_invitations()
Anybody who has not declined this meeting will get a new invite.
"""
if not self.id:
raise TypeError(u"You can't send invites fo... |
java | static Token complementRanges(Token token) {
if (token.type != RANGE && token.type != NRANGE)
throw new IllegalArgumentException(
"Token#complementRanges(): must be RANGE: " + token.type);
RangeToken tok = (RangeToken) token;
tok.sortRanges();
tok.compactRanges();
int len = tok.ranges.length + ... |
java | private static String key2Str(Key k, byte type) {
String s = key2Str_impl(k, type);
Key x;
assert (x = str2Key_impl(s)).equals(k) : "bijection fail " + k + "." + (char) type + " <-> " + s + " <-> " + x;
return s;
} |
java | private static String mapEnglishPennTagSetToNAF(final String postag) {
if (postag.startsWith("RB")) {
return "A"; // adverb
} else if (postag.equalsIgnoreCase("CC")) {
return "C"; // conjunction
} else if (postag.startsWith("D") || postag.equalsIgnoreCase("PDT")) {
return "D"; // determine... |
java | public final <T> TcpServer attr(AttributeKey<T> key, @Nullable T value) {
Objects.requireNonNull(key, "key");
return bootstrap(b -> b.childAttr(key, value));
} |
java | public static List<? extends IResource> chain(IResource resource)
{
List<IResource> chain = new ArrayList<IResource>();
while (true)
{
chain.add(resource);
if (!resource.hasParent())
break;
resource = resource.getParent();
}
ret... |
java | protected void updateRoles(final LoginContext _login,
final Person _person)
throws EFapsException
{
for (final JAASSystem system : JAASSystem.getAllJAASSystems()) {
if (system.getRoleJAASPrincipleClass() != null) {
final Set<?> rolesJaas = _... |
java | public static int writeString(DataOutput out, String s) throws IOException {
if (s.length() > 0xffff/3) { // maybe too long
LOG.warn("truncating long string: " + s.length()
+ " chars, starting with " + s.substring(0, 20));
s = s.substring(0, 0xffff/3);
}
int len = utf... |
java | public double getDoublePropertyFallback(T property) throws NumberFormatException
{
try
{
return Double.parseDouble(getProperty(property));
}
catch (NumberFormatException e)
{
return Double.parseDouble(getDefaultProperty(property));
}
... |
python | def get_film_id(self, title, three_dimensional=False):
"""get the film id using the title in conjunction with the searching function"""
films = self.film_search(title)
for film in films:
if (film['title'].find('3D') is - 1) is not three_dimensional:
return film['edi']... |
java | @Override
public double getPercentageOfIdentity(boolean countGaps) {
double seqid = getNumIdenticals();
double length = getLength();
if (!countGaps) {
length = length - getAlignedSequence(1).getNumGapPositions()
- getAlignedSequence(2).getNumGapPositions();
}
return seqid / length;
} |
java | @Override
public Future<Void> registerProvider(final String domain,
Object provider,
ProviderQos providerQos,
boolean awaitGlobalRegistration) {
if (providerQos == null) {
t... |
java | protected JsonToken handleBinary() throws IOException {
int size = _in.readInt();
byte subtype = _in.readByte();
Context ctx = getContext();
switch (subtype) {
case BsonConstants.SUBTYPE_BINARY_OLD:
int size2 = _in.readInt();
byte[] buf2 = new byte[size2];
_in.readFully(buf2);
ctx.value = buf2;
... |
java | public List<Integer> getDogmaAttributes(String datasource, String ifNoneMatch) throws ApiException {
ApiResponse<List<Integer>> resp = getDogmaAttributesWithHttpInfo(datasource, ifNoneMatch);
return resp.getData();
} |
python | def register_actions(self, shortcut_manager):
"""Register callback methods fot triggered actions.
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_fo... |
python | def burst_run(self):
""" Run CPU as fast as Python can... """
# https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...
get_and_call_next_op = self.get_and_call_next_op
for __ in range(self.outer_burst_op_count):
for __ in range(self.inner_burst_op_count):
... |
java | public final void entryRuleLiteralCondition() throws RecognitionException {
try {
// InternalXtext.g:596:1: ( ruleLiteralCondition EOF )
// InternalXtext.g:597:1: ruleLiteralCondition EOF
{
before(grammarAccess.getLiteralConditionRule());
pushFollow(... |
java | private String resolveUri(String rawUri, EntityContext context, boolean handleURIOverride) throws Siren4JException {
String resolvedUri = rawUri;
String baseUri = null;
boolean fullyQualified = false;
if (context.getCurrentObject() instanceof Resource) {
Resource resourc... |
python | def Parse(self, rdf_data):
"""Process rdf data through filters. Test if results match expectations.
Processing of rdf data is staged by a filter handler, which manages the
processing of host data. The output of the filters are compared against
expected results.
Args:
rdf_data: An list contai... |
python | def multiply(self, matrix):
"""
Multiply this matrix by a local dense matrix on the right.
:param matrix: a local dense matrix whose number of rows must match the number of columns
of this matrix
:returns: :py:class:`IndexedRowMatrix`
>>> mat = IndexedRow... |
java | public SimplifySpanBuild append(String text) {
if (TextUtils.isEmpty(text)) return this;
mNormalSizeText.append(text);
mStringBuilder.append(text);
return this;
} |
java | public void marshallAsAttribute(final AttributeDefinition attribute,final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException{
throw ControllerLogger.ROOT_LOGGER.couldNotMarshalAttributeAsAttribute(attribute.getName());
} |
java | protected ResponseFuture doInvokeAsync(SofaRequest request, RpcInternalContext rpcContext, int timeoutMillis) {
SofaResponseCallback listener = request.getSofaResponseCallback();
if (listener != null) {
AbstractHttpClientHandler callback = new CallbackInvokeClientHandler(transportConfig.getC... |
java | public ExternalAutoCommitTransaction createAutoCommitTransaction()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createAutoCommitTransaction");
ExternalAutoCommitTransaction instance = new MSAutoCommitTransaction(_ms, _persistence, getMaximumTransactionSize());... |
java | public static synchronized Map<String, Statistics> getStatistics() {
Map<String, Statistics> result = new HashMap<String, Statistics>();
for(Statistics stat: statisticsTable.values()) {
result.put(stat.getScheme(), stat);
}
return result;
} |
python | def _is_in_try_again(self, x, y):
"""Checks if the game is to be restarted."""
if self.won == 1:
# Checks if in try button on won screen.
x1, y1, x2, y2 = self._won_try_again
return x1 <= x < x2 and y1 <= y < y2
elif self.lost:
# Checks if in try b... |
java | public static double elementDiagonalMaxAbs( DMatrixD1 a ) {
final int size = Math.min(a.numRows,a.numCols);
double max = 0;
for( int i = 0; i < size; i++ ) {
double val = Math.abs(a.get( i,i ));
if( val > max ) {
max = val;
}
}
... |
python | def indent(text: str, num: int = 2) -> str:
"""Indent a piece of text."""
lines = text.splitlines()
return "\n".join(indent_iterable(lines, num=num)) |
python | def create_head(nf:int, nc:int, lin_ftrs:Optional[Collection[int]]=None, ps:Floats=0.5,
concat_pool:bool=True, bn_final:bool=False):
"Model head that takes `nf` features, runs through `lin_ftrs`, and about `nc` classes."
lin_ftrs = [nf, 512, nc] if lin_ftrs is None else [nf] + lin_ftrs + [nc]
... |
python | def _signal_handler(self, *_) -> None:
"""
On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal.
"""
if self._num_signals == 0:
logging.warning('Interrupt signal caught - training will be terminated')
... |
python | def performXpath(parent, xpath):
""" Perform an XPath on an element and indicate if we need to loop over it to find something
:param parent: XML Node on which to perform XPath
:param xpath: XPath to run
:return: (Result, Need to loop Indicator)
"""
loop = False
if xpath.startswith(".//"):
... |
java | private Assignment doSamplingRound(FactorGraph factorGraph, Assignment curAssignment) {
Assignment assignment = curAssignment;
int[] variableNums = factorGraph.getVariables().getVariableNumsArray();
for (int i = 0; i < variableNums.length; i++) {
assignment = doSample(factorGraph, assignment, variableNums[i]... |
python | def recalculate_concepts(self, concepts, lang=None):
"""
Recalculated given concepts for given users
Args:
concepts (dict): user id (int -> set of concepts to recalculate)
lang(Optional[str]): language used to get items in all concepts (cached).
Defaults ... |
java | public ListenerUtils putListener(String tag, SuperToast.OnDismissListener onDismissListener) {
this.mOnDismissListenerHashMap.put(tag, onDismissListener);
return this;
} |
python | def all_terminated():
"""For each remote shell determine if its terminated"""
instances_found = False
for i in all_instances():
instances_found = True
if i.state not in (remote_dispatcher.STATE_TERMINATED,
remote_dispatcher.STATE_DEAD):
return False
... |
java | public void releaseMe() {
Ancestor eot = Stapler.getCurrentRequest().findAncestor(BoundObjectTable.class);
if (eot==null)
throw new IllegalStateException("The thread is not handling a request to a abound object");
String id = eot.getNextToken(0);
resolve(false).release(id); ... |
java | @Override
public Response toResponse(final AccessDeniedException e) {
debugException(this, e, LOGGER);
return status(FORBIDDEN).build();
} |
python | def moment1(self):
"""The first time delay weighted statistical moment of the
instantaneous unit hydrograph."""
delays, response = self.delay_response_series
return statstools.calc_mean_time(delays, response) |
python | def get_downsample_pct(in_bam, target_counts, data):
"""Retrieve percentage of file to downsample to get to target counts.
Avoids minimal downsample which is not especially useful for
improving QC times; 90& or more of reads.
"""
total = sum(x.aligned for x in idxstats(in_bam, data))
with pysam... |
java | public void marshall(AssociateIpGroupsRequest associateIpGroupsRequest, ProtocolMarshaller protocolMarshaller) {
if (associateIpGroupsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(associa... |
java | public static <K, V, NV> Map<K, NV> newFilteredChangedValueWithEntryMap(
Map<K, V> map, Predicate<Entry<K, V>> filter,
Function<Entry<K, V>, NV> changingValueFunction) {
return getEntryStreamWithFilter(map, filter).collect(
toMap(Entry::getKey, changingValueFunction::appl... |
python | def quote_edge(identifier):
"""Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s'
"""
node, _, rest = identifier.partition(':')
... |
python | def __bad_transition(self, state):
"""
Raises an C{AssertionError} exception for an invalid state transition.
@see: L{stateNames}
@type state: int
@param state: Intended breakpoint state.
@raise Exception: Always.
"""
statemsg = ""
oldState = s... |
java | public URL asDirectoryURL() throws MalformedURLException {
final String pathName = getPathName(false);
return new URL(VFSUtils.VFS_PROTOCOL, "", -1, parent == null ? pathName : pathName + "/", VFSUtils.VFS_URL_HANDLER);
} |
java | @Override
public void removeSection(int identity) throws InvalidRecoverableUnitSectionException, InternalLogException
{
if (tc.isEntryEnabled())
Tr.entry(tc, "removeSection", new java.lang.Object[] { this, new Integer(identity) });
// REQD: Implementation not yet provided. No users ... |
java | public <OUT> IPromise serve(Publisher<OUT> source, ActorPublisher networRxPublisher, boolean closeConnectionOnCompleteOrError, Consumer<Actor> disconCB) {
if ( networRxPublisher.getClass().getSimpleName().equals("HttpPublisher") ) {
throw new RuntimeException("Http long poll cannot be supported. Use... |
java | @Nullable
private TableReportEntryTable convertToTableReportEntryTable(
String tableId, Map<String, Object> map, Predicate<String> placementFilter,
Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) {
// Check the filters for placement, dropped, and facade
... |
python | def get_dynamical_matrix_at_q(self, q):
"""Calculate dynamical matrix at a given q-point
Parameters
----------
q: array_like
A q-vector.
shape=(3,), dtype='double'
Returns
-------
dynamical_matrix: ndarray
Dynamical matrix.
... |
java | public void advanceNodeStage() {
this.setQueryStageTimeStamp(Calendar.getInstance().getTime());
switch (this.nodeStage) {
case NODEBUILDINFO_EMPTYNODE:
try {
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_PROTOINFO);
this.controller.identifyNode(this.nodeId);
} catch (SerialInterfaceExcept... |
java | @Deprecated
public Add add(long projectId, String deviceId, String deviceName, String deviceType,
Date created) {
return add(projectId, new Device.Spec(deviceId, deviceName, deviceType), created);
} |
java | public GenericsContext parameterTypeAs(final int pos, final Class<?> asType) {
checkParameter(pos);
return inlyingTypeAs(meth.getGenericParameterTypes()[pos], asType);
} |
java | @SuppressWarnings("unchecked") // cache ensures types match
@Override public <T> ModuleAdapter<T> getModuleAdapter(Class<T> type) {
return (ModuleAdapter<T>) loadedAdapters.get(type);
} |
java | private void setWeekDays(SortedSet<WeekDay> weekDays) {
List<CmsCheckBox> checked = new ArrayList<CmsCheckBox>();
for (WeekDay day : weekDays) {
for (CmsCheckBox box : m_checkboxes) {
if (box.getInternalValue().equals(day.toString())) {
checked.ad... |
java | public int getTotalPage() {
int i = totalNum % pageSize;
int j = totalNum / pageSize;
return i == 0 ? j : j + 1;
} |
python | def separation_from(self, another_icrf):
"""Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1],... |
java | public long getDateLastVisitedBy(CmsRequestContext context, String poolName, CmsUser user, CmsResource resource)
throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
long result = 0;
try {
result = m_driverManager.getDateLastVisitedBy(dbc, poolName,... |
java | @Override
public Date computeFirstFireTime (final ICalendar calendar)
{
m_aNextFireTime = getFireTimeAfter (new Date (getStartTime ().getTime () - 1000L));
// Check calendar for date-time exclusion
while (m_aNextFireTime != null && calendar != null && !calendar.isTimeIncluded (m_aNextFireTime.getTime (... |
java | public DataLakeAnalyticsAccountInner create(String resourceGroupName, String name, DataLakeAnalyticsAccountInner parameters) {
return createWithServiceResponseAsync(resourceGroupName, name, parameters).toBlocking().last().body();
} |
java | protected Object getProxyFromResultSet() throws PersistenceBrokerException
{
// 1. get Identity of current row:
Identity oid = getIdentityFromResultSet();
// 2. return a Proxy instance:
return getBroker().createProxy(getItemProxyClass(), oid);
} |
python | def _save_to_history(word, data_dir):
"""Write word to history file.
Parameters
----------
word : str
Word to save to history.
data_dir : pathlib.Path
Directory where history file should be saved.
data_dir and it's parent directories will be created if needed.
"""
if no... |
python | def name(self):
"""str: name of the file entry, which does not include the full path."""
if self._name is None:
location = getattr(self.path_spec, 'location', None)
if location is not None:
self._name = self._file_system.BasenamePath(location)
else:
volume_index = apfs_helper.A... |
java | public CloseableIterator<Entry<KeyType>> combine(
List<? extends CloseableIterator<Entry<KeyType>>> sortedIterators,
List<String> mergedDictionary
)
{
// CombineBuffer is initialized when this method is called and closed after the result iterator is done
final Closer closer = Closer.create();
... |
python | def _mark_started(self):
"""
Set the state information for a task once it has completely started.
In particular, the time limit is applied as of this time (ie after
and start delay has been taking.
"""
log = self._params.get('log', self._discard)
now = time.time()
... |
python | def addWatchedDirectory(self, dirname, watching=Purr.WATCHED, save_config=True):
"""Starts watching the specified directories for changes"""
# see if we're alredy watching this exact set of directories -- do nothing if so
dirname = Purr.canonizePath(dirname)
# do nothing if already watch... |
python | def query_segdb(cls, flag, *args, **kwargs):
"""Query the initial LIGO segment database for the given flag
Parameters
----------
flag : `str`
The name of the flag for which to query
*args
Either, two `float`-like numbers indicating the
GPS [s... |
python | def timeout(seconds):
"""
Raises a TimeoutError if a function does not terminate within
specified seconds.
"""
def _timeout_error(signal, frame):
raise TimeoutError("Operation did not finish within \
{} seconds".format(seconds))
def timeout_decorator(func):
@wraps(func)... |
java | public static long MurmurHash3_x64_64_direct(MemoryAccessor mem, long base, int offset, int len) {
return MurmurHash3_x64_64(mem.isBigEndian() ? NARROW_DIRECT_LOADER : WIDE_DIRECT_LOADER,
mem, base + offset, len, DEFAULT_MURMUR_SEED);
} |
python | def get_nfc_quick_check_property(value, is_bytes=False):
"""Get `NFC QUICK CHECK` property."""
obj = unidata.ascii_nfc_quick_check if is_bytes else unidata.unicode_nfc_quick_check
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['nfcquickcheck'].get(negated... |
python | def as_stream(self):
"""Convert this selector to a DataStream.
This function will only work if this is a singular selector that
matches exactly one DataStream.
"""
if not self.singular:
raise ArgumentError("Attempted to convert a non-singular selector to a data stre... |
java | public List<ExpandedAnnotation> expand(final Annotation targetAnno) {
Objects.requireNonNull(targetAnno);
final List<ExpandedAnnotation> expandedList = new ArrayList<>();
if(isRepeated(targetAnno)) {
// 繰り返しのアノテーションの場合、要素を抽出する。
try {
... |
python | def set_data(self, pos=None, color=None, width=None, connect=None,
arrows=None):
"""Set the data used for this visual
Parameters
----------
pos : array
Array of shape (..., 2) or (..., 3) specifying vertex coordinates.
color : Color, tuple, or array
... |
python | def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
# re... |
python | def wait_for_deletion(self, interval=1):
"""
Wait for the online model to be deleted.
:param interval: check interval
"""
deleted = False
while True:
try:
if self.status != OnlineModel.Status.DELETING:
break
exc... |
java | public void setSla(boolean newSla) {
boolean oldSla = sla;
sla = newSla;
boolean oldSlaESet = slaESet;
slaESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.PARAMETER__SLA, oldSla, sla, !oldSlaESet));
} |
java | public FileEntry put( DirectoryEntry parent, String name, byte[] content )
throws IOException
{
return put( parent, name, new ByteArrayInputStream( content ) );
} |
python | def format_duration(minutes, human = True):
"""formats duration in a human readable format.
accepts either minutes or timedelta"""
if isinstance(minutes, dt.timedelta):
minutes = duration_minutes(minutes)
if not minutes:
if human:
return ""
else:
return ... |
python | def full_path(self):
"""Absolute system path to the node"""
if self.parent:
return os.path.join(self.parent.full_path, self.name)
return self.name |
python | def smooth_frames(self, sigtype='physical'):
"""
Convert expanded signals with different samples/frame into
a uniform numpy array.
Input parameters
- sigtype (default='physical'): Specifies whether to mooth
the e_p_signal field ('physical'), or the e_d_signal
... |
python | def get_incomings_per_page(self, per_page=1000, page=1, params=None):
"""
Get incomings per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
... |
python | def connect_entry_signals():
"""
Connect all the signals on Entry model.
"""
post_save.connect(
ping_directories_handler, sender=Entry,
dispatch_uid=ENTRY_PS_PING_DIRECTORIES)
post_save.connect(
ping_external_urls_handler, sender=Entry,
dispatch_uid=ENTRY_PS_PING_EXTE... |
java | public void setValue(int numStrings, String[] newValues) {
value.clear();
if (numStrings == newValues.length) {
for (int i = 0; i < newValues.length; i++) {
value.add(newValues[i]);
}
}
else {
Log.e(TAG, "X3D MFString setValue() numStri... |
java | public static double findMin(double min, double max, Function1D f, double eps, int maxSteps)
{
double a = min, b = max;
double fa = f.f(a), fb = f.f(b);
double c = b - goldenRatio * (b - a);
double d = a + goldenRatio * (b - a);
double fc = f.f(c);
double fd ... |
python | def getCSD (lfps,sampr,minf=0.05,maxf=300,norm=True,vaknin=False,spacing=1.0):
"""
get current source density approximation using set of local field potentials with equidistant spacing
first performs a lowpass filter
lfps is a list or numpy array of LFPs arranged spatially by column
spacing is in microns ... |
java | public static String getLocalizedDateTimePattern(
FormatStyle dateStyle, FormatStyle timeStyle, Chronology chrono, Locale locale) {
Jdk8Methods.requireNonNull(locale, "locale");
Jdk8Methods.requireNonNull(chrono, "chrono");
if (dateStyle == null && timeStyle == null) {
... |
python | def collapse(iterable, base_type=None, levels=None):
"""Flatten an iterable with multiple levels of nesting (e.g., a list of
lists of tuples) into non-iterable types.
>>> iterable = [(1, 2), ([3, 4], [[5], [6]])]
>>> list(collapse(iterable))
[1, 2, 3, 4, 5, 6]
Binary and text strin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.