language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public SDVariable assign(SDVariable x, SDVariable y) {
return assign(null, x, y);
} |
python | def post_sea_resource(url, body):
"""
Get the requested resource using the Seattle account
:returns: http response with content in json
"""
response = None
response = TrumbaSea_DAO().postURL(
url,
{"Content-Type": "application/json"},
body)
_log_json_resp("Seattle", u... |
java | @Override
public final boolean configure(FeatureContext featureContext) {
HashMap<Integer, String> errorMap = Maps.newHashMap();
Map<String, Object> config = featureContext.getConfiguration().getProperties();
String defaultTemplate = null;
String clazz = (String) config.get(GEN_CONF_... |
python | def handle_response(self, msgtype, msgid, response):
"""Handle a response."""
self._proxy.response(msgid, response) |
java | @Override
public FileBasedPersistenceContext createPersistenceContextWithin(PersistenceSpaceIdentifier<?> identifier, String name)
throws CachePersistenceException {
if(getPersistenceSpace(identifier) == null) {
throw newCachePersistenceException(identifier);
}
return new DefaultFileBasedPersi... |
python | def _set_transit_overlay(self, v, load=False):
"""
Setter method for transit_overlay, mapped from YANG variable /overlay_transit/transit_overlay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_transit_overlay is considered as a private
method. Backends looking... |
java | public EEnum getIfcTransitionCode() {
if (ifcTransitionCodeEEnum == null) {
ifcTransitionCodeEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(919);
}
return ifcTransitionCodeEEnum;
} |
python | def _check_filepath(changes):
'''
Ensure all changes are fully qualified and affect only one file.
This ensures that the diff output works and a state change is not
incorrectly reported.
'''
filename = None
for change_ in changes:
try:
cmd, arg = change_.split(' ', 1)
... |
python | def minimal_raw_seqs(self):
''' m.minimal_raw_seqs() -- Return minimal list of seqs that represent consensus '''
seqs = [[], []]
for letter in self.oneletter:
if one2two.has_key(letter):
seqs[0].append(one2two[letter][0])
seqs[1].append(one2two[letter]... |
python | def largest_compartment_id_met(model):
"""
Return the ID of the compartment with the most metabolites.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
Returns
-------
string
Compartment ID of the compartment with the most metabolites.
... |
java | protected Writer openWriter(GenerationContext context) {
Charset charset = Charset.forName(context.getEncoding());
return new BufferedWriter(
new OutputStreamWriter(createFileOutputStream(context.getFile()), charset));
} |
java | public boolean endsWith(byte[] prefix) {
//logger.debug("Inside endsWith()");
if ((prefix.length == 0) || (prefix.length > size())) {
//It could not match :
return false;
}
boolean match = true;
int i = prefix.length - 1;
int j = (this.currentWrite... |
java | @SuppressWarnings("WeakerAccess")
@UiThread
public void setBackstack(@NonNull List<RouterTransaction> newBackstack, @Nullable ControllerChangeHandler changeHandler) {
ThreadUtils.ensureMainThread();
List<RouterTransaction> oldTransactions = getBackstack();
List<RouterTransaction> oldVis... |
python | def get_customer_group_by_id(cls, customer_group_id, **kwargs):
"""Find CustomerGroup
Return single instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_cus... |
java | Map<String, List<GraphQLObjectType>> groupImplementations(GraphQLSchema schema) {
Map<String, List<GraphQLObjectType>> result = new LinkedHashMap<>();
for (GraphQLType type : schema.getAllTypesAsList()) {
if (type instanceof GraphQLObjectType) {
for (GraphQLOutputType interfa... |
python | def exclude(self, pattern):
"""Exclude files that match 'pattern'."""
match = translate_pattern(pattern)
return self._remove_files(match.match) |
python | def terminate(self, force=False):
'''This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. '''
if not ... |
java | public static void addCell(StringBuilder builder, String cell)
{
if(builder.length() != 0)
builder.append(SEPARATOR);
builder.append(toCell(cell));
} |
java | @Deprecated
public void setMonitorNotifier(@Nullable MonitorNotifier notifier) {
if (determineIfCalledFromSeparateScannerProcess()) {
return;
}
monitorNotifiers.clear();
if (null != notifier) {
addMonitorNotifier(notifier);
}
} |
java | protected static double regularizedIncBetaCF(double alpha, double beta, double x) {
final double FPMIN = Double.MIN_VALUE / NUM_PRECISION;
double qab = alpha + beta;
double qap = alpha + 1.0;
double qam = alpha - 1.0;
double c = 1.0;
double d = 1.0 - qab * x / qap;
if(Math.abs(d) < FPMIN) {
... |
python | def run2(job_haz, job_risk, calc_id, concurrent_tasks, pdb, loglevel,
exports, params):
"""
Run both hazard and risk, one after the other
"""
hcalc = base.calculators(readinput.get_oqparam(job_haz), calc_id)
hcalc.run(concurrent_tasks=concurrent_tasks, pdb=pdb,
exports=exports... |
python | def open_uris(self, uris, chname=None, bulk_add=False):
"""Open a set of URIs.
Parameters
----------
uris : list of str
The URIs of the files to load
chname: str, optional (defaults to channel with focus)
The name of the channel in which to load the item... |
java | public boolean getFeature(String name)
throws XPathFactoryConfigurationException {
// feature name cannot be null
if (name == null) {
String fmsg = XSLMessages.createXPATHMessage(
XPATHErrorResources.ER_GETTING_NULL_FEATURE,
new ... |
java | @Override
public Class<? extends ChannelFactory> lookupFactory(String name) {
Class<? extends ChannelFactory> clazz = null;
synchronized (this.factories) {
clazz = this.factories.get(name);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
T... |
python | def _get_history_id(self, connection, agent_id, instance_id):
'''
Checks own cache for history_id for agent_id and instance_id.
If information is missing fetch it from database. If it is not there
create the new record.
BEWARE: This method runs in a thread.
'''
c... |
java | private void initData(byte[] fileData) {
traceData = fileData;
if (isABI()) {
setIndex();
setBasecalls();
setQcalls();
setSeq();
setTraces();
} else throw new IllegalArgumentException("Not a valid ABI file.");
} |
python | def deprecations(self, index=None, params=None):
"""
`<http://www.elastic.co/guide/en/migration/current/migration-api-deprecation.html>`_
:arg index: Index pattern
"""
return self.transport.perform_request(
"GET", _make_path(index, "_migration", "deprecations"), para... |
java | private int getMatchingPoint(String pattern, String itemName) {
int index = pattern.indexOf('*');
if (index == -1) {
return -1;
}
String firstPart = pattern.substring(0, index);
if (!itemName.startsWith(firstPart)) {
return -1;
}
String s... |
java | public static Utensils createDefaultUtensils(JBakeConfiguration config) {
JBakeConfigurationInspector inspector = new JBakeConfigurationInspector(config);
inspector.inspect();
Utensils utensils = new Utensils();
utensils.setConfiguration(config);
ContentStore contentStore = DBU... |
java | final void setFRP(List<SIDestinationAddress> value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setFRP", value);
if (value == null) {
getHdr2().setField(JsHdr2Access.FORWARDROUTINGPATH_DESTINATIONNAME, null);
getHdr2().se... |
java | private String getExtractRequestPath(String dataServiceName, String viewName, Date from, Date until, Boolean idsOnly, String mainValue, Boolean partial, String mainName)
{
String path = extractPath;
if (viewName != null)
{
path += "/" + viewName;
}
else
{
return null;
}
if (dataServic... |
java | public com.google.appengine.v1.Instance getInstances(int index) {
return instances_.get(index);
} |
java | public void put(final String keys, final P value) {
if (keys.contains(OR_STRING)) {
final String[] keysSplit = OR_PATTERN.split(keys);
for (String string : keysSplit) {
simplyPut(string, value);
}
} else {
simplyPut(keys, value);
}
... |
python | def changed(self, selection='all'):
'''
Returns the list of changed values.
The key is added to each item.
selection
Specifies the desired changes.
Supported values are
``all`` - all changed items are included in the output
``inter... |
python | def WriteClientStartupInfo(self, client_id, startup_info):
"""Writes a new client startup record."""
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
ts = rdfvalue.RDFDatetime.Now()
self.metadatas[client_id]["startup_info_timestamp"] = ts
history = self.startup_histo... |
python | def substring_search(word, collection):
"""Find all matches in the `collection` for the specified `word`.
If `word` is empty, returns all items in `collection`.
:type word: str
:param word: The substring to search for.
:type collection: collection, usually a list
:param collection: A collecti... |
java | public void marshall(DescribeElasticsearchInstanceTypeLimitsRequest describeElasticsearchInstanceTypeLimitsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeElasticsearchInstanceTypeLimitsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
... |
java | boolean processOldJdk(String jdkHome, Collection<String> classNames) throws IOException {
String RTJAR = jdkHome + "/jre/lib/rt.jar";
String CSJAR = jdkHome + "/jre/lib/charsets.jar";
bootClassPath.add(0, new File(RTJAR));
bootClassPath.add(1, new File(CSJAR));
options.add("-sou... |
java | @Override
public EEnum getNotifictionResultEnum() {
if (notifictionResultEnumEEnum == null) {
notifictionResultEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(82);
}
return notifictionResultEnumEEnum;
} |
java | private SortedSet<TypeElement> get(Map<TypeElement, SortedSet<TypeElement>> map, TypeElement typeElement) {
return map.computeIfAbsent(typeElement, t -> new TreeSet<>(comparator));
} |
python | def use(self,classtype,key):
"""
HACKED 9/29/16: No longer caching SyllableBodies. Reuse was causing bugs. More thorough solution would be helpful.
"""
if type(key)==type([]):
key=tuple(key)
if (not key in self.dict[classtype]):
if classtype in ['Phoneme','Onset','Nucleus','Coda','Rime','Syllable']:
... |
java | public void setParameters(Parameterization config) {
TrackParameters track = new TrackParameters(config);
configureStep(track);
// update parameter table
{
parameterTable.setEnabled(false);
parameterTable.clear();
for(TrackedParameter pair : track.getAllParameters()) {
parame... |
java | private static CapacityIncrementer loadIncrementer(Extension incrementer, ClassLoaderPlugin classLoaderPlugin)
{
Object result = loadExtension(incrementer, classLoaderPlugin);
if (result != null && result instanceof CapacityIncrementer)
{
return (CapacityIncrementer)result;
}
... |
python | def permute_outputs(Y, X):
"""
Permute the output according to one of the inputs as in [_2]
References
----------
.. [2] Elmar Plischke (2010) "An effective algorithm for computing global
sensitivity indices (EASI) Reliability Engineering & System Safety",
95:4, 354-360.... |
java | @Override
public CommerceShippingFixedOptionRel fetchByCommerceShippingFixedOptionId_Last(
long commerceShippingFixedOptionId,
OrderByComparator<CommerceShippingFixedOptionRel> orderByComparator) {
int count = countByCommerceShippingFixedOptionId(commerceShippingFixedOptionId);
if (count == 0) {
return nul... |
python | def destroyTempFile(self, tempFile):
"""Removes the temporary file in the temp file dir, checking its in the temp file tree.
"""
#Do basic assertions for goodness of the function
assert os.path.isfile(tempFile)
assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir... |
python | def convert(model, feature_names, target):
"""Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : GradientBoostingClassifier
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
Name of the ou... |
python | def cache_call_refresh(self, method, *options):
"""
Call a remote method and update the local cache with the result
if it already existed.
:param str method: The name of the remote procedure to execute.
:return: The return value from the remote function.
"""
options_hash = self.encode(options)
if len(o... |
python | async def cas(self, key, value, *, flags=None, index):
"""Sets the key to the given value with check-and-set semantics.
Parameters:
key (str): Key to set
value (Payload): Value to set, It will be encoded by flags
index (ObjectIndex): Index ID
flags (int):... |
python | def create_interface_connection(interface_a, interface_b):
'''
.. versionadded:: 2019.2.0
Create an interface connection between 2 interfaces
interface_a
Interface id for Side A
interface_b
Interface id for Side B
CLI Example:
.. code-block:: bash
salt myminion n... |
java | public void cloneTo (@Nonnull final PDBusinessEntity ret)
{
ret.m_aNames.setAll (m_aNames);
ret.m_sCountryCode = m_sCountryCode;
ret.m_sGeoInfo = m_sGeoInfo;
ret.m_aIDs.setAll (m_aIDs);
ret.m_aWebsiteURIs.setAll (m_aWebsiteURIs);
ret.m_aContacts.setAllMapped (m_aContacts, PDContact::getClone);... |
java | @SuppressWarnings( "unchecked" )
protected List<TypeMetadata> createTypeMetadata( CompilationUnit unit ) {
List<TypeMetadata> metadata = new ArrayList<TypeMetadata>();
List<AbstractTypeDeclaration> topLevelType = unit.types();
for (AbstractTypeDeclaration abstractTypeDeclaration : topLevelT... |
java | public String get(String columnCode) throws UnknownColumnException {
for (DataColumn column : columns) {
if (columnCode.equals(column.getCode())) {
return content.get(column);
}
}
throw new UnknownColumnException(columnCode);
} |
java | @BetaApi
public final Operation deleteNodesNodeGroup(
ProjectZoneNodeGroupName nodeGroup,
NodeGroupsDeleteNodesRequest nodeGroupsDeleteNodesRequestResource) {
DeleteNodesNodeGroupHttpRequest request =
DeleteNodesNodeGroupHttpRequest.newBuilder()
.setNodeGroup(nodeGroup == null ? n... |
python | def get_file(path,
dest,
saltenv='base',
makedirs=False,
template=None,
gzip=None):
'''
Send a file from the master to the location in specified
.. note::
gzip compression is not supported in the salt-ssh version of
cp.get_fi... |
java | @SuppressWarnings("PMD.UselessParentheses")
public Schema create(Schema parent, String path, String refFragmentPathDelimiters) {
if (!path.equals("#")) {
// if path is an empty string then resolving it below results in jumping up a level. e.g. "/path/to/file.json" becomes "/path/to"
... |
java | private long findShortcuts(ShortcutHandler sch) {
int maxVisitedNodes = getMaxVisitedNodesEstimate();
long degree = 0;
EdgeIterator incomingEdges = inEdgeExplorer.setBaseNode(sch.getNode());
// collect outgoing nodes (goal-nodes) only once
while (incomingEdges.next()) {
... |
java | public void removeLastConstraint()
{
if (constraints.isEmpty()) return;
MappedConst mc = constraints.get(constraints.size() - 1);
constraints.remove(mc);
if (mc.canGenerate() && mc.getInds()[mc.getInds().length - 1] == lastIndex)
{
setLastIndexToMaxFound();
}
} |
python | def get(policy_class=None, return_full_policy_names=True,
hierarchical_return=False, adml_language='en-US',
return_not_configured=False):
'''
Get a policy value
Args:
policy_class (str):
Some policies are both user and computer, by default all policies
will ... |
java | public boolean getBoolean(String key, boolean defaultValue)
{
String tmp = properties.getProperty(key);
if (tmp == null)
{
logger.debug("No value for key \"" + key + "\", using default "
+ defaultValue + ".");
properties.put(key, String.va... |
java | public static boolean isClassAvailable(String s)
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
classLoader.loadClass(s);
return true;
}
catch (ClassNotFoundException e)
{
return false;
... |
java | public void processDocument(BufferedReader document) throws IOException {
if (wordToTransformedVector != null) {
throw new IllegalStateException("Cannot add new documents to a " +
"GenericWordSpace whose vectors have been transformed");
}
Queue<String> prevWords = ne... |
java | public void start() {
FixedSchedulerPool update = new FixedSchedulerPool(poolSize);
if (!pool.compareAndSet(NONE, update)) {
update.shutdown();
}
} |
java | @Column(header = Messages.GUI_MODULES_HEADER_NAME_0, styleName = OpenCmsTheme.HOVER_COLUMN, width = 350, order = 10)
public String getName() {
return m_module.getName();
} |
python | def _get_path(self, filename):
"""Creates the cache directory if it doesn't already exist. Returns the
full path to the specified file inside the cache directory."""
tempdir = settings._temp_directory
if not os.path.exists(tempdir):
os.makedirs(tempdir)
return os.path... |
python | def blasr(args):
"""
%prog blasr ref.fasta fofn
Run blasr on a set of PacBio reads. This is based on a divide-and-conquer
strategy described below.
"""
from jcvi.apps.grid import MakeManager
from jcvi.utils.iter import grouper
p = OptionParser(blasr.__doc__)
p.set_cpus(cpus=8)
... |
java | public SegmentIndexBuffer loadSegmentIndexBuffer(int segId) {
File sibFile = getSegmentIndexBufferFile(segId);
if(sibFile.exists()) {
SegmentIndexBuffer sib = new SegmentIndexBuffer();
try {
_sibManager.getSegmentIndexBufferIO().read(sib, sibFile);
... |
python | def make_qq_plot(kev, obs, mdl, unit, key_text):
"""Make a quantile-quantile plot comparing events and a model.
*kev*
A 1D, sorted array of event energy bins measured in keV.
*obs*
A 1D array giving the number or rate of events in each bin.
*mdl*
A 1D array giving the modeled number o... |
java | @Override
@SuppressWarnings("unchecked")
public T forward() {
T x = modIn.getOutput();
y = (T) x.copyAndConvertAlgebra(s);
return y;
} |
java | public void marshall(Timing timing, ProtocolMarshaller protocolMarshaller) {
if (timing == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(timing.getSubmitTimeMillis(), SUBMITTIMEMILLIS_BINDING);
... |
java | public static Date addMilliseconds(final Date date, final int addMilliseconds)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.MILLISECOND, addMilliseconds);
return dateOnCalendar.getTime();
} |
python | def task_done(self, message):
"""Mark a fetched message as consumed.
Offsets for messages marked as "task_done" will be stored back
to the kafka cluster for this consumer group on commit()
Arguments:
message (KafkaMessage): the message to mark as complete
Returns:
... |
java | protected final <T> T getId(String name, Class<T> clazz) {
Object[] entityIds = getAll(name + ".id");
if (Arrays.isEmpty(entityIds)) entityIds = getAll(name + "Id");
if (Arrays.isEmpty(entityIds)) entityIds = getAll("id");
if (Arrays.isEmpty(entityIds)) return null;
else {
String entityId = en... |
python | def iostat(interval=1, count=5, disks=None):
'''
Gather and return (averaged) IO stats.
.. versionadded:: 2016.3.0
.. versionchanged:: 2016.11.4
Added support for AIX
CLI Example:
.. code-block:: bash
salt '*' disk.iostat 1 5 disks=sda
'''
if salt.utils.platform.is_l... |
java | public static COSFileStatus createFileStatus(Path keyPath,
S3ObjectSummary summary,
long blockSize) {
long size = summary.getSize();
return createFileStatus(keyPath,
objectRepresentsDirectory(summary.getKey(), size),
size, summary.getLastModified(), blockSize);
} |
java | public EJSHome getHomeByInterface(String application,
String module,
String beanInterface)
throws EJBNotFoundException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && t... |
java | public <T extends KubernetesCommand> T command(T command) {
action.setCommand(command);
return command;
} |
python | def vaddg(v1, v2, ndim):
""" Add two n-dimensional vectors
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html
:param v1: First vector to be added.
:type v1: list[ndim]
:param v2: Second vector to be added.
:type v2: list[ndim]
:param ndim: Dimension of v1 and v2.
:t... |
python | def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
"""Add latitude and longitude each netCDF feature
Lookup table is a CSV file with rivid, Lat, Lon, columns.
Columns must be in that order and these must be the first
three columns.
"""
# only add if user adds
... |
java | public static It<Object> findVis(VisualizerContext context, Object start) {
if(start instanceof Result) { // In first hierarchy.
It<Result> it1 = context.getHierarchy().iterDescendantsSelf((Result) start);
return new StackedIter<>(it1, context.getVisHierarchy());
}
return context.getVisHierarchy... |
java | public static base_responses add(nitro_service client, streamidentifier resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
streamidentifier addresources[] = new streamidentifier[resources.length];
for (int i=0;i<resources.length;i++){
addresource... |
python | def remove(self, func):
"""Remove any provisioned log sink if auto created"""
if not self.data['name'].startswith(self.prefix):
return
parent = self.get_parent(self.get_log())
_, sink_path, _ = self.get_sink()
client = self.session.client(
'logging', 'v2',... |
python | def read(self, path, size=MAX_PAYLOAD, offset=0, timeout=0):
"""read data at path"""
if size > MAX_PAYLOAD:
raise ValueError("size cannot exceed %d" % MAX_PAYLOAD)
ret, data = self.sendmess(MSG_READ, str2bytez(path),
size=size, offset=offset, timeo... |
java | public static <T extends Comparable<?>> DateTimeTemplate<T> dateTimeTemplate(Class<? extends T> cl,
String template, Object... args) {
return dateTimeTemplate(cl, createTemplate(template), ImmutableList.copyOf(args));
} |
java | public Criteria near(Point location, @Nullable Distance distance) {
Assert.notNull(location, "Location must not be 'null' for near criteria.");
assertPositiveDistanceValue(distance);
predicates.add(
new Predicate(OperationKey.NEAR, new Object[] { location, distance != null ? distance : new Distance(0) }));
... |
python | def cli(env, identifier):
"""Cancel all virtual guests of the dedicated host immediately.
Use the 'slcli vs cancel' command to cancel an specific guest
"""
dh_mgr = SoftLayer.DedicatedHostManager(env.client)
host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host')
if... |
python | def _add_decision_criteria(self, criteria_dict):
"""
Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
... |
python | def parameters(self):
""" Return the model parameters. """
try:
return self._parameters
except AttributeError:
None
parameters = []
parameters.extend(self.grid_points.dtype.names)
model_configuration = self._configuration.get("model", {})
... |
java | public SuperActivityToast setProgress(int progress) {
if (this.mProgressBar == null) {
Log.e(getClass().getName(), "Could not set SuperActivityToast " +
"progress, are you sure you set the type to TYPE_PROGRESS_CIRCLE " +
"or TYPE_PROGRESS_BAR?");
... |
java | private File extract(InstrumentsVersion version) {
if (version.getBuild() == null) {
throw new WebDriverException("you are running a version of XCode that is too old " + version);
}
extractFromJar("instruments");
extractFromJar("InstrumentsShim.dylib");
extractFromJar("ScriptAgentShim.dylib")... |
python | def convert_types_slow(df):
'''This is a slow operation.'''
dtypes = get_types(df)
for k, v in dtypes.items():
t = df[df['key']==k]
t['value'] = t['value'].astype(v)
df = df.apply(convert_row, axis=1)
return df |
python | def laplace(affinity_matrix, shi_malik_type=False):
""" Converts affinity matrix into normalised graph Laplacian,
for spectral clustering.
(At least) two forms exist:
L = (D^-0.5).A.(D^-0.5) - default
L = (D^-1).A - `Shi-Malik` type, from Shi Malik paper"""
diagonal = affinity_matrix.sum(axis... |
python | def get_object_url(self):
"""
Returns the url where this object can be edited.
"""
if self.kwargs.get(self.slug_url_kwarg, False) == \
unicode(getattr(self.object, self.slug_field, "")) \
and not self.force_add:
url = self.request.buil... |
java | public static Cipher newCipher(final CryptModel<Cipher, String> model)
throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
final KeySpec keySpec = KeySpecFactory.newPBEKeySpec(model.getKey(), mod... |
java | public List<FacesConfigFlowDefinitionInboundParameterType<FacesConfigFlowDefinitionType<T>>> getAllInboundParameter()
{
List<FacesConfigFlowDefinitionInboundParameterType<FacesConfigFlowDefinitionType<T>>> list = new ArrayList<FacesConfigFlowDefinitionInboundParameterType<FacesConfigFlowDefinitionType<T>>>();
... |
java | public ComplianceItem withDetails(java.util.Map<String, String> details) {
setDetails(details);
return this;
} |
java | <R extends Request<T>> R setRequestQueue(RequestQueue requestQueue) {
checkIfActive();
java.lang.reflect.Method m = null;
if (!(this.getClass().equals(Request.class))) {
try {
m = this.getClass().getDeclaredMethod("parseNetworkResponse", NetworkResponse
... |
python | def getlist(self, key: 'Entity') -> Sequence[object]:
r"""Return all values associated to the given ``key`` property
in sequence.
:param key: The property entity.
:type key: :class:`Entity`
:return: A sequence of all values associated to the given ``key``
proper... |
java | public static <K, V> Map<V, K> invert(Map<K, V> pSource, Map<V, K> pResult, DuplicateHandler<K> pHandler) {
if (pSource == null) {
throw new IllegalArgumentException("source == null");
}
Map<V, K> result = pResult;
if (result == null) {
try {
... |
python | def getSensoryAssociatedLocationRepresentation(self):
"""
Get the location cells in the location layer that were driven by the input
layer (or, during learning, were associated with this input.)
"""
cells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.