language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private <A> TableData<A> tableData(final ResultSet rs, final RowFunction<A> f) throws SQLException { final ResultSetMetaData meta = rs.getMetaData(); final int c = meta.getColumnCount(); final TableData<A> td = new TableData<A>(); for (int...
python
def _shift(tokens): """pop the next token, then peek the gid of the following""" after = tokens.peek(n=1, skip=_is_comment, drop=True) tok = tokens._buffer.popleft() return tok[0], tok[1], tok[2], after[0]
python
def tty_stream(self): """ Whether or not our stream is a tty """ return hasattr(self.options.stream, "isatty") \ and self.options.stream.isatty()
java
public List<com.ibm.wsspi.security.wim.model.RolePlayer> getRelatedRolePlayer() { if (relatedRolePlayer == null) { relatedRolePlayer = new ArrayList<com.ibm.wsspi.security.wim.model.RolePlayer>(); } return this.relatedRolePlayer; }
python
def url_combo_activated(self, valid): """Load URL from combo box first item""" text = to_text_string(self.url_combo.currentText()) self.go_to(self.text_to_url(text))
python
def parse_from_xml(self, xml_spec): '''Parse a string or file containing an XML specification. Example: >>> s = RtsProfile() >>> s.parse_from_xml(open('test/rtsystem.xml')) >>> len(s.components) 3 Load of invalid data should throw exception: >>> s.parse_...
java
public static int orCardinality(final ImmutableRoaringBitmap x1, final ImmutableRoaringBitmap x2) { // we use the fact that the cardinality of the bitmaps is known so that // the union is just the total cardinality minus the intersection return x1.getCardinality() + x2.getCardinality() - andCardinalit...
java
public Object displayLicenseFile(InputStream licenseFile, CommandConsole commandConsole) { Object e = LicenseUtility.class; if (licenseFile != null) { e = showLicenseFile(licenseFile, commandConsole); } if (e != null) { commandConsole.printErrorMessage(CommandUtil...
java
public static JSONValue parse(InputStream is, String csName) throws IOException { try (Reader rdr = new InputStreamReader(is, csName)) { return parse(rdr); } }
java
private Map<String, Factory> getVisibleIDMap() { synchronized (this) { // or idcache-only lock? if (idcache == null) { try { factoryLock.acquireRead(); Map<String, Factory> mutableMap = new HashMap<String, Factory>(); ListIt...
java
@Override public Value<List<BigQueryLoadJobReference>> run( BigQueryStoreResult<GoogleCloudStorageFileSet> bigQueryStoreResult) throws Exception { BigQueryStoreResult<GoogleCloudStorageFileSet> outputResult = bigQueryStoreResult; List<GcsFilename> files = outputResult.getResult().getFiles(); List<Li...
java
private static <T> void blockyTandemMergeSortRecursion(final T[] keySrc, final long[] valSrc, final T[] keyDst, final long[] valDst, final int grpStart, final int grpLen, // block indices final int blkSize, final int arrLim, final Comparator<? super T> comparator) { // Important note: grpStart and grpLe...
python
def get_substructure(data, path): """ Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_su...
python
def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]: """Supports the completion of sub-commands for commands through the cmd2 help command.""" for idx, token in enumerate(tokens): if idx >= self._token_start_index: i...
java
public static base_responses add(nitro_service client, vpnvserver resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { vpnvserver addresources[] = new vpnvserver[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new vpnvser...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.RESOURCE_USAGE_ATTRIBUTE__FREQUENCY: setFrequency((Integer)newValue); return; } super.eSet(featureID, newValue); }
python
def has_parent_bins(self, bin_id): """Tests if the ``Bin`` has any parents. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the bin has parents, ``false`` otherwise raise: NotFound - ``bin_id`` is not found raise: NullArgument -...
java
public long guessNextBAMRecordStart(long beg, long end) throws IOException { // Use a reader to skip through the headers at the beginning of a BAM file, since // the headers may exceed MAX_BYTES_READ in length. Don't close the reader // otherwise it will close the underlying stream, which we continue to read f...
python
def get(self, metric_id=None, **kwargs): """ https://docs.cachethq.io/docs/get-metric-points """ if metric_id is None: raise AttributeError('metric_id is required to get metric points.') return self._get('metrics/%s/points' % metric_id, data=kwargs)
python
def lip2dens(perc_lipid, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994, dens_ash=2.3): '''Derive tissue density from lipids The equation calculating animal density is from Biuw et al. (2003), and default values for component densities are from human studies collected in the book by Moore ...
python
def is_extension_array_dtype(arr_or_dtype): """ Check if an object is a pandas extension array type. See the :ref:`Use Guide <extending.extension-types>` for more. Parameters ---------- arr_or_dtype : object For array-like input, the ``.dtype`` attribute will be extracted. ...
java
@Override public void addCreateListener( AsyncCallback<T> callback ) { DataSubscription subscription = new DataSubscription( RTDataEvents.created, tableName, createCallback( callback ) ); addEventListener( subscription ); }
python
def get_all(runas=None): ''' Return a list of services that are enabled or available. Can be used to find the name of a service. :param str runas: User to run launchctl commands :return: A list of all the services available or enabled :rtype: list CLI Example: .. code-block:: bash ...
python
def get_column_index(self, header): """Get index of a column from it's header. Parameters ---------- header: str header of the column. Raises ------ ValueError: If no column could be found corresponding to `header`. """ tr...
java
protected void stacktrace(Throwable e, boolean always) { if (debug || always) { println(">>> stacktrace:"); if (output instanceof PrintStream) { e.printStackTrace((PrintStream) output); } else { e.printStackTrace((PrintWriter) output); ...
python
def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionaries represented as ndarrays Examples -------- Print the dict keys to obtain the identifiers of the available dicti...
java
@Override public void close() { if (!closed.getAndSet(true)) { if (fc != null) { try { fc.close(); fc = null; } catch (final IOException e) { // Ignore } } if (raf ...
java
private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
java
public java.util.List<SingleInstanceHealth> getInstanceHealthList() { if (instanceHealthList == null) { instanceHealthList = new com.amazonaws.internal.SdkInternalList<SingleInstanceHealth>(); } return instanceHealthList; }
java
public boolean blockUntilConnectedOrTimedOut() throws InterruptedException { Preconditions.checkState(started.get(), "Client is not started"); log.debug("blockUntilConnectedOrTimedOut() start"); OperationTrace trace = startAdvancedTracer("blockUntilConnectedOrTimedOut"); inte...
java
private static Properties loadSecretProperties() throws IOException { Properties properties = new Properties(); InputStream propertiesStream = Server.class.getClassLoader().getResourceAsStream("secrets.properties"); if (propertiesStream == null) { // Fallback to file access in the ca...
python
def write(self, chunk: Union[str, bytes, dict]) -> None: """Writes the given chunk to the output buffer. To write the output to the network, use the `flush()` method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``applicat...
java
private void removeTemporaryMethodData(BeanMetaData bmd) { bmd.methodsExposedOnLocalHomeInterface = null; bmd.methodsExposedOnLocalInterface = null; bmd.methodsExposedOnRemoteHomeInterface = null; bmd.methodsExposedOnRemoteInterface = null; bmd.allPublicMethodsOnBean = null; ...
python
def cache_local_file(self, path, **kwargs): ''' Cache a local file on the minion in the localfiles cache ''' dest = os.path.join(self.opts['cachedir'], 'localfiles', path.lstrip('/')) destdir = os.path.dirname(dest) if not os.path.isdir(destdi...
java
public T mapObject(final Map<String, String> values) throws Exception { T result = createInstance(); // for each field for (Map.Entry<String, String> entry : values.entrySet()) { String field = entry.getKey(); //get field raw value String value = values.get...
java
public void purchaseReservedInstance(PurchaseReservedInstanceRequeset request) { checkNotNull(request, "request should not be null."); if (Strings.isNullOrEmpty(request.getClientToken())) { request.setClientToken(this.generateClientToken()); } if (null == request.getBilling()...
java
@Pure public Iterator<BusHub> getBusHubsIn(Rectangle2afp<?, ?, ?, ?, ?, ?> clipBounds) { return Iterators.unmodifiableIterator( this.validBusHubs.iterator(clipBounds)); }
java
public Shape createSliderThumbContinuous(final int x, final int y, final int diameter) { return createEllipseInternal(x, y, diameter, diameter); }
java
public static void generateJavaFiles(String requirementsFolder, String platformName, String src_test_dir, String tests_package, String casemanager_package, String loggingPropFile) throws Exception { File reqFolder = new File(requirementsFolder); if (reqFolder.isDirec...
python
def get_ids_in_region( self, resource, resolution, x_range, y_range, z_range, time_range=[0, 1]): """Get all ids in the region defined by x_range, y_range, z_range. Args: resource (intern.resource.Resource): An annotation channel. resolution (int): 0 indi...
java
public void setData(TByteList list) { this.buffer = CausticUtil.createByteBuffer(list.size()); this.buffer.put(list.toArray()); }
java
public boolean isMainMenu() { boolean bIsMainMenu = false; if (m_strMenu != null) { if (this.getTask() != null) if (HtmlConstants.MAIN_MENU_KEY.equalsIgnoreCase(this.getTask().getProperty(DBParams.MENU))) bIsMainMenu = true; if (m_strMe...
python
def v_unique_name_defintions(ctx, stmt): """Make sure that all top-level definitions in a module are unique""" defs = [('typedef', 'TYPE_ALREADY_DEFINED', stmt.i_typedefs), ('grouping', 'GROUPING_ALREADY_DEFINED', stmt.i_groupings)] def f(s): for (keyword, errcode, dict) in defs: ...
java
public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) { if (dynamoDBAction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLEN...
java
String getDefaultInstanceTopLevelId() { String topLevelConfigId = (String) config.get("config.id"); if (topLevelConfigId != null) if (topLevelConfigId.startsWith("com.ibm.ws.jca.resourceAdapter[")) return topLevelConfigId.substring(31, topLevelConfigId.length() - 1); ...
java
public ProxyDataSourceBuilder logSlowQueryByJUL(long thresholdTime, TimeUnit timeUnit, Level logLevel, String loggerName) { this.createJulSlowQueryListener = true; this.slowQueryThreshold = thresholdTime; this.slowQueryTimeUnit = timeUnit; this.julSlowQueryLogLevel = logLevel; th...
python
def _query_dns(self, host: str, family: int=socket.AF_INET) \ -> dns.resolver.Answer: '''Query DNS using Python. Coroutine. ''' record_type = {socket.AF_INET: 'A', socket.AF_INET6: 'AAAA'}[family] event_loop = asyncio.get_event_loop() query = functools.parti...
python
def set_group_name(group, old_name, new_name): """ Group was renamed. """ for datastore in _get_datastores(): datastore.set_group_name(group, old_name, new_name)
python
def first(self): """Return a (value, source) pair for the first object found for this view. This amounts to the first element returned by `resolve`. If no values are available, a NotFoundError is raised. """ pairs = self.resolve() try: return iter_firs...
java
public <T> T getMapped(final String param, final Map<String, T> possibleValues) { checkNotNull(possibleValues); checkArgument(!possibleValues.isEmpty()); final String value = getString(param); final T ret = possibleValues.get(value); if (ret == null) { throw new InvalidEnumeratedPropertyExce...
java
private static void setupAWSExceptionLogging(AmazonEC2 ec2) { boolean accessible = false; Field exceptionUnmarshallersField = null; try { exceptionUnmarshallersField = AmazonEC2Client.class.getDeclaredField("exceptionUnmarshallers"); accessible = exceptionUnmarshallersField.isAccessible(); ...
java
public static Nengo ofKanji(String kanji) { Nengo nengo = KANJI_TO_NENGO.get(kanji); if (nengo == null) { throw new IllegalArgumentException( "Could not find any nengo for Japanese kanji: " + kanji); } else { return nengo; } }
python
def cat_acc(y, z): """Classification accuracy for multi-categorical case """ weights = _cat_sample_weights(y) _acc = K.cast(K.equal(K.argmax(y, axis=-1), K.argmax(z, axis=-1)), K.floatx()) _acc = K.sum(_acc * weights) / K.sum(weights) return _acc
python
def on_for_rotations(self, speed, rotations, brake=True, block=True): """ Rotate the motor at ``speed`` for ``rotations`` ``speed`` can be a percentage or a :class:`ev3dev2.motor.SpeedValue` object, enabling use of other units. """ speed_sp = self._speed_native_units(spe...
java
public EList<Calendar> getCalendar() { if (calendar == null) { calendar = new EObjectContainmentEList<Calendar>(Calendar.class, this, BpsimPackage.SCENARIO__CALENDAR); } return calendar; }
java
@Override public int update(SpatialReferenceSystem data) throws SQLException { int result = super.update(data); updateDefinition_12_063(data); return result; }
java
public void put(Var var, int state) { if (state < 0 || state >= var.getNumStates()) { throw new IllegalArgumentException("Invalid state idx " + state + " for var " + var); } config.put(var, state); vars.add(var); }
java
public String query(String deviceInfo, String date, BillType type){ checkNotNullAndEmpty(date, "date"); checkNotNull(type, "bill type can't be null"); Map<String, String> downloadParams = buildDownloadParams(deviceInfo, date, type); String billData = Http.post(DOWNLOAD).body(Maps.toXml(d...
java
public static ExecutorService newWorkStealingPool() { return new ForkJoinPool (Runtime.getRuntime().availableProcessors(), ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
java
public final void begin() { this.file = this.getAppender().getIoFile(); if (this.file == null) { this.getAppender().getErrorHandler() .error("Scavenger not started: missing log file name"); return; } if (this.getProperties().getScavengeInterval() > -1) { final Thread thread =...
java
@SuppressWarnings("unchecked") private <T> T loadService(Class<T> spiType, Class<?> defaultImpl, ClassLoader loader) { final String defaultImplName = defaultImpl != null ? defaultImpl.getName() : null; return (T)ServiceLoader.loadService(spiType.getName(), defaultImplName, loader); }
python
def wait_for_thrift_interface(self, **kwargs): """ Waits for the Thrift interface to be listening. Emits a warning if not listening after 30 seconds. """ if self.cluster.version() >= '4': return; self.watch_log_for("Listening for thrift clients...", **kwargs...
python
def controlPoints(cmd, data): """ Checks if there are control points in the path data Returns the indices of all values in the path data which are control points """ cmd = cmd.lower() if cmd in ['c', 's', 'q']: indices = range(len(data)) if cmd == 'c': # c: (x1 y1 x2 y2 x...
python
def correlation_matvec(P, obs1, obs2=None, times=[1]): r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarra...
java
public EEnum getObjectClassificationStrucFlgs() { if (objectClassificationStrucFlgsEEnum == null) { objectClassificationStrucFlgsEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(101); } return objectClassificationStrucFlgsEEnum; }
java
public long toNanos() { long totalNanos = Math.multiplyExact(seconds, NANOS_PER_SECOND); totalNanos = Math.addExact(totalNanos, nanos); return totalNanos; }
python
def make_msg_id(): """ Create a semi random message id, by using 12 char random hex string and a timestamp. @return: string consisting of timestamp, -, random value """ random_string = get_rand_string(12) timestamp = time.strftime("%Y%m%d%I%M%S") msg_id = timestamp + "-" + random_string ...
python
def build_feature_collection(node, name=None): """ Build and return a (decoded) GeoJSON FeatureCollection corresponding to this KML DOM node (typically a KML Folder). If a name is given, store it in the FeatureCollection's ``'name'`` attribute. """ # Initialize geojson = { 'type': 'Feature...
python
def toogle_breakpoint(self, line_number=None, condition=None, edit_condition=False): """Add/remove breakpoint.""" if not self.editor.is_python_like(): return if line_number is None: block = self.editor.textCursor().block() else: ...
java
@Override public Request<DeleteSnapshotRequest> getDryRunRequest() { Request<DeleteSnapshotRequest> request = new DeleteSnapshotRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS): """ Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of bytes consumed to create it. :param obj: The parent :class:`.PebblePacket` of this fie...
java
@Override public Map<String, String> getExtensionProperties() { List<Node> props = extension.get("property"); Map<String, String> properties = new HashMap<String, String>(); for (Node prop : props) { properties.put(prop.getAttribute("name"), prop.getText()); } re...
java
@Override public final Connection createConnection() throws JMSException { String username = getStringProperty(Context.SECURITY_PRINCIPAL,null); String password = getStringProperty(Context.SECURITY_CREDENTIALS,null); return createConnection(username,password); }
java
private BigInteger toBigInteger(ByteBuffer bb, int significantBytes) { byte[] bytes = Bytes.getArray(bb); byte[] target; if (significantBytes != bytes.length) { target = new byte[significantBytes]; System.arraycopy(bytes, 0, target, 0, bytes.length); } else { target = bytes; } ...
python
def add_argument_to(self, parser): """Used by cli to add this as an argument to argparse parser. Args: parser: parser to add this argument to """ from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory if isinstance(self.kwargs.get('action', ''...
java
private Cache getScopeCache(String scope) throws InvalidScopeException { Cache scopeCache = scopeManager.getCache(scope); if (scopeCache == null) { throw new InvalidScopeException("The scope " + scope + " doesn't exist"); } else { return scopeCache; } }
python
def send(self, request): """ Send a request to the server and wait for its response. Args: request (Request): Reference to a request object that is sent to the server. Returns: Response: The response from the server to the request. """ self._connection.c...
python
def check() -> Result: """Open and close the broker channel.""" try: # Context to release connection with Connection(conf.get('CELERY_BROKER_URL')) as conn: conn.connect() except ConnectionRefusedError: return Result(message='Service unable to ...
python
def copy(self, datasets=None): """Create a copy of the Scene including dependency information. Args: datasets (list, tuple): `DatasetID` objects for the datasets to include in the new Scene object. """ new_scn = self.__class__() n...
java
public void setDBInfoList(int i, DBInfo v) { if (ManualDescriptor_Type.featOkTst && ((ManualDescriptor_Type)jcasType).casFeat_dBInfoList == null) jcasType.jcas.throwFeatMissing("dBInfoList", "de.julielab.jules.types.pubmed.ManualDescriptor"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(...
java
public void stopAllPlugins() { synchronized (pluginMap) { // remove the listener for this repository loggerRepository.removeLoggerRepositoryEventListener(listener); Iterator iter = pluginMap.values().iterator(); while (iter.hasNext()) { Plugin pl...
java
private SymbolScope createScopeFrom(StaticScope otherScope) { Node otherScopeRoot = otherScope.getRootNode(); SymbolScope myScope = scopes.get(otherScopeRoot); if (myScope == null) { StaticScope otherScopeParent = otherScope.getParentScope(); // If otherScope is a global scope, and we already ...
python
def _try_to_clean_garbage(self, writer_spec, exclude_list=()): """Tries to remove any files created by this shard that aren't needed. Args: writer_spec: writer_spec for the MR. exclude_list: A list of filenames (strings) that should not be removed. """ # Try to remove garbage (if an...
python
def remove_child_log(self, log_id, child_id): """Removes a child from a log. arg: log_id (osid.id.Id): the ``Id`` of a log arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``log_id`` not a parent of ``child_id`` raise: NullArgument - ``log_id`` o...
python
def can_handle(self, data): r""" >>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),)) >>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3...
python
async def update_object(obj, only=None): """Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save...
python
def resolve(self, container: Container, fn: str) -> str: """ Ensures that relative paths are transformed into absolute paths. """ bug = self.__mgr_bug[container.bug] fn_orig = fn if not os.path.isabs(fn): fn = os.path.join(bug.source_dir, fn) logg...
python
def graceful_exit(servers, *, loop, signals=frozenset({signal.SIGINT, signal.SIGTERM})): """Utility context-manager to help properly shutdown server in response to the OS signals By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals. There are two stages: ...
python
def _write(self, data): """ Writes string data out to Scratch """ total_sent = 0 length = len(data) while total_sent < length: try: sent = self.socket.send(data[total_sent:]) except socket.error as (err, msg): self.c...
java
protected RootContextIdentifierType getSelectedContextIdentifierType() { if (this.randomContextIdentifierButton.getSelection()) { return RootContextIdentifierType.RANDOM_CONTEXT_ID; } if (this.bootContextIdentifierButton.getSelection()) { return RootContextIdentifierType.BOOT_AGENT_CONTEXT_ID; } return ...
python
def prompt(*args, **kwargs): """Prompt the user for input and handle any abort exceptions.""" try: return click.prompt(*args, **kwargs) except click.Abort: return False
java
public void put(Class key, AdvancedExternalizer value) { final Class[] keys = this.keys; final int mask = keys.length - 1; final AdvancedExternalizer[] values = this.values; Class k; int hc = System.identityHashCode(key) & mask; for (int idx = hc;; idx = hc++ & mask) { k = k...
python
def validate(self, path, schema, value, results): """ Validates a given value against this rule. :param path: a dot notation path to the value. :param schema: a schema this rule is called from :param value: a value to be validated. :param results: a list with validati...
java
protected final Stack<Long> addNewElement(final Stack<Long> paramLeftSiblingKeyStack, final StartElement paramEvent) throws TTException { assert paramLeftSiblingKeyStack != null && paramEvent != null; long key; final QName name = paramEvent.getName(); if (mFirstChildAppend == E...
java
private CmsComboWidget createTemplateSelect() { List<CmsSelectWidgetOption> options = new ArrayList<CmsSelectWidgetOption>(); try { I_CmsResourceType templateType = OpenCms.getResourceManager().getResourceType( CmsResourceTypeJsp.getContainerPageTemplateTypeName()); ...
java
public static SourceSnippet forText(final String text) { return new SourceSnippet() { public String getSource(InjectorWriteContext writeContext) { return text; } }; }
python
def as_leaf_class(self): """ Returns the leaf class no matter where the calling instance is in the inheritance hierarchy. Inspired by http://www.djangosnippets.org/snippets/1031/ """ try: return self.__getattribute__(self.class_name.lower()) except AttributeEr...
java
public List<Marker> getBookmarksAsMarkers(MapView view) { List<Marker> markers = new ArrayList<>(); try { //TODO order by title final Cursor cur = mDatabase.rawQuery("SELECT * FROM " + TABLE, null); while(cur.moveToNext()) { Marker m = new Marker(view)...
python
async def _fair_send(self, frames): """ Send from the first available, non-blocking peer or wait until one meets the condition. :params frames: The frames to write. :returns: The peer that was used. """ peer = await self._fair_get_out_peer() peer.outbox.w...
python
def apply_hyperparameter_renames(cls, hyperparameters): """ Handle hyperparameter renames. Parameters ---------- hyperparameters : dict Returns ------- dict : updated hyperparameters """ for (from_name, to_name) in cls.hyperparameter_ren...