language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private URI createFileSystemURI(URI configKey) throws URISyntaxException, IOException {
// Validate the scheme
String configKeyScheme = configKey.getScheme();
if (!configKeyScheme.startsWith(getSchemePrefix())) {
throw new IllegalArgumentException(
String.format("Scheme for configKey \"%s\" ... |
python | def abort(http_status_code, **kwargs):
"""Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
"""
#noinspection PyUnresolvedReferences
try:
original_flask_abort(http_status_code)
except HTTPException as e:
if l... |
python | def sendWakeOnLan(self, macAddress, lanInterfaceId=1, timeout=1):
"""Send a wake up package to a device specified by its MAC address.
:param str macAddress: MAC address in the form ``38:C9:86:26:7E:38``; be aware that the MAC address might
be case sensitive, depending on the router
... |
java | public char getChar(String name, char defaultValue) {
String value = getString(name, null);
if (!StringUtils.isNullOrEmpty(value)) {
return value.trim().charAt(0);
}
return defaultValue;
} |
python | def _clear_done_waiters(self):
"""Remove waiters that are done (should only happen if they are cancelled)"""
while self._waiters and self._waiters[0].done():
self._waiters.popleft()
if not self._waiters:
self._stop_listening() |
java | @Override
public int read() throws IOException {
synchronized (lock) {
if (!isOpen()) {
throw new IOException("InputStreamReader is closed.");
}
char buf[] = new char[1];
return read(buf, 0, 1) != -1 ? buf[0] : -1;
}
} |
python | def save(self, filename):
"""
Save validator object to pickle.
"""
with open(filename, 'wb') as output:
pickle.dump(self, output, protocol=pickle.HIGHEST_PROTOCOL) |
python | def assign_version_default_trigger(plpy, td):
"""Trigger to fill in legacy data fields.
A compatibilty trigger to fill in legacy data fields that are not
populated when inserting publications from cnx-publishing.
If this is not a legacy publication the ``version`` will be set
based on the ``major_... |
java | public void setLinearVelocity(float x, float y, float z) {
Native3DRigidBody.setLinearVelocity(getNative(), x, y, z);
} |
java | public ConnectionPoolConfigurationBuilder withPoolProperties(Properties properties) {
TypedProperties typed = TypedProperties.toTypedProperties(properties);
exhaustedAction(typed.getEnumProperty(ConfigurationProperties.CONNECTION_POOL_EXHAUSTED_ACTION, ExhaustedAction.class,
ExhaustedAction.values(... |
java | static String equalsParameterType(Map<ObjectMethod, ExecutableElement> methodsToGenerate) {
ExecutableElement equals = methodsToGenerate.get(ObjectMethod.EQUALS);
if (equals == null) {
return ""; // this will not be referenced because no equals method will be generated
}
TypeMirror parameterType =... |
java | protected void initializeLocalTypes(GenerationContext context, JvmFeature feature, XExpression expression) {
if (expression != null) {
int localTypeIndex = context.getLocalTypeIndex();
final TreeIterator<EObject> iterator = EcoreUtil2.getAllNonDerivedContents(expression, true);
final String nameStub = "__" +... |
python | def flush_buffer(self):
''' Flush the buffer of the tail '''
if len(self.buffer) > 0:
return_value = ''.join(self.buffer)
self.buffer.clear()
self.send_message(return_value)
self.last_flush_date = datetime.datetime.now() |
python | def generate(self, api):
"""Generates a module for each namespace."""
for namespace in api.namespaces.values():
# One module per namespace is created. The module takes the name
# of the namespace.
with self.output_to_relative_path('{}.py'.format(namespace.name)):
... |
java | public Map<String, Map<String, CmsJspResourceWrapper>> getLocaleResource() {
return CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
@SuppressWarnings("synthetic-access")
public Object transform(Object arg) {
if (!(arg instanceof String)) {
... |
python | def heappushpop(heap, item):
"""Fast version of a heappush followed by a heappop."""
if heap and heap[0] < item:
item, heap[0] = heap[0], item
_siftup(heap, 0)
return item |
java | public void setProgress(float progress) {
if (isSpinning) {
mProgress = 0.0f;
isSpinning = false;
runCallback();
}
if (progress > 1.0f) {
progress -= 1.0f;
} else if (progress < 0) {
progress = 0;
}
if (progress == mTargetProgress) {
return;
}
// I... |
python | def event_date(self, event_date):
"""
Updates the event_date.
Args:
event_date: Converted to %Y-%m-%dT%H:%M:%SZ date format.
Returns:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
event_date = self._utils.forma... |
python | def _get_instance_params(cls, instance):
"""
Parse instance configuration and perform minimal verification
"""
url = instance.get("url")
if url is None:
raise ConfigurationError("You must specify a url for your instance in `conf.yaml`")
username = instance.get... |
java | boolean hasOption(String opt) {
Boolean has = options.get(opt);
if (has == null) {
throw new InternalError("hasOption called before allowedOptions or on bad option");
}
return has;
} |
java | public void registerComponentBindingsProvider(ServiceReference reference) {
log.info("registerComponentBindingsProvider");
log.info("Registering Component Bindings Provider {} - {}",
new Object[] { reference.getProperty(Constants.SERVICE_ID),
reference.getProperty(Constants.SERVICE_PID) });
String[] res... |
java | public Object repushContextClassLoaderForUnprivileged(Object origLoader, ClassLoader loader) {
if (origLoader == UNCHANGED) {
return pushContextClassLoaderForUnprivileged(loader);
}
setContextClassLoaderForUnprivileged(Thread.currentThread(), loader);
return origLoader;
... |
java | public VoltXMLElement findChild(String elementName, String attributeName)
{
String attName = attributeName;
if (attName == null) {
attName = "default";
}
return findChild(elementName + attName);
} |
java | public static void projViewFromRectangle(
Vector3d eye, Vector3d p, Vector3d x, Vector3d y, double nearFarDist, boolean zeroToOne,
Matrix4d projDest, Matrix4d viewDest) {
double zx = y.y * x.z - y.z * x.y, zy = y.z * x.x - y.x * x.z, zz = y.x * x.y - y.y * x.x;
double zd = zx * (... |
java | public void setProperty(String columnName, Object newValue) {
try {
getResultSet().updateObject(columnName, newValue);
updated = true;
}
catch (SQLException e) {
throw new MissingPropertyException(columnName, GroovyResultSetProxy.class, e);
}
} |
java | public final void setEntries(@NonNull final CharSequence[] entries) {
Condition.INSTANCE.ensureNotNull(entries, "The entries may not be null");
this.entries = entries;
} |
java | public void format(long number, StringBuilder toInsertInto, int pos, int recursionCount) {
if (recursionCount >= RECURSION_LIMIT) {
throw new IllegalStateException("Recursion limit exceeded when applying ruleSet " + name);
}
NFRule applicableRule = findNormalRule(number);
app... |
java | public static double[] rotate90Equals(final double[] v1) {
assert v1.length == 2 : "rotate90Equals is only valid for 2d vectors.";
final double temp = v1[0];
v1[0] = v1[1];
v1[1] = -temp;
return v1;
} |
python | def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... |
python | def _patch_for_tf1_13(tf):
"""Monkey patch tf 1.13 so tfds can use it."""
if not hasattr(tf.io.gfile, "GFile"):
tf.io.gfile.GFile = tf.gfile.GFile
if not hasattr(tf, "nest"):
tf.nest = tf.contrib.framework.nest
if not hasattr(tf.compat, "v2"):
tf.compat.v2 = types.ModuleType("tf.compat.v2")
tf.c... |
python | def end_time(self):
""" Return the end time of the current valid segment of data """
return float(self.strain.start_time + (len(self.strain) - self.total_corruption) / self.sample_rate) |
python | def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... |
java | public void setConnectTimeout(int timeout) {
Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
this.httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
} |
python | def build_url (self):
"""
Calls super.build_url() and adds a trailing slash to directories.
"""
self.build_base_url()
if self.parent_url is not None:
# URL joining with the parent URL only works if the query
# of the base URL are removed first.
... |
python | def save_voxel_grid(voxel_grid, file_name):
""" Saves binary voxel grid as a binary file.
The binary file is structured in little-endian unsigned int format.
:param voxel_grid: binary voxel grid
:type voxel_grid: list, tuple
:param file_name: file name to save
:type file_name: str
"""
... |
java | @NotNull
public Mode with(@NotNull Key<Boolean> key) {
return new Mode(Map(this.defs, key, true));
} |
java | public DescribeDirectConnectGatewaysResult withDirectConnectGateways(DirectConnectGateway... directConnectGateways) {
if (this.directConnectGateways == null) {
setDirectConnectGateways(new com.amazonaws.internal.SdkInternalList<DirectConnectGateway>(directConnectGateways.length));
}
... |
python | def send_report(self, report_parts):
"""
Publish by sending the report by e-mail
"""
logger.info('Creating an email message')
report_parts = sorted(
filter(lambda x: x.fmt in self.formats, report_parts),
key=lambda x: self.formats.index(x.fmt)
)
... |
python | def userinfo(access_token, scope_request=None, claims_request=None):
"""
Returns data required for an OpenID Connect UserInfo response, according to:
http://openid.net/specs/openid-connect-basic-1_0.html#UserInfoResponse
Supports scope and claims request parameter as described in:
- http://openid... |
java | public int calculateNodePathDistance(String nodePath1, String nodePath2) {
String[] nodePathFragment1 = nodePath1.split("\\.");
String[] nodePathFragment2 = nodePath2.split("\\.");
int overlapBlock = 0;
while (overlapBlock < nodePathFragment1.length
&& overlapBlock < nodePathFragment2.length
... |
java | public void processEvent(EventObject event) {
if (event instanceof RequestEvent) {
processRequest((RequestEvent) event);
} else if (event instanceof ResponseEvent) {
processResponse((ResponseEvent) event);
} else if (event instanceof TimeoutEvent) {
processTimeout((TimeoutEvent) event);
... |
java | protected void addIndex(Content body) {
addIndexContents(packages, "doclet.Package_Summary",
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Package_Summary"),
configuration.getText("doclet.packages")), body);
} |
python | def AuxPlane(s1, d1, r1):
"""
Get Strike and dip of second plane.
Adapted from MATLAB script
`bb.m <http://www.ceri.memphis.edu/people/olboyd/Software/Software.html>`_
written by Andy Michael and Oliver Boyd.
"""
r2d = 180 / np.pi
z = (s1 + 90) / r2d
z2 = d1 / r2d
z3 = r1 / r2d... |
python | def parse_zone(zonefile=None, zone=None):
'''
Parses a zone file. Can be passed raw zone data on the API level.
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.parse_zone /var/lib/named/example.com.zone
'''
if zonefile:
try:
with salt.utils.files.fopen(zonefile,... |
python | def __initialize_menu_bar(self):
"""
Initializes Component menu_bar.
"""
self.__file_menu = QMenu("&File", parent=self.__menu_bar)
self.__file_menu.addAction(self.__engine.actions_manager.register_action(
"Actions|Umbra|Components|factory.script_editor|&File|&New",
... |
python | def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragmen... |
java | public static boolean startAny(String target, Integer toffset, List<String> startWith) {
if (isNull(target)) {
return false;
}
return matcher(target).starts(toffset, startWith);
} |
java | private void removeNodeFromList(RepairQueueNode el) {
// the head case
//
if (null == el.prev) {
if (null != el.next) {
this.head = el.next;
this.head.prev = null;
el=null;
}
else {
// can't happen? yep. if there is only one element exists...
this.he... |
python | def convert_coco_stuff_mat(data_dir, out_dir):
"""Convert to png and save json with path. This currently only contains
the segmentation labels for objects+stuff in cocostuff - if we need to
combine with other labels from original COCO that will be a TODO."""
sets = ['train', 'val']
categories = []
... |
java | public void onModuleLoad() {
ToolbarRegistry.put(RasterizingToolId.GET_LEGEND_IMAGE, new ToolCreator() {
public ToolbarBaseAction createTool(MapWidget mapWidget) {
return new GetLegendImageAction(mapWidget);
}
});
ToolbarRegistry.put(RasterizingToolId.GET_MAP_IMAGE, new ToolCreator() {
public Toolb... |
python | def send_file(self, local_path, remote_path, unix_mode=None):
"""Send a file to the remote host.
:param local_path: the local path of the file
:type local_path: str
:param remote_path: the remote path of the file
:type remote_path: str
:return: the file attributes
... |
java | public void propertiesReloaded(PropertiesReloadedEvent event) {
Properties oldProperties = lastMergedProperties;
try {
//
Properties newProperties = mergeProperties();
//
// 获取哪些 dynamic property 被影响
//
Set<String> placeholders =... |
java | private void assignAsymIds(List<List<Chain>> polys, List<List<Chain>> nonPolys, List<List<Chain>> waters) {
for (int i=0; i<polys.size(); i++) {
String asymId = "A";
for (Chain poly:polys.get(i)) {
poly.setId(asymId);
asymId = getNextAsymId(asymId);
}
for (Chain nonPoly:nonPolys.get(i)) {
no... |
java | @Override
public MessageResourcesGateway getMessageResourceGateway() {
final MessageResourcesGateway gateway = messageResourcesHolder.getGateway();
if (gateway == null) {
String msg = "Not found the gateway for message resource: holder=" + messageResourcesHolder;
throw new Il... |
python | def get_families(data_dir=None):
'''Return a list of all basis set families'''
data_dir = fix_data_dir(data_dir)
metadata = get_metadata(data_dir)
families = set()
for v in metadata.values():
families.add(v['family'])
return sorted(list(families)) |
java | public static Map.Entry<Object, Object> bayes(DataTable2D payoffMatrix, AssociativeArray eventProbabilities) {
if(payoffMatrix.isValid()==false) {
throw new IllegalArgumentException("The payoff matrix does not have a rectangular format.");
}
AssociativeArray expectedPayoffs ... |
java | public boolean shouldShowInContext(CmsContainerElementData elementData) {
CmsTemplateContextInfo contextInfo = getData().getTemplateContextInfo();
if (contextInfo.getCurrentContext() == null) {
return true;
}
CmsDefaultSet<String> allowedContexts = contextInfo.getAllowedCont... |
java | private void clearPrefOnBranchKeyChange() {
// If stored key isn't the same as the current key, we need to clean up
// Note: Link Click Identifier is not cleared because of the potential for that to mess up a deep link
String linkClickID = getLinkClickID();
String linkClickIdentifier = g... |
python | def get_logger(name='', log_stream=None, log_file=None,
quiet=False, verbose=False):
"""Convenience function for getting a logger."""
# configure root logger
log_level = logging.INFO
if quiet:
log_level = logging.WARNING
elif verbose:
log_level = logging.DEBUG
if... |
python | def add_overlay_to_slice_file(
self,
filename,
overlay,
i_overlay,
filename_out=None
):
""" Function adds overlay to existing file.
"""
if filename_out is None:
filename_out = filename
filename = op.expanduser(filename)
data... |
java | public static Set<Bugsnag> uncaughtExceptionClients() {
UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
if (handler instanceof ExceptionHandler) {
ExceptionHandler bugsnagHandler = (ExceptionHandler) handler;
return Collections.unmodifiableSet(bugs... |
python | def policy_create(request, **kwargs):
"""Create a QoS Policy.
:param request: request context
:param name: name of the policy
:param description: description of policy
:param shared: boolean (true or false)
:return: QoSPolicy object
"""
body = {'policy': kwargs}
policy = neutronclie... |
python | def closure(self):
"""
Returns a new `Independencies()`-object that additionally contains those `IndependenceAssertions`
that are implied by the the current independencies (using with the `semi-graphoid axioms
<https://en.wikipedia.org/w/index.php?title=Conditional_independence&oldid=708... |
python | def eth_sendTransaction(self, from_, to=None, gas=None,
gas_price=None, value=None, data=None,
nonce=None):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction
:param from_: From account address
:type from_: str
... |
java | private String getScalaClassName(PsiClass c) {
String baseName = c.getName();
return baseName.replaceAll("\\$", "");
} |
java | final void install() {
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = AndPermission.getFileUri(mSource.getContext(), mFile);
intent.setDataAndType(uri, "a... |
python | def _parse_non_negative_int(self, istr, name):
"""Parse integer from string (istr).
The (name) parameter is used just for IIIFRequestError message
generation to indicate what the error is in.
"""
if (istr == ''):
return(None)
try:
i = int(istr)
... |
python | def delete(ctx, slot, force):
"""
Deletes the configuration of a slot.
"""
controller = ctx.obj['controller']
if not force and not controller.slot_status[slot - 1]:
ctx.fail('Not possible to delete an empty slot.')
force or click.confirm(
'Do you really want to delete'
' ... |
python | def get_dataframe_row(self, dataset_cases, predicted_data, pdb_data, record_id, additional_prediction_data_columns):
'''Create a dataframe row for a prediction.'''
# Ignore derived mutations if appropriate
record = dataset_cases[record_id]
if self.is_this_record_a_derived_mutation(recor... |
python | def split(string, separator_regexp=None, maxsplit=0):
"""Split a string to a list
>>> split('fred, was, here')
['fred', ' was', ' here']
"""
if not string:
return []
if separator_regexp is None:
separator_regexp = _default_separator()
if not separator_regexp:
return ... |
python | def update(self, instance, validated_data):
""" change password """
instance.user.set_password(validated_data["password1"])
instance.user.full_clean()
instance.user.save()
# mark password reset object as reset
instance.reset = True
instance.full_clean()
in... |
python | def abs_timedelta(delta):
"""Returns an "absolute" value for a timedelta, always representing a
time distance."""
if delta.days < 0:
now = _now()
return now - (now + delta)
return delta |
java | private static void enlargeTables(float[][] data, int[][] rowIndex, int cols, int currentRow, int currentCol) {
while (data[currentRow].length < currentCol + cols) {
if(data[currentRow].length == SPARSE_MATRIX_DIM) {
currentCol = 0;
cols -= (data[currentRow].length - ... |
java | public static void mkdir(File dir) throws IOException{
if(!dir.exists() && !dir.mkdir())
throw new IOException("couldn't create directory: "+dir);
} |
python | def remove_tag(self, task, params={}, **options):
"""Removes a tag from the task. Returns an empty data block.
Parameters
----------
task : {Id} The task to remove a tag from.
[data] : {Object} Data for the request
- tag : {Id} The tag to remove from the task.
... |
python | def diff(compiled_requirements, installed_dists):
"""
Calculate which packages should be installed or uninstalled, given a set
of compiled requirements and a list of currently installed modules.
"""
requirements_lut = {r.link or key_from_req(r.req): r for r in compiled_requirements}
satisfied =... |
java | public InputStreamReader getDecompressionStream(String path, String encoding)
throws IOException
{
File fileToUncompress = new File(path);
BufferedInputStream fileStream = new BufferedInputStream(new FileInputStream(fileToUncompress));
// read bzip2 prefix: BZ
fileStream.read();
fileStream.read();
Buf... |
java | @Override
public JmsQueue createQueue(String name) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "createQueue", name);
JmsQueue queue = null;
// if name string is null, empty or just "queue://", throw exception
... |
java | public static void main(String[] args) throws Exception {
if (args.length < 2) {
logger.info("using BatchReplaceMain dir patternfile encoding");
return;
}
String dir = args[0];
if (!new File(dir).exists()) {
logger.error("{} not a valid file or directory", dir);
return;
}
... |
java | public AssessmentRunInProgressException withAssessmentRunArns(String... assessmentRunArns) {
if (this.assessmentRunArns == null) {
setAssessmentRunArns(new java.util.ArrayList<String>(assessmentRunArns.length));
}
for (String ele : assessmentRunArns) {
this.assessmentRunA... |
java | public final void init(Key key) throws InvalidKeyException {
try {
if (spi != null && (key == null || lock == null)) {
spi.engineInit(key, null);
} else {
chooseProvider(key, null);
}
} catch (InvalidAlgorithmParameterException e) {
... |
java | public static CommerceOrderNote fetchByC_ERC(long companyId,
String externalReferenceCode, boolean retrieveFromCache) {
return getPersistence()
.fetchByC_ERC(companyId, externalReferenceCode,
retrieveFromCache);
} |
java | public Object getFieldData(int iSFieldSeq)
{
ScreenField sField = null;
if (iSFieldSeq != -1)
sField = m_gridScreen.getSField(this.getRelativeSField(iSFieldSeq));
if (sField != null)
return sField.getConverter().getData();
return null;
} |
java | public final void key_sentence() throws RecognitionException {
CommonTree vtl=null;
try {
// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:88:5: ( variable_definition |vtl= VT_LITERAL | VT_SPACE )
int alt10=3;
switch ( input.LA(1) ) {
case VT_VAR_DEF:
{
alt10=1;
}
break... |
python | def get_json_val(source, path, *, ignore_bad_path=False):
"""Get the nested value identified by the json path, rooted at source."""
try:
return JP.find(source, path)
except JP.JSONPathError as ex:
if ignore_bad_path:
return None
else:
raise |
java | protected void eventPostCommitRemove(SIMPMessage msg, TransactionCommon transaction)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "eventPostCommitRemove", new Object[] { msg, transaction });
// NB: ideally this would go in afterCompletion but we
... |
python | def pkg_config(pkg_libraries):
"""Use pkg-config to query for the location of libraries, library directories,
and header directories
Arguments:
pkg_libries(list): A list of packages as strings
Returns:
libraries(list), library_dirs(list), include_dirs(list)
"""
l... |
java | @Override
public void write(byte[] b, int off, int len) throws PacketException {
baq.add(b, off, len);
while (packetSize > 0 || (packetSize = parser.getSize(baq.array(),
baq.offset(), baq.length())) > 0) {
if (baq.length() < packetSize) {
return;
}
consumer.accept(baq.array(), baq.offset()... |
python | def _add(self, lines):
'''Add can also handle https, and compressed files.
Parameters
==========
line: the line from the recipe file to parse for ADD
'''
lines = self._setup('ADD', lines)
for line in lines:
values = line.split(" ")
... |
python | def VerifyScripts(verifiable):
"""
Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise.
"""
try:
hashes = verifia... |
java | @Override
public int compareTo(ValueArray<CharValue> o) {
CharValueArray other = (CharValueArray) o;
int min = Math.min(position, other.position);
for (int i = 0; i < min; i++) {
int cmp = Character.compare(data[i], other.data[i]);
if (cmp != 0) {
return cmp;
}
}
return Integer.compare(positi... |
java | public OperationFuture<List<Server>> removeAutoscalePolicyOnServer(List<Server> serverList) {
List<JobFuture> jobs = serverList
.stream()
.map(server -> removeAutoscalePolicyOnServer(server).jobFuture())
.collect(toList());
return
new OperationFuture<>(
... |
java | public static void validateClusterNodeCounts(final Cluster lhs, final Cluster rhs) {
if(!lhs.getNodeIds().equals(rhs.getNodeIds())) {
throw new VoldemortException("Node ids are not the same [ lhs cluster node ids ("
+ lhs.getNodeIds()
... |
python | def from_json(cls, data):
"""Create a Data Collection from a dictionary.
Args:
{
"header": A Ladybug Header,
"values": An array of values,
"datetimes": An array of datetimes,
"validated_a_period": Boolean for whether header ana... |
java | protected Catalog getCatalog(String url, String user, String password, String infoLevelName, String bundledDriverName, Properties properties)
throws IOException {
// Determine info level
InfoLevel level = InfoLevel.valueOf(infoLevelName.toLowerCase());
SchemaInfoLevel schemaInfoLevel... |
java | @javax.annotation.Nonnull
public java.util.Optional<net.morimekta.util.Binary> optionalData() {
return java.util.Optional.ofNullable(mData);
} |
python | def set_config(**kwargs):
"""Set up the configure of profiler (only accepts keyword arguments).
Parameters
----------
filename : string,
output file for profile data
profile_all : boolean,
all profile types enabled
profile_symbolic : boolean,
whether to profile symbolic ... |
python | def ind_lm(index, lmax):
"""Convert single index to corresponding (ell, m) pair"""
import numpy as np
lm = np.empty(2, dtype=np.float64)
_ind_lm(index, lmax, lm)
return lm |
java | public static <D> Predicate eqConst(Expression<D> left, D constant) {
return eq(left, ConstantImpl.create(constant));
} |
java | void compute_Rv() {
double t = Math.sqrt(v1*v1 + v2*v2);
double s = Math.sqrt(t*t + 1);
double cosT = 1.0/s;
double sinT = Math.sqrt(1-1.0/(s*s));
K_x.data[0] = 0; K_x.data[1] = 0; K_x.data[2] = v1;
K_x.data[3] = 0; K_x.data[4] = 0; K_x.data[5] = v2;
K_x.data[6] = -v1; K_x.data[7] = -v2; K_x.data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.