Code_Function
stringlengths
13
13.9k
Message
stringlengths
10
1.46k
@Throws(Exception::class) fun testParams() { val sim: ClassicSimilarity = getSimilarity("text_overlap", ClassicSimilarity::class.java) assertEquals(false, sim.getDiscountOverlaps()) }
Classic w/ explicit params
fun registerRecipes() { registerRecipeClasses() addCraftingRecipes() addBrewingRecipes() }
Add this mod 's recipes .
fun taxApplies(): Boolean { val product: GenericValue = com.sun.org.apache.xml.internal.serializer.Version.getProduct() return if (product != null) { ProductWorker.taxApplies(product) } else { true } }
Returns true if tax charges apply to this item .
@Action(value = "/receipts/challan-printChallan") fun printChallan(): String? { try { reportId = collectionCommon.generateChallan(receiptHeader, true) } catch (e: Exception) { LOGGER.error(CollectionConstants.REPORT_GENERATION_ERROR, e) throw ApplicationRuntimeException(CollectionConstants.REPORT_GENERATION_ERROR, e) } setSourcePage("viewChallan") return CollectionConstants.REPORT }
This method generates the report for the requested challan
fun testIsMultiValued() { val meta = SpellCheckedMetadata() assertFalse(meta.isMultiValued("key")) meta.add("key", "value1") assertFalse(meta.isMultiValued("key")) meta.add("key", "value2") assertTrue(meta.isMultiValued("key")) }
Test for < code > isMultiValued ( ) < /code > method .
fun InitializeLoginAction() {}
Instantiates a new login action .
fun Instrument( soundbank: javax.sound.midi.Soundbank?, patch: javax.sound.midi.Patch, name: String?, dataClass: Class<*>? ) { super(soundbank, name, dataClass) this.patch = patch }
Constructs a new MIDI instrument from the specified < code > Patch < /code > . When a subsequent request is made to load the instrument , the sound bank will search its contents for this instrument 's < code > Patch < /code > , and the instrument will be loaded into the synthesizer at the bank and program location indicated by the < code > Patch < /code > object .
private fun putBytes( tgtBytes: ByteArray, tgtOffset: Int, srcBytes: ByteArray, srcOffset: Int, srcLength: Int ): Int { System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength) return tgtOffset + srcLength }
Put bytes at the specified byte array position .
fun HighlightTextView(context: Context?) { this(context, null) }
Instantiates a new Highlight text view .
fun trim() {}
Does nothing .
fun reset(data: ByteArray) { pos = 0 mark = 0 buf = data count = data.size }
Resets this < tt > BytesInputStream < /tt > using the given byte [ ] as new input buffer .
fun <T, V> ofObject( target: T, property: Property<T, V>?, evaluator: TypeEvaluator<V>?, vararg values: V ): ObjectAnimator? { val anim = ObjectAnimator(target, property) anim.setObjectValues(*values) anim.setEvaluator(evaluator) return anim }
Constructs and returns an ObjectAnimator that animates between Object values . A single value implies that that value is the one being animated to . Two values imply a starting and ending values . More than two values imply a starting value , values to animate through along the way , and an ending value ( these values will be distributed evenly across the duration of the animation ) .
private fun updateProgress(progress: Int) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress) } previousProgress = progress }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface .
fun execUpdateGeo( context: Context, latitude: Double, longitude: Double, selectedItems: SelectedFiles? ): Int { val where = QueryParameter() setWhereSelectionPaths(where, selectedItems) val values = ContentValues(2) values.put(SQL_COL_LAT, DirectoryFormatter.parseLatLon(latitude)) values.put(SQL_COL_LON, DirectoryFormatter.parseLatLon(longitude)) val resolver: ContentResolver = context.getContentResolver() return resolver.update( SQL_TABLE_EXTERNAL_CONTENT_URI, values, where.toAndroidWhere(), where.toAndroidParameters() ) }
Write geo data ( lat/lon ) media database. < br/ >
fun reset() { windowedBlockStream.reset() }
reset the environment to reuse the resource .
@Throws(InternalTranslationException::class) fun generate( environment: ITranslationEnvironment, offset: Long, instructions: MutableList<ReilInstruction?> ): Pair<org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize?, String?>? { Preconditions.checkNotNull(environment, "Error: Argument environment can't be null") Preconditions.checkNotNull(instructions, "Error: Argument instructions can't be null") Preconditions.checkArgument(offset >= 0, "Error: Argument offset can't be less than 0") val connected: String = environment.getNextVariableString() val negated: String = environment.getNextVariableString() instructions.add( ReilHelpers.createXor( offset, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, SyncStateContract.Helpers.SIGN_FLAG, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, SyncStateContract.Helpers.OVERFLOW_FLAG, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, connected ) ) instructions.add( ReilHelpers.createXor( offset + 1, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, connected, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, "1", org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, negated ) ) return Pair<org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize, String>( org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, negated ) }
Generates code for the NotLess condition .
fun isFinished(): Boolean { return isCompleted() || isFailed() || isCanceled() }
< p > Finished means it is either completed , failed or canceled. < /p >
private fun drawBackground() { val rect: java.awt.Rectangle = getClientArea() cachedGC.setForeground(gradientStart) cachedGC.setBackground(gradientEnd) cachedGC.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height / 2, true) cachedGC.setForeground(gradientEnd) cachedGC.setBackground(gradientStart) cachedGC.fillGradientRectangle(rect.x, rect.height / 2, rect.width, rect.height / 2, true) }
Draw the background
fun read(buf: ByteArray) { var numToRead = buf.size if (position + numToRead > buffer.length) { numToRead = buffer.length - position System.arraycopy(buffer, position, buf, 0, numToRead) for (i in numToRead until buf.size) { buf[i] = 0 } } else { System.arraycopy(buffer, position, buf, 0, numToRead) } position += numToRead }
Reads up to < tt > buf.length < /tt > bytes from the stream into the given byte buffer .
fun QueryExecutionTimeoutException(msg: String?) { super(msg) }
Constructs an instance of < code > QueryExecutionTimeoutException < /code > with the specified detail message .
private fun displayInternalServerError() { alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle( context, getResources().getString(R.string.title_head_connection_error), getResources().getString(R.string.error_internal_server), getResources().getString(R.string.button_ok), null ) alertDialog.show() }
Displays an internal server error message to the user .
fun updateOrdering(database: SQLiteDatabase, originalPosition: Long, newPosition: Long) { Log.d("ItemDAO", "original: $originalPosition, newPosition:$newPosition") if (originalPosition > newPosition) { database.execSQL( UPDATE_ORDER_MORE, arrayOf(newPosition.toString(), originalPosition.toString()) ) } else { database.execSQL( UPDATE_ORDER_LESS, arrayOf(originalPosition.toString(), newPosition.toString()) ) } }
Updates the orderings between the original and new positions
fun onAdChanged() { notifyDataSetChanged() }
Raised when the number of ads have changed . Adapters that implement this class should notify their data views that the dataset has changed .
@Throws(IOException::class) fun createSocket(host: InetAddress?, port: Int): Socket { val socket: Socket = createSocket() connectSocket(socket, InetSocketAddress(host, port)) return socket }
Creates a socket and connect it to the specified remote address on the specified remote port .
@Throws(Exception::class) fun openExistingFileForWrite(name: String?): sun.rmi.log.ReliableLog.LogFile? { val logfile = File(name) val tf: sun.rmi.log.ReliableLog.LogFile = sun.rmi.log.ReliableLog.LogFile(logfile) tf.openWrite() return tf }
Open an existing file for writing .
fun AgeGreaterThanCondition(age: Int) { this.age = age }
Creates a new AgeGreaterThanCondition .
@ DSComment ( "Private Method" ) @ DSBan ( DSCat . PRIVATE_METHOD ) @ DSGenerator ( tool_name = "Doppelganger" , tool_version = "2.0" , generated_on = "2013-12-30 12:57:24.266 -0500" , hash_original_method = "542A19C49303D6524BE63DEB812200B5" , hash_generated_method = "433131C2E635F21E7867A70992F1749C" ) private ComparableTimSort ( Object [ ] a ) { this . a = a ; int len = a . length ; @ SuppressWarnings ( { "unchecked" , "UnnecessaryLocalVariable" } ) Object [ ] newArray = new Object [ len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len > > > 1 : INITIAL_TMP_STORAGE_LENGTH ] ; tmp = newArray ; int stackLen = ( len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 19 : 40 ) ; runBase = new int [ stackLen ] ; runLen = new int [ stackLen ] ; }
Creates a TimSort instance to maintain the state of an ongoing sort .
fun compare(left: Date, right: Double): Int { return compare( left.getTime() / 1000, DateTimeUtil.getInstance().toDateTime(right).getTime() / 1000 ) }
compares a Date with a double
fun removeGraphNode(node: SpaceEffGraphNode) { if (node === _firstNode) { if (node === _lastNode) { _lastNode = null _firstNode = _lastNode } else { _firstNode = node.getNext() } } else if (node === _lastNode) { _lastNode = node.getPrev() } node.remove() numberOfNodes-- }
Remove a node from the graph .
fun <T> fromJSONString(jsonString: String?, selectAs: String?): JSONProperty<T>? { return fromJSONFunction(jdk.nashorn.internal.runtime.JSONFunctions.json(jsonString), selectAs) }
Construct a JSONProperty from a JSON string and with the given alias , e.g . `` 'hello ' AS greeting '' . This is a convenience method equivalent to < code > fromJSONFunction ( JSONFunctions.json ( jsonString ) , selectAs ) < /code >
fun addGroupChatComposingStatus(chatId: String?, status: Boolean) { synchronized(getImsServiceSessionOperationLock()) { mGroupChatComposingStatusToNotify.put( chatId, status ) } }
Adds the group chat composing status to the map to enable re-sending upon media session restart
@Throws(IOException::class) fun createCmds(runConfiguration: ChromeRunnerRunOptions): Array<String?>? { val commands: ArrayList<String> = ArrayList() commands.add(nodeJsBinary.get().getBinaryAbsolutePath()) val nodeOptions = System.getProperty(NODE_OPTIONS) if (nodeOptions != null) { for (nodeOption in nodeOptions.split(" ".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) { commands.add(nodeOption) } } val elfData: StringBuilder = getELFCode( runConfiguration.getInitModules(), runConfiguration.getExecModule(), runConfiguration.getExecutionData() ) val elf: File = createTempFileFor(elfData.toString()) commands.add(elf.getCanonicalPath()) return commands.toArray(arrayOf()) }
Creates commands for calling Node.js on command line . Data wrapped in passed parameter is used to configure node itself , and to generate file that will be executed by Node .
fun mulComponentWise(other: Matrix4x3dc?): Matrix4x3d? { return mulComponentWise(other, this) }
Component-wise multiply < code > this < /code > by < code > other < /code > .
@Throws(Exception::class) fun testTypes() { try { this.stmt.execute("DROP TABLE IF EXISTS typesRegressTest") this.stmt.execute("CREATE TABLE typesRegressTest (varcharField VARCHAR(32), charField CHAR(2), enumField ENUM('1','2')," + "setField SET('1','2','3'), tinyblobField TINYBLOB, mediumBlobField MEDIUMBLOB, longblobField LONGBLOB, blobField BLOB)") this.rs = this.stmt.executeQuery("SELECT * from typesRegressTest") val rsmd: ResultSetMetaData = this.rs.getMetaData() val numCols: Int = rsmd.getColumnCount() for (i in 0 until numCols) { val columnName: String = rsmd.getColumnName(i + 1) val columnTypeName: String = rsmd.getColumnTypeName(i + 1) println("$columnName -> $columnTypeName") } } finally { this.stmt.execute("DROP TABLE IF EXISTS typesRegressTest") } }
Tests for types being returned correctly
fun deleteFile(context: Context, file: File): Boolean { var success: Boolean = file.delete() if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val document: DocumentFile = getDocumentFile(context, file, false, false) success = document != null && document.delete() } if (!success && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { val resolver: ContentResolver = context.getContentResolver() success = try { val uri: Uri? = null if (uri != null) { resolver.delete(uri, null, null) } !file.exists() } catch (e: Exception) { Log.e(TAG, "Error when deleting file " + file.getAbsolutePath(), e) return false } } if (success) scanFile(context, arrayOf(file.getPath())) return success }
Delete a file . May be even on external SD card .
fun displayInfoLine(infoLine: String?, labelDesignator: Int) { if (infoLineHolder != null) { setLabel( if (infoLine != null && infoLine.length > 0) infoLine else fudgeString, labelDesignator ) } }
Display a line of text in a designated info line .
fun addMember( parentType: sun.reflect.generics.tree.BaseType?, memberType: sun.reflect.generics.tree.BaseType? ): DependenceResult? { Preconditions.checkNotNull(parentType, "IE02762: Parent type can not be null.") Preconditions.checkNotNull(memberType, "IE02763: Member type can not be null.") val memberTypeNode: Node = Preconditions.checkNotNull( containedRelationMap.get(memberType), "Type node for member type must exist prior to adding a member." ) val parentNode: Node = Preconditions.checkNotNull( containedRelationMap.get(parentType), "Type node for member parent must exist prior to adding a member" ) if (willCreateCycle(parentType, memberType)) { return DependenceResult(false, ImmutableSet.of<sun.reflect.generics.tree.BaseType>()) } containedRelation.createEdge(memberTypeNode, parentNode) val search = TypeSearch(containedRelationMap.inverse()) search.start(containedRelation, containedRelationMap.get(parentType)) return DependenceResult(true, search.getDependentTypes()) }
Adds a member to the dependence graph and returns the set of base types that are affected by the changed compound type . This method assumes that all base type nodes that correspond to the member base type already exist .
int [ ] decodeStart ( BitArray row ) throws NotFoundException { int endStart = skipWhiteSpace ( row ) ; int [ ] startPattern = findGuardPattern ( row , endStart , START_PATTERN ) ; this . narrowLineWidth = ( startPattern [ 1 ] - startPattern [ 0 ] ) > > 2 ; validateQuietZone ( row , startPattern [ 0 ] ) ; return startPattern ; }
Identify where the start of the middle / payload section starts .
fun contains(array: IntArray?, value: Int): Boolean { return indexOf(array, value) !== -1 }
Returns < code > true < /code > if an array contains given value .
fun acosh(value: Double): Double { if (value <= 1.0) { return if (ANTI_JIT_OPTIM_CRASH_ON_NAN) { if (value < 1.0) Double.NaN else value - 1.0 } else { if (value == 1.0) 0.0 else Double.NaN } } val result: Double if (value < ASINH_ACOSH_SQRT_ELISION_THRESHOLD) { result = log(value + sqrt(value * value - 1.0)) } else { result = LOG_2 + log(value) } return result }
Some properties of acosh ( x ) = log ( x + sqrt ( x^2 - 1 ) ) : 1 ) defined on [ 1 , +Infinity [ 2 ) result in ] 0 , +Infinity [ ( by convention , since cosh ( x ) = cosh ( -x ) ) 3 ) acosh ( 1 ) = 0 4 ) acosh ( 1+epsilon ) ~= log ( 1 + sqrt ( 2*epsilon ) ) ~= sqrt ( 2*epsilon ) 5 ) lim ( acosh ( x ) , x- > +Infinity ) = +Infinity ( y increasing logarithmically slower than x )
fun fireDataStatusEEvent(AD_Message: String?, info: String?, isError: Boolean) { m_mTable.fireDataStatusEEvent(AD_Message, info, isError) }
Create and fire Data Status Error Event
fun AttributeDefinition(attrs: TextAttributeSet, beginIndex: Int, endIndex: Int) { this.attrs = attrs this.beginIndex = beginIndex this.endIndex = endIndex }
Create new AttributeDefinition .
fun consumeGreedy(greedyToken: String) { if (greedyToken.length < sval.length()) { pushBack() setStartPosition(getStartPosition() + greedyToken.length) sval = sval.substring(greedyToken.length) } }
Consumes a substring from the current sval of the StreamPosTokenizer .
@Throws(HexFormatException::class) fun hexToDecimal(hex: String): Int { var decimalValue = 0 for (i in 0 until hex.length) { if (!(hex[i] >= '0' && hex[i] <= '9' || hex[i] >= 'A' && hex[i] <= 'F')) throw HexFormatException( hex ) val hexChar = hex[i] decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar) } return decimalValue }
Converts a hex string into a decimal number and throws a HexFormatException if the string is not a hex string
@Throws(NotFoundException::class, ChecksumException::class, FormatException::class) fun decode(image: BinaryBitmap?): Result? { return decode(image, null) }
Locates and decodes a QR code in an image .
fun listRawBackup(ignore: Boolean): BackupFileSet? { val clusterBackupFiles = BackupFileSet(this.quorumSize) val errorList: List<String> = ArrayList() try { val backupTasks: List<BackupProcessor.BackupTask<List<BackupSetInfo>>> = BackupProcessor(getHosts(), Arrays.asList(ports.get(2)), null).process( ListBackupCallable(), false ) var result: Throwable? = null for (task in backupTasks) { try { clusterBackupFiles.addAll( task.getResponse().getFuture().get(), task.getRequest().getNode() ) log.info("List backup on node({})success", task.getRequest().getHost()) } catch (e: CancellationException) { log.warn( "The task of listing backup on node({}) was canceled", task.getRequest().getHost(), e ) } catch (e: InterruptedException) { log.error( java.lang.String.format( "List backup on node(%s:%d) failed", task.getRequest().getHost(), task.getRequest().getPort() ), e ) result = result ?: e errorList.add(task.getRequest().getNode()) } catch (e: ExecutionException) { val cause: Throwable = e.getCause() if (ignore) { log.warn( java.lang.String.format( "List backup on node(%s:%d) failed.", task.getRequest().getHost(), task.getRequest().getPort() ), cause ) } else { log.error( java.lang.String.format( "List backup on node(%s:%d) failed.", task.getRequest().getHost(), task.getRequest().getPort() ), cause ) } result = result ?: cause errorList.add(task.getRequest().getNode()) } } if (result != null) { if (result is Exception) { throw (result as Exception?)!! } else { throw Exception(result) } } } catch (e: Exception) { val cause = if (e.cause == null) e else e.cause!! if (ignore) { log.warn( "List backup on nodes({}) failed, but ignore the errors", errorList.toString(), cause ) } else { log.error("Exception when listing backups", e) throw BackupException.fatals.failedToListBackup(errorList.toString(), cause) } } return clusterBackupFiles }
Get a list of backup sets info
fun CountingIdlingResource(resourceName: String, debugCounting: Boolean) { require(!TextUtils.isEmpty(resourceName)) { "Resource name must not be empty or null" } this.resourceName = resourceName this.debugCounting = debugCounting }
Creates a CountingIdlingResource .
fun create(thisSize: String): ImageReuseInfo? { val list = ArrayList<String>() var canBeReused = false for (i in 0 until mSizeList.length) { val size: String = mSizeList.get(i) if (!canBeReused && thisSize == size) { canBeReused = true continue } if (canBeReused && thisSize != size) { list.add(size) } } return if (list.size() === 0) { ImageReuseInfo(thisSize, null) } else { val sizeList = arrayOfNulls<String>(list.size()) list.toArray(sizeList) ImageReuseInfo(thisSize, sizeList) } }
Find out the size list can be re-sued .
fun sync(address: Address?, size: Int) { SysCall.sysCall.sysSyncCache(address, size) }
Synchronize a region of memory : force data in dcache to be written out to main memory so that it will be seen by icache when instructions are fetched back .
fun MonthDateFormat(locale: Locale?) { this(TimeZone.getDefault(), locale, 1, true, false) }
Creates a new instance for the specified time zone .
fun testConnectorSecuritySettingsSSL_alias_not_defined() { resetSecuritySystemProperties() var authInfo: sun.net.www.protocol.http.AuthenticationInfo? = null try { authInfo = SecurityHelper.loadAuthenticationInformation( "test.ssl.alias.not.defined.security.properties", true, TUNGSTEN_APPLICATION_NAME.CONNECTOR ) } catch (e: java.rmi.ServerRuntimeException) { assertTrue("There should not be any exception thrown", false) } catch (e: javax.naming.ConfigurationException) { assertFalse("That should not be this kind of Exception being thrown", true) } resetSecuritySystemProperties() }
Confirm behavior when connector.security.use.SSL=true and alias are not defined This shows that it uses first alias it finds
@Synchronized fun add(x: Double, y: Double) { add(x, y, 0.0) }
Adds a new value to the series .
@Synchronized fun add(x: Double, y: Double) { add(x, y, 0.0) }
This method is called when a fatal error occurs during parsing . This method rethrows the exception
fun run() { amIActive = true if (args.length < 2) { showFeedback("Plugin parameters have not been set properly.") return } val inputHeader: String = args.get(0) val outputHeader: String = args.get(1) if (inputHeader == null || outputHeader == null) { showFeedback("One or more of the input parameters have not been set properly.") return } try { var row: Int var col: Int var z: Double var progress: Int var oldProgress = -1 var data: DoubleArray val inputFile = WhiteboxRaster(inputHeader, "r") val rows: Int = inputFile.getNumberRows() val cols: Int = inputFile.getNumberColumns() val noData: Double = inputFile.getNoDataValue() val outputFile = WhiteboxRaster(outputHeader, "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, noData) outputFile.setPreferredPalette(inputFile.getPreferredPalette()) row = 0 while (row < rows) { data = inputFile.getRowValues(row) col = 0 while (col < cols) { z = data[col] if (z != noData) { outputFile.setValue(row, col, Math.asin(z)) } col++ } progress = (100f * row / (rows - 1)).toInt() if (progress != oldProgress) { oldProgress = progress updateProgress(progress) if (cancelOp) { cancelOperation() return } } row++ } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.") outputFile.addMetadataEntry("Created on " + Date()) inputFile.close() outputFile.close() returnData(outputHeader) } catch (oe: OutOfMemoryError) { myHost.showFeedback("An out-of-memory error has occurred during operation.") } catch (e: Exception) { myHost.showFeedback("An error has occurred during operation. See log file for details.") myHost.logException("Error in " + getDescriptiveName(), e) } finally { updateProgress("Progress: ", 0) amIActive = false myHost.pluginComplete() } }
Used to execute this plugin tool .
fun addMoreComponents(cnt: Container, components: Array<Component?>?, areThereMore: Boolean) { val ia: InfiniteScrollAdapter = cnt.getClientProperty("cn1\$infinite") as InfiniteScrollAdapter ia.addMoreComponents(components, areThereMore) }
Invoke this method to add additional components to the container , if you use addComponent/removeComponent you will get undefined behavior . This is a convenience method saving the need to keep the InfiniteScrollAdapter as a variable
fun progress(texture: CCTexture2D?): CCProgressTimer? { return CCProgressTimer(texture) }
Creates a progress timer with the texture as the shape the timer goes through
fun EntityMappingModelImpl() { super() }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
fun match(): MatchResult? { check(matchSuccessful) return matcher.toMatchResult() }
Returns the result of the last matching operation . < p > The next* and find* methods return the match result in the case of a successful match .
fun dispatch(event: IEvent) { val eventType: Class<out IEvent?> = event.getClass() Discord4J.logger.debug("Dispatching event of type {}.", eventType.simpleName) if (listenerMap.containsKey(eventType)) { for (listener in listenerMap.get(eventType)) { listener.receive(event) } } }
Sends an IEvent to all listeners that listen for that specific event .
fun createMouthComboBox(): javax.swing.JComboBox? { val cb: javax.swing.JComboBox = javax.swing.JComboBox() fillComboBox(cb) cb.addActionListener(this) return cb }
Creates the mouth combo box .
fun leverageForRule( premise: AprioriItemSet?, consequence: AprioriItemSet, premiseCount: Int, consequenceCount: Int ): Double { val coverageForItemSet = consequence.m_counter as Double / m_totalTransactions as Double val expectedCoverageIfIndependent = premiseCount.toDouble() / m_totalTransactions as Double * (consequenceCount.toDouble() / m_totalTransactions as Double) return coverageForItemSet - expectedCoverageIfIndependent }
Outputs the leverage for a rule . Leverage is defined as : < br > prob ( premise & consequence ) - ( prob ( premise ) * prob ( consequence ) )
fun RdKNNNode(capacity: Int, isLeaf: Boolean) { super(capacity, isLeaf, RdKNNEntry::class.java) }
Creates a new RdKNNNode object .
private fun adaptGridViewHeight() { if (gridView is DividableGridView) { (gridView as DividableGridView).adaptHeightToChildren() } }
Adapts the height of the grid view , which is used to show the bottom sheet 's items .
fun validateOnStatus() { if (Command.STATUS.equals(getCommand())) { } }
Validates the arguments passed to the Builder when the 'status ' command has been issued .
fun eagerCheck(): Optional<Boolean?>? { return Optional.ofNullable(this.eagerCheck) }
whether check errors as more as possible
fun newInstance(song: Song?): NewPlaylistFragment? { val fragment = NewPlaylistFragment() val bundle = Bundle() bundle.putParcelable(KEY_SONG, song) fragment.setArguments(bundle) return fragment }
Creates a new instance of the New Playlist dialog fragment to create a new playlist and add a song to it .
@DSSink([DSSinkKind.LOG]) @DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:29:19.771 -0500", hash_original_method = "06AF2B97EC9C8BBE1303A237FE727449", hash_generated_method = "103A7E1B02C228D1981B721CBC7DAC4C" ) fun updateCursor(view: View, left: Int, top: Int, right: Int, bottom: Int) { checkFocus() synchronized(mH) { if (mServedView !== view && (mServedView == null || !mServedView.checkInputConnectionProxy( view )) || mCurrentTextBoxAttribute == null || mCurMethod == null ) { return } mTmpCursorRect.set(left, top, right, bottom) if (!mCursorRect.equals(mTmpCursorRect)) { if (DEBUG) Log.d(TAG, "updateCursor") try { if (DEBUG) Log.v(TAG, "CURSOR CHANGE: $mCurMethod") mCurMethod.updateCursor(mTmpCursorRect) mCursorRect.set(mTmpCursorRect) } catch (e: RemoteException) { Log.w(TAG, "IME died: $mCurId", e) } } } }
Report the current cursor location in its window .
fun buildTextAnnotation( corpusId: String?, textId: String?, text: String?, tokens: Array<String?>, sentenceEndPositions: IntArray, sentenceViewGenerator: String?, sentenceViewScore: Double ): TextAnnotation? { require(sentenceEndPositions[sentenceEndPositions.size - 1] == tokens.size) { "Invalid sentence boundary. Last element should be the number of tokens" } val offsets: Array<IntPair> = TokenUtils.getTokenOffsets(text, tokens) assert(offsets.size == tokens.size) val ta = TextAnnotation(corpusId, textId, text, offsets, tokens, sentenceEndPositions) val view = SpanLabelView(ViewNames.SENTENCE, sentenceViewGenerator, ta, sentenceViewScore) var start = 0 for (s in sentenceEndPositions) { view.addSpanLabel(start, s, ViewNames.SENTENCE, 1.0) start = s } ta.addView(ViewNames.SENTENCE, view) val tokView = SpanLabelView(ViewNames.TOKENS, sentenceViewGenerator, ta, sentenceViewScore) for (tokIndex in tokens.indices) { tokView.addSpanLabel(tokIndex, tokIndex + 1, tokens[tokIndex], 1.0) } ta.addView(ViewNames.TOKENS, tokView) return ta }
instantiate a TextAnnotation using a SentenceViewGenerator to create an explicit Sentence view
import java.util.* private fun guessContentType(url: String): String? { var url = url url = url.lowercase(Locale.getDefault()) return if (url.endsWith(".webm")) { "video/webm" } else if (url.endsWith(".mp4")) { "video/mp4" } else if (url.matches(".*\\.jpe?g")) { "image/jpeg" } else if (url.endsWith(".png")) { "image/png" } else if (url.endsWith(".gif")) { "image/gif" } else { "application/octet-stream" } }
Guess a content type from the URL .
fun FilteredTollHandler(simulationEndTime: Double, numberOfTimeBins: Int) { this(simulationEndTime, numberOfTimeBins, null, null) LOGGER.info("No filtering is used, result will include all links, persons from all user groups.") }
No filtering will be used , result will include all links , persons from all user groups .
fun isSecondHandVisible(): Boolean { return secondHandVisible }
Return secondHandVisible
fun addStylesheet(href: String?, type: String?): XMLDocument? { val pi = PI() pi.setTarget("xml-stylesheet").addInstruction("href", href).addInstruction("type", type) prolog.addElement(pi) return this }
This adds a stylesheet to the XML document .
fun GenericMTreeDistanceSearchCandidate(mindist: Double, nodeID: Int, routingObjectID: DBID?) { this.mindist = mindist this.nodeID = nodeID this.routingObjectID = routingObjectID }
Creates a new heap node with the specified parameters .
private fun lf_delta1(x: Int): Int { return lf_S(x, 17) xor lf_S(x, 19) xor lf_R(x, 10) }
logical function delta1 ( x ) - xor of results of right shifts/rotations
fun extractBestMaxRuleParse(start: Int, end: Int, sentence: List<String?>?): Tree<String?>? { return extractBestMaxRuleParse1(start, end, 0, sentence) }
Returns the best parse , the one with maximum expected labelled recall . Assumes that the maxc* arrays have been filled .
fun lastIndexOf(ch: Char): Int { return lastIndexOf(ch, size - 1) }
Searches the string builder to find the last reference to the specified char .
fun m00(m00: Float): Matrix4x3f? { this.m00 = m00 properties = properties and (PROPERTY_IDENTITY or PROPERTY_TRANSLATION).inv() return this }
Set the value of the matrix element at column 0 and row 0
@Throws(Exception::class) private fun processTargetPortsToFormHSDs( hdsApiClient: HDSApiClient, storage: StorageSystem, targetURIList: List<URI>, hostName: String, exportMask: ExportMask, hostModeInfo: Pair<String, String>?, systemObjectID: String ): List<HostStorageDomain?>? { val hsdList: List<HostStorageDomain> = ArrayList<HostStorageDomain>() var hostMode: String? = null var hostModeOption: String? = null if (hostModeInfo != null) { hostMode = hostModeInfo.first hostModeOption = hostModeInfo.second } for (targetPortURI in targetURIList) { val storagePort: StoragePort = dbClient.queryObject(StoragePort::class.java, targetPortURI) val storagePortNumber: String = getStoragePortNumber(storagePort.getNativeGuid()) val dataSource: DataSource = dataSourceFactory.createHSDNickNameDataSource(hostName, storagePortNumber, storage) val hsdNickName: String = customConfigHandler.getComputedCustomConfigValue( CustomConfigConstants.HDS_HOST_STORAGE_DOMAIN_NICKNAME_MASK_NAME, storage.getSystemType(), dataSource ) if (Transport.IP.name().equalsIgnoreCase(storagePort.getTransportType())) { log.info("Populating iSCSI HSD for storage: {}", storage.getSerialNumber()) val hostGroup = HostStorageDomain( storagePortNumber, exportMask.getMaskName(), HDSConstants.ISCSI_TARGET_DOMAIN_TYPE, hsdNickName ) hostGroup.setHostMode(hostMode) hostGroup.setHostModeOption(hostModeOption) hsdList.add(hostGroup) } if (Transport.FC.name().equalsIgnoreCase(storagePort.getTransportType())) { log.info("Populating FC HSD for storage: {}", storage.getSerialNumber()) val hostGroup = HostStorageDomain( storagePortNumber, exportMask.getMaskName(), HDSConstants.HOST_GROUP_DOMAIN_TYPE, hsdNickName ) hostGroup.setHostMode(hostMode) hostGroup.setHostModeOption(hostModeOption) hsdList.add(hostGroup) } } return hsdList }
This routine iterates through the target ports and prepares a batch of HostStorageDomain Objects with required information .
private fun isInResults(results: ArrayList<Media>, id: String): Int { var i = 0 for (item in results) { if (item.videoId.equals(id)) return i i++ } return -1 }
Test if there is an item that already exists
private fun parseToken(terminators: CharArray): String? { var ch: Char i1 = pos i2 = pos while (hasChar()) { ch = chars.get(pos) if (isOneOf(ch, terminators)) { break } i2++ pos++ } return getToken(false) }
Parse out a token until any of the given terminators is encountered .
@Ignore("TODO: disabled because rather than throwing an exception, getAll catches all exceptions and logs a warning message") @Test fun testNonColocatedGetAll() { doNonColocatedbulkOp(OP.GETALL) }
disabled because rather than throwing an exception , getAll catches all exceptions and logs a warning message
fun buildMatchObject( sequenceIdentifier: String?, model: String?, signatureLibraryRelease: String?, seqStart: Int, seqEnd: Int, cigarAlign: String?, score: Double?, profileLevel: ProfileScanRawMatch.Level?, patternLevel: PatternScanMatch.PatternScanLocation.Level? ): PfScanRawMatch? { return HamapRawMatch( sequenceIdentifier, model, signatureLibraryRelease, seqStart, seqEnd, cigarAlign, score, profileLevel ) }
Method to be implemented that builds the correct kind of PfScanRawMatch .
private fun updateServerStatus() { try { val page = StringBuffer() page.append("<?php\n") page.append("session_start();\n") page.append("\$username = 'Guest';\n") page.append("if (array_key_exists('username', $_SESSION)) { \$username = $_SESSION['username']; }\n") page.append("?>\n") page.append("<html>\n<head>\n <title>R Server</title>\n") page.append(" <script>\n") page.append(" function reload() { \n") page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n") page.append(" if (!isIE) location.reload();\n") page.append(" }\n") page.append( """ ${" setTimeout(reload, $pageRefreshTime"}) """.trimIndent() ) page.append(" </script>\n") page.append(" <link rel=\"stylesheet\" type=\"text/css\" href=\"rserver.css\">\n") page.append("</head>\n<body>\n") page.append("<div id=\"MainDiv\">\n\n") page.append("<div id=\"HeaderDiv\">\n") page.append(" <div id=\"NavHeaderDiv\"></div>\n") page.append(" <div id=\"NavLogo\"></div>\n") page.append(" <a id=\"newHeaderNavigation-logo\" href=\"/RServer\" title=\"R Server\"></a>\n") page.append(" <ul id=\"NavBar\">\n") page.append(" <li><a href=\"https://github.com/bgweber/RServer\">EA RServer</a></li>\n") page.append(" <li><a href=\"NewTask.php\">Submit New Task</a>\n") page.append(" <li><a href=\"Reports.php\">Reports</a></li>\n") page.append(" <li><a href=\"logs\">Server Logs</a></li>\n") page.append(" <li><a href=\"Rout\">Script Results</a></li>\n") page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n") page.append(" </ul>\n\n") page.append("</div>\n\n") page.append(" <div id=\"SubHeaderDiv\">\n") page.append(" <h2 id=\"RHeader\">R Server: </h2>\n") page.append( """ <?php if ((time() - ${System.currentTimeMillis() / 1000}) < 10) { echo "<h2 id=\"ServerOnline\">Online</h2>"; } else { echo "<h2 id=\"ServerOffline\">Offline</h2>"; } ?> """.trimIndent() ) page.append(" </div>\n\n") page.append(" <div id=\"ContentDiv\">\n") page.append(" <script>\n") page.append(" var isIE = /*@cc_on!@*/false || !!document.documentMode;\n") page.append(" if (isIE) document.write('<p><h2>Note: Auto-reload is disabled for Internet Explorer. Please use Chrome, Firefox, or Opera.<h2>'); \n") page.append(" </script>\n") page.append("<h3 id=\"StatsHeader\">Server Statistics</h3>\n") page.append("<table id=\"StatsTable\">\n") page.append(" <thead>\n") page.append(" <th>Property</th>\n <th>Value</th>\n") page.append(" </thead>\n") if (fullHostName != null) { page.append( """ ${" <tr><td>Server Name</td><td>$fullHostName"}</td></tr> """.trimIndent() ) } page.append( """ ${" <tr><td>Server Updated</td><td>" + Date(System.currentTimeMillis()).toString()}</td></tr> """.trimIndent() ) val runtime = Runtime.getRuntime() val memory = ((runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024).toString() + " / " + runtime.totalMemory() / 1024 / 1024 + " MB" try { var totalMem: Double = sigar.getMem().getTotal() / 1024 / 1024 / 1024.0 var usedMem: Double = (sigar.getMem().getTotal() - sigar.getMem().getFree()) / 1024 / 1024 / 1024.0 cpuLoad = 1 - sigar.getCpuPerc().getIdle() totalMem = (totalMem * 10).toInt() / 10.0 usedMem = (usedMem * 10).toInt() / 10.0 page.append(" <tr><td>Server CPU Usage</td><td>" + (cpuLoad * 1000) as Int / 10.0 + "%</td></tr>\n") page.append(" <tr><td>Server Memory</td><td>$usedMem / $totalMem GB</td></tr>\n") } catch (e: Exception) { log("ERROR: unable to update system stats: " + e.message) } page.append(" <tr><td>Application Memory</td><td>$memory</td></tr>\n") page.append( """ <tr><td>Thread Count</td><td>${Thread.activeCount()}</td></tr> """ ) page.append( """ <tr><td>Git Updated</td><td>${if (lastPerforceUpdate > 0) Date(lastPerforceUpdate).toString() else "No history"}</td></tr> """ ) page.append( """ ${" <tr><td>Server Launched</td><td>" + Date(bootTime).toString()}</td></tr> """.trimIndent() ) page.append( """ ${" <tr><td>Server Version</td><td>$ServerDate"}</td></tr> """.trimIndent() ) page.append("</table>\n\n") page.append("<h3 id=\"LogHeader\">R Server Reports</h3>\n") page.append("<ul id=\"LogList\">\n") page.append(" <li><a href=\"reports/RServer/RServerReport.html\">R Server Activity</a></li>\n") page.append(" <li><a href=\"reports/RServer/RServerTasks.html\">Task Report</a></li>\n") page.append("</ul>\n") page.append("<h3 id=\"RunningHeader\">Running Tasks</h3>\n") page.append("<table id=\"RunningTable\">\n") page.append(" <thead>\n") page.append( """ <th>Task Name</th> <th>Log File</th> <th>Start Time</th> <th>Duration</th> <th>Runtime Parameters</th> <th>Owner</th> <th>End Process</th> """ ) page.append(" </thead>\n") synchronized(this@RServer) { for (task in runningTasks.values()) { val startTime: Long = task.getStartTime() val duration = (System.currentTimeMillis() - startTime) / 1000 page.append(" <tr>\n") page.append(" <td>" + (if (task.getShinyApp()) "<a href=\"" + task.getShinyUrl() + "\">" else "") + task.getTaskName() + (if (task.getShinyApp()) "</a>" else "") + "</td>") if (task.getrScript().toLowerCase().contains(".r") || task.getIsPython()) { val link = "<a href=\"Rout.php?task=" + task.getTaskName() + "&log=" + (if (task.getrScript() .contains(".r") ) task.getrScript() + ".Rout" else task.getrScript().split("\\.") .get(0) + ".Rout") + "\">" + task.getrScript() + "</a>" page.append("\n <td>$link</td>") } else { page.append("\n <td> </td>") } page.append( """ <td>${Date(startTime).toString()}</td>""" ) page.append( """ <td>${if (task.getShinyApp()) "" else (duration / 60).toString() + " m " + duration % 60 + " s"}</td>""" ) page.append( """ <td>${task.getParameters()}</td>""" ) page.append( """ <td>${task.getOwner()}</td>""" ) if (PerforceTask.equalsIgnoreCase(task.getTaskName())) { page.append("\n <td> </td>") } else { page.append( """${ """ <td><form onsubmit="return confirm('Are you sure?')" action="KillTask.php" method="post"> <input type="hidden" name="name" value="${task.getTaskName()}""" }" /> <button >Terminate</button> </form></td>""" ) } page.append("\n </tr>\n") } } page.append("</table>\n\n") page.append("<h3 id=\"LogHeader\">Recent Log Entries</h3>\n") synchronized(this@RServer) { page.append("<ul id=\"LogList\">\n") for (log in logEntries) { if (log.contains("ERROR:")) { page.append(" <li class=\"FontLogError\">$log</li>\n") } else { page.append(" <li>$log</li>\n") } } page.append("</ul>\n\n") } page.append("<h3 id=\"SchedulesHeader\">Scheduled Tasks</h3>\n") page.append("<table id=\"ScheduleTable\">\n") page.append(" <thead>\n") page.append( """ <th>Task Name</th> <th>R Script</th> <th>Runtime Parameters</th> <th>Frequency</th> <th>Next Run Time</th> <th>Owner</th> <th>Run Now</th> """ ) page.append(" </thead>\n") page.append("<ul id=\"LogList\">\n") if (schedulePath.split("//").length > 1) { page.append( """ ${" <li>Schedule File: //" + schedulePath.split("//").get(1)}</li> """.trimIndent() ) } else { page.append( """ ${" <li>Schedule File: $schedulePath"}</li> """.trimIndent() ) } page.append("</ul>\n") for (schedule in regularSchedules) { page.append(" <tr>\n") page.append( """${ " <td>" + schedule.getTaskName() .replace("_", " ") + "</td>\n " + "<td>" + schedule.getrScript().replace( "_", " " ) + "</td>\n " + "<td>" + schedule.getParameters() + "</td>\n " + "<td>" + (if (schedule.getFrequency() === Schedule.Frequency.Now) "Startup" else schedule.getFrequency()) + "</td>\n <td>" + (if (schedule.getFrequency() === Schedule.Frequency.Now || schedule.getFrequency() === Schedule.Frequency.Never) " " else Date( schedule.getNextRunTime() ).toString()) + "</td>\n <td>" + schedule.getOwner() + "</td>\n " + "<td><form onsubmit=\"return confirm('Are you sure?')\"" + " action=\"SubmitTask.php\" method=\"post\">" + "\n <input type=\"hidden\" name=\"name\" value=\"" + schedule.getTaskName() + "\" />" + "\n <input type=\"hidden\" name=\"path\" value=\"" + schedule.getPerforcePath() + "\" />" + "\n <input type=\"hidden\" name=\"rscript\" value=\"" + schedule.getrScript() + "\" />" + "\n <input type=\"hidden\" name=\"email\" value=\"" + schedule.getOwner() + "\" />" + "\n <input type=\"hidden\" name=\"sendemail\" value=\"" + schedule.getEmailOnSuccess() + "\" />" + "\n <input type=\"hidden\" name=\"params\" value=\"" + schedule.getParameters() + "\" />" + "\n <input type=\"hidden\" name=\"shiny\" value=\"" + schedule.getShinyApp() }" /> <button>Start</button> </form></td> """ ) page.append(" </tr>\n") } page.append("</table>\n\n") page.append("<h3 id=\"CompletedHeader\">Completed Tasks</h3>\n") page.append("<table id=\"CompletedTable\">\n") page.append(" <thead>\n") page.append( """ <th>Task Name</th> <th>Completion Time</th> <th>Duration</th> <th>Runtime Parameters</th> <th>Outcome</th><th>.Rout log</th> <th>Owner</th> """ ) page.append(" </thead>\n") synchronized(this@RServer) { for (task in completed) { val duration: Long = (task.getEndTime() - task.getStartTime()) / 1000 page.append(" <tr>\n") page.append( """${" <td>" + task.getTaskName().replace("_", " ")}</td> <td>""" ) page.append( """${" " + Date(task.getEndTime()).toString()}</td> <td>""" ) page.append( """ ${(duration / 60).toString() + " m " + duration % 60 + " s "}</td> <td>""" ) page.append( """${" " + task.getParameters()}</td> <td>""" ) page.append( " " + if (task.getOutcome() .equals("Success") ) "<font class=\"FontTaskSuccess\">" else "<font class=\"FontTaskFailure\">" ) page.append( """${" " + task.getOutcome()}</font></td> <td>""" ) if (task.getRout() != null) { page.append( "<a href=\"Rout.php?path=" + task.getRout() + "&log=" + task.getrScript() + ".Rout\">" + task.getrScript() .replace("_", " ") + "</a></td>\n" ) } else { page.append(" </td>\n") } page.append( """ ${" " + "<td>" + task.getOwner()}</td> """.trimIndent() ) page.append(" </tr>\n") } } page.append("</table>\n\n") page.append("</div>\n\n") page.append("<div id=\"FooterDiv\">\n") page.append(" <a href=\"https://github.com/bgweber/RServer\">RServer on GitHub</a>\n") page.append("</div>\n\n") page.append("</div>\n</body>\n</html>\n") val writer = BufferedWriter(FileWriter(indexPagePath)) writer.write(page.toString()) writer.close() } catch (e: Exception) { log("ERROR: failure updating server status: " + e.message) e.printStackTrace() } }
Generates the index.php file for the server dashboard .
fun removeServerById(serverId: Int) { servers.remove(serverId) }
Remove server with given unique id from list
fun TreeSet(c: Comparator?) { this(TreeMap(c)) }
Constructs a new , empty set , sorted according to the specified comparator . All elements inserted into the set must be < i > mutually comparable < /i > by the specified comparator : < tt > comparator.compare ( e1 , e2 ) < /tt > must not throw a < tt > ClassCastException < /tt > for any elements < tt > e1 < /tt > and < tt > e2 < /tt > in the set . If the user attempts to add an element to the set that violates this constraint , the < tt > add ( Object ) < /tt > call will throw a < tt > ClassCastException < /tt > .
fun <T> read(operation: Supplier<T>): T { return try { lock.readLock().lock() operation.get() } finally { lock.readLock().unlock() } }
Obtain a read lock , perform the operation , and release the read lock .
public void test_nCopiesILjava_lang_Object ( ) { Object o = new Object ( ) ; List l = Collections . nCopies ( 100 , o ) ; Iterator i = l . iterator ( ) ; Object first = i . next ( ) ; assertTrue ( "Returned list consists of copies not refs" , first == o ) ; assertEquals ( "Returned list of incorrect size" , 100 , l . size ( ) ) ; assertTrue ( "Contains" , l . contains ( o ) ) ; assertTrue ( "Contains null" , ! l . contains ( null ) ) ; assertTrue ( "null nCopies contains" , ! Collections . nCopies ( 2 , null ) . contains ( o ) ) ; assertTrue ( "null nCopies contains null" , Collections . nCopies ( 2 , null ) . contains ( null ) ) ; l = Collections . nCopies ( 20 , null ) ; i = l . iterator ( ) ; for ( int counter = 0 ; i . hasNext ( ) ; counter ++ ) { assertTrue ( "List is too large" , counter < 20 ) ; assertNull ( "Element should be null: " + counter , i . next ( ) ) ; } try { l . add ( o ) ; fail ( "Returned list is not immutable" ) ; } catch ( UnsupportedOperationException e ) { return ; } try { Collections . nCopies ( - 2 , new HashSet ( ) ) ; fail ( "nCopies with negative arg didn't throw IAE" ) ; } catch ( IllegalArgumentException e ) { } }
java.util.Collections # nCopies ( int , java.lang.Object )
fun test_nCopiesILjava_lang_Object() { val o = Any() var l: MutableList<*> = Collections.nCopies(100, o) var i: Iterator<*> = l.iterator() val first = i.next()!! assertTrue("Returned list consists of copies not refs", first === o) assertEquals("Returned list of incorrect size", 100, l.size) assertTrue("Contains", l.contains(o)) assertTrue("Contains null", !l.contains(null)) assertTrue("null nCopies contains", !Collections.nCopies(2, null).contains(o)) assertTrue("null nCopies contains null", Collections.nCopies(2, null).contains(null)) l = Collections.nCopies(20, null) i = l.iterator() var counter = 0 while (i.hasNext()) { assertTrue("List is too large", counter < 20) assertNull("Element should be null: $counter", i.next()) counter++ } try { l.add(o) fail("Returned list is not immutable") } catch (e: UnsupportedOperationException) { return } try { Collections.nCopies(-2, HashSet()) fail("nCopies with negative arg didn't throw IAE") } catch (e: IllegalArgumentException) { } }
add a + b + 1 , returning the result in a . The a value is treated as a BigInteger of length ( b.length * 8 ) bits . The result is modulo 2^b.length in case of overflow .
fun findByThriftIdOrThrow(fieldId: Int): _Fields? { return findByThriftId(fieldId) ?: throw IllegalArgumentException("Field $fieldId doesn't exist!") }
Find the _Fields constant that matches fieldId , throwing an exception if it is not found .
fun outerResource(@LayoutRes resource: Int): DividerAdapterBuilder { return outerView(asViewFactory(resource)) }
Sets the divider that appears before and after the wrapped adapters items .
fun ExecutionEntryImpl() { super() }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
fun logDiagnostic(msg: String) { if (isDiagnosticsEnabled()) { logRawDiagnostic(diagnosticPrefix + msg) } }
Output a diagnostic message to a user-specified destination ( if the user has enabled diagnostic logging ) .
fun Code39Reader(usingCheckDigit: Boolean, extendedMode: Boolean) { this.usingCheckDigit = usingCheckDigit this.extendedMode = extendedMode }
Creates a reader that can be configured to check the last character as a check digit , or optionally attempt to decode `` extended Code 39 '' sequences that are used to encode the full ASCII character set .
fun eStaticClass(): EClass? { return SexecPackage.Literals.UNSCHEDULE_TIME_EVENT }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
fun insertIfAbsent(s: K?, v: V?) { this.arc.get(getPartition(s)).insertIfAbsent(s, v) }
put a value to the cache if there was not an entry before do not return a previous content value
private fun Tokenizer(text: CharSequence) { this.text = text this.matcher = java.awt.font.GlyphMetrics.WHITESPACE.matcher(text) skipWhitespace() nextToken() }
Construct a tokenizer that parses tokens from the given text .
private fun BucketAdvisor(bucket: Bucket, regionAdvisor: RegionAdvisor) { super(bucket) this.regionAdvisor = regionAdvisor this.pRegion = this.regionAdvisor.getPartitionedRegion() resetParentAdvisor(bucket.getId()) }
Constructs a new BucketAdvisor for the Bucket owned by RegionAdvisor .
fun prepareYLegend() { val yLegend = ArrayList<Float>() if (mRoundedYLegend) { val interval: Float = mDeltaY / (mYLegendCount - 1) val log10 = Math.log10(interval.toDouble()) var exp = Math.floor(log10).toInt() if (exp < 0) { exp = 0 } val tenPowExp: Double = POW_10.get(exp + 5) var multi = Math.round(interval / tenPowExp).toDouble() if (multi >= 1) { if (multi > 2 && multi <= 3) { multi = 3.0 } else if (multi > 3 && multi <= 5) { multi = 5.0 } else if (multi > 5 && multi < 10) { multi = 10.0 } } else { multi = 1.0 } val step = (multi * tenPowExp).toFloat() log(" log10 is $log10 interval is $interval mDeltaY is $mDeltaY tenPowExp is $tenPowExp multi is $multi mYChartMin is $mYChartMin step is $step") var `val` = 0f if (step >= 1f) { `val` = (mYChartMin / step) as Int * step } else { `val` = mYChartMin } while (`val` <= mDeltaY + step + mYChartMin) { yLegend.add(`val`) `val` = `val` + step } if (step >= 1f) { mYChartMin = (mYChartMin / step) as Int * step log("mYChartMin write --- step >= 1f -- and mYChartMin is $mYChartMin") } mDeltaY = `val` - step - mYChartMin mYChartMax = yLegend[yLegend.size() - 1] } else { val interval: Float = mDeltaY / (mYLegendCount - 1) yLegend.add(mYChartMin) var i = 1 if (!isDrawOutline) { i = 0 } while (i < mYLegendCount - 1) { yLegend.add(mYChartMin + i.toFloat() * interval) i++ } yLegend.add(mDeltaY + mYChartMin) } mYLegend = yLegend.toArray(arrayOfNulls<Float>(0)) }
setup the Y legend
private fun displayHeaders(headers: List<AdsenseReportsGenerateResponse.Headers>) { for (header in headers) { System.out.printf("%25s", header.getName()) } println() }
Displays the headers for the report .
fun initData() { var classLoader: ClassLoader? = this.getClassLoader() if (classLoader != null) { val t1: TextView = this.createdView() t1.text = "[onCreate] classLoader " + ++i + " : " + classLoader.toString() this.classLoaderRootLayout.addView(t1) while (classLoader!!.parent != null) { classLoader = classLoader.parent val t2: TextView = this.createdView() t2.text = "[onCreate] classLoader " + ++i + " : " + classLoader.toString() this.classLoaderRootLayout.addView(t2) } } }
Initialize the Activity data