language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | void resumeReadsInternal(boolean wakeup) {
synchronized (lock) {
boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED);
state |= STATE_READS_RESUMED;
if (!alreadyResumed || wakeup) {
if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) {
... |
java | public static <T> AbstractSetJsonDeserializer<T> newInstance( JsonDeserializer<T> deserializer ) {
return new AbstractSetJsonDeserializer<T>( deserializer );
} |
python | def _preprocess_successor(self, state, add_guard=True): #pylint:disable=unused-argument
"""
Preprocesses the successor state.
:param state: the successor state
"""
# Next, simplify what needs to be simplified
if o.SIMPLIFY_EXIT_STATE in state.options:
state.... |
python | def InputAA(seq_length, name=None, **kwargs):
"""Input placeholder for array returned by `encodeAA`
Wrapper for: `keras.layers.Input((seq_length, 22), name=name, **kwargs)`
"""
return Input((seq_length, len(AMINO_ACIDS)), name=name, **kwargs) |
python | def process_part(self, char):
'''Process chars while in a part'''
if char in self.whitespace or char == self.eol_char:
# End of the part.
self.parts.append( ''.join(self.part) )
self.part = []
# Switch back to processing a delimiter.
self.proce... |
java | @Deprecated
public B sslContext(
SessionProtocol protocol,
File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException {
if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) {
throw new IllegalArgumentException("unsupported protoc... |
java | @Api
public void setUseCache(boolean useCache) {
if (null == cacheManagerService && useCache) {
log.warn("The caching plugin needs to be available to cache WMS requests. Not setting useCache.");
} else {
this.useCache = useCache;
}
} |
python | def make_float(s, default='', ignore_commas=True):
r"""Coerce a string into a float
>>> make_float('12,345')
12345.0
>>> make_float('12.345')
12.345
>>> make_float('1+2')
3.0
>>> make_float('+42.0')
42.0
>>> make_float('\r\n-42?\r\n')
-42.0
>>> make_float('$42.42')
4... |
python | def open_workshared_model(self, model_path, central=False,
detached=False, keep_worksets=True, audit=False,
show_workset_config=1):
"""Append a open workshared model entry to the journal.
This instructs Revit to open a workshared model.
... |
python | async def load(self, mem_addr=0x0000, rec_count=0, retry=0):
"""Read the device database and load."""
if self._version == ALDBVersion.Null:
self._status = ALDBStatus.LOADED
_LOGGER.debug('Device has no ALDB')
else:
self._status = ALDBStatus.LOADING
... |
python | def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4, debug=False):
"""See: pyqrcode.QRCode.png()
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
... |
java | public EncodedElement getData(EncodedElement dataEle) {
//EncodedElement dataEle = new EncodedElement(_totalBits/8+1,_offset);
int startSize = dataEle.getTotalBits();
int unencSampleSize = _frameSampleSize;
//write headers
int encodedType = 1<<3 | _order;
dataEle.addInt(0, 1);
dataEle.addInt... |
java | public Table inner(Table table2, String col2Name) {
return inner(table2, false, col2Name);
} |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.GCLINE__RG:
getRg().clear();
getRg().addAll((Collection<? extends GCLINERG>)newValue);
return;
}
super.eSet(featureID, newValue);
} |
python | def buying_pressure(close_data, low_data):
"""
Buying Pressure.
Formula:
BP = current close - min()
"""
catch_errors.check_for_input_len_diff(close_data, low_data)
bp = [close_data[idx] - np.min([low_data[idx], close_data[idx-1]]) for idx in range(1, len(close_data))]
bp = fill_for_nonc... |
java | public void marshall(TargetInstances targetInstances, ProtocolMarshaller protocolMarshaller) {
if (targetInstances == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(targetInstances.getTagFilters(), T... |
java | private String wordFeature(String word) {
//String feat = (String) wordFeatureCache.get(word);
//if (feat != null) {
// return(feat);
//}
String feat;
if (lowercase.matcher(word).find()) {
feat = "lc";
}
else if (twoDigits.matcher(word).find()) {
feat = "2d";
}
else ... |
python | def summary(self):
"""Summary string of mean and standard deviation.
Returns:
Summary tensor.
"""
with tf.name_scope(self._name + '/summary'):
mean_summary = tf.cond(
self._count > 0, lambda: self._summary('mean', self._mean), str)
std_summary = tf.cond(
self._coun... |
java | public static HashOrderMixingStrategy defaultStrategy() {
if (strategy == null) {
try {
String propValue = java.security.AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(PROPERTY_BIT_MIXER);
... |
java | private void initPlaybackStateBuilder() {
mStateBuilder = new PlaybackStateCompat.Builder();
mStateBuilder.setActions(
PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE
| PlaybackStateCompat.ACTION_PLAY_PAUSE
... |
java | public ResultSet executeQuery(final String sql) throws SQLException {
checkClosed();
// Not an update, so no update count or generated keys
this.updateCount = -1;
this.generatedKeys = EMPTY_GENERATED_KEYS.withStatement(this);
try {
final QueryResult res = this.handl... |
python | def potential(self, x, y, kwargs, k=None):
"""
lensing potential
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters ... |
python | def filedet(name, fobj=None, suffix=None):
"""
Detect file type by filename.
:param name: file name
:param fobj: file object
:param suffix: file suffix like ``py``, ``.py``
:return: file type full name, such as ``python``, ``bash``
"""
name = name or (fobj and fobj.name) or suffix
s... |
java | private RepositoryResource compareNonProductResourceAppliesTo(RepositoryResource res1, RepositoryResource res2) {
// all types other than INSTALLS or TOOLS use appliesTo to determine which is the higher level
String res1AppliesTo = ((ApplicableToProduct) res1).getAppliesTo();
String res2Applies... |
python | def classify(self, token_type, value, lineno, column, line):
"""Find the label for a token."""
if token_type == self.grammar.KEYWORD_TOKEN:
label_index = self.grammar.keyword_ids.get(value, -1)
if label_index != -1:
return label_index
label_index = self.gr... |
java | public Deferred<Boolean> processTSMetaThroughTrees(final TSMeta meta) {
if (config.enable_tree_processing()) {
return TreeBuilder.processAllTrees(this, meta);
}
return Deferred.fromResult(false);
} |
python | def splitread(args):
"""
%prog splitread fastqfile
Split fastqfile into two read fastqfiles, cut in the middle.
"""
p = OptionParser(splitread.__doc__)
p.add_option("-n", dest="n", default=76, type="int",
help="Split at N-th base position [default: %default]")
p.add_option("--rc... |
java | private IQTree liftChildConstructionNode(ConstructionNode newChildRoot, UnaryIQTree newChild, IQProperties liftedProperties) {
UnaryIQTree newOrderByTree = iqFactory.createUnaryIQTree(
applySubstitution(newChildRoot.getSubstitution()),
newChild.getChild(),
lifted... |
python | def main(json_file):
"""
cachemaker.py creates a precache datastore of all available apis of
CloudStack and dumps the precache dictionary in an
importable python module. This way we cheat on the runtime overhead of
completing commands and help docs. This reduces the overall search and
cache_miss... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'credential_id') and self.credential_id is not None:
_dict['credential_id'] = self.credential_id
if hasattr(self, 'status') and self.status is not None:
_dict['... |
java | @Override
public Request<RevokeSecurityGroupEgressRequest> getDryRunRequest() {
Request<RevokeSecurityGroupEgressRequest> request = new RevokeSecurityGroupEgressRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
java | public RpcResponse request(RpcRequest req) {
InputStream is = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
serializer.write(req.marshal(contract), bos);
bos.close();
byte[] data = bos.toByteArray();
is = requestRaw(data... |
python | def _filehash(filepath, blocksize=4096):
""" Return the hash object for the file `filepath', processing the file
by chunk of `blocksize'.
:type filepath: str
:param filepath: Path to file
:type blocksize: int
:param blocksize: Size of the chunk when processing the file
"""
sha = hashl... |
java | @Override
public List<OperableTrigger> acquireNextTriggers(
long noLaterThan, int maxCount, long timeWindow) {
synchronized (lock) {
List<OperableTrigger> result = new ArrayList<OperableTrigger>();
while (true) {
TriggerWrapper tw;
try {
tw = timeWrappedTriggers.firs... |
java | public RuleConditionElement build(final RuleBuildContext context,
final BaseDescr descr,
final Pattern prefixPattern) {
boolean typesafe = context.isTypesafe();
// it must be an EvalDescr
final EvalDescr evalDescr = (Eva... |
java | public static synchronized GVRPeriodicEngine getInstance(GVRContext context) {
if (sInstance == null) {
sInstance = new GVRPeriodicEngine(context);
}
return sInstance;
} |
python | def read(self, uri=None, resources=None, index_only=False):
"""Read sitemap from a URI including handling sitemapindexes.
If index_only is True then individual sitemaps references in a sitemapindex
will not be read. This will result in no resources being returned and is
useful only to r... |
python | def _construct_adb_cmd(self, raw_name, args, shell):
"""Constructs an adb command with arguments for a subprocess call.
Args:
raw_name: string, the raw unsanitized name of the adb command to
format.
args: string or list of strings, arguments to the adb command.
... |
java | public void removeAll()
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "removeAll");
FileBeanFilter theFilter = new FileBeanFilter();
File[] files = new File(passivationDir == null ? "." : passivationD... |
java | @SuppressWarnings("unchecked")
static ObjectProperty<Paint> Text_selectionFillProperty(Text text) {
try {
if (mText_selectionFillProperty == null) {
mText_selectionFillProperty = Text.class.getMethod(
isJava9orLater ? "selectionFillProperty" : "impl_select... |
java | private void createLog(File outputDirectory, boolean onlyFailures) throws Exception
{
if (!Reporter.getOutput().isEmpty())
{
VelocityContext context = createContext();
context.put(ONLY_FAILURES_KEY, onlyFailures);
generateFile(new File(outputDirectory, OUTPUT_FILE... |
java | public static <T extends EntryValue> void sortEntriesById(List<Entry<T>> entryList) {
if (entryList.size() > 0) {
Collections.sort(entryList, new Comparator<Entry<?>>() {
@Override
public int compare(Entry<?> e1, Entry<?> e2) {
long v1 = getEntryId... |
python | def _parse_errback(self, error):
"""
Parse an error from an XML-RPC call.
raises: ``IOError`` when the Twisted XML-RPC connection times out.
raises: ``KojiException`` if we got a response from the XML-RPC
server but it is not one of the ``xmlrpc.Fault``s that
... |
python | def compare(left, right):
"""
generator emiting pairs indicating the contents of the left and
right directories. The pairs are in the form of (difference,
filename) where difference is one of the LEFT, RIGHT, DIFF, or
BOTH constants. This generator recursively walks both trees.
"""
dc = dir... |
python | def resource(self, api_path=None, base_path='/api/now', chunk_size=None, **kwargs):
"""Creates a new :class:`Resource` object after validating paths
:param api_path: Path to the API to operate on
:param base_path: (optional) Base path override
:param chunk_size: Response stream parser c... |
python | def fopen(*args, **kwargs):
'''
Wrapper around open() built-in to set CLOEXEC on the fd.
This flag specifies that the file descriptor should be closed when an exec
function is invoked;
When a file descriptor is allocated (as with open or dup), this bit is
initially cleared on the new file desc... |
java | private static void selectWithCoreApi(CqlSession session) {
// Reading the whole row as a JSON object:
Row row =
session
.execute(
SimpleStatement.newInstance(
"SELECT JSON * FROM examples.querybuilder_json WHERE id = ?", 1))
.one();
assert... |
python | def traverse_inventory(self, item_filter=None):
"""Generates market Item objects for each inventory item.
:param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module.
"""
not self._intentory_raw and self._get_inventory_raw()
for item in self._intentory_raw['rgDe... |
python | def get_api_keys_of_account_group(self, account_id, group_id, **kwargs): # noqa: E501
"""Get API keys of a group. # noqa: E501
An endpoint for listing the API keys of the group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID}... |
java | @Pure
public static URL getJarURL(URL url) {
if (!isJarURL(url)) {
return null;
}
String path = url.getPath();
final int idx = path.lastIndexOf(JAR_URL_FILE_ROOT);
if (idx >= 0) {
path = path.substring(0, idx);
}
try {
return new URL(path);
} catch (MalformedURLException exception) {
return... |
java | private static void waitForChannelClosure(Channel channel, long timoutInMs) {
final long start = System.currentTimeMillis();
final long until = start + timoutInMs;
try {
while (!channel.isClosed() && System.currentTimeMillis() < until) {
Thread.sleep(CLOSURE_WAIT_INTE... |
java | @Override
public NetworkConnectionServiceMessage decode(final byte[] data) {
try (final ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
try (final DataInputStream dais = new DataInputStream(bais)) {
final String connFactoryId = dais.readUTF();
final Identifier srcId = factory.g... |
java | public ReviewReport withReviewActions(ReviewActionDetail... reviewActions) {
if (this.reviewActions == null) {
setReviewActions(new java.util.ArrayList<ReviewActionDetail>(reviewActions.length));
}
for (ReviewActionDetail ele : reviewActions) {
this.reviewActions.add(ele)... |
java | public void setErrors(java.util.Collection<SnapshotErrorMessage> errors) {
if (errors == null) {
this.errors = null;
return;
}
this.errors = new com.amazonaws.internal.SdkInternalList<SnapshotErrorMessage>(errors);
} |
python | def processRequest(cls, ps, **kw):
"""invokes callback that should return a (request,response) tuple.
representing the SOAP request and response respectively.
ps -- ParsedSoap instance representing HTTP Body.
request -- twisted.web.server.Request
"""
resource = kw['resour... |
java | @NonNull
private int[] getEnteredTime(@NonNull Boolean[] enteredZeros) {
int amOrPm = -1;
int startIndex = 1;
if (!mIs24HourMode && isTypedTimeFullyLegal()) {
int keyCode = mTypedTimes.get(mTypedTimes.size() - 1);
if (keyCode == getAmOrPmKeyCode(AM)) {
... |
python | def rename_tokens(docgraph_with_old_names, docgraph_with_new_names, verbose=False):
"""
Renames the tokens of a graph (``docgraph_with_old_names``) in-place,
using the token names of another document graph
(``docgraph_with_new_names``). Also updates the ``.tokens`` list of the old
graph.
This w... |
python | def sparse(self, rows: np.ndarray, cols: np.ndarray) -> scipy.sparse.coo_matrix:
"""
Return the layer as :class:`scipy.sparse.coo_matrix`
"""
return scipy.sparse.coo_matrix(self.values[rows, :][:, cols]) |
java | static ContentCryptoMaterial create(SecretKey cek, byte[] iv,
EncryptionMaterials kekMaterials,
ContentCryptoScheme contentCryptoScheme,
S3CryptoScheme targetScheme,
... |
java | public NodeData getVersionableAncestor() throws RepositoryException
{
checkValid();
NodeData node = nodeData();
NodeTypeDataManager ntman = session.getWorkspace().getNodeTypesHolder();
while (node.getParentIdentifier() != null)
{
if (ntman.isNodeType(Constants.MIX_VERSIONABLE,... |
java | private ConsoleReaderWrapper initConsole() {
ConsoleReaderWrapper consoleReaderWrapper = new ConsoleReaderWrapper();
consoleReaderWrapper.print("");
consoleReaderWrapper.print(question);
consoleReaderWrapper.setCompleters(completers);
if (history.isPresent()) {
consol... |
java | public void reset() {
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
xOff = 0;
for (int i = 0; i != X.length; i++) {
X[i] = 0;
}
} |
python | def listar_por_tipo_ambiente(self, id_tipo_equipamento, id_ambiente):
"""Lista os equipamentos de um tipo e que estão associados a um ambiente.
:param id_tipo_equipamento: Identificador do tipo do equipamento.
:param id_ambiente: Identificador do ambiente.
:return: Dicionário com a seg... |
java | public GridCoverage2D buildRaster() {
if (makeNew) {
GridCoverage2D coverage = buildCoverage("raster", newWR, regionMap, crs);
return coverage;
} else {
throw new RuntimeException("The raster is readonly, so no new raster can be built.");
}
} |
java | protected void bodyEntered (final int bodyOid)
{
log.debug("Body entered", "where", where(), "oid", bodyOid);
// let our delegates know what's up
applyToDelegates(new DelegateOp(PlaceManagerDelegate.class) {
@Override
public void apply (PlaceManagerDelegate delegate)... |
java | public void zeroMeanStdOne(Kernel1D kernel, T input , double maxPixelValue , double delta , T output ) {
// check preconditions and initialize data structures
initialize(input, output);
// avoid overflow issues by ensuring that the max pixel value is 1
T adjusted = ensureMaxValueOfOne(input, maxPixelValue);
... |
python | def filename(self, index):
'''
Get the absolute filename corresponding to a key; run the
key_transformer on the key and do a few other small things.
:raises TypeError: if the key_transformer returns something other than
a :py:class:`tuple` of :py:class:`strings <str>`
... |
python | def report(config, tags, accounts, master, debug, region):
"""report on guard duty enablement by account"""
accounts_config, master_info, executor = guardian_init(
config, debug, master, accounts, tags)
session = get_session(
master_info.get('role'), 'c7n-guardian',
master_info.get(... |
java | protected void addAppConfigToCategory(I_CmsWorkplaceAppConfiguration appConfig) {
CmsAppCategoryNode node = m_nodes.get(appConfig.getAppCategory());
if (node == null) {
LOG.info(
"Missing parent ["
+ appConfig.getAppCategory()
+ "] for... |
python | def save_file(self, path=None, filters='*.dat', force_extension=None, force_overwrite=False, header_only=False, delimiter='use current', binary=None):
"""
This will save all the header info and columns to an ascii file with
the specified path.
Parameters
----------
path=... |
java | @SuppressWarnings({"unused", "WeakerAccess"})
public void pushGooglePlusPerson(final com.google.android.gms.plus.model.people.Person person) {
postAsyncSafely("pushGooglePlusPerson", new Runnable() {
@Override
public void run() {
_pushGooglePlusPerson(person);
... |
python | def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
"""
Returns the VM instance for the given block number.
"""
header = self.ensure_header(at_header)
vm_class = self.get_vm_class_for_block_number(header.block_number)
return vm_class(header=header, chaindb=self.cha... |
python | def run_container(name, image, command=None, environment=None,
ro=None, rw=None, links=None, detach=True, volumes_from=None,
port_bindings=None, log_syslog=False):
"""
Wrapper for docker create_container, start calls
:param log_syslog: bool flag to redirect container's l... |
python | def loadAddressbyPrefix(self, prefix, type, network_id, callback=None, errback=None):
"""
Load an existing address by prefix, type and network into a high level Address object
:param str prefix: CIDR prefix of an existing Address
:param str type: Type of address assignement (planned, as... |
python | def sample_from_proposal(self, A: pd.DataFrame) -> None:
""" Sample a new transition matrix from the proposal distribution,
given a current candidate transition matrix. In practice, this amounts
to the in-place perturbation of an element of the transition matrix
currently being used by t... |
python | def get_license_manager(service_instance):
'''
Returns the license manager.
service_instance
The Service Instance Object from which to obrain the license manager.
'''
log.debug('Retrieving license manager')
try:
lic_manager = service_instance.content.licenseManager
except v... |
java | @Override
@NonNull
public Rect evaluate(float fraction, @NonNull Rect startValue, @NonNull Rect endValue) {
int left = startValue.left + (int) ((endValue.left - startValue.left) * fraction);
int top = startValue.top + (int) ((endValue.top - startValue.top) * fraction);
int right = startV... |
python | def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vo... |
java | public java.util.List<TransitGatewayRoute> getRoutes() {
if (routes == null) {
routes = new com.amazonaws.internal.SdkInternalList<TransitGatewayRoute>();
}
return routes;
} |
java | public final void transliterate(Replaceable text, Position index,
String insertion) {
index.validate(text.length());
// int originalStart = index.contextStart;
if (insertion != null) {
text.replace(index.limit, index.limit, insertion);
... |
java | public void bindEip(String eip, String instanceId, String instanceType) {
this.bindEip(new BindEipRequest().withEip(eip).withInstanceId(instanceId).withInstanceType(instanceType));
} |
python | def validate(self, value):
"""
Validates that the input is in self.choices.
"""
super(ChoicesField, self).validate(value)
if value and not self.valid_value(value):
self._on_invalid_value(value) |
java | private ArtifactNotification collectNotificationsForPrefix(String prefix, Set<String> paths) {
Set<String> gatheredPaths = new HashSet<String>();
if ("/".equals(prefix)) {
gatheredPaths.addAll(paths);
} else {
for (String path : paths) {
if (path.startsWit... |
java | private static String getColumnNameFromGetter(Method getter,Field f){
String columnName = "";
Column columnAnno = getter.getAnnotation(Column.class);
if(columnAnno != null){
//如果是列注解就读取name属性
columnName = columnAnno.name();
}
if(columnName == null || "".equals(columnName)){
//如果没有列注解就用命名方式去猜
co... |
python | def MACRO_DEFINITION(self, cursor):
"""
Parse MACRO_DEFINITION, only present if the TranslationUnit is
used with TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD.
"""
# TODO: optionalize macro parsing. It takes a LOT of time.
# ignore system macro
if (not hasattr(... |
java | protected Element getElement(Object parent, String name) {
if (name == null) {
return null;
}
String id;
if (parent == null) {
id = getRootElement().getId();
} else {
id = groupToId.get(parent);
}
return Dom.getElementById(Dom.assembleId(id, name));
} |
java | public Long insertForGeneratedKey(Connection conn, Entity record) throws SQLException {
checkConn(conn);
if(CollectionUtil.isEmpty(record)){
throw new SQLException("Empty entity provided!");
}
PreparedStatement ps = null;
try {
ps = dialect.psForInsert(conn, record);
ps.executeUpdate();
... |
java | public static Collection<Token> getBootstrapTokens(final TokenMetadata metadata) throws ConfigurationException
{
Collection<String> initialTokens = DatabaseDescriptor.getInitialTokens();
// if user specified tokens, use those
if (initialTokens.size() > 0)
{
logger.debug("... |
python | def _add_string_to_commastring(self, field, string):
# type: (str, str) -> bool
"""Add a string to a comma separated list of strings
Args:
field (str): Field containing comma separated list
string (str): String to add
Returns:
bool: True if string ad... |
python | def sample_stats_to_xarray(self):
"""Extract sample_stats from posterior."""
posterior = self.posterior
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coords is not None else {}
# log_lik... |
java | public String getProperty(String strName)
{
Record recUserRegistration = this.getUserRegistration();
return ((PropertiesField)recUserRegistration.getField(UserRegistrationModel.PROPERTIES)).getProperty(strName);
} |
python | def get_toplevel_parent(self, treeitem):
"""Returns the top level parent for treeitem."""
tv = self.treeview
toplevel_items = tv.get_children()
item = treeitem
while not (item in toplevel_items):
item = tv.parent(item)
return item |
python | def _area_is_empty(self, screen, write_position):
"""
Return True when the area below the write position is still empty.
(For floats that should not hide content underneath.)
"""
wp = write_position
Transparent = Token.Transparent
for y in range(wp.ypos, wp.ypos ... |
java | public final static Object toPrimitiveArray(final Object array) {
if (!array.getClass().isArray()) {
return array;
}
final Class<?> clazz = OBJ_TO_PRIMITIVE.get(array.getClass().getComponentType());
return setArray(clazz, array);
} |
java | public static MatrixFunction asMulFunction(final double arg) {
return new MatrixFunction() {
@Override
public double evaluate(int i, int j, double value) {
return value * arg;
}
};
} |
python | def _get_hashed_path(self, path):
"""Returns an md5 hash for the specified file path."""
return self._get_path('%s.pkl' % hashlib.md5(path.encode("utf-8")).hexdigest()) |
java | public void setLastUsedGallery(String galleryKey, String gallerypath) {
m_lastUsedGalleries.put(galleryKey, gallerypath);
LOG.info("user=" + m_user.getName() + ": setLastUsedGallery " + galleryKey + " -> " + gallerypath);
} |
python | def _get_library(gi, sample_info, config):
"""Retrieve the appropriate data library for the current user.
"""
galaxy_lib = sample_info.get("galaxy_library",
config.get("galaxy_library"))
role = sample_info.get("galaxy_role",
config.get("galaxy_... |
python | def threadpooled(
func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
*,
loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
loop_getter_need_context: bool = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:... |
python | def list_udfs(self, database=None, like=None):
"""
Lists all UDFs associated with given database
Parameters
----------
database : string
like : string for searching (optional)
"""
if not database:
database = self.current_database
state... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.