language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def embed(contents='', width='100%', height=512, *args, **kwargs):
"""
Embed geojson.io in an iframe in Jupyter/IPython notebook.
Parameters
----------
contents - see make_url()
width - string, default '100%' - width of the iframe
height - string / int, default 512 - height of the iframe
... |
python | def maybe_with_graph(graph=None, create_if_none=True):
"""Eager-compatible Graph().as_default() yielding the graph."""
if tf.executing_eagerly():
yield None
else:
if graph is None and create_if_none:
graph = tf.Graph()
if graph is None:
yield None
else:
with graph.as_default():
... |
python | def combine(self, x):
"""Return the output from the experts.
When one example goes to multiple experts, the outputs are summed.
Args:
x: a Tensor with shape [batch, num_experts, expert_capacity, depth]
Returns:
a `Tensor` with shape `[batch, length, depth]
"""
depth = tf.shape(x)[... |
python | def add_route(app, fn, context=default_context):
"""
a decorator that adds a transmute route to the application.
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add... |
java | static int scanTypeArgumentSignature(String string, int start) {
// need a minimum 1 char
if (start >= string.length()) {
throw new IllegalArgumentException();
}
char c = string.charAt(start);
switch (c) {
case C_STAR :
return start;
case C_EXTENDS :
case C_SUPER :
return scanTypeBoundSign... |
python | def get_last_array(self):
"""
Returns last array in compound.
:rtype: CompoundSequenceReader
"""
# Get the root array (might not have been registered).
root = self.repo[self.id]
# Get length and last item in the root array.
apex_id, apex_height = root.ge... |
python | def bbox(hashcode):
"""
decode a hashcode and get north, south, east and west border.
"""
lat, lon, lat_length, lon_length = _decode_c2i(hashcode)
if hasattr(float, "fromhex"):
latitude_delta = 180.0/(1 << lat_length)
longitude_delta = 360.0/(1 << lon_length)
latitude = _int... |
java | public static InitialisersFinder newInstance(final Collection<MethodNode> methodsOfAnalysedClass,
final CandidatesInitialisersMapping candidatesInitialisersMapping) {
final String msgTemplate = "Argument '%s' must not be null!";
checkNotNull(methodsOfAnalysedClass, format(msgTemplate, "metho... |
java | public ReactiveTask requestAsync(final long n) {
return withSubscriptionAndTask(subscriptionAndTask.map2(c -> CompletableFuture.runAsync(() -> subscriptionAndTask._1().join()
.request(n),
... |
python | def fix_pbc(structure, matrix=None):
"""
Set all frac_coords of the input structure within [0,1].
Args:
structure (pymatgen structure object):
input structure
matrix (lattice matrix, 3 by 3 array/matrix)
new structure's lattice matrix, if none, use
input ... |
java | private void unregisterMBeanInService(String name) {
ServiceRegistration<DynamicMBean> existingMBean = endpointMBeans.remove(name);
if (existingMBean != null) {
existingMBean.unregister();
}
} |
python | def get_queryset(self, **kwargs):
"""
Gets our queryset. This takes care of filtering if there are any
fields to filter by.
"""
queryset = self.derive_queryset(**kwargs)
return self.order_queryset(queryset) |
python | def get_country_info_from_iso2(cls, iso2, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
"""Get country name from ISO2 code
Args:
iso2 (str): ISO2 code for which to get country information
use_live (bool): Try to... |
python | def DOMDebugger_removeInstrumentationBreakpoint(self, eventName):
"""
Function path: DOMDebugger.removeInstrumentationBreakpoint
Domain: DOMDebugger
Method name: removeInstrumentationBreakpoint
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'eventName' (t... |
python | def get_connectable_volume_templates(self, start=0, count=-1, filter='', query='', sort=''):
"""
Gets the storage volume templates that are available on the specified networks based on the storage system
port's expected network connectivity. If there are no storage volume templates that meet the... |
java | @Override
protected RepositoryImpl createRepository() throws IOException {
try {
final RepositoryConfig config = createRepositoryConfiguration();
return RepositoryImpl.create(config);
} catch (final ConfigurationException e) {
LOG.error("Configuration invalid", e... |
python | def create(self, cidr_mask, description, **kwargs):
"""Create an ACL for this instance.
See :py:meth:`Acls.create` for call signature.
"""
return self._instance._client.acls.create(
self._instance.name,
cidr_mask,
description,
**kwargs
... |
python | def tie_break(sorted_list, results, prop_key, ndecoys):
"""
When finding the best ensemble, using "find_best_ensemble," in the event of a tie, we break it by looking at
enrichment factors at successively larger FPF values, beginning with the smallest FPF not trained on.
:param sorted_list:
:param re... |
python | def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
enable_rev_strand_matc... |
python | def get_speaker_muted(self):
"""Return whether or not the speaker is muted."""
if not self.camera_extended_properties:
return None
speaker = self.camera_extended_properties.get('speaker')
if not speaker:
return None
return speaker.get('mute') |
java | public void purgeOldPersistedFile() throws IOException {
if (!this.persistDir.isPresent() || !this.fs.exists(this.persistDir.get())) {
log.info("No persist directory to clean.");
return;
}
long retentionMillis = TimeUnit.HOURS.toMillis(this.retentionHours);
long now = System.currentTimeMill... |
python | def from_path(cls, path):
"""Read configuration from a file on disk."""
f = GitFile(path, 'rb')
try:
ret = cls.from_file(f)
ret.path = path
return ret
finally:
f.close() |
python | def in_date(objet, pattern):
""" abstractSearch dans une date datetime.date"""
if objet:
pattern = re.sub(" ", '', pattern)
objet_str = abstractRender.date(objet)
return bool(re.search(pattern, objet_str))
return False |
java | public int getScale(final int column) throws SQLException {
final int type = getColumnType(column);
if (type == -1) {
return 0;
} // end of if
final Integer s = Defaults.jdbcTypeScales.get(type);
return (s == null) ? 0 : s;
... |
java | @SuppressWarnings("PMD.NcssCount")
static String expandEscapedChars(String str) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == '\\') {
++i;
if (i >= str.length()) {
throw error("dangling escape", st... |
java | private static int findCommonAncestor(RevisionInternal rev, List<String> possibleRevIDs) {
if (possibleRevIDs == null || possibleRevIDs.size() == 0) {
return 0;
}
List<String> history = Database.parseCouchDBRevisionHistory(rev.getProperties());
//rev is missing _revisions pr... |
java | @SuppressWarnings("unchecked")
public <T extends TermedStatementDocument> T updateTermsStatements(T currentDocument,
List<MonolingualTextValue> addLabels,
List<MonolingualTextValue> addDescriptions,
List<MonolingualTextValue> addAliases,
List<MonolingualTextValue> deleteAliases,
List<Statement> addState... |
python | def to_df(self, fields=None, fields_to_explode=None):
"""
Export items as rows in a pandas dataframe table.
Parameters
----------
fields: list or dict
List of field names to export, or dictionary mapping output column names
to attribute names of the gene... |
java | public static <A, S, N extends Node<A, S, N>> DepthLimitedSearch<A, S, N> createDepthLimitedSearch(
SearchProblem<A, S, N> components, int depth) {
return new DepthLimitedSearch<A, S, N>(components.getInitialNode(), components.getFinalNode(),
components.getExpander(), depth);
} |
python | def environment(self, id=None, name=None, zone=None, default=False):
""" Smart method. Creates, picks or modifies environment.
If environment found by name or id parameters not changed: return env.
If env found by id, but other parameters differs: change them.
If no environment found, cr... |
java | public void retireWindow(W window) {
W removed = this.mapping.remove(window);
if (removed == null) {
throw new IllegalStateException("Window " + window + " is not in in-flight window set.");
}
} |
java | @Deprecated
public Future<?> disconnect() {
recordTermination();
if (Util.isOverridden(Computer.class,getClass(),"disconnect",OfflineCause.class))
// if the subtype already derives disconnect(OfflineCause), delegate to it
return disconnect(null);
connectTime=0;
... |
python | def merge(*tables, **kwargs):
"""
Convenience function to combine multiple tables (via
:func:`petl.transform.sorts.mergesort`) then combine duplicate rows by
merging under the given key (via
:func:`petl.transform.reductions.mergeduplicates`). E.g.::
>>> import petl as etl
>>> table1... |
java | public final boolean isDeprecated() {
OptionElement deprecatedOption = OptionElement.findByName(options(), "deprecated");
return deprecatedOption != null && "true".equals(deprecatedOption.value());
} |
java | public CompletionStage<String> detectMimeTypeAsync(final Path path) {
String filename = path.getFileName().toString();
Supplier<CompletionStage<byte[]>> supplier = () -> {
final CompletableFuture<byte[]> futureBytes = new CompletableFuture<byte[]>();
AsynchronousFileChannel channel;
... |
python | def create_window(title, url=None, js_api=None, width=800, height=600,
resizable=True, fullscreen=False, min_size=(200, 100), strings={}, confirm_quit=False,
background_color='#FFFFFF', text_select=False, frameless=False, debug=False):
"""
Create a web view window using a nat... |
java | public synchronized void load2() throws IOException {
COL result = create();
if (exists()) {
try (LinesStream stream = linesStream()) {
for (String line : stream) {
if (line.startsWith("#")) continue; // comment
T r = parse(line);
... |
python | def find_tags(self, tag_name, **attribute_filter):
"""
Return a list of all the matched tags in all available xml
:param str tag: specify the tag name
"""
all_tags = [
self.find_tags_from_xml(
i, tag_name, **attribute_filter
)
... |
python | def create_nanopubs_fh(output_fn: str):
"""Create Nanopubs output filehandle
\b
If output fn is '-' will write JSONlines to STDOUT
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be written as a JSON f... |
java | protected Date getDateParam(String paramName, String errorMessage) throws IOException {
return getDateParam(paramName, errorMessage, (Map<String, Object>) inputParams.get());
} |
python | def extract_entity(found):
"""Copy found entity to a dict."""
obj = dict()
for prop in found.entity.property:
obj[prop.name] = prop.value.string_value
return obj |
java | public ModelNode asResource(ModelNode baseAddress, String... args) {
assert getNumWildCards() ==args.length :
"Address arguments don't match number of wildcards: "+getNumWildCards()+" -> "+ Arrays.toString(args);
ModelNode model = new ModelNode();
model.get(ADDRESS).set(baseAdd... |
java | @Override
public Response handle() throws Exception {
Object p = getRequest().getPayload().get("id");
if (JSONObject.NULL.equals(p)) {
getWebDriver().getContext().setCurrentFrame(null, null, null);
} else {
RemoteWebElement iframe;
if (p instanceof String) {
iframe = getIframe((... |
java | protected void rollbackLocalConnection(Connection connection) {
try {
if (connection != null) {
connection.rollback();
}
} catch (Exception e) {
if (logger.isTraceEnabled()) {
logger.trace(e.getMessage());
}
}
} |
python | def _modf(ins):
''' Reminder of div. 2 float values. The result is pushed onto the stack.
'''
op1, op2 = tuple(ins.quad[2:])
output = _float_oper(op1, op2)
output.append('call __MODF')
output.extend(_fpush())
REQUIRES.add('modf.asm')
return output |
python | def get_pyof_obj_new_version(name, obj, new_version):
r"""Return a class attribute on a different pyof version.
This method receives the name of a class attribute, the class attribute
itself (object) and an openflow version.
The attribute will be evaluated and from it we will recover it... |
java | @Override
public Optional<DataType> handleIntermediateGet( TraversalStep traversalStep, Object tree, String key, TraversalStep.Operation op ) {
Optional<Object> optSub = traversalStep.get( tree, key );
Object sub = optSub.get();
if ( sub == null && op == TraversalStep.Operation.SET ) {
... |
python | def load_config(self, path, environments, fill_with_defaults=False):
"""Will load default.yaml and <environment>.yaml at given path.
The environment config will override the default values.
:param path: directory where to find your config files. If the last character is not a slash (/) it will ... |
java | public static String buildRewriteDomain(String backendRoute, String subzone) throws MalformedURLException {
if (backendRoute == null || backendRoute.isEmpty()) {
logger.error("Backend route can't be null.");
return null;
}
String applicationRoute = backendRoute;
... |
java | public synchronized void addListener(String threadPrefix,
EventListener listener) {
if (threadPrefix.trim().equals("")) {
globalListeners.addElement(listener);
} else {
keyedListeners.put(threadPrefix.trim(), listener);
}
} |
java | public String getBuilding() {
if (RoomNumber_Type.featOkTst && ((RoomNumber_Type)jcasType).casFeat_building == null)
jcasType.jcas.throwFeatMissing("building", "org.apache.uima.examples.RoomNumber");
return jcasType.ll_cas.ll_getStringValue(addr, ((RoomNumber_Type)jcasType).casFeatCode_building);} |
python | def move(self, path_list, dest, **kwargs):
"""
移动文件或文件夹
:param path_list: 在百度盘上要移动的源文件path
:type path_list: list
:param dest: 要移动到的目录
:type dest: str
"""
def __path(path):
if path.endswith('/'):
return path.split('/')[-2]
... |
python | def dskrb2(vrtces, plates, corsys, corpar):
"""
Determine range bounds for a set of triangular plates to
be stored in a type 2 DSK segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskrb2_c.html
:param vrtces: Vertices
:type vrtces: NxM-Element Array of floats
:param plates:... |
python | def update_member_profile(self, brief_details, profile_details):
''' a method to update user profile details on meetup
:param brief_details: dictionary with member brief details with updated values
:param profile_details: dictionary with member profile details with updated values
... |
java | public InvalidationList withItems(InvalidationSummary... items) {
if (this.items == null) {
setItems(new com.amazonaws.internal.SdkInternalList<InvalidationSummary>(items.length));
}
for (InvalidationSummary ele : items) {
this.items.add(ele);
}
return thi... |
python | def dbclass(self, value):
"""Set the connection's dbclass property.
Args:
value: New dbclass value. String.
Returns:
Nothing.
"""
if not is_valid_dbclass(value):
raise AttributeError("'{}' is not a valid database type".format(value))
... |
python | def rule_expand(component, text):
'''expand one rule component'''
global rline_mpstate
if component[0] == '<' and component[-1] == '>':
return component[1:-1].split('|')
if component in rline_mpstate.completion_functions:
return rline_mpstate.completion_functions[component](text)
ret... |
python | def aligned(e1, e2):
"""
alignment is determined by two boxes having one exactly the same
attribute, which could mean parallel, perpendicularly forming a
corner etc.
"""
return (
any(close(c1, c2) for c1, c2 in zip(e1.bbox, e2.bbox))
or x_center_aligned(e1, e2)
or y_cente... |
java | @Nonnull
public static <T, R> LObjIntBoolFunctionBuilder<T, R> objIntBoolFunction(Consumer<LObjIntBoolFunction<T, R>> consumer) {
return new LObjIntBoolFunctionBuilder(consumer);
} |
python | def acp_users_permissions():
"""Change user permissions."""
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = PermissionsForm()
users = []
uids = db.hgetall('users... |
java | private Object convertStringToNearestObjectType(String value) {
switch (value) {
case "true":
return true;
case "false":
return false;
default: {
if (NumberUtils.isParsable(value)) {
return Integer.parseInt(value);
}
return value;
}
}
} |
java | public static List<MediaType> parseMediaTypes(String mediaTypes) {
if (StringUtils.isEmpty(mediaTypes)) {
return Collections.emptyList();
}
String[] tokens = StringUtils.tokenizeToStringArray(mediaTypes, ",");
List<MediaType> result = new ArrayList<>(tokens.length);
f... |
java | public static Result evaluate(String goldFile, String predFile, String dictPath) throws IOException
{
IOUtil.LineIterator goldIter = new IOUtil.LineIterator(goldFile);
IOUtil.LineIterator predIter = new IOUtil.LineIterator(predFile);
CWSEvaluator evaluator = new CWSEvaluator(dictPath);
... |
python | def ensure_parent_directory(path, ensure_parent=True):
"""
Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raise... |
java | @SuppressWarnings("unchecked")
public S instantiate(RawSupport<S> support, byte[] key, byte[] value) throws FetchException {
try {
return (S) mInstanceFactory.instantiate(support, key, value);
} catch (CorruptEncodingException e) {
// Try to instantiate just the key and ... |
java | public static void removeCache(Class<? extends BaseEntity> entityClass,String key){
if(CacheHandler.cacheProvider == null)return;
String entityClassName = entityClass.getSimpleName();
key = entityClassName + CacheHandler.SPLIT_PONIT + key;
String cacheGroupKey = entityClassName + CacheHandler.GROUPKEY_SUF... |
java | public <R> Plan0<R> then(Func9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> selector) {
if (selector == null) {
throw new NullPointerException();
}
return new Plan9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R>(this, selector);
} |
python | def _refresh_resource_index(self, resource):
"""Refresh index for given resource.
:param resource: resource name
"""
if self._resource_config(resource, 'FORCE_REFRESH', True):
self.elastic(resource).indices.refresh(self._resource_index(resource)) |
java | public static <T> void wrapMethod(T object, String methodName,
AfterMethodCall<T> afterMethodCall) {
Function method = (Function) ((JsPropertyMap) object).get(methodName);
WrappingFunction wrappingFunction = args -> {
Object result = method.apply(object, args);
afterMethodCall.execute(object,... |
java | public static List<DayOfTheWeek> getPart(@NotNull final DayOfTheWeek from, @NotNull final DayOfTheWeek to) {
final List<DayOfTheWeek> days = new ArrayList<>();
for (final DayOfTheWeek day : ALL) {
if (day.id >= from.id && day.id <= to.id) {
days.add(day);
}
... |
python | def createManualIndex(self, indexName, indexClass):
"""Creates an index manually managed
@params name: The index name
@params indexClass: vertex or edge
@returns The created Index"""
indexClass = str(indexClass).lower()
if indexClass == "vertex":
index = self... |
python | def get_client(url, username, password, allow_insecure, ca_bundle):
"""Create a new client for the HNV REST API."""
return _HNVClient(url, username, password, allow_insecure, ca_bundle) |
java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
CreativeWrapperServiceInterface creativeWrapperService =
adManagerServices.get(session, CreativeWrapperServiceInterface.class);
// Create a statement to select creative wrappers.
... |
java | public static final void indexAllClasses(final Indexer indexer, final List<File> classFiles) {
classFiles.forEach(file -> {
try {
final InputStream in = new FileInputStream(file);
try {
indexer.index(in);
} finally {
... |
python | def validate_types(self, types=None):
"""Return a valid list of types.
`types` may be a string or a list of strings.
If `types` is not supplied, returns the default_types.
"""
types = types or self.default_types
if types is None:
types = []
if isinst... |
java | public void setTopRightIcon(String iconClass, String title) {
if (m_topRightIcon == null) {
m_topRightIcon = new HTML();
m_contentPanel.add(m_topRightIcon);
}
m_topRightIcon.setStyleName(I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().topRightIcon() + " " + iconClass);
... |
python | def release(self):
""" Get rid of the lock by deleting the lockfile.
When working in a `with` statement, this gets automatically
called at the end.
"""
if self.is_locked:
os.close(self.fd)
os.unlink(self.lockfile)
self.is_locked = False |
python | def _read_opt_ilnp(self, code, *, desc):
"""Read HOPOPT ILNP Nonce option.
Structure of HOPOPT ILNP Nonce option [RFC 6744]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-... |
java | public List<com.ibm.wsspi.security.wim.model.Entity> getEntities() {
if (entities == null) {
entities = new ArrayList<com.ibm.wsspi.security.wim.model.Entity>();
}
return this.entities;
} |
java | @Override
@SuppressLint("NewApi")
public void setTintMode(@NonNull PorterDuff.Mode tintMode) {
mBackgroundDrawable.setTintMode(tintMode);
mSecondaryProgressDrawable.setTintMode(tintMode);
mProgressDrawable.setTintMode(tintMode);
} |
python | def run(self, **run_params):
"""Run the simulation (or lookup the results in the cache)."""
self.use_default_run_params()
self.set_run_params(**run_params)
if self.print_run_params:
print("Run Params:", self.run_params)
self.results = self._backend.backend_run() |
java | public CorporationStarbaseResponse getCorporationsCorporationIdStarbasesStarbaseId(Integer corporationId,
Long starbaseId, Integer systemId, String datasource, String ifNoneMatch, String token) throws ApiException {
ApiResponse<CorporationStarbaseResponse> resp = getCorporationsCorporationIdStarbase... |
java | private ExecutionCallback<Boolean> loadingFinishedCallback() {
return new ExecutionCallback<Boolean>() {
@Override
public void onResponse(Boolean loadingFinished) {
if (loadingFinished) {
updateLocalKeyLoadStatus(null);
}
}
... |
python | def copy_config_input_target_config_target_startup_startup(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
input = ET.SubElement(copy_config, "input")
target = ET.SubElement(inp... |
java | public void setReference(final Reference reference) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, "setReference", reference);
}
// Make sure no-one can pull the rug from beneath us.
synchronized (_properties) {
... |
python | def run(self):
"""
Actual run method that starts the processing of jobs and initiates the status polling, or
performs job cancelling or cleaning, depending on the task parameters.
"""
task = self.task
self._outputs = self.output()
# create the job dashboard inter... |
java | public final void setLength(int l)
{
m_lastChunk = l >>> m_chunkBits;
if (m_lastChunk == 0 && m_innerFSB != null)
{
// Replace this FSB with the appropriate inner FSB, truncated
m_innerFSB.setLength(l, this);
}
else
{
m_firstFree = l & m_chunkMask;
// There's an ed... |
java | public <T> T get(String name, Class<T> type){
Object o = context.get(name);
return o == null? null : (T) o;
} |
java | public final Trace alert(Class<?> c, String message) {
return _trace.alert(c, message);
} |
java | public void populateModule(final DistributionSet distributionSet) {
removeAllItems();
if (distributionSet != null) {
if (isUnassignSoftModAllowed && permissionChecker.hasUpdateRepositoryPermission()) {
try {
isTargetAssigned = false;
} catc... |
java | public void log(CmsDbContext dbc, CmsLogEntry logEntry, boolean force) {
if (dbc == null) {
return;
}
// check log level
if (!logEntry.getType().isActive()) {
// do not log inactive entries
return;
}
// if not forcing
if (!forc... |
java | public Direction direction() {
double range = this.end - this.start;
if (!Op.isFinite(range) || Op.isEq(range, 0.0)) {
return Direction.Zero;
}
if (Op.isGt(range, 0.0)) {
return Direction.Positive;
}
return Direction.Negative;
} |
python | def write_bif(self, filename):
"""
Writes the BIF data into a file
Parameters
----------
filename : Name of the file
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
... |
java | static Object getIndexObject(String s)
{
long indexTest = indexFromString(s);
if (indexTest >= 0) {
return Integer.valueOf((int)indexTest);
}
return s;
} |
java | @Override
public void setSecondAxis(double x, double y, double z, double extent, CoordinateSystem3D system) {
this.axis2.set(x, y, z);
assert(this.axis2.isUnitVector());
if (system.isLeftHanded()) {
this.axis3.set(this.axis1.crossLeftHand(this.axis2));
} else {
this.axis3.set(this.axis3.crossRightHand(th... |
python | def _traverse_command(self, name, *args, **kwargs):
"""Add key AND the hash field to the args, and call the Redis command."""
args = list(args)
args.insert(0, self.name)
return super(InstanceHashField, self)._traverse_command(name, *args, **kwargs) |
python | def search(self, field_name, field_value, record=None, **options):
"""
Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field ... |
python | def _fixedpoint(D, tol=1e-7, maxiter=None):
'''Simple fixed point iteration method for MLE of Dirichlet distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
# Start updating
if maxiter is None:
maxiter = MAXINT
for i in xrange(maxiter):
a1 = _ipsi(psi(a0... |
java | public final void setDialogHeaderIcon(@Nullable final Bitmap icon) {
this.dialogHeaderIcon = new BitmapDrawable(getContext().getResources(), icon);
this.dialogHeaderIconBitmap = icon;
this.dialogHeaderIconId = -1;
} |
java | public static Map<String, String> resource(String type, Map<String, String> meta) {
HashMap<String, String> authResource = new HashMap<String, String>();
if (null != meta) {
authResource.putAll(meta);
}
authResource.put(TYPE_FIELD, type);
return authResource;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.