content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.github.fluidsonic.jetpack internal object LibResources : Resources()
Sources/LibResources.kt
2477505202
package com.github.prologdb.runtime import com.github.prologdb.runtime.term.CompoundTerm import com.github.prologdb.runtime.term.RandomVariable import com.github.prologdb.runtime.term.Term import com.github.prologdb.runtime.term.Variable import java.lang.ref.WeakReference import kotlin.math.max import kotlin.math.min /** * Handles the remapping of user-specified variables to random variables (that avoids name collisions). */ class RandomVariableScope { /** * This is essentially the most simple PRNG possible: this int will just be incremented until it hits Long.MAX_VALUE * and will then throw an exception. That number is then used to generate variable names. */ private var counter: Long = 0 /** * Replaces all the variables in the given term with random instances; the mapping gets stored * in the given map. */ fun withRandomVariables(term: Term, mapping: VariableMapping): Term { return term.substituteVariables { originalVariable -> if (originalVariable == Variable.ANONYMOUS) { createNewRandomVariable() } else { if (!mapping.hasOriginal(originalVariable)) { val randomVariable = createNewRandomVariable() mapping.storeSubstitution(originalVariable, randomVariable) } mapping.getSubstitution(originalVariable)!! } } } fun withRandomVariables(term: CompoundTerm, mapping: VariableMapping) = withRandomVariables(term as Term, mapping) as CompoundTerm fun withRandomVariables(terms: Array<out Term>, mapping: VariableMapping): Array<out Term> = Array(terms.size) { index -> this.withRandomVariables(terms[index], mapping) } fun createNewRandomVariable(): Variable { val localCounter = ++counter if (localCounter == Long.MAX_VALUE) { throw PrologInternalError("Out of random variables (reached $localCounter random variables in one proof search).") } if (localCounter >= Integer.MAX_VALUE.toLong()) { return RandomVariable(localCounter) } val localCounterInt = localCounter.toInt() val localPool = pool if (localCounterInt < localPool.size) { var variable = localPool[localCounterInt]?.get() if (variable == null) { variable = RandomVariable(localCounter) localPool[localCounterInt] = WeakReference(variable) } return variable } val newPool = localPool.copyOf( newSize = min( max( localCounter + 1L, localPool.size.toLong() * 2L ), Integer.MAX_VALUE.toLong() ).toInt() ) val variable = RandomVariable(localCounter) newPool[localCounterInt] = WeakReference(variable) pool = newPool return variable } companion object { /** * Shared cache for random variables. The index corresponds to [RandomVariableScope.counter] */ @JvmStatic @Volatile private var pool: Array<WeakReference<RandomVariable>?> = Array(100) { counter -> WeakReference(RandomVariable(counter.toLong())) } } }
core/src/main/kotlin/com/github/prologdb/runtime/RandomVariableScope.kt
3774584653
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api /** * Only for use by SandboxDataAccessService. This class is for ProcessorNodes that run in an * isolated sandbox */ class SandboxProcessorNode(private val processorNode: ProcessorNode) : ProcessorNode { override val requiredConnectionTypes: Set<Class<out Connection>> get() = processorNode.requiredConnectionTypes override val requiredConnectionNames: Set<ConnectionName<out Connection>> get() = processorNode.requiredConnectionNames }
java/com/google/android/libraries/pcc/chronicle/api/SandboxProcessorNode.kt
3994564990
object Libs { const val androidGradlePlugin = "com.android.tools.build:gradle:7.3.1" const val gradleVersionsPlugin = "com.github.ben-manes:gradle-versions-plugin:0.43.0" const val bus = "org.greenrobot:eventbus:3.3.1" const val timber = "com.jakewharton.timber:timber:5.0.1" const val relinker = "com.getkeepsafe.relinker:relinker:1.4.5" const val junit = "junit:junit:4.13.2" const val coil = "io.coil-kt:coil-compose:2.2.2" object Kotlin { private const val version = "1.7.20" const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$version" const val gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$version" const val immutable = "org.jetbrains.kotlinx:kotlinx-collections-immutable:0.3.5" } object Coroutines { private const val version = "1.6.4" const val core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$version" const val android = "org.jetbrains.kotlinx:kotlinx-coroutines-android:$version" const val test = "org.jetbrains.kotlinx:kotlinx-coroutines-test:$version" } object AndroidX { const val coreKtx = "androidx.core:core-ktx:1.9.0" const val activityKtx = "androidx.activity:activity-compose:1.6.1" const val fragmentKtx = "androidx.fragment:fragment-ktx:1.5.4" const val appCompat = "androidx.appcompat:appcompat:1.5.1" const val preference = "androidx.preference:preference:1.2.0" const val swipeRefreshLayout = "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0" const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.1.4" const val multiDex = "androidx.multidex:multidex:2.0.1" const val viewPager2 = "androidx.viewpager2:viewpager2:1.0.0" const val datastorePreferences = "androidx.datastore:datastore-preferences:1.0.0" object Lifecycle { private const val version = "2.5.1" const val viewModelKtx = "androidx.lifecycle:lifecycle-viewmodel-compose:$version" const val liveDataKtx = "androidx.lifecycle:lifecycle-livedata-ktx:$version" const val common = "androidx.lifecycle:lifecycle-common-java8:$version" } object Navigation { private const val version = "2.5.3" const val fragment = "androidx.navigation:navigation-fragment-ktx:$version" const val ui = "androidx.navigation:navigation-ui-ktx:$version" const val safeArgs = "androidx.navigation:navigation-safe-args-gradle-plugin:$version" } object Compose { const val compilerVersion = "1.3.2" const val bom = "androidx.compose:compose-bom:2022.10.00" const val material = "androidx.compose.material:material" const val animations = "androidx.compose.animation:animation" const val uiTooling = "androidx.compose.ui:ui-tooling" const val uiToolingPreview = "androidx.compose.ui:ui-tooling-preview" const val swipeToRefresh = "com.google.accompanist:accompanist-swiperefresh:0.27.0" } object Test { private const val version = "1.4.0" const val core = "androidx.test:core:$version" const val runner = "androidx.test:runner:$version" const val rules = "androidx.test:rules:$version" const val archCoreTesting = "androidx.arch.core:core-testing:2.1.0" const val jUnitExt = "androidx.test.ext:junit:1.1.3" const val orchestrator = "androidx.test:orchestrator:1.4.1" object Espresso { private const val version = "3.4.0" const val core = "androidx.test.espresso:espresso-core:$version" const val contrib = "androidx.test.espresso:espresso-contrib:$version" } } } object Google { const val material = "com.google.android.material:material:1.7.0" const val gson = "com.google.code.gson:gson:2.10" } object Rx { const val rxJava = "io.reactivex.rxjava3:rxjava:3.1.5" const val rxAndroid = "io.reactivex.rxjava3:rxandroid:3.0.0" } object Hilt { private const val version = "2.44" const val gradlePlugin = "com.google.dagger:hilt-android-gradle-plugin:$version" const val android = "com.google.dagger:hilt-android:$version" const val androidCompiler = "com.google.dagger:hilt-android-compiler:$version" const val androidTesting = "com.google.dagger:hilt-android-testing:$version" } object Glide { private const val version = "4.14.2" const val glide = "com.github.bumptech.glide:glide:$version" const val compiler = "com.github.bumptech.glide:compiler:$version" } object Airbnb { private const val version = "5.1.0" const val epoxy = "com.airbnb.android:epoxy:$version" const val processor = "com.airbnb.android:epoxy-processor:$version" const val dataBinding = "com.airbnb.android:epoxy-databinding:$version" } object Mockito { const val core = "org.mockito:mockito-core:4.8.1" const val kotlin = "org.mockito.kotlin:mockito-kotlin:4.0.0" } }
buildSrc/src/main/java/Libs.kt
473670515
package ca.josephroque.bowlingcompanion.games.views import android.content.Context import android.os.Bundle import android.os.Parcelable import android.support.constraint.ConstraintLayout import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.matchplay.MatchPlayResult import kotlinx.android.synthetic.main.view_game_footer.view.pins_divider as pinsDivider import kotlinx.android.synthetic.main.view_game_footer.view.iv_clear_pins as clearPinsIcon import kotlinx.android.synthetic.main.view_game_footer.view.iv_foul as foulIcon import kotlinx.android.synthetic.main.view_game_footer.view.iv_lock as lockIcon import kotlinx.android.synthetic.main.view_game_footer.view.iv_match_play as matchPlayIcon import kotlinx.android.synthetic.main.view_game_footer.view.iv_fullscreen as fullscreenIcon /** * Copyright (C) 2018 Joseph Roque * * Footer view to display game and frame controls at the foot of the game details. */ class GameFooterView : ConstraintLayout { companion object { @Suppress("unused") private const val TAG = "GameFooterView" private const val SUPER_STATE = "${TAG}_super_state" private const val STATE_CURRENT_BALL = "${TAG}_current_ball" private const val STATE_MATCH_PLAY_RESULT = "${TAG}_match_play_result" private const val STATE_LOCK = "${TAG}_lock" private const val STATE_FOUL = "${TAG}_foul" private const val STATE_MANUAL_SCORE = "${TAG}_manual" private const val STATE_FULLSCREEN = "${TAG}_fullscreen" enum class Clear { Strike, Spare, Fifteen; val image: Int get() = when (this) { Strike -> R.drawable.ic_clear_pins_strike Spare -> R.drawable.ic_clear_pins_spare Fifteen -> R.drawable.ic_clear_pins_fifteen } companion object { private val map = Clear.values().associateBy(Clear::ordinal) fun fromInt(type: Int) = map[type] } } } var delegate: GameFooterInteractionDelegate? = null var isFullscreen: Boolean = false set(value) { field = value fullscreenIcon.setImageResource(if (value) R.drawable.ic_fullscreen_exit else R.drawable.ic_fullscreen) } var clear: Clear = Clear.Strike set(value) { field = value clearPinsIcon.setImageResource(value.image) } var matchPlayResult: MatchPlayResult = MatchPlayResult.NONE set(value) { field = value matchPlayIcon.setImageResource(value.getIcon()) } var isGameLocked: Boolean = false set(value) { field = value lockIcon.setImageResource(if (value) R.drawable.ic_lock else R.drawable.ic_lock_open) } var isFoulActive: Boolean = false set(value) { field = value foulIcon.setImageResource(if (value) R.drawable.ic_foul_active else R.drawable.ic_foul_inactive) } var isManualScoreSet: Boolean = false set(value) { field = value val visible = if (value) View.GONE else View.VISIBLE clearPinsIcon.visibility = visible foulIcon.visibility = visible pinsDivider.visibility = visible } private val onClickListener = View.OnClickListener { when (it.id) { R.id.iv_fullscreen -> delegate?.onFullscreenToggle() R.id.iv_clear_pins -> delegate?.onClearPins() R.id.iv_foul -> delegate?.onFoulToggle() R.id.iv_lock -> delegate?.onLockToggle() R.id.iv_match_play -> delegate?.onMatchPlaySettings() } } // MARK: Constructors constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { LayoutInflater.from(context).inflate(R.layout.view_game_footer, this, true) fullscreenIcon.setOnClickListener(onClickListener) clearPinsIcon.setOnClickListener(onClickListener) foulIcon.setOnClickListener(onClickListener) lockIcon.setOnClickListener(onClickListener) matchPlayIcon.setOnClickListener(onClickListener) } // MARK: Lifecycle functions override fun onSaveInstanceState(): Parcelable { return Bundle().apply { putParcelable(SUPER_STATE, super.onSaveInstanceState()) putInt(STATE_CURRENT_BALL, clear.ordinal) putInt(STATE_MATCH_PLAY_RESULT, matchPlayResult.ordinal) putBoolean(STATE_LOCK, isGameLocked) putBoolean(STATE_FOUL, isFoulActive) putBoolean(STATE_MANUAL_SCORE, isManualScoreSet) putBoolean(STATE_FULLSCREEN, isFullscreen) } } override fun onRestoreInstanceState(state: Parcelable?) { var superState: Parcelable? = null if (state is Bundle) { clear = Clear.fromInt(state.getInt(STATE_CURRENT_BALL))!! matchPlayResult = MatchPlayResult.fromInt(state.getInt(STATE_MATCH_PLAY_RESULT))!! isGameLocked = state.getBoolean(STATE_LOCK) isFoulActive = state.getBoolean(STATE_FOUL) isManualScoreSet = state.getBoolean(STATE_MANUAL_SCORE) isFullscreen = state.getBoolean(STATE_FULLSCREEN) superState = state.getParcelable(SUPER_STATE) } super.onRestoreInstanceState(superState) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() delegate = null } // MARK: GameFooterInteractionDelegate interface GameFooterInteractionDelegate { fun onLockToggle() fun onClearPins() fun onFoulToggle() fun onMatchPlaySettings() fun onFullscreenToggle() } }
app/src/main/java/ca/josephroque/bowlingcompanion/games/views/GameFooterView.kt
700441057
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[email protected]> * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ package com.github.shadowsocks.plugin import android.graphics.drawable.Drawable abstract class Plugin { abstract val id: String abstract val label: CharSequence open val icon: Drawable? get() = null open val defaultConfig: String? get() = null open val packageName: String get() = "" open val trusted: Boolean get() = true }
mobile/src/main/java/com/github/shadowsocks/plugin/Plugin.kt
2103635151
/*- * ========================LICENSE_START================================= * camel-multipart-processor * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.camel.multipart import org.apache.commons.fileupload.FileUpload import org.apache.commons.fileupload.UploadContext import org.apache.commons.fileupload.disk.DiskFileItemFactory import org.slf4j.LoggerFactory import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.nio.charset.StandardCharsets class MultiPartStringParser internal constructor(private val multipartInput: InputStream) : UploadContext { private var boundary: String? = null var header: String? = null var payload: InputStream? = null var payloadContentType: String? = null override fun getCharacterEncoding(): String = StandardCharsets.UTF_8.name() override fun getContentLength() = -1 override fun getContentType() = "multipart/form-data, boundary=$boundary" override fun getInputStream() = multipartInput override fun contentLength() = -1L companion object { private val LOG = LoggerFactory.getLogger(MultiPartStringParser::class.java) } init { multipartInput.mark(10240) BufferedReader(InputStreamReader(multipartInput, StandardCharsets.UTF_8)).use { reader -> val boundaryLine = reader.readLine() ?: throw IOException( "Message body appears to be empty, expected multipart boundary." ) boundary = boundaryLine.substring(2).trim { it <= ' ' } multipartInput.reset() for (i in FileUpload(DiskFileItemFactory()).parseRequest(this)) { val fieldName = i.fieldName if (LOG.isTraceEnabled) { LOG.trace("Found multipart field with name \"{}\"", fieldName) } if (MultiPartConstants.MULTIPART_HEADER == fieldName) { header = i.string if (LOG.isDebugEnabled) { LOG.debug("Found header:\n{}", header) } } else if (MultiPartConstants.MULTIPART_PAYLOAD == fieldName) { payload = i.inputStream payloadContentType = i.contentType if (LOG.isDebugEnabled) { LOG.debug("Found body with Content-Type \"{}\"", payloadContentType) } } else { throw IOException("Unknown multipart field name detected: $fieldName") } } } } }
camel-multipart-processor/src/main/kotlin/de/fhg/aisec/ids/camel/multipart/MultiPartStringParser.kt
4291700063
package de.roamingthings.devworkbench.persistence open class UpdateField<T>(val value: T? = null, val ignored: Boolean = false) { fun get(): T = value ?: throw IllegalStateException("value cannot be null.") fun getOrDefault(defaultValue: T): T = if (ignored) defaultValue else get() companion object { fun <T> ignore() = UpdateField<T>(ignored = true) fun <T> of(value: T) = UpdateField<T>(value = value) } }
dev-workbench-backend/src/main/kotlin/de/roamingthings/devworkbench/persistence/UpdateField.kt
2766518956
package com.github.shchurov.gitterclient.data.database.implementation import com.github.shchurov.gitterclient.data.database.Database import com.github.shchurov.gitterclient.data.database.implementation.realm_models.RoomRealm import com.github.shchurov.gitterclient.domain.models.Room import io.realm.Realm class DatabaseImpl(initializer: RealmInitializer) : Database { private val converter = DatabaseConverter() init { initializer.initRealm() } override fun getRooms(): MutableList<Room> { val realm = getRealmInstance() val realmRooms = realm.allObjects(RoomRealm::class.java) val rooms: MutableList<Room> = mutableListOf() realmRooms.mapTo(rooms) { converter.convertRealmToRoom(it) } realm.close() return rooms } override fun insertRooms(rooms: List<Room>) { val realmRooms = rooms.map { converter.convertRoomToRealm(it) } executeTransaction { realm -> realm.copyToRealm(realmRooms) } } override fun updateRoomLastAccessTime(roomId: String, timestamp: Long) { executeTransaction { realm -> getRoom(roomId, realm).lastAccessTimestamp = timestamp } } private fun getRoom(roomId: String, realm: Realm) = realm.where(RoomRealm::class.java) .equalTo(RoomRealm.FIELD_ID, roomId) .findFirst() override fun decrementRoomUnreadItems(roomId: String) { executeTransaction { realm -> val realmRoom = getRoom(roomId, realm) realmRoom.unreadItems-- } } override fun clearRooms() { executeTransaction { realm -> realm.clear(RoomRealm::class.java) } } private fun executeTransaction(transaction: (Realm) -> Unit) { val realm = getRealmInstance() realm.beginTransaction() try { transaction(realm) realm.commitTransaction() } catch (e: Exception) { e.printStackTrace() realm.cancelTransaction() } realm.close() } private fun getRealmInstance() = Realm.getDefaultInstance() }
app/src/main/kotlin/com/github/shchurov/gitterclient/data/database/implementation/DatabaseImpl.kt
164120571
package com.fwdekker.randomness.template import com.fwdekker.randomness.DummyScheme import com.fwdekker.randomness.Scheme import com.fwdekker.randomness.SettingsState import com.fwdekker.randomness.clickActionButton import com.fwdekker.randomness.datetime.DateTimeScheme import com.fwdekker.randomness.decimal.DecimalScheme import com.fwdekker.randomness.integer.IntegerScheme import com.fwdekker.randomness.string.StringScheme import com.fwdekker.randomness.uuid.UuidScheme import com.fwdekker.randomness.word.WordScheme import com.intellij.testFramework.fixtures.IdeaTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.ui.JBSplitter import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.assertj.swing.edt.FailOnThreadViolationRepaintManager import org.assertj.swing.edt.GuiActionRunner import org.assertj.swing.fixture.AbstractComponentFixture import org.assertj.swing.fixture.Containers import org.assertj.swing.fixture.FrameFixture import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe /** * GUI tests for [TemplateListEditor]. */ object TemplateListEditorTest : Spek({ lateinit var ideaFixture: IdeaTestFixture lateinit var frame: FrameFixture lateinit var state: SettingsState lateinit var editor: TemplateListEditor beforeGroup { FailOnThreadViolationRepaintManager.install() TemplateListEditor.CREATE_SPLITTER = { vertical, proportionKey, defaultProportion -> JBSplitter(vertical, proportionKey, defaultProportion) } } beforeEachTest { ideaFixture = IdeaTestFixtureFactory.getFixtureFactory().createBareFixture() ideaFixture.setUp() state = SettingsState( TemplateList( listOf( Template("Whip", listOf(IntegerScheme(), StringScheme())), Template("Ability", listOf(DecimalScheme(), WordScheme())) ) ) ) state.templateList.applySettingsState(state) editor = GuiActionRunner.execute<TemplateListEditor> { TemplateListEditor(state) } frame = Containers.showInFrame(editor.rootComponent) } afterEachTest { frame.cleanUp() GuiActionRunner.execute { editor.dispose() } ideaFixture.tearDown() } describe("loadState") { it("loads the list's schemes") { assertThat(GuiActionRunner.execute<Int> { frame.tree().target().rowCount }).isEqualTo(6) } } describe("readState") { it("returns the original state if no editor changes are made") { assertThat(editor.readState()).isEqualTo(editor.originalState) } it("returns the editor's state") { GuiActionRunner.execute { frame.tree().target().selectionRows = intArrayOf(0) frame.clickActionButton("Remove") } val readScheme = editor.readState() assertThat(readScheme.templateList.templates).hasSize(1) } it("returns the loaded state if no editor changes are made") { GuiActionRunner.execute { frame.tree().target().selectionRows = intArrayOf(0) frame.clickActionButton("Remove") } assertThat(editor.isModified()).isTrue() GuiActionRunner.execute { editor.loadState(editor.readState()) } assertThat(editor.isModified()).isFalse() assertThat(editor.readState()).isEqualTo(editor.originalState) } it("returns different instances of the settings") { val readState = editor.readState() assertThat(readState).isNotSameAs(state) assertThat(readState.templateList).isNotSameAs(state.templateList) } it("retains the list's UUIDs") { val readState = editor.readState() assertThat(readState.uuid).isEqualTo(state.uuid) assertThat(readState.templateList.uuid).isEqualTo(state.templateList.uuid) assertThat(readState.templateList.templates.map { it.uuid }) .containsExactlyElementsOf(state.templateList.templates.map { it.uuid }) } } describe("reset") { it("undoes changes to the initial selection") { GuiActionRunner.execute { frame.tree().target().setSelectionRow(1) frame.spinner("minValue").target().value = 7 } GuiActionRunner.execute { editor.reset() } assertThat(frame.spinner("minValue").target().value).isEqualTo(0L) } it("retains the selection if `queueSelection` is null") { editor.queueSelection = null GuiActionRunner.execute { editor.reset() } assertThat(frame.tree().target().selectionRows).containsExactly(0) } it("selects the indicated template after reset") { editor.queueSelection = state.templateList.templates[1].uuid GuiActionRunner.execute { editor.reset() } assertThat(frame.tree().target().selectionRows).containsExactly(3) } it("does nothing if the indicated template could not be found") { editor.queueSelection = "231ee9da-8f72-4535-b770-0119fdf68f70" GuiActionRunner.execute { editor.reset() } assertThat(frame.tree().target().selectionRows).containsExactly(0) } } describe("addChangeListener") { it("invokes the listener if the model is changed") { GuiActionRunner.execute { frame.tree().target().setSelectionRow(1) } var invoked = 0 GuiActionRunner.execute { editor.addChangeListener { invoked++ } } GuiActionRunner.execute { frame.spinner("minValue").target().value = 321 } assertThat(invoked).isNotZero() } it("invokes the listener if a scheme is removed") { GuiActionRunner.execute { frame.tree().target().selectionRows = intArrayOf(0) } var invoked = 0 GuiActionRunner.execute { editor.addChangeListener { invoked++ } } GuiActionRunner.execute { frame.clickActionButton("Remove") } assertThat(invoked).isNotZero() } it("invokes the listener if the selection is changed") { GuiActionRunner.execute { frame.tree().target().clearSelection() } var invoked = 0 GuiActionRunner.execute { editor.addChangeListener { invoked++ } } GuiActionRunner.execute { frame.tree().target().setSelectionRow(2) } assertThat(invoked).isNotZero() } } describe("scheme editor") { it("loads the selected scheme's editor") { GuiActionRunner.execute { frame.tree().target().setSelectionRow(2) } frame.textBox("pattern").requireVisible() } it("retains changes made in a scheme editor") { GuiActionRunner.execute { frame.tree().target().setSelectionRow(2) frame.textBox("pattern").target().text = "strange" } GuiActionRunner.execute { frame.tree().target().setSelectionRow(1) frame.tree().target().setSelectionRow(2) } frame.textBox("pattern").requireText("strange") } describe("editor creation") { data class Param( val name: String, val scheme: Scheme, val matcher: (FrameFixture) -> AbstractComponentFixture<*, *, *> ) listOf( Param("integer", IntegerScheme()) { it.spinner("minValue") }, Param("decimal", DecimalScheme()) { it.spinner("minValue") }, Param("string", StringScheme()) { it.textBox("pattern") }, Param("UUID", UuidScheme()) { it.radioButton("type1") }, Param("word", WordScheme()) { it.radioButton("capitalizationRetain") }, Param("date-time", DateTimeScheme()) { it.textBox("minDateTime") }, Param("template reference", TemplateReference()) { it.list() } ).forEach { (name, scheme, matcher) -> it("loads an editor for ${name}s") { state.templateList.templates = listOf(Template(schemes = listOf(scheme))) state.templateList.applySettingsState(state) GuiActionRunner.execute { editor.reset() frame.tree().target().setSelectionRow(1) } matcher(frame).requireVisible() } } it("loads an editor for templates") { state.templateList.templates = listOf(Template(schemes = emptyList())) state.templateList.applySettingsState(state) GuiActionRunner.execute { editor.reset() } frame.textBox("templateName").requireVisible() } it("throws an error for unknown scheme types") { state.templateList.templates = listOf(Template(schemes = listOf(DummyScheme.from("grain")))) state.templateList.applySettingsState(state) assertThatThrownBy { GuiActionRunner.execute { editor.reset() frame.tree().target().setSelectionRow(1) } } .isInstanceOf(IllegalStateException::class.java) .hasMessage("Unknown scheme type 'com.fwdekker.randomness.DummyScheme'.") } } } })
src/test/kotlin/com/fwdekker/randomness/template/TemplateListEditorTest.kt
1320316044
package com.fsck.k9.mail.transport.smtp data class EnhancedStatusCode( val statusClass: StatusCodeClass, val subject: Int, val detail: Int )
mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/EnhancedStatusCode.kt
3767880115
package com.fwdekker.randomness.integer import com.fwdekker.randomness.CapitalizationMode import com.fwdekker.randomness.array.ArrayDecorator import org.assertj.core.api.Assertions.assertThat import org.assertj.swing.edt.FailOnThreadViolationRepaintManager import org.assertj.swing.edt.GuiActionRunner import org.assertj.swing.fixture.Containers.showInFrame import org.assertj.swing.fixture.FrameFixture import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe /** * GUI tests for [IntegerSchemeEditor]. */ object IntegerSchemeEditorTest : Spek({ lateinit var scheme: IntegerScheme lateinit var editor: IntegerSchemeEditor lateinit var frame: FrameFixture beforeGroup { FailOnThreadViolationRepaintManager.install() } beforeEachTest { scheme = IntegerScheme() editor = GuiActionRunner.execute<IntegerSchemeEditor> { IntegerSchemeEditor(scheme) } frame = showInFrame(editor.rootComponent) } afterEachTest { frame.cleanUp() } describe("input handling") { describe("base") { it("truncates decimals in the base") { GuiActionRunner.execute { frame.spinner("base").target().value = 22.62f } frame.spinner("base").requireValue(22) } } describe("minimum value") { it("truncates decimals in the minimum value") { GuiActionRunner.execute { frame.spinner("minValue").target().value = 285.21f } frame.spinner("minValue").requireValue(285L) } } describe("maximum value") { it("truncates decimals in the maximum value") { GuiActionRunner.execute { frame.spinner("maxValue").target().value = 490.34f } frame.spinner("maxValue").requireValue(490L) } } } describe("loadState") { it("loads the scheme's minimum value") { GuiActionRunner.execute { editor.loadState(IntegerScheme(minValue = 145L, maxValue = 341L)) } frame.spinner("minValue").requireValue(145L) } it("loads the scheme's maximum value") { GuiActionRunner.execute { editor.loadState(IntegerScheme(minValue = 337L, maxValue = 614L)) } frame.spinner("maxValue").requireValue(614L) } it("loads the scheme's base value") { GuiActionRunner.execute { editor.loadState(IntegerScheme(base = 25)) } frame.spinner("base").requireValue(25) } it("loads the scheme's grouping separator") { GuiActionRunner.execute { editor.loadState(IntegerScheme(groupingSeparator = "_")) } frame.radioButton("groupingSeparatorNone").requireSelected(false) frame.radioButton("groupingSeparatorPeriod").requireSelected(false) frame.radioButton("groupingSeparatorComma").requireSelected(false) frame.radioButton("groupingSeparatorUnderscore").requireSelected(true) frame.panel("groupingSeparatorCustom").radioButton().requireSelected(false) } it("loads the scheme's custom grouping separator") { GuiActionRunner.execute { editor.loadState(IntegerScheme(customGroupingSeparator = "r")) } frame.panel("groupingSeparatorCustom").textBox().requireText("r") } it("selects the scheme's custom grouping separator") { GuiActionRunner.execute { editor.loadState(IntegerScheme(groupingSeparator = "a", customGroupingSeparator = "a")) } frame.panel("groupingSeparatorCustom").radioButton().requireSelected() } it("loads the scheme's capitalization mode") { GuiActionRunner.execute { editor.loadState(IntegerScheme(capitalization = CapitalizationMode.LOWER)) } frame.radioButton("capitalizationLower").requireSelected(true) frame.radioButton("capitalizationUpper").requireSelected(false) } it("loads the scheme's prefix") { GuiActionRunner.execute { editor.loadState(IntegerScheme(prefix = "wage")) } frame.textBox("prefix").requireText("wage") } it("loads the scheme's suffix") { GuiActionRunner.execute { editor.loadState(IntegerScheme(suffix = "fat")) } frame.textBox("suffix").requireText("fat") } } describe("readState") { describe("defaults") { it("returns default brackets if no brackets are selected") { GuiActionRunner.execute { editor.loadState(IntegerScheme(groupingSeparator = "unsupported")) } assertThat(editor.readState().groupingSeparator).isEqualTo(IntegerScheme.DEFAULT_GROUPING_SEPARATOR) } it("returns default brackets if no brackets are selected") { GuiActionRunner.execute { editor.loadState(IntegerScheme(capitalization = CapitalizationMode.DUMMY)) } assertThat(editor.readState().capitalization).isEqualTo(IntegerScheme.DEFAULT_CAPITALIZATION) } } it("returns the original state if no editor changes are made") { assertThat(editor.readState()).isEqualTo(editor.originalState) } it("returns the editor's state") { GuiActionRunner.execute { frame.spinner("minValue").target().value = 2_147_483_648L frame.spinner("maxValue").target().value = 2_147_483_649L frame.spinner("base").target().value = 14 frame.radioButton("groupingSeparatorPeriod").target().isSelected = true frame.panel("groupingSeparatorCustom").textBox().target().text = "s" frame.radioButton("capitalizationUpper").target().isSelected = true frame.textBox("prefix").target().text = "silent" frame.textBox("suffix").target().text = "pain" } val readScheme = editor.readState() assertThat(readScheme.minValue).isEqualTo(2_147_483_648L) assertThat(readScheme.maxValue).isEqualTo(2_147_483_649L) assertThat(readScheme.base).isEqualTo(14) assertThat(readScheme.groupingSeparator).isEqualTo(".") assertThat(readScheme.customGroupingSeparator).isEqualTo("s") assertThat(readScheme.capitalization).isEqualTo(CapitalizationMode.UPPER) assertThat(readScheme.prefix).isEqualTo("silent") assertThat(readScheme.suffix).isEqualTo("pain") } it("returns the loaded state if no editor changes are made") { GuiActionRunner.execute { frame.spinner("minValue").target().value = 242L } assertThat(editor.isModified()).isTrue() GuiActionRunner.execute { editor.loadState(editor.readState()) } assertThat(editor.isModified()).isFalse() assertThat(editor.readState()).isEqualTo(editor.originalState) } it("returns a different instance from the loaded scheme") { val readState = editor.readState() assertThat(readState) .isEqualTo(editor.originalState) .isNotSameAs(editor.originalState) assertThat(readState.arrayDecorator) .isEqualTo(editor.originalState.arrayDecorator) .isNotSameAs(editor.originalState.arrayDecorator) } it("retains the scheme's UUID") { assertThat(editor.readState().uuid).isEqualTo(editor.originalState.uuid) } } describe("addChangeListener") { it("invokes the listener if a field changes") { var listenerInvoked = false editor.addChangeListener { listenerInvoked = true } GuiActionRunner.execute { frame.spinner("minValue").target().value = 76L } assertThat(listenerInvoked).isTrue() } it("invokes the listener if the array decorator changes") { GuiActionRunner.execute { editor.loadState(IntegerScheme(arrayDecorator = ArrayDecorator(enabled = true))) } var listenerInvoked = false editor.addChangeListener { listenerInvoked = true } GuiActionRunner.execute { frame.spinner("arrayMinCount").target().value = 528 } assertThat(listenerInvoked).isTrue() } } })
src/test/kotlin/com/fwdekker/randomness/integer/IntegerSchemeEditorTest.kt
311883709
package com.zj.example.kotlin.shengshiyuan.helloworld /** * 默认参数(default arguments) * lambda表达式 * * 在默认情况下,lambda表达式中最后一个表达式的值,会隐式作为该lambda表达式的返回值, * 但是我们可以通过全限定的return语法来显示从lambda表达式来返回值. * * CreateTime: 18/5/14 08:59 * @author 郑炯 */ fun main(vararg args: String) { val fun1 = HelloKotlin_Function1() /** * 下方依次输出: 1 3 2 5 4 */ fun1.test() fun1.test(2) fun1.test(b = 2) fun1.test(3, 2) fun1.test(a = 3) println("-----------------") val a = HelloKotlin_Function1.A() val b = HelloKotlin_Function1.B(); println(a.method(1))//输出5 println(b.method(2))//输出6 println("-----------------") //这里必须用具名参数的形式, fun1.test2(b = 2); //a可以不指定具名参数名 fun1.test3(1, c = 3) //a可以不指定具名参数名 fun1.test32(1, d = 4) println("-----------------") //把一个方法当成参数传递, 前面要加::, 前面要指定改方法位于的类, 因为test是包级函数所以可以不指定类 fun1.test4(1, 2, ::test) //把fun1中的test方法当成参数传递 fun1.test4(1, 2, fun1::test) fun1.test4(1, 2, { a, b -> println(a - b) }) fun1.test4(2, compute = { a, b -> println(a - b) }) /** * 这里为什么可以不用加compute具名参数名? * 因为如果lambda表达式是最后一个参数的时候,可以把lambda表达式放到括号的外面, 这个 * 时候可以无视这条规定. */ fun1.test4(2) { a, b -> println(a - b) } //不使用lambda表达式, 使用匿名函数的方式 fun1.test4(1, compute = fun(a, b) { println(a - b) }) } fun test(a: Int = 0, b: Int = 1) = println(a + b) open class HelloKotlin_Function1 { //默认参数(default arguments) fun test(a: Int = 0, b: Int = 1) = println(a + b) /** * 如果一个默认参数位于其他无默认值参数的前面, 那么在省略a参数的时候, 无默认值的参数只能通过具名参数的形式调用 */ fun test2(a: Int = 1, b: Int) = println(a - b) /** * 这里虽然前面有一个没有默认参数的a, 但是d位于默认参数的后面, 所有c必须用具名参数的形式调用. */ fun test3(a: Int, b: Int = 1, c: Int) = println(a + b + c) fun test32(a: Int, b: Int = 2, c: Int = 3, d: Int) = println(a + b + c + d) /** * 对于重写的方法来说, 子类所拥有的重写方法会使用与父类相同的默认参数值. * 在重写一个拥有默认参数值的方法时, 方法签名中必须要将默认参数值省略掉. */ open class A { open fun method(a: Int, b: Int = 4) = a + b } class B : A() { //这里b, 不能有默认参数值不然会报错, 虽然b不写默认参数值, 但是b的默认参数也是4 override fun method(a: Int, b: Int) = a + b } fun test4(a: Int = 1, b: Int = 2, compute: (x: Int, y: Int) -> Unit) { compute(a, b) } }
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/45.HelloKotlin-函数1(具名函数和lambda表达式).kt
1956452735
package com.jeremiahzucker.pandroid.request.json.v5.model import com.jeremiahzucker.pandroid.PandroidApplication.Companion.Preferences /** * Created by Jeremiah Zucker on 8/20/2017. */ open class SyncTokenRequestBody(tokenType: TokenType = TokenType.USER) { enum class TokenType(val getToken: () -> String?) { USER({ Preferences.userAuthToken }), PARTNER({ Preferences.partnerAuthToken }), NONE({ null }) } val syncTime: Long = (Preferences.syncTimeOffset ?: 0L) + (System.currentTimeMillis() / 1000L) // Use nullable types to allow GSON to only serialize populated members var userAuthToken: String? = null var partnerAuthToken: String? = null init { when (tokenType) { TokenType.USER -> { userAuthToken = tokenType.getToken() } TokenType.PARTNER -> { partnerAuthToken = tokenType.getToken() } } } }
app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/model/SyncTokenRequestBody.kt
375458601
package com.jeremiahzucker.pandroid.persist import android.app.Application import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit import androidx.preference.PreferenceManager import kotlin.reflect.KClass import kotlin.reflect.KProperty // class NullableDatastoreDelegate<V>(private val dataStore: DataStore<Preferences>, private val key: Preferences.Key<V>) { // // companion object { // private const val LONG_NULL = Long.MAX_VALUE // } // // operator fun getValue(thisRef: Any?, prop: KProperty<*>): V? = runBlocking { // dataStore.data.map { it[key] }.map { if (it == LONG_NULL) null else it }.single() // } // // operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: V?) = dataStore.editBlocking { // it[key] = when (value) { // is Long -> value // else -> value // } ?: LONG_NULL as V // } // // private fun DataStore<Preferences>.editBlocking(transform: suspend (MutablePreferences) -> Unit): Preferences = runBlocking { // edit(transform) // } // } // // inline fun <reified V : Any> DataStore<Preferences>.bindToPreferenceFieldNullable(prop: KProperty<*>) = NullableDatastoreDelegate<V>(this, preferencesKey(prop.name)) class NullableSharedPreferencesDelegate<V : Any>(private val sharedPreferences: SharedPreferences, private val dataClass: KClass<V>) { companion object { private const val LONG_NULL = Long.MAX_VALUE private const val STRING_NULL = "I'm a null string baby" } operator fun getValue(thisRef: Any?, prop: KProperty<*>): V? = when (dataClass) { Long::class -> when (val value = sharedPreferences.getLong(prop.name, LONG_NULL)) { LONG_NULL -> null else -> value } String::class -> when (val value = sharedPreferences.getString(prop.name, STRING_NULL)) { STRING_NULL -> null else -> value } else -> throw IllegalArgumentException("unsupported type $dataClass") } as? V operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: V?) = sharedPreferences.edit { when (dataClass) { Long::class -> putLong(prop.name, value as? Long ?: LONG_NULL) String::class -> putString(prop.name, value as? String ?: STRING_NULL) else -> throw IllegalArgumentException("unsupported type $dataClass") } as? V } } inline fun <reified V : Any> SharedPreferences.bindToPreferenceFieldNullable() = NullableSharedPreferencesDelegate(this, V::class) /** * Created by jzucker on 7/7/17. * SharedPreferences */ class Preferences(application: Application) { // fun init(context: Context) { // this.context = context // } // // private lateinit var context: Context private val context: Context = application private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) // private val dataStore: DataStore<Preferences> = context.createDataStore("settings") // init { // GlobalScope.launch { // dataStore.data.first() // } // } var syncTimeOffset: Long? by sharedPreferences.bindToPreferenceFieldNullable() var partnerId: String? by sharedPreferences.bindToPreferenceFieldNullable() var partnerAuthToken: String? by sharedPreferences.bindToPreferenceFieldNullable() var userAuthToken: String? by sharedPreferences.bindToPreferenceFieldNullable() var userId: String? by sharedPreferences.bindToPreferenceFieldNullable() var stationListChecksum: String? by sharedPreferences.bindToPreferenceFieldNullable() var username: String? by sharedPreferences.bindToPreferenceFieldNullable() var password: String? by sharedPreferences.bindToPreferenceFieldNullable() fun reset() { syncTimeOffset = null partnerId = null partnerAuthToken = null userAuthToken = null userId = null stationListChecksum = null } }
app/src/main/java/com/jeremiahzucker/pandroid/persist/Preferences.kt
4005552328
package net.perfectdreams.spicymorenitta.views.dashboard import kotlinx.html.* import kotlinx.html.dom.create import net.perfectdreams.spicymorenitta.utils.loriUrl import net.perfectdreams.spicymorenitta.utils.TingleModal import net.perfectdreams.spicymorenitta.utils.TingleOptions import kotlinx.browser.document import kotlinx.browser.window object Stuff { fun showPremiumFeatureModal(description: (DIV.() -> (Unit))? = null) { val modal = TingleModal( TingleOptions( footer = true, cssClass = arrayOf("tingle-modal--overflow") ) ) modal.setContent( document.create.div { div(classes = "category-name") { + "Você encontrou uma função premium!" } div { style = "text-align: center;" img(src = "https://i.imgur.com/wEUDTZG.png") { width = "250" } if (description != null) { description.invoke(this) } else { p { +"Você encontrou uma função premium minha! Legal, né?" } p { +"Para ter esta função e muito mais, veja a minha lista de vantagens que você pode ganhar doando!" } } } } ) modal.addFooterBtn("<i class=\"fas fa-gift\"></i> Vamos lá!", "button-discord button-discord-info pure-button button-discord-modal") { window.open("${loriUrl}donate", "_blank") } modal.addFooterBtn("<i class=\"fas fa-times\"></i> Fechar", "button-discord pure-button button-discord-modal button-discord-modal-secondary-action") { modal.close() } modal.open() } }
web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/views/dashboard/Stuff.kt
1937920276
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.randomroleplaypictures.client.RandomRoleplayPicturesClient class RoleplayAttackExecutor( loritta: LorittaBot, client: RandomRoleplayPicturesClient, ) : RoleplayPictureExecutor( loritta, client, RoleplayUtils.ATTACK_ATTRIBUTES )
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/roleplay/RoleplayAttackExecutor.kt
2190961579
@file:Suppress("MethodOverloading") package me.proxer.app.util.extension import android.content.Context import android.content.res.Resources import androidx.appcompat.content.res.AppCompatResources import com.mikepenz.iconics.IconicsDrawable import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial import com.mikepenz.iconics.utils.colorInt import me.proxer.app.R import me.proxer.app.R.id.description import me.proxer.app.R.id.post import me.proxer.app.anime.AnimeStream import me.proxer.app.anime.resolver.StreamResolutionResult import me.proxer.app.chat.prv.LocalConference import me.proxer.app.chat.prv.LocalMessage import me.proxer.app.chat.pub.message.ParsedChatMessage import me.proxer.app.comment.LocalComment import me.proxer.app.forum.ParsedPost import me.proxer.app.forum.TopicMetaData import me.proxer.app.media.LocalTag import me.proxer.app.media.comments.ParsedComment import me.proxer.app.profile.comment.ParsedUserComment import me.proxer.app.profile.history.LocalUserHistoryEntry import me.proxer.app.profile.media.LocalUserMediaListEntry import me.proxer.app.profile.settings.LocalProfileSettings import me.proxer.app.profile.topten.LocalTopTenEntry import me.proxer.app.ui.view.bbcode.BBArgs import me.proxer.app.ui.view.bbcode.toBBTree import me.proxer.app.ui.view.bbcode.toSimpleBBTree import me.proxer.library.entity.anime.Stream import me.proxer.library.entity.chat.ChatMessage import me.proxer.library.entity.forum.Post import me.proxer.library.entity.forum.Topic import me.proxer.library.entity.info.Comment import me.proxer.library.entity.info.Entry import me.proxer.library.entity.info.EntryCore import me.proxer.library.entity.info.EntrySeasonInfo import me.proxer.library.entity.info.Synonym import me.proxer.library.entity.list.Tag import me.proxer.library.entity.manga.Chapter import me.proxer.library.entity.manga.Page import me.proxer.library.entity.messenger.Conference import me.proxer.library.entity.messenger.Message import me.proxer.library.entity.ucp.UcpHistoryEntry import me.proxer.library.entity.ucp.UcpSettings import me.proxer.library.entity.ucp.UcpTopTenEntry import me.proxer.library.entity.user.TopTenEntry import me.proxer.library.entity.user.UserComment import me.proxer.library.entity.user.UserHistoryEntry import me.proxer.library.entity.user.UserMediaListEntry import me.proxer.library.enums.AnimeLanguage import me.proxer.library.enums.CalendarDay import me.proxer.library.enums.Category import me.proxer.library.enums.Country import me.proxer.library.enums.FskConstraint import me.proxer.library.enums.Gender import me.proxer.library.enums.IndustryType import me.proxer.library.enums.Language import me.proxer.library.enums.License import me.proxer.library.enums.MediaLanguage import me.proxer.library.enums.MediaState import me.proxer.library.enums.MediaType import me.proxer.library.enums.Medium import me.proxer.library.enums.MessageAction import me.proxer.library.enums.RelationshipStatus import me.proxer.library.enums.Season import me.proxer.library.enums.SynonymType import me.proxer.library.enums.UserMediaProgress import me.proxer.library.util.ProxerUrls import me.proxer.library.util.ProxerUrls.hasProxerHost import okhttp3.HttpUrl import java.io.UnsupportedEncodingException import java.net.URLDecoder object ProxerLibExtensions { fun fskConstraintFromAppString(context: Context, string: String) = when (string) { context.getString(R.string.fsk_0) -> FskConstraint.FSK_0 context.getString(R.string.fsk_6) -> FskConstraint.FSK_6 context.getString(R.string.fsk_12) -> FskConstraint.FSK_12 context.getString(R.string.fsk_16) -> FskConstraint.FSK_16 context.getString(R.string.fsk_18) -> FskConstraint.FSK_18 context.getString(R.string.fsk_bad_language) -> FskConstraint.BAD_LANGUAGE context.getString(R.string.fsk_fear) -> FskConstraint.FEAR context.getString(R.string.fsk_violence) -> FskConstraint.VIOLENCE context.getString(R.string.fsk_sex) -> FskConstraint.SEX else -> error("Could not find fsk constraint for description: $description") } } fun Medium.toAppString(context: Context): String = context.getString( when (this) { Medium.ANIMESERIES -> R.string.medium_anime_series Medium.HENTAI -> R.string.medium_hentai Medium.MOVIE -> R.string.medium_movie Medium.OVA -> R.string.medium_ova Medium.MANGASERIES -> R.string.medium_manga_series Medium.LIGHTNOVEL -> R.string.medium_lightnovel Medium.WEBNOVEL -> R.string.medium_webnovel Medium.VISUALNOVEL -> R.string.medium_visualnovel Medium.DOUJIN -> R.string.medium_doujin Medium.HMANGA -> R.string.medium_h_manga Medium.ONESHOT -> R.string.medium_oneshot Medium.OTHER -> R.string.medium_other } ) fun MediaLanguage.toGeneralLanguage() = when (this) { MediaLanguage.GERMAN, MediaLanguage.GERMAN_SUB, MediaLanguage.GERMAN_DUB -> Language.GERMAN MediaLanguage.ENGLISH, MediaLanguage.ENGLISH_SUB, MediaLanguage.ENGLISH_DUB -> Language.ENGLISH MediaLanguage.OTHER -> Language.OTHER } fun MediaLanguage.toAnimeLanguage() = when (this) { MediaLanguage.GERMAN, MediaLanguage.GERMAN_SUB -> AnimeLanguage.GERMAN_SUB MediaLanguage.ENGLISH, MediaLanguage.ENGLISH_SUB -> AnimeLanguage.ENGLISH_SUB MediaLanguage.GERMAN_DUB -> AnimeLanguage.GERMAN_DUB MediaLanguage.ENGLISH_DUB -> AnimeLanguage.ENGLISH_DUB MediaLanguage.OTHER -> AnimeLanguage.OTHER } fun Language.toMediaLanguage() = when (this) { Language.GERMAN -> MediaLanguage.GERMAN Language.ENGLISH -> MediaLanguage.ENGLISH Language.OTHER -> MediaLanguage.OTHER } fun AnimeLanguage.toMediaLanguage() = when (this) { AnimeLanguage.GERMAN_SUB -> MediaLanguage.GERMAN_SUB AnimeLanguage.GERMAN_DUB -> MediaLanguage.GERMAN_DUB AnimeLanguage.ENGLISH_SUB -> MediaLanguage.ENGLISH_SUB AnimeLanguage.ENGLISH_DUB -> MediaLanguage.ENGLISH_DUB AnimeLanguage.OTHER -> MediaLanguage.OTHER } fun Language.toAppDrawable(context: Context) = AppCompatResources.getDrawable( context, when (this) { Language.GERMAN -> R.drawable.ic_germany Language.ENGLISH -> R.drawable.ic_united_states Language.OTHER -> R.drawable.ic_united_nations } ) ?: error("Could not resolve Drawable for language: $this") fun MediaLanguage.toAppString(context: Context): String = context.getString( when (this) { MediaLanguage.GERMAN -> R.string.language_german MediaLanguage.ENGLISH -> R.string.language_english MediaLanguage.GERMAN_SUB -> R.string.language_german_sub MediaLanguage.GERMAN_DUB -> R.string.language_german_dub MediaLanguage.ENGLISH_SUB -> R.string.language_english_sub MediaLanguage.ENGLISH_DUB -> R.string.language_english_dub MediaLanguage.OTHER -> R.string.language_other } ) fun Country.toAppDrawable(context: Context) = AppCompatResources.getDrawable( context, when (this) { Country.GERMANY -> R.drawable.ic_germany Country.ENGLAND -> R.drawable.ic_united_states Country.UNITED_STATES -> R.drawable.ic_united_states Country.JAPAN -> R.drawable.ic_japan Country.KOREA -> R.drawable.ic_korea Country.CHINA -> R.drawable.ic_china Country.INTERNATIONAL, Country.OTHER, Country.NONE -> R.drawable.ic_united_nations } ) ?: error("Could not resolve Drawable for country: $this") fun Medium.toCategory() = when (this) { Medium.ANIMESERIES, Medium.MOVIE, Medium.OVA, Medium.HENTAI -> Category.ANIME Medium.MANGASERIES, Medium.ONESHOT, Medium.DOUJIN, Medium.HMANGA -> Category.MANGA Medium.LIGHTNOVEL, Medium.WEBNOVEL, Medium.VISUALNOVEL -> Category.NOVEL Medium.OTHER -> error("Invalid medium: OTHER") } fun Category.toEpisodeAppString(context: Context, number: Int? = null): String = when (number) { null -> context.getString( when (this) { Category.ANIME -> R.string.category_anime_episodes_title Category.MANGA, Category.NOVEL -> R.string.category_manga_episodes_title } ) else -> context.getString( when (this) { Category.ANIME -> R.string.category_anime_episode_number Category.MANGA, Category.NOVEL -> R.string.category_manga_episode_number }, number ) } fun MediaState.toAppDrawable(context: Context): IconicsDrawable = IconicsDrawable(context).apply { icon = when (this@toAppDrawable) { MediaState.PRE_AIRING -> CommunityMaterial.Icon3.cmd_radio_tower MediaState.FINISHED -> CommunityMaterial.Icon.cmd_book MediaState.AIRING -> CommunityMaterial.Icon.cmd_book_open_variant MediaState.CANCELLED -> CommunityMaterial.Icon.cmd_close MediaState.CANCELLED_SUB -> CommunityMaterial.Icon.cmd_close } colorInt = context.resolveColor(R.attr.colorIcon) } fun UserMediaProgress.toEpisodeAppString( context: Context, episode: Int = 1, category: Category = Category.ANIME ): String = when (this) { UserMediaProgress.WATCHED -> context.getString( when (category) { Category.ANIME -> R.string.user_media_progress_watched Category.MANGA, Category.NOVEL -> R.string.user_media_progress_read } ) UserMediaProgress.WATCHING -> context.getString( when (category) { Category.ANIME -> R.string.user_media_progress_watching Category.MANGA, Category.NOVEL -> R.string.user_media_progress_reading }, episode ) UserMediaProgress.WILL_WATCH -> context.getString( when (category) { Category.ANIME -> R.string.user_media_progress_will_watch Category.MANGA, Category.NOVEL -> R.string.user_media_progress_will_read } ) UserMediaProgress.CANCELLED -> context.getString(R.string.user_media_progress_cancelled, episode) } fun Synonym.toTypeAppString(context: Context): String = context.getString( when (this.type) { SynonymType.ORIGINAL -> R.string.synonym_original_type SynonymType.ENGLISH -> R.string.synonym_english_type SynonymType.GERMAN -> R.string.synonym_german_type SynonymType.JAPANESE -> R.string.synonym_japanese_type SynonymType.KOREAN -> R.string.synonym_korean_type SynonymType.CHINESE -> R.string.synonym_chinese_type SynonymType.ORIGINAL_ALTERNATIVE -> R.string.synonym_alternative_type SynonymType.OTHER -> R.string.synonym_alternative_type } ) fun EntrySeasonInfo.toStartAppString(context: Context): String = when (season) { Season.WINTER -> context.getString(R.string.season_winter_start, year) Season.SPRING -> context.getString(R.string.season_spring_start, year) Season.SUMMER -> context.getString(R.string.season_summer_start, year) Season.AUTUMN -> context.getString(R.string.season_autumn_start, year) Season.UNSPECIFIED -> year.toString() } fun EntrySeasonInfo.toEndAppString(context: Context): String = when (season) { Season.WINTER -> context.getString(R.string.season_winter_end, year) Season.SPRING -> context.getString(R.string.season_spring_end, year) Season.SUMMER -> context.getString(R.string.season_summer_end, year) Season.AUTUMN -> context.getString(R.string.season_autumn_end, year) Season.UNSPECIFIED -> year.toString() } fun MediaState.toAppString(context: Context): String = context.getString( when (this) { MediaState.PRE_AIRING -> R.string.media_state_pre_airing MediaState.AIRING -> R.string.media_state_airing MediaState.CANCELLED -> R.string.media_state_cancelled MediaState.CANCELLED_SUB -> R.string.media_state_cancelled_sub MediaState.FINISHED -> R.string.media_state_finished } ) fun License.toAppString(context: Context): String = context.getString( when (this) { License.LICENSED -> R.string.license_licensed License.NOT_LICENSED -> R.string.license_not_licensed License.UNKNOWN -> R.string.license_unknown } ) fun FskConstraint.toAppString(context: Context): String = context.getString( when (this) { FskConstraint.FSK_0 -> R.string.fsk_0 FskConstraint.FSK_6 -> R.string.fsk_6 FskConstraint.FSK_12 -> R.string.fsk_12 FskConstraint.FSK_16 -> R.string.fsk_16 FskConstraint.FSK_18 -> R.string.fsk_18 FskConstraint.BAD_LANGUAGE -> R.string.fsk_bad_language FskConstraint.FEAR -> R.string.fsk_fear FskConstraint.VIOLENCE -> R.string.fsk_violence FskConstraint.SEX -> R.string.fsk_sex } ) fun FskConstraint.toAppStringDescription(context: Context): String = context.getString( when (this) { FskConstraint.FSK_0 -> R.string.fsk_0_description FskConstraint.FSK_6 -> R.string.fsk_6_description FskConstraint.FSK_12 -> R.string.fsk_12_description FskConstraint.FSK_16 -> R.string.fsk_16_description FskConstraint.FSK_18 -> R.string.fsk_18_description FskConstraint.BAD_LANGUAGE -> R.string.fsk_bad_language_description FskConstraint.FEAR -> R.string.fsk_fear_description FskConstraint.VIOLENCE -> R.string.fsk_violence_description FskConstraint.SEX -> R.string.fsk_sex_description } ) fun FskConstraint.toAppDrawable(context: Context) = AppCompatResources.getDrawable( context, when (this) { FskConstraint.FSK_0 -> R.drawable.ic_fsk_0 FskConstraint.FSK_6 -> R.drawable.ic_fsk_6 FskConstraint.FSK_12 -> R.drawable.ic_fsk_12 FskConstraint.FSK_16 -> R.drawable.ic_fsk_16 FskConstraint.FSK_18 -> R.drawable.ic_fsk_18 FskConstraint.BAD_LANGUAGE -> R.drawable.ic_fsk_bad_language FskConstraint.FEAR -> R.drawable.ic_fsk_fear FskConstraint.SEX -> R.drawable.ic_fsk_sex FskConstraint.VIOLENCE -> R.drawable.ic_fsk_violence } ) ?: error("Could not resolve Drawable for fsk constraint: $this") fun IndustryType.toAppString(context: Context): String = context.getString( when (this) { IndustryType.PUBLISHER -> R.string.industry_publisher IndustryType.STUDIO -> R.string.industry_studio IndustryType.STUDIO_SECONDARY -> R.string.industry_studio_secondary IndustryType.PRODUCER -> R.string.industry_producer IndustryType.RECORD_LABEL -> R.string.industry_record_label IndustryType.TALENT_AGENT -> R.string.industry_talent_agent IndustryType.STREAMING -> R.string.industry_streaming IndustryType.DEVELOPER -> R.string.industry_developer IndustryType.TV -> R.string.industry_tv IndustryType.SOUND_STUDIO -> R.string.industry_sound_studio IndustryType.UNKNOWN -> R.string.industry_unknown } ) fun CalendarDay.toAppString(context: Context): String = context.getString( when (this) { CalendarDay.MONDAY -> R.string.day_monday CalendarDay.TUESDAY -> R.string.day_tuesday CalendarDay.WEDNESDAY -> R.string.day_wednesday CalendarDay.THURSDAY -> R.string.day_thursday CalendarDay.FRIDAY -> R.string.day_friday CalendarDay.SATURDAY -> R.string.day_saturday CalendarDay.SUNDAY -> R.string.day_sunday } ) fun Gender.toAppString(context: Context): String = context.getString( when (this) { Gender.MALE -> R.string.gender_male Gender.FEMALE -> R.string.gender_female Gender.OTHER -> R.string.gender_other Gender.UNKNOWN -> R.string.gender_unknown } ) fun RelationshipStatus.toAppString(context: Context): String = context.getString( when (this) { RelationshipStatus.SINGLE -> R.string.relationship_status_single RelationshipStatus.IN_RELATION -> R.string.relationship_status_in_relation RelationshipStatus.ENGAGED -> R.string.relationship_status_engaged RelationshipStatus.COMPLICATED -> R.string.relationship_status_complicated RelationshipStatus.MARRIED -> R.string.relationship_status_married RelationshipStatus.SEARCHING -> R.string.relationship_status_searching RelationshipStatus.NOT_SEARCHING -> R.string.relationship_status_not_searching RelationshipStatus.UNKNOWN -> R.string.relationship_status_unknown } ) fun MessageAction.toAppString(context: Context, username: String, message: String): String = when (this) { MessageAction.ADD_USER -> context.getString(R.string.action_conference_add_user, "@$username", "@$message") MessageAction.REMOVE_USER -> context.getString(R.string.action_conference_delete_user, "@$username", "@$message") MessageAction.SET_LEADER -> context.getString(R.string.action_conference_set_leader, "@$username", "@$message") MessageAction.SET_TOPIC -> context.getString(R.string.action_conference_set_topic, "@$username", message) MessageAction.EXIT -> context.getString(R.string.action_conference_exit, "@$message") MessageAction.NONE -> message } fun MediaType.isAgeRestricted(): Boolean { return this == MediaType.ALL_WITH_HENTAI || this == MediaType.HENTAI || this == MediaType.HMANGA } inline val Chapter.isOfficial: Boolean get() = if (pages == null) { val serverUrl = server.toPrefixedUrlOrNull() serverUrl != null && serverUrl.host in arrayOf("www.webtoons.com", "www.lezhin.com") } else { false } inline val Entry.isTrulyAgeRestricted: Boolean get() = isAgeRestricted || medium == Medium.HMANGA || medium == Medium.HENTAI || fskConstraints.contains(FskConstraint.FSK_18) inline val EntryCore.isAgeRestricted: Boolean get() = medium == Medium.HMANGA || medium == Medium.HENTAI || fskConstraints.contains(FskConstraint.FSK_18) inline val Page.decodedName: String get() = try { URLDecoder.decode(name, "UTF-8") } catch (error: UnsupportedEncodingException) { "" } fun Stream.toAnimeStream( isSupported: Boolean, resolutionResult: StreamResolutionResult? = null ) = AnimeStream( id, hoster, hosterName, image, uploaderId, uploaderName, date.toInstantBP(), translatorGroupId, translatorGroupName, isOfficial, isPublic, isSupported, resolutionResult ) fun Conference.toLocalConference(isFullyLoaded: Boolean) = LocalConference( id.toLong(), topic, customTopic, participantAmount, image, imageType, isGroup, isRead, isRead, date.toInstantBP(), unreadMessageAmount, lastReadMessageId, isFullyLoaded ) fun UcpSettings.toLocalSettings() = LocalProfileSettings( profileVisibility, topTenVisibility, animeVisibility, mangaVisibility, commentVisibility, forumVisibility, friendVisibility, friendRequestConstraint, aboutVisibility, historyVisibility, guestBookVisibility, guestBookEntryConstraint, galleryVisibility, articleVisibility, isHideTags, isShowAds, adInterval ) fun Message.toLocalMessage() = LocalMessage( id.toLong(), conferenceId.toLong(), userId, username, message, action, date.toInstantBP(), device ) fun Comment.toParsedComment() = ParsedComment( id, entryId, authorId, mediaProgress, ratingDetails, content.toSimpleBBTree(), overallRating, episode, helpfulVotes, date.toInstantBP(), author, image ) fun Comment.toLocalComment() = LocalComment( id, entryId, mediaProgress, ratingDetails, content, overallRating, episode ) fun UserComment.toParsedUserComment() = ParsedUserComment( id, entryId, entryName, medium, category, authorId, mediaProgress, ratingDetails, content.toSimpleBBTree(), overallRating, episode, helpfulVotes, date.toInstantBP(), author, image ) fun Topic.toTopicMetaData() = TopicMetaData( categoryId, categoryName, firstPostDate, lastPostDate, hits, isLocked, post, subject ) fun Post.toParsedPost(resources: Resources): ParsedPost { val parsedMessage = message.toBBTree(BBArgs(resources = resources, userId = userId)) val parsedSignature = signature?.let { if (it.isNotBlank()) it.toBBTree(BBArgs(resources = resources, userId = userId)) else null } return ParsedPost( id, parentId, userId, username, image, date.toInstantBP(), parsedSignature, modifiedById, modifiedByName, modifiedReason, parsedMessage, thankYouAmount ) } fun Tag.toParcelableTag() = LocalTag(id, type, name, description, subType, isSpoiler) fun ChatMessage.toParsedMessage() = ParsedChatMessage(id, userId, username, image, message, action, date.toInstantBP()) fun UserMediaListEntry.toLocalEntry() = LocalUserMediaListEntry( id, name, episodeAmount, medium, state, commentId, commentContent, mediaProgress, episode, rating ) fun UserMediaListEntry.toLocalEntryUcp() = LocalUserMediaListEntry.Ucp( id, name, episodeAmount, medium, state, commentId, commentContent, mediaProgress, episode, rating ) fun UserHistoryEntry.toLocalEntry() = LocalUserHistoryEntry(id, entryId, name, language, medium, category, episode) fun UcpHistoryEntry.toLocalEntryUcp() = LocalUserHistoryEntry.Ucp( id, entryId, name, language, medium, category, episode, date ) fun TopTenEntry.toLocalEntry() = LocalTopTenEntry(id, name, category, medium) fun UcpTopTenEntry.toLocalEntryUcp() = LocalTopTenEntry.Ucp(id, name, category, medium, entryId) fun HttpUrl.proxyIfRequired() = when (this.hasProxerHost) { true -> this false -> ProxerUrls.proxyImage(this) }
src/main/kotlin/me/proxer/app/util/extension/ProxerLibExtensions.kt
1456778670
package com.androidvip.hebf.ui.main.tools.apps import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Environment import android.view.View import android.widget.* import androidx.lifecycle.lifecycleScope import com.androidvip.hebf.R import com.androidvip.hebf.applyAnim import com.androidvip.hebf.getThemedVectorDrawable import com.androidvip.hebf.models.App import com.androidvip.hebf.ui.base.BaseActivity import com.androidvip.hebf.utils.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_app_details.* import kotlinx.coroutines.launch import java.io.File // Todo: check target sdk 29 class AppDetailsActivity : BaseActivity() { private lateinit var appPackageName: TextView private lateinit var appVersion: TextView private lateinit var storageDetails: TextView private lateinit var pathDetails: TextView private lateinit var storage: LinearLayout private lateinit var path: LinearLayout private lateinit var appOps: FrameLayout private lateinit var appIcon: ImageView private lateinit var packagesManager: PackagesManager private var sdSize: Long = 0 private var internalSize: Long = 0 private var appSize: Long = 0 private lateinit var apkFile: File private var aPackageName: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_app_details) setUpToolbar(toolbar) bindViews() packagesManager = PackagesManager(this) // Check the data from intent val app = intent.getSerializableExtra(K.EXTRA_APP) as App? if (app != null) { aPackageName = app.packageName // Update Toolbar title with app name supportActionBar?.title = app.label // Show info according to the given package name appIcon.setImageDrawable(packagesManager.getAppIcon(app.packageName)) appPackageName.text = app.packageName appVersion.text = "v${app.versionName}" // Get disabled state of the package and set button text accordingly if (!app.isEnabled) appDetailsDisable.setText(R.string.enable) appOps.setOnClickListener { val i = Intent(this@AppDetailsActivity, AppOpsActivity::class.java) i.putExtra(K.EXTRA_APP, intent.getSerializableExtra(K.EXTRA_APP)) startActivity(i) } lifecycleScope.launch(workerContext) { // Check if the system has the appops binary val supportsAppOps = RootUtils.executeSync("which appops").isNotEmpty() // Get the package installation path from the PackageManager val pathString = Utils.runCommand( "pm path ${aPackageName!!}", getString(android.R.string.unknownName) ).replace("package:", "") apkFile = File(pathString) if (apkFile.exists()) { appSize = runCatching { // Get root installation folder size RootUtils.executeWithOutput( "du -s ${apkFile.parentFile.absolutePath} | awk '{print $1}'", "0" ).toLong() }.getOrElse { runCatching { RootUtils.executeWithOutput( "du -s ${apkFile.parentFile.absolutePath} | awk '{print $1}'", "0" ).toLong() }.getOrDefault(0) } } try { // Get external folder size sdSize = FileUtils.getFileSize(File("${Environment.getExternalStorageDirectory()}/Android/data/$aPackageName")) / 1024 // Get root data folder size internalSize = RootUtils.executeWithOutput("du -s /data/data/$aPackageName | awk '{print $1}'", "0").toLong() } catch (e: Exception) { try { //again sdSize = FileUtils.getFileSize(File("${Environment.getExternalStorageDirectory()}/Android/data/$aPackageName")) / 1024 internalSize = RootUtils.executeWithOutput("du -s /data/data/$aPackageName | awk '{print $1}'", "0").toLong() } catch (ex: Exception) { sdSize = 0 internalSize = 0 } } runSafeOnUiThread { /* * Compute and show total storage size on the UI Thread. * Set pathDetails text to the package path obtained from PackageManager, * this path is used to share .apk file of the app. */ val finalSize = (sdSize + internalSize + appSize) / 1024 pathDetails.text = pathString storageDetails.text = "$finalSize MB" findViewById<View>(R.id.app_details_progress).visibility = View.GONE findViewById<View>(R.id.app_details_detail_layout).visibility = View.VISIBLE if (!supportsAppOps) { appOps.visibility = View.GONE Logger.logWarning("Appops is not supported", this@AppDetailsActivity) } } } // Show storage usage details storage.setOnClickListener { MaterialAlertDialogBuilder(this@AppDetailsActivity) .setTitle(R.string.storage) .setMessage("SD: ${if (sdSize >= 1024) "${(sdSize / 1024)}MB\n" else "${sdSize}KB\n"}Internal: ${if (internalSize >= 1024) "${(internalSize / 1024)}MB\n" else "${internalSize}KB\n"}App: ${appSize / 1024}MB") .setPositiveButton(R.string.clear_data) { _, _ -> // Clear data associated with the package using the PackageManager runCommand("pm clear ${aPackageName!!}") Logger.logInfo("Cleared data of the package: ${aPackageName!!}", this) } .setNegativeButton(R.string.close) { _, _ -> } .applyAnim().also { it.show() } } path.setOnClickListener { if (apkFile.isFile) { // Share .apk file val uri = Uri.parse(apkFile.toString()) val share = Intent(Intent.ACTION_SEND) share.type = "application/octet-stream" share.putExtra(Intent.EXTRA_STREAM, uri) startActivity(Intent.createChooser(share, "Share APK File")) } } // Disable or enable package appDetailsDisable.setOnClickListener { if (app.isEnabled) { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.warning)) .setIcon(getThemedVectorDrawable(R.drawable.ic_warning)) .setMessage(getString(R.string.confirmation_message)) .setNegativeButton(R.string.cancelar) { _, _ -> } .setPositiveButton(R.string.disable) { _, _ -> runCommand("pm disable ${aPackageName!!}") Logger.logInfo("Disabled package: ${aPackageName!!}", this) Snackbar.make(appDetailsDisable, R.string.package_disabled, Snackbar.LENGTH_LONG).show() // Update button text appDetailsDisable.setText(R.string.enable) }.applyAnim().also { it.show() } } else { // Enable package using the PackageManager and update button text runCommand("pm enable ${aPackageName!!}") Logger.logInfo("Enabled package: ${aPackageName!!}", this) appDetailsDisable.setText(R.string.disable) } } appDetailsUninstall.setOnClickListener { Logger.logWarning("Attempting to uninstall package: ${aPackageName!!}", this) if (app.isSystemApp) { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.warning)) .setIcon(getThemedVectorDrawable(R.drawable.ic_warning)) .setMessage(getString(R.string.confirmation_message)) .setNegativeButton(android.R.string.cancel) { _, _ -> } .setPositiveButton(R.string.uninstall) { _, _ -> lifecycleScope.launch(workerContext) { // Get package path val packagePathString = RootUtils.executeWithOutput("pm path ${aPackageName!!}", "", this@AppDetailsActivity).substring(8) val packagePath = File(packagePathString) if (packagePath.isFile) { RootUtils.deleteFileOrDir(packagePathString) RootUtils.deleteFileOrDir("${Environment.getDataDirectory()}/data/$aPackageName") Logger.logInfo("Deleted package: ${aPackageName!!}", this@AppDetailsActivity) runSafeOnUiThread { MaterialAlertDialogBuilder(this@AppDetailsActivity) .setTitle(R.string.package_uninstalled) .setMessage("Reboot your device") .setPositiveButton(android.R.string.ok) { _, _ -> } .setNeutralButton(R.string.reboot) { _, _ -> runCommand("reboot") } .applyAnim().also { it.show() } } } else { runSafeOnUiThread { Snackbar.make(appDetailsUninstall, "${getString(R.string.error)}: $packagePath does not exist", Snackbar.LENGTH_LONG).show() } } } } .applyAnim().also { it.show() } } else { // User app, invoke Android uninstall dialog and let it deal with the package try { val packageURI = Uri.parse("package:${aPackageName!!}") val uninstallIntent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI) startActivity(uninstallIntent) } catch (e: Exception) { Toast.makeText(this@AppDetailsActivity, "Could not launch uninstall dialog for package: $aPackageName. Reason: ${e.message}", Toast.LENGTH_LONG).show() Logger.logError("Could not launch uninstall dialog for package: $aPackageName. Reason: ${e.message}", this@AppDetailsActivity) } } } } else { // Something went wrong, return back to the previous screen Logger.logWTF("Failed to show app details because no app was provided to begin with", this) Toast.makeText(this, R.string.failed, Toast.LENGTH_SHORT).show() finish() } } private fun bindViews() { appPackageName = findViewById(R.id.app_details_package_name) appVersion = findViewById(R.id.app_details_version) appIcon = findViewById(R.id.app_details_icon) appOps = findViewById(R.id.app_details_app_ops) storage = findViewById(R.id.app_details_storage) storageDetails = findViewById(R.id.app_details_storage_sum) path = findViewById(R.id.app_details_path) pathDetails = findViewById(R.id.app_details_path_sum) } }
app/src/main/java/com/androidvip/hebf/ui/main/tools/apps/AppDetailsActivity.kt
3901350733
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hcl.terraform.config.watchers.macros import com.intellij.ide.macro.Macro import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import org.intellij.plugins.hcl.terraform.TerraformToolProjectSettings class TerraformExecutableMacro : Macro() { companion object { fun isRegistered() = MacrosInstaller.isPluginMacrosSupported } override fun getName(): String { return "TerraformExecPath" } override fun getDescription(): String { return "Terraform executable path" } @Throws(Macro.ExecutionCancelledException::class) override fun expand(dataContext: DataContext): String? { val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return null return TerraformToolProjectSettings.getInstance(project).terraformPath } }
src/kotlin/org/intellij/plugins/hcl/terraform/config/watchers/macros/TerraformExecutableMacro.kt
2432443353
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.core import android.app.Application import android.content.Context import android.content.Intent import android.graphics.Point import android.graphics.Rect import android.graphics.drawable.Drawable import android.os.Build import android.view.WindowManager import androidx.appcompat.app.AppCompatDelegate import androidx.core.content.res.ResourcesCompat import fr.cph.chicago.R import fr.cph.chicago.core.activity.ErrorActivity import fr.cph.chicago.core.model.Theme import fr.cph.chicago.service.PreferenceService import io.reactivex.rxjava3.plugins.RxJavaPlugins import timber.log.Timber import timber.log.Timber.DebugTree /** * Main class that extends Application. Mainly used to get the context from anywhere in the app. * * @author Carl-Philipp Harmant * @version 1 */ class App : Application() { companion object { lateinit var instance: App private val preferenceService = PreferenceService fun startErrorActivity() { val context = instance.applicationContext val intent = Intent(context, ErrorActivity::class.java) intent.putExtra(context.getString(R.string.bundle_error), "Something went wrong") intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } } var refresh: Boolean = false val lineWidthGoogleMap: Float by lazy { if (screenWidth > 1080) 7f else if (screenWidth > 480) 4f else 2f } val lineWidthMapBox: Float by lazy { if (screenWidth > 1080) 2f else if (screenWidth > 480) 1f else 2f } val streetViewPlaceHolder: Drawable by lazy { ResourcesCompat.getDrawable(resources, R.drawable.placeholder_street_view, this.theme)!! } override fun onCreate() { instance = this Timber.plant(DebugTree()) RxJavaPlugins.setErrorHandler { throwable -> Timber.e(throwable, "RxError not handled") startErrorActivity() } themeSetup() super.onCreate() } fun themeSetup() { when (preferenceService.getTheme()) { Theme.AUTO -> { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY) } } Theme.LIGHT -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) Theme.DARK -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } } val screenWidth: Int by lazy { when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> { val windowManager: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager val rect: Rect = windowManager.currentWindowMetrics.bounds rect.width() } else -> { val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager val display = wm.defaultDisplay val point = Point() display.getSize(point) point.x } } } }
android-app/src/main/kotlin/fr/cph/chicago/core/App.kt
2382692928
package com.nextcloud.client.etm.pages import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.nextcloud.client.etm.EtmBaseFragment import com.owncloud.android.R import kotlinx.android.synthetic.main.fragment_etm_migrations.* import java.util.Locale class EtmMigrations : EtmBaseFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_etm_migrations, container, false) } override fun onResume() { super.onResume() showStatus() } fun showStatus() { val builder = StringBuilder() val status = vm.migrationsStatus.toString().toLowerCase(Locale.US) builder.append("Migration status: $status\n") val lastMigratedVersion = if (vm.lastMigratedVersion >= 0) { vm.lastMigratedVersion.toString() } else { "never" } builder.append("Last migrated version: $lastMigratedVersion\n") builder.append("Migrations:\n") vm.migrationsInfo.forEach { val migrationStatus = if (it.applied) { "applied" } else { "pending" } builder.append(" - ${it.id} ${it.description} - $migrationStatus\n") } etm_migrations_text.text = builder.toString() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_etm_migrations, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.etm_migrations_delete -> { onDeleteMigrationsClicked(); true } else -> super.onOptionsItemSelected(item) } } private fun onDeleteMigrationsClicked() { vm.clearMigrations() showStatus() } }
src/main/java/com/nextcloud/client/etm/pages/EtmMigrations.kt
3997574987
package com.chrynan.chords.model import android.os.Parcelable import com.chrynan.chords.parcel.ChordChartParceler import kotlinx.android.parcel.Parcelize import kotlinx.android.parcel.WriteWith @Parcelize data class ParcelableChartWrapper(val chart: @WriteWith<ChordChartParceler> ChordChart) : Parcelable
android/src/main/java/com/chrynan/chords/model/ParcelableChartWrapper.kt
2333090996
package i_introduction._9_Extensions_On_Collections import kotlin.test.* import org.junit.Test as test import org.junit.Assert class _09_Extensions_On_Collections { test fun testCollectionOfOneElement() { doTest(listOf("a"), listOf("a")) } test fun testEmptyCollection() { doTest(null, listOf()) } test fun testSimpleCollection() { doTest(listOf("a", "c"), listOf("a", "bb", "c")) } test fun testCollectionWithEmptyStrings() { doTest(listOf("", "", "", ""), listOf("", "", "", "", "a", "bb", "ccc", "dddd")) } test fun testCollectionWithTwoGroupsOfMaximalSize() { doTest(listOf("a", "c"), listOf("a", "bb", "c", "dd")) } private fun doTest(expected: Collection<String>?, argument: Collection<String>) { Assert.assertEquals("The function 'doSomethingStrangeWithCollection' should do at least something with a collection:", expected, doSomethingStrangeWithCollection(argument)) } }
test/i_introduction/_9_Extensions_On_Collections/_09_Extensions_On_Collections.kt
2213883994
/* * Sone - SoneInsertingEvent.kt - Copyright © 2013–2020 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.core.event import net.pterodactylus.sone.data.* /** * Event that signals that a [Sone] is now being inserted. */ class SoneInsertingEvent(sone: Sone) : SoneEvent(sone)
src/main/kotlin/net/pterodactylus/sone/core/event/SoneInsertingEvent.kt
3331494774
package cz.vhromada.catalog.web.domain import cz.vhromada.catalog.entity.Season import cz.vhromada.common.entity.Time import java.io.Serializable import java.util.Objects /** * A class represents season data. * * @author Vladimir Hromada */ data class SeasonData( /** * Season */ val season: Season, /** * Count of episodes */ val episodesCount: Int, /** * Total length */ val totalLength: Time) : Serializable { override fun equals(other: Any?): Boolean { if (this === other) { return true } return if (other !is SeasonData) { false } else season == other.season } override fun hashCode(): Int { return Objects.hashCode(season) } }
src/main/kotlin/cz/vhromada/catalog/web/domain/SeasonData.kt
4055534787
package org.rcgonzalezf.weather.openweather.model import org.rcgonzalezf.weather.common.models.converter.Data class OpenWeatherCurrentData : Data { val name: String? = null val cod: String? = null val wind: Wind? = null val weather: List<Weather>? = null val sys: Sys? = null val dt: Long = 0 val main: Main? = null }
weather-library/src/main/java/org/rcgonzalezf/weather/openweather/model/OpenWeatherCurrentData.kt
1207050589
package chat.willow.warren.event import kotlin.reflect.KClass interface IEventListener<in T> { fun on(event: T) } interface IEventListenersWrapper<T> { fun add(listener: (T) -> Unit) fun fireToAll(event: T) operator fun plusAssign(listener: (T) -> Unit) = add(listener) } class EventListenersWrapper<T> : IEventListenersWrapper<T> { private var listeners: Set<IEventListener<T>> = setOf() override fun fireToAll(event: T) { listeners.forEach { it.on(event) } } override fun add(listener: (T) -> Unit) { listeners += object : IEventListener<T> { override fun on(event: T) = listener(event) } } } interface IWarrenEventDispatcher { fun <T : IWarrenEvent> fire(event: T) fun <T : IWarrenEvent> on(eventClass: KClass<T>, listener: (T) -> Unit) fun onAny(listener: (Any) -> Unit) } class WarrenEventDispatcher : IWarrenEventDispatcher { private val onAnythingListeners: IEventListenersWrapper<Any> = EventListenersWrapper<Any>() private var eventToListenersMap = mutableMapOf<Class<*>, IEventListenersWrapper<*>>() override fun <T : IWarrenEvent> fire(event: T) { onAnythingListeners.fireToAll(event) @Suppress("UNCHECKED_CAST") val listenersWrapper = eventToListenersMap[event::class.java] as? IEventListenersWrapper<T> listenersWrapper?.fireToAll(event) } override fun <T : IWarrenEvent> on(eventClass: KClass<T>, listener: (T) -> Unit) { val wrapper = eventToListenersMap[eventClass.java] ?: constructAndAddWrapperForEvent(eventClass) @Suppress("UNCHECKED_CAST") val typedWrapper = wrapper as? IEventListenersWrapper<T> ?: return typedWrapper += listener } override fun onAny(listener: (Any) -> Unit) { onAnythingListeners += listener } private fun <T : IWarrenEvent> constructAndAddWrapperForEvent(eventClass: KClass<T>): IEventListenersWrapper<T> { val newWrapper = EventListenersWrapper<T>() eventToListenersMap[eventClass.java] = newWrapper return newWrapper } }
src/main/kotlin/chat/willow/warren/event/WarrenEventDispatcher.kt
1294530340
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.ds3autogen.go.models.response data class ResponseCode(val code: Int, val parseResponse: String)
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/models/response/ResponseCode.kt
123433867
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.ui.browse import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlaylistPlay import androidx.compose.material.icons.filled.Settings import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.wear.compose.material.ScalingLazyListState import com.google.android.horologist.media.ui.screens.browse.BrowseScreen import com.google.android.horologist.media.ui.screens.browse.BrowseScreenPlaylistsSectionButton import com.google.android.horologist.mediasample.R @Composable fun UampStreamingBrowseScreen( onPlaylistsClick: () -> Unit, onSettingsClick: () -> Unit, scalingLazyListState: ScalingLazyListState, modifier: Modifier = Modifier ) { BrowseScreen( scalingLazyListState = scalingLazyListState, modifier = modifier ) { this.playlistsSection( buttons = listOf( BrowseScreenPlaylistsSectionButton( textId = R.string.horologist_browse_library_playlists_button, icon = Icons.Default.PlaylistPlay, onClick = onPlaylistsClick ), BrowseScreenPlaylistsSectionButton( textId = R.string.horologist_browse_library_settings_button, icon = Icons.Default.Settings, onClick = onSettingsClick ) ) ) } }
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/browse/UampStreamingBrowseScreen.kt
2566516890
/* * Copyright 2016 Jonathan Beaudoin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xena.offsets.offsets import com.github.jonatino.misc.Strings import org.xena.offsets.OffsetManager.engineModule import org.xena.offsets.misc.PatternScanner import org.xena.offsets.misc.PatternScanner.byPattern import java.io.IOException import java.lang.reflect.Field import java.nio.file.Files import java.nio.file.Paths /** * Created by Jonathan on 11/13/2015. */ object EngineOffsets { /** * Engine.dll offsets */ @JvmField var dwClientState: Int = 0 @JvmField var dwInGame: Int = 0 @JvmField var dwMaxPlayer: Int = 0 @JvmField var dwMapDirectory: Int = 0 @JvmField var dwMapname: Int = 0 @JvmField var dwPlayerInfo: Int = 0 @JvmField var dwViewAngles: Int = 0 @JvmField var dwEnginePosition: Int = 0 @JvmField var m_bCanReload: Int = 0 @JvmField var bSendPacket: Int = 0 @JvmField var dwLocalPlayerIndex: Int = 0 @JvmField var dwGlobalVars: Int = 0 @JvmField var dwSignOnState: Int = 0 @JvmStatic fun load() { dwGlobalVars = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0x68, 0x0, 0x0, 0x0, 0x0, 0x68, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x50, 0x08, 0x85, 0xC0) dwClientState = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x33, 0xD2, 0x6A, 0x0, 0x6A, 0x0, 0x33, 0xC9, 0x89, 0xB0) dwInGame = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x83, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x94, 0xC0, 0xC3) dwMaxPlayer = byPattern(engineModule(), 0x7, 0x0, PatternScanner.READ, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x80, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x8A, 0x45, 0x08) dwMapDirectory = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ, 0x05, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x80, 0x3D) dwMapname = byPattern(engineModule(), 0x1, 0x0, PatternScanner.READ, 0x05, 0x00, 0x00, 0x00, 0x00, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xA1, 0x00, 0x00, 0x00, 0x00) dwPlayerInfo = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x8B, 0x89, 0x00, 0x00, 0x00, 0x00, 0x85, 0xC9, 0x0F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x01) dwViewAngles = byPattern(engineModule(), 0x4, 0x0, PatternScanner.READ, 0xF3, 0x0F, 0x11, 0x80, 0x00, 0x00, 0x00, 0x00, 0xD9, 0x46, 0x04, 0xD9, 0x05, 0x00, 0x00, 0x00, 0x00) dwEnginePosition = byPattern(engineModule(), 0x4, 0x0, PatternScanner.READ or PatternScanner.SUBTRACT, 0xF3, 0x0F, 0x11, 0x15, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x0D, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x05, 0x00, 0x00, 0x00, 0x00, 0xF3, 0x0F, 0x11, 0x3D, 0x00, 0x00, 0x00, 0x00) dwLocalPlayerIndex = byPattern(engineModule(), 0x2, 0x0, PatternScanner.READ, 0x8B, 0x80, 0x00, 0x00, 0x00, 0x00, 0x40, 0xC3) bSendPacket = byPattern(engineModule(), 0, 0, PatternScanner.SUBTRACT, 0x01, 0x8B, 0x01, 0x8B, 0x40, 0x10) dwSignOnState = byPattern(engineModule(), 2, 0, PatternScanner.READ, 0x83, 0xB8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0F, 0x94, 0xC0, 0xC3) } @JvmStatic fun dump() { val text = EngineOffsets::class.java.fields.map { it.name + " -> " + Strings.hex(getValue(it)) } try { Files.write(Paths.get("EngineOffsets.txt"), text) } catch (e: IOException) { e.printStackTrace() } } private fun getValue(field: Field): Int { try { return field.get(EngineOffsets::class.java) as? Int ?: -1 } catch (t: Throwable) { t.printStackTrace() } return -1 } }
src/main/java/org/xena/offsets/offsets/EngineOffsets.kt
3821847780
package karballo object TestColors { val ANSI_RESET = "\u001B[0m" val ANSI_RED = "\u001B[31m" val ANSI_GREEN = "\u001B[32m" val ANSI_WHITE = "\u001B[37m" }
karballo-jvm/src/test/kotlin/karballo/TestColors.kt
3933116310
package com.eden.orchid.javadoc.pages import com.copperleaf.javadoc.json.models.JavaDocElement import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.javadoc.JavadocGenerator import com.eden.orchid.javadoc.resources.BaseJavadocResource @Archetype(value = ConfigArchetype::class, key = "${JavadocGenerator.GENERATOR_KEY}.pages") abstract class BaseJavadocPage( resource: BaseJavadocResource, key: String, title: String ) : OrchidPage(resource, key, title) { fun renderCommentText(el: JavaDocElement) : String { val builder = StringBuilder() for(commentComponent in el.comment) { if(commentComponent.kind in listOf("see", "link")) { val linkedPage = context.findPage(null, null, commentComponent.className) if(linkedPage != null) { builder.append(""" <a href="${linkedPage.link}">${linkedPage.title}</a> """) } } else { builder.append(commentComponent.text) } } return builder.toString() } }
plugins/OrchidJavadoc/src/main/kotlin/com/eden/orchid/javadoc/pages/BaseJavadocPage.kt
2159519289
package org.wordpress.android.fluxc.example.ui.customer import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_woo_customer.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.wordpress.android.fluxc.example.R import org.wordpress.android.fluxc.example.prependToLog import org.wordpress.android.fluxc.example.replaceFragment import org.wordpress.android.fluxc.example.ui.customer.creation.WooCustomerCreationFragment import org.wordpress.android.fluxc.example.ui.customer.search.WooCustomersSearchBuilderFragment import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment import org.wordpress.android.fluxc.example.utils.showSingleLineDialog import org.wordpress.android.fluxc.store.WCCustomerStore import javax.inject.Inject class WooCustomersFragment : StoreSelectingFragment() { @Inject internal lateinit var wcCustomerStore: WCCustomerStore private val coroutineScope = CoroutineScope(Dispatchers.Main) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_woo_customer, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btnPrintCutomer.setOnClickListener { printCustomerById() } btnFetchCustomerList.setOnClickListener { replaceFragment(WooCustomersSearchBuilderFragment.newInstance(selectedSite!!.id)) } btnCreateCustomer.setOnClickListener { replaceFragment(WooCustomerCreationFragment.newInstance(selectedSite!!.id)) } } private fun printCustomerById() { val site = selectedSite!! showSingleLineDialog( activity, "Enter the remote customer Id:", isNumeric = true ) { remoteIdEditText -> if (remoteIdEditText.text.isEmpty()) { prependToLog("Remote Id is null so doing nothing") return@showSingleLineDialog } val remoteId = remoteIdEditText.text.toString().toLong() prependToLog("Submitting request to print customer with id: $remoteId") coroutineScope.launch { withContext(Dispatchers.Default) { wcCustomerStore.fetchSingleCustomer(site, remoteId) }.run { error?.let { prependToLog("${it.type}: ${it.message}") } if (model != null) { prependToLog("Customer data: ${this.model}") } else { prependToLog("Customer with id $remoteId is missing") } } } } } }
example/src/main/java/org/wordpress/android/fluxc/example/ui/customer/WooCustomersFragment.kt
787044679
package fr.corenting.edcompanion.network.retrofit import fr.corenting.edcompanion.models.apis.Inara.InaraProfileRequestBody import fr.corenting.edcompanion.models.apis.Inara.InaraProfileResponse import retrofit2.http.Body import retrofit2.http.POST interface InaraRetrofit { @POST("inapi/v1/") suspend fun getProfile(@Body body: InaraProfileRequestBody): InaraProfileResponse }
app/src/main/java/fr/corenting/edcompanion/network/retrofit/InaraRetrofit.kt
2264469062
package upcomingmovies.andresmr.com.upcomingmovies.ui import android.app.Activity import android.content.Intent import android.graphics.Color import android.widget.TextView import org.jetbrains.anko.textColor import upcomingmovies.andresmr.com.upcomingmovies.data.entities.Result inline fun <reified T : Activity> Activity.navigate(movie: Result? = null) { val intent = Intent(this, T::class.java) intent.putExtra("movie", movie) startActivity(intent) } fun TextView.showMovieHeader(movie: Result?) { textColor = Color.BLACK textSize = 20f val headerTitle = movie?.title + " - " + movie?.popularity text = headerTitle } fun TextView.showMovieContent(movie: Result?) { text = movie?.overview }
app/src/main/java/upcomingmovies/andresmr/com/upcomingmovies/ui/FuntionUtils.kt
612292482
/* * Copyright 2020 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.dagger.modules.about import com.github.vase4kin.teamcityapp.api.Repository import dagger.Module import dagger.Provides import teamcityapp.features.about.repository.AboutRepository @Module object AboutRepositoryModule { @JvmStatic @Provides fun providesRepository(repository: Repository): AboutRepository = repository }
app/src/main/java/com/github/vase4kin/teamcityapp/dagger/modules/about/AboutRepositoryModule.kt
1068670105
package com.hosshan.android.salad.component.scene.log import kotlin.properties.Delegates /** * LogPresenter Implements */ internal class LogPresenterImpl : LogPresenter { var view: LogView by Delegates.notNull() override fun initialize(view: LogView) { this.view = view } }
app/src/main/kotlin/com/hosshan/android/salad/component/scene/log/LogPresenterImpl.kt
3308256802
package it.sephiroth.android.library.bottomnavigation import android.graphics.Canvas import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable import android.os.SystemClock /** * Created by crugnola on 4/12/16. * * The MIT License */ class BadgeDrawable(color: Int, private val size: Int) : Drawable() { private val paint = Paint(Paint.ANTI_ALIAS_FLAG) private var startTimeMillis: Long = 0 var animating: Boolean = true init { this.paint.color = color } override fun draw(canvas: Canvas) { if (!animating) { paint.alpha = ALPHA_MAX.toInt() drawInternal(canvas) } else { if (startTimeMillis == 0L) { startTimeMillis = SystemClock.uptimeMillis() } val normalized = (SystemClock.uptimeMillis() - startTimeMillis) / FADE_DURATION if (normalized >= 1f) { animating = false paint.alpha = ALPHA_MAX.toInt() drawInternal(canvas) } else { val partialAlpha = (ALPHA_MAX * normalized).toInt() alpha = partialAlpha drawInternal(canvas) } } } private fun drawInternal(canvas: Canvas) { val bounds = bounds val w = bounds.width() val h = bounds.height() canvas.drawCircle((bounds.centerX() + w / 2).toFloat(), (bounds.centerY() - h / 2).toFloat(), (w / 2).toFloat(), paint) } override fun setAlpha(alpha: Int) { paint.alpha = alpha invalidateSelf() } override fun getAlpha(): Int { return paint.alpha } override fun isStateful(): Boolean { return false } override fun setColorFilter(colorFilter: ColorFilter?) { paint.colorFilter = colorFilter invalidateSelf() } override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } override fun getIntrinsicHeight(): Int { return size } override fun getIntrinsicWidth(): Int { return size } companion object { const val FADE_DURATION = 100f const val ALPHA_MAX = 255f } }
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BadgeDrawable.kt
1045154832
package me.mrkirby153.KirBot import me.mrkirby153.kcutils.child import me.mrkirby153.kcutils.createFileIfNotExist import java.io.File class BotFiles { val data = File("data").apply { if (!exists()) mkdir() } val properties = data.child("config.properties").createFileIfNotExist() val admins = data.child("admins").createFileIfNotExist() val schedule = data.child("schedule.json") }
src/main/kotlin/me/mrkirby153/KirBot/BotFiles.kt
1033251793
/* * Copyright 2021 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.activities import com.pitchedapps.frost.helper.activityRule import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import org.junit.Rule import org.junit.Test @HiltAndroidTest class SelectorActivityTest { @get:Rule(order = 0) val hildAndroidRule = HiltAndroidRule(this) @get:Rule(order = 1) val activityRule = activityRule<SelectorActivity>() @Test fun initializesSuccessfully() { activityRule.scenario.use { it.onActivity { // Verify no crash } } } }
app/src/androidTest/kotlin/com/pitchedapps/frost/activities/SelectorActivityTest.kt
1151050446
package com.netflix.spinnaker.mockito import org.mockito.stubbing.OngoingStubbing infix fun <P1, R> OngoingStubbing<R>.doStub(stub: (P1) -> R): OngoingStubbing<R> = thenAnswer { it.arguments.run { @Suppress("UNCHECKED_CAST") stub.invoke(component1() as P1) } } infix fun <P1, P2, R> OngoingStubbing<R>.doStub(stub: (P1, P2) -> R): OngoingStubbing<R> = thenAnswer { it.arguments.run { @Suppress("UNCHECKED_CAST") stub.invoke(component1() as P1, component2() as P2) } } infix fun <P1, P2, P3, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3) -> R): OngoingStubbing<R> = thenAnswer { it.arguments.run { @Suppress("UNCHECKED_CAST") stub.invoke(component1() as P1, component2() as P2, component3() as P3) } } /* ktlint-disable max-line-length */ infix fun <P1, P2, P3, P4, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3, P4) -> R): OngoingStubbing<R> = thenAnswer { it.arguments.run { @Suppress("UNCHECKED_CAST") stub.invoke(component1() as P1, component2() as P2, component3() as P3, component4() as P4) } } infix fun <P1, P2, P3, P4, P5, R> OngoingStubbing<R>.doStub(stub: (P1, P2, P3, P4, P5) -> R): OngoingStubbing<R> = thenAnswer { it.arguments.run { @Suppress("UNCHECKED_CAST") stub.invoke(component1() as P1, component2() as P2, component3() as P3, component4() as P4, component5() as P5) } } /* ktlint-enable max-line-length */
keiko-test-common/src/main/kotlin/com/netflix/spinnaker/mockito/mockito_extensions.kt
1746736022
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.prx.view internal sealed class PRXScreenViewEvent internal object NavigateUpEvent : PRXScreenViewEvent() internal object TurnOnAlert : PRXScreenViewEvent() internal object TurnOffAlert : PRXScreenViewEvent() internal object DisconnectEvent : PRXScreenViewEvent() internal object OpenLoggerEvent : PRXScreenViewEvent()
profile_prx/src/main/java/no/nordicsemi/android/prx/view/PRXScreenViewEvent.kt
3190015852
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.kryptnostic.rhizome.hazelcast.serializers.AbstractStreamSerializerTest import com.openlattice.assembler.AssemblerConnectionManager import com.openlattice.assembler.processors.DeleteOrganizationAssemblyProcessor import org.mockito.Mockito class DeleteOrganizationAssemblyProcessorStreamSerializerTest : AbstractStreamSerializerTest<DeleteOrganizationAssemblyProcessorStreamSerializer, DeleteOrganizationAssemblyProcessor>() { override fun createSerializer(): DeleteOrganizationAssemblyProcessorStreamSerializer { val processorSerializer = DeleteOrganizationAssemblyProcessorStreamSerializer() processorSerializer.init(Mockito.mock(AssemblerConnectionManager::class.java)) return processorSerializer } override fun createInput(): DeleteOrganizationAssemblyProcessor { return DeleteOrganizationAssemblyProcessor() } }
src/test/kotlin/com/openlattice/hazelcast/serializers/DeleteOrganizationAssemblyProcessorStreamSerializerTest.kt
3575466263
package ii_collections fun example9() { val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult }) result == 24 } // The same as fun whatFoldDoes(): Int { var result = 1 listOf(1, 2, 3, 4).forEach { element -> result = element * result} return result } fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> { // Return the set of products ordered by every customer return customers.fold(allOrderedProducts, { orderedByAll, customer -> orderedByAll.intersect(customer.orderedProducts) }) }
src/ii_collections/n22Fold.kt
1494891712
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.assembler import com.openlattice.analysis.requests.* import com.openlattice.datastore.services.EdmManager import com.openlattice.postgres.DataTables import com.openlattice.postgres.PostgresColumn import com.openlattice.postgres.PostgresTable import com.openlattice.postgres.streams.BasePostgresIterable import com.openlattice.postgres.streams.StatementHolderSupplier import com.zaxxer.hikari.HikariDataSource import org.slf4j.LoggerFactory @Deprecated("Unused, needs rewrite") class AssemblerQueryService( private val edmService: EdmManager ) { companion object { private val logger = LoggerFactory.getLogger(AssemblerQueryService::class.java) private const val SRC_TABLE_ALIAS = "SRC_TABLE" private const val EDGE_TABLE_ALIAS = "EDGE_TABLE" private const val DST_TABLE_ALIAS = "DST_TABLE" } fun simpleAggregation( hds: HikariDataSource, srcEntitySetName: String, edgeEntitySetName: String, dstEntitySetName: String, srcGroupColumns: List<String>, edgeGroupColumns: List<String>, dstGroupColumns: List<String>, srcAggregates: Map<String, List<AggregationType>>, edgeAggregates: Map<String, List<AggregationType>>, dstAggregates: Map<String, List<AggregationType>>, calculations: Set<Calculation>, srcFilters: Map<String, List<Filter>>, edgeFilters: Map<String, List<Filter>>, dstFilters: Map<String, List<Filter>> ): Iterable<Map<String, Any?>> { // Groupings val srcGroupColAliases = mutableListOf<String>() val edgeGroupColAliases = mutableListOf<String>() val dstGroupColAliases = mutableListOf<String>() val srcGroupCols = srcGroupColumns.map { val alias = "${SRC_TABLE_ALIAS}_$it" srcGroupColAliases.add(alias) "$SRC_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}" } val edgeGroupCols = edgeGroupColumns.map { val alias = "${EDGE_TABLE_ALIAS}_$it" edgeGroupColAliases.add(alias) "$EDGE_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}" } val dstGroupCols = dstGroupColumns.map { val alias = "${DST_TABLE_ALIAS}_$it" edgeGroupColAliases.add(alias) "$DST_TABLE_ALIAS.${DataTables.quote(it)} AS ${DataTables.quote(alias)}" } val cols = (srcGroupCols + edgeGroupCols + dstGroupCols).joinToString(", ") // Aggregations val srcAggregateAliases = mutableListOf<String>() val srcAggregateCols = srcAggregates.flatMap { aggregate -> val quotedColumn = DataTables.quote(aggregate.key) val aggregateColumn = "$SRC_TABLE_ALIAS.$quotedColumn" aggregate.value.map { aggregateFun -> val aggregateAlias = "${SRC_TABLE_ALIAS}_${aggregate.key}_$aggregateFun" srcAggregateAliases.add(aggregateAlias) "$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}" } } val edgeAggregateAliases = mutableListOf<String>() val edgeAggregateCols = edgeAggregates.flatMap { aggregate -> val quotedColumn = DataTables.quote(aggregate.key) val aggregateColumn = "$EDGE_TABLE_ALIAS.$quotedColumn" aggregate.value.map { aggregateFun -> val aggregateAlias = "${EDGE_TABLE_ALIAS}_${aggregate.key}_$aggregateFun" edgeAggregateAliases.add(aggregateAlias) "$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}" } } val dstAggregateAliases = mutableListOf<String>() val dstAggregateCols = dstAggregates.flatMap { aggregate -> val quotedColumn = DataTables.quote(aggregate.key) val aggregateColumn = "$DST_TABLE_ALIAS.$quotedColumn" aggregate.value.map { aggregateFun -> val aggregateAlias = "${DST_TABLE_ALIAS}_${aggregate.key}_$aggregateFun" dstAggregateAliases.add(aggregateAlias) "$aggregateFun( $aggregateColumn ) AS ${DataTables.quote(aggregateAlias)}" } } // Calculations val calculationAliases = mutableListOf<String>() val calculationGroupCols = mutableListOf<String>() val calculationSqls = calculations .filter { it.calculationType.basseType == BaseCalculationTypes.DURATION } .map { val firstPropertyType = edmService.getPropertyTypeFqn(it.firstPropertyId.propertyTypeId).fullQualifiedNameAsString val firstPropertyCol = mapOrientationToTableAlias(it.firstPropertyId.orientation) + "." + DataTables.quote(firstPropertyType) val secondPropertyType = edmService.getPropertyTypeFqn(it.secondPropertyId.propertyTypeId).fullQualifiedNameAsString val secondPropertyCol = mapOrientationToTableAlias(it.secondPropertyId.orientation) + "." + DataTables.quote(secondPropertyType) calculationGroupCols.add(firstPropertyCol) calculationGroupCols.add(secondPropertyCol) val calculator = DurationCalculator(firstPropertyCol, secondPropertyCol) val alias = "${it.calculationType}_${firstPropertyType}_$secondPropertyType" calculationAliases.add(alias) mapDurationCalcualtionsToSql(calculator, it.calculationType) + " AS ${DataTables.quote(alias)}" } // The query val groupingColAliases = (srcGroupColAliases + edgeGroupColAliases + dstGroupColAliases) .joinToString(", ") { DataTables.quote(it) } + if (calculationGroupCols.isNotEmpty()) { calculationGroupCols.joinToString(", ", ", ", "") } else { "" } // Filters val srcFilterSqls = srcFilters.map { val colName = " $SRC_TABLE_ALIAS.${DataTables.quote(it.key)} " it.value.map { it.asSql(colName) }.joinToString(" AND ") } val edgeFilterSqls = edgeFilters.map { val colName = " $EDGE_TABLE_ALIAS.${DataTables.quote(it.key)} " it.value.map { it.asSql(colName) }.joinToString(" AND ") } val dstFilterSqls = dstFilters.map { val colName = " $DST_TABLE_ALIAS.${DataTables.quote(it.key)} " it.value.map { it.asSql(colName) }.joinToString(" AND ") } val allFilters = (srcFilterSqls + edgeFilterSqls + dstFilterSqls) val filtersSql = if (allFilters.isNotEmpty()) allFilters.joinToString(" AND ", " AND ", " ") else "" val aggregateCols = (srcAggregateCols + edgeAggregateCols + dstAggregateCols).joinToString(", ") val calculationCols = if (calculationSqls.isNotEmpty()) ", " + calculationSqls.joinToString(", ") else "" val simpleSql = simpleAggregationJoinSql(srcEntitySetName, edgeEntitySetName, dstEntitySetName, cols, groupingColAliases, aggregateCols, calculationCols, filtersSql) logger.info("Simple assembly aggregate query:\n$simpleSql") return BasePostgresIterable(StatementHolderSupplier(hds, simpleSql)) { rs -> ((srcGroupColAliases + edgeGroupColAliases + dstGroupColAliases).map { col -> val arrayVal = rs.getArray(col) col to if (arrayVal == null) { null } else { (rs.getArray(col).array as Array<Any>)[0] } } + (srcAggregateAliases + edgeAggregateAliases + dstAggregateAliases).map { col -> col to rs.getObject(col) } + (calculationAliases).map { col -> col to rs.getObject(col) }).toMap() } } private fun simpleAggregationJoinSql(srcEntitySetName: String, edgeEntitySetName: String, dstEntitySetName: String, cols: String, groupingColAliases: String, aggregateCols: String, calculationCols: String, filtersSql: String): String { return "SELECT $cols, $aggregateCols $calculationCols FROM ${AssemblerConnectionManager.OPENLATTICE_SCHEMA}.${PostgresTable.E.name} " + "INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(srcEntitySetName)} AS $SRC_TABLE_ALIAS USING( ${PostgresColumn.ID.name} ) " + "INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(edgeEntitySetName)} AS $EDGE_TABLE_ALIAS ON( $EDGE_TABLE_ALIAS.${PostgresColumn.ID.name} = ${PostgresColumn.EDGE_COMP_2.name} ) " + "INNER JOIN ${AssemblerConnectionManager.entitySetNameTableName(dstEntitySetName)} AS $DST_TABLE_ALIAS ON( $DST_TABLE_ALIAS.${PostgresColumn.ID.name} = ${PostgresColumn.EDGE_COMP_1.name} ) " + "WHERE ${PostgresColumn.COMPONENT_TYPES.name} = 0 $filtersSql " + "GROUP BY ($groupingColAliases)" } private fun mapOrientationToTableAlias(orientation: Orientation): String { return when (orientation) { Orientation.SRC -> SRC_TABLE_ALIAS Orientation.EDGE -> EDGE_TABLE_ALIAS Orientation.DST -> DST_TABLE_ALIAS } } private fun mapDurationCalcualtionsToSql(durationCalculation: DurationCalculator, calculationType: CalculationType): String { return when (calculationType) { CalculationType.DURATION_YEAR -> durationCalculation.numberOfYears() CalculationType.DURATION_DAY -> durationCalculation.numberOfDays() CalculationType.DURATION_HOUR -> durationCalculation.numberOfHours() } } private class DurationCalculator(private val endColumn: String, private val startColumn: String) { fun firstStart(): String { return "(SELECT unnest($startColumn) ORDER BY 1 LIMIT 1)" } fun lastEnd(): String { return "(SELECT unnest($endColumn) ORDER BY 1 DESC LIMIT 1)" } fun numberOfYears(): String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600/24/365)" } fun numberOfDays(): String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600/24)" } fun numberOfHours(): String { return "SUM(EXTRACT(epoch FROM (${lastEnd()} - ${firstStart()}))/3600)" } } }
src/main/kotlin/com/openlattice/assembler/AssemblerQueryService.kt
475595957
package org.http4k.filter import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.present import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.filter.SamplingDecision.Companion.DO_NOT_SAMPLE import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.util.concurrent.Executors class RequestTracingTest { @BeforeEach fun before() { ZipkinTracesStorage.INTERNAL_THREAD_LOCAL.remove() } @Test fun `request traces are copied correctly from inbound to outbound requests`() { val originalTraceId = TraceId("originalTrace") val originalSpanId = TraceId("originalSpan") val originalParentSpanId = TraceId("originalParentSpanId") val traces = ZipkinTraces(originalTraceId, originalSpanId, originalParentSpanId, DO_NOT_SAMPLE) val client: HttpHandler = ClientFilters.RequestTracing().then { val actual = ZipkinTraces(it) assertThat(actual.traceId, equalTo(originalTraceId)) assertThat(actual.parentSpanId, equalTo(originalSpanId)) assertThat(actual.spanId, present()) assertThat(actual.samplingDecision, equalTo(DO_NOT_SAMPLE)) Response(OK) } val simpleProxyServer: HttpHandler = ServerFilters.RequestTracing().then { client(Request(GET, "/somePath")) } val response = simpleProxyServer(ZipkinTraces(traces, Request(GET, ""))) assertThat(ZipkinTraces(response), equalTo(traces)) } @Test fun `client should create new span_id even if parent null`() { val cliWithEvents = ClientFilters.RequestTracing() .then { val actual = ZipkinTraces(it) assertThat(actual.parentSpanId, equalTo(TraceId("span_id"))) Response(OK) } ZipkinTracesStorage.THREAD_LOCAL .setForCurrentThread(ZipkinTraces(TraceId("trace_id"), TraceId("span_id"), null)) cliWithEvents(Request(GET, "/parentNull")) ZipkinTracesStorage.THREAD_LOCAL .setForCurrentThread(ZipkinTraces(TraceId("trace_id"), TraceId("span_id"), TraceId("parent_id"))) cliWithEvents(Request(GET, "/parentNotNull")) } @Test fun `request traces may be copied to child threads`() { val originalTraceId = TraceId("originalTrace") val originalSpanId = TraceId("originalSpan") val originalParentSpanId = TraceId("originalParentSpanId") val traces = ZipkinTraces(originalTraceId, originalSpanId, originalParentSpanId, DO_NOT_SAMPLE) val client: HttpHandler = ClientFilters.RequestTracing().then { val actual = ZipkinTraces(it) assertThat(actual.traceId, equalTo(originalTraceId)) assertThat(actual.parentSpanId, equalTo(originalSpanId)) assertThat(actual.spanId, present()) assertThat(actual.samplingDecision, equalTo(DO_NOT_SAMPLE)) Response(OK) } val executor = Executors.newSingleThreadExecutor() val storage = ZipkinTracesStorage.THREAD_LOCAL val simpleProxyServer: HttpHandler = ServerFilters.RequestTracing().then { val traceForOuterThread = storage.forCurrentThread() val clientTask = { storage.setForCurrentThread(traceForOuterThread) client(Request(GET, "/somePath")) } executor.submit(clientTask).get() } val response = simpleProxyServer(ZipkinTraces(traces, Request(GET, ""))) assertThat(ZipkinTraces(response), equalTo(traces)) } }
http4k-core/src/test/kotlin/org/http4k/filter/RequestTracingTest.kt
2696863465
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.autofillframework.app import android.content.Context import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.ArrayAdapter import com.example.android.autofillframework.R import kotlinx.android.synthetic.main.credit_card_activity.clear import kotlinx.android.synthetic.main.credit_card_activity.creditCardNumberField import kotlinx.android.synthetic.main.credit_card_activity.expirationDay import kotlinx.android.synthetic.main.credit_card_activity.expirationMonth import kotlinx.android.synthetic.main.credit_card_activity.expirationYear import kotlinx.android.synthetic.main.credit_card_activity.submit import java.util.Calendar class CreditCardActivity : AppCompatActivity() { private val CC_EXP_YEARS_COUNT = 5 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.credit_card_activity) // Create an ArrayAdapter using the string array and a default spinner layout expirationDay.adapter = ArrayAdapter.createFromResource(this, R.array.day_array, android.R.layout.simple_spinner_item).apply { // Specify the layout to use when the list of choices appears setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } expirationMonth.adapter = ArrayAdapter.createFromResource(this, R.array.month_array, android.R.layout.simple_spinner_item).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } val year = Calendar.getInstance().get(Calendar.YEAR) val years = (0 until CC_EXP_YEARS_COUNT) .map { Integer.toString(year + it) } .toTypedArray<CharSequence>() expirationYear.adapter = object : ArrayAdapter<CharSequence?>(this, android.R.layout.simple_spinner_item, years) { override fun getAutofillOptions() = years } submit.setOnClickListener { submitCcInfo() } clear.setOnClickListener { resetFields() } } private fun resetFields() { creditCardNumberField.setText("") expirationDay.setSelection(0) expirationMonth.setSelection(0) expirationYear.setSelection(0) } /** * Launches new Activity and finishes, triggering an autofill save request if the user entered * any new data. */ private fun submitCcInfo() { startActivity(WelcomeActivity.getStartActivityIntent(this)) finish() } companion object { fun getStartActivityIntent(context: Context) = Intent(context, CreditCardActivity::class.java) } }
kotlinApp/Application/src/main/java/com/example/android/autofillframework/app/CreditCardActivity.kt
541619960
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.fido2.api import okhttp3.Interceptor import okhttp3.Response internal class AddHeaderInterceptor(private val userAgent: String) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { return chain.proceed( chain.request().newBuilder() .header("User-Agent", userAgent) .header("X-Requested-With", "XMLHttpRequest") .build() ) } }
android/app/src/main/java/com/example/android/fido2/api/AddHeaderInterceptor.kt
2668952501
package br.com.freestuffs import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
FreeStuffs-Android/app/src/test/java/br/com/freestuffs/ExampleUnitTest.kt
2864196818
package kodando.mithril.elements external interface HtmlVideoElementProps : HtmlElementProps
kodando-mithril/src/main/kotlin/kodando/mithril/elements/HtmlVideoElementProps.kt
840698531
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.loanrepayment import android.content.DialogInterface import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.widget.AdapterView.OnItemSelectedListener import androidx.fragment.app.DialogFragment import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.google.gson.Gson import com.jakewharton.fliptables.FlipTable import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.core.MaterialDialog import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.core.util.Toaster import com.mifos.mifosxdroid.uihelpers.MFDatePicker import com.mifos.mifosxdroid.uihelpers.MFDatePicker.OnDatePickListener import com.mifos.objects.accounts.loan.LoanRepaymentRequest import com.mifos.objects.accounts.loan.LoanRepaymentResponse import com.mifos.objects.accounts.loan.LoanWithAssociations import com.mifos.objects.templates.loans.LoanRepaymentTemplate import com.mifos.utils.Constants import com.mifos.utils.FragmentConstants import com.mifos.utils.Utils import javax.inject.Inject class LoanRepaymentFragment : MifosBaseFragment(), OnDatePickListener, LoanRepaymentMvpView, DialogInterface.OnClickListener { val LOG_TAG = javaClass.simpleName @kotlin.jvm.JvmField @BindView(R.id.rl_loan_repayment) var rl_loan_repayment: RelativeLayout? = null @kotlin.jvm.JvmField @BindView(R.id.tv_clientName) var tv_clientName: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.tv_loan_product_short_name) var tv_loanProductShortName: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.tv_loanAccountNumber) var tv_loanAccountNumber: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.tv_in_arrears) var tv_inArrears: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.tv_amount_due) var tv_amountDue: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.tv_repayment_date) var tv_repaymentDate: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.et_amount) var et_amount: EditText? = null @kotlin.jvm.JvmField @BindView(R.id.et_additional_payment) var et_additionalPayment: EditText? = null @kotlin.jvm.JvmField @BindView(R.id.et_fees) var et_fees: EditText? = null @kotlin.jvm.JvmField @BindView(R.id.tv_total) var tv_total: TextView? = null @kotlin.jvm.JvmField @BindView(R.id.sp_payment_type) var sp_paymentType: Spinner? = null @kotlin.jvm.JvmField @BindView(R.id.bt_paynow) var bt_paynow: Button? = null @kotlin.jvm.JvmField @Inject var mLoanRepaymentPresenter: LoanRepaymentPresenter? = null private lateinit var rootView: View // Arguments Passed From the Loan Account Summary Fragment private var clientName: String? = null private var loanId: String? = null private var loanAccountNumber: String? = null private var loanProductName: String? = null private var amountInArrears: Double? = null private var paymentTypeOptionId = 0 private var mfDatePicker: DialogFragment? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) arguments?.getParcelable<LoanWithAssociations>(Constants.LOAN_SUMMARY)?.let { loanWithAssociations -> clientName = loanWithAssociations.clientName loanAccountNumber = loanWithAssociations.accountNo loanId = loanWithAssociations.id.toString() loanProductName = loanWithAssociations.loanProductName amountInArrears = loanWithAssociations.summary.totalOverdue } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { rootView = inflater.inflate(R.layout.fragment_loan_repayment, container, false) setToolbarTitle("Loan Repayment") ButterKnife.bind(this, rootView) mLoanRepaymentPresenter!!.attachView(this) //This Method Checking LoanRepayment made before in Offline mode or not. //If yes then User have to sync this first then he can able to make transaction. //If not then User able to make LoanRepayment in Online or Offline. checkLoanRepaymentStatusInDatabase() return rootView } override fun checkLoanRepaymentStatusInDatabase() { // Checking LoanRepayment Already made in Offline mode or Not. mLoanRepaymentPresenter!!.checkDatabaseLoanRepaymentByLoanId(loanId!!.toInt()) } override fun showLoanRepaymentExistInDatabase() { //Visibility of ParentLayout GONE, If Repayment Already made in Offline Mode rl_loan_repayment!!.visibility = View.GONE MaterialDialog.Builder().init(activity) .setTitle(R.string.sync_previous_transaction) .setMessage(R.string.dialog_message_sync_transaction) .setPositiveButton(R.string.dialog_action_ok, this) .setCancelable(false) .createMaterialDialog() .show() } override fun onClick(dialog: DialogInterface, which: Int) { if (DialogInterface.BUTTON_POSITIVE == which) { requireActivity().supportFragmentManager.popBackStackImmediate() } } override fun showLoanRepaymentDoesNotExistInDatabase() { // This Method Inflating UI and Initializing the Loading LoadRepayment // Template for transaction inflateUI() // Loading PaymentOptions. mLoanRepaymentPresenter!!.loanLoanRepaymentTemplate(loanId!!.toInt()) } /** * This Method Setting UI and Initializing the Object, TextView or EditText. */ fun inflateUI() { tv_clientName!!.text = clientName tv_loanProductShortName!!.text = loanProductName tv_loanAccountNumber!!.text = loanId tv_inArrears!!.text = amountInArrears.toString() //Setup Form with Default Values et_amount!!.setText("0.0") et_amount!!.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) { try { tv_total!!.text = calculateTotal().toString() } catch (nfe: NumberFormatException) { et_amount!!.setText("0") } finally { tv_total!!.text = calculateTotal().toString() } } override fun afterTextChanged(editable: Editable) {} }) et_additionalPayment!!.setText("0.0") et_additionalPayment!!.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) { try { tv_total!!.text = calculateTotal().toString() } catch (nfe: NumberFormatException) { et_additionalPayment!!.setText("0") } finally { tv_total!!.text = calculateTotal().toString() } } override fun afterTextChanged(editable: Editable) {} }) et_fees!!.setText("0.0") et_fees!!.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {} override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) { try { tv_total!!.text = calculateTotal().toString() } catch (nfe: NumberFormatException) { et_fees!!.setText("0") } finally { tv_total!!.text = calculateTotal().toString() } } override fun afterTextChanged(editable: Editable) {} }) inflateRepaymentDate() tv_total!!.text = calculateTotal().toString() } /** * Calculating the Total of the Amount, Additional Payment and Fee * * @return Total of the Amount + Additional Payment + Fee Amount */ fun calculateTotal(): Double { return et_amount!!.text.toString().toDouble() + et_additionalPayment!!.text.toString().toDouble() + et_fees!!.text.toString().toDouble() } /** * Setting the Repayment Date */ fun inflateRepaymentDate() { mfDatePicker = MFDatePicker.newInsance(this) tv_repaymentDate!!.text = MFDatePicker.getDatePickedAsString() /* TODO Add Validation to make sure : 1. Date Is in Correct Format 2. Date Entered is not greater than Date Today i.e Date is not in future */tv_repaymentDate!!.setOnClickListener { (mfDatePicker as MFDatePicker?)!!.show(requireActivity().supportFragmentManager, FragmentConstants.DFRAG_DATE_PICKER) } } /** * Whenever user click on Date Picker and in Result, setting Date in TextView. * * @param date Selected Date by Date picker */ override fun onDatePicked(date: String) { tv_repaymentDate!!.text = date } /** * Submitting the LoanRepayment after setting all arguments and Displaying the Dialog * First, So that user make sure. He/She wanna make LoanRepayment */ @OnClick(R.id.bt_paynow) fun onPayNowButtonClicked() { try { val headers = arrayOf("Field", "Value") val data = arrayOf(arrayOf("Account Number", loanAccountNumber), arrayOf<String?>("Repayment Date", tv_repaymentDate!!.text.toString()), arrayOf<String?>("Payment Type", sp_paymentType!!.selectedItem.toString()), arrayOf<String?>("Amount", et_amount!!.text.toString()), arrayOf<String?>("Addition Payment", et_additionalPayment!!.text.toString()), arrayOf<String?>("Fees", et_fees!!.text.toString()), arrayOf<String?>("Total", calculateTotal().toString())) Log.d(LOG_TAG, FlipTable.of(headers, data)) val formReviewString = StringBuilder().append(data[0][0].toString() + " : " + data[0][1]) .append("\n") .append(data[1][0].toString() + " : " + data[1][1]) .append("\n") .append(data[2][0].toString() + " : " + data[2][1]) .append("\n") .append(data[3][0].toString() + " : " + data[3][1]) .append("\n") .append(data[4][0].toString() + " : " + data[4][1]) .append("\n") .append(data[5][0].toString() + " : " + data[5][1]) .append("\n") .append(data[6][0].toString() + " : " + data[6][1]).toString() MaterialDialog.Builder().init(activity) .setTitle(R.string.review_payment) .setMessage(formReviewString) .setPositiveButton(R.string.dialog_action_pay_now ) { dialog, which -> submitPayment() } .setNegativeButton(R.string.dialog_action_back ) { dialog, which -> dialog.dismiss() } .createMaterialDialog() .show() } catch (npe: NullPointerException) { Toaster.show(rootView, "Please make sure every field has a value, before submitting " + "repayment!") } } /** * Cancel button on Home UI */ @OnClick(R.id.bt_cancelPayment) fun onCancelPaymentButtonClicked() { requireActivity().supportFragmentManager.popBackStackImmediate() } /** * Submit the Final LoanRepayment */ fun submitPayment() { //TODO Implement a proper builder method here val dateString = tv_repaymentDate!!.text.toString().replace("-", " ") val request = LoanRepaymentRequest() request.accountNumber = loanAccountNumber request.paymentTypeId = paymentTypeOptionId.toString() request.locale = "en" request.transactionAmount = calculateTotal().toString() request.dateFormat = "dd MM yyyy" request.transactionDate = dateString val builtRequest = Gson().toJson(request) Log.i("LOG_TAG", builtRequest) mLoanRepaymentPresenter!!.submitPayment(loanId!!.toInt(), request) } override fun showLoanRepayTemplate(loanRepaymentTemplate: LoanRepaymentTemplate?) { /* Activity is null - Fragment has been detached; no need to do anything. */ if (activity == null) return if (loanRepaymentTemplate != null) { tv_amountDue!!.text = loanRepaymentTemplate.amount.toString() inflateRepaymentDate() val listOfPaymentTypes = Utils.getPaymentTypeOptions(loanRepaymentTemplate.paymentTypeOptions) val paymentTypeAdapter = ArrayAdapter(requireActivity(), android.R.layout.simple_spinner_item, listOfPaymentTypes) paymentTypeAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item) sp_paymentType!!.adapter = paymentTypeAdapter sp_paymentType!!.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { paymentTypeOptionId = loanRepaymentTemplate .paymentTypeOptions[position].id } override fun onNothingSelected(parent: AdapterView<*>?) {} } et_amount!!.setText((loanRepaymentTemplate .principalPortion + loanRepaymentTemplate.interestPortion).toString()) et_additionalPayment!!.setText("0.0") et_fees!!.setText(loanRepaymentTemplate .feeChargesPortion.toString()) } } override fun showPaymentSubmittedSuccessfully(loanRepaymentResponse: LoanRepaymentResponse?) { if (loanRepaymentResponse != null) { Toaster.show(rootView, "Payment Successful, Transaction ID = " + loanRepaymentResponse.resourceId) } requireActivity().supportFragmentManager.popBackStackImmediate() } override fun showError(errorMessage: Int) { Toaster.show(rootView, errorMessage) } override fun showProgressbar(b: Boolean) { if (b) { rl_loan_repayment!!.visibility = View.GONE showMifosProgressBar() } else { rl_loan_repayment!!.visibility = View.VISIBLE hideMifosProgressBar() } } override fun onDestroyView() { super.onDestroyView() mLoanRepaymentPresenter!!.detachView() } interface OnFragmentInteractionListener companion object { @kotlin.jvm.JvmStatic fun newInstance(loanWithAssociations: LoanWithAssociations?): LoanRepaymentFragment { val fragment = LoanRepaymentFragment() val args = Bundle() if (loanWithAssociations != null) { args.putParcelable(Constants.LOAN_SUMMARY, loanWithAssociations) fragment.arguments = args } return fragment } } }
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/loanrepayment/LoanRepaymentFragment.kt
1537192718
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.Disposable import com.intellij.openapi.options.Configurable import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.JDOMUtil import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CodeStyleSettingsProvider import com.intellij.psi.codeStyle.CustomCodeStyleSettings import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.util.containers.ContainerUtil import org.assertj.core.api.Assertions.assertThat import org.jdom.Element import org.junit.ClassRule import org.junit.Test class CodeStyleTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } @Test fun `do not remove unknown`() { val settings = CodeStyleSettings() val loaded = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <UnknownDoNotRemoveMe> <option name="ALIGN_OBJECT_PROPERTIES" value="2" /> </UnknownDoNotRemoveMe> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> <option name="KEEP_BLANK_LINES_IN_CODE" value="10" /> </codeStyleSettings> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(loaded)) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(JDOMUtil.writeElement(serialized)).isEqualTo(loaded) } @Test fun `do not duplicate known extra sections`() { val newProvider: CodeStyleSettingsProvider = object : CodeStyleSettingsProvider() { override fun createCustomSettings(settings: CodeStyleSettings?): CustomCodeStyleSettings { return object : CustomCodeStyleSettings("NewComponent", settings) { override fun getKnownTagNames(): List<String> { return ContainerUtil.concat(super.getKnownTagNames(), listOf("NewComponent-extra")) } override fun writeExternal(parentElement: Element?, parentSettings: CustomCodeStyleSettings) { super.writeExternal(parentElement, parentSettings) writeMain(parentElement) writeExtra(parentElement) } private fun writeMain(parentElement: Element?) { var extra = parentElement!!.getChild(tagName) if (extra == null) { extra = Element(tagName) parentElement.addContent(extra) } val option = Element("option") option.setAttribute("name", "MAIN") option.setAttribute("value", "3") extra.addContent(option) } private fun writeExtra(parentElement: Element?) { val extra = Element("NewComponent-extra") val option = Element("option") option.setAttribute("name", "EXTRA") option.setAttribute("value", "3") extra.addContent(option) parentElement!!.addContent(extra) } } } override fun createSettingsPage(settings: CodeStyleSettings?, originalSettings: CodeStyleSettings?): Configurable { throw UnsupportedOperationException("not implemented") } } val disposable = Disposable {} PlatformTestUtil.registerExtension(com.intellij.psi.codeStyle.CodeStyleSettingsProvider.EXTENSION_POINT_NAME, newProvider, disposable) try { val settings = CodeStyleSettings() val text : (param: String) -> String = { param -> """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <NewComponent> <option name="MAIN" value="${param}" /> </NewComponent> <NewComponent-extra> <option name="EXTRA" value="${param}" /> </NewComponent-extra> <codeStyleSettings language="CoffeeScript"> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> </codeStyleSettings> <codeStyleSettings language="Gherkin"> <indentOptions> <option name="USE_TAB_CHARACTER" value="true" /> </indentOptions> </codeStyleSettings> <codeStyleSettings language="SQL"> <option name="KEEP_LINE_BREAKS" value="false" /> <option name="KEEP_BLANK_LINES_IN_CODE" value="10" /> </codeStyleSettings> </code_scheme>""".trimIndent() } settings.readExternal(JDOMUtil.load(text("2"))) val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(JDOMUtil.writeElement(serialized)).isEqualTo(text("3")) } finally { Disposer.dispose(disposable) } } @Test fun `reset deprecations`() { val settings = CodeStyleSettings() val initial = """ <code_scheme name="testSchemeName"> <option name="RIGHT_MARGIN" value="64" /> <option name="USE_FQ_CLASS_NAMES_IN_JAVADOC" value="false" /> </code_scheme>""".trimIndent() val expected = """ <code_scheme name="testSchemeName" version="${CodeStyleSettings.CURR_VERSION}"> <option name="RIGHT_MARGIN" value="64" /> </code_scheme>""".trimIndent() settings.readExternal(JDOMUtil.load(initial)) settings.resetDeprecatedFields() val serialized = Element("code_scheme").setAttribute("name", "testSchemeName") settings.writeExternal(serialized) assertThat(JDOMUtil.writeElement(serialized)).isEqualTo(expected) } }
platform/configuration-store-impl/testSrc/CodeStyleTest.kt
3593371269
package components.progressBar import utils.ThreadMain import java.awt.Dimension import java.util.concurrent.CompletableFuture import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JTextArea /** * Created by vicboma on 05/12/16. */ class TextAreaImpl internal constructor(val _text: String) : JTextArea() , TextArea { companion object { var scrollPane : JScrollPane? = null fun create(text: String): TextArea { return TextAreaImpl(text) } } init{ scrollPane = JScrollPane(this) scrollPane?.setPreferredSize(Dimension(380, 100)) scrollPane?.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) this.lineWrap = true this.wrapStyleWord = true this.isEditable = false this.alignmentX = JPanel.CENTER_ALIGNMENT this.autoscrolls = true for ( i in 0.._text.length-1) { i.text() } } override fun asyncUI() { ThreadMain.asyncUI { CompletableFuture.runAsync { Thread.sleep(1500) text = "" for ( i in 0.._text.length-1) { Thread.sleep(50) i.text() } }.thenAcceptAsync { asyncUI() } } } private fun isMod(a : Int, b :Int) = (a % b) == 0 public fun Int.text() = when { //isMod(this,TextArea.MOD) -> caretPosition = getDocument().getLength() else -> { append(_text[this].toString()) caretPosition = getDocument().getLength() } } override fun component() : JScrollPane? = scrollPane }
09-start-async-radiobutton-application/src/main/kotlin/components/textArea/TextAreaImpl.kt
1156693789
package cat.xojan.random1.data import cat.xojan.random1.domain.model.Podcast import cat.xojan.random1.domain.model.PodcastData import cat.xojan.random1.domain.repository.PodcastRepository import io.reactivex.Single class RemotePodcastRepository(private val service: ApiService): PodcastRepository { private var hourPodcasts: Single<PodcastData>? = null private var sectionPodcasts: Single<PodcastData>? = null private var programId: String? = null private var sectionId: String? = null override fun getPodcasts(programId: String, sectionId: String?, refresh: Boolean) : Single<List<Podcast>> { val podcastData: Single<PodcastData> if (sectionId != null) { if (sectionPodcasts == null || refresh || programId != this.programId || sectionId != this.sectionId) { sectionPodcasts = service.getPodcastData(programId, sectionId).cache() } podcastData = sectionPodcasts!! } else { if (hourPodcasts == null || refresh || programId != this.programId) { hourPodcasts = service.getPodcastData(programId).cache() } podcastData = hourPodcasts!! } this.programId = programId this.sectionId = sectionId return podcastData.map { pd -> pd.toPodcasts(programId) } } }
app/src/rac1/java/cat/xojan/random1/data/RemotePodcastRepository.kt
756459133
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.cardviewer.ViewerCommand import com.ichi2.libanki.Sound import net.ankiweb.rsdroid.RustCleanup import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.hasSize import org.hamcrest.Matchers.nullValue import org.junit.Test import org.junit.runner.RunWith import java.util.* /** Tests Sound Rendering - should be extracted from the GUI at some point */ @RustCleanup("doesn't work with V16") @RunWith(AndroidJUnit4::class) class AbstractFlashcardViewerSoundRenderTest : RobolectricTest() { /** Call this after a valid card has been added */ private val sounds by lazy { val ret = super.startRegularActivity<ReviewerSoundAccessor>() assertThat("activity was started before it had cards", ret.isDestroyed, equalTo(false)) ret } @Test fun sound_on_front() { addNoteUsingBasicModel("[sound:a.mp3]", "back") assertThat(sounds.q(), hasSize(1)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(1)) assertThat(sounds.a(), nullValue()) assertThat("despite being included in the answer by {{FrontSide}}, play once", sounds.qa(), hasSize(1)) } @Test fun sound_on_back() { addNoteUsingBasicModel("front", "[sound:a.mp3]") assertThat(sounds.q(), nullValue()) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), nullValue()) assertThat(sounds.a(), hasSize(1)) assertThat(sounds.qa(), hasSize(1)) } @Test fun different_sound_on_front_and_back() { addNoteUsingBasicModel("[sound:a.mp3]", "[sound:b.mp3]") assertThat(sounds.q(), hasSize(1)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(1)) assertThat(sounds.a(), hasSize(1)) assertThat(sounds.qa(), hasSize(2)) } @Test fun same_sound_on_front_and_back() { addNoteUsingBasicModel("[sound:a.mp3]", "[sound:a.mp3]") assertThat(sounds.q(), hasSize(1)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(1)) assertThat(sounds.a(), hasSize(1)) assertThat("Despite being in FrontSide, the sound is added again, so play it twice", sounds.qa(), hasSize(2)) } @Test fun same_sound_on_front_and_back_twice() { addNoteUsingBasicModel("[sound:a.mp3][sound:a.mp3]", "[sound:a.mp3]") assertThat(sounds.q(), hasSize(2)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(2)) assertThat(sounds.a(), hasSize(1)) assertThat("Despite being in FrontSide, the sound is added again, so play it twice", sounds.qa(), hasSize(3)) } @Test fun same_sound_on_front_and_back_no_frontSide() { addNoteWithNoFrontSide("[sound:a.mp3]", "[sound:a.mp3]") assertThat(sounds.q(), hasSize(1)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(1)) assertThat(sounds.a(), hasSize(1)) assertThat(sounds.qa(), hasSize(2)) } @Test fun different_sound_on_front_and_back_no_frontSide() { addNoteWithNoFrontSide("[sound:a.mp3]", "[sound:b.mp3]") assertThat(sounds.q(), hasSize(1)) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), hasSize(1)) assertThat(sounds.a(), hasSize(1)) assertThat(sounds.qa(), hasSize(2)) } @Test fun sound_on_back_no_frontSide() { addNoteWithNoFrontSide("aa", "[sound:a.mp3]") assertThat(sounds.q(), nullValue()) sounds.executeCommand(ViewerCommand.SHOW_ANSWER) assertThat(sounds.q(), nullValue()) assertThat(sounds.a(), hasSize(1)) assertThat(sounds.qa(), hasSize(1)) } private fun addNoteWithNoFrontSide(front: String, back: String) { addNonClozeModel("NoFrontSide", arrayOf("Front", "Back"), "{{Front}}", "{{Back}}") addNoteUsingModelName("NoFrontSide", front, back) } class ReviewerSoundAccessor : Reviewer() { fun a(): ArrayList<String>? { return super.mSoundPlayer.getSounds(Sound.SoundSide.ANSWER) } fun q(): ArrayList<String>? { return super.mSoundPlayer.getSounds(Sound.SoundSide.QUESTION) } fun qa(): ArrayList<String>? { return super.mSoundPlayer.getSounds(Sound.SoundSide.QUESTION_AND_ANSWER) } } }
AnkiDroid/src/test/java/com/ichi2/anki/AbstractFlashcardViewerSoundRenderTest.kt
1122493066
package pl.loziuu.ivms import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class IvmsApplication fun main(args: Array<String>) { SpringApplication.run(IvmsApplication::class.java, *args) }
ivms/src/main/kotlin/pl/loziuu/ivms/IvmsApplication.kt
1759989234
package de.westnordost.streetcomplete.quests.oneway import android.content.Context import android.os.Bundle import androidx.annotation.AnyThread import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.databinding.QuestStreetSidePuzzleBinding import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment import de.westnordost.streetcomplete.quests.StreetSideRotater import de.westnordost.streetcomplete.quests.oneway.OnewayAnswer.* import de.westnordost.streetcomplete.util.getOrientationAtCenterLineInDegrees import de.westnordost.streetcomplete.view.DrawableImage import de.westnordost.streetcomplete.view.ResImage import de.westnordost.streetcomplete.view.ResText import de.westnordost.streetcomplete.view.RotatedCircleDrawable import de.westnordost.streetcomplete.view.image_select.* import kotlin.math.PI class AddOnewayForm : AbstractQuestFormAnswerFragment<OnewayAnswer>() { override val contentLayoutResId = R.layout.quest_street_side_puzzle private val binding by contentViewBinding(QuestStreetSidePuzzleBinding::bind) override val contentPadding = false private var streetSideRotater: StreetSideRotater? = null private var selection: OnewayAnswer? = null private var mapRotation: Float = 0f private var wayRotation: Float = 0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) savedInstanceState?.getString(SELECTION)?.let { selection = valueOf(it) } wayRotation = (elementGeometry as ElementPolylinesGeometry).getOrientationAtCenterLineInDegrees() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.puzzleView.showOnlyRightSide() binding.puzzleView.onClickSideListener = { showDirectionSelectionDialog() } val defaultResId = R.drawable.ic_oneway_unknown binding.puzzleView.setRightSideImage(ResImage(selection?.iconResId ?: defaultResId)) binding.puzzleView.setRightSideText(selection?.titleResId?.let { resources.getString(it) }) if (selection == null && !HAS_SHOWN_TAP_HINT) { binding.puzzleView.showRightSideTapHint() HAS_SHOWN_TAP_HINT = true } streetSideRotater = StreetSideRotater( binding.puzzleView, binding.littleCompass.root, elementGeometry as ElementPolylinesGeometry ) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) selection?.let { outState.putString(SELECTION, it.name) } } override fun isFormComplete() = selection != null override fun onClickOk() { applyAnswer(selection!!) } @AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) { streetSideRotater?.onMapOrientation(rotation, tilt) mapRotation = (rotation * 180 / PI).toFloat() } private fun showDirectionSelectionDialog() { val ctx = context ?: return val items = OnewayAnswer.values().map { it.toItem(ctx, wayRotation + mapRotation) } ImageListPickerDialog(ctx, items, R.layout.labeled_icon_button_cell, 3) { selected -> val oneway = selected.value!! binding.puzzleView.replaceRightSideImage(ResImage(oneway.iconResId)) binding.puzzleView.setRightSideText(resources.getString(oneway.titleResId)) selection = oneway checkIsFormComplete() }.show() } companion object { private const val SELECTION = "selection" private var HAS_SHOWN_TAP_HINT = false } } private fun OnewayAnswer.toItem(context: Context, rotation: Float): DisplayItem<OnewayAnswer> { val drawable = RotatedCircleDrawable(context.getDrawable(iconResId)!!) drawable.rotation = rotation return Item2(this, DrawableImage(drawable), ResText(titleResId)) } private val OnewayAnswer.titleResId: Int get() = when(this) { FORWARD -> R.string.quest_oneway2_dir BACKWARD -> R.string.quest_oneway2_dir NO_ONEWAY -> R.string.quest_oneway2_no_oneway } private val OnewayAnswer.iconResId: Int get() = when(this) { FORWARD -> R.drawable.ic_oneway_lane BACKWARD -> R.drawable.ic_oneway_lane_reverse NO_ONEWAY -> R.drawable.ic_oneway_lane_no }
app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOnewayForm.kt
678662657
package de.westnordost.streetcomplete.quests.address sealed class AddressStreetAnswer(open val name: String) data class StreetName(override val name: String) : AddressStreetAnswer(name) data class PlaceName(override val name: String) : AddressStreetAnswer(name)
app/src/main/java/de/westnordost/streetcomplete/quests/address/AddressStreetAnswer.kt
1930199679
package org.fossasia.openevent.general.common /* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import androidx.annotation.MainThread import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import java.util.concurrent.atomic.AtomicBoolean import timber.log.Timber /** * A lifecycle-aware observable that sends only new updates after subscription, used for events like * navigation and Snackbar messages. * * * This avoids a common problem with events: on configuration change (like rotation) an update * can be emitted if the observer is active. This LiveData only calls the observable if there's an * explicit call to setValue() or call(). * * * Note that only one observer is going to be notified of changes. */ class SingleLiveEvent<T> : MutableLiveData<T>() { private val mPending = AtomicBoolean(false) @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { if (hasActiveObservers()) { Timber.w("Multiple observers registered but only one will be notified of changes.") } // Observe the internal MutableLiveData super.observe(owner, Observer { t -> if (mPending.compareAndSet(true, false)) { observer.onChanged(t) } }) } @MainThread override fun setValue(t: T?) { mPending.set(true) super.setValue(t) } /** * Used for cases where T is Void, to make calls cleaner. */ @MainThread fun call() { value = null } companion object { private val TAG = "SingleLiveEvent" } }
app/src/main/java/org/fossasia/openevent/general/common/SingleLiveEvent.kt
555104366
package com.thunder.horizons.checklist.checklist enum class ChecklistScreens { BACK_TO_AIRCRAFT, SETTINGS_FRAGMENT, PROCEDURE_FRAGMENT }
app/src/main/java/com/thunder/horizons/checklist/checklist/ChecklistScreens.kt
3563773781
/* * Copyright 2019 Marco Gomiero * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.prof.youtubeparser.engine import com.prof.youtubeparser.core.CoreJsonFetcher import java.util.concurrent.Callable internal class JsonFetcher(private val url: String) : Callable<String> { override fun call(): String { return CoreJsonFetcher.fetchJson(url) } }
youtubeparser/src/main/java/com/prof/youtubeparser/engine/JsonFetcher.kt
3333734268
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization import kotlinx.serialization.modules.* import kotlin.native.concurrent.* @Serializable open class PolyBase(val id: Int) { override fun hashCode(): Int { return id } override fun toString(): String { return "PolyBase(id=$id)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as PolyBase if (id != other.id) return false return true } } @Serializable data class PolyDerived(val s: String) : PolyBase(1) @SharedImmutable val BaseAndDerivedModule = SerializersModule { polymorphic(PolyBase::class, PolyBase.serializer()) { subclass(PolyDerived.serializer()) } }
core/commonTest/src/kotlinx/serialization/PolymorphismTestData.kt
254315774
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.base import com.github.pockethub.android.R import dagger.android.support.DaggerAppCompatActivity abstract class BaseActivity : DaggerAppCompatActivity() { override fun onContentChanged() { super.onContentChanged() setSupportActionBar(findViewById(R.id.toolbar)) } }
app/src/main/java/com/github/pockethub/android/ui/base/BaseActivity.kt
3117534044
package com.xander.paneldemo import com.xander.panel.XanderPanel.Builder.setTitle import com.xander.panel.XanderPanel.Builder.setIcon import com.xander.panel.XanderPanel.Builder.setMessage import com.xander.panel.XanderPanel.Builder.setGravity import com.xander.panel.XanderPanel.Builder.setController import com.xander.panel.XanderPanel.Builder.setCanceledOnTouchOutside import com.xander.panel.XanderPanel.Builder.setSheet import com.xander.panel.XanderPanel.Builder.list import com.xander.panel.XanderPanel.Builder.setMenu import com.xander.panel.XanderPanel.Builder.grid import com.xander.panel.XanderPanel.Builder.shareText import com.xander.panel.XanderPanel.Builder.shareImages import com.xander.panel.XanderPanel.Builder.setView import com.xander.panel.XanderPanel.Builder.create import com.xander.panel.XanderPanel.show import androidx.appcompat.app.AppCompatActivity import com.xander.paneldemo.R import android.view.LayoutInflater import android.os.Bundle import android.view.Gravity import com.xander.panel.PanelInterface.PanelControllerListener import com.xander.panel.XanderPanel import com.xander.panel.PanelInterface.SheetListener import com.xander.panel.PanelInterface.PanelMenuListener import android.widget.Toast import org.junit.Assert import org.junit.Test import java.lang.Exception import kotlin.Throws /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ class ExampleUnitTest { @Test @Throws(Exception::class) fun addition_isCorrect() { Assert.assertEquals(4, (2 + 2).toLong()) } }
demo/src/test/java/com/xander/paneldemo/ExampleUnitTest.kt
2344922968
/* * Copyright (C) 2014 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.api.entity data class TrendingItem(var watchers: Long, var show: Show? = null, var movie: Movie? = null)
trakt-api/src/main/java/net/simonvt/cathode/api/entity/TrendingItem.kt
2233991355
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import org.jetbrains.uast.* import org.jetbrains.uast.java.expressions.JavaUNamedExpression class JavaUAnnotation( override val psi: PsiAnnotation, override val uastParent: UElement? ) : UAnnotation { override val qualifiedName: String? get() = psi.qualifiedName override val attributeValues: List<UNamedExpression> by lz { val context = getUastContext() val attributes = psi.parameterList.attributes attributes.map { attribute -> JavaUNamedExpression(attribute, this) } } override fun resolve(): PsiClass? = psi.nameReferenceElement?.resolve() as? PsiClass override fun findAttributeValue(name: String?): UExpression? { val context = getUastContext() val attributeValue = psi.findAttributeValue(name) ?: return null return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression } override fun findDeclaredAttributeValue(name: String?): UExpression? { val context = getUastContext() val attributeValue = psi.findDeclaredAttributeValue(name) ?: return null return context.convertElement(attributeValue, this, null) as? UExpression ?: UastEmptyExpression } companion object { @JvmStatic fun wrap(annotation: PsiAnnotation): UAnnotation = JavaUAnnotation(annotation, null) @JvmStatic fun wrap(annotations: List<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) } @JvmStatic fun wrap(annotations: Array<PsiAnnotation>): List<UAnnotation> = annotations.map { JavaUAnnotation(it, null) } } }
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUAnnotation.kt
990041104
package com.hea3ven.dulcedeleche.modules.redstone.client.gui import com.hea3ven.dulcedeleche.modules.redstone.container.AssemblerContainer import net.minecraft.entity.player.PlayerInventory import net.minecraft.text.TextComponent import net.minecraft.util.Identifier import kotlin.math.roundToInt class AssemblerScreen(private val assemblerContainer: AssemblerContainer, playerInv: PlayerInventory, name: TextComponent) : CraftingMachineScreen<AssemblerContainer>(assemblerContainer, playerInv, name, Identifier( "dulcedeleche:textures/gui/container/assembler.png")) { override fun drawBackground(var1: Float, var2: Int, var3: Int) { super.drawBackground(var1, var2, var3) val progress = assemblerContainer.progress this.blit(left + 89, top + 34, 176, 0, (24 * progress).roundToInt(), 16) } }
src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/client/gui/AssemblerScreen.kt
4205757680
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.connection import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.TimeUnit import okhttp3.Address import okhttp3.ConnectionPool import okhttp3.Route import okhttp3.internal.assertThreadHoldsLock import okhttp3.internal.closeQuietly import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskQueue import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.connection.RealCall.CallReference import okhttp3.internal.okHttpName import okhttp3.internal.platform.Platform class RealConnectionPool( taskRunner: TaskRunner, /** The maximum number of idle connections for each address. */ private val maxIdleConnections: Int, keepAliveDuration: Long, timeUnit: TimeUnit ) { private val keepAliveDurationNs: Long = timeUnit.toNanos(keepAliveDuration) private val cleanupQueue: TaskQueue = taskRunner.newQueue() private val cleanupTask = object : Task("$okHttpName ConnectionPool") { override fun runOnce() = cleanup(System.nanoTime()) } /** * Holding the lock of the connection being added or removed when mutating this, and check its * [RealConnection.noNewExchanges] property. This defends against races where a connection is * simultaneously adopted and removed. */ private val connections = ConcurrentLinkedQueue<RealConnection>() init { // Put a floor on the keep alive duration, otherwise cleanup will spin loop. require(keepAliveDuration > 0L) { "keepAliveDuration <= 0: $keepAliveDuration" } } fun idleConnectionCount(): Int { return connections.count { synchronized(it) { it.calls.isEmpty() } } } fun connectionCount(): Int { return connections.size } /** * Attempts to acquire a recycled connection to [address] for [call]. Returns true if a connection * was acquired. * * If [routes] is non-null these are the resolved routes (ie. IP addresses) for the connection. * This is used to coalesce related domains to the same HTTP/2 connection, such as `square.com` * and `square.ca`. */ fun callAcquirePooledConnection( address: Address, call: RealCall, routes: List<Route>?, requireMultiplexed: Boolean ): Boolean { for (connection in connections) { synchronized(connection) { if (requireMultiplexed && !connection.isMultiplexed) return@synchronized if (!connection.isEligible(address, routes)) return@synchronized call.acquireConnectionNoEvents(connection) return true } } return false } fun put(connection: RealConnection) { connection.assertThreadHoldsLock() connections.add(connection) cleanupQueue.schedule(cleanupTask) } /** * Notify this pool that [connection] has become idle. Returns true if the connection has been * removed from the pool and should be closed. */ fun connectionBecameIdle(connection: RealConnection): Boolean { connection.assertThreadHoldsLock() return if (connection.noNewExchanges || maxIdleConnections == 0) { connection.noNewExchanges = true connections.remove(connection) if (connections.isEmpty()) cleanupQueue.cancelAll() true } else { cleanupQueue.schedule(cleanupTask) false } } fun evictAll() { val i = connections.iterator() while (i.hasNext()) { val connection = i.next() val socketToClose = synchronized(connection) { if (connection.calls.isEmpty()) { i.remove() connection.noNewExchanges = true return@synchronized connection.socket() } else { return@synchronized null } } socketToClose?.closeQuietly() } if (connections.isEmpty()) cleanupQueue.cancelAll() } /** * Performs maintenance on this pool, evicting the connection that has been idle the longest if * either it has exceeded the keep alive limit or the idle connections limit. * * Returns the duration in nanoseconds to sleep until the next scheduled call to this method. * Returns -1 if no further cleanups are required. */ fun cleanup(now: Long): Long { var inUseConnectionCount = 0 var idleConnectionCount = 0 var longestIdleConnection: RealConnection? = null var longestIdleDurationNs = Long.MIN_VALUE // Find either a connection to evict, or the time that the next eviction is due. for (connection in connections) { synchronized(connection) { // If the connection is in use, keep searching. if (pruneAndGetAllocationCount(connection, now) > 0) { inUseConnectionCount++ } else { idleConnectionCount++ // If the connection is ready to be evicted, we're done. val idleDurationNs = now - connection.idleAtNs if (idleDurationNs > longestIdleDurationNs) { longestIdleDurationNs = idleDurationNs longestIdleConnection = connection } else { Unit } } } } when { longestIdleDurationNs >= this.keepAliveDurationNs || idleConnectionCount > this.maxIdleConnections -> { // We've chosen a connection to evict. Confirm it's still okay to be evict, then close it. val connection = longestIdleConnection!! synchronized(connection) { if (connection.calls.isNotEmpty()) return 0L // No longer idle. if (connection.idleAtNs + longestIdleDurationNs != now) return 0L // No longer oldest. connection.noNewExchanges = true connections.remove(longestIdleConnection) } connection.socket().closeQuietly() if (connections.isEmpty()) cleanupQueue.cancelAll() // Clean up again immediately. return 0L } idleConnectionCount > 0 -> { // A connection will be ready to evict soon. return keepAliveDurationNs - longestIdleDurationNs } inUseConnectionCount > 0 -> { // All connections are in use. It'll be at least the keep alive duration 'til we run // again. return keepAliveDurationNs } else -> { // No connections, idle or in use. return -1 } } } /** * Prunes any leaked calls and then returns the number of remaining live calls on [connection]. * Calls are leaked if the connection is tracking them but the application code has abandoned * them. Leak detection is imprecise and relies on garbage collection. */ private fun pruneAndGetAllocationCount(connection: RealConnection, now: Long): Int { connection.assertThreadHoldsLock() val references = connection.calls var i = 0 while (i < references.size) { val reference = references[i] if (reference.get() != null) { i++ continue } // We've discovered a leaked call. This is an application bug. val callReference = reference as CallReference val message = "A connection to ${connection.route().address.url} was leaked. " + "Did you forget to close a response body?" Platform.get().logCloseableLeak(message, callReference.callStackTrace) references.removeAt(i) connection.noNewExchanges = true // If this was the last allocation, the connection is eligible for immediate eviction. if (references.isEmpty()) { connection.idleAtNs = now - keepAliveDurationNs return 0 } } return references.size } companion object { fun get(connectionPool: ConnectionPool): RealConnectionPool = connectionPool.delegate } }
okhttp/src/main/kotlin/okhttp3/internal/connection/RealConnectionPool.kt
3525856037
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents class TarBzip2ExtractorTest2 : TarBzip2ExtractorTest() { override val archiveType: String = "tbz" }
app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/TarBzip2ExtractorTest2.kt
3537716036
package fr.free.nrw.commons.upload.structure.depictions import com.nhaarman.mockitokotlin2.mock import depictedItem import entity import entityId import fr.free.nrw.commons.wikidata.WikidataProperties import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.nullValue import org.junit.Test import place import snak import statement import valueString import wikiBaseEntityValue class DepictedItemTest { @Test fun `name and description get user language label`() { val depictedItem = DepictedItem(entity(mapOf("en" to "label"), mapOf("en" to "description"))) assertThat(depictedItem.name, `is`("label")) assertThat(depictedItem.description, `is`("description")) } @Test fun `name and descriptions get first language label if user language not present`() { val depictedItem = DepictedItem(entity(mapOf("" to "label"), mapOf("" to "description"))) assertThat(depictedItem.name, `is`("label")) assertThat(depictedItem.description, `is`("description")) } @Test fun `name and descriptions get empty if nothing present`() { val depictedItem = DepictedItem(entity()) assertThat(depictedItem.name, `is`("")) assertThat(depictedItem.description, `is`("")) } @Test fun `image is empty with null statements`() { assertThat(DepictedItem(entity(statements = null)).imageUrl, nullValue()) } @Test fun `image is empty with no image statement`() { assertThat(DepictedItem(entity()).imageUrl, nullValue()) } @Test fun `image is empty with dataValue not of ValueString type`() { assertThat( DepictedItem( entity( statements = mapOf( WikidataProperties.IMAGE.propertyName to listOf(statement(snak(dataValue = mock()))) ) ) ).imageUrl, nullValue() ) } @Test fun `image is not empty with dataValue of ValueString type`() { assertThat( DepictedItem( entity( statements = mapOf( WikidataProperties.IMAGE.propertyName to listOf( statement(snak(dataValue = valueString("prefix: example_"))) ) ) ) ).imageUrl, `is`("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b7/_example_/70px-_example_") ) } @Test fun `instancesOf maps EntityIds to ids`() { assertThat( DepictedItem( entity( statements = mapOf( WikidataProperties.INSTANCE_OF.propertyName to listOf( statement(snak(dataValue = valueString("prefix: example_"))), statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "1")))), statement(snak(dataValue = entityId(wikiBaseEntityValue(id = "2")))) ) ) ) ).instanceOfs, `is`(listOf("1", "2"))) } @Test fun `instancesOf is empty with no values`() { assertThat(DepictedItem(entity()).instanceOfs, `is`(emptyList())) } @Test fun `commonsCategory maps ValueString to strings`() { assertThat( DepictedItem( entity( statements = mapOf( WikidataProperties.COMMONS_CATEGORY.propertyName to listOf( statement(snak(dataValue = valueString("1"))), statement(snak(dataValue = valueString("2"))) ) ) ) ).commonsCategories, `is`(listOf("1", "2"))) } @Test fun `commonsCategory is empty with no values`() { assertThat(DepictedItem(entity()).commonsCategories, `is`(emptyList())) } @Test fun `isSelected is false at creation`() { assertThat(DepictedItem(entity()).isSelected, `is`(false)) } @Test fun `id is entityId`() { assertThat(DepictedItem(entity(id = "1")).id, `is`("1")) } @Test fun `place constructor uses place name and longDescription`() { val depictedItem = DepictedItem(entity(), place(name = "1", longDescription = "2")) assertThat(depictedItem.name, `is`("1")) assertThat(depictedItem.description, `is`("2")) } @Test fun `same object is Equal`() { val depictedItem = depictedItem() assertThat(depictedItem == depictedItem, `is`(true)) } @Test fun `different type is not Equal`() { assertThat(depictedItem().equals(Unit), `is`(false)) } @Test fun `if names are equal is Equal`() { assertThat( depictedItem(name="a", id = "0") == depictedItem(name="a", id = "1"), `is`(true)) } @Test fun `if names are not equal is not Equal`() { assertThat( depictedItem(name="a") == depictedItem(name="b"), `is`(false)) } @Test fun `hashCode returns same values for objects with same name`() { assertThat(depictedItem(name="a").hashCode(), `is`(depictedItem(name="a").hashCode())) } @Test fun `hashCode returns different values for objects with different name`() { assertThat(depictedItem(name="a").hashCode(), not(depictedItem(name="b").hashCode())) } }
app/src/test/kotlin/fr/free/nrw/commons/upload/structure/depictions/DepictedItemTest.kt
3700818373
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.dependency // https://checkerframework.org/ object CheckerFramework { private const val version = "3.21.3" const val annotations = "org.checkerframework:checker-qual:${version}" @Suppress("unused") val dataflow = listOf( "org.checkerframework:dataflow:${version}", "org.checkerframework:javacutil:${version}" ) /** * This is discontinued artifact, which we do not use directly. * This is a transitive dependency for us, which we force in * [DependencyResolution.forceConfiguration] */ const val compatQual = "org.checkerframework:checker-compat-qual:2.5.5" }
buildSrc/src/main/kotlin/io/spine/internal/dependency/CheckerFramework.kt
598955102
/* * The MIT License * * Copyright (c) 2018 Niek Haarman * Copyright (c) 2007 Mockito contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.nhaarman.mockitokotlin2 import org.mockito.BDDMockito import org.mockito.BDDMockito.BDDMyOngoingStubbing import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer /** * Alias for [BDDMockito.given]. */ fun <T> given(methodCall: T): BDDMockito.BDDMyOngoingStubbing<T> { return BDDMockito.given(methodCall) } /** * Alias for [BDDMockito.given] with a lambda. */ fun <T> given(methodCall: () -> T): BDDMyOngoingStubbing<T> { return given(methodCall()) } /** * Alias for [BDDMockito.then]. */ fun <T> then(mock: T): BDDMockito.Then<T> { return BDDMockito.then(mock) } /** * Alias for [BDDMyOngoingStubbing.will] * */ infix fun <T> BDDMyOngoingStubbing<T>.will(value: Answer<T>): BDDMockito.BDDMyOngoingStubbing<T> { return will(value) } /** * Alias for [BBDMyOngoingStubbing.willAnswer], accepting a lambda. */ infix fun <T> BDDMyOngoingStubbing<T>.willAnswer(value: (InvocationOnMock) -> T?): BDDMockito.BDDMyOngoingStubbing<T> { return willAnswer { value(it) } } /** * Alias for [BBDMyOngoingStubbing.willReturn]. */ infix fun <T> BDDMyOngoingStubbing<T>.willReturn(value: () -> T): BDDMockito.BDDMyOngoingStubbing<T> { return willReturn(value()) } /** * Alias for [BBDMyOngoingStubbing.willThrow]. */ infix fun <T> BDDMyOngoingStubbing<T>.willThrow(value: () -> Throwable): BDDMockito.BDDMyOngoingStubbing<T> { return willThrow(value()) }
mockito-kotlin/src/main/kotlin/com/nhaarman/mockitokotlin2/BDDMockito.kt
37805590
package com.github.perseacado.aquasketch.frontend.media import org.springframework.data.mongodb.core.mapping.Document import java.util.* /** * @author Marco Eigletsberger, 13.07.16. */ @Document class Media { var id: String = UUID.randomUUID().toString() lateinit var userId: String lateinit var data: ByteArray }
aquasketch-frontend/src/main/java/com/github/perseacado/aquasketch/frontend/media/Media.kt
2539946920
package io.gitlab.arturbosch.detekt.sample.extensions.reports import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.OutputReport class QualifiedNamesOutputReport : OutputReport() { override val ending: String = "txt" override fun render(detektion: Detektion): String? { return qualifiedNamesReport(detektion) } }
detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/reports/QualifiedNamesOutputReport.kt
299163174
package com.fireflysource.net.http.common.v2.stream import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.http.common.HttpConfig.DEFAULT_WINDOW_SIZE import com.fireflysource.net.http.common.v2.frame.WindowUpdateFrame abstract class AbstractFlowControlStrategy( protected var initialStreamRecvWindow: Int = DEFAULT_WINDOW_SIZE ) : FlowControl { companion object { private val log = SystemLogger.create(AbstractFlowControlStrategy::class.java) } private var initialStreamSendWindow: Int = DEFAULT_WINDOW_SIZE override fun onStreamCreated(stream: Stream) { val http2Stream = stream as AsyncHttp2Stream http2Stream.updateSendWindow(initialStreamSendWindow) http2Stream.updateRecvWindow(initialStreamRecvWindow) } override fun onStreamDestroyed(stream: Stream) { } override fun updateInitialStreamWindow( http2Connection: Http2Connection, initialStreamWindow: Int, local: Boolean ) { val previousInitialStreamWindow: Int if (local) { previousInitialStreamWindow = initialStreamRecvWindow initialStreamRecvWindow = initialStreamWindow } else { previousInitialStreamWindow = initialStreamSendWindow initialStreamSendWindow = initialStreamWindow } val delta = initialStreamWindow - previousInitialStreamWindow if (delta == 0) return http2Connection.streams.forEach { stream -> if (local) { val http2Stream = stream as AsyncHttp2Stream http2Stream.updateRecvWindow(delta) log.debug { "Updated initial stream recv window $previousInitialStreamWindow -> $initialStreamWindow for $http2Stream" } } else { (http2Connection as AsyncHttp2Connection).onWindowUpdate(stream, WindowUpdateFrame(stream.id, delta)) } } } override fun onWindowUpdate(http2Connection: Http2Connection, stream: Stream?, frame: WindowUpdateFrame) { if (frame.isStreamWindowUpdate) { // The stream may have been removed concurrently. if (stream != null && stream is AsyncHttp2Stream) { stream.updateSendWindow(frame.windowDelta) } } else { (http2Connection as AsyncHttp2Connection).updateSendWindow(frame.windowDelta) } } override fun onDataReceived(http2Connection: Http2Connection, stream: Stream?, length: Int) { val connection = http2Connection as AsyncHttp2Connection var oldSize: Int = connection.updateRecvWindow(-length) log.debug { "Data received, $length bytes, updated session recv window $oldSize -> ${oldSize - length} for $connection" } if (stream != null && stream is AsyncHttp2Stream) { oldSize = stream.updateRecvWindow(-length) log.debug { "Data received, $length bytes, updated stream recv window $oldSize -> ${oldSize - length} for $stream" } } } override fun onDataSending(stream: Stream, length: Int) { if (length == 0) return val http2Stream = stream as AsyncHttp2Stream val connection = http2Stream.http2Connection as AsyncHttp2Connection val oldSessionWindow = connection.updateSendWindow(-length) val newSessionWindow = oldSessionWindow - length log.debug { "Sending, session send window $oldSessionWindow -> $newSessionWindow for $connection" } val oldStreamWindow = http2Stream.updateSendWindow(-length) val newStreamWindow = oldStreamWindow - length log.debug { "Sending, stream send window $oldStreamWindow -> $newStreamWindow for $stream" } } override fun onDataSent(stream: Stream, length: Int) { } override fun windowUpdate(http2Connection: Http2Connection, stream: Stream?, frame: WindowUpdateFrame) { } }
firefly-net/src/main/kotlin/com/fireflysource/net/http/common/v2/stream/AbstractFlowControlStrategy.kt
3813837055
package com.jraska.github.client.android.test import android.app.Activity import com.jraska.github.client.core.android.LinkLauncher import okhttp3.HttpUrl class DeepLinksRecorder : LinkLauncher { val linksLaunched = mutableListOf<HttpUrl>() private var swallowLinks = false override fun priority() = LinkLauncher.Priority.TESTING override fun launch(inActivity: Activity, deepLink: HttpUrl): LinkLauncher.Result { linksLaunched.add(deepLink) return if (swallowLinks) { LinkLauncher.Result.LAUNCHED // swallows link only as recorded } else { LinkLauncher.Result.NOT_LAUNCHED } } fun usingLinkRecording(block: (DeepLinksRecorder) -> Unit) { try { swallowLinks = true block(this) } finally { swallowLinks = false linksLaunched.clear() } } }
core-android-testing/src/main/java/com/jraska/github/client/android/test/DeepLinksRecorder.kt
2657387818
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.vaadin import com.mycollab.configuration.IDeploymentMode import com.mycollab.core.Version import com.mycollab.module.file.StorageUtils import com.mycollab.module.user.service.BillingAccountService import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.TooltipHelper.TOOLTIP_ID import com.mycollab.vaadin.ui.UIUtils import com.vaadin.server.BootstrapFragmentResponse import com.vaadin.server.BootstrapListener import com.vaadin.server.BootstrapPageResponse /** * @author MyCollab Ltd. * @since 3.0 */ class AppBootstrapListener : BootstrapListener { override fun modifyBootstrapFragment(response: BootstrapFragmentResponse) {} override fun modifyBootstrapPage(response: BootstrapPageResponse) { val request = response.request val domain = UIUtils.getSubDomain(request) val billingService = AppContextUtil.getSpringBean(BillingAccountService::class.java) val account = billingService.getAccountByDomain(domain) if (account != null) { val favIconPath = StorageUtils.getFavIconPath(account.id!!, account.faviconpath) response.document.head().getElementsByAttributeValue("rel", "shortcut icon").attr("href", favIconPath) response.document.head().getElementsByAttributeValue("rel", "icon").attr("href", favIconPath) } response.document.head().append("<meta name=\"robots\" content=\"nofollow\" />") val deploymentMode = AppContextUtil.getSpringBean(IDeploymentMode::class.java) response.document.head() .append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/jquery-2.1.4.min.js\"></script>") response.document.head() .append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/stickytooltip-1.0.2.js?v=${Version.getVersion()}\"></script>") response.document.head() .append("<script type=\"text/javascript\" src=\"${deploymentMode.getCdnUrl()}js/common-1.0.0.js?v=${Version.getVersion()}\"></script>") val div1 = response.document.body().appendElement("div") div1.attr("id", "div1$TOOLTIP_ID") div1.attr("class", "stickytooltip") val div12 = div1.appendElement("div") div12.attr("style", "padding:5px") val div13 = div12.appendElement("div") div13.attr("id", "div13$TOOLTIP_ID") div13.attr("class", "atip") div13.attr("style", "width:550px") val div14 = div13.appendElement("div") div14.attr("id", "div14$TOOLTIP_ID") val linkToTop = response.document.body().appendElement("a") linkToTop.attr("href", "#") linkToTop.attr("id", "linkToTop") linkToTop.append("<iron-icon icon=\"vaadin:vaadin-h\"></iron-icon>") } }
mycollab-web/src/main/java/com/mycollab/vaadin/AppBootstrapListener.kt
4276317275
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.designernews.data.login.model import com.google.gson.annotations.SerializedName /** * Models a Designer News API access token */ data class AccessToken(@SerializedName("access_token") val accessToken: String)
core/src/main/java/io/plaidapp/core/designernews/data/login/model/AccessToken.kt
543532321
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.EventDispatcher import org.jetbrains.annotations.CalledInAny import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.AccountTokenChangedListener import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountManager import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException import java.awt.Component import java.util.* /** * Allows to acquire API executor without exposing the auth token to external code */ class GithubApiRequestExecutorManager(private val authenticationManager: GithubAuthenticationManager, private val requestExecutorFactory: GithubApiRequestExecutor.Factory) { @CalledInAwt fun getExecutor(account: GithubAccount, project: Project): GithubApiRequestExecutor? { return authenticationManager.getOrRequestTokenForAccount(account, project) ?.let(requestExecutorFactory::create) } @CalledInAwt fun getManagedHolder(account: GithubAccount, project: Project): ManagedHolder? { val requestExecutor = getExecutor(account, project) ?: return null val holder = ManagedHolder(account, requestExecutor) ApplicationManager.getApplication().messageBus.connect(holder).subscribe(GithubAccountManager.ACCOUNT_TOKEN_CHANGED_TOPIC, holder) return holder } @CalledInAwt fun getExecutor(account: GithubAccount, parentComponent: Component): GithubApiRequestExecutor? { return authenticationManager.getOrRequestTokenForAccount(account, null, parentComponent) ?.let(requestExecutorFactory::create) } @CalledInAwt @Throws(GithubMissingTokenException::class) fun getExecutor(account: GithubAccount): GithubApiRequestExecutor { return authenticationManager.getTokenForAccount(account)?.let(requestExecutorFactory::create) ?: throw GithubMissingTokenException(account) } inner class ManagedHolder internal constructor(private val account: GithubAccount, initialExecutor: GithubApiRequestExecutor) : Disposable, AccountTokenChangedListener { private var isDisposed = false var executor: GithubApiRequestExecutor = initialExecutor @CalledInAny get() { if (isDisposed) throw IllegalStateException("Already disposed") return field } @CalledInAwt internal set(value) { field = value eventDispatcher.multicaster.executorChanged() } private val eventDispatcher = EventDispatcher.create(ExecutorChangeListener::class.java) override fun tokenChanged(account: GithubAccount) { if (account == this.account) runInEdt { try { executor = getExecutor(account) } catch (e: GithubMissingTokenException) { //token is missing, so content will be closed anyway } } } fun addListener(listener: ExecutorChangeListener, disposable: Disposable) = eventDispatcher.addListener(listener, disposable) override fun dispose() { isDisposed = true } } interface ExecutorChangeListener : EventListener { fun executorChanged() } companion object { @JvmStatic fun getInstance(): GithubApiRequestExecutorManager = service() } }
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutorManager.kt
1548730194
package com.robyn.dayplus2.display import com.robyn.dayplus2.BasePresenter import com.robyn.dayplus2.BaseView import com.robyn.dayplus2.data.MyEvent /** * Created by yifei on 11/23/2017. */ interface DisplayContract { interface View : BaseView<Presenter> { fun activityFinish() fun setDisplayContent(event: MyEvent) fun updateToolbar(event: MyEvent) } interface Presenter : BasePresenter { fun loadEvent() fun setFragmentContent() fun deleteEvent() fun fetchEvent(uuidString: String):MyEvent fun getEvent():MyEvent //fun updateDisplayContent() // Actionbar + fg content fun positionToUuid(position: Int): String fun uuidToPosition(uuid: String): Int fun getEventsCount(): Int fun updateToolbar() } }
app/src/main/java/com/robyn/dayplus2/display/DisplayContract.kt
3116115482
/* * Copyright (C) 2016 Mihály Szabó * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplicator.core.journal.file import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.isEmptyString import org.junit.After import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path class DefaultFileHandlerTest { private val FIRST_LINE = "first-line" private val SECOND_LINE = "second-line" private val NEW_LINE = "new-line" private val NEW_DIRECTORY = "new-directory" private lateinit var testDirectory: Path private lateinit var file: Path private lateinit var emptyFile: Path private lateinit var notExistingFile: Path private lateinit var notExistingDirectory: Path private lateinit var fileHandler: FileHandler @Before fun setUp() { testDirectory = createTestDirectory() file = createFile() emptyFile = createEmptyFile() notExistingFile = initializeNotExistingFile() notExistingDirectory = initializeNotExistingDirectory() fileHandler = DefaultFileHandler() } @After fun tearDown() { removeTestDirectory() } @Test fun createDirectory_createsDirectories_whenParentDirectoryNotExists() { fileHandler.createDirectory(notExistingDirectory, NEW_DIRECTORY) val newParentDirectory = notExistingDirectory.toFile() assertThat(newParentDirectory.exists(), equalTo(true)) assertThat(newParentDirectory.isDirectory, equalTo(true)) val newDirectory = notExistingDirectory.resolve(NEW_DIRECTORY).toFile() assertThat(newDirectory.exists(), equalTo(true)) assertThat(newDirectory.isDirectory, equalTo(true)) } @Test fun createDirectory_createsDirectory() { fileHandler.createDirectory(testDirectory, NEW_DIRECTORY) val newDirectory = testDirectory.resolve(NEW_DIRECTORY).toFile() assertThat(newDirectory.exists(), equalTo(true)) assertThat(newDirectory.isDirectory, equalTo(true)) } @Test(expected = NoSuchFileException::class) fun readFirstLine_throwsException_whenFileNotExists() { fileHandler.readFirstLine(notExistingFile) } @Test fun readFistLine_returnsEmptyString_whenFileIsEmpty() { assertThat(fileHandler.readFirstLine(emptyFile), isEmptyString()) } @Test fun readFirstLine_returnsFirstLine() { assertThat(fileHandler.readFirstLine(file), equalTo(FIRST_LINE)) } @Test fun write_createsFileAndWritesLine_whenFileNotExists() { fileHandler.write(notExistingFile, FIRST_LINE) assertThat(Files.readAllLines(notExistingFile).first(), equalTo(FIRST_LINE)) } @Test fun write_writesLineIntoEmptyFile() { fileHandler.write(emptyFile, FIRST_LINE) val lines = Files.readAllLines(emptyFile) assertThat(lines.size, equalTo(1)) assertThat(lines.first(), equalTo(FIRST_LINE)) } @Test fun write_truncatesExistingFileAndWritesLine() { fileHandler.write(file, NEW_LINE) val lines = Files.readAllLines(file) assertThat(lines.size, equalTo(1)) assertThat(lines.first(), equalTo(NEW_LINE)) } @Test(expected = NoSuchFileException::class) fun move_throwsException_whenSourceNotExists() { fileHandler.move(notExistingFile, emptyFile) } @Test fun move_movesFile() { fileHandler.move(file, emptyFile) assertThat(Files.readAllLines(emptyFile), equalTo(listOf(FIRST_LINE, SECOND_LINE))) } private fun createTestDirectory(): Path { return Files.createTempDirectory("libreplicator-test-file-handler-") } private fun createFile(): Path { val file = testDirectory.resolve("file") Files.write(file, listOf(FIRST_LINE, SECOND_LINE)) return file } private fun createEmptyFile(): Path { val file = testDirectory.resolve("empty-file") file.toFile().createNewFile() return file } private fun initializeNotExistingFile(): Path { return testDirectory.resolve("not-existing-file") } private fun initializeNotExistingDirectory(): Path { return testDirectory.resolve("not-existing-directory") } private fun removeTestDirectory() { testDirectory.toFile().deleteRecursively() } }
libreplicator-core/src/test/kotlin/org/libreplicator/core/journal/file/DefaultFileHandlerTest.kt
3403029876
package com.soywiz.korge.view import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.kmem.umod import com.soywiz.korim.atlas.* import com.soywiz.korim.bitmap.Bitmap import com.soywiz.korim.bitmap.BmpSlice import com.soywiz.korim.bitmap.sliceWithSize class SpriteAnimation constructor( val sprites: List<BmpSlice>, val defaultTimePerFrame: TimeSpan = TimeSpan.NIL ) { companion object { operator fun invoke( spriteMap: Bitmap, spriteWidth: Int = 16, spriteHeight: Int = 16, marginTop: Int = 0, marginLeft: Int = 0, columns: Int = 1, rows: Int = 1, offsetBetweenColumns: Int = 0, offsetBetweenRows: Int = 0 ): SpriteAnimation { return SpriteAnimation( FastArrayList<BmpSlice>().apply { for (row in 0 until rows){ for (col in 0 until columns){ add( spriteMap.sliceWithSize( marginLeft + (spriteWidth + offsetBetweenColumns) * col, marginTop + (spriteHeight + offsetBetweenRows) * row, spriteWidth, spriteHeight, name = "slice$size" ) ) } } } ) } } val spriteStackSize: Int get() = sprites.size val size: Int get() = sprites.size val firstSprite: BmpSlice get() = sprites[0] fun getSprite(index: Int): BmpSlice = sprites[index umod sprites.size] operator fun get(index: Int) = getSprite(index) } fun Atlas.getSpriteAnimation(prefix: String = "", defaultTimePerFrame: TimeSpan = TimeSpan.NIL): SpriteAnimation = SpriteAnimation(this.entries.filter { it.filename.startsWith(prefix) }.map { it.slice }.toFastList(), defaultTimePerFrame) fun Atlas.getSpriteAnimation(regex: Regex, defaultTimePerFrame: TimeSpan = TimeSpan.NIL): SpriteAnimation = SpriteAnimation(this.entries.filter { regex.matches(it.filename) }.map { it.slice }.toFastList(), defaultTimePerFrame)
korge/src/commonMain/kotlin/com/soywiz/korge/view/SpriteAnimation.kt
2879543782
package eu.corvus.corax.platforms.desktop.graphics.context import org.lwjgl.opengl.GL13.* val texturePositions = arrayOf( GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2, GL_TEXTURE3, GL_TEXTURE4, GL_TEXTURE5, GL_TEXTURE6, GL_TEXTURE7, GL_TEXTURE8, GL_TEXTURE9, GL_TEXTURE10, GL_TEXTURE11, GL_TEXTURE12, GL_TEXTURE13, GL_TEXTURE14, GL_TEXTURE15, GL_TEXTURE16, GL_TEXTURE17, GL_TEXTURE18, GL_TEXTURE19, GL_TEXTURE20, GL_TEXTURE21, GL_TEXTURE22, GL_TEXTURE23, GL_TEXTURE24, GL_TEXTURE25, GL_TEXTURE26, GL_TEXTURE27, GL_TEXTURE28, GL_TEXTURE29, GL_TEXTURE30, GL_TEXTURE31 )
src/main/kotlin/eu/corvus/corax/platforms/desktop/graphics/context/convertors.kt
4284826035
package com.soywiz.korge.component.list import com.soywiz.kds.iterators.* import com.soywiz.korge.view.* /* Deprecated("") class GridViewList( val row0: View, val row1: View, val cellSelector: (View) -> Pair<View, View>, val initialRows: Int, val initialColumns: Int, val container: Container = row0.parent!! ) { private val rowsData = arrayListOf<ViewList>() var columns: Int = initialColumns set(value) { field = value update() } var rows: Int = initialRows set(value) { field = value update() } private fun addItem() { val n = container.numChildren val item = row0.clone() container += item item.setMatrixInterpolated(n.toDouble(), row0.localMatrix, row1.localMatrix) val select = cellSelector(item) rowsData += ViewList(select.first, select.second, columns) } private fun removeLastItem() { container.lastChild?.removeFromParent() rowsData.removeAt(rowsData.size - 1) } fun update() { while (rowsData.size < rows) addItem() while (rowsData.size > rows) removeLastItem() rowsData.fastForEach { rowData -> rowData.length = columns } } init { container.removeChildren() update() } val length: Int get() = columns * rows operator fun get(row: Int): ViewList = this.rowsData[row] operator fun get(row: Int, column: Int): View? = this[row][column] } */
korge/src/commonMain/kotlin/com/soywiz/korge/component/list/GridViewList.kt
3342744436
/* * Copyright (c) 2009 Daniel Svärd [email protected]> * Copyright (c) 2011 Norbert Nagold [email protected]> * Copyright (c) 2014 Houssam Salem <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki import android.content.ContentValues import android.text.TextUtils import androidx.annotation.VisibleForTesting import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.CollectionHelper import com.ichi2.anki.R import com.ichi2.async.CancelListener import com.ichi2.libanki.Consts.CARD_QUEUE import com.ichi2.libanki.Consts.CARD_TYPE import com.ichi2.libanki.TemplateManager.TemplateRenderContext.TemplateRenderOutput import com.ichi2.libanki.stats.Stats import com.ichi2.libanki.template.TemplateError import com.ichi2.utils.Assert import com.ichi2.utils.JSONObject import com.ichi2.utils.LanguageUtil import net.ankiweb.rsdroid.RustCleanup import timber.log.Timber import java.util.* import java.util.concurrent.CancellationException /** * A Card is the ultimate entity subject to review; it encapsulates the scheduling parameters (from which to derive * the next interval), the note it is derived from (from which field data is retrieved), its own ownership (which deck it * currently belongs to), and the retrieval of presentation elements (filled-in templates). * * Card presentation has two components: the question (front) side and the answer (back) side. The presentation of the * card is derived from the template of the card's Card Type. The Card Type is a component of the Note Type (see Models) * that this card is derived from. * * This class is responsible for: * - Storing and retrieving database entries that map to Cards in the Collection * - Providing the HTML representation of the Card's question and answer * - Recording the results of review (answer chosen, time taken, etc) * * It does not: * - Generate new cards (see Collection) * - Store the templates or the style sheet (see Models) * * Type: 0=new, 1=learning, 2=due * Queue: same as above, and: * -1=suspended, -2=user buried, -3=sched buried * Due is used differently for different queues. * - new queue: note id or random int * - rev queue: integer day * - lrn queue: integer timestamp */ open class Card : Cloneable { // Needed for tests var col: Collection /** * Time in MS when timer was started */ var timerStarted: Long // Not in LibAnki. Record time spent reviewing in MS in order to restore when resuming. private var elapsedTime: Long = 0 // BEGIN SQL table entries @set:VisibleForTesting var id: Long var nid: Long = 0 var did: Long = 0 var ord = 0 var mod: Long = 0 var usn = 0 @get:CARD_TYPE @CARD_TYPE var type = 0 @get:CARD_QUEUE @CARD_QUEUE var queue = 0 var due: Long = 0 var ivl = 0 var factor = 0 var reps = 0 private set var lapses = 0 var left = 0 var oDue: Long = 0 var oDid: Long = 0 private var flags = 0 private var data: String? = null // END SQL table entries @set:JvmName("setRenderOutput") @get:JvmName("getRenderOutput") protected var render_output: TemplateRenderOutput? private var note: Note? /** Used by Sched to determine which queue to move the card to after answering. */ var wasNew = false /** Used by Sched to record the original interval in the revlog after answering. */ var lastIvl = 0 constructor(col: Collection) { this.col = col timerStarted = 0L render_output = null note = null // to flush, set nid, ord, and due this.id = this.col.time.timestampID(this.col.db, "cards") did = 1 this.type = Consts.CARD_TYPE_NEW queue = Consts.QUEUE_TYPE_NEW ivl = 0 factor = 0 reps = 0 lapses = 0 left = 0 oDue = 0 oDid = 0 flags = 0 data = "" } constructor(col: Collection, id: Long) { this.col = col timerStarted = 0L render_output = null note = null this.id = id load() } fun load() { col.db.query("SELECT * FROM cards WHERE id = ?", this.id).use { cursor -> if (!cursor.moveToFirst()) { throw WrongId(this.id, "card") } this.id = cursor.getLong(0) nid = cursor.getLong(1) did = cursor.getLong(2) ord = cursor.getInt(3) mod = cursor.getLong(4) usn = cursor.getInt(5) this.type = cursor.getInt(6) queue = cursor.getInt(7) due = cursor.getInt(8).toLong() ivl = cursor.getInt(9) factor = cursor.getInt(10) reps = cursor.getInt(11) lapses = cursor.getInt(12) left = cursor.getInt(13) oDue = cursor.getLong(14) oDid = cursor.getLong(15) flags = cursor.getInt(16) data = cursor.getString(17) } render_output = null note = null } @JvmOverloads fun flush(changeModUsn: Boolean = true) { if (changeModUsn) { mod = col.time.intTime() usn = col.usn() } assert(due < "4294967296".toLong()) col.db.execute( "insert or replace into cards values " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", this.id, nid, did, ord, mod, usn, this.type, queue, due, ivl, factor, reps, lapses, left, oDue, oDid, flags, data ) col.log(this) } fun flushSched() { mod = col.time.intTime() usn = col.usn() assert(due < "4294967296".toLong()) val values = ContentValues() values.put("mod", mod) values.put("usn", usn) values.put("type", this.type) values.put("queue", queue) values.put("due", due) values.put("ivl", ivl) values.put("factor", factor) values.put("reps", reps) values.put("lapses", lapses) values.put("left", left) values.put("odue", oDue) values.put("odid", oDid) values.put("did", did) // TODO: The update DB call sets mod=true. Verify if this is intended. col.db.update("cards", values, "id = ?", arrayOf(java.lang.Long.toString(this.id))) col.log(this) } @JvmOverloads fun q(reload: Boolean = false, browser: Boolean = false): String { return render_output(reload, browser).question_and_style() } fun a(): String { return render_output().answer_and_style() } @RustCleanup("legacy") fun css(): String { return "<style>${render_output().css}</style>" } /** * @throws net.ankiweb.rsdroid.exceptions.BackendInvalidInputException: If the card does not exist */ @JvmOverloads @RustCleanup("move col.render_output back to Card once the java collection is removed") open fun render_output(reload: Boolean = false, browser: Boolean = false): TemplateRenderOutput { if (render_output == null || reload) { render_output = col.render_output(this, reload, browser) } return render_output!! } open fun note(): Note { return note(false) } open fun note(reload: Boolean): Note { if (note == null || reload) { note = col.getNote(nid) } return note!! } // not in upstream open fun model(): Model { return note().model() } fun template(): JSONObject { val m = model() return if (m.isStd) { m.getJSONArray("tmpls").getJSONObject(ord) } else { model().getJSONArray("tmpls").getJSONObject(0) } } fun startTimer() { timerStarted = col.time.intTimeMS() } /** * Time limit for answering in milliseconds. */ fun timeLimit(): Int { val conf = col.decks.confForDid(if (!isInDynamicDeck) did else oDid) return conf.getInt("maxTaken") * 1000 } /* * Time taken to answer card, in integer MS. */ fun timeTaken(): Int { // Indeed an int. Difference between two big numbers is still small. val total = (col.time.intTimeMS() - timerStarted).toInt() return Math.min(total, timeLimit()) } open val isEmpty: Boolean get() = try { Models.emptyCard(model(), ord, note().fields) } catch (er: TemplateError) { Timber.w("Card is empty because the card's template has an error: %s.", er.message(col.context)) true } /* * *********************************************************** * The methods below are not in LibAnki. * *********************************************************** */ fun qSimple(): String { return render_output(false).question_text } /* * Returns the answer with anything before the <hr id=answer> tag removed */ val pureAnswer: String get() { val s = render_output(false).answer_text val target = "<hr id=answer>" val pos = s.indexOf(target) return if (pos == -1) { s } else s.substring(pos + target.length).trim { it <= ' ' } } /** * Save the currently elapsed reviewing time so it can be restored on resume. * * Use this method whenever a review session (activity) has been paused. Use the resumeTimer() * method when the session resumes to start counting review time again. */ fun stopTimer() { elapsedTime = col.time.intTimeMS() - timerStarted } /** * Resume the timer that counts the time spent reviewing this card. * * Unlike the desktop client, AnkiDroid must pause and resume the process in the middle of * reviewing. This method is required to keep track of the actual amount of time spent in * the reviewer and *must* be called on resume before any calls to timeTaken() take place * or the result of timeTaken() will be wrong. */ fun resumeTimer() { timerStarted = col.time.intTimeMS() - elapsedTime } @VisibleForTesting fun setReps(reps: Int): Int { return reps.also { this.reps = it } } fun incrReps(): Int { return ++reps } fun showTimer(): Boolean { val options = col.decks.confForDid(if (!isInDynamicDeck) did else oDid) return DeckConfig.parseTimerOpt(options, true) } public override fun clone(): Card { return try { super.clone() as Card } catch (e: CloneNotSupportedException) { throw RuntimeException(e) } } override fun toString(): String { val declaredFields = this.javaClass.declaredFields val members: MutableList<String?> = ArrayList(declaredFields.size) for (f in declaredFields) { try { // skip non-useful elements if (SKIP_PRINT.contains(f.name)) { continue } members.add(String.format("'%s': %s", f.name, f[this])) } catch (e: IllegalAccessException) { members.add(String.format("'%s': %s", f.name, "N/A")) } catch (e: IllegalArgumentException) { members.add(String.format("'%s': %s", f.name, "N/A")) } } return TextUtils.join(", ", members) } override fun equals(other: Any?): Boolean { return if (other is Card) { this.id == other.id } else super.equals(other) } override fun hashCode(): Int { // Map a long to an int. For API>=24 you would just do `Long.hashCode(this.getId())` return (this.id xor (this.id ushr 32)).toInt() } fun userFlag(): Int { return intToFlag(flags) } @VisibleForTesting fun setFlag(flag: Int) { flags = flag } /** Should use [userFlag] */ fun internalGetFlags() = flags fun setUserFlag(flag: Int) { flags = setFlagInInt(flags, flag) } // not in Anki. val dueString: String get() { var t = nextDue() if (queue < 0) { t = "($t)" } return t } // as in Anki aqt/browser.py @VisibleForTesting fun nextDue(): String { val date: Long val due = due date = if (isInDynamicDeck) { return AnkiDroidApp.getAppResources().getString(R.string.card_browser_due_filtered_card) } else if (queue == Consts.QUEUE_TYPE_LRN) { due } else if (queue == Consts.QUEUE_TYPE_NEW || type == Consts.CARD_TYPE_NEW) { return java.lang.Long.valueOf(due).toString() } else if (queue == Consts.QUEUE_TYPE_REV || queue == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN || type == Consts.CARD_TYPE_REV && queue < 0) { val time = col.time.intTime() val nbDaySinceCreation = due - col.sched.today time + nbDaySinceCreation * Stats.SECONDS_PER_DAY } else { return "" } return LanguageUtil.getShortDateFormatFromS(date) } // In Anki Desktop, a card with oDue <> 0 && oDid == 0 is not marked as dynamic. /** Non libAnki */ val isInDynamicDeck: Boolean get() = // In Anki Desktop, a card with oDue <> 0 && oDid == 0 is not marked as dynamic. oDid != 0L val isReview: Boolean get() = this.type == Consts.CARD_TYPE_REV && queue == Consts.QUEUE_TYPE_REV val isNew: Boolean get() = this.type == Consts.CARD_TYPE_NEW /** A cache represents an intermediary step between a card id and a card object. Creating a Card has some fixed cost * in term of database access. Using an id has an unknown cost: none if the card is never accessed, heavy if the * card is accessed a lot of time. CardCache ensure that the cost is paid at most once, by waiting for first access * to load the data, and then saving them. Since CPU and RAM is usually less of a bottleneck than database access, * it may often be worth using this cache. * * Beware that the card is loaded only once. Change in the database are not reflected, so use it only if you can * safely assume that the card has not changed. That is * long id; * Card card = col.getCard(id); * .... * Card card2 = col.getCard(id); * is not equivalent to * long id; * Card.Cache cache = new Cache(col, id); * Card card = cache.getCard(); * .... * Card card2 = cache.getCard(); * * It is equivalent to: * long id; * Card.Cache cache = new Cache(col, id); * Card card = cache.getCard(); * .... * cache.reload(); * Card card2 = cache.getCard(); */ open class Cache : Cloneable { val col: Collection val id: Long private var mCard: Card? = null constructor(col: Collection, id: Long) { this.col = col this.id = id } /** Copy of cache. Useful to create a copy of a subclass without loosing card if it is loaded. */ protected constructor(cache: Cache) { col = cache.col this.id = cache.id mCard = cache.mCard } /** Copy of cache. Useful to create a copy of a subclass without loosing card if it is loaded. */ constructor(card: Card) { col = card.col this.id = card.id mCard = card } /** * The card with id given at creation. Note that it has content of the time at which the card was loaded, which * may have changed in database. So it is not equivalent to getCol().getCard(getId()). If you need fresh data, reload * first. */ @get:Synchronized val card: Card get() { if (mCard == null) { mCard = col.getCard(this.id) } return mCard!! } /** Next access to card will reload the card from the database. */ @Synchronized open fun reload() { mCard = null } override fun hashCode(): Int { return java.lang.Long.valueOf(this.id).hashCode() } /** The cloned version represents the same card but data are not loaded. */ public override fun clone(): Cache { return Cache(col, this.id) } override fun equals(other: Any?): Boolean { return if (other !is Cache) { false } else this.id == other.id } fun loadQA(reload: Boolean, browser: Boolean) { card.render_output(reload, browser) } } companion object { const val TYPE_REV = 2 // A list of class members to skip in the toString() representation val SKIP_PRINT: Set<String> = HashSet( Arrays.asList( "SKIP_PRINT", "\$assertionsDisabled", "TYPE_LRN", "TYPE_NEW", "TYPE_REV", "mNote", "mQA", "mCol", "mTimerStarted", "mTimerStopped" ) ) fun intToFlag(flags: Int): Int { // setting all bits to 0, except the three first one. // equivalent to `mFlags % 8`. Used this way to copy Anki. return flags and 7 } fun setFlagInInt(flags: Int, flag: Int): Int { Assert.that(0 <= flag, "flag to set is negative") Assert.that(flag <= 7, "flag to set is greater than 7.") // Setting the 3 firsts bits to 0, keeping the remaining. val extraData = flags and 7.inv() // flag in 3 fist bits, same data as in mFlags everywhere else return extraData or flag } @Throws(CancellationException::class) fun deepCopyCardArray(originals: Array<Card>, cancelListener: CancelListener): Array<Card> { val col = CollectionHelper.getInstance().getCol(AnkiDroidApp.getInstance()) val copies = mutableListOf<Card>() for (i in originals.indices) { if (cancelListener.isCancelled) { Timber.i("Cancelled during deep copy, probably memory pressure?") throw CancellationException("Cancelled during deep copy") } // TODO: the performance-naive implementation loads from database instead of working in memory // the high performance version would implement .clone() on Card and test it well copies.add(Card(col, originals[i].id)) } return copies.toTypedArray() } } }
AnkiDroid/src/main/java/com/ichi2/libanki/Card.kt
1141391307
/* * Copyright 2016 Ali Moghnieh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blurengine.blur.modules.goal /** * Represents winners data class for winners in the event of stage changing. */ class GoalWinnersStageChangeData(var winners: MutableList<Any> = mutableListOf())
src/main/java/com/blurengine/blur/modules/goal/GoalWinnersStageChangeData.kt
3619841681
package io.mgba.utilities.async import androidx.work.* import androidx.work.WorkManager import androidx.work.OneTimeWorkRequest import io.mgba.mgba object WorkManagerWrapper { // Added this to fix the tests... In cause of the workManager not working irl. This is to blame init { WorkManager.initialize(mgba.context, Configuration.Builder().build()) } private var workManager: WorkManager = WorkManager.getInstance() fun scheduleToRunWhenConnected(worker: Class<out Worker>, tag: String, replace: Boolean = false) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val request = OneTimeWorkRequest.Builder(worker) .setConstraints(constraints) .build() val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP workManager.beginUniqueWork(tag, policy, request).enqueue() } fun scheduleToRunWithExtras(worker: Class<out Worker>, extras: List<Pair<String, String>>, tag: String, replace: Boolean = false) { val data = Data.Builder() extras.forEach { k -> data.putString(k.first, k.second) } val request = OneTimeWorkRequest.Builder(worker) .setInputData(data.build()) .build() val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP workManager.beginUniqueWork(tag, policy, request).enqueue() } fun scheduleToRunWhenConnectedWithExtras(worker: Class<out Worker>, extras: List<Pair<String, Int>>, tag: String, replace: Boolean = false) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val data = Data.Builder() extras.forEach { k -> data.putInt(k.first, k.second) } val request = OneTimeWorkRequest.Builder(worker) .setConstraints(constraints) .setInputData(data.build()) .build() val policy = if(replace) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP workManager.beginUniqueWork(tag, policy, request).enqueue() } }
app/src/main/java/io/mgba/utilities/async/WorkManagerWrapper.kt
974074125
package com.telenav.osv.common.service.location import android.app.IntentService import android.content.Intent import android.location.Address import android.location.Geocoder import android.location.Location import android.os.Bundle import android.os.ResultReceiver import com.telenav.osv.R import com.telenav.osv.utils.Log import java.io.IOException import java.util.* class IntentServiceFetchAddress : IntentService(NAME_SERVICE) { private val TAG by lazy { IntentServiceFetchAddress::class.java.name } var receiver: ResultReceiver? = null override fun onHandleIntent(intent: Intent?) { val geocoder = Geocoder(this, Locale.getDefault()) var errorMessage = "" // Get the location passed to this service through an extra. val location = intent!!.getParcelableExtra<Location>(LOCATION_DATA_LOC) receiver = intent.getParcelableExtra(RECEIVER) val sequenceId = intent.getStringExtra(LOCATION_DATA_SEQ_ID) val sequencePos = intent.getIntExtra(LOCATION_DATA_SEQ_POS, 0) var addresses: List<Address> = emptyList() try { addresses = geocoder.getFromLocation( location.latitude, location.longitude, // In this sample, we get just a single address. RESULTS_NUMBER) } catch (ioException: IOException) { // Catch network or other I/O problems. errorMessage = getString(R.string.service_not_available) Log.e(TAG, errorMessage, ioException) } catch (illegalArgumentException: IllegalArgumentException) { // Catch invalid latitude or longitude values. errorMessage = getString(R.string.invalid_lat_long_used) Log.e(TAG, "$errorMessage. Latitude = $location.latitude , " + "Longitude = $location.longitude", illegalArgumentException) } // Handle case where no address was found. if (addresses.isEmpty()) { if (errorMessage.isEmpty()) { errorMessage = getString(R.string.no_address_found) Log.e(TAG, errorMessage) } deliverResultToReceiver(FAILURE_RESULT, errorMessage, sequenceId, sequencePos) } else { val address = addresses[0] // Fetch the address lines using getAddressLine, // join them, and send them to the thread. val addressFragments = with(address) { (0..maxAddressLineIndex).map { getAddressLine(it) } } Log.i(TAG, getString(R.string.address_found)) deliverResultToReceiver(SUCCESS_RESULT, addressFragments.joinToString(separator = "\n"), sequenceId, sequencePos) } } private fun deliverResultToReceiver(resultCode: Int, message: String, sequenceId: String, position: Int) { val bundle = Bundle().apply { putString(RESULT_DATA_KEY, message) putString(RESULT_DATA_SEQUENCE_ID, sequenceId) putInt(RESULT_DATA_SEQUENCE_POSITION, position) } receiver?.send(resultCode, bundle) } companion object { private const val NAME_SERVICE = "intent-service-fetch-address" const val SUCCESS_RESULT = 0 const val FAILURE_RESULT = 1 const val PACKAGE_NAME = "com.google.android.gms.location.sample.locationaddress" const val RECEIVER = "$PACKAGE_NAME.RECEIVER" const val RESULT_DATA_KEY = "${PACKAGE_NAME}.RESULT_DATA_KEY" const val RESULT_DATA_SEQUENCE_ID = "${PACKAGE_NAME}.RESULT_DATA_SEQUENCE_ID" const val RESULT_DATA_SEQUENCE_POSITION = "${PACKAGE_NAME}.RESULT_DATA_SEQUENCE_POSITION" const val LOCATION_DATA_LOC = "${PACKAGE_NAME}.LOCATION_DATA_LOC" const val LOCATION_DATA_SEQ_ID = "${PACKAGE_NAME}.LOCATION_DATA_SEQ_ID" const val LOCATION_DATA_SEQ_POS = "${PACKAGE_NAME}.LOCATION_DATA_SEQ_POS" private const val RESULTS_NUMBER = 1 } }
app/src/main/java/com/telenav/osv/common/service/location/IntentServiceFetchAddress.kt
3159179509
package fr.bmartel.bboxapi.router.model import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.annotations.SerializedName import fr.bmartel.bboxapi.router.BboxApiUtils data class Device( val device: BboxDevice? = null ){ class Deserializer : ResponseDeserializable<List<Device>> { override fun deserialize(content: String) = BboxApiUtils.fromJson<List<Device>>(content) } } data class BboxDevice( val now: String? = null, val status: Int? = null, val numberofboots: Int? = null, val modelname: String? = null, @SerializedName("user_configured") val userConfigured: Int? = null, val display: Display? = null, val main: Version? = null, val reco: Version? = null, val running: Version? = null, val bcck: Version? = null, val ldr1: Version? = null, val ldr2: Version? = null, val firstusedate: String? = null, val uptime: Int? = null, val serialnumber: String? = null, val using: DeviceService? = null ) data class Display( val luminosity: Int? = null, val state: String? = null ) data class Version( private val version: String? = null, private val date: String? = null ) { fun getMajor(): Int { return BboxApiUtils.getVersionPattern(version, 1) } fun getMinor(): Int { return BboxApiUtils.getVersionPattern(version, 2) } fun getPatch(): Int { return BboxApiUtils.getVersionPattern(version, 3) } } data class DeviceService( val ipv4: Int? = null, val ipv6: Int? = null, val ftth: Int? = null, val adsl: Int? = null, val vdsl: Int? = null )
bboxapi-router/src/main/kotlin/fr/bmartel/bboxapi/router/model/Device.kt
567367114
package ch.schulealtendorf.psa.core.user.validation import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class PSAPasswordValidatorTest { companion object { const val VALID_PASSWORD = "Psa12345$" } private lateinit var passwordValidator: PSAPasswordValidator @BeforeEach internal fun beforeEach() { passwordValidator = PSAPasswordValidator() } @Test internal fun validateWhenAllRulesFulfilled() { val validationResult = passwordValidator.validate(VALID_PASSWORD) assertThat(validationResult.isValid) .withFailMessage("Expected password to be valid") .isTrue assertThat(validationResult.messages).isEmpty() } @Test internal fun validateEqualsWhenPasswordIsValid() { val validationResult = passwordValidator.validateEquals(VALID_PASSWORD, VALID_PASSWORD) assertThat(validationResult.isValid) .withFailMessage("Expected password to be valid") .isTrue assertThat(validationResult.messages).isEmpty() } @Test internal fun validateEqualsWhenPasswordsDontMatch() { val validationResult = passwordValidator.validateEquals(VALID_PASSWORD, "no match") assertThat(validationResult.isValid) .withFailMessage("Expected password to be invalid") .isFalse assertThat(validationResult.messages).hasSize(1) assertThat(validationResult.messages[0]).isEqualTo("Passwords do not match.") } }
app/core/src/test/kotlin/ch/schulealtendorf/psa/core/user/validation/PSAPasswordValidatorTest.kt
3220306112
package com.adityakamble49.ttl.ui.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import com.adityakamble49.ttl.BuildConfig import com.adityakamble49.ttl.R import com.adityakamble49.ttl.utils.* import kotlinx.android.synthetic.main.activity_about.* import kotlinx.android.synthetic.main.card_about_development.* import kotlinx.android.synthetic.main.card_about_general.* import kotlinx.android.synthetic.main.card_about_team.* class AboutActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_about) setSupportActionBar(toolbar) // App Details about_version.text = BuildConfig.VERSION_NAME about_changelog.setOnClickListener { createChangelogDialog(this).show() } about_licenses.setOnClickListener { createLicensesDialog(this).show() } // Team aboutTeamAkshay.setOnClickListener { openUrl("https://github.com/akshaychordiya/") } aboutTeamAditya.setOnClickListener { openUrl("http://www.adityakamble49.com/") } aboutTeamPiyush.setOnClickListener { openUrl("https://plus.google.com/104580127666963940082/") } aboutTeamMarc.setOnClickListener { openUrl("https://plus.google.com/107192270381957371449/") } // Support about_rate.setOnClickListener { openUrl("http://play.google.com/store/apps/details?id=" + packageName) } about_email.setOnClickListener { sendSupportEmail() } } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { android.R.id.home -> consume { finish() } else -> super.onOptionsItemSelected(item) } }
app/src/main/java/com/adityakamble49/ttl/ui/activity/AboutActivity.kt
570364091
package com.calebprior.boilerplate.ui.base import android.support.design.widget.Snackbar import com.calebprior.boilerplate.R import com.calebprior.boilerplate.flowcontrol.FlowController import com.calebprior.boilerplate.ui.base.BaseView import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.info open class BasePresenter<V : BaseView>( var flowController: FlowController ) : AnkoLogger { var view: V? = null open fun afterAttach() {} open fun afterDetach() {} open fun afterError() {} fun attachView(view: V) { this.view = view afterAttach() } fun detachView() { view = null afterDetach() } fun handleError(e: Throwable, message: String = "Error Occurred") { info(e) hideKeyboard() stopLoading() showSnackBar(message) afterError() } fun hideKeyboard() { view?.hideKeyboard() } fun showLoading() { view?.showLoading() } fun stopLoading() { view?.stopLoading() } fun showSnackBar(message: String, id: Int = R.id.root_view, length: Int = Snackbar.LENGTH_SHORT, actionText: String = "", action: () -> Unit = {} ) { view?.showSnackBar(message, id, length, actionText, action) } }
app/src/main/kotlin/com/calebprior/boilerplate/ui/base/BasePresenter.kt
65365924
package com.stripe.android.paymentsheet internal interface PaymentSheetLauncher { fun presentWithPaymentIntent( paymentIntentClientSecret: String, configuration: PaymentSheet.Configuration? = null ) fun presentWithSetupIntent( setupIntentClientSecret: String, configuration: PaymentSheet.Configuration? = null ) }
paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheetLauncher.kt
2507369052
package com.stripe.android.payments.wechatpay import android.app.Activity import androidx.activity.result.ActivityResultLauncher import androidx.fragment.app.Fragment import com.stripe.android.payments.wechatpay.WeChatPayAuthStarter.Legacy import com.stripe.android.payments.wechatpay.WeChatPayAuthStarter.Modern import com.stripe.android.view.AuthActivityStarter import com.stripe.android.view.AuthActivityStarterHost /** * An [AuthActivityStarter] wrapper to start a [WeChatPayAuthActivity] through different APIs. * * [Modern] uses the [ActivityResultLauncher]. * [Legacy] uses [Activity.startActivityForResult] or [Fragment.startActivityForResult]. */ internal sealed class WeChatPayAuthStarter : AuthActivityStarter<WeChatPayAuthContract.Args> { class Modern( private val launcher: ActivityResultLauncher<WeChatPayAuthContract.Args> ) : WeChatPayAuthStarter() { override fun start(args: WeChatPayAuthContract.Args) { launcher.launch(args) } } class Legacy( private val host: AuthActivityStarterHost, private val requestCode: Int ) : WeChatPayAuthStarter() { override fun start(args: WeChatPayAuthContract.Args) { host.startActivityForResult( WeChatPayAuthActivity::class.java, args.toBundle(), requestCode ) } } }
wechatpay/src/main/java/com/stripe/android/payments/wechatpay/WeChatPayAuthStarter.kt
2175574619
package com.stripe.android.financialconnections.model import android.os.Parcelable import com.stripe.android.core.model.StripeModel import com.stripe.android.core.model.serializers.EnumIgnoreUnknownSerializer import kotlinx.parcelize.Parcelize import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * A FinancialConnectionsAccount represents an account that exists outside of Stripe, * to which you have been granted some degree of access. * * @param category * @param created Time at which the object was created. Measured in seconds since the Unix epoch. * @param id Unique identifier for the object. * @param institutionName The name of the institution that holds this account. * @param livemode Has the value `true` if the object exists in live mode or the value `false` if * the object exists in test mode. * @param status The status of the link to the account. * @param subcategory If `category` is `cash`, one of: - `checking` - `savings` - `other` * If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other` * If `category` is `investment` or `other`, this will be `other`. * @param supportedPaymentMethodTypes * The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s) * that can be created from this FinancialConnectionsAccount. * @param accountholder * @param balance The most recent information about the account's balance. * @param balanceRefresh The state of the most recent attempt to refresh the account balance. * @param displayName A human-readable name that has been assigned to this account, * either by the account holder or by the institution. * @param last4 The last 4 digits of the account number. If present, this will be 4 numeric characters. * @param ownership The most recent information about the account's owners. * @param ownershipRefresh The state of the most recent attempt to refresh the account owners. * @param permissions The list of permissions granted by this account. */ @Serializable @Parcelize @Suppress("unused") data class FinancialConnectionsAccount( @SerialName("category") val category: Category = Category.UNKNOWN, /* Time at which the object was created. Measured in seconds since the Unix epoch. */ @SerialName("created") val created: Int, /* Unique identifier for the object. */ @SerialName("id") val id: String, /* The name of the institution that holds this account. */ @SerialName("institution_name") val institutionName: String, /* Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode. */ @SerialName("livemode") val livemode: Boolean, /* The status of the link to the account. */ @SerialName("status") val status: Status = Status.UNKNOWN, /* If `category` is `cash`, one of: - `checking` - `savings` - `other` If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other` If `category` is `investment` or `other`, this will be `other`. */ @SerialName("subcategory") val subcategory: Subcategory = Subcategory.UNKNOWN, /* The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s) that can be created from this FinancialConnectionsAccount. */ @SerialName("supported_payment_method_types") val supportedPaymentMethodTypes: List<SupportedPaymentMethodTypes>, /* The most recent information about the account's balance. */ @SerialName("balance") val balance: Balance? = null, /* The state of the most recent attempt to refresh the account balance. */ @SerialName("balance_refresh") val balanceRefresh: BalanceRefresh? = null, /* A human-readable name that has been assigned to this account, either by the account holder or by the institution. */ @SerialName("display_name") val displayName: String? = null, /* The last 4 digits of the account number. If present, this will be 4 numeric characters. */ @SerialName("last4") val last4: String? = null, /* The most recent information about the account's owners. */ @SerialName("ownership") val ownership: String? = null, /* The state of the most recent attempt to refresh the account owners. */ @SerialName("ownership_refresh") val ownershipRefresh: OwnershipRefresh? = null, /* The list of permissions granted by this account. */ @SerialName("permissions") val permissions: List<Permissions>? = null ) : StripeModel, Parcelable, PaymentAccount() { /** * * * Values: cash,credit,investment,other */ @Serializable(with = Category.Serializer::class) enum class Category(val value: String) { @SerialName("cash") CASH("cash"), @SerialName("credit") CREDIT("credit"), @SerialName("investment") INVESTMENT("investment"), @SerialName("other") OTHER("other"), UNKNOWN("unknown"); internal object Serializer : EnumIgnoreUnknownSerializer<Category>(Category.values(), UNKNOWN) } /** * The status of the link to the account. * * Values: active,disconnected,inactive */ @Serializable(with = Status.Serializer::class) enum class Status(val value: String) { @SerialName("active") ACTIVE("active"), @SerialName("disconnected") DISCONNECTED("disconnected"), @SerialName("inactive") INACTIVE("inactive"), UNKNOWN("unknown"); internal object Serializer : EnumIgnoreUnknownSerializer<Status>(Status.values(), UNKNOWN) } /** * If `category` is `cash`, one of: - `checking` - `savings` - `other` * If `category` is `credit`, one of: - `mortgage` - `line_of_credit` - `credit_card` - `other` * If `category` is `investment` or `other`, this will be `other`. * * Values: checking,creditCard,lineOfCredit,mortgage,other,savings */ @Serializable(with = Subcategory.Serializer::class) enum class Subcategory(val value: String) { @SerialName("checking") CHECKING("checking"), @SerialName("credit_card") CREDIT_CARD("credit_card"), @SerialName("line_of_credit") LINE_OF_CREDIT("line_of_credit"), @SerialName("mortgage") MORTGAGE("mortgage"), @SerialName("other") OTHER("other"), @SerialName("savings") SAVINGS("savings"), UNKNOWN("unknown"); internal object Serializer : EnumIgnoreUnknownSerializer<Subcategory>(Subcategory.values(), UNKNOWN) } /** * The [PaymentMethod type](https://stripe.com/docs/api/payment_methods/object#payment_method_object-type)(s) * that can be created from this FinancialConnectionsAccount. * * Values: link,usBankAccount */ @Serializable(with = SupportedPaymentMethodTypes.Serializer::class) enum class SupportedPaymentMethodTypes(val value: String) { @SerialName("link") LINK("link"), @SerialName("us_bank_account") US_BANK_ACCOUNT("us_bank_account"), UNKNOWN("unknown"); internal object Serializer : EnumIgnoreUnknownSerializer<SupportedPaymentMethodTypes>(values(), UNKNOWN) } /** * The list of permissions granted by this account. * * Values: balances,identity,ownership,paymentMethod,transactions */ @Serializable(with = Permissions.Serializer::class) enum class Permissions(val value: String) { @SerialName("balances") BALANCES("balances"), @SerialName("ownership") OWNERSHIP("ownership"), @SerialName("payment_method") PAYMENT_METHOD("payment_method"), @SerialName("transactions") TRANSACTIONS("transactions"), @SerialName("account_numbers") ACCOUNT_NUMBERS("account_numbers"), UNKNOWN("unknown"); internal object Serializer : EnumIgnoreUnknownSerializer<Permissions>(values(), UNKNOWN) } companion object { internal const val OBJECT_OLD = "linked_account" internal const val OBJECT_NEW = "financial_connections.account" } }
financial-connections/src/main/java/com/stripe/android/financialconnections/model/FinancialConnectionsAccount.kt
434558139
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model.sudoku.complexity /** * This interface specifies methods to create ComplexityConstraints subject to a complexity. */ interface ComplexityFactory { /** * This method creates a complexity constraint that specifies the requirements of a sudoku of the given complexity. * * @param complexity The [Complexity for which to generate a [ComplexityConstraint] * @return A ComplexityConstraint for the given complexity of null, if complexity constraint is not valid * Todo throw illegalArgException instead */ fun buildComplexityConstraint(complexity: Complexity?): ComplexityConstraint? //todo make non-nullable /** * Returns the factor that indicates the number of [Cell]s, that are randomly prefilled and * allow the generation algorithm to validate. * * @return the standard factor for preallocated Cells */ fun getStandardAllocationFactor(): Float }
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/sudoku/complexity/ComplexityFactory.kt
2170904535
/* * The MIT License (MIT) * * Copyright (c) 2020 Vimeo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vimeo.networking2.params import com.vimeo.networking2.enums.StringValue /** * The search options for the rough duration of a video. */ enum class SearchDurationType(override val value: String?) : StringValue { SHORT("short"), MEDIUM("medium"), LONG("long") }
models/src/main/java/com/vimeo/networking2/params/SearchDurationType.kt
4139247226
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration.interop /** * Denotes that the annotated method uses the experimental methods which allow direct access to * camera2 classes. * * The Camera2Interop and Camera2Interop.Extender exposes the underlying instances of camera2 * classes such CameraDevice.StateCallback, CameraCaptureSession.StateCallback and * CameraCaptureSession.CaptureCallback. In addition the configs allow setting of camera2 * CaptureRequest parameters. However, CameraX does not provide any guarantee on how it operates * on these parameters. The ordering and number of times these objects might in order to best * optimize the top level behavior. * * The values from the callbacks should only be read. Methods that modify the CameraDevice or * CameraCaptureSession will likely move CameraX into an inconsistent internal state. * * These will be changed in future release possibly, hence add @Experimental annotation. */ @Retention(AnnotationRetention.BINARY) @RequiresOptIn annotation class ExperimentalCamera2Interop
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/interop/ExperimentalCamera2Interop.kt
1624893045
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.video.internal.encoder import android.media.MediaCodecInfo import androidx.camera.core.impl.Timebase import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = 21) class AudioEncoderInfoImplTest { companion object { private const val MIME_TYPE = "audio/mp4a-latm" private const val ENCODER_PROFILE = MediaCodecInfo.CodecProfileLevel.AACObjectLC private const val BIT_RATE = 64000 private const val SAMPLE_RATE = 44100 private const val CHANNEL_COUNT = 1 private val TIMEBASE = Timebase.UPTIME } private lateinit var encoderConfig: AudioEncoderConfig @Before fun setup() { encoderConfig = AudioEncoderConfig.builder() .setMimeType(MIME_TYPE) .setInputTimebase(TIMEBASE) .setProfile(ENCODER_PROFILE) .setBitrate(BIT_RATE) .setSampleRate(SAMPLE_RATE) .setChannelCount(CHANNEL_COUNT) .build() } @Test fun canCreateEncoderInfoFromConfig() { // No exception is thrown AudioEncoderInfoImpl.from(encoderConfig) } }
camera/camera-video/src/androidTest/java/androidx/camera/video/internal/encoder/AudioEncoderInfoImplTest.kt
1574061095