language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def three_partition(x): """partition a set of integers in 3 parts of same total value :param x: table of non negative values :returns: triplet of the integers encoding the sets, or None otherwise :complexity: :math:`O(2^{2n})` """ f = [0] * (1 << len(x)) for i in range(len(x)): for ...
java
static public LoginOutput openSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { AssertUtil.assertTrue(loginInput.getServerUrl() != null, "missing server URL for opening session"); AssertUtil.assertTrue(loginInput.getAppId() != null, ...
python
def first(self, timeout=None): """ Wait for the first successful result to become available :param timeout: Wait timeout, sec :type timeout: float|int|None :return: result, or None if all threads have failed :rtype: * """ while True: with self._jobfini...
java
private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException { if (scope_ifname_set) { ifname = scope_ifname.getName(); } s.defaultWriteObject(); }
java
@FFDCIgnore(NamingException.class) public void releaseDirContext(TimedDirContext ctx) throws WIMSystemException { final String METHODNAME = "releaseDirContext"; if (iContextPoolEnabled) { //Get the lock for the current domain synchronized (iLock) { // If the ...
python
def _format_to_floating_precision(self, precision): """ Format a nonzero finite BigFloat instance to a given number of significant digits. Returns a triple (negative, digits, exp) where: - negative is a boolean, True for a negative number, else False - digits is a string gi...
python
def shutdown(self, vm_names=None, reboot=False): """ Shutdown this prefix Args: vm_names(list of str): List of the vms to shutdown reboot(bool): If true, reboot the requested vms Returns: None """ self.virt_env.shutdown(vm_names, rebo...
java
public static int calculateEncodedLength(BigInteger value) { if (value == null) { return 1; } int bytesLength = (value.bitLength() >> 3) + 1; return bytesLength < 0x7f ? (1 + bytesLength) : (5 + bytesLength); }
java
public Connection<?> completeConnection(OAuth1ConnectionFactory<?> connectionFactory, NativeWebRequest request) { String verifier = request.getParameter("oauth_verifier"); AuthorizedRequestToken requestToken = new AuthorizedRequestToken(extractCachedRequestToken(request), verifier); OAuthToken accessToken = conn...
java
@Override public void processWorkUnit( final DocWorkUnit workUnit, final List<Map<String, String>> featureMaps, final List<Map<String, String>> groupMaps) { CommandLineArgumentParser clp = null; List<? extends CommandLinePluginDescriptor<?>> pluginDescriptors = n...
java
void threadFactoryDestroyed(String threadFactoryName, ThreadGroup parentGroup) { Collection<ThreadGroup> groupsToDestroy = new LinkedList<ThreadGroup>(); for (ConcurrentHashMap<String, ThreadGroup> threadFactoryToThreadGroup : metadataIdentifierToThreadGroups.values()) { ThreadGroup group = ...
python
def read_config_file(self, config_data=None, quiet=False): """read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== ...
java
public static boolean canCreatePalette(RenderedImage image) { if (image == null) { throw new IllegalArgumentException("image == null"); } ImageTypeSpecifier type = new ImageTypeSpecifier(image); return canCreatePalette(type); }
java
public void createLabelFeatures(Collector fv, DependencyInstance inst, int[] heads, int[] types, int mod, int order) { int head = heads[mod]; int type = types[mod]; if (order != 2) createLabeledArcFeatures(fv, inst, head, mod, type); int g...
java
protected ConditionalEventDefinition parseConditionalEventDefinition(Element element, ActivityImpl conditionalActivity) { ConditionalEventDefinition conditionalEventDefinition = null; Element conditionExprElement = element.element(CONDITION); if (conditionExprElement != null) { Condition condition = ...
java
public void marshall(ListJobsRequest listJobsRequest, ProtocolMarshaller protocolMarshaller) { if (listJobsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listJobsRequest.getArn(), ARN_BIND...
python
def authenticateRequest(self, service_request, username, password, **kwargs): """ Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: C{Deferred}. @rtype: C{twisted.internet.defer.Deferred} """ authenticato...
python
def after_init_app(self, app: FlaskUnchained): """ Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models. """ self.set_json_encoder(app) app.before_first_request(self.register_model_resources)
python
def movingMax(requestContext, seriesList, windowSize): """ Graphs the moving maximum of a metric (or metrics) over a fixed number of past points, or a time interval. Takes one metric or a wildcard seriesList followed by a number N of datapoints or a quoted string with a length of time like '1hour' ...
java
@SuppressWarnings("rawtypes") public static <T> Collector<T, ?, Optional<T>> first() { final Supplier<Holder<T>> supplier = (Supplier) first_last_supplier; final BiConsumer<Holder<T>, T> accumulator = (BiConsumer) first_accumulator; final BinaryOperator<Holder<T>> combiner = (BinaryOpera...
python
def find_le(self, dt): '''Find the index corresponding to the rightmost value less than or equal to *dt*. If *dt* is less than :func:`dynts.TimeSeries.end` a :class:`dynts.exceptions.LeftOutOfBound` exception will raise. *dt* must be a python datetime.date instance.''' i = bisect_right(self.dat...
java
public void setDirectionArrow(final Bitmap personBitmap, final Bitmap directionArrowBitmap){ this.mPersonBitmap = personBitmap; this.mDirectionArrowBitmap=directionArrowBitmap; mDirectionArrowCenterX = mDirectionArrowBitmap.getWidth() / 2.0f - 0.5f; mDirectionArrowCenterY = mDirectionArrowBitmap.getHeight() /...
python
def brighten(color, brightness): """ Adds or subtracts value to a color. """ h, s, v = rgb_to_hsv(*map(down_scale, color)) return tuple(map(up_scale, hsv_to_rgb(h, s, v + down_scale(brightness))))
python
def get_access_token(self, code=None, **params): """ Return the memoized access token or go out and fetch one. """ if self._access_token is None: if code is None: raise ValueError(_('Invalid code.')) self.access_token_dict = self._get_...
python
def get_bibtex(self): """Bibliographic entry in BibTeX format. Raises ------ ValueError If the item's aggregationType is not Journal. """ if self.aggregationType != 'Journal': raise ValueError('Only Journal articles supported.') # Item key...
python
def is_valid(self, csdl): """ Checks if the given CSDL is valid. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate :param csdl: CSDL to validate :type csdl: str :returns: Boolean indicating the validity of the CSDL :...
python
def parse(el, typ): """ Parse a ``BeautifulSoup`` element as the given type. """ if not el: return typ() txt = text(el) if not txt: return typ() return typ(txt)
python
def design_assembly(self): '''Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict ''' # Input parameters needed to design the oligos length_range = self.kwargs['length...
python
async def wait_message(self): """Blocks until new message appear.""" if not self._queue.empty(): return True if self._queue.closed: return False await self._queue.wait() return self.is_active
python
def probePoints(img, pts): """ Takes a ``vtkImageData`` and probes its scalars at the specified points in space. """ src = vtk.vtkProgrammableSource() def readPoints(): output = src.GetPolyDataOutput() points = vtk.vtkPoints() for p in pts: x, y, z = p ...
java
public static double transposeTimesTimes(final double[] v1, final double[][] m2, final double[] v3) { final int rowdim = m2.length, coldim = getColumnDimensionality(m2); assert rowdim == v1.length : ERR_MATRIX_INNERDIM; assert coldim == v3.length : ERR_MATRIX_INNERDIM; double sum = 0.0; for(int k = ...
python
def parse_ents(doc, options={}): """Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. """ ents = [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label...
python
def tally(self): """ tally() Records the value of all tracing variables. """ if self.verbose > 2: print_(self.__name__ + ' tallying.') if self._cur_trace_index < self.max_trace_length: self.db.tally() self._cur_trace_index += 1 if...
python
def get_layers(self, Psurf=1013.25, Ptop=0.01, **kwargs): """ Compute scalars or coordinates associated to the vertical layers. Parameters ---------- grid_spec : CTMGrid object CTMGrid containing the information necessary to re-construct grid levels for a...
python
def DropPrivileges(): """Attempt to drop privileges if required.""" if config.CONFIG["Server.username"]: try: os.setuid(pwd.getpwnam(config.CONFIG["Server.username"]).pw_uid) except (KeyError, OSError): logging.exception("Unable to switch to user %s", config.CONFIG["Serve...
python
def project(self, **kwargs: Dict[str, Any]) -> Union[Hist, Dict[str, Hist]]: """ Perform the requested projection(s). Note: All cuts on the original histograms will be reset when this function is completed. Args: kwargs (dict): Additional named args to be passed to proj...
python
def prepare_response_header(origin_header, segment): """ Prepare a trace header to be inserted into response based on original header and the request segment. """ if origin_header and origin_header.sampled == '?': new_header = TraceHeader(root=segment.trace_id, ...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case SarlPackage.SARL_BEHAVIOR__EXTENDS: return extends_ != null; } return super.eIsSet(featureID); }
python
def get_tor(reactor, launch_tor=False, tor_control_port=None, timing=None, stderr=sys.stderr): """ If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion...
java
private Map < String, String > generateConverterClasses( String xmlSchemaSource, String targetPackageName) { log.debug("Converter support classes generation started"); Map < String, String > codeMap = xsd2CobolTypes.generate( new StringReader(xmlSchemaSource), targetPackageN...
java
private static Direction getTailDirection(final Point2DArray points, final NFastDoubleArrayJSO buffer, final Direction lastDirection, Direction tailDirection, final double correction, final OrthogonalPolyLine pline, final double p0x, final double p0y, final double p1x, final double p1y) { final double offse...
python
def randomPairsMatch(n_records_A, n_records_B, sample_size): """ Return random combinations of indices for record list A and B """ n = int(n_records_A * n_records_B) if sample_size >= n: random_pairs = numpy.arange(n) else: random_pairs = numpy.array(random.sample(range(n), samp...
java
public Observable<List<BatchLabelExample>> batchAsync(UUID appId, String versionId, List<ExampleLabelObject> exampleLabelObjectArray) { return batchWithServiceResponseAsync(appId, versionId, exampleLabelObjectArray).map(new Func1<ServiceResponse<List<BatchLabelExample>>, List<BatchLabelExample>>() { ...
java
public void duplicate(IVector result) { if (result.size != size) result.reshape(size); int i; for (i = 0; i < size; i++) { result.realvector[i] = realvector[i]; result.imagvector[i] = imagvector[i]; } }
java
@Override public CommerceAvailabilityEstimate getCommerceAvailabilityEstimateByUuidAndGroupId( String uuid, long groupId) throws PortalException { return commerceAvailabilityEstimatePersistence.findByUUID_G(uuid, groupId); }
java
private void checkForLeadingZeroes() { Character la1 = chars.lookahead(1); Character la2 = chars.lookahead(2); if (la1 != null && la1 == '0' && CharType.DIGIT.isMatchedBy(la2)) { throw new ParseException("Numeric identifier MUST NOT contain leading zeroes"); } }
python
def show(self, annotations=True): """ Plot the current Path2D object using matplotlib. """ if self.is_closed: self.plot_discrete(show=True, annotations=annotations) else: self.plot_entities(show=True, annotations=annotations)
java
public static responderhtmlpage get(nitro_service service, String name) throws Exception{ responderhtmlpage obj = new responderhtmlpage(); obj.set_name(name); responderhtmlpage response = (responderhtmlpage) obj.get_resource(service); return response; }
java
public static void lsp_expand_1( float buf[], /* in/out: lsp vectors */ float gap ) { int j; float diff, tmp; for(j=1; j<LD8KConstants.NC; j++) { diff = buf[j-1] - buf[j]; tmp = (diff + gap) * (float)0.5; if(tmp > 0) { buf[j-1] -= tmp; buf[j] ...
python
def _apply_base_theme(app): """ Apply base theme to the application. Args: app (QApplication): QApplication instance. """ if QT_VERSION < (5,): app.setStyle('plastique') else: app.setStyle('Fusion') with open(_STYLESHEET) as stylesheet: app.setStyleShee...
java
public void println(double d) throws IOException { if(this._listener!= null && !checkIfCalledFromWLonError()){ if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "non blocking println double , WriteListener enabled: " + this._listener); ...
python
def parents( self, node ): """Retrieve/calculate the set of parents for the given node""" if 'index' in node: index = node['index']() parents = list(meliaeloader.children( node, index, 'parents' )) return parents return []
python
def distance(self, lat, lon): '''distance of this tile from a given lat/lon''' (tlat, tlon) = self.coord((TILES_WIDTH/2,TILES_HEIGHT/2)) return mp_util.gps_distance(lat, lon, tlat, tlon)
python
def pool_info(name=None, **kwargs): ''' Return informations on a storage pool provided its name. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to conn...
java
public com.google.appengine.v1.RequestUtilization getRequestUtilization() { return requestUtilization_ == null ? com.google.appengine.v1.RequestUtilization.getDefaultInstance() : requestUtilization_; }
python
def check_bucket_exists(self, bucket: str) -> bool: """ Checks if bucket with specified name exists. :param bucket: the bucket to be checked. :return: true if specified bucket exists. """ exists = True try: self.s3_client.head_bucket(Bucket=bucket) ...
python
def find_task(self, name): """ Find a task by name. If a task with the exact name cannot be found, then tasks with similar names are searched for. Returns ------- Task If the task is found. Raises ------ NoSuchTaskError ...
python
def get_field_mapping(self, using=None, **kwargs): """ Retrieve mapping definition of a specific field. Any additional keyword arguments will be passed to ``Elasticsearch.indices.get_field_mapping`` unchanged. """ return self._get_connection(using).indices.get_field_mapp...
python
def token(config, token): """Store and fetch a GitHub access token""" if not token: info_out( "To generate a personal API token, go to:\n\n\t" "https://github.com/settings/tokens\n\n" "To read more about it, go to:\n\n\t" "https://help.github.com/articles/...
python
def format_sklearn(self): """ Returns dataset in (X, y) format for use in scikit-learn. Unlabeled entries are ignored. Returns ------- X : numpy array, shape = (n_samples, n_features) Sample feature set. y : numpy array, shape = (n_samples) ...
java
private OntologyTermDynamicAnnotation createDynamicAnnotation(String label) { OntologyTermDynamicAnnotation entity = ontologyTermDynamicAnnotationFactory.create(); entity.setId(idGenerator.generateId()); String fragments[] = label.split(":"); entity.setName(fragments[0]); entity.setValue(fragments[1...
python
def status(self): """ Status of this SMS. Can be ENROUTE, DELIVERED or FAILED The actual status report object may be accessed via the 'report' attribute if status is 'DELIVERED' or 'FAILED' """ if self.report == None: return SentSms.ENROUTE else: ...
java
public void setTriggers(java.util.Collection<Trigger> triggers) { if (triggers == null) { this.triggers = null; return; } this.triggers = new java.util.ArrayList<Trigger>(triggers); }
java
@Override public void setDate(java.time.LocalDate date) { this.setDate(date != null ? new org.joda.time.LocalDate(date.getYear(), date.getMonthValue(), date.getDayOfMonth()) : null); }
python
def find_executable(self): '''Find an executable node, which means nodes that has not been completed and has no input dependency.''' if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']: env.log_to_file('DAG', 'find_executable') for node in self.nodes(): ...
java
private void requiredParameter(String value, String name, String description) throws WebApplicationException { if (value == null) { throw new WebApplicationException( Response.status(Response.Status.BAD_REQUEST).type( MediaType.TEXT_PLAIN).entity( "missing required parameter ...
python
def patch_pymongo(config): """ Monkey-patch pymongo's collections to add some logging """ # Nothing to change! if not config["print_mongodb"] and not config["trace_io"]: return from termcolor import cprint # Print because we are very early and log() may not be ready yet. cprint("Monke...
python
def intersect(self, *queries): '''Return a new :class:`Query` obtained form the intersection of this :class:`Query` with one or more *queries*. Workds the same way as the :meth:`union` method.''' q = self._clone() q.intersections += queries return q
python
def kernel_shap_1000_meanref(model, data): """ Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid """ return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0)
java
public int readADC(Destination dst, int channelNr, int repeat) throws KNXTimeoutException, KNXDisconnectException, KNXRemoteException, KNXLinkClosedException { if (channelNr < 0 || channelNr > 63 || repeat < 0 || repeat > 255) throw new KNXIllegalArgumentException("ADC arguments out of range"); if (ds...
java
public DescribeSpotInstanceRequestsResult withSpotInstanceRequests(SpotInstanceRequest... spotInstanceRequests) { if (this.spotInstanceRequests == null) { setSpotInstanceRequests(new com.amazonaws.internal.SdkInternalList<SpotInstanceRequest>(spotInstanceRequests.length)); } for (Spo...
python
def get_scan(self, scan_id): """ :param scan_id: The scan ID as a string :return: A resource containing the scan information """ url = self.build_full_url('%s%s' % (self.SCANS, scan_id)) _, json_data = self.send_request(url) return Resource(json_data)
java
public final void setBorderWidth(int unit, int size) { if (size < 0) { throw new IllegalArgumentException("Border width cannot be less than zero."); } int scaledSize = (int) TypedValue.applyDimension(unit, size, getResources().getDisplayMetrics()...
python
def create_pointing(self,event): """Plot the sky coverage of pointing at event.x,event.y on the canavas""" import math (ra,dec)=self.c2p((self.canvasx(event.x), self.canvasy(event.y))) this_camera=camera(camera=self.camera.get()) ccds=this_camera.getGe...
java
public Observable<ServiceResponse<Page<UpgradeOperationHistoricalStatusInfoInner>>> getOSUpgradeHistoryNextWithServiceResponseAsync(final String nextPageLink) { return getOSUpgradeHistoryNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<UpgradeOperationHistoricalStatusInfoI...
python
def mean(self): """return the median value""" # XXX rename this method if len(self.values) > 0: return sorted(self.values)[len(self.values) / 2] else: return None
python
def getandstrip_varintdata(data): ''' Takes a hex string that begins with varint data, and has extra at the end, and gets the varint integer, strips the varint bytes, and returns the integer and the remaining data. So rather than having to manually read the varint prefix, count, and strip, you can ...
python
def _get_master_address(self, instance): """ Get the master address from the instance configuration """ master_address = instance.get(MASTER_ADDRESS) if master_address is None: master_address = instance.get(DEPRECATED_MASTER_ADDRESS) if master_address: ...
java
public void shutDown() { downloadExecutor.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!downloadExecutor.awaitTermination(60, TimeUnit.SECONDS)) { downloadExecutor.shutdownNow(); // Cancel currently executing tasks // Wait a whil...
java
private void backwardsInferenceFromCallSite(Node n, FunctionType fnType, FlowScope scope) { boolean updatedFnType = inferTemplatedTypesForCall(n, fnType, scope); if (updatedFnType) { fnType = n.getFirstChild().getJSType().toMaybeFunctionType(); } updateTypeOfArguments(n, fnType); updateBind(n)...
java
public static EncodedPair toPair(String name, String value, Charset charset, boolean encoded) throws UnsupportedEncodingException { String nameEncoded; String valueEncoded; if(encoded){ nameEncoded = name; valueEncoded = value; }else{ nameEncoded = enc...
java
public int getRank(E element) { Ranking ranking = this.map.get(element); if (ranking == null) { return 0; } else { return ranking.rank; } }
python
def modify_profile_request_view(request, request_pk): ''' The page to modify a user's profile request. request_pk is the pk of the profile request. ''' page_name = "Admin - Profile Request" profile_request = get_object_or_404(ProfileRequest, pk=request_pk) mod_form = ModifyProfileRequestForm( re...
python
def remove_media(files): """ Delete file from media dir """ for filename in files: os.remove(os.path.join(settings.MEDIA_ROOT, filename))
java
public int getLimitPartIndex(int start) { int limit=parts.get(start).limitPartIndex; if(limit<start) { return start; } return limit; }
java
public static void setLogLevel(String cls, String level){ Logger l = null; if(Objects.isNullOrEmpty(cls)) l = LogManager.getRootLogger(); else l = LogManager.getLogger(cls); if(level.equalsIgnoreCase("TRACE")) l.setLevel(Level.TRACE); else if(l...
java
public static boolean exampleHasAtLeastOneCriteriaCheck(Object parameter) { if (parameter != null) { try { if (parameter instanceof Example) { List<Example.Criteria> criteriaList = ((Example) parameter).getOredCriteria(); if (criteriaList != nu...
java
public static boolean operate(PageContext pc, double scope, Collection.Key[] varNames) { return _operate(pc, scope, varNames, 0); }
java
static Class<?>[] getImplementedContracts(Object provider, Class<?>[] restrictedClasses) { Class<?> providerClass = provider instanceof Class<?> ? ((Class<?>)provider) : provider.getClass(); Set<Class<?>> interfaces = collectAllInterfaces(providerClass); List<Class<?>> implementedContracts = i...
python
def create(self, friendly_name, type, permission): """ Create a new RoleInstance :param unicode friendly_name: A string to describe the new resource :param RoleInstance.RoleType type: The type of role :param unicode permission: A permission the role should have :returns...
python
def delta(a, b): """Computes the distances between two colors or color sets. The shape of `a` and `b` must be equal. """ diff = a - b return numpy.einsum("i...,i...->...", diff, diff)
python
def calibrate(self, dataset_id, pre_launch_coeffs=False, calib_coeffs=None): """Calibrate the data """ tic = datetime.now() if calib_coeffs is None: calib_coeffs = {} units = {'reflectance': '%', ...
java
private List<TypePattern> getPatternsFrom(String value) { if (value == null) { return Collections.emptyList(); } List<TypePattern> typePatterns = new ArrayList<TypePattern>(); StringTokenizer st = new StringTokenizer(value, ","); while (st.hasMoreElements()) { String typepattern = st.nextToken(); Typ...
python
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index...
java
private String installPhp() { log.debug("Installing PHP v", new Object[]{getEntity().getPhpVersion()}); if (getEntity().getPhpVersion().equals("5.4")) { return instalPhp54v(); } else { return installPhpSuggestedVersionByDefault(); } }
java
private static LoginContext createLoginContext(AuthType authType, Subject subject, ClassLoader classLoader, javax.security.auth.login.Configuration configuration, AlluxioConfiguration alluxioConf) throws LoginException { CallbackHandler callbackHandler = null; if (authType.equals(AuthType.SIMP...
java
@SuppressWarnings("unchecked") public static <T> List<T> getAny(Collection<T> collection, int... indexes) { final int size = collection.size(); final ArrayList<T> result = new ArrayList<>(); if (collection instanceof List) { final List<T> list = ((List<T>) collection); for (int index : indexes) { ...
python
def action_checklist(self): """Return the list of action check list dictionary. :return: The list of action check list dictionary. :rtype: list """ actions = [] exposure = definition(self.exposure.keywords.get('exposure')) actions.extend(exposure.get('actions')) ...
java
@Nullable public static ImmutablePair<Schema, Schema> findSchema(Set<Schema> output, Set<Schema> input) { ImmutablePair<Schema, Schema> compatibleSchema = null; for (Schema outputSchema : output) { for (Schema inputSchema : input) { if (outputSchema.equals(inputSchema)) { return new I...
java
public boolean isConnected(Interval other) { Objects.requireNonNull(other, "other"); return this.equals(other) || (start.compareTo(other.end) <= 0 && other.start.compareTo(end) <= 0); }