language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static Matrix[] svdlibc(File matrix, int dimensions, Format format) { try { String formatString = ""; // output the correct formatting flags based on the matrix type switch (format) { case SVDLIBC_DENSE_BINARY: formatString = " -r db "...
python
def done_item(item, code): '''Succeed or fail an item based on the return code of a program''' try: if const('FSQ_SUCCESS') == code: success(item) chirp('{0}: succeeded'.format(item.id)) elif const('FSQ_FAIL_TMP') == code: fail_tmp(item) shout('{0}...
python
def sce2s(sc, et, lenout=_default_len_out): """ Convert an epoch specified as ephemeris seconds past J2000 (ET) to a character string representation of a spacecraft clock value (SCLK). http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sce2s_c.html :param sc: NAIF spacecraft clock ID code. ...
python
def signin(request, auth_form=AuthenticationForm, template_name='accounts/signin_form.html', redirect_field_name=REDIRECT_FIELD_NAME, redirect_signin_function=signin_redirect, extra_context=None): """ Signin using email or username with password. Signs a user in by combinin...
python
def _updateCallSetIds(self, variantFile): """ Updates the call set IDs based on the specified variant file. """ if len(self._callSetIdMap) == 0: for sample in variantFile.header.samples: self.addCallSetFromName(sample)
python
def byaxis(self): """Return the subspace defined along one or several dimensions. Examples -------- Indexing with integers or slices: >>> space = odl.rn((2, 3, 4)) >>> space.byaxis[0] rn(2) >>> space.byaxis[1:] rn((3, 4)) Lists can be us...
python
def starts(self): """Return all start records for this the dataset, grouped by the start record""" return (self._session.query(Process) .filter(Process.d_vid == self._d_vid) .filter(Process.log_action == 'start') ).all()
python
def GetSubkeyByName(self, name): """Retrieves a subkey by name. Args: name (str): name of the subkey. Returns: WinRegistryKey: Windows Registry subkey or None if not found. """ if not self._registry_key and self._registry: self._GetKeyFromRegistry() return self._subkeys.get(...
java
public void contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { if (!actual().contains(rowKey, columnKey)) { fail("contains mapping for row/column", rowKey, columnKey); } }
java
public boolean contains( Location other ) { if( isSameStrand( other )) { return ( mStart <= other.mStart && mEnd >= other.mEnd ); } else { throw new IllegalArgumentException( "Locations are on opposite strands." ); } }
python
def transliterate(mode, string, ignore = '', reverse = False ): # @todo: arabtex and iso8859-6 need individual handling because in some cases using one-two mapping """ encode & decode different romanization systems :param mode: :param string: :param ignore: :param reverse: :return: ...
java
protected void copyDependencies(String outputSubdirectory) throws MojoExecutionException { outputDirectory = project.getBuild().getDirectory(); baseDirectory = project.getBasedir().getAbsolutePath(); String outputDirectory = outputSubdirectory == null ? this.outputD...
python
def _hugoniot_pth(self, v): """ calculate thermal pressure along hugoniot :param v: unit-cell volume in A^3 :return: thermal pressure along hugoniot in GPa """ temp = self._hugoniot_t(v) return self.cal_pth(v, temp)
java
private void handleToken(String token) throws OptionParserException { currentToken = token; if (!"--".equals(token)) { if (currentOption != null && currentOption.acceptsValue() && !currentOption.isWithEqualSign() && isArgument(token)) { String t = OptionUt...
java
public static String readFile(String fileName) throws IOException { logger.entering(fileName); Preconditions.checkArgument(StringUtils.isNotBlank(fileName), "File name cannot be null (or) empty."); StringBuilder output = new StringBuilder(); try (BufferedReader buffreader = new BufferedR...
java
static int findRelativeSecond(long delayMillis) { long now = Clock.currentTimeMillis(); long d = (now + delayMillis - INITIAL_TIME_MILLIS); return ceilToSecond(d); }
java
@Override public DisassociateCertificateResult disassociateCertificate(DisassociateCertificateRequest request) { request = beforeClientExecution(request); return executeDisassociateCertificate(request); }
java
void updateWith(EfficientAdapter<T> efficientAdapter, List<T> list) { new AdapterUpdater<>(efficientAdapter).update(list); }
java
public void setSecretList(java.util.Collection<SecretListEntry> secretList) { if (secretList == null) { this.secretList = null; return; } this.secretList = new java.util.ArrayList<SecretListEntry>(secretList); }
python
def cmd(send, msg, args): """Handles quotes. Syntax: {command} <number|nick>, !quote --add <quote> --nick <nick> (--approve), !quote --list, !quote --delete <number>, !quote --edit <number> <quote> --nick <nick> !quote --search (--offset <num>) <number> """ session = args['db'] parser = argument...
python
def tracer(object): """ | Traces execution. | Any method / definition decorated will have it's execution traced through debug messages. | Both object entry and exit are logged. Entering in an object:: INFO : ---> foundations.environment.get_user_application_data_directory() <<<--- ...
java
@Override public void processTextMessage(WebSocketChannel channel, String message) { LOG.entering(CLASS_NAME, "send", message); WebSocketCompositeChannel parent = (WebSocketCompositeChannel)channel; if (parent.readyState != ReadyState.OPEN) { LOG.warning("Attempt to post message...
python
def _read_stderr(self): """Read the stderr file of the kernel.""" # We need to read stderr_file as bytes to be able to # detect its encoding with chardet f = open(self.stderr_file, 'rb') try: stderr_text = f.read() # This is needed to avoid show...
java
@Deprecated public static boolean isSingleField(String skeleton) { char first = skeleton.charAt(0); for (int i = 1; i < skeleton.length(); ++i) { if (skeleton.charAt(i) != first) return false; } return true; }
java
public void loadMore(final Card card) { if (mAsyncPageLoader == null) { return; } if (!card.loading && card.loadMore && card.hasMore) { card.loading = true; if (!card.loaded) { card.page = sInitialPage; } mAsyncPageLoa...
java
public boolean exists(final String pTileSource, final long pMapTileIndex) { return 1 == getRowCount(primaryKey, getPrimaryKeyParameters(getIndex(pMapTileIndex), pTileSource)); }
java
private int shiftMask(FileAccessClass fileModeClass, int bitMask) { if (fileModeClass == FileAccessClass.USER) { return bitMask << 6; } else if (fileModeClass == FileAccessClass.GROUP) { return bitMask << 3; } else if (fileModeClass == FileAccessClass.OTHERS) { return bitMask; } t...
java
public IJsonMarshaller getIJsonMarshallerInstance(Class<? extends IJsonMarshaller> cls) throws JsonMarshallerException { if(logger.isDebugEnabled()) { logger.debug("Try to get {} by CDI.select Unsatisfied: {}", cls.getName(), CDI.current().select(cls).isUnsatisfied()); } if(CDI.current().select(cls).isUnsa...
python
def normalize(self, body): """ Invoke the JSON API normalizer Perform the following: * add the type as a rtype property * flatten the payload * add the id as a rid property ONLY if present We don't need to vet the inputs much because the Parser has ...
python
def _add_comparison_methods(cls): """ Add in comparison methods. """ cls.__eq__ = _make_comparison_op(operator.eq, cls) cls.__ne__ = _make_comparison_op(operator.ne, cls) cls.__lt__ = _make_comparison_op(operator.lt, cls) cls.__gt__ = _make_comparison_op(operator....
java
public static char getFirstLetter(char ch) { if (ch >= 'a' && ch <= 'z') { return ch; } if (ch >= 'A' && ch <= 'Z') { return Character.toLowerCase(ch); } final byte[] bys = String.valueOf(ch).getBytes(CharsetUtil.CHARSET_GBK); if (bys.length == 1) { return ch; } int count = (bys[0] +...
java
public static Digest valueOf(final String value) { final String[] parts = value.split("=", 2); if (parts.length == 2) { return new Digest(parts[0], parts[1]); } return null; }
java
public byte[] read(int len) throws SQLException { // This is the original method, where the entire block (len bytes) // is retrieved in one go. FastpathArg[] args = new FastpathArg[2]; args[0] = new FastpathArg(fd); args[1] = new FastpathArg(len); return fp.getData("loread", args); }
python
def get_pointlist(self): """ Get a list of lists of tuples from JSON raw data string. Those lists represent strokes with control points. Returns ------- list : A list of strokes. Each stroke is a list of dictionaries {'x': 123, 'y': 42, 'time': 13...
java
public static <T> T visitField(FieldDescriptor fieldDescriptor, FieldVisitor<T> visitor) { // NOTE: map fields are technically repeated, so check isMap first. if (fieldDescriptor.isMapField()) { List<FieldDescriptor> mapFields = fieldDescriptor.getMessageType().getFields(); checkState(mapFields.size...
python
def update(args): """Update a record. Argument: args: arguments object Firstly call delete(), then create(). """ # Check specifying some new values if ((not args.__dict__.get('new_type') and not args.__dict__.get('new_content') and not args.__dict__.get('new_ttl') an...
python
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)): """Draws text over the image. Requires PIL. Args: img: The image to use. text: The text string to overlay. position: The text (x, y) position. (Default value = (10, 10)) font: The tt...
python
def url_for(self, entity=None, object_type=None, object_id=None, **kwargs): """Return canonical view URL for given entity instance. If no view has been registered the registry will try to find an endpoint named with entity's class lowercased followed by '.view' and that accepts `object_...
python
def maybe_cythonize_extensions(top_path, config): """Tweaks for building extensions between release and development mode.""" is_release = os.path.exists(os.path.join(top_path, 'PKG-INFO')) if is_release: build_from_c_and_cpp_files(config.ext_modules) else: message = ('Please install cyt...
python
def load_classifiers(algo_defs, env): """ Load an algorithm into a module. The algorithm is an instance of ``AlgorithmDef`` class. :param algo_defs: algorithm definitions :type algo_defs: AlgorithmDef | list[AlgorithmDef] :param env: environment :Example: >>> import sys >>> from odps.m...
java
public DescribeUserProfilesRequest withIamUserArns(String... iamUserArns) { if (this.iamUserArns == null) { setIamUserArns(new com.amazonaws.internal.SdkInternalList<String>(iamUserArns.length)); } for (String ele : iamUserArns) { this.iamUserArns.add(ele); } ...
python
def register_simulants(self, simulants: pd.DataFrame): """Adds new simulants to the randomness mapping. Parameters ---------- simulants : A table with state data representing the new simulants. Each simulant should pass through this function exactly once. ...
python
def quoted(text): """ Args: text (str | unicode | None): Text to optionally quote Returns: (str): Quoted if 'text' contains spaces """ if text and " " in text: sep = "'" if '"' in text else '"' return "%s%s%s" % (sep, text, sep) return text
java
@Nullable public MountTable.Resolution resolveSyncPoint(AlluxioURI syncPoint) throws InvalidPathException { if (!mSyncPathList.contains(syncPoint)) { LOG.debug("syncPoint not found {}", syncPoint.getPath()); return null; } MountTable.Resolution resolution = mMountTable.resolve(syncPoint); ...
python
def intersection(*args): """ Return the intersection of lists, using the first list to determine item order """ if not args: return [] # remove duplicates from first list whilst preserving order base = list(OrderedDict.fromkeys(args[0])) if len(args) == 1: return base e...
java
private boolean hasNoSubjOpt(List<String> tags) { if(tags.size() > 1) { for (String tag : tags) { if(!tag.endsWith("=SUBJ")) { return true; } } } return false; }
python
def write(self, b): """ Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. Args: b (bytes-like object): Bytes to write. Returns: int: The number of bytes written. """ if not self._w...
python
def step_type(self): """Whether it's a IFCW step or Keyword Wizard Step.""" if 'stepfc' in self.__class__.__name__.lower(): return STEP_FC if 'stepkw' in self.__class__.__name__.lower(): return STEP_KW
java
public B annotatedService(String pathPrefix, Object service, Iterable<?> exceptionHandlersAndConverters) { return annotatedService(pathPrefix, service, Function.identity(), requireNonNull(exceptionHandlersAndConverters, ...
java
public static ExecutorService getExecutorService() { HttpDispatcher f = instance.get().get(); if (f == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "HttpDispatcher instance not found"); } return null; ...
java
public void setLineDashesInMeters(double... dashes) { final double[] newDashes; if (dashes == null) { newDashes = dashes; } else { newDashes = new double[dashes.length]; for (int i = 0; i < newDashes.length; ++i) { newDashes[i] = doc2fxSize(dashes[i]); } } setLineDashesInPixels(newDashes); }
java
public static void premain(String arg, Instrumentation inst) throws Exception { BootstrapAgent.arg = arg; BootstrapAgent.instrumentation = inst; setSystemProperties(); if (arg == null || arg.length() == 0) { return; } // Find the relative location of the tar...
java
private static ImmutableList<SoyMsgPart> buildMsgPartsForChildren( MsgBlockNode parent, MsgNode msgNode) { ImmutableList.Builder<SoyMsgPart> msgParts = ImmutableList.builder(); doBuildMsgPartsForChildren(parent, msgNode, msgParts); return msgParts.build(); }
java
public long getLong(int index) throws JSONException { Object object = get(index); Long result = JSON.toLong(object); if (result == null) { throw JSON.typeMismatch(index, object, "long"); } return result; }
java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public int getCompoundPaddingEnd (){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) return mInputView.getCompoundPaddingEnd(); return mInputView.getCompoundPaddingRight(); }
java
public final void setExceptionInserts(String[] values) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setExceptionInserts", values); boolean wasEmpty = (getHdr2().getChoiceField(JsHdr2Access.EXCEPTION) == JsHdr2Access.IS_EXCEPTION_EMPTY); if...
python
def startWizard(args, mainwin, modal=True): """ Parses list of directories ('args') and attaches to purrlogs appropriately. 'mainwin' is a Purr.MainWindow object. Return value: * if modal=True: True if arguments parse OK and Purr.MainWindow should be shown, False on error. * if modal=False:...
python
def create(self, pools): """ Method to create pool's :param pools: List containing pool's desired to be created on database :return: None """ data = {'server_pools': pools} return super(ApiPool, self).post('api/v3/pool/', data)
java
public ListServerNeighborsRequest withNeighborConfigurationIds(String... neighborConfigurationIds) { if (this.neighborConfigurationIds == null) { setNeighborConfigurationIds(new java.util.ArrayList<String>(neighborConfigurationIds.length)); } for (String ele : neighborConfigurationId...
python
def parse_json(raw_json): """Parse a Puppet forge JSON stream. The method parses a JSON stream and returns a list with the parsed data. :param raw_json: JSON string to parse :returns: a list with the parsed data """ result = json.loads(raw_json) if 're...
java
public float get(String name, float defaultValue) throws IllegalArgumentException { ObjectSlot slot = findMandatorySlot(name, float.class); return slot.defaulted ? defaultValue : ((Float) slot.fieldValue).floatValue(); }
java
private void extractFromCallNode(Builder builder, Node node) throws MalformedException { // Check the function being called if (!node.isCall()) { throw new MalformedException( "Message must be initialized using " + MSG_FUNCTION_NAME + " function.", node); } Node fnNameNo...
python
def save(self, *args, **kwargs): """ Fill 'created' and 'modified' attributes on first create and allways update the thread's 'modified' attribute """ edited = not(self.created is None) if self.created is None: self.created = tz_now() ...
java
public boolean measureAll(List<Widget> measuredChildren) { boolean changed = false; for (int i = 0; i < mContainer.size(); ++i) { if (!isChildMeasured(i)) { Widget child = measureChild(i, false); if (child != null) { if (measuredChildren !...
python
def save(self, png_file): """Save png to disk. Parameters ---------- png_file : path to file file to write to Notes ----- It relies on _repr_png_, so fix issues there. """ with open(png_file, 'wb') as f: f.write(self._repr...
python
def _update_ssl_config(opts): ''' Resolves string names to integer constant in ssl configuration. ''' if opts['ssl'] in (None, False): opts['ssl'] = None return if opts['ssl'] is True: opts['ssl'] = {} return import ssl for key, prefix in (('cert_reqs', 'CERT_...
java
@Override public CPSpecificationOption findByUuid_C_First(String uuid, long companyId, OrderByComparator<CPSpecificationOption> orderByComparator) throws NoSuchCPSpecificationOptionException { CPSpecificationOption cpSpecificationOption = fetchByUuid_C_First(uuid, companyId, orderByComparator); if (cpSp...
java
private int getItemViewType(Class prototypeClass) { int itemViewType = -1; for (Renderer renderer : prototypes) { if (renderer.getClass().equals(prototypeClass)) { itemViewType = getPrototypeIndex(renderer); break; } } if (itemViewType == -1) { throw new PrototypeNotFou...
java
public com.google.api.ads.admanager.axis.v201902.BandwidthGroupTargeting getBandwidthGroupTargeting() { return bandwidthGroupTargeting; }
python
def download_items(self, items, file_path, file_format='zip'): """ Retrieve a file from the server containing the metadata and documents for the speficied items :type items: List or ItemGroup :param items: List of the the URLs of the items to download, or an ItemGroup object...
python
def print_facilities(self, facilities): """Print method for facilities. """ for facility in facilities: print('{} - ({}): {}'.format(facility.code, facility.name, ",".join(facility.features)))
python
def log(self, message, result_code, log_message=""): """ create a log entry for an attempt to send the given message and record the given result and (optionally) a log message """ return self.create( message_data=message.message_data, message_id=get_messag...
java
public void marshall(ResetCacheRequest resetCacheRequest, ProtocolMarshaller protocolMarshaller) { if (resetCacheRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resetCacheRequest.getGateway...
python
def pid_tuning_send(self, axis, desired, achieved, FF, P, I, D, force_mavlink1=False): ''' PID tuning information axis : axis (uint8_t) desired : desired rate (degrees/s) (float) achieved ...
java
void topicSpaceCreated(DestinationHandler destination) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "topicSpaceCreated", destination); // Synchronize around the topic space references to stop removal and // additions occuring at the s...
java
static final int find(final int[] array, final int lgArrInts, final int coupon) { final int arrMask = array.length - 1; int probe = coupon & arrMask; final int loopIndex = probe; do { final int couponAtIdx = array[probe]; if (couponAtIdx == EMPTY) { return ~probe; //empty } ...
java
@Override protected void initGraphics() { super.initGraphics(); mouseEventHandler = e -> { final EventType TYPE = e.getEventType(); final Object SRC = e.getSource(); if (MouseEvent.MOUSE_PRESSED == TYPE) { if (SRC.equals(thumb)) { ...
java
public static CurrencyFunction currency(Field field, @Nullable String currencyCode) { Assert.notNull(field, "Field for currency function must not be 'null'."); CurrencyFunction function = new CurrencyFunction(field); if (StringUtils.hasText(currencyCode)) { function.addArgument(currencyCode); } return fu...
java
public static boolean isSkewSymmetric(DMatrixRMaj A , double tol ){ if( A.numCols != A.numRows ) return false; for( int i = 0; i < A.numRows; i++ ) { for( int j = 0; j < i; j++ ) { double a = A.get(i,j); double b = A.get(j,i); dou...
java
@Override public String[] tag(List<String> wordList) { String[] termArray = new String[wordList.size()]; wordList.toArray(termArray); return tag(termArray); }
java
public void setParameters(Map<String, ?> parameters) { WebcamDevice device = getDevice(); if (device instanceof Configurable) { ((Configurable) device).setParameters(parameters); } else { LOG.debug("Webcam device {} is not configurable", device); } }
java
public OrderingList<S> reverseDirections() { if (size() == 0) { return this; } OrderingList<S> reversedList = emptyList(); for (int i=0; i<size(); i++) { reversedList = reversedList.concat(get(i).reverse()); } return reversedList; }
python
def syllabify(word): '''Syllabify the given word, whether simplex or complex.''' word = split(word) # detect any non-delimited compounds compound = True if re.search(r'-| |\.', word) else False syllabify = _syllabify_compound if compound else _syllabify syll, rules = syllabify(word) yield syll...
python
def _check_formula_terms(self, ds, coord): ''' Checks a dimensionless vertical coordinate contains valid formula_terms - formula_terms is a non-empty string - formula_terms matches regx - every variable defined in formula_terms exists :param netCDF4.Dataset ds: An open ...
java
private void handleGeneratedCssInDebugMode(String requestedPath, HttpServletRequest request, HttpServletResponse response, BinaryResourcesHandler binaryRsHandler) throws ResourceNotFoundException, IOException { // Retrieves the content of the CSS Reader rd = rsReaderHandler.getResource(null, requestedPath); ...
python
def get_single_value(d): """Get a value from a dict which contains just one item.""" assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.itervalues(d))
java
public void billingAccount_line_serviceName_phone_phonebook_bookKey_DELETE(String billingAccount, String serviceName, String bookKey) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone/phonebook/{bookKey}"; StringBuilder sb = path(qPath, billingAccount, serviceName, bookKey); ...
python
def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None): '''Initialize users database initialize database and create necessary tables to handle users oprations. :param dbURL: database url, as described in :func:`init_proxy` ''' if not dbURL: dbURL = 'sqlite:///:memory:' logging.get...
java
public String read(String path, Watcher watcher, Stat stat) throws InterruptedException, KeeperException { return store.read(path, watcher, stat); }
python
def check_permission(permission, hidden=True): """Check if permission is allowed. If permission fails then the connection is aborted. :param permission: The permission to check. :param hidden: Determine if a 404 error (``True``) or 401/403 error (``False``) should be returned if the permission...
java
@XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "sn") public JAXBElement<String> createSn(String value) { return new JAXBElement<String>(_Sn_QNAME, String.class, null, value); }
python
def _handle_nodes(nodes: MaybeNodeList) -> List[BaseEntity]: """Handle node(s) that might be dictionaries.""" if isinstance(nodes, BaseEntity): return [nodes] return [ ( parse_result_to_dsl(node) if not isinstance(node, BaseEntity) else node ) ...
java
public static <T> VicariousThreadLocal<T> newThreadLocal(final T initialValue) { return new VicariousThreadLocal<T>() { @Override public T initialValue() { return initialValue; } }; }
python
def voip_play2(s1, **kargs): """ Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets. """ dsp, rd = os.popen2(sox_base % "-c 2") global x1, ...
java
public @Nonnull Iterable<VirtualMachineProduct> listProducts( @Nonnull VirtualMachineProductFilterOptions options, @Nullable Architecture architecture ) throws InternalException, CloudException { String cacheName = "ALL"; if( architecture != null ) { cacheName = architecture.name(); ...
java
private Collection<String> buildTopicNames(Response response) { Collection<String> topicNames = new HashSet<>(); Collection<String> detectionSystemNames = appSensorServer.getConfiguration().getRelatedDetectionSystems(response.getDetectionSystem()); for(String detectionSystemName : detectionSystemNames) { ...
java
public ServiceFuture<List<SkuInfoInner>> listWorkerPoolSkusNextAsync(final String nextPageLink, final ServiceFuture<List<SkuInfoInner>> serviceFuture, final ListOperationCallback<SkuInfoInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listWorkerPoolSkusNextSinglePageAsync(nextPa...
python
def extract_data(data_path, feature): '''Loads a list of neurons, extracts feature and transforms the fitted distribution in the correct format. Returns the optimal distribution, corresponding parameters, minimun and maximum values. ''' population = nm.load_neurons(data_path) featu...
python
def _get_imsize(self, im_name): """ get image size info Returns: ---------- tuple of (height, width) """ img = cv2.imread(im_name) return (img.shape[0], img.shape[1])
java
public void parse(File f, DefaultHandler dh) throws SAXException, IOException { XMLReader reader = getXMLReader(); InputSource source = new InputSource(new FileInputStream(f)); reader.setContentHandler(dh); reader.parse(source); }