content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2020 Peter Kenji Yamanaka
*
* 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.pyamsoft.pasterino.main
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import com.pyamsoft.pydroid.arch.UiViewState
import com.pyamsoft.pydroid.ui.theme.Theming
@Stable
@Immutable
internal data class MainViewState
internal constructor(
val theme: Theming.Mode,
val isServiceAlive: Boolean,
) : UiViewState
@Stable
@Immutable
internal data class ToolbarViewState
internal constructor(
val topBarHeight: Int,
val bottomSpaceHeight: Int,
) : UiViewState
| app/src/main/java/com/pyamsoft/pasterino/main/MainFlows.kt | 1503986147 |
/*
* Copyright 2015 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.android.anko.generator
import org.jetbrains.android.anko.utils.MethodNodeWithClass
import org.jetbrains.android.anko.utils.fqName
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.InnerClassNode
import org.objectweb.asm.tree.MethodNode
class ViewElement(val clazz: ClassNode, val isContainer: Boolean, allMethods: () -> List<MethodNode>) {
val allMethods: List<MethodNode> by lazy {
allMethods()
}
val fqName: String
get() = clazz.fqName
}
class LayoutElement(val layout: ClassNode, val layoutParams: ClassNode, val constructors: List<MethodNode>)
class ServiceElement(val service: ClassNode, val name: String)
class PropertyElement(val name: String, val getter: MethodNodeWithClass?, val setters: List<MethodNodeWithClass>)
class ListenerMethod(val methodWithClass: MethodNodeWithClass, val name: String, val returnType: Type)
abstract class ListenerElement(val setter: MethodNodeWithClass, val clazz: ClassNode)
class SimpleListenerElement(
setter: MethodNodeWithClass,
clazz: ClassNode,
val method: ListenerMethod
) : ListenerElement(setter, clazz)
class ComplexListenerElement(
setter: MethodNodeWithClass,
clazz: ClassNode,
val name: String,
val methods: List<ListenerMethod>
) : ListenerElement(setter, clazz) {
val id: String
get() = "${clazz.name}#name"
} | dsl/src/org/jetbrains/android/anko/generator/dslElements.kt | 3468779309 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[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 de.vanita5.twittnuker.loader.users
import android.content.Context
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.PageableResponseList
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.microblog.library.twitter.model.User
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.exception.APINotSupportedException
import de.vanita5.twittnuker.extension.model.api.microblog.mapToPaginated
import de.vanita5.twittnuker.extension.model.api.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.PaginatedList
abstract class UserListRelatedUsersLoader(
context: Context,
accountKey: UserKey?,
private val listId: String?,
private val userKey: UserKey?,
private val screenName: String?,
private val listName: String?,
data: List<ParcelableUser>?,
fromUser: Boolean
) : AbsRequestUsersLoader(context, accountKey, data, fromUser) {
@Throws(MicroBlogException::class)
override final fun getUsers(details: AccountDetails, paging: Paging): PaginatedList<ParcelableUser> {
when (details.type) {
AccountType.TWITTER -> return getTwitterUsers(details, paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
else -> {
throw APINotSupportedException(details.type)
}
}
}
protected abstract fun getByListId(microBlog: MicroBlog, listId: String, paging: Paging): PageableResponseList<User>
protected abstract fun getByUserKey(microBlog: MicroBlog, listName: String, userKey: UserKey, paging: Paging): PageableResponseList<User>
protected abstract fun getByScreenName(microBlog: MicroBlog, listName: String, screenName: String, paging: Paging): PageableResponseList<User>
@Throws(MicroBlogException::class)
private fun getTwitterUsers(details: AccountDetails, paging: Paging): PageableResponseList<User> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
when {
listId != null -> {
return getByListId(microBlog, listId, paging)
}
listName != null && userKey != null -> {
return getByUserKey(microBlog, listName.replace(' ', '-'), userKey, paging)
}
listName != null && screenName != null -> {
return getByScreenName(microBlog, listName.replace(' ', '-'), screenName, paging)
}
}
throw MicroBlogException("list_id or list_name and user_id (or screen_name) required")
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/users/UserListRelatedUsersLoader.kt | 3511024953 |
package com.sapuseven.untis.models.untis
import com.sapuseven.untis.helpers.SerializationUtils.getJSON
import com.sapuseven.untis.models.UntisSchoolInfo
import com.sapuseven.untis.models.untis.response.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class ResponseTest {
@Test
fun baseResponse_serialization() {
assertThat(getJSON().encodeToString<BaseResponse>(BaseResponse()), `is`("""{"id":null,"error":null,"jsonrpc":null}"""))
}
@Test
fun appSharedSecretResponse_serialization() {
assertThat(getJSON().encodeToString<AppSharedSecretResponse>(AppSharedSecretResponse()), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":""}"""))
assertThat(getJSON().encodeToString<AppSharedSecretResponse>(AppSharedSecretResponse(
result = "key"
)), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":"key"}"""))
}
@Test
fun schoolSearchResponse_serialization() {
assertThat(getJSON().encodeToString<SchoolSearchResponse>(SchoolSearchResponse()), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":null}"""))
assertThat(getJSON().encodeToString<SchoolSearchResponse>(SchoolSearchResponse(
result = SchoolSearchResult(
size = 2,
schools = listOf(UntisSchoolInfo(
server = "server 1",
useMobileServiceUrlAndroid = true,
useMobileServiceUrlIos = false,
address = "123",
displayName = "school display name 1",
loginName = "LOGIN_NAME",
schoolId = 123,
serverUrl = "http://",
mobileServiceUrl = "http://"
), UntisSchoolInfo(
server = "server 2",
useMobileServiceUrlAndroid = true,
useMobileServiceUrlIos = false,
address = "123",
displayName = "school display name 2",
loginName = "LOGIN_NAME",
schoolId = 123,
serverUrl = "http://",
mobileServiceUrl = "http://"
))
)
)), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":{"size":2,"schools":[{"server":"server 1","useMobileServiceUrlAndroid":true,"useMobileServiceUrlIos":false,"address":"123","displayName":"school display name 1","loginName":"LOGIN_NAME","schoolId":123,"serverUrl":"http://","mobileServiceUrl":"http://"},{"server":"server 2","useMobileServiceUrlAndroid":true,"useMobileServiceUrlIos":false,"address":"123","displayName":"school display name 2","loginName":"LOGIN_NAME","schoolId":123,"serverUrl":"http://","mobileServiceUrl":"http://"}]}}"""))
}
@Test
fun userDataResponse_serialization() {
assertThat(getJSON().encodeToString<UserDataResponse>(UserDataResponse()), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":null}"""))
/*assertThat(getJSON().encodeToString<UserDataResponse(
result = UntisUserData(
masterData = MasterData(),
userData = UserData(),
settings = Settings()
)
)), `is`("""{"id":null,"error":null,"jsonrpc":null,"result":{"masterData":{"timeStamp":0},"userData":{"elemType":null,"elemId":0,"displayName":"","schoolName":"","departmentId":0},"settings":{"showAbsenceReason":true,"showAbsenceText":true,"absenceCheckRequired":false,"defaultAbsenceReasonId":0,"defaultLatenessReasonId":0,"defaultAbsenceEndTime":null,"customAbsenceEndTime":null}}}"""))*/
}
@Test
fun appSharedSecretResponse_deserialization() {
val appSharedSecretResponse1 = getJSON().decodeFromString<AppSharedSecretResponse>("""{"id":"id","error":{"code":1000,"message":"error message"},"jsonrpc":"2.0"}""")
assertThat(appSharedSecretResponse1.id, `is`("id"))
assertThat(appSharedSecretResponse1.jsonrpc, `is`("2.0"))
assertThat(appSharedSecretResponse1.result, `is`(""))
assertThat(appSharedSecretResponse1.error!!.code, `is`(1000))
assertThat(appSharedSecretResponse1.error!!.message, `is`("error message"))
assertThat(appSharedSecretResponse1.error!!.data, nullValue())
val appSharedSecretResponse2 = getJSON().decodeFromString<AppSharedSecretResponse>("""{"id":"id","jsonrpc":"2.0","result":"key"}""")
assertThat(appSharedSecretResponse2.id, `is`("id"))
assertThat(appSharedSecretResponse2.jsonrpc, `is`("2.0"))
assertThat(appSharedSecretResponse2.result, `is`("key"))
assertThat(appSharedSecretResponse2.error, nullValue())
}
@Test
fun schoolSearchResponse_deserialization() {
val schoolSearchResponse1 = getJSON().decodeFromString<SchoolSearchResponse>("""{"id":"id","error":{"code":1000,"message":"error message"},"jsonrpc":"2.0"}""")
assertThat(schoolSearchResponse1.id, `is`("id"))
assertThat(schoolSearchResponse1.jsonrpc, `is`("2.0"))
assertThat(schoolSearchResponse1.result, nullValue())
assertThat(schoolSearchResponse1.error!!.code, `is`(1000))
assertThat(schoolSearchResponse1.error!!.message, `is`("error message"))
assertThat(schoolSearchResponse1.error!!.data, nullValue())
val schoolSearchResponse2 = getJSON().decodeFromString<SchoolSearchResponse>("""{"id":"id","jsonrpc":"2.0","result":{"size":2,"schools":[{"server":"server 1","useMobileServiceUrlAndroid":true,"useMobileServiceUrlIos":false,"address":"123","displayName":"school display name 1","loginName":"LOGIN_NAME","schoolId":123,"serverUrl":"http://","mobileServiceUrl":"http://"},{"server":"server 2","useMobileServiceUrlAndroid":true,"useMobileServiceUrlIos":false,"address":"123","displayName":"school display name 2","loginName":"LOGIN_NAME","schoolId":123,"serverUrl":"http://","mobileServiceUrl":"http://"}]}}""")
assertThat(schoolSearchResponse2.id, `is`("id"))
assertThat(schoolSearchResponse2.jsonrpc, `is`("2.0"))
assertThat(schoolSearchResponse2.result!!.size, `is`(2))
assertThat(schoolSearchResponse2.result!!.schools[0], `is`(UntisSchoolInfo(
server = "server 1",
useMobileServiceUrlAndroid = true,
useMobileServiceUrlIos = false,
address = "123",
displayName = "school display name 1",
loginName = "LOGIN_NAME",
schoolId = 123,
serverUrl = "http://",
mobileServiceUrl = "http://"
)))
assertThat(schoolSearchResponse2.result!!.schools[1], `is`(UntisSchoolInfo(
server = "server 2",
useMobileServiceUrlAndroid = true,
useMobileServiceUrlIos = false,
address = "123",
displayName = "school display name 2",
loginName = "LOGIN_NAME",
schoolId = 123,
serverUrl = "http://",
mobileServiceUrl = "http://"
)))
assertThat(schoolSearchResponse2.error, nullValue())
}
@Test
fun userDataResponse_deserialization() {
val userDataResponse1 = getJSON().decodeFromString<UserDataResponse>("""{"id":"id","error":{"code":1000,"message":"error message"},"jsonrpc":"2.0"}""")
assertThat(userDataResponse1.id, `is`("id"))
assertThat(userDataResponse1.jsonrpc, `is`("2.0"))
assertThat(userDataResponse1.result, nullValue())
assertThat(userDataResponse1.error, notNullValue())
assertThat(userDataResponse1.error!!.code, `is`(1000))
assertThat(userDataResponse1.error!!.message, `is`("error message"))
assertThat(userDataResponse1.error!!.data, nullValue())
val userDataResponse2 = getJSON().decodeFromString<UserDataResponse>("""{"id":"id","jsonrpc":"2.0","result":{"masterData":{"timeStamp":0,"absenceReasons":[],"departments":[],"duties":[],"eventReasons":[],"eventReasonGroups":[],"excuseStatuses":[],"holidays":[],"klassen":[],"rooms":[],"subjects":[],"teachers":[],"teachingMethods":[],"schoolyears":[],"timeGrid":{"days":[]}},"userData":{"elemType":null,"elemId":0,"displayName":"","schoolName":"","departmentId":0,"children":[],"klassenIds":[],"rights":[]},"settings":{"showAbsenceReason":true,"showAbsenceText":true,"absenceCheckRequired":false,"defaultAbsenceReasonId":0,"defaultLatenessReasonId":0,"defaultAbsenceEndTime":"","customAbsenceEndTime":null}}}""")
assertThat(userDataResponse2.id, `is`("id"))
assertThat(userDataResponse2.jsonrpc, `is`("2.0"))
assertThat(userDataResponse2.result, notNullValue())
assertThat(userDataResponse2.error, nullValue())
}
}
| app/src/test/java/com/sapuseven/untis/models/untis/ResponseTest.kt | 1279471538 |
package com.sapuseven.untis.data.databases
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.Cursor.FIELD_TYPE_INTEGER
import android.database.Cursor.FIELD_TYPE_STRING
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.provider.BaseColumns
import com.sapuseven.untis.R
import com.sapuseven.untis.helpers.SerializationUtils.getJSON
import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateCreateTable
import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateDropTable
import com.sapuseven.untis.helpers.UserDatabaseQueryHelper.generateValues
import com.sapuseven.untis.interfaces.TableModel
import com.sapuseven.untis.models.TimetableBookmark
import com.sapuseven.untis.models.untis.UntisMasterData
import com.sapuseven.untis.models.untis.UntisSettings
import com.sapuseven.untis.models.untis.UntisUserData
import com.sapuseven.untis.models.untis.masterdata.*
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
private const val DATABASE_VERSION = 7
private const val DATABASE_NAME = "userdata.db"
class UserDatabase private constructor(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
const val COLUMN_NAME_USER_ID = "_user_id"
private var instance: UserDatabase? = null
fun createInstance(context: Context): UserDatabase {
return instance ?: UserDatabase(context)
}
}
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V7)
db.execSQL(generateCreateTable<AbsenceReason>())
db.execSQL(generateCreateTable<Department>())
db.execSQL(generateCreateTable<Duty>())
db.execSQL(generateCreateTable<EventReason>())
db.execSQL(generateCreateTable<EventReasonGroup>())
db.execSQL(generateCreateTable<ExcuseStatus>())
db.execSQL(generateCreateTable<Holiday>())
db.execSQL(generateCreateTable<Klasse>())
db.execSQL(generateCreateTable<Room>())
db.execSQL(generateCreateTable<Subject>())
db.execSQL(generateCreateTable<Teacher>())
db.execSQL(generateCreateTable<TeachingMethod>())
db.execSQL(generateCreateTable<SchoolYear>())
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
var currentVersion = oldVersion
while (currentVersion < newVersion) {
when (currentVersion) {
1 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v1")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V2)
db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT _id, apiUrl, NULL, user, ${UserDatabaseContract.Users.TABLE_NAME}_v1.\"key\", anonymous, timeGrid, masterDataTimestamp, userData, settings, time_created FROM ${UserDatabaseContract.Users.TABLE_NAME}_v1;")
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v1")
}
2 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v2")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V3)
db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT * FROM ${UserDatabaseContract.Users.TABLE_NAME}_v2;")
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v2")
}
3 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v3")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V4)
db.execSQL("INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT * FROM ${UserDatabaseContract.Users.TABLE_NAME}_v3;")
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v3")
}
4 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v4")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V5)
db.execSQL(
"INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " +
"${BaseColumns._ID}," +
"'', " +
"${UserDatabaseContract.Users.COLUMN_NAME_APIURL}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USER}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_CREATED} " +
"FROM ${UserDatabaseContract.Users.TABLE_NAME}_v4;"
)
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v4")
}
5 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v5")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V6)
db.execSQL(
"INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " +
"${BaseColumns._ID}," +
"${UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME}, " +
"'', " +
"${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USER}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_CREATED} " +
"FROM ${UserDatabaseContract.Users.TABLE_NAME}_v5;"
)
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v5")
}
6 -> {
db.execSQL("ALTER TABLE ${UserDatabaseContract.Users.TABLE_NAME} RENAME TO ${UserDatabaseContract.Users.TABLE_NAME}_v6")
db.execSQL(UserDatabaseContract.Users.SQL_CREATE_ENTRIES_V7)
db.execSQL(
"INSERT INTO ${UserDatabaseContract.Users.TABLE_NAME} SELECT " +
"${BaseColumns._ID}," +
"'', " +
"${UserDatabaseContract.Users.COLUMN_NAME_APIURL}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USER}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_KEY}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_USERDATA}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_SETTINGS}, " +
"${UserDatabaseContract.Users.COLUMN_NAME_CREATED}, " +
"'[]' " +
"FROM ${UserDatabaseContract.Users.TABLE_NAME}_v6;"
)
db.execSQL("DROP TABLE ${UserDatabaseContract.Users.TABLE_NAME}_v6")
}
}
currentVersion++
}
}
fun resetDatabase(db: SQLiteDatabase) {
db.execSQL(UserDatabaseContract.Users.SQL_DELETE_ENTRIES)
db.execSQL(generateDropTable<AbsenceReason>())
db.execSQL(generateDropTable<Department>())
db.execSQL(generateDropTable<Duty>())
db.execSQL(generateDropTable<EventReason>())
db.execSQL(generateDropTable<EventReasonGroup>())
db.execSQL(generateDropTable<ExcuseStatus>())
db.execSQL(generateDropTable<Holiday>())
db.execSQL(generateDropTable<Klasse>())
db.execSQL(generateDropTable<Room>())
db.execSQL(generateDropTable<Subject>())
db.execSQL(generateDropTable<Teacher>())
db.execSQL(generateDropTable<TeachingMethod>())
db.execSQL(generateDropTable<SchoolYear>())
}
fun addUser(user: User): Long? {
val db = writableDatabase
val values = ContentValues()
values.put(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, user.profileName)
values.put(UserDatabaseContract.Users.COLUMN_NAME_APIURL, user.apiUrl)
values.put(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, user.schoolId)
values.put(UserDatabaseContract.Users.COLUMN_NAME_USER, user.user)
values.put(UserDatabaseContract.Users.COLUMN_NAME_KEY, user.key)
values.put(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, user.anonymous)
values.put(UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, getJSON().encodeToString<TimeGrid>(user.timeGrid))
values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, user.masterDataTimestamp)
values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData))
user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) }
values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData))
user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) }
values.put(UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES, getJSON().encodeToString<List<TimetableBookmark>>(user.bookmarks))
val id = db.insert(UserDatabaseContract.Users.TABLE_NAME, null, values)
db.close()
return if (id == -1L)
null
else
id
}
fun editUser(user: User): Long? {
val db = writableDatabase
val values = ContentValues()
values.put(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME, user.profileName)
values.put(UserDatabaseContract.Users.COLUMN_NAME_APIURL, user.apiUrl)
values.put(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID, user.schoolId)
values.put(UserDatabaseContract.Users.COLUMN_NAME_USER, user.user)
values.put(UserDatabaseContract.Users.COLUMN_NAME_KEY, user.key)
values.put(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS, user.anonymous)
values.put(UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID, getJSON().encodeToString<TimeGrid>(user.timeGrid))
values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, user.masterDataTimestamp)
values.put(UserDatabaseContract.Users.COLUMN_NAME_USERDATA, getJSON().encodeToString<UntisUserData>(user.userData))
user.settings?.let { values.put(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS, getJSON().encodeToString<UntisSettings>(it)) }
values.put(UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES, getJSON().encodeToString<List<TimetableBookmark>>(user.bookmarks))
db.update(UserDatabaseContract.Users.TABLE_NAME, values, BaseColumns._ID + "=?", arrayOf(user.id.toString()))
db.close()
return user.id
}
fun deleteUser(userId: Long) {
val db = writableDatabase
db.delete(UserDatabaseContract.Users.TABLE_NAME, BaseColumns._ID + "=?", arrayOf(userId.toString()))
db.close()
}
fun getUser(id: Long): User? {
val db = this.readableDatabase
val cursor = db.query(
UserDatabaseContract.Users.TABLE_NAME,
arrayOf(
BaseColumns._ID,
UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME,
UserDatabaseContract.Users.COLUMN_NAME_APIURL,
UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID,
UserDatabaseContract.Users.COLUMN_NAME_USER,
UserDatabaseContract.Users.COLUMN_NAME_KEY,
UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS,
UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID,
UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP,
UserDatabaseContract.Users.COLUMN_NAME_USERDATA,
UserDatabaseContract.Users.COLUMN_NAME_SETTINGS,
UserDatabaseContract.Users.COLUMN_NAME_CREATED,
UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES
),
BaseColumns._ID + "=?",
arrayOf(id.toString()), null, null, UserDatabaseContract.Users.COLUMN_NAME_CREATED + " DESC")
if (!cursor.moveToFirst())
return null
val user = User(
id,
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME)),
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_APIURL)),
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID)),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_USER)),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_KEY)),
cursor.getIntOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS)) == 1,
getJSON().decodeFromString(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID
)
)
),
cursor.getLong(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP)),
getJSON().decodeFromString<UntisUserData>(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_USERDATA
)
)
),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS))
?.let { getJSON().decodeFromString<UntisSettings>(it) },
cursor.getLongOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_CREATED)),
getJSON().decodeFromString(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES
)
)
),
)
cursor.close()
db.close()
return user
}
fun getAllUsers(): List<User> {
val users = ArrayList<User>()
val db = this.readableDatabase
val cursor = db.query(
UserDatabaseContract.Users.TABLE_NAME,
arrayOf(
BaseColumns._ID,
UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME,
UserDatabaseContract.Users.COLUMN_NAME_APIURL,
UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID,
UserDatabaseContract.Users.COLUMN_NAME_USER,
UserDatabaseContract.Users.COLUMN_NAME_KEY,
UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS,
UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID,
UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP,
UserDatabaseContract.Users.COLUMN_NAME_USERDATA,
UserDatabaseContract.Users.COLUMN_NAME_SETTINGS,
UserDatabaseContract.Users.COLUMN_NAME_CREATED,
UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES
), null, null, null, null, UserDatabaseContract.Users.COLUMN_NAME_CREATED + " DESC")
if (cursor.moveToFirst()) {
do {
users.add(User(
cursor.getLongOrNull(cursor.getColumnIndexOrThrow(BaseColumns._ID)),
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_PROFILENAME)),
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_APIURL)),
cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SCHOOL_ID)),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_USER)),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_KEY)),
cursor.getInt(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_ANONYMOUS)) == 1,
getJSON().decodeFromString<TimeGrid>(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_TIMEGRID
)
)
),
cursor.getLong(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP)),
getJSON().decodeFromString<UntisUserData>(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_USERDATA
)
)
),
cursor.getStringOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_SETTINGS))
?.let { getJSON().decodeFromString<UntisSettings>(it) },
cursor.getLongOrNull(cursor.getColumnIndexOrThrow(UserDatabaseContract.Users.COLUMN_NAME_CREATED)),
getJSON().decodeFromString(
cursor.getString(
cursor.getColumnIndexOrThrow(
UserDatabaseContract.Users.COLUMN_NAME_BOOKMARK_TIMETABLES
)
)
)
))
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return users
}
fun getUsersCount(): Int {
val db = this.readableDatabase
val cursor = db.query(
UserDatabaseContract.Users.TABLE_NAME,
arrayOf(BaseColumns._ID), null, null, null, null, null)
val count = cursor.count
cursor.close()
db.close()
return count
}
fun setAdditionalUserData(
userId: Long,
masterData: UntisMasterData
) {
val db = writableDatabase
db.beginTransaction()
listOf(
AbsenceReason.TABLE_NAME to masterData.absenceReasons,
Department.TABLE_NAME to masterData.departments,
Duty.TABLE_NAME to masterData.duties,
EventReason.TABLE_NAME to masterData.eventReasons,
EventReasonGroup.TABLE_NAME to masterData.eventReasonGroups,
ExcuseStatus.TABLE_NAME to masterData.excuseStatuses,
Holiday.TABLE_NAME to masterData.holidays,
Klasse.TABLE_NAME to masterData.klassen,
Room.TABLE_NAME to masterData.rooms,
Subject.TABLE_NAME to masterData.subjects,
Teacher.TABLE_NAME to masterData.teachers,
TeachingMethod.TABLE_NAME to masterData.teachingMethods,
SchoolYear.TABLE_NAME to masterData.schoolyears
).forEach { refreshAdditionalUserData(db, userId, it.first, it.second) }
val values = ContentValues()
values.put(UserDatabaseContract.Users.COLUMN_NAME_MASTERDATATIMESTAMP, masterData.timeStamp)
db.update(
UserDatabaseContract.Users.TABLE_NAME,
values,
BaseColumns._ID + "=?",
arrayOf(userId.toString()))
db.setTransactionSuccessful()
db.endTransaction()
db.close()
}
private fun refreshAdditionalUserData(db: SQLiteDatabase, userId: Long, tableName: String, items: List<TableModel>?) {
db.delete(tableName, "$COLUMN_NAME_USER_ID=?", arrayOf(userId.toString()))
items?.forEach { data -> db.insert(tableName, null, generateValues(userId, data)) }
}
inline fun <reified T : TableModel> getAdditionalUserData(userId: Long, table: TableModel): Map<Int, T>? {
val db = readableDatabase
val cursor = db.query(
table.tableName,
table.generateValues().keySet().toTypedArray(), "$COLUMN_NAME_USER_ID=?",
arrayOf(userId.toString()), null, null, "id DESC")
if (!cursor.moveToFirst())
return null
val result = mutableMapOf<Int, T>()
if (cursor.moveToFirst()) {
do {
val data = table.parseCursor(cursor) as T
result[(data as TableModel).elementId] = data
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return result.toMap()
}
class User(
val id: Long? = null,
val profileName: String = "",
val apiUrl: String,
val schoolId: String,
val user: String? = null,
val key: String? = null,
val anonymous: Boolean = false,
val timeGrid: TimeGrid,
val masterDataTimestamp: Long,
val userData: UntisUserData,
val settings: UntisSettings? = null,
val created: Long? = null,
var bookmarks: List<TimetableBookmark>
) {
fun getDisplayedName(context: Context): String {
return when {
profileName.isNotBlank() -> profileName
anonymous -> context.getString(R.string.all_anonymous)
else -> userData.displayName
}
}
}
}
private fun Cursor.getIntOrNull(columnIndex: Int): Int? {
return if (getType(columnIndex) == FIELD_TYPE_INTEGER)
getInt(columnIndex)
else null
}
private fun Cursor.getLongOrNull(columnIndex: Int): Long? {
return if (getType(columnIndex) == FIELD_TYPE_INTEGER)
getLong(columnIndex)
else null
}
private fun Cursor.getStringOrNull(columnIndex: Int): String? {
return if (getType(columnIndex) == FIELD_TYPE_STRING)
getString(columnIndex)
else null
}
| app/src/main/java/com/sapuseven/untis/data/databases/UserDatabase.kt | 1704175820 |
package org.wikipedia.dataclient.mwapi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.wikipedia.dataclient.page.Protection
import org.wikipedia.gallery.ImageInfo
import org.wikipedia.page.Namespace
@Serializable
class MwQueryPage {
@SerialName("descriptionsource") val descriptionSource: String? = null
@SerialName("imageinfo") private val imageInfo: List<ImageInfo>? = null
@SerialName("videoinfo") private val videoInfo: List<ImageInfo>? = null
@SerialName("watchlistexpiry") private val watchlistExpiry: String? = null
@SerialName("pageviews") val pageViewsMap: Map<String, Long?> = emptyMap()
@SerialName("pageid") val pageId = 0
@SerialName("pageprops") val pageProps: PageProps? = null
@SerialName("entityterms") val entityTerms: EntityTerms? = null
private val ns = 0
private var coordinates: List<Coordinates>? = null
private val thumbnail: Thumbnail? = null
private val varianttitles: Map<String, String>? = null
private val actions: Map<String, List<MwServiceError>>? = null
val index = 0
var title: String = ""
val langlinks: List<LangLink> = emptyList()
val revisions: List<Revision> = emptyList()
val protection: List<Protection> = emptyList()
val extract: String? = null
val description: String? = null
private val imagerepository: String? = null
var redirectFrom: String? = null
var convertedFrom: String? = null
var convertedTo: String? = null
val watched = false
val lastrevid: Long = 0
fun namespace(): Namespace {
return Namespace.of(ns)
}
fun coordinates(): List<Coordinates>? {
// TODO: Handle null values in lists during deserialization, perhaps with a new
// @RequiredElements annotation and corresponding TypeAdapter
coordinates = coordinates?.filterNotNull()
return coordinates
}
fun thumbUrl(): String? {
return thumbnail?.source
}
fun imageInfo(): ImageInfo? {
return imageInfo?.get(0) ?: videoInfo?.get(0)
}
fun appendTitleFragment(fragment: String?) {
title += "#$fragment"
}
fun displayTitle(langCode: String): String {
return varianttitles?.get(langCode).orEmpty().ifEmpty { title }
}
val isImageShared: Boolean
get() = imagerepository.orEmpty() == "shared"
fun hasWatchlistExpiry(): Boolean {
return !watchlistExpiry.isNullOrEmpty()
}
fun getErrorForAction(actionName: String): List<MwServiceError> {
return actions?.get(actionName) ?: emptyList()
}
@Serializable
class Revision {
@SerialName("contentformat") private val contentFormat: String? = null
@SerialName("contentmodel") private val contentModel: String? = null
@SerialName("timestamp") val timeStamp: String = ""
private val slots: Map<String, RevisionSlot>? = null
val minor = false
@SerialName("revid") val revId: Long = 0
@SerialName("parentid") val parentRevId: Long = 0
@SerialName("anon") val isAnon = false
val size = 0
val user: String = ""
val content: String = ""
val comment: String = ""
val parsedcomment: String = ""
var diffSize = 0
fun getContentFromSlot(slot: String): String {
return slots?.get(slot)?.content.orEmpty()
}
}
@Serializable
class RevisionSlot(val content: String = "",
private val contentformat: String? = null,
private val contentmodel: String? = null)
@Serializable
class LangLink(val lang: String = "", val title: String = "")
@Serializable
class Coordinates(val lat: Double? = null, val lon: Double? = null)
@Serializable
internal class Thumbnail(val source: String? = null,
private val width: Int = 0,
private val height: Int = 0)
@Serializable
class PageProps {
@SerialName("wikibase_item") val wikiBaseItem: String = ""
private val disambiguation: String? = null
@SerialName("displaytitle") val displayTitle: String? = null
}
@Serializable
class EntityTerms {
val alias: List<String> = emptyList()
val label: List<String> = emptyList()
val description: List<String> = emptyList()
}
}
| app/src/main/java/org/wikipedia/dataclient/mwapi/MwQueryPage.kt | 1155865396 |
package org.softeg.slartus.forpdaplus.forum.impl.ui.fingerprints
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.BaseViewHolder
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.Item
import org.softeg.slartus.forpdaplus.core_lib.ui.adapter.ItemFingerprint
import org.softeg.slartus.forpdaplus.forum.impl.R
import org.softeg.slartus.forpdaplus.forum.impl.databinding.LayoutTopicsBinding
class TopicsItemItemFingerprint(
private val onClickListener: (view: View?, item: TopicsItemItem) -> Unit
) :
ItemFingerprint<LayoutTopicsBinding, TopicsItemItem> {
private val diffUtil = object : DiffUtil.ItemCallback<TopicsItemItem>() {
override fun areItemsTheSame(
oldItem: TopicsItemItem,
newItem: TopicsItemItem
) = oldItem.id == newItem.id
override fun areContentsTheSame(
oldItem: TopicsItemItem,
newItem: TopicsItemItem
) = oldItem == newItem
}
override fun getLayoutId() = R.layout.layout_topics
override fun isRelativeItem(item: Item) = item is TopicsItemItem
override fun getViewHolder(
layoutInflater: LayoutInflater,
parent: ViewGroup
): BaseViewHolder<LayoutTopicsBinding, TopicsItemItem> {
val binding = LayoutTopicsBinding.inflate(layoutInflater, parent, false)
return TopicsItemViewHolder(binding, onClickListener)
}
override fun getDiffUtil() = diffUtil
}
class TopicsItemViewHolder(
binding: LayoutTopicsBinding,
private val onClickListener: (view: View?, item: TopicsItemItem) -> Unit
) :
BaseViewHolder<LayoutTopicsBinding, TopicsItemItem>(binding) {
init {
itemView.setOnClickListener { v -> onClickListener(v, item) }
}
}
data class TopicsItemItem(
val id: String?
) : Item | forum/forum-impl/src/main/java/org/softeg/slartus/forpdaplus/forum/impl/ui/fingerprints/TopicsItemFingerprint.kt | 2062793605 |
package pl.wendigo.chrome.api.log
/**
* Log entry.
*
* @link [Log#LogEntry](https://chromedevtools.github.io/devtools-protocol/tot/Log#type-LogEntry) type documentation.
*/
@kotlinx.serialization.Serializable
data class LogEntry(
/**
* Log entry source.
*/
val source: String,
/**
* Log entry severity.
*/
val level: String,
/**
* Logged text.
*/
val text: String,
/**
* Timestamp when this entry was added.
*/
val timestamp: pl.wendigo.chrome.api.runtime.Timestamp,
/**
* URL of the resource if known.
*/
val url: String? = null,
/**
* Line number in the resource.
*/
val lineNumber: Int? = null,
/**
* JavaScript stack trace.
*/
val stackTrace: pl.wendigo.chrome.api.runtime.StackTrace? = null,
/**
* Identifier of the network request associated with this entry.
*/
val networkRequestId: pl.wendigo.chrome.api.network.RequestId? = null,
/**
* Identifier of the worker associated with this entry.
*/
val workerId: String? = null,
/**
* Call arguments.
*/
val args: List<pl.wendigo.chrome.api.runtime.RemoteObject>? = null
)
/**
* Violation configuration setting.
*
* @link [Log#ViolationSetting](https://chromedevtools.github.io/devtools-protocol/tot/Log#type-ViolationSetting) type documentation.
*/
@kotlinx.serialization.Serializable
data class ViolationSetting(
/**
* Violation type.
*/
val name: String,
/**
* Time threshold to trigger upon.
*/
val threshold: Double
)
| src/main/kotlin/pl/wendigo/chrome/api/log/Types.kt | 932126606 |
/*
* 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 org.apache.jmeter.threads.openmodel
import org.apiguardian.api.API
import org.slf4j.LoggerFactory
import java.nio.DoubleBuffer
import java.util.PrimitiveIterator
import java.util.Random
import kotlin.math.min
import kotlin.math.sqrt
/**
* Generates events that represent constant, linearly increasing or linearly decreasing load.
*
* Sample usage:
*
* val ramp = PoissonArrivalsRamp()
* ramp.prepare(beginRate = 0.0, endRate = 1.0, duration = 10, random = ...)
* while(ramp.hasNext()) {
* println(ramp.nextDouble()) // -> values from 0..duration
* }
*/
@API(status = API.Status.EXPERIMENTAL, since = "5.5")
public class PoissonArrivalsRamp : PrimitiveIterator.OfDouble {
private lateinit var events: DoubleBuffer
private companion object {
private val log = LoggerFactory.getLogger(PoissonArrivalsRamp::class.java)
}
override fun remove() {
TODO("Element removal is not supported")
}
override fun hasNext(): Boolean = events.hasRemaining()
/**
* Returns the time of the next event `0..duration`.
*/
override fun nextDouble(): Double = events.get()
private fun ensureCapacity(len: Int) {
if (::events.isInitialized && events.capacity() >= len) {
events.clear()
return
}
events = DoubleBuffer.allocate(len)
}
/**
* Prepares events for constant, linearly increasing or linearly decreasing load.
* @param beginRate the load rate at the beginning of the interval, must be positive
* @param endRate the load rate at the end of the interval, must be positive
* @param duration the duration of the load interval, must be positive
* @param random random number generator
*/
public fun prepare(
beginRate: Double,
endRate: Double,
duration: Double,
random: Random
) {
val minRate = min(beginRate, endRate)
// 3.7 events means 3, not 4. It ensures we always we do not overflow over duration interval
val numEvents = ((beginRate + endRate) / 2 * duration).toInt()
ensureCapacity(numEvents)
val flatEvents = (minRate * duration).toInt()
val events = events
if (minRate > 0) {
// Generate uniform process with minimal rate
repeat(flatEvents) {
events.put(random.nextDouble() * duration)
}
}
val eventsLeft = numEvents - flatEvents
if (log.isInfoEnabled) {
log.info(
"Generating {} events, beginRate = {} / sec, endRate = {} / sec, duration = {} sec",
numEvents,
beginRate,
endRate,
duration
)
}
if (beginRate != endRate && eventsLeft != 0) {
// The rest is either increasing from 0 or decreasing to 0 load
// For "increasing from 0 to 1" load the cumulative distribution function is x*x
// so sqrt(random) generates "linearly increasing load"
// and 1-sqrt(random) generates "linearly decreasing load"
// See https://en.wikipedia.org/wiki/Inverse_transform_sampling
repeat(eventsLeft) {
var time = sqrt(random.nextDouble())
if (beginRate > endRate) {
time = 1 - time
}
events.put(time * duration)
}
}
events.array().sort(0, events.position())
events.flip()
}
}
| src/core/src/main/kotlin/org/apache/jmeter/threads/openmodel/PoissonArrivalsRamp.kt | 2343035145 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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 linq.sql.functions
import linq.sql.parser.Lexer
import java.util.*
/**
* Created by Tom Needham on 09/03/2016.
*/
class SQLFunctions {
companion object SQL{
fun<ElementType> ExecSQL(list: AbstractList<ElementType?>, SQL: String) : ArrayList<ElementType?>?{
val lexical : Lexer = Lexer(SQL)
if(lexical.Start())
return ArrayList<ElementType?>()
else
return null
}
}
} | src/linq/sql/functions/SQLFunctions.kt | 3937284529 |
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.FollowableInteractions
/**
* All actions that can be taken on a category.
*/
@JsonClass(generateAdapter = true)
data class CategoryInteractions(
@Json(name = "follow")
override val follow: FollowInteraction? = null
) : FollowableInteractions
| models/src/main/java/com/vimeo/networking2/CategoryInteractions.kt | 2836121747 |
package com.xenoage.zong.core.music.clef
import com.xenoage.zong.core.music.Pitch
import com.xenoage.zong.core.music.Pitch.Companion.pi
import com.xenoage.zong.core.music.Step
/**
* Symbols for clefs.
*/
enum class ClefSymbol(
/** The pitch of the line position this type of clef sits on. */
val pitch: Pitch,
/** The minimum line position allowed for a sharp symbol of a key signature. */
val minSharpLp: Int,
/** The minimum line position allowed for a flat symbol of a key signature. */
val minFlatLp: Int,
/** The octave change implied by this clef.
* E.g. 0 means no change, 1 means 1 octave higher, -2 means two octaves lower. */
val octaveChange: Int
) {
/** G clef. */
G(pi(Step.G, 0, 4), 3, 1, 0),
/** G clef quindicesima bassa. */
G15vb(pi(Step.G, 0, 2), 3, 1, -2),
/** G clef ottava bassa. */
G8vb(pi(Step.G, 0, 3), 3, 1, -1),
/** G clef ottava alta. */
G8va(pi(Step.G, 0, 5), 3, 1, 1),
/** G clef quindicesima alta. */
G15va(pi(Step.G, 0, 6), 3, 1, 2),
/** F clef. */
F(pi(Step.F, 0, 3), 1, -1, 0),
/** F clef quindicesima bassa. */
F15vb(pi(Step.F, 0, 1), 1, -1, -2),
/** F clef ottava bassa. */
F8vb(pi(Step.F, 0, 2), 1, -1, -1),
/** F clef ottava alta. */
F8va(pi(Step.F, 0, 4), 1, -1, 1),
/** F clef quindicesima alta. */
F15va(pi(Step.F, 0, 5), 1, -1, 2),
/** C clef. */
C(pi(Step.C, 0, 4), 2, 0, 0),
/** Tab clef. */
Tab(pi(Step.B, 0, 4), 3, 1, 0),
/** Smaller tab clef. */
TabSmall(pi(Step.B, 0, 4), 3, 1, 0),
/** Percussion clef, two filled rects. */
PercTwoRects(pi(Step.B, 0, 4), 3, 1, 0),
/** Percussion clef, large empty rects. */
PercEmptyRect(pi(Step.B, 0, 4), 3, 1, 0),
/** No clef symbol. */
None(pi(Step.B, 0, 4), 3, 1, 0)
}
| core/src/com/xenoage/zong/core/music/clef/ClefSymbol.kt | 432599570 |
package expo.modules.devlauncher.launcher
import android.content.Intent
import android.net.Uri
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.ReactNativeHost
import com.facebook.react.bridge.ReactContext
import expo.modules.devlauncher.DevLauncherController
import expo.modules.manifests.core.Manifest
import expo.modules.updatesinterface.UpdatesInterface
import kotlinx.coroutines.CoroutineScope
interface DevLauncherControllerInterface {
suspend fun loadApp(url: Uri, mainActivity: ReactActivity? = null)
fun onAppLoaded(context: ReactContext)
fun onAppLoadedWithError()
fun getRecentlyOpenedApps(): Map<String, String?>
fun navigateToLauncher()
fun maybeSynchronizeDevMenuDelegate()
fun maybeInitDevMenuDelegate(context: ReactContext)
fun getCurrentReactActivityDelegate(activity: ReactActivity, delegateSupplierDevLauncher: DevLauncherReactActivityDelegateSupplier): ReactActivityDelegate
fun handleIntent(intent: Intent?, activityToBeInvalidated: ReactActivity?): Boolean
val manifest: Manifest?
val manifestURL: Uri?
val devClientHost: DevLauncherClientHost
val mode: DevLauncherController.Mode
val appHost: ReactNativeHost
val latestLoadedApp: Uri?
val useDeveloperSupport: Boolean
var updatesInterface: UpdatesInterface?
val coroutineScope: CoroutineScope
}
| packages/expo-dev-launcher/android/src/main/java/expo/modules/devlauncher/launcher/DevLauncherControllerInterface.kt | 1229018866 |
package com.github.kittinunf.fuel.core
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.net.URL
class ResponseTest {
@Test
fun responseHasHeaderGetter() {
val response = Response(
url = URL("https://test.fuel.com"),
headers = Headers.from(Headers.CONTENT_TYPE to "image/png")
)
assertThat(response[Headers.CONTENT_TYPE].lastOrNull(), equalTo("image/png"))
}
@Test
fun responseHasHeader() {
val response = Response(
url = URL("https://test.fuel.com"),
headers = Headers.from(Headers.CONTENT_TYPE to "image/png")
)
assertThat(response.header(Headers.CONTENT_TYPE).lastOrNull(), equalTo("image/png"))
}
} | fuel/src/test/kotlin/com/github/kittinunf/fuel/core/ResponseTest.kt | 1252777085 |
/*
* Copyright 2020 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.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.animation.animateColorAsState
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.IconToggleButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
@Sampled
@Composable
fun IconButtonSample() {
IconButton(onClick = { /* doSomething() */ }) {
Icon(Icons.Filled.Favorite, contentDescription = "Localized description")
}
}
@Sampled
@Composable
fun IconToggleButtonSample() {
var checked by remember { mutableStateOf(false) }
IconToggleButton(checked = checked, onCheckedChange = { checked = it }) {
val tint by animateColorAsState(if (checked) Color(0xFFEC407A) else Color(0xFFB0BEC5))
Icon(Icons.Filled.Favorite, contentDescription = "Localized description", tint = tint)
}
}
| compose/material/material/samples/src/main/java/androidx/compose/material/samples/IconButtonSamples.kt | 2854370602 |
package com.github.jk1.ytplugin
interface YouTrackConnectionTrait {
val serverUrl: String
get() = "https://ytplugintest.youtrack.cloud"
val serverUrlOld: String
get() = "https://ytplugintest.myjetbrains.com/youtrack"
val projectId: String
get() = "AT"
val username: String
get() = "ideplugin"
val password: String
get() = "ideplugin"
val token: String
get() = "perm:aWRlcGx1Z2lu.NjItMA==.7iaoaBCduVgrbAj9BkQSxksQLQcEte"
val applicationPassword: String
get() = "YOJSM4CNCD8ZKBSYI59H"
} | src/test/kotlin/com/github/jk1/ytplugin/YouTrackConnectionTrait.kt | 3803678080 |
/*
Copyright 2017-2020 Charles Korn.
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 batect.execution.model.events
import batect.testutils.on
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object TemporaryDirectoryDeletionFailedEventSpec : Spek({
describe("a 'temporary directory deletion failed' event") {
val directoryPath = Jimfs.newFileSystem(Configuration.unix()).getPath("/some-path")
val event = TemporaryDirectoryDeletionFailedEvent(directoryPath, "Something went wrong.")
on("toString()") {
it("returns a human-readable representation of itself") {
assertThat(event.toString(), equalTo("TemporaryDirectoryDeletionFailedEvent(directory path: '/some-path', message: 'Something went wrong.')"))
}
}
}
})
| app/src/unitTest/kotlin/batect/execution/model/events/TemporaryDirectoryDeletionFailedEventSpec.kt | 1752438012 |
package com.habitrpg.android.habitica.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentPromoInfoBinding
import com.habitrpg.android.habitica.helpers.AppConfigManager
import javax.inject.Inject
class PromoInfoFragment : BaseMainFragment<FragmentPromoInfoBinding>() {
override var binding: FragmentPromoInfoBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentPromoInfoBinding {
return FragmentPromoInfoBinding.inflate(inflater, container, false)
}
@Inject
lateinit var configManager: AppConfigManager
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val promo = configManager.activePromo()
promo?.configureInfoFragment(this)
}
override fun onResume() {
super.onResume()
activity?.title = ""
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/PromoInfoFragment.kt | 3961430292 |
/*
Copyright 2017-2020 Charles Korn.
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 batect.docker
import batect.config.Container
import batect.config.VariableExpression
import batect.config.LiteralValue
import batect.config.VariableExpressionEvaluationException
import batect.execution.ConfigVariablesProvider
import batect.execution.ContainerRuntimeConfiguration
import batect.os.proxies.ProxyEnvironmentVariablesProvider
import batect.testutils.given
import batect.testutils.imageSourceDoesNotMatter
import batect.testutils.isEmptyMap
import batect.testutils.on
import batect.testutils.withMessage
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.throws
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.doThrow
import com.nhaarman.mockitokotlin2.mock
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object DockerContainerEnvironmentVariableProviderSpec : Spek({
describe("a Docker container environment variable provider") {
val allContainersInNetwork = setOf(
Container("container-1", imageSourceDoesNotMatter()),
Container("container-2", imageSourceDoesNotMatter())
)
given("the console's type is not provided") {
val terminalType = null as String?
given("propagating proxy environment variables is disabled") {
val hostEnvironmentVariables = emptyMap<String, String>()
val propagateProxyEnvironmentVariables = false
val proxyEnvironmentVariablesProvider = mock<ProxyEnvironmentVariablesProvider> {
on { getProxyEnvironmentVariables(setOf("container-1", "container-2")) } doReturn mapOf("SOME_PROXY_VAR" to "this should not be used")
}
val provider = DockerContainerEnvironmentVariableProvider(proxyEnvironmentVariablesProvider, hostEnvironmentVariables, configVariablesProviderFor(emptyMap()))
given("there are no additional environment variables") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to LiteralValue("SOME_VALUE"))
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
on("getting environment variables for the container") {
it("returns the environment variables from the container") {
assertThat(environmentVariables, equalTo(mapOf("SOME_VAR" to "SOME_VALUE")))
}
}
}
given("there are additional environment variables") {
val additionalEnvironmentVariables = mapOf(
"SOME_HOST_VAR" to LiteralValue("SOME_HOST_VALUE")
)
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
given("none of them conflict with environment variables on the container") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to LiteralValue("SOME_VALUE"))
)
on("getting environment variables for the container") {
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and from the additional environment variables") {
assertThat(
environmentVariables, equalTo(
mapOf(
"SOME_VAR" to "SOME_VALUE",
"SOME_HOST_VAR" to "SOME_HOST_VALUE"
)
)
)
}
}
}
given("one of them conflicts with environment variables on the container") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_HOST_VAR" to LiteralValue("SOME_CONTAINER_VALUE"))
)
on("getting environment variables for the container") {
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and from the additional environment variables, with the additional environment variables taking precedence") {
assertThat(
environmentVariables, equalTo(
mapOf(
"SOME_HOST_VAR" to "SOME_HOST_VALUE"
)
)
)
}
}
}
}
}
}
given("the console's type is provided") {
val terminalType = "some-term"
val proxyEnvironmentVariablesProvider = mock<ProxyEnvironmentVariablesProvider>()
val hostEnvironmentVariables = emptyMap<String, String>()
val provider = DockerContainerEnvironmentVariableProvider(proxyEnvironmentVariablesProvider, hostEnvironmentVariables, configVariablesProviderFor(emptyMap()))
val propagateProxyEnvironmentVariables = false
given("a container with no override for the TERM environment variable") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to LiteralValue("SOME_VALUE"))
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and the TERM environment variable from the host") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALUE",
"TERM" to "some-term"
))
)
}
}
}
given("a container with an override for the TERM environment variable") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf(
"SOME_VAR" to LiteralValue("SOME_VALUE"),
"TERM" to LiteralValue("some-other-term")
)
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and the TERM environment variable from the container") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALUE",
"TERM" to "some-other-term"
))
)
}
}
}
given("some additional environment variables with an override for the TERM environment variable") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf(
"SOME_VAR" to LiteralValue("SOME_VALUE")
)
)
val additionalEnvironmentVariables = mapOf("TERM" to LiteralValue("some-additional-term"))
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and the TERM environment variable from the additional environment variables") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALUE",
"TERM" to "some-additional-term"
))
)
}
}
}
given("both the container and the additional environment variables have an override for the TERM environment variable") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf(
"SOME_VAR" to LiteralValue("SOME_VALUE"),
"TERM" to LiteralValue("some-container-term")
)
)
val additionalEnvironmentVariables = mapOf("TERM" to LiteralValue("some-additional-term"))
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the environment variables from the container and the TERM environment variable from the additional environment variables") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALUE",
"TERM" to "some-additional-term"
)))
}
}
}
}
given("there are references to config variables or host environment variables") {
val terminalType = null as String?
val proxyEnvironmentVariablesProvider = mock<ProxyEnvironmentVariablesProvider>()
val hostEnvironmentVariables = mapOf("SOME_HOST_VARIABLE" to "SOME_HOST_VALUE")
val configVariables = mapOf("SOME_CONFIG_VARIABLE" to "SOME_CONFIG_VALUE")
val provider = DockerContainerEnvironmentVariableProvider(proxyEnvironmentVariablesProvider, hostEnvironmentVariables, configVariablesProviderFor(configVariables))
val propagateProxyEnvironmentVariables = false
val invalidReference = mock<VariableExpression> {
on { evaluate(hostEnvironmentVariables, configVariables) } doThrow VariableExpressionEvaluationException("Couldn't evaluate expression.")
}
given("and those references are on the container") {
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
given("and the reference is valid") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to LiteralValue("SOME_VALID_VALUE"))
)
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the value of the reference") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALID_VALUE"
)))
}
}
}
given("and the reference is not valid") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to invalidReference)
)
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
it("throws an appropriate exception") {
assertThat({ provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork) },
throws<ContainerCreationFailedException>(withMessage("The value for the environment variable 'SOME_VAR' cannot be evaluated: Couldn't evaluate expression."))
)
}
}
}
}
given("and those references are in the additional environment variables") {
given("and the reference is valid") {
val container = Container(
"some-container",
imageSourceDoesNotMatter()
)
val additionalEnvironmentVariables = mapOf("SOME_VAR" to LiteralValue("SOME_VALID_VALUE"))
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the overridden value") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALID_VALUE"
)))
}
}
}
given("and the references is invalid") {
val container = Container(
"some-container",
imageSourceDoesNotMatter()
)
val additionalEnvironmentVariables = mapOf("SOME_VAR" to invalidReference)
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
it("throws an appropriate exception") {
assertThat({ provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork) },
throws<ContainerCreationFailedException>(withMessage("The value for the environment variable 'SOME_VAR' cannot be evaluated: Couldn't evaluate expression."))
)
}
}
}
given("and the reference overrides a container-level environment variable that is invalid") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf("SOME_VAR" to invalidReference)
)
val additionalEnvironmentVariables = mapOf("SOME_VAR" to LiteralValue("SOME_VALID_VALUE"))
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the overridden value") {
assertThat(environmentVariables, equalTo(mapOf(
"SOME_VAR" to "SOME_VALID_VALUE"
)))
}
}
}
}
}
given("there are proxy environment variables present on the host") {
val terminalType = null as String?
val hostEnvironmentVariables = emptyMap<String, String>()
val proxyEnvironmentVariablesProvider = mock<ProxyEnvironmentVariablesProvider> {
on { getProxyEnvironmentVariables(setOf("container-1", "container-2")) } doReturn mapOf(
"HTTP_PROXY" to "http://some-proxy",
"NO_PROXY" to "dont-proxy-this"
)
}
val provider = DockerContainerEnvironmentVariableProvider(proxyEnvironmentVariablesProvider, hostEnvironmentVariables, configVariablesProviderFor(emptyMap()))
given("propagating proxy environment variables is enabled") {
val propagateProxyEnvironmentVariables = true
given("neither the container nor the additional environment variables override the proxy settings") {
val container = Container(
"some-container",
imageSourceDoesNotMatter()
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the proxy environment variables from the host") {
assertThat(environmentVariables, equalTo(mapOf(
"HTTP_PROXY" to "http://some-proxy",
"NO_PROXY" to "dont-proxy-this"
))
)
}
}
}
given("the container overrides the proxy settings") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf(
"HTTP_PROXY" to LiteralValue("http://some-other-proxy")
)
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the proxy environment variables from the host, with overrides from the container") {
assertThat(environmentVariables, equalTo(mapOf(
"HTTP_PROXY" to "http://some-other-proxy",
"NO_PROXY" to "dont-proxy-this"
))
)
}
}
}
given("the additional environment variables override the proxy settings") {
val container = Container(
"some-container",
imageSourceDoesNotMatter(),
environment = mapOf(
"HTTP_PROXY" to LiteralValue("http://some-other-proxy")
)
)
val additionalEnvironmentVariables = mapOf(
"HTTP_PROXY" to LiteralValue("http://some-additional-proxy")
)
on("getting environment variables for the container") {
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("returns the proxy environment variables from the host, with overrides from the container and additional environment variables") {
assertThat(environmentVariables, equalTo(mapOf(
"HTTP_PROXY" to "http://some-additional-proxy",
"NO_PROXY" to "dont-proxy-this"
))
)
}
}
}
}
given("propagating proxy environment variables is disabled") {
val propagateProxyEnvironmentVariables = false
on("getting environment variables for the container") {
val container = Container(
"some-container",
imageSourceDoesNotMatter()
)
val additionalEnvironmentVariables = emptyMap<String, VariableExpression>()
val config = configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables)
val environmentVariables = provider.environmentVariablesFor(container, config, propagateProxyEnvironmentVariables, terminalType, allContainersInNetwork)
it("does not propagate the proxy environment variables") {
assertThat(environmentVariables, isEmptyMap())
}
}
}
}
}
})
private fun configWithAdditionalEnvironmentVariables(additionalEnvironmentVariables: Map<String, VariableExpression>) =
ContainerRuntimeConfiguration(null, null, null, additionalEnvironmentVariables, emptySet())
private fun configVariablesProviderFor(variables: Map<String, String?>) = mock<ConfigVariablesProvider> {
on { configVariableValues } doReturn variables
}
| app/src/unitTest/kotlin/batect/docker/DockerContainerEnvironmentVariableProviderSpec.kt | 1977194658 |
package org.jetbrains.dokka.tests
import org.jetbrains.dokka.NodeKind
import org.jetbrains.dokka.RefKind
import org.junit.Assert.*
import org.junit.Ignore
import org.junit.Test
public class JavaTest {
@Test fun function() {
verifyJavaPackageMember("testdata/java/member.java") { cls ->
assertEquals("Test", cls.name)
assertEquals(NodeKind.Class, cls.kind)
with(cls.members(NodeKind.Function).single()) {
assertEquals("fn", name)
assertEquals("Summary for Function", content.summary.toTestString().trimEnd())
assertEquals(3, content.sections.size)
with(content.sections[0]) {
assertEquals("Parameters", tag)
assertEquals("name", subjectName)
assertEquals("render(Type:String,SUMMARY): is String parameter", toTestString())
}
with(content.sections[1]) {
assertEquals("Parameters", tag)
assertEquals("value", subjectName)
assertEquals("render(Type:String,SUMMARY): is int parameter", toTestString())
}
with(content.sections[2]) {
assertEquals("Author", tag)
assertEquals("yole", toTestString())
}
assertEquals("Unit", detail(NodeKind.Type).name)
assertTrue(members.none())
assertTrue(links.none())
with(details.first { it.name == "name" }) {
assertEquals(NodeKind.Parameter, kind)
assertEquals("String", detail(NodeKind.Type).name)
}
with(details.first { it.name == "value" }) {
assertEquals(NodeKind.Parameter, kind)
assertEquals("Int", detail(NodeKind.Type).name)
}
}
}
}
@Test fun memberWithModifiers() {
verifyJavaPackageMember("testdata/java/memberWithModifiers.java") { cls ->
val modifiers = cls.details(NodeKind.Modifier).map { it.name }
assertTrue("abstract" in modifiers)
with(cls.members.single { it.name == "fn" }) {
assertEquals("protected", details[0].name)
}
with(cls.members.single { it.name == "openFn" }) {
assertEquals("open", details[1].name)
}
}
}
@Test fun superClass() {
verifyJavaPackageMember("testdata/java/superClass.java") { cls ->
val superTypes = cls.details(NodeKind.Supertype)
assertEquals(2, superTypes.size)
assertEquals("Exception", superTypes[0].name)
assertEquals("Cloneable", superTypes[1].name)
}
}
@Test fun arrayType() {
verifyJavaPackageMember("testdata/java/arrayType.java") { cls ->
with(cls.members(NodeKind.Function).single()) {
val type = detail(NodeKind.Type)
assertEquals("Array", type.name)
assertEquals("String", type.detail(NodeKind.Type).name)
with(details(NodeKind.Parameter).single()) {
val parameterType = detail(NodeKind.Type)
assertEquals("IntArray", parameterType.name)
}
}
}
}
@Test fun typeParameter() {
verifyJavaPackageMember("testdata/java/typeParameter.java") { cls ->
val typeParameters = cls.details(NodeKind.TypeParameter)
with(typeParameters.single()) {
assertEquals("T", name)
with(detail(NodeKind.UpperBound)) {
assertEquals("Comparable", name)
assertEquals("T", detail(NodeKind.Type).name)
}
}
with(cls.members(NodeKind.Function).single()) {
val methodTypeParameters = details(NodeKind.TypeParameter)
with(methodTypeParameters.single()) {
assertEquals("E", name)
}
}
}
}
@Test fun constructors() {
verifyJavaPackageMember("testdata/java/constructors.java") { cls ->
val constructors = cls.members(NodeKind.Constructor)
assertEquals(2, constructors.size)
with(constructors[0]) {
assertEquals("<init>", name)
}
}
}
@Test fun innerClass() {
verifyJavaPackageMember("testdata/java/InnerClass.java") { cls ->
val innerClass = cls.members(NodeKind.Class).single()
assertEquals("D", innerClass.name)
}
}
@Test fun varargs() {
verifyJavaPackageMember("testdata/java/varargs.java") { cls ->
val fn = cls.members(NodeKind.Function).single()
val param = fn.detail(NodeKind.Parameter)
assertEquals("vararg", param.details(NodeKind.Modifier).first().name)
val psiType = param.detail(NodeKind.Type)
assertEquals("String", psiType.name)
assertTrue(psiType.details(NodeKind.Type).isEmpty())
}
}
@Test fun fields() {
verifyJavaPackageMember("testdata/java/field.java") { cls ->
val i = cls.members(NodeKind.Property).single { it.name == "i" }
assertEquals("Int", i.detail(NodeKind.Type).name)
assertTrue("var" in i.details(NodeKind.Modifier).map { it.name })
val s = cls.members(NodeKind.Property).single { it.name == "s" }
assertEquals("String", s.detail(NodeKind.Type).name)
assertFalse("var" in s.details(NodeKind.Modifier).map { it.name })
assertTrue("static" in s.details(NodeKind.Modifier).map { it.name })
}
}
@Test fun staticMethod() {
verifyJavaPackageMember("testdata/java/staticMethod.java") { cls ->
val m = cls.members(NodeKind.Function).single { it.name == "foo" }
assertTrue("static" in m.details(NodeKind.Modifier).map { it.name })
}
}
/**
* `@suppress` not supported in Java!
*
* [Proposed tags](http://www.oracle.com/technetwork/java/javase/documentation/proposed-tags-142378.html)
* Proposed tag `@exclude` for it, but not supported yet
*/
@Ignore("@suppress not supported in Java!") @Test fun suppressTag() {
verifyJavaPackageMember("testdata/java/suppressTag.java") { cls ->
assertEquals(1, cls.members(NodeKind.Function).size)
}
}
@Test fun hideAnnotation() {
verifyJavaPackageMember("testdata/java/hideAnnotation.java") { cls ->
assertEquals(1, cls.members(NodeKind.Function).size)
assertEquals(1, cls.members(NodeKind.Property).size)
// The test file contains two classes, one of which is hidden.
// The test for @hide annotation on classes is via verifyJavaPackageMember(),
// which will throw an IllegalArgumentException if it detects more than one class.
}
}
@Test fun annotatedAnnotation() {
verifyJavaPackageMember("testdata/java/annotatedAnnotation.java") { cls ->
assertEquals(1, cls.annotations.size)
with(cls.annotations[0]) {
assertEquals(1, details.count())
with(details[0]) {
assertEquals(NodeKind.Parameter, kind)
assertEquals(1, details.count())
with(details[0]) {
assertEquals(NodeKind.Value, kind)
assertEquals("[AnnotationTarget.FIELD, AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER]", name)
}
}
}
}
}
@Test fun deprecation() {
verifyJavaPackageMember("testdata/java/deprecation.java") { cls ->
val fn = cls.members(NodeKind.Function).single()
assertEquals("This should no longer be used", fn.deprecation!!.content.toTestString())
}
}
@Test fun javaLangObject() {
verifyJavaPackageMember("testdata/java/javaLangObject.java") { cls ->
val fn = cls.members(NodeKind.Function).single()
assertEquals("Any", fn.detail(NodeKind.Type).name)
}
}
@Test fun enumValues() {
verifyJavaPackageMember("testdata/java/enumValues.java") { cls ->
val superTypes = cls.details(NodeKind.Supertype)
assertEquals(1, superTypes.size)
assertEquals(1, cls.members(NodeKind.EnumItem).size)
}
}
@Test fun inheritorLinks() {
verifyJavaPackageMember("testdata/java/InheritorLinks.java") { cls ->
val fooClass = cls.members.single { it.name == "Foo" }
val inheritors = fooClass.references(RefKind.Inheritor)
assertEquals(1, inheritors.size)
}
}
}
| core/src/test/kotlin/model/JavaTest.kt | 3716179996 |
package org.jetbrains.android.anko.config
import java.io.File
val LOG_LEVEL = CliConfigurationKey(
"logLevel",
defaultValue = Logger.LogLevel.WARNING,
mapper = { Logger.LogLevel.valueOf(it) })
val CONFIGURATION = CliConfigurationKey(
"configuration",
mapper = ::File)
val OUTPUT_DIRECTORY = CliConfigurationKey(
"outputDirectory",
mapper = ::File)
val ANDROID_SDK_LOCATION = CliConfigurationKey(
"androidSdk",
mapper = ::File)
val CLI_CONFIGURATION_KEYS: List<CliConfigurationKey<Any>> = listOf(
LOG_LEVEL, CONFIGURATION, OUTPUT_DIRECTORY, ANDROID_SDK_LOCATION) | anko/library/generator/src/org/jetbrains/android/anko/config/configurationKeys.kt | 1394205290 |
package taiwan.no1.app.ssfm.models.entities.lastfm
import com.google.gson.annotations.SerializedName
/**
* @author jieyi
* @since 10/16/17
*/
data class TrackSimilarEntity(@SerializedName("similartracks")
var similartrack: TopTrackEntity.Tracks) | app/src/main/kotlin/taiwan/no1/app/ssfm/models/entities/lastfm/TrackSimilarEntity.kt | 1824322937 |
package com.simplemobiletools.notes.pro.interfaces
import androidx.room.*
import com.simplemobiletools.notes.pro.models.Note
@Dao
interface NotesDao {
@Query("SELECT * FROM notes ORDER BY title COLLATE NOCASE ASC")
fun getNotes(): List<Note>
@Query("SELECT * FROM notes WHERE id = :id")
fun getNoteWithId(id: Long): Note?
@Query("SELECT id FROM notes WHERE path = :path")
fun getNoteIdWithPath(path: String): Long?
@Query("SELECT id FROM notes WHERE title = :title COLLATE NOCASE")
fun getNoteIdWithTitle(title: String): Long?
@Query("SELECT id FROM notes WHERE title = :title")
fun getNoteIdWithTitleCaseSensitive(title: String): Long?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertOrUpdate(note: Note): Long
@Delete
fun deleteNote(note: Note)
}
| app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/NotesDao.kt | 2496078060 |
package org.thoughtcrime.securesms.stories.tabs
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.animation.PathInterpolatorCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieProperty
import com.airbnb.lottie.model.KeyPath
import org.signal.core.util.DimensionUnit
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.util.visible
import java.text.NumberFormat
/**
* Displays the "Chats" and "Stories" tab to a user.
*/
class ConversationListTabsFragment : Fragment(R.layout.conversation_list_tabs) {
private val viewModel: ConversationListTabsViewModel by viewModels(ownerProducer = { requireActivity() })
private lateinit var chatsUnreadIndicator: TextView
private lateinit var storiesUnreadIndicator: TextView
private lateinit var chatsIcon: LottieAnimationView
private lateinit var storiesIcon: LottieAnimationView
private lateinit var chatsPill: ImageView
private lateinit var storiesPill: ImageView
private var shouldBeImmediate = true
private var pillAnimator: Animator? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
chatsUnreadIndicator = view.findViewById(R.id.chats_unread_indicator)
storiesUnreadIndicator = view.findViewById(R.id.stories_unread_indicator)
chatsIcon = view.findViewById(R.id.chats_tab_icon)
storiesIcon = view.findViewById(R.id.stories_tab_icon)
chatsPill = view.findViewById(R.id.chats_pill)
storiesPill = view.findViewById(R.id.stories_pill)
val iconTint = ContextCompat.getColor(requireContext(), R.color.signal_colorOnSecondaryContainer)
chatsIcon.addValueCallback(
KeyPath("**"),
LottieProperty.COLOR
) { iconTint }
storiesIcon.addValueCallback(
KeyPath("**"),
LottieProperty.COLOR
) { iconTint }
view.findViewById<View>(R.id.chats_tab_touch_point).setOnClickListener {
viewModel.onChatsSelected()
}
view.findViewById<View>(R.id.stories_tab_touch_point).setOnClickListener {
viewModel.onStoriesSelected()
}
viewModel.state.observe(viewLifecycleOwner) {
update(it, shouldBeImmediate)
shouldBeImmediate = false
}
}
private fun update(state: ConversationListTabsState, immediate: Boolean) {
chatsIcon.isSelected = state.tab == ConversationListTab.CHATS
chatsPill.isSelected = state.tab == ConversationListTab.CHATS
storiesIcon.isSelected = state.tab == ConversationListTab.STORIES
storiesPill.isSelected = state.tab == ConversationListTab.STORIES
val hasStateChange = state.tab != state.prevTab
if (immediate) {
chatsIcon.pauseAnimation()
storiesIcon.pauseAnimation()
chatsIcon.progress = if (state.tab == ConversationListTab.CHATS) 1f else 0f
storiesIcon.progress = if (state.tab == ConversationListTab.STORIES) 1f else 0f
runPillAnimation(0, chatsPill, storiesPill)
} else if (hasStateChange) {
runLottieAnimations(chatsIcon, storiesIcon)
runPillAnimation(150, chatsPill, storiesPill)
}
chatsUnreadIndicator.visible = state.unreadChatsCount > 0
chatsUnreadIndicator.text = formatCount(state.unreadChatsCount)
storiesUnreadIndicator.visible = state.unreadStoriesCount > 0
storiesUnreadIndicator.text = formatCount(state.unreadStoriesCount)
requireView().visible = state.visibilityState.isVisible()
}
private fun runLottieAnimations(vararg toAnimate: LottieAnimationView) {
toAnimate.forEach {
if (it.isSelected) {
it.resumeAnimation()
} else {
if (it.isAnimating) {
it.pauseAnimation()
}
it.progress = 0f
}
}
}
private fun runPillAnimation(duration: Long, vararg toAnimate: ImageView) {
val (selected, unselected) = toAnimate.partition { it.isSelected }
pillAnimator?.cancel()
pillAnimator = AnimatorSet().apply {
this.duration = duration
interpolator = PathInterpolatorCompat.create(0.17f, 0.17f, 0f, 1f)
playTogether(
selected.map { view ->
view.visibility = View.VISIBLE
ValueAnimator.ofInt(view.paddingLeft, 0).apply {
addUpdateListener {
view.setPadding(it.animatedValue as Int, 0, it.animatedValue as Int, 0)
}
}
}
)
start()
}
unselected.forEach {
val smallPad = DimensionUnit.DP.toPixels(16f).toInt()
it.setPadding(smallPad, 0, smallPad, 0)
it.visibility = View.INVISIBLE
}
}
private fun formatCount(count: Long): String {
if (count > 99L) {
return getString(R.string.ConversationListTabs__99p)
}
return NumberFormat.getInstance().format(count)
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/tabs/ConversationListTabsFragment.kt | 2221839275 |
package com.sedsoftware.yaptalker.presentation.base
import com.arellomobile.mvp.viewstate.strategy.AddToEndSingleStrategy
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType
interface CanShowLoadingIndicator {
@StateStrategyType(value = AddToEndSingleStrategy::class, tag = "LoadingIndicator")
fun showLoadingIndicator()
@StateStrategyType(value = AddToEndSingleStrategy::class, tag = "LoadingIndicator")
fun hideLoadingIndicator()
}
| app/src/main/java/com/sedsoftware/yaptalker/presentation/base/CanShowLoadingIndicator.kt | 3423722494 |
/*
* 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.camera2.pipe.integration.testing
import androidx.camera.camera2.pipe.CameraDevices
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CameraMetadata
import kotlinx.coroutines.runBlocking
class FakeCameraDevicesWithCameraMetaData(
private val cameraMetadataMap: Map<CameraId, CameraMetadata>,
private val defaultCameraMetadata: CameraMetadata
) : CameraDevices {
@Deprecated(
message = "findAll may block the calling thread and is deprecated.",
replaceWith = ReplaceWith("ids"),
level = DeprecationLevel.WARNING
)
override fun findAll(): List<CameraId> = runBlocking { ids() }
override suspend fun ids(): List<CameraId> = cameraMetadataMap.keys.toList()
override suspend fun getMetadata(camera: CameraId): CameraMetadata = awaitMetadata(camera)
override fun awaitMetadata(camera: CameraId) =
cameraMetadataMap[camera] ?: defaultCameraMetadata
} | camera/camera-camera2-pipe-integration/src/test/java/androidx/camera/camera2/pipe/integration/testing/FakeCameraDevicesWithCameraMetaData.kt | 85455505 |
package io.github.crabzilla.stack.command.internal
import io.github.crabzilla.core.CommandSession
import io.github.crabzilla.stack.*
import io.github.crabzilla.stack.CrabzillaContext.Companion.POSTGRES_NOTIFICATION_CHANNEL
import io.github.crabzilla.stack.command.CommandServiceApi
import io.github.crabzilla.stack.command.CommandServiceConfig
import io.github.crabzilla.stack.command.CommandServiceException
import io.github.crabzilla.stack.command.CommandServiceException.ConcurrencyException
import io.github.crabzilla.stack.command.CommandServiceOptions
import io.vertx.core.Future
import io.vertx.core.Future.failedFuture
import io.vertx.core.Future.succeededFuture
import io.vertx.core.Promise
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.sqlclient.*
import org.slf4j.LoggerFactory
import java.time.Instant
import java.util.*
internal class DefaultCommandServiceApi<S : Any, C : Any, E : Any>(
private val crabzillaContext: CrabzillaContext,
private val commandServiceConfig: CommandServiceConfig<S, C, E>,
private val serDer: JsonObjectSerDer<S, C, E>,
private val options: CommandServiceOptions = CommandServiceOptions(),
) : CommandServiceApi<C> {
companion object {
const val SQL_LOCK =
""" SELECT pg_try_advisory_xact_lock($1, $2) as locked
"""
const val GET_EVENTS_BY_ID =
"""
SELECT id, event_type, event_payload, version, causation_id, correlation_id
FROM events
WHERE state_id = $1
ORDER BY sequence
"""
const val SQL_APPEND_EVENT =
""" INSERT
INTO events (event_type, causation_id, correlation_id, state_type, state_id, event_payload, version, id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) returning sequence"""
const val SQL_APPEND_CMD =
""" INSERT INTO commands (state_id, causation_id, last_causation_id, cmd_payload)
VALUES ($1, $2, $3, $4)"""
const val correlationIdIndex = 2
const val eventPayloadIndex = 5
const val currentVersionIndex = 6
const val eventIdIndex = 7
}
private val streamName = commandServiceConfig.stateClass.simpleName!!
private val log = LoggerFactory.getLogger("${DefaultCommandServiceApi::class.java.simpleName}-$streamName")
override fun handle(stateId: UUID, command: C, versionPredicate: ((Int) -> Boolean)?): Future<EventMetadata> {
return crabzillaContext.pgPool().withTransaction { conn: SqlConnection ->
handle(conn, stateId, command, versionPredicate)
}
}
override fun withinTransaction(f: (SqlConnection) -> Future<EventMetadata>): Future<EventMetadata> {
return crabzillaContext.pgPool().withTransaction(f)
}
override fun handle(conn: SqlConnection, stateId: UUID, command: C, versionPredicate: ((Int) -> Boolean)?)
: Future<EventMetadata> {
fun lock(conn: SqlConnection): Future<Void> {
return conn
.preparedQuery(SQL_LOCK)
.execute(Tuple.of(streamName.hashCode(), stateId.hashCode()))
.compose { pgRow ->
if (pgRow.first().getBoolean("locked")) {
succeededFuture()
} else {
failedFuture(ConcurrencyException("Can't be locked ${stateId}"))
}
}
}
fun appendEvents(
conn: SqlConnection,
snapshot: Snapshot<S>?,
events: List<E>,
): Future<List<EventRecord>> {
var resultingVersion = snapshot?.version ?: 0
val eventIds = events.map { UUID.randomUUID() }
val causationIds = eventIds.toMutableList()
val correlationIds = eventIds.toMutableList()
val tuples = events.mapIndexed { index, event ->
correlationIds[index] = snapshot?.correlationId ?: causationIds[0]
val eventAsJsonObject = serDer.eventToJson(event)
val eventId = eventIds[index]
val type = eventAsJsonObject.getString("type")
if (index == 0) {
causationIds[0] = snapshot?.causationId ?: eventIds[0]
} else {
causationIds[index] = eventIds[(index - 1)]
}
Tuple.of(type, causationIds[index], correlationIds[index], streamName,
stateId, eventAsJsonObject, ++resultingVersion, eventId
)
}
val appendedEventList = mutableListOf<EventRecord>()
return conn.preparedQuery(SQL_APPEND_EVENT)
.executeBatch(tuples)
.onSuccess { rowSet ->
var rs: RowSet<Row>? = rowSet
List(tuples.size) { index ->
val sequence = rs!!.iterator().next().getLong("sequence")
val correlationId = tuples[index].getUUID(correlationIdIndex)
val currentVersion = tuples[index].getInteger(currentVersionIndex)
val eventId = tuples[index].getUUID(eventIdIndex)
val eventPayload = tuples[index].getJsonObject(eventPayloadIndex)
val eventMetadata = EventMetadata(
stateType = streamName, stateId = stateId, eventId = eventId,
correlationId = correlationId, causationId = eventId, eventSequence = sequence, version = currentVersion,
tuples[index].getString(0)
)
appendedEventList.add(EventRecord(eventMetadata, eventPayload))
rs = rs!!.next()
}
}.map {
appendedEventList
}
}
fun projectEvents(conn: SqlConnection, appendedEvents: List<EventRecord>, subscription: EventProjector)
: Future<Void> {
log.debug("Will project {} events", appendedEvents.size)
val initialFuture = succeededFuture<Void>()
return appendedEvents.fold(
initialFuture
) { currentFuture: Future<Void>, appendedEvent: EventRecord ->
currentFuture.compose {
subscription.project(conn, appendedEvent)
}
}.mapEmpty()
}
fun appendCommand(conn: SqlConnection, cmdAsJson: JsonObject, stateId: UUID,
causationId: UUID, lastCausationId: UUID): Future<Void> {
log.debug("Will append command {} as {}", command, cmdAsJson)
val params = Tuple.of(stateId, causationId, lastCausationId, cmdAsJson)
return conn.preparedQuery(SQL_APPEND_CMD).execute(params).mapEmpty()
}
return lock(conn)
.compose {
log.debug("State locked {}", stateId.hashCode())
getSnapshot(conn, stateId)
}.compose { snapshot: Snapshot<S>? ->
if (snapshot == null) {
succeededFuture(null)
} else {
succeededFuture(snapshot)
}
}.compose { snapshot: Snapshot<S>? ->
log.debug("Got snapshot {}", snapshot)
if (versionPredicate != null && !versionPredicate.invoke(snapshot?.version ?: 0)) {
val error = "Current version ${snapshot?.version ?: 0} is invalid"
failedFuture(ConcurrencyException(error))
} else {
try {
val session = commandServiceConfig.commandHandler.handle(command, snapshot?.state)
succeededFuture(Pair(snapshot, session))
} catch (e: Exception) {
val error = CommandServiceException.BusinessException(e.message ?: "Unknown")
failedFuture(error)
}
}
}.compose { pair ->
val (snapshot: Snapshot<S>?, session: CommandSession<S, E>) = pair
log.debug("Command handled")
appendEvents(conn, snapshot, session.appliedEvents())
.map { Triple(snapshot, session, it) }
}.compose { triple ->
val (_, _, appendedEvents) = triple
log.debug("Events appended {}", appendedEvents)
if (options.eventProjector != null) {
projectEvents(conn, appendedEvents, options.eventProjector)
.onSuccess {
log.debug("Events projected")
}.map { triple }
} else {
log.debug("EventProjector is null, skipping projecting events")
succeededFuture(triple)
}
}.compose {
val (_, _, appendedEvents) = it
val cmdAsJson = serDer.commandToJson(command)
if (options.persistCommands) {
appendCommand(conn, cmdAsJson, stateId,
appendedEvents.first().metadata.causationId,
appendedEvents.last().metadata.causationId)
.map { Pair(appendedEvents, cmdAsJson) }
} else {
succeededFuture(Pair(appendedEvents, cmdAsJson))
}
}.compose {
log.debug("Command was appended")
val (appendedEvents, cmdAsJson) = it
if (options.eventBusTopic != null) {
val message = JsonObject()
.put("stateType", streamName)
.put("stateId", stateId.toString())
.put("command", cmdAsJson)
.put("events", JsonArray(appendedEvents.map { e -> e.toJsonObject() }))
.put("timestamp", Instant.now())
crabzillaContext.vertx().eventBus().publish(options.eventBusTopic, message)
log.debug("Published to topic ${options.eventBusTopic} the message ${message.encodePrettily()}")
}
succeededFuture(appendedEvents.last().metadata)
}.onSuccess {
val query = "NOTIFY $POSTGRES_NOTIFICATION_CHANNEL, '$streamName'"
crabzillaContext.pgPool().preparedQuery(query).execute()
.onSuccess { log.debug("Notified postgres: $query") }
log.debug("Transaction committed")
}.onFailure {
log.debug("Transaction aborted {}", it.message)
}
}
private fun getSnapshot(conn: SqlConnection, id: UUID): Future<Snapshot<S>?> {
val promise = Promise.promise<Snapshot<S>?>()
return conn
.prepare(GET_EVENTS_BY_ID)
.compose { pq: PreparedStatement ->
var state: S? = null
var latestVersion = 0
var lastCausationId: UUID? = null
var lastCorrelationId: UUID? = null
var error: Throwable? = null
// Fetch 1000 rows at a time
val stream: RowStream<Row> = pq.createStream(options.eventStreamSize, Tuple.of(id))
// Use the stream
stream.handler { row: Row ->
latestVersion = row.getInteger("version")
lastCausationId = row.getUUID("id")
lastCorrelationId = row.getUUID("correlation_id")
log.debug("Found event version {}, causationId {}, correlationId {}",
latestVersion, lastCausationId, lastCorrelationId)
state = commandServiceConfig.eventHandler
.handle(state, serDer.eventFromJson(JsonObject(row.getValue("event_payload").toString())))
log.debug("State {}", state)
}
stream.exceptionHandler { error = it }
stream.endHandler {
stream.close()
log.debug("End of stream")
if (error != null) {
promise.fail(error)
} else {
if (latestVersion == 0) {
promise.complete(null)
} else {
promise.complete(Snapshot(state!!, latestVersion, lastCausationId!!, lastCorrelationId!!))
}
}
}
promise.future()
}
}
}
| crabzilla-stack/src/main/kotlin/io/github/crabzilla/stack/command/internal/DefaultCommandServiceApi.kt | 1825682106 |
package org.andstatus.app.view
import android.content.Context
import android.provider.BaseColumns
import android.view.View
import android.view.ViewGroup
import android.widget.SimpleAdapter
import org.andstatus.app.context.MyPreferences
class MySimpleAdapter(context: Context, data: MutableList<out MutableMap<String, *>>, resource: Int,
from: Array<String?>?, to: IntArray?, val hasActionOnClick: Boolean) : SimpleAdapter(context, data, resource, from, to), View.OnClickListener {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
val view = super.getView(position, convertView, parent)
if (!hasActionOnClick) {
view.setOnClickListener(this)
}
return view
}
override fun getItemId(position: Int): Long {
val item = getItem(position) as MutableMap<String, *>
return try {
val id = item[BaseColumns._ID] as String?
id?.toLong() ?: 0
} catch (e: NumberFormatException) {
throw NumberFormatException(e.message + " caused by wrong item: " + item)
}
}
fun getPositionById(itemId: Long): Int {
if (itemId != 0L) {
for (position in 0 until count) {
if (getItemId(position) == itemId) {
return position
}
}
}
return -1
}
override fun onClick(v: View) {
if (!MyPreferences.isLongPressToOpenContextMenu() && v.getParent() != null) {
v.showContextMenu()
}
}
}
| app/src/main/kotlin/org/andstatus/app/view/MySimpleAdapter.kt | 3324357915 |
package io.github.crabzilla.example1.customer
import io.github.crabzilla.core.CommandHandler
import io.github.crabzilla.core.CommandSession
import io.github.crabzilla.core.EventHandler
import io.github.crabzilla.example1.customer.CustomerCommand.*
import io.github.crabzilla.example1.customer.CustomerEvent.*
import java.util.*
sealed interface CustomerEvent {
data class CustomerRegistered(val id: UUID) : CustomerEvent
data class CustomerRegisteredPrivate(val name: String) : CustomerEvent
data class CustomerActivated(val reason: String) : CustomerEvent
data class CustomerDeactivated(val reason: String) : CustomerEvent
}
sealed interface CustomerCommand {
data class RegisterCustomer(val customerId: UUID, val name: String) : CustomerCommand
data class ActivateCustomer(val reason: String) : CustomerCommand
data class DeactivateCustomer(val reason: String) : CustomerCommand
data class RegisterAndActivateCustomer(
val customerId: UUID,
val name: String,
val reason: String
) : CustomerCommand
}
data class Customer(val id: UUID, val name: String? = null, val isActive: Boolean = false, val reason: String? = null) {
companion object {
fun create(id: UUID, name: String): List<CustomerEvent> {
return listOf(CustomerRegistered(id = id), CustomerRegisteredPrivate(name))
}
fun fromEvent(event: CustomerRegistered): Customer {
return Customer(id = event.id, isActive = false)
}
}
fun activate(reason: String): List<CustomerEvent> {
return listOf(CustomerActivated(reason))
}
fun deactivate(reason: String): List<CustomerEvent> {
return listOf(CustomerDeactivated(reason))
}
}
val customerEventHandler = EventHandler<Customer, CustomerEvent> { state, event ->
when (event) {
is CustomerRegistered -> Customer.fromEvent(event)
is CustomerRegisteredPrivate -> state!!.copy(name = event.name)
is CustomerActivated -> state!!.copy(isActive = true, reason = event.reason)
is CustomerDeactivated -> state!!.copy(isActive = false, reason = event.reason)
}
}
class CustomerAlreadyExists(val id: UUID) : IllegalStateException("Customer $id already exists")
class CustomerCommandHandler : CommandHandler<Customer, CustomerCommand, CustomerEvent>(customerEventHandler) {
override fun handle(command: CustomerCommand, state: Customer?): CommandSession<Customer, CustomerEvent> {
return when (command) {
is RegisterCustomer -> {
if (state != null) throw CustomerAlreadyExists(command.customerId)
withNew(Customer.create(command.customerId, command.name))
}
is RegisterAndActivateCustomer -> {
if (state != null) throw CustomerAlreadyExists(command.customerId)
withNew(Customer.create(command.customerId, command.name))
.execute { it.activate(command.reason) }
}
is ActivateCustomer -> {
if (command.reason == "because I want it")
throw IllegalArgumentException("Reason cannot be = [${command.reason}], please be polite.")
with(state)
.execute { it.activate(command.reason) }
}
is DeactivateCustomer -> {
with(state)
.execute { it.deactivate(command.reason) }
}
}
}
}
| crabzilla-stack/src/test/kotlin/io/github/crabzilla/example1/customer/customerDomain.kt | 2248173157 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import javax.swing.Icon
object MixinModuleType : AbstractModuleType<MixinModule>("org.spongepowered", "mixin") {
const val ID = "MIXIN_MODULE_TYPE"
override val platformType = PlatformType.MIXIN
override val icon: Icon? = null
override val id = ID
override val ignoredAnnotations = emptyList<String>()
override val listenerAnnotations = emptyList<String>()
override val hasIcon = false
override fun generateModule(facet: MinecraftFacet) = MixinModule(facet)
}
| src/main/kotlin/platform/mixin/MixinModuleType.kt | 1581189020 |
package br.com.stickyindex.sample.common.di.main
import android.arch.lifecycle.Lifecycle
import br.com.stickyindex.sample.domain.Router
import br.com.stickyindex.sample.presentation.presenter.MainPresenter
import br.com.stickyindex.sample.presentation.view.MainView
import dagger.Module
import dagger.Provides
/**
* Created by edgarsf on 18/03/2018.
*/
@Module
class MainViewModule {
@Provides
fun providesLifecycle(mainView: MainView): Lifecycle = mainView.lifecycle
@Provides
fun providesRouter(mainView: MainView): Router = Router(mainView)
@Provides
fun providesPresenter(
mainView: MainView,
lifecycle: Lifecycle,
router: Router
): MainPresenter = MainPresenter(lifecycle, mainView, router)
} | demo/src/main/java/br/com/stickyindex/sample/common/di/main/MainViewModule.kt | 2081081636 |
package org.andstatus.app.account
import android.content.Intent
import org.andstatus.app.context.DemoData
class AccountSettingsActivityTest2() : AccountSettingsActivityTest() {
override val accountAction: String = Intent.ACTION_EDIT
override val accountNameString: String = DemoData.demoData.activityPubTestAccountName
}
| app/src/androidTest/kotlin/org/andstatus/app/account/AccountSettingsActivityTest2.kt | 1381348597 |
package com.mycollab.module.project.dao
import com.mycollab.module.project.domain.RolePermissionVal
import org.apache.ibatis.annotations.Param
/**
* @author MyCollab Ltd
* @since 7.0.0
*/
interface ProjectRolePermissionMapperExt {
fun findProjectsPermissions(@Param("username") username: String?,
@Param("projectIds") projectIds: List<Int>?,
@Param("sAccountId") sAccountId: Int): List<RolePermissionVal>
fun findProjectPermission(@Param("username") username: String?,
@Param("projectId") projectId: Int,
@Param("sAccountId") sAccountId: Int): RolePermissionVal
} | mycollab-services/src/main/java/com/mycollab/module/project/dao/ProjectRolePermissionMapperExt.kt | 3661063992 |
/*
* Copyright 2018 Kislitsyn Ilya
*
* 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.github.snt.dao.config
import org.springframework.boot.context.properties.ConfigurationProperties
/**
* DAO configuration.
*/
@ConfigurationProperties(prefix = "snt.dao")
class SntDaoConfig {
var ds = DS()
class DS {
lateinit var driverClass: String
lateinit var url: String
lateinit var user: String
lateinit var password: String
var cachePrepStmts = false
var prepStmtCacheSize = 250
var prepStmtCacheSqlLimit = 2048
}
} | snt-dao-starter/src/main/kotlin/org/github/snt/dao/config/SntDaoConfig.kt | 2116940379 |
package me.nickellis.towers.sample.data
import java.util.*
data class Tree(
val name: String
) {
val id: String = UUID.randomUUID().toString()
} | app/src/main/java/me/nickellis/towers/sample/data/Tree.kt | 745334258 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// 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.wfanet.panelmatch.client.eventpreprocessing
import com.google.protobuf.ByteString
/**
* Takes in a cryptokey as ByteString and outputs the same ByteString
*
* Security concerns this introduces:
*
* The crypto key could get logged. If logs are visible to engineers, this could be vulnerable to
* insider risk.
*
* The crypto key will reside in memory for longer. Other processes on the machines executing the
* Apache Beam could potentially compromise it.
*
* The crypto key will be serialized and sent between Apache Beam workers. This means that
* vulnerable temporary files or network connections could leak key material.
*/
class HardCodedDeterministicCommutativeCipherKeyProvider(private val cryptoKey: ByteString) :
DeterministicCommutativeCipherKeyProvider {
override fun get(): ByteString = cryptoKey
}
| src/main/kotlin/org/wfanet/panelmatch/client/eventpreprocessing/HardCodedDeterministicCommutativeCipherKeyProvider.kt | 4241923557 |
/*
* Copyright 2016 Jake Wharton
*
* 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 reagent.operator
class ObservableConcatMapTest {
// TODO overload resolution doesn't work here
// @Test fun concatMapObservable() = runTest {
// val concatMapItems = mutableListOf<String>()
// var observableCalled = 0
//
// observableOf("Task", "Two")
// .concatMap {
// concatMapItems.add(it)
// observableReturning { ++observableCalled }
// }
// .testObservable {
// item(1)
// item(2)
// complete()
// }
// }
//
// @Test fun concatMapObservableEmpty() = runTest {
// emptyActualObservable<String>()
// .concatMap { failObservable<String>() }
// .testObservable {
// complete()
// }
// }
//
// @Test fun concatMapObservableError() = runTest {
// val exception = RuntimeException("Oops!")
// exception.toActualObservable<String>()
// .concatMap { failObservable<String>() }
// .testObservable {
// error(exception)
// }
// }
//
// @Test fun concatMapOne() = runTest {
// val concatMapItems = mutableListOf<String>()
// var oneCalled = 0
//
// observableOf("Task", "Two")
// .concatMap {
// concatMapItems.add(it)
// observableReturning { ++oneCalled }
// }
// .testObservable {
// item(1)
// item(2)
// complete()
// }
//
// assertEquals(listOf("Task", "Two"), concatMapItems)
// assertEquals(2, oneCalled)
// }
//
// @Test fun concatMapOneEmpty() = runTest {
// emptyActualObservable<String>()
// .concatMap { failOne<String>() }
// .testObservable {
// complete()
// }
// }
//
// @Test fun concatMapOneError() = runTest {
// val exception = RuntimeException("Oops!")
// exception.toActualObservable<String>()
// .concatMap { failOne<String>() }
// .testObservable {
// error(exception)
// }
// }
}
| reagent/common/src/test/kotlin/reagent/operator/ObservableConcatMapTest.kt | 1845475593 |
package com.junnanhao.next.data
import android.app.Application
import android.support.v4.media.MediaMetadataCompat
import com.github.ajalt.timberkt.wtf
import com.junnanhao.next.App
import com.junnanhao.next.BuildConfig
import com.junnanhao.next.data.model.Song
import com.junnanhao.next.data.model.remote.TrackResponse
import io.objectbox.Box
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Created by jonashao on 2017/9/11.
* Music Provider Source implemented by ObjectBox
*/
class ObjectBoxMusicSource(application: Application) : MusicProviderSource {
private val source: SongsDataSource = SongsRepository(application)
private val retrofit: Retrofit
private val service: LastFmService
private val songBox: Box<Song> = (application as App).boxStore.boxFor(Song::class.java)
init {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
}).build()
retrofit = Retrofit.Builder()
.baseUrl("http://ws.audioscrobbler.com/2.0/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
.build()
service = retrofit.create<LastFmService>(LastFmService::class.java)
}
override fun iterator(): Iterator<MediaMetadataCompat> {
if (!source.isInitialized()) {
source.scanMusic().subscribe()
}
return source.getSongs()
.map { song ->
if (song.art == null && song.mbid == null) {
service.getTrack2(BuildConfig.LAST_FM_API_KEY, song.artist, song.title)
.enqueue(object : Callback<TrackResponse> {
override fun onFailure(call: Call<TrackResponse>?, t: Throwable?) {
wtf { "t :${t?.message}" }
}
override fun onResponse(call: Call<TrackResponse>?, response: Response<TrackResponse>?) {
val track = response?.body()?.track
if (track != null) {
song.mbid = track.mbid
song.art = track.album?.image?.
getOrNull(track.album.image.size - 1)?.url
songBox.put(song)
}
}
})
}
val uri = if (song.art?.startsWith("/storage") == true)
"file://${song.art}" else song.art
return@map MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, song.resId.toString())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, song.album)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, song.artist)
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, song.duration.toLong())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, uri)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, song.title)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, song.path)
.putString(MusicProviderSource.CUSTOM_METADATA_MBID, song.mbid)
.build()
}.iterator()
}
} | app/src/main/java/com/junnanhao/next/data/ObjectBoxMusicSource.kt | 647908742 |
// Copyright 2014 The Bazel Authors. 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.
// Copied from bazel core and there is some code in other branches which will use the some of the unused elements. Fix
// this later on.
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package io.bazel.kotlin.builder.utils.jars
import java.io.FileNotFoundException
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.Calendar
import java.util.GregorianCalendar
import java.util.HashSet
import java.util.jar.Attributes
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.CRC32
/**
* A simple helper class for creating Jar files. All Jar entries are sorted alphabetically. Allows
* normalization of Jar entries by setting the timestamp of non-.class files to the DOS epoch.
* Timestamps of .class files are set to the DOS epoch + 2 seconds (The zip timestamp granularity)
* Adjusting the timestamp for .class files is necessary since otherwise javac will recompile java
* files if both the java file and its .class file are present.
*/
open class JarHelper internal constructor(
// The path to the Jar we want to create
protected val jarPath: Path,
// The properties to describe how to create the Jar
protected val normalize: Boolean = true,
protected val verbose: Boolean = false,
compression: Boolean = true,
) {
private var storageMethod: Int = JarEntry.DEFLATED
// The state needed to create the Jar
private val names: MutableSet<String> = HashSet()
init {
setCompression(compression)
}
/**
* Enables or disables compression for the Jar file entries.
*
* @param compression if true enables compressions for the Jar file entries.
*/
private fun setCompression(compression: Boolean) {
storageMethod = if (compression) JarEntry.DEFLATED else JarEntry.STORED
}
/**
* Returns the normalized timestamp for a jar entry based on its name. This is necessary since
* javac will, when loading a class X, prefer a source file to a class file, if both files have
* the same timestamp. Therefore, we need to adjust the timestamp for class files to slightly
* after the normalized time.
*
* @param name The name of the file for which we should return the normalized timestamp.
* @return the time for a new Jar file entry in milliseconds since the epoch.
*/
private fun normalizedTimestamp(name: String): Long {
return if (name.endsWith(".class")) {
DEFAULT_TIMESTAMP + MINIMUM_TIMESTAMP_INCREMENT
} else {
DEFAULT_TIMESTAMP
}
}
/**
* Returns the time for a new Jar file entry in milliseconds since the epoch. Uses JarCreator.DEFAULT_TIMESTAMP]
* for normalized entries, [System.currentTimeMillis] otherwise.
*
* @param filename The name of the file for which we are entering the time
* @return the time for a new Jar file entry in milliseconds since the epoch.
*/
private fun newEntryTimeMillis(filename: String): Long {
return if (normalize) normalizedTimestamp(filename) else System.currentTimeMillis()
}
/**
* Writes an entry with specific contents to the jar. Directory entries must include the trailing
* '/'.
*/
@Throws(IOException::class)
private fun writeEntry(out: JarOutputStream, name: String, content: ByteArray) {
if (names.add(name)) {
// Create a new entry
val entry = JarEntry(name)
entry.time = newEntryTimeMillis(name)
val size = content.size
entry.size = size.toLong()
if (size == 0) {
entry.method = JarEntry.STORED
entry.crc = 0
out.putNextEntry(entry)
} else {
entry.method = storageMethod
if (storageMethod == JarEntry.STORED) {
val crc = CRC32()
crc.update(content)
entry.crc = crc.value
}
out.putNextEntry(entry)
out.write(content)
}
out.closeEntry()
}
}
/**
* Writes a standard Java manifest entry into the JarOutputStream. This includes the directory
* entry for the "META-INF" directory
*
* @param content the Manifest content to write to the manifest entry.
* @throws IOException
*/
@Throws(IOException::class)
protected fun writeManifestEntry(out: JarOutputStream, content: ByteArray) {
val oldStorageMethod = storageMethod
// Do not compress small manifest files, the compressed one is frequently
// larger than the original. The threshold of 256 bytes is somewhat arbitrary.
if (content.size < 256) {
storageMethod = JarEntry.STORED
}
try {
writeEntry(out, MANIFEST_DIR, byteArrayOf())
writeEntry(out, MANIFEST_NAME, content)
} finally {
storageMethod = oldStorageMethod
}
}
/**
* Copies file or directory entries from the file system into the jar. Directory entries will be
* detected and their names automatically '/' suffixed.
*/
@Throws(IOException::class)
protected fun JarOutputStream.copyEntry(name: String, path: Path) {
var normalizedName = name
if (!names.contains(normalizedName)) {
if (!Files.exists(path)) {
throw FileNotFoundException("${path.toAbsolutePath()} (No such file or directory)")
}
val isDirectory = Files.isDirectory(path)
if (isDirectory && !normalizedName.endsWith("/")) {
normalizedName = "$normalizedName/" // always normalize directory names before checking set
}
if (names.add(normalizedName)) {
if (verbose) {
System.err.println("adding $path")
}
// Create a new entry
val size = if (isDirectory) 0 else Files.size(path)
val outEntry = JarEntry(normalizedName)
val newtime =
if (normalize) {
normalizedTimestamp(normalizedName)
} else {
Files.getLastModifiedTime(path)
.toMillis()
}
outEntry.time = newtime
outEntry.size = size
if (size == 0L) {
outEntry.method = JarEntry.STORED
outEntry.crc = 0
putNextEntry(outEntry)
} else {
outEntry.method = storageMethod
if (storageMethod == JarEntry.STORED) {
// ZipFile requires us to calculate the CRC-32 for any STORED entry.
// It would be nicer to do this via DigestInputStream, but
// the architecture of ZipOutputStream requires us to know the CRC-32
// before we write the data to the stream.
val bytes = Files.readAllBytes(path)
val crc = CRC32()
crc.update(bytes)
outEntry.crc = crc.value
putNextEntry(outEntry)
write(bytes)
} else {
putNextEntry(outEntry)
Files.copy(path, this)
}
}
closeEntry()
}
}
}
/**
* Copies a a single entry into the jar. This variant differs from the other [copyEntry] in two ways. Firstly the
* jar contents are already loaded in memory and Secondly the [name] and [path] entries don't necessarily have a
* correspondence.
*
* @param path the path used to retrieve the timestamp in case normalize is disabled.
* @param data if this is empty array then the entry is a directory.
*/
protected fun JarOutputStream.copyEntry(
name: String,
path: Path? = null,
data: ByteArray = EMPTY_BYTEARRAY,
) {
val outEntry = JarEntry(name)
outEntry.time = when {
normalize -> normalizedTimestamp(name)
else -> Files.getLastModifiedTime(checkNotNull(path)).toMillis()
}
outEntry.size = data.size.toLong()
if (data.isEmpty()) {
outEntry.method = JarEntry.STORED
outEntry.crc = 0
putNextEntry(outEntry)
} else {
outEntry.method = storageMethod
if (storageMethod == JarEntry.STORED) {
val crc = CRC32()
crc.update(data)
outEntry.crc = crc.value
putNextEntry(outEntry)
write(data)
} else {
putNextEntry(outEntry)
write(data)
}
}
closeEntry()
}
companion object {
const val MANIFEST_DIR = "META-INF/"
const val MANIFEST_NAME = JarFile.MANIFEST_NAME
const val SERVICES_DIR = "META-INF/services/"
internal val EMPTY_BYTEARRAY = ByteArray(0)
// Normalized timestamp for zip entries
// We do not include the system's default timezone and locale and additionally avoid the unix epoch
// to ensure Java's zip implementation does not add the System's timezone into the extra field of the zip entry
val DEFAULT_TIMESTAMP = GregorianCalendar(1980, Calendar.FEBRUARY, 1, 0, 0, 0).getTimeInMillis()
// These attributes are used by JavaBuilder, Turbine, and ijar.
// They must all be kept in sync.
val TARGET_LABEL = Attributes.Name("Target-Label")
val INJECTING_RULE_KIND = Attributes.Name("Injecting-Rule-Kind")
// ZIP timestamps have a resolution of 2 seconds.
// see http://www.info-zip.org/FAQ.html#limits
const val MINIMUM_TIMESTAMP_INCREMENT = 2000L
}
}
| src/main/kotlin/io/bazel/kotlin/builder/utils/jars/JarHelper.kt | 15394148 |
package eu.kanade.tachiyomi.extension.all.manhwa18net
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.multisrc.fmreader.FMReader
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
import eu.kanade.tachiyomi.source.model.FilterList
import okhttp3.Request
class Manhwa18NetFactory : SourceFactory {
override fun createSources(): List<Source> = listOf(
Manhwa18Net(),
Manhwa18NetRaw(),
)
}
@Nsfw
class Manhwa18Net : FMReader("Manhwa18.net", "https://manhwa18.net", "en") {
override fun popularMangaRequest(page: Int): Request =
GET("$baseUrl/$requestPath?listType=pagination&page=$page&sort=views&sort_type=DESC&ungenre=raw", headers)
override fun latestUpdatesRequest(page: Int): Request =
GET("$baseUrl/$requestPath?listType=pagination&page=$page&sort=last_update&sort_type=DESC&ungenre=raw", headers)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val noRawsUrl = super.searchMangaRequest(page, query, filters).url.newBuilder().addQueryParameter("ungenre", "raw").toString()
return GET(noRawsUrl, headers)
}
override fun getGenreList() = getAdultGenreList()
}
@Nsfw
class Manhwa18NetRaw : FMReader("Manhwa18.net", "https://manhwa18.net", "ko") {
override val requestPath = "manga-list-genre-raw.html"
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val onlyRawsUrl = super.searchMangaRequest(page, query, filters).url.newBuilder().addQueryParameter("genre", "raw").toString()
return GET(onlyRawsUrl, headers)
}
override fun getFilterList() = FilterList(super.getFilterList().filterNot { it == GenreList(getGenreList()) })
}
| multisrc/overrides/fmreader/manhwa18net/src/Manhwa18NetFactory.kt | 3887210898 |
package eu.kanade.tachiyomi.extension.all.leviatanscans
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceFactory
import eu.kanade.tachiyomi.source.model.SChapter
import okhttp3.Response
class LeviatanScansFactory : SourceFactory {
override fun createSources(): List<Source> = listOf(
LeviatanScansEN(),
LeviatanScansES(),
)
}
class LeviatanScansEN : Madara("Leviatan Scans", "https://leviatanscans.com", "en") {
override fun chapterListParse(response: Response): List<SChapter> = super.chapterListParse(response).sortedBy { it.name.toInt() }.reversed()
}
class LeviatanScansES : Madara("Leviatan Scans", "https://es.leviatanscans.com", "es")
| multisrc/overrides/madara/leviatanscans/src/LeviatanScansFactory.kt | 1263000968 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.statements
import com.felipebz.flr.tests.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.RuleTest
class DeleteStatementTest : RuleTest() {
@BeforeEach
fun init() {
setRootRule(PlSqlGrammar.DELETE_STATEMENT)
}
@Test
fun matchesSimpleDelete() {
assertThat(p).matches("delete tab;")
}
@Test
fun matchesDeleteFrom() {
assertThat(p).matches("delete from tab;")
}
@Test
fun matchesDeleteWithWhere() {
assertThat(p).matches("delete from tab where x = 1;")
}
@Test
fun matchesDeleteWithAlias() {
assertThat(p).matches("delete tab t;")
}
@Test
fun matchesDeleteWithSchema() {
assertThat(p).matches("delete sch.tab;")
}
@Test
fun matchesDeleteCurrentOf() {
assertThat(p).matches("delete tab where current of cur;")
}
@Test
fun matchesLabeledDelete() {
assertThat(p).matches("<<foo>> delete tab;")
}
@Test
fun matchesDeleteFromQuery() {
assertThat(p).matches("delete (select * from dual);")
}
@Test
fun matchesDeleteWithReturningInto() {
assertThat(p).matches("delete from tab returning x bulk collect into y;")
}
}
| zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/statements/DeleteStatementTest.kt | 1686227300 |
package leetcode
/**
* https://leetcode.com/problems/maximum-split-of-positive-even-integers/
*/
class Problem2178 {
fun maximumEvenSplit(finalSum: Long): List<Long> {
val answer = mutableListOf<Long>()
if (finalSum % 2L != 0L) {
return answer
}
var n = finalSum
var m = 2L
while (true) {
if (n - m <= m) {
answer += n
break
}
n -= m
answer += m
m += 2
}
return answer
}
}
| src/main/kotlin/leetcode/Problem2178.kt | 603263864 |
package de.gesellix.docker.compose.types
import com.squareup.moshi.Json
data class RestartPolicy(
var condition: String? = null,
// Duration Delay
var delay: String? = null,
@Json(name = "max_attempts")
var maxAttempts: Int? = null,
// Duration Window
var window: String? = null
)
| src/main/kotlin/de/gesellix/docker/compose/types/RestartPolicy.kt | 3616101830 |
package com.tbuonomo.dotsindicatorsample.viewpager2
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.tbuonomo.dotsindicatorsample.R
class DotIndicatorPager2Adapter : RecyclerView.Adapter<ViewHolder>() {
data class Card(val id: Int)
val items = mutableListOf<Card>().apply {
repeat(10) { add(Card(it)) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return object : ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.material_page, parent, false)
) {}
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Empty
}
}
| viewpagerdotsindicator-sample/src/main/kotlin/com/tbuonomo/dotsindicatorsample/viewpager2/DotIndicatorPager2Adapter.kt | 2074916843 |
package org.stepik.android.data.course_revenue.repository
import io.reactivex.Single
import org.stepik.android.data.course_revenue.source.CourseBeneficiariesRemoteDataSource
import org.stepik.android.domain.course_revenue.model.CourseBeneficiary
import org.stepik.android.domain.course_revenue.repository.CourseBeneficiariesRepository
import javax.inject.Inject
class CourseBeneficiariesRepositoryImpl
@Inject
constructor(
private val courseBeneficiariesRemoteDataSource: CourseBeneficiariesRemoteDataSource
) : CourseBeneficiariesRepository {
override fun getCourseBeneficiary(courseId: Long, userId: Long): Single<CourseBeneficiary> =
courseBeneficiariesRemoteDataSource.getCourseBeneficiary(courseId, userId)
} | app/src/main/java/org/stepik/android/data/course_revenue/repository/CourseBeneficiariesRepositoryImpl.kt | 4000026321 |
package org.stepik.android.view.injection.view_assignment
import javax.inject.Qualifier
@Qualifier
annotation class ViewAssignmentBus | app/src/main/java/org/stepik/android/view/injection/view_assignment/ViewAssignmentBus.kt | 2357819447 |
package info.hzvtc.hipixiv
import android.app.Application
import android.content.Context
import com.facebook.cache.disk.DiskCacheConfig
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory
import info.hzvtc.hipixiv.inject.component.ApplicationComponent
import info.hzvtc.hipixiv.inject.component.DaggerApplicationComponent
import info.hzvtc.hipixiv.inject.module.ApplicationModule
import info.hzvtc.hipixiv.net.interceptor.ImageInterceptor
import info.hzvtc.hipixiv.net.interceptor.LoggingInterceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
class App : Application() {
private val mAppComponent : ApplicationComponent by lazy {
DaggerApplicationComponent.builder().applicationModule(ApplicationModule(this)).build()
}
override fun onCreate() {
super.onCreate()
mAppComponent.inject(this)
initFresco()
}
private fun initFresco(){
val client = OkHttpClient.Builder()
.addInterceptor(ImageInterceptor())
.addInterceptor(LoggingInterceptor())
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.build()
val cache = DiskCacheConfig.newBuilder(this)
.setMaxCacheSize(256 * 1024 * 1024)
.build()
val config = OkHttpImagePipelineConfigFactory
.newBuilder(this,client)
.setMainDiskCacheConfig(cache)
.build()
Fresco.initialize(this,config)
}
companion object {
fun getApp(context: Context) : App = context.applicationContext as App
}
}
| app/src/main/java/info/hzvtc/hipixiv/App.kt | 2869541222 |
package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.BowType
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.isWater
import nl.sugcube.dirtyarrows.util.showGrowthParticle
import org.bukkit.Material
import org.bukkit.TreeType
import org.bukkit.entity.Arrow
import org.bukkit.entity.Player
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.inventory.ItemStack
import kotlin.random.Random
/**
* Shoots arrows that summons a tree on impact.
*
* @author SugarCaney
*/
open class TreeBow(plugin: DirtyArrows, val tree: Tree) : BowAbility(
plugin = plugin,
type = tree.bowType,
canShootInProtectedRegions = false,
protectionRange = 8.0,
costRequirements = tree.requiredItems,
description = "Spawns ${tree.treeName}."
) {
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
// Try a random tree type.
val variant = if (arrow.location.block.isWater()) TreeType.SWAMP else tree.randomTreeType()
if (arrow.world.generateTree(arrow.location, variant)) {
arrow.location.showGrowthParticle()
return
}
// Try a block lower.
if (arrow.world.generateTree(arrow.location.clone().add(0.0, -1.0, 0.0), variant)) {
arrow.location.showGrowthParticle()
return
}
// If it didn't work, fallback on the default.
if (arrow.world.generateTree(arrow.location, tree.defaultType)) {
arrow.location.showGrowthParticle()
return
}
// Try a block lower.
if (arrow.world.generateTree(arrow.location.clone().add(0.0, -1.0, 0.0), tree.defaultType)) {
arrow.location.showGrowthParticle()
return
}
// If that didn't work, reimburse items.
player.reimburseBowItems()
}
/**
* @author SugarCaney
*/
enum class Tree(
/**
* Bow type that generates this tree.
*/
val bowType: BowType,
/**
* The 'normal' variant of the tree.
*/
val defaultType: TreeType,
/**
* The log material.
*/
val material: Material,
/**
* The damage value of the log material (for items).
*/
val damageValue: Short,
/**
* The amount of saplings required to spawn the default tree.
*/
val saplingCount: Int,
/**
* Contains a map of each tree type supported by this kind of tree.
* Maps to the frequency of how many times it should generate.
*/
val treeTypes: Map<TreeType, Int>,
/**
* The name of the tree w/ article.
*/
val treeName: String
) {
OAK(DefaultBow.OAK, TreeType.TREE, Material.OAK_LOG, 0, 1, mapOf(
TreeType.TREE to 7,
TreeType.BIG_TREE to 1,
TreeType.SWAMP to 1
), "an oak"),
SPRUCE(DefaultBow.SPRUCE, TreeType.REDWOOD, Material.SPRUCE_LOG, 0, 1, mapOf(
TreeType.REDWOOD to 7,
TreeType.TALL_REDWOOD to 3,
TreeType.MEGA_REDWOOD to 1
), "a spruce tree"),
BIRCH(DefaultBow.BIRCH, TreeType.BIRCH, Material.BIRCH_LOG, 0, 1, mapOf(
TreeType.BIRCH to 3,
TreeType.TALL_BIRCH to 1
), "a birch"),
JUNGLE(DefaultBow.JUNGLE, TreeType.JUNGLE, Material.JUNGLE_LOG, 0, 1, mapOf(
TreeType.JUNGLE to 1,
TreeType.SMALL_JUNGLE to 7,
TreeType.JUNGLE_BUSH to 3
), "a jungle tree"),
ACACIA(DefaultBow.ACACIA, TreeType.ACACIA, Material.ACACIA_LOG, 0, 1, mapOf(
TreeType.ACACIA to 1
), "an acacia tree"),
DARK_OAK(DefaultBow.DARK_OAK, TreeType.DARK_OAK, Material.DARK_OAK_LOG, 0, 4, mapOf(
TreeType.DARK_OAK to 1
), "a dark oak");
/**
* The items required to use a bow of this tree type.
*/
val requiredItems = listOf(
// ItemStack(Material.SAPLING, saplingCount, (damageValue + if (material == Material.LOG_2) 4 else 0).toShort()),
ItemStack(Material.BONE_MEAL, 1)
// TODO: Tree Bow required materials
)
/**
* Get a random TreeType for this tree.
*/
fun randomTreeType(): TreeType {
var total = treeTypes.values.sum()
treeTypes.forEach { (type, frequency) ->
if (Random.nextInt(total) < frequency) return type
total -= frequency
}
error("Problem in algorthm (total: '$total')")
}
}
} | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/TreeBow.kt | 197793251 |
package eu.kanade.tachiyomi.util.chapter
import eu.kanade.domain.chapter.model.Chapter
import eu.kanade.domain.manga.model.Manga
fun getChapterSort(manga: Manga, sortDescending: Boolean = manga.sortDescending()): (Chapter, Chapter) -> Int {
return when (manga.sorting) {
Manga.CHAPTER_SORTING_SOURCE -> when (sortDescending) {
true -> { c1, c2 -> c1.sourceOrder.compareTo(c2.sourceOrder) }
false -> { c1, c2 -> c2.sourceOrder.compareTo(c1.sourceOrder) }
}
Manga.CHAPTER_SORTING_NUMBER -> when (sortDescending) {
true -> { c1, c2 -> c2.chapterNumber.compareTo(c1.chapterNumber) }
false -> { c1, c2 -> c1.chapterNumber.compareTo(c2.chapterNumber) }
}
Manga.CHAPTER_SORTING_UPLOAD_DATE -> when (sortDescending) {
true -> { c1, c2 -> c2.dateUpload.compareTo(c1.dateUpload) }
false -> { c1, c2 -> c1.dateUpload.compareTo(c2.dateUpload) }
}
else -> throw NotImplementedError("Invalid chapter sorting method: ${manga.sorting}")
}
}
| app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterSorter.kt | 3656425553 |
/*
* Copyright (C) 2018 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.google.android.filament.multiview
import android.animation.ValueAnimator
import android.app.Activity
import android.opengl.Matrix
import android.os.Bundle
import android.view.Choreographer
import android.view.Surface
import android.view.SurfaceView
import android.view.animation.LinearInterpolator
import com.google.android.filament.*
import com.google.android.filament.RenderableManager.*
import com.google.android.filament.VertexBuffer.*
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import java.util.*
class MainActivity : Activity() {
// Make sure to initialize Filament first
// This loads the JNI library needed by most API calls
companion object {
init {
Filament.init()
}
}
// The View we want to render into
private lateinit var surfaceView: SurfaceView
// UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture
private lateinit var uiHelper: UiHelper
// Choreographer is used to schedule new frames
private lateinit var choreographer: Choreographer
// Engine creates and destroys Filament resources
// Each engine must be accessed from a single thread of your choosing
// Resources cannot be shared across engines
private lateinit var engine: Engine
// A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.)
private lateinit var renderer: Renderer
// A scene holds all the renderable, lights, etc. to be drawn
private lateinit var scene: Scene
// A view defines a viewport, a scene and a camera for rendering
private lateinit var view0: View
private lateinit var view1: View
private lateinit var view2: View
private lateinit var view3: View
private lateinit var view4: View
// We need skybox to set the background color
private lateinit var skybox: Skybox
// Should be pretty obvious :)
private lateinit var camera: Camera
private lateinit var material: Material
private lateinit var materialInstance: MaterialInstance
private lateinit var vertexBuffer: VertexBuffer
private lateinit var indexBuffer: IndexBuffer
// Filament entity representing a renderable object
@Entity private var renderable = 0
@Entity private var light = 0
// A swap chain is Filament's representation of a surface
private var swapChain: SwapChain? = null
// Performs the rendering and schedules new frames
private val frameScheduler = FrameCallback()
private val animator = ValueAnimator.ofFloat(0.0f, 360.0f)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
surfaceView = SurfaceView(this)
setContentView(surfaceView)
choreographer = Choreographer.getInstance()
setupSurfaceView()
setupFilament()
setupViews()
setupScene()
}
private fun setupSurfaceView() {
uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
uiHelper.renderCallback = SurfaceCallback()
// NOTE: To choose a specific rendering resolution, add the following line:
// uiHelper.setDesiredSize(1280, 720)
uiHelper.attachTo(surfaceView)
}
private fun setupFilament() {
engine = Engine.create()
renderer = engine.createRenderer()
scene = engine.createScene()
view0 = engine.createView()
view1 = engine.createView()
view2 = engine.createView()
view3 = engine.createView()
view4 = engine.createView()
view0.setName("view0");
view1.setName("view1");
view2.setName("view2");
view3.setName("view3");
view4.setName("view4");
view4.blendMode = View.BlendMode.TRANSLUCENT;
skybox = Skybox.Builder().build(engine);
scene.skybox = skybox
camera = engine.createCamera(engine.entityManager.create())
}
private fun setupViews() {
view0.camera = camera
view1.camera = camera
view2.camera = camera
view3.camera = camera
view4.camera = camera
view0.scene = scene
view1.scene = scene
view2.scene = scene
view3.scene = scene
view4.scene = scene
}
private fun setupScene() {
loadMaterial()
setupMaterial()
createMesh()
// To create a renderable we first create a generic entity
renderable = EntityManager.get().create()
// We then create a renderable component on that entity
// A renderable is made of several primitives; in this case we declare only 1
// If we wanted each face of the cube to have a different material, we could
// declare 6 primitives (1 per face) and give each of them a different material
// instance, setup with different parameters
RenderableManager.Builder(1)
// Overall bounding box of the renderable
.boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f))
// Sets the mesh data of the first primitive, 6 faces of 6 indices each
.geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6)
// Sets the material of the first primitive
.material(0, materialInstance)
.build(engine, renderable)
// Add the entity to the scene to render it
scene.addEntity(renderable)
// We now need a light, let's create a directional light
light = EntityManager.get().create()
// Create a color from a temperature (5,500K)
val (r, g, b) = Colors.cct(5_500.0f)
LightManager.Builder(LightManager.Type.DIRECTIONAL)
.color(r, g, b)
// Intensity of the sun in lux on a clear day
.intensity(110_000.0f)
// The direction is normalized on our behalf
.direction(0.0f, -0.5f, -1.0f)
.castShadows(true)
.build(engine, light)
// Add the entity to the scene to light it
scene.addEntity(light)
// Set the exposure on the camera, this exposure follows the sunny f/16 rule
// Since we've defined a light that has the same intensity as the sun, it
// guarantees a proper exposure
camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f)
// Move the camera back to see the object
camera.lookAt(0.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
startAnimation()
}
private fun loadMaterial() {
readUncompressedAsset("materials/lit.filamat").let {
material = Material.Builder().payload(it, it.remaining()).build(engine)
}
}
private fun setupMaterial() {
// Create an instance of the material to set different parameters on it
materialInstance = material.createInstance()
// Specify that our color is in sRGB so the conversion to linear
// is done automatically for us. If you already have a linear color
// you can pass it directly, or use Colors.RgbType.LINEAR
materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f)
// The default value is always 0, but it doesn't hurt to be clear about our intentions
// Here we are defining a dielectric material
materialInstance.setParameter("metallic", 0.0f)
// We increase the roughness to spread the specular highlights
materialInstance.setParameter("roughness", 0.3f)
}
private fun createMesh() {
val floatSize = 4
val shortSize = 2
// A vertex is a position + a tangent frame:
// 3 floats for XYZ position, 4 floats for normal+tangents (quaternion)
val vertexSize = 3 * floatSize + 4 * floatSize
// Define a vertex and a function to put a vertex in a ByteBuffer
@Suppress("ArrayInDataClass")
data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray)
fun ByteBuffer.put(v: Vertex): ByteBuffer {
putFloat(v.x)
putFloat(v.y)
putFloat(v.z)
v.tangents.forEach { putFloat(it) }
return this
}
// 6 faces, 4 vertices per face
val vertexCount = 6 * 4
// Create tangent frames, one per face
val tfPX = FloatArray(4)
val tfNX = FloatArray(4)
val tfPY = FloatArray(4)
val tfNY = FloatArray(4)
val tfPZ = FloatArray(4)
val tfNZ = FloatArray(4)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX)
MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY)
MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY)
MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ)
MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ)
val vertexData = ByteBuffer.allocate(vertexCount * vertexSize)
// It is important to respect the native byte order
.order(ByteOrder.nativeOrder())
// Face -Z
.put(Vertex(-1.0f, -1.0f, -1.0f, tfNZ))
.put(Vertex(-1.0f, 1.0f, -1.0f, tfNZ))
.put(Vertex( 1.0f, 1.0f, -1.0f, tfNZ))
.put(Vertex( 1.0f, -1.0f, -1.0f, tfNZ))
// Face +X
.put(Vertex( 1.0f, -1.0f, -1.0f, tfPX))
.put(Vertex( 1.0f, 1.0f, -1.0f, tfPX))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPX))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfPX))
// Face +Z
.put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ))
// Face -X
.put(Vertex(-1.0f, -1.0f, 1.0f, tfNX))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfNX))
.put(Vertex(-1.0f, 1.0f, -1.0f, tfNX))
.put(Vertex(-1.0f, -1.0f, -1.0f, tfNX))
// Face -Y
.put(Vertex(-1.0f, -1.0f, 1.0f, tfNY))
.put(Vertex(-1.0f, -1.0f, -1.0f, tfNY))
.put(Vertex( 1.0f, -1.0f, -1.0f, tfNY))
.put(Vertex( 1.0f, -1.0f, 1.0f, tfNY))
// Face +Y
.put(Vertex(-1.0f, 1.0f, -1.0f, tfPY))
.put(Vertex(-1.0f, 1.0f, 1.0f, tfPY))
.put(Vertex( 1.0f, 1.0f, 1.0f, tfPY))
.put(Vertex( 1.0f, 1.0f, -1.0f, tfPY))
// Make sure the cursor is pointing in the right place in the byte buffer
.flip()
// Declare the layout of our mesh
vertexBuffer = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(vertexCount)
// Because we interleave position and color data we must specify offset and stride
// We could use de-interleaved data by declaring two buffers and giving each
// attribute a different buffer index
.attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
.attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize)
.build(engine)
// Feed the vertex data to the mesh
// We only set 1 buffer because the data is interleaved
vertexBuffer.setBufferAt(engine, 0, vertexData)
// Create the indices
val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize)
.order(ByteOrder.nativeOrder())
repeat(6) {
val i = (it * 4).toShort()
indexData
.putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort())
.putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort())
}
indexData.flip()
// 6 faces, 2 triangles per face,
indexBuffer = IndexBuffer.Builder()
.indexCount(vertexCount * 2)
.bufferType(IndexBuffer.Builder.IndexType.USHORT)
.build(engine)
indexBuffer.setBuffer(engine, indexData)
}
private fun startAnimation() {
// Animate the triangle
animator.interpolator = LinearInterpolator()
animator.duration = 6000
animator.repeatMode = ValueAnimator.RESTART
animator.repeatCount = ValueAnimator.INFINITE
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
val transformMatrix = FloatArray(16)
override fun onAnimationUpdate(a: ValueAnimator) {
Matrix.setRotateM(transformMatrix, 0, a.animatedValue as Float, 0.0f, 1.0f, 0.0f)
val tcm = engine.transformManager
tcm.setTransform(tcm.getInstance(renderable), transformMatrix)
}
})
animator.start()
}
override fun onResume() {
super.onResume()
choreographer.postFrameCallback(frameScheduler)
animator.start()
}
override fun onPause() {
super.onPause()
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
}
override fun onDestroy() {
super.onDestroy()
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel();
// Always detach the surface before destroying the engine
uiHelper.detach()
// Cleanup all resources
engine.destroyEntity(light)
engine.destroyEntity(renderable)
engine.destroyRenderer(renderer)
engine.destroyVertexBuffer(vertexBuffer)
engine.destroyIndexBuffer(indexBuffer)
engine.destroyMaterialInstance(materialInstance)
engine.destroyMaterial(material)
engine.destroyView(view0)
engine.destroyView(view1)
engine.destroyView(view2)
engine.destroyView(view3)
engine.destroyView(view4)
engine.destroySkybox(skybox)
engine.destroyScene(scene)
engine.destroyCameraComponent(camera.entity)
// Engine.destroyEntity() destroys Filament related resources only
// (components), not the entity itself
val entityManager = EntityManager.get()
entityManager.destroy(light)
entityManager.destroy(renderable)
entityManager.destroy(camera.entity)
// Destroying the engine will free up any resource you may have forgotten
// to destroy, but it's recommended to do the cleanup properly
engine.destroy()
}
inner class FrameCallback : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
// Schedule the next frame
choreographer.postFrameCallback(this)
// This check guarantees that we have a swap chain
if (uiHelper.isReadyToRender) {
// If beginFrame() returns false you should skip the frame
// This means you are sending frames too quickly to the GPU
if (renderer.beginFrame(swapChain!!, frameTimeNanos)) {
skybox.setColor(0.035f, 0.035f, 0.035f, 1.0f);
renderer.render(view0)
skybox.setColor(1.0f, 0.0f, 0.0f, 1.0f);
renderer.render(view1)
skybox.setColor(0.0f, 1.0f, 0.0f, 1.0f);
renderer.render(view2)
skybox.setColor(0.0f, 0.0f, 1.0f, 1.0f);
renderer.render(view3)
skybox.setColor(0.0f, 0.0f, 0.0f, 0.0f);
renderer.render(view4)
renderer.endFrame()
}
}
}
}
inner class SurfaceCallback : UiHelper.RendererCallback {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface)
renderer.setDisplayInfo(DisplayHelper.getDisplayInfo(surfaceView.display, Renderer.DisplayInfo()))
}
override fun onDetachedFromSurface() {
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
// destroySwapChain command, otherwise Android might destroy the Surface
// too early
engine.flushAndWait()
swapChain = null
}
}
override fun onResized(width: Int, height: Int) {
val aspect = width.toDouble() / height.toDouble()
camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL)
view0.viewport = Viewport(0, 0, width / 2, height / 2)
view1.viewport = Viewport(width / 2, 0, width / 2, height / 2)
view2.viewport = Viewport(0, height / 2, width / 2, height / 2)
view3.viewport = Viewport(width / 2, height / 2, width / 2, height / 2)
view4.viewport = Viewport(width / 4, height / 4, width / 2, height / 2)
}
}
private fun readUncompressedAsset(assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()
val dst = ByteBuffer.allocate(fd.length.toInt())
val src = Channels.newChannel(input)
src.read(dst)
src.close()
return dst.apply { rewind() }
}
}
}
| android/samples/sample-multi-view/src/main/java/com/google/android/filament/multiview/MainActivity.kt | 1676781184 |
package com.gkzxhn.mygithub.extension
import android.annotation.SuppressLint
import android.content.Context
import android.widget.Toast
/**
* Created by 方 on 2017/10/21.
*/
var toast :Toast? = null
@SuppressLint("ShowToast")
fun Context.toast(msg : String) {
if (toast == null) {
toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT)
}
toast!!.setText(msg)
toast!!.show()
} | app/src/main/java/com/gkzxhn/mygithub/extension/ContextExtensions.kt | 1335142634 |
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs
/**
* Created by andy on 21/05/2018.
*/
enum class RXFilterMode(val value: Byte) {
Wide(0x50),
Narrow(0x90.toByte());
} | rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RXFilterMode.kt | 1131755105 |
// Copyright 2022 The Cross-Media Measurement Authors
//
// 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.wfanet.virtualpeople.core.labeler
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.wfanet.virtualpeople.common.*
import org.wfanet.virtualpeople.common.BranchNodeKt.branch
import org.wfanet.virtualpeople.common.PopulationNodeKt.virtualPersonPool
private const val EVENT_ID_NUMBER = 10000
@RunWith(JUnit4::class)
class LabelerTest {
@Test
fun `build from root`() {
/**
* A model with
* - 40% probability to assign virtual person id 10
* - 60% probability to assign virtual person id 20
*/
val root = compiledNode {
name = "TestNode1"
branchNode = branchNode {
branches.add(
branch {
node = compiledNode {
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
chance = 0.4
}
)
branches.add(
branch {
node = compiledNode {
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
chance = 0.6
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val labeler = Labeler.build(root)
val vPidCounts = mutableMapOf<ULong, Int>()
(0 until EVENT_ID_NUMBER).forEach {
val input = labelerInput { eventId = eventId { id = it.toString() } }
val vPid = labeler.label(input).getPeople(0).virtualPersonId.toULong()
vPidCounts[vPid] = vPidCounts.getOrDefault(vPid, 0) + 1
}
/**
* Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The
* expected count for 10 is 0.4 * EVENT_ID_NUMBER = 4000, the expected count for 20 is 0.6 *
* EVENT_ID_NUMBER = 6000
*/
assertEquals(2, vPidCounts.size)
assertEquals(4061, vPidCounts[10UL])
assertEquals(5939, vPidCounts[20UL])
}
@Test
fun `build from nodes root with index`() {
/**
* All nodes, including root node, have index set.
*
* A model with
* - 40% probability to assign virtual person id 10
* - 60% probability to assign virtual person id 20
*/
val node1 = compiledNode {
name = "TestNode1"
index = 1
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 0.4
}
)
branches.add(
branch {
nodeIndex = 3
chance = 0.6
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 3
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
/** The root node is put at the end. */
val nodes = listOf(node2, node3, node1)
val labeler = Labeler.build(nodes)
val vPidCounts = mutableMapOf<ULong, Int>()
(0 until EVENT_ID_NUMBER).forEach {
val input = labelerInput { eventId = eventId { id = it.toString() } }
val vPid = labeler.label(input).getPeople(0).virtualPersonId.toULong()
vPidCounts[vPid] = vPidCounts.getOrDefault(vPid, 0) + 1
}
/**
* Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The
* expected count for 10 is 0.4 * EVENT_ID_NUMBER = 4000, the expected count for 20 is 0.6 *
* EVENT_ID_NUMBER = 6000
*/
assertEquals(2, vPidCounts.size)
assertEquals(4061, vPidCounts[10UL])
assertEquals(5939, vPidCounts[20UL])
}
@Test
fun `build from nodes root without index`() {
/**
* All nodes, except root node, have index set.
*
* A model with
* - 40% probability to assign virtual person id 10
* - 60% probability to assign virtual person id 20
*/
val node1 = compiledNode {
name = "TestNode1"
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 0.4
}
)
branches.add(
branch {
nodeIndex = 3
chance = 0.6
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 3
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
/** The root node is put at the end. */
val nodes = listOf(node2, node3, node1)
val labeler = Labeler.build(nodes)
val vPidCounts = mutableMapOf<ULong, Int>()
(0 until EVENT_ID_NUMBER).forEach {
val input = labelerInput { eventId = eventId { id = it.toString() } }
val vPid = labeler.label(input).getPeople(0).virtualPersonId.toULong()
vPidCounts[vPid] = vPidCounts.getOrDefault(vPid, 0) + 1
}
/**
* Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The
* expected count for 10 is 0.4 * EVENT_ID_NUMBER = 4000, the expected count for 20 is 0.6 *
* EVENT_ID_NUMBER = 6000
*/
assertEquals(2, vPidCounts.size)
assertEquals(4061, vPidCounts[10UL])
assertEquals(5939, vPidCounts[20UL])
}
@Test
fun `build from list with single node`() {
/**
* All nodes, except root node, have index set.
*
* A model with
* - 40% probability to assign virtual person id 10
* - 60% probability to assign virtual person id 20
*/
val node = compiledNode {
name = "TestNode1"
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val labeler = Labeler.build(listOf(node))
(0 until EVENT_ID_NUMBER).forEach {
val input = labelerInput { eventId = eventId { id = it.toString() } }
val vPid = labeler.label(input).getPeople(0).virtualPersonId.toULong()
assertEquals(10UL, vPid)
}
}
@Test
fun `build from nodes node after root should throw`() {
val node1 = compiledNode {
name = "TestNode1"
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 0.4
}
)
branches.add(
branch {
nodeIndex = 3
chance = 0.6
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 3
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
/** The root node is not at the end. */
val nodes = listOf(node2, node1, node3)
val exception = assertFailsWith<IllegalStateException> { Labeler.build(nodes) }
assertTrue(
exception.message!!.contains("The ModelNode object of the child node index 3 is not provided")
)
}
@Test
fun `build from nodes multiple roots should throw`() {
/**
* ```
* 2 trees exist:
* 1 -> 3, 4
* 2 -> 5
* ```
*/
val root1 = compiledNode {
name = "TestNode1"
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 3
chance = 0.4
}
)
branches.add(
branch {
nodeIndex = 4
chance = 0.6
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val root2 = compiledNode {
name = "TestNode2"
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 5
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 3
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val node4 = compiledNode {
name = "TestNode4"
index = 4
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
val node5 = compiledNode {
name = "TestNode5"
index = 5
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed3"
}
}
val nodes = listOf(node3, node4, node5, root1, root2)
val exception = assertFailsWith<IllegalStateException> { Labeler.build(nodes) }
assertTrue(exception.message!!.contains("No node is allowed after the root node"))
}
@Test
fun `build from nodes no root should throw`() {
/** Nodes 1 and 2 reference each other as child node. No root node can be recognized. */
val node1 = compiledNode {
name = "TestNode1"
index = 1
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed1"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 1
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed2"
}
}
val exception = assertFailsWith<IllegalStateException> { Labeler.build(listOf(node1, node2)) }
assertTrue(
exception.message!!.contains("The ModelNode object of the child node index 2 is not provided")
)
}
@Test
fun `build from nodes no node for index should throw`() {
/** Nodes 1 and 2 reference each other as child node. No root node can be recognized. */
val node1 = compiledNode {
name = "TestNode1"
index = 1
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed1"
}
}
val exception = assertFailsWith<IllegalStateException> { Labeler.build(listOf(node1)) }
assertTrue(
exception.message!!.contains("The ModelNode object of the child node index 2 is not provided")
)
}
@Test
fun `build from nodes duplicated indexes should throw`() {
val node1 = compiledNode {
name = "TestNode1"
index = 1
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 10
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed1"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 2
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
val exception =
assertFailsWith<IllegalStateException> { Labeler.build(listOf(node2, node3, node1)) }
assertTrue(exception.message!!.contains("Duplicated indexes"))
}
@Test
fun `build from nodes multiple parents should throw`() {
val node1 = compiledNode {
name = "TestNode1"
index = 1
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 2
chance = 0.5
}
)
branches.add(
branch {
nodeIndex = 3
chance = 10.5
}
)
randomSeed = "TestBranchNodeSeed1"
}
}
val node2 = compiledNode {
name = "TestNode2"
index = 2
branchNode = branchNode {
branches.add(
branch {
nodeIndex = 3
chance = 1.0
}
)
randomSeed = "TestBranchNodeSeed2"
}
}
val node3 = compiledNode {
name = "TestNode3"
index = 3
populationNode = populationNode {
pools.add(
virtualPersonPool {
populationOffset = 20
totalPopulation = 1
}
)
randomSeed = "TestPopulationNodeSeed2"
}
}
val exception =
assertFailsWith<IllegalStateException> { Labeler.build(listOf(node3, node2, node1)) }
assertTrue(
exception.message!!.contains("The ModelNode object of the child node index 3 is not provided")
)
}
}
| src/test/kotlin/org/wfanet/virtualpeople/core/labeler/LabelerTest.kt | 3814484901 |
package info.nightscout.androidaps.plugins.general.automation.actions
import info.nightscout.androidaps.automation.R
import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName
import info.nightscout.androidaps.queue.Callback
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyInt
import org.mockito.Mockito.anyString
class ActionProfileSwitchTest : ActionsTestBase() {
private lateinit var sut: ActionProfileSwitch
private val stringJson = "{\"data\":{\"profileToSwitchTo\":\"Test\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionProfileSwitch\"}"
@Before fun setUp() {
`when`(rh.gs(R.string.profilename)).thenReturn("Change profile to")
`when`(rh.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s")
`when`(rh.gs(R.string.alreadyset)).thenReturn("Already set")
`when`(rh.gs(R.string.notexists)).thenReturn("not exists")
`when`(rh.gs(R.string.error_field_must_not_be_empty)).thenReturn("The field must not be empty")
`when`(rh.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet")
sut = ActionProfileSwitch(injector)
}
@Test fun friendlyName() {
Assert.assertEquals(R.string.profilename, sut.friendlyName())
}
@Test fun shortDescriptionTest() {
Assert.assertEquals("Change profile to %s", sut.shortDescription())
}
@Test fun doAction() {
//Empty input
`when`(profileFunction.getProfileName()).thenReturn("Test")
sut.inputProfileName = InputProfileName(rh, activePlugin, "")
sut.doAction(object : Callback() {
override fun run() {
Assert.assertFalse(result.success)
}
})
//Not initialized profileStore
`when`(profileFunction.getProfile()).thenReturn(null)
sut.inputProfileName = InputProfileName(rh, activePlugin, "someProfile")
sut.doAction(object : Callback() {
override fun run() {
Assert.assertFalse(result.success)
}
})
//profile already set
`when`(profileFunction.getProfile()).thenReturn(validProfile)
`when`(profileFunction.getProfileName()).thenReturn("Test")
sut.inputProfileName = InputProfileName(rh, activePlugin, "Test")
sut.doAction(object : Callback() {
override fun run() {
Assert.assertTrue(result.success)
Assert.assertEquals("Already set", result.comment)
}
})
// profile doesn't exists
`when`(profileFunction.getProfileName()).thenReturn("Active")
sut.inputProfileName = InputProfileName(rh, activePlugin, "Test")
sut.doAction(object : Callback() {
override fun run() {
Assert.assertFalse(result.success)
Assert.assertEquals("not exists", result.comment)
}
})
// do profile switch
`when`(profileFunction.getProfileName()).thenReturn("Test")
`when`(profileFunction.createProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong())).thenReturn(true)
sut.inputProfileName = InputProfileName(rh, activePlugin, TESTPROFILENAME)
sut.doAction(object : Callback() {
override fun run() {
Assert.assertTrue(result.success)
Assert.assertEquals("OK", result.comment)
}
})
Mockito.verify(profileFunction, Mockito.times(1)).createProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong())
}
@Test fun hasDialogTest() {
Assert.assertTrue(sut.hasDialog())
}
@Test fun toJSONTest() {
sut.inputProfileName = InputProfileName(rh, activePlugin, "Test")
Assert.assertEquals(stringJson, sut.toJSON())
}
@Test fun fromJSONTest() {
val data = "{\"profileToSwitchTo\":\"Test\"}"
sut.fromJSON(data)
Assert.assertEquals("Test", sut.inputProfileName.value)
}
@Test fun iconTest() {
Assert.assertEquals(R.drawable.ic_actions_profileswitch, sut.icon())
}
} | automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt | 168860706 |
package com.prateekj.snooper.dbreader.activity
import android.graphics.Typeface
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.TableRow
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getDrawable
import com.prateekj.snooper.R
import com.prateekj.snooper.dbreader.DatabaseDataReader
import com.prateekj.snooper.dbreader.DatabaseReader
import com.prateekj.snooper.dbreader.activity.DatabaseDetailActivity.Companion.TABLE_NAME
import com.prateekj.snooper.dbreader.model.Table
import com.prateekj.snooper.dbreader.view.TableViewCallback
import com.prateekj.snooper.infra.BackgroundTaskExecutor
import com.prateekj.snooper.networksnooper.activity.SnooperBaseActivity
import kotlinx.android.synthetic.main.activity_table_view.*
class TableDetailActivity : SnooperBaseActivity(), TableViewCallback {
private lateinit var databaseReader: DatabaseReader
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_table_view)
initViews()
val tableName = intent.getStringExtra(TABLE_NAME)
val dbPath = intent.getStringExtra(DatabaseDetailActivity.DB_PATH)
val backgroundTaskExecutor = BackgroundTaskExecutor(this)
databaseReader = DatabaseReader(this, backgroundTaskExecutor, DatabaseDataReader())
databaseReader.fetchTableContent(this, dbPath, tableName!!)
}
override fun onTableFetchStarted() {
embedded_loader!!.visibility = VISIBLE
}
override fun onTableFetchCompleted(table: Table) {
embedded_loader!!.visibility = GONE
updateView(table)
}
private fun initViews() {
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
private fun updateView(table: Table) {
addTableColumnNames(table)
addTableRowsToUi(table)
}
private fun addTableRowsToUi(table: Table) {
val rows = table.rows!!
for (i in rows.indices) {
table_layout!!.addView(addRowData(rows[i].data, i + 1))
}
}
private fun addTableColumnNames(table: Table) {
val columnRow = TableRow(this)
val serialNoCell = getCellView(getString(R.string.serial_number_column_heading))
serialNoCell.setTypeface(null, Typeface.BOLD)
columnRow.addView(serialNoCell)
for (column in table.columns!!) {
val columnView = getCellView(column).apply {
setBackgroundColor(ContextCompat.getColor(this@TableDetailActivity, R.color.snooper_grey))
background = getDrawable(this@TableDetailActivity, R.drawable.table_cell_background)
setTypeface(null, Typeface.BOLD)
}
columnRow.addView(columnView)
}
table_layout!!.addView(columnRow)
}
private fun addRowData(data: List<String>, serialNumber: Int): TableRow {
val row = TableRow(this)
row.addView(getCellView(serialNumber.toString()))
for (cellValue in data) {
row.addView(getCellView(cellValue))
}
return row
}
private fun getCellView(cellValue: String): TextView {
val textView = TextView(this)
textView.setPadding(1, 0, 0, 0)
textView.background = getDrawable(this, R.drawable.table_cell_background)
textView.text = cellValue
return textView
}
} | Snooper/src/main/java/com/prateekj/snooper/dbreader/activity/TableDetailActivity.kt | 752387163 |
/*
* Copyright (C) 2019 Square, 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.
*/
package com.squareup.wire.schema
/** Loads other files as needed by their import path. */
interface Loader {
fun load(path: String): ProtoFile
/** Returns a new loader that reports failures to [errors]. */
fun withErrors(errors: ErrorCollector): Loader
}
| wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Loader.kt | 1578467986 |
/*
* Copyright (c) 2020. Adventech <[email protected]>
*
* 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.cryart.sabbathschool.ui.splash
import app.cash.turbine.test
import app.ss.auth.AuthRepository
import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs
import com.cryart.sabbathschool.core.response.Resource
import com.cryart.sabbathschool.reminder.DailyReminderManager
import com.cryart.sabbathschool.test.coroutines.TestDispatcherProvider
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.test.runTest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
class SplashViewModelTest {
private val mockDailyReminderManager: DailyReminderManager = mockk()
private val mockSSPrefs: SSPrefs = mockk()
private val mockAuthRepository: AuthRepository = mockk()
private val dispatcherProvider = TestDispatcherProvider()
private lateinit var viewModel: SplashViewModel
@Before
fun setUp() {
every { mockDailyReminderManager.scheduleReminder() }.returns(Unit)
every { mockSSPrefs.reminderEnabled() }.returns(true)
every { mockSSPrefs.isReminderScheduled() }.returns(false)
every { mockSSPrefs.isReadingLatestQuarterly() }.returns(false)
every { mockSSPrefs.getLastQuarterlyIndex() }.returns(null)
coEvery { mockAuthRepository.getUser() }.returns(Resource.success(mockk()))
viewModel = SplashViewModel(
ssPrefs = mockSSPrefs,
authRepository = mockAuthRepository,
dailyReminderManager = mockDailyReminderManager,
dispatcherProvider = dispatcherProvider
)
}
@Test
fun `should schedule reminder when user is signed in`() {
viewModel.launch()
verify { mockDailyReminderManager.scheduleReminder() }
}
@Test
@Ignore("Verify no interaction")
fun `should not schedule reminder when user is signed in and reminder is disabled`() {
every { mockSSPrefs.reminderEnabled() }.returns(false)
viewModel.launch()
verify(inverse = false) { mockDailyReminderManager.scheduleReminder() }
}
@Test
fun `should return Quarterlies state when user is signed in and no last saved index`() = runTest {
every { mockSSPrefs.getLastQuarterlyIndex() }.returns(null)
viewModel.launchStateFlow.test {
viewModel.launch()
awaitItem() shouldBeEqualTo LaunchState.Loading
awaitItem() shouldBeEqualTo LaunchState.Quarterlies
}
}
@Test
fun `should return Quarterlies state when user is signed in with last saved index and not reading latest quarterly`() = runTest {
every { mockSSPrefs.getLastQuarterlyIndex() }.returns("index")
every { mockSSPrefs.isReadingLatestQuarterly() }.returns(false)
viewModel.launchStateFlow.test {
viewModel.launch()
awaitItem() shouldBeEqualTo LaunchState.Loading
awaitItem() shouldBeEqualTo LaunchState.Quarterlies
}
}
@Test
fun `should return Lessons state when user is signed in with last saved index and reading latest quarterly`() = runTest {
every { mockSSPrefs.getLastQuarterlyIndex() }.returns("index")
every { mockSSPrefs.isReadingLatestQuarterly() }.returns(true)
viewModel.launchStateFlow.test {
viewModel.launch()
awaitItem() shouldBeEqualTo LaunchState.Loading
awaitItem() shouldBeEqualTo LaunchState.Lessons("index")
}
}
}
| app/src/test/java/com/cryart/sabbathschool/ui/splash/SplashViewModelTest.kt | 2233839658 |
/*
* Copyright (C) 2015 Square, 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.
*/
package com.squareup.wire.schema.internal.parser
import com.squareup.wire.schema.Field.Label.OPTIONAL
import com.squareup.wire.schema.Field.Label.REQUIRED
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.internal.parser.OptionElement.Kind
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class FieldElementTest {
internal var location = Location.get("file.proto")
@Test
fun field() {
val field = FieldElement(
location = location,
label = OPTIONAL,
type = "CType",
name = "ctype",
tag = 1,
options = listOf(
OptionElement.create("default", Kind.ENUM, "TEST"),
OptionElement.create("deprecated", Kind.BOOLEAN, "true")
)
)
assertThat(field.options)
.containsOnly(
OptionElement.create("default", Kind.ENUM, "TEST"),
OptionElement.create("deprecated", Kind.BOOLEAN, "true")
)
}
@Test
fun addMultipleOptions() {
val kitKat = OptionElement.create("kit", Kind.STRING, "kat")
val fooBar = OptionElement.create("foo", Kind.STRING, "bar")
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
options = listOf(kitKat, fooBar)
)
assertThat(field.options).hasSize(2)
}
@Test
fun defaultIsSet() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
tag = 1,
defaultValue = "defaultValue"
)
assertThat(field.toSchema())
.isEqualTo(
"""
|required string name = 1 [default = "defaultValue"];
|""".trimMargin()
)
}
@Test
fun jsonNameAndDefaultValue() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
defaultValue = "defaultValue",
jsonName = "my_json",
tag = 1
)
assertThat(field.toSchema())
.isEqualTo(
"""
|required string name = 1 [
| default = "defaultValue",
| json_name = "my_json"
|];
|""".trimMargin()
)
}
@Test
fun jsonName() {
val field = FieldElement(
location = location,
label = REQUIRED,
type = "string",
name = "name",
jsonName = "my_json",
tag = 1
)
assertThat(field.toSchema())
.isEqualTo(
"""
|required string name = 1 [json_name = "my_json"];
|""".trimMargin()
)
}
}
| wire-library/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/internal/parser/FieldElementTest.kt | 792324087 |
/*******************************************************************************
* This file is part of Improbable Bot.
*
* Improbable Bot 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.
*
* Improbable Bot 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 Improbable Bot. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.joedanpar.improbabot.components.game.world
import com.joedanpar.improbabot.components.common.HasId
import javax.persistence.Entity
import javax.persistence.ManyToOne
@Entity
data class Distance(
@ManyToOne
val start: Location?,
@ManyToOne
val end: Location?,
val distance: Int
) : HasId() {
constructor() : this(null, null, 0)
}
| src/main/kotlin/com/joedanpar/improbabot/components/game/world/Distance.kt | 2662053589 |
package com.fsck.k9
import com.fsck.k9.backend.api.SyncConfig.ExpungePolicy
import com.fsck.k9.mail.Address
import com.fsck.k9.mail.ServerSettings
import java.util.Calendar
import java.util.Date
/**
* Account stores all of the settings for a single account defined by the user. Each account is defined by a UUID.
*/
class Account(override val uuid: String) : BaseAccount {
@get:Synchronized
@set:Synchronized
var deletePolicy = DeletePolicy.NEVER
@get:Synchronized
@set:Synchronized
private var internalIncomingServerSettings: ServerSettings? = null
@get:Synchronized
@set:Synchronized
private var internalOutgoingServerSettings: ServerSettings? = null
var incomingServerSettings: ServerSettings
get() = internalIncomingServerSettings ?: error("Incoming server settings not set yet")
set(value) {
internalIncomingServerSettings = value
}
var outgoingServerSettings: ServerSettings
get() = internalOutgoingServerSettings ?: error("Outgoing server settings not set yet")
set(value) {
internalOutgoingServerSettings = value
}
@get:Synchronized
@set:Synchronized
var oAuthState: String? = null
/**
* Storage provider ID, used to locate and manage the underlying DB/file storage.
*/
@get:Synchronized
@set:Synchronized
var localStorageProviderId: String? = null
@get:Synchronized
@set:Synchronized
override var name: String? = null
set(value) {
field = value?.takeIf { it.isNotEmpty() }
}
@get:Synchronized
@set:Synchronized
var alwaysBcc: String? = null
/**
* -1 for never.
*/
@get:Synchronized
@set:Synchronized
var automaticCheckIntervalMinutes = 0
@get:Synchronized
@set:Synchronized
var displayCount = 0
set(value) {
if (field != value) {
field = value.takeIf { it != -1 } ?: K9.DEFAULT_VISIBLE_LIMIT
isChangedVisibleLimits = true
}
}
@get:Synchronized
@set:Synchronized
var chipColor = 0
@get:Synchronized
@set:Synchronized
var isNotifyNewMail = false
@get:Synchronized
@set:Synchronized
var folderNotifyNewMailMode = FolderMode.ALL
@get:Synchronized
@set:Synchronized
var isNotifySelfNewMail = false
@get:Synchronized
@set:Synchronized
var isNotifyContactsMailOnly = false
@get:Synchronized
@set:Synchronized
var isIgnoreChatMessages = false
@get:Synchronized
@set:Synchronized
var legacyInboxFolder: String? = null
@get:Synchronized
@set:Synchronized
var importedDraftsFolder: String? = null
@get:Synchronized
@set:Synchronized
var importedSentFolder: String? = null
@get:Synchronized
@set:Synchronized
var importedTrashFolder: String? = null
@get:Synchronized
@set:Synchronized
var importedArchiveFolder: String? = null
@get:Synchronized
@set:Synchronized
var importedSpamFolder: String? = null
@get:Synchronized
@set:Synchronized
var inboxFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var outboxFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var draftsFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var sentFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var trashFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var archiveFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var spamFolderId: Long? = null
@get:Synchronized
var draftsFolderSelection = SpecialFolderSelection.AUTOMATIC
private set
@get:Synchronized
var sentFolderSelection = SpecialFolderSelection.AUTOMATIC
private set
@get:Synchronized
var trashFolderSelection = SpecialFolderSelection.AUTOMATIC
private set
@get:Synchronized
var archiveFolderSelection = SpecialFolderSelection.AUTOMATIC
private set
@get:Synchronized
var spamFolderSelection = SpecialFolderSelection.AUTOMATIC
private set
@get:Synchronized
@set:Synchronized
var importedAutoExpandFolder: String? = null
@get:Synchronized
@set:Synchronized
var autoExpandFolderId: Long? = null
@get:Synchronized
@set:Synchronized
var folderDisplayMode = FolderMode.NOT_SECOND_CLASS
@get:Synchronized
@set:Synchronized
var folderSyncMode = FolderMode.FIRST_CLASS
@get:Synchronized
@set:Synchronized
var folderPushMode = FolderMode.NONE
@get:Synchronized
@set:Synchronized
var folderTargetMode = FolderMode.NOT_SECOND_CLASS
@get:Synchronized
@set:Synchronized
var accountNumber = 0
@get:Synchronized
@set:Synchronized
var isNotifySync = false
@get:Synchronized
@set:Synchronized
var sortType: SortType = SortType.SORT_DATE
private val sortAscending: MutableMap<SortType, Boolean> = mutableMapOf()
@get:Synchronized
@set:Synchronized
var showPictures = ShowPictures.NEVER
@get:Synchronized
@set:Synchronized
var isSignatureBeforeQuotedText = false
@get:Synchronized
@set:Synchronized
var expungePolicy = Expunge.EXPUNGE_IMMEDIATELY
@get:Synchronized
@set:Synchronized
var maxPushFolders = 0
@get:Synchronized
@set:Synchronized
var idleRefreshMinutes = 0
@get:JvmName("useCompression")
@get:Synchronized
@set:Synchronized
var useCompression = true
@get:Synchronized
@set:Synchronized
var searchableFolders = Searchable.ALL
@get:Synchronized
@set:Synchronized
var isSubscribedFoldersOnly = false
@get:Synchronized
@set:Synchronized
var maximumPolledMessageAge = 0
@get:Synchronized
@set:Synchronized
var maximumAutoDownloadMessageSize = 0
@get:Synchronized
@set:Synchronized
var messageFormat = MessageFormat.HTML
@get:Synchronized
@set:Synchronized
var isMessageFormatAuto = false
@get:Synchronized
@set:Synchronized
var isMessageReadReceipt = false
@get:Synchronized
@set:Synchronized
var quoteStyle = QuoteStyle.PREFIX
@get:Synchronized
@set:Synchronized
var quotePrefix: String? = null
@get:Synchronized
@set:Synchronized
var isDefaultQuotedTextShown = false
@get:Synchronized
@set:Synchronized
var isReplyAfterQuote = false
@get:Synchronized
@set:Synchronized
var isStripSignature = false
@get:Synchronized
@set:Synchronized
var isSyncRemoteDeletions = false
@get:Synchronized
@set:Synchronized
var openPgpProvider: String? = null
set(value) {
field = value?.takeIf { it.isNotEmpty() }
}
@get:Synchronized
@set:Synchronized
var openPgpKey: Long = 0
@get:Synchronized
@set:Synchronized
var autocryptPreferEncryptMutual = false
@get:Synchronized
@set:Synchronized
var isOpenPgpHideSignOnly = false
@get:Synchronized
@set:Synchronized
var isOpenPgpEncryptSubject = false
@get:Synchronized
@set:Synchronized
var isOpenPgpEncryptAllDrafts = false
@get:Synchronized
@set:Synchronized
var isMarkMessageAsReadOnView = false
@get:Synchronized
@set:Synchronized
var isMarkMessageAsReadOnDelete = false
@get:Synchronized
@set:Synchronized
var isAlwaysShowCcBcc = false
// Temporarily disabled
@get:Synchronized
@set:Synchronized
var isRemoteSearchFullText = false
get() = false
@get:Synchronized
@set:Synchronized
var remoteSearchNumResults = 0
set(value) {
field = value.coerceAtLeast(0)
}
@get:Synchronized
@set:Synchronized
var isUploadSentMessages = false
@get:Synchronized
@set:Synchronized
var lastSyncTime: Long = 0
@get:Synchronized
@set:Synchronized
var lastFolderListRefreshTime: Long = 0
@get:Synchronized
var isFinishedSetup = false
private set
@get:Synchronized
@set:Synchronized
var messagesNotificationChannelVersion = 0
@get:Synchronized
@set:Synchronized
var isChangedVisibleLimits = false
private set
/**
* Database ID of the folder that was last selected for a copy or move operation.
*
* Note: For now this value isn't persisted. So it will be reset when K-9 Mail is restarted.
*/
@get:Synchronized
var lastSelectedFolderId: Long? = null
private set
@get:Synchronized
@set:Synchronized
var identities: MutableList<Identity> = mutableListOf()
set(value) {
field = value.toMutableList()
}
@get:Synchronized
var notificationSettings = NotificationSettings()
private set
val displayName: String
get() = name ?: email
@get:Synchronized
@set:Synchronized
override var email: String
get() = identities[0].email!!
set(email) {
val newIdentity = identities[0].withEmail(email)
identities[0] = newIdentity
}
@get:Synchronized
@set:Synchronized
var senderName: String?
get() = identities[0].name
set(name) {
val newIdentity = identities[0].withName(name)
identities[0] = newIdentity
}
@get:Synchronized
@set:Synchronized
var signatureUse: Boolean
get() = identities[0].signatureUse
set(signatureUse) {
val newIdentity = identities[0].withSignatureUse(signatureUse)
identities[0] = newIdentity
}
@get:Synchronized
@set:Synchronized
var signature: String?
get() = identities[0].signature
set(signature) {
val newIdentity = identities[0].withSignature(signature)
identities[0] = newIdentity
}
/**
* @param automaticCheckIntervalMinutes or -1 for never.
*/
@Synchronized
fun updateAutomaticCheckIntervalMinutes(automaticCheckIntervalMinutes: Int): Boolean {
val oldInterval = this.automaticCheckIntervalMinutes
this.automaticCheckIntervalMinutes = automaticCheckIntervalMinutes
return oldInterval != automaticCheckIntervalMinutes
}
@Synchronized
fun setDraftsFolderId(folderId: Long?, selection: SpecialFolderSelection) {
draftsFolderId = folderId
draftsFolderSelection = selection
}
@Synchronized
fun hasDraftsFolder(): Boolean {
return draftsFolderId != null
}
@Synchronized
fun setSentFolderId(folderId: Long?, selection: SpecialFolderSelection) {
sentFolderId = folderId
sentFolderSelection = selection
}
@Synchronized
fun hasSentFolder(): Boolean {
return sentFolderId != null
}
@Synchronized
fun setTrashFolderId(folderId: Long?, selection: SpecialFolderSelection) {
trashFolderId = folderId
trashFolderSelection = selection
}
@Synchronized
fun hasTrashFolder(): Boolean {
return trashFolderId != null
}
@Synchronized
fun setArchiveFolderId(folderId: Long?, selection: SpecialFolderSelection) {
archiveFolderId = folderId
archiveFolderSelection = selection
}
@Synchronized
fun hasArchiveFolder(): Boolean {
return archiveFolderId != null
}
@Synchronized
fun setSpamFolderId(folderId: Long?, selection: SpecialFolderSelection) {
spamFolderId = folderId
spamFolderSelection = selection
}
@Synchronized
fun hasSpamFolder(): Boolean {
return spamFolderId != null
}
@Synchronized
fun updateFolderSyncMode(syncMode: FolderMode): Boolean {
val oldSyncMode = folderSyncMode
folderSyncMode = syncMode
return (oldSyncMode == FolderMode.NONE && syncMode != FolderMode.NONE) ||
(oldSyncMode != FolderMode.NONE && syncMode == FolderMode.NONE)
}
@Synchronized
fun isSortAscending(sortType: SortType): Boolean {
return sortAscending.getOrPut(sortType) { sortType.isDefaultAscending }
}
@Synchronized
fun setSortAscending(sortType: SortType, sortAscending: Boolean) {
this.sortAscending[sortType] = sortAscending
}
@Synchronized
fun replaceIdentities(identities: List<Identity>) {
this.identities = identities.toMutableList()
}
@Synchronized
fun getIdentity(index: Int): Identity {
if (index !in identities.indices) error("Identity with index $index not found")
return identities[index]
}
fun isAnIdentity(addresses: Array<Address>?): Boolean {
if (addresses == null) return false
return addresses.any { address -> isAnIdentity(address) }
}
fun isAnIdentity(address: Address): Boolean {
return findIdentity(address) != null
}
@Synchronized
fun findIdentity(address: Address): Identity? {
return identities.find { identity ->
identity.email.equals(address.address, ignoreCase = true)
}
}
val earliestPollDate: Date?
get() {
val age = maximumPolledMessageAge.takeIf { it >= 0 } ?: return null
val now = Calendar.getInstance()
now[Calendar.HOUR_OF_DAY] = 0
now[Calendar.MINUTE] = 0
now[Calendar.SECOND] = 0
now[Calendar.MILLISECOND] = 0
if (age < 28) {
now.add(Calendar.DATE, age * -1)
} else when (age) {
28 -> now.add(Calendar.MONTH, -1)
56 -> now.add(Calendar.MONTH, -2)
84 -> now.add(Calendar.MONTH, -3)
168 -> now.add(Calendar.MONTH, -6)
365 -> now.add(Calendar.YEAR, -1)
}
return now.time
}
val isOpenPgpProviderConfigured: Boolean
get() = openPgpProvider != null
@Synchronized
fun hasOpenPgpKey(): Boolean {
return openPgpKey != NO_OPENPGP_KEY
}
@Synchronized
fun setLastSelectedFolderId(folderId: Long) {
lastSelectedFolderId = folderId
}
@Synchronized
fun resetChangeMarkers() {
isChangedVisibleLimits = false
}
@Synchronized
fun markSetupFinished() {
isFinishedSetup = true
}
@Synchronized
fun updateNotificationSettings(block: (oldNotificationSettings: NotificationSettings) -> NotificationSettings) {
notificationSettings = block(notificationSettings)
}
override fun toString(): String {
return if (K9.isSensitiveDebugLoggingEnabled) displayName else uuid
}
override fun equals(other: Any?): Boolean {
return if (other is Account) {
other.uuid == uuid
} else {
super.equals(other)
}
}
override fun hashCode(): Int {
return uuid.hashCode()
}
enum class FolderMode {
NONE,
ALL,
FIRST_CLASS,
FIRST_AND_SECOND_CLASS,
NOT_SECOND_CLASS
}
enum class SpecialFolderSelection {
AUTOMATIC,
MANUAL
}
enum class ShowPictures {
NEVER,
ALWAYS,
ONLY_FROM_CONTACTS
}
enum class Searchable {
ALL,
DISPLAYABLE,
NONE
}
enum class QuoteStyle {
PREFIX,
HEADER
}
enum class MessageFormat {
TEXT,
HTML,
AUTO
}
enum class Expunge {
EXPUNGE_IMMEDIATELY,
EXPUNGE_MANUALLY,
EXPUNGE_ON_POLL;
fun toBackendExpungePolicy(): ExpungePolicy = when (this) {
EXPUNGE_IMMEDIATELY -> ExpungePolicy.IMMEDIATELY
EXPUNGE_MANUALLY -> ExpungePolicy.MANUALLY
EXPUNGE_ON_POLL -> ExpungePolicy.ON_POLL
}
}
enum class DeletePolicy(@JvmField val setting: Int) {
NEVER(0),
SEVEN_DAYS(1),
ON_DELETE(2),
MARK_AS_READ(3);
companion object {
fun fromInt(initialSetting: Int): DeletePolicy {
return values().find { it.setting == initialSetting } ?: error("DeletePolicy $initialSetting unknown")
}
}
}
enum class SortType(val isDefaultAscending: Boolean) {
SORT_DATE(false),
SORT_ARRIVAL(false),
SORT_SUBJECT(true),
SORT_SENDER(true),
SORT_UNREAD(true),
SORT_FLAGGED(true),
SORT_ATTACHMENT(true);
}
companion object {
/**
* Fixed name of outbox - not actually displayed.
*/
const val OUTBOX_NAME = "Outbox"
@JvmField
val DEFAULT_SORT_TYPE = SortType.SORT_DATE
const val DEFAULT_SORT_ASCENDING = false
const val NO_OPENPGP_KEY: Long = 0
const val UNASSIGNED_ACCOUNT_NUMBER = -1
const val INTERVAL_MINUTES_NEVER = -1
const val DEFAULT_SYNC_INTERVAL = 60
}
}
| app/core/src/main/java/com/fsck/k9/Account.kt | 3705555828 |
package app.k9mail.cli.html.cleaner
import app.k9mail.html.cleaner.HtmlHeadProvider
import app.k9mail.html.cleaner.HtmlProcessor
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.optional
import com.github.ajalt.clikt.parameters.types.file
import com.github.ajalt.clikt.parameters.types.inputStream
import java.io.File
import okio.buffer
import okio.sink
import okio.source
@Suppress("MemberVisibilityCanBePrivate")
class HtmlCleaner : CliktCommand(
help = "A tool that modifies HTML to only keep allowed elements and attributes the same way that K-9 Mail does."
) {
val input by argument(help = "HTML input file (needs to be UTF-8 encoded)")
.inputStream()
val output by argument(help = "Output file")
.file(mustExist = false, canBeDir = false)
.optional()
override fun run() {
val html = readInput()
val processedHtml = cleanHtml(html)
writeOutput(processedHtml)
}
private fun readInput(): String {
return input.source().buffer().use { it.readUtf8() }
}
private fun cleanHtml(html: String): String {
val htmlProcessor = HtmlProcessor(object : HtmlHeadProvider {
override val headHtml = """<meta name="viewport" content="width=device-width"/>"""
})
return htmlProcessor.processForDisplay(html)
}
private fun writeOutput(data: String) {
output?.writeOutput(data) ?: echo(data)
}
private fun File.writeOutput(data: String) {
sink().buffer().use {
it.writeUtf8(data)
}
}
}
fun main(args: Array<String>) = HtmlCleaner().main(args)
| cli/html-cleaner-cli/src/main/kotlin/Main.kt | 1158594427 |
/*
* This file is part of HomebankCvsConverter.
* Copyright (C) 2015 Raik Bieniek <[email protected]>
*
* HomebankCvsConverter 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.
*
* HomebankCvsConverter 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 HomebankCvsConverter. If not, see <http://www.gnu.org/licenses/>.
*/
package de.voidnode.homebankCvsConverter
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.charset.Charset;
fun main(args : Array<String>) {
if(args.size != 2) {
printHelp()
return
}
val input = Paths.get(args.get(0));
val output = Paths.get(args.get(1));
if(!Files.exists(input)) {
printHelp()
return
}
convert(input, output)
}
/**
* Converts a CVS file exported from the Commerzbank page into a CVS file that can be imported into the Homebank application.
*/
private fun convert(input: Path, output: Path) {
val utf8 = Charset.forName("UTF-8");
val inputLines = Files.readAllLines(input, utf8)
val transactions = readCommerzbankCsv(inputLines)
val outputLines = serializeHomeBankCsv(transactions)
Files.write(output, outputLines, utf8)
}
private fun printHelp() {
println("Usage: homebankCvsConverter <input CSV> <output CSV>")
println(" <input CSV> The CVS file exported from the website of the bank.")
println(" <output CSV> The destination path where the CSV file to import into HomeBank should be stored.")
} | src/main/kotlin/de/voidnode/homebankCvsConverter/Commerzbank2Homebank.kt | 2126027248 |
package failchat.chat.badge
interface BadgeFinder {
fun findBadge(origin: BadgeOrigin, badgeId: Any): Badge?
} | src/main/kotlin/failchat/chat/badge/BadgeFinder.kt | 2168787135 |
package kotlincursor.data
import android.content.ContentValues
import android.database.Cursor
import kotlincursor.annotation.ColumnAdapter
import kotlincursor.annotation.ColumnName
import kotlincursor.annotation.ColumnTypeAdapter
import kotlincursor.annotation.KCursorData
@KCursorData
data class SimpleData(val a: Int) {
class ColumnAdapter : ColumnTypeAdapter<SimpleData> {
override fun fromCursor(cursor: Cursor, columnName: String): SimpleData {
return SimpleData(cursor.getInt(cursor.getColumnIndexOrThrow(columnName)))
}
override fun toContentValues(values: ContentValues, columnName: String, value: SimpleData) {
values.put(columnName, value.a)
}
}
}
@KCursorData
data class SimpleNamedData(@ColumnName("my_name") val a: Int)
@KCursorData
data class SupportedTypesData(
val aString: String,
val aByteArray: ByteArray,
val aDouble: Double,
val aFloat: Float,
val anInt: Int,
val anLong: Long,
val anShort: Short,
val anBoolean: Boolean
)
@KCursorData
data class NullableSupportedTypesData(
val aString: String?,
val aByteArray: ByteArray?,
val aDouble: Double?,
val aFloat: Float?,
val anInt: Int?,
val anLong: Long?,
val anShort: Short?,
val anBoolean: Boolean?
)
@KCursorData
data class NestedCursorData(val a: SimpleData)
@KCursorData
data class NullableNestedCursorData(val a: SimpleData?)
@KCursorData
data class AdapterData(@ColumnAdapter(SimpleData.ColumnAdapter::class) val a: SimpleData)
@KCursorData
data class NullableAdapterData(@ColumnAdapter(SimpleData.ColumnAdapter::class) val a: SimpleData?)
@KCursorData
data class InvalidData(val invalidProperty: List<String>)
@KCursorData
data class AccompaniedData(val a: Int) {
companion object {
@JvmStatic val TAG = "AccompaniedData"
}
} | kotlincursor-compiler/src/test/java/kotlincursor/data/DataClasses.kt | 1049536832 |
package kebab.support.download
import kebab.core.Page
/**
* Created by yy_yank on 2016/10/02.
*/
class UninitializedDownloadSupport(page: Page) : DownloadSupport | src/main/kotlin/support/download/UninitializedDownloadSupport.kt | 1573143165 |
package ktn.lab
import java.math.BigInteger
object Perf {
internal fun fib(n: Int): BigInteger {
var a = BigInteger.ONE
var b = BigInteger.ZERO
var c: BigInteger
for (i in 1 until n) {
c = a
a = a.add(b)
b = c
}
return a
}
}
| kt/pe/src/main/kotlin/ktn/lab/Perf.kt | 961196560 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.key
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.helper.mode
import org.jetbrains.annotations.NonNls
sealed class ShortcutOwnerInfo {
data class AllModes(val owner: ShortcutOwner) : ShortcutOwnerInfo()
data class PerMode(
val normal: ShortcutOwner,
val insert: ShortcutOwner,
val visual: ShortcutOwner,
val select: ShortcutOwner,
) : ShortcutOwnerInfo() {
fun toNotation(): String {
val owners = HashMap<ShortcutOwner, MutableList<String>>()
owners[normal] = (owners[normal] ?: mutableListOf()).also { it.add("n") }
owners[insert] = (owners[insert] ?: mutableListOf()).also { it.add("i") }
owners[visual] = (owners[visual] ?: mutableListOf()).also { it.add("x") }
owners[select] = (owners[select] ?: mutableListOf()).also { it.add("s") }
if ("x" in (owners[ShortcutOwner.VIM] ?: emptyList()) && "s" in (owners[ShortcutOwner.VIM] ?: emptyList())) {
val existing = owners[ShortcutOwner.VIM] ?: mutableListOf()
existing.remove("x")
existing.remove("s")
existing.add("v")
owners[ShortcutOwner.VIM] = existing
}
if ("x" in (owners[ShortcutOwner.IDE] ?: emptyList()) && "s" in (owners[ShortcutOwner.IDE] ?: emptyList())) {
val existing = owners[ShortcutOwner.IDE] ?: mutableListOf()
existing.remove("x")
existing.remove("s")
existing.add("v")
owners[ShortcutOwner.IDE] = existing
}
if ((owners[ShortcutOwner.IDE] ?: emptyList()).isEmpty()) {
owners.remove(ShortcutOwner.VIM)
owners[ShortcutOwner.VIM] = mutableListOf("a")
}
if ((owners[ShortcutOwner.VIM] ?: emptyList()).isEmpty()) {
owners.remove(ShortcutOwner.IDE)
owners[ShortcutOwner.IDE] = mutableListOf("a")
}
val ideOwners = (owners[ShortcutOwner.IDE] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-")
val vimOwners = (owners[ShortcutOwner.VIM] ?: emptyList()).sortedBy { wights[it] ?: 1000 }.joinToString(separator = "-")
return if (ideOwners.isNotEmpty() && vimOwners.isNotEmpty()) {
ideOwners + ":" + ShortcutOwner.IDE.ownerName + " " + vimOwners + ":" + ShortcutOwner.VIM.ownerName
} else if (ideOwners.isNotEmpty() && vimOwners.isEmpty()) {
ideOwners + ":" + ShortcutOwner.IDE.ownerName
} else if (ideOwners.isEmpty() && vimOwners.isNotEmpty()) {
vimOwners + ":" + ShortcutOwner.VIM.ownerName
} else {
error("Unexpected state")
}
}
}
fun forEditor(editor: VimEditor): ShortcutOwner {
return when (this) {
is AllModes -> this.owner
is PerMode -> when (editor.mode) {
VimStateMachine.Mode.COMMAND -> this.normal
VimStateMachine.Mode.VISUAL -> this.visual
VimStateMachine.Mode.SELECT -> this.visual
VimStateMachine.Mode.INSERT -> this.insert
VimStateMachine.Mode.CMD_LINE -> this.normal
VimStateMachine.Mode.OP_PENDING -> this.normal
VimStateMachine.Mode.REPLACE -> this.insert
VimStateMachine.Mode.INSERT_NORMAL -> this.normal
VimStateMachine.Mode.INSERT_VISUAL -> this.visual
VimStateMachine.Mode.INSERT_SELECT -> this.select
}
}
}
companion object {
@JvmField
val allUndefined = AllModes(ShortcutOwner.UNDEFINED)
val allVim = AllModes(ShortcutOwner.VIM)
val allIde = AllModes(ShortcutOwner.IDE)
val allPerModeVim = PerMode(ShortcutOwner.VIM, ShortcutOwner.VIM, ShortcutOwner.VIM, ShortcutOwner.VIM)
val allPerModeIde = PerMode(ShortcutOwner.IDE, ShortcutOwner.IDE, ShortcutOwner.IDE, ShortcutOwner.IDE)
private val wights = mapOf(
"a" to 0,
"n" to 1,
"i" to 2,
"x" to 3,
"s" to 4,
"v" to 5
)
}
}
enum class ShortcutOwner(val ownerName: @NonNls String, private val title: @NonNls String) {
UNDEFINED("undefined", "Undefined"),
IDE(Constants.IDE_STRING, "IDE"),
VIM(Constants.VIM_STRING, "Vim");
override fun toString(): String = title
private object Constants {
const val IDE_STRING: @NonNls String = "ide"
const val VIM_STRING: @NonNls String = "vim"
}
companion object {
@JvmStatic
fun fromString(s: String): ShortcutOwner = when (s) {
Constants.IDE_STRING -> IDE
Constants.VIM_STRING -> VIM
else -> UNDEFINED
}
fun fromStringOrNull(s: String): ShortcutOwner? {
return when {
Constants.IDE_STRING.equals(s, ignoreCase = true) -> IDE
Constants.VIM_STRING.equals(s, ignoreCase = true) -> VIM
else -> null
}
}
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/key/ShortcutOwner.kt | 1356859908 |
package com.edwardharker.aircraftrecognition.search
import com.edwardharker.aircraftrecognition.model.Aircraft
import com.shazam.shazamcrest.matcher.Matchers.sameBeanAs
import org.hamcrest.CoreMatchers.equalTo
import org.junit.Assert.assertThat
import org.junit.Test
class SearchReducerTest {
@Test
fun returnsProperStateForSearchResultsAction() {
val aircraft = listOf(Aircraft())
val action = SearchResultsAction(aircraft)
val expected = SearchState.success(aircraft)
val actual = SearchReducer.reduce(SearchState.empty(), action)
assertThat(actual, sameBeanAs(expected))
}
@Test
fun returnsSameStateForSearchQueryChangedAction() {
val action = QueryChangedAction("query")
val expected = SearchState.empty()
val actual = SearchReducer.reduce(expected, action)
assertThat(actual, equalTo(expected))
}
} | recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/search/SearchReducerTest.kt | 2055883012 |
package com.example.subscriptions
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
@Entity
// These are mutable references here...
// Is there a better way to do this such that the
// Subscription is immutable???
data class Subscription(
@Id @GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
var id: Long = 0,
var userId: String = "",
var packageId: String = ""
)
| components/subscriptions/src/main/kotlin/com/example/subscriptions/Subscription.kt | 146062472 |
package org.wordpress.android.ui.avatars
import androidx.annotation.AttrRes
import androidx.annotation.DimenRes
import org.wordpress.android.R
import org.wordpress.android.ui.avatars.TrainOfAvatarsViewType.AVATAR
import org.wordpress.android.ui.avatars.TrainOfAvatarsViewType.TRAILING_LABEL
import org.wordpress.android.ui.utils.UiString
@DimenRes const val AVATAR_LEFT_OFFSET_DIMEN = R.dimen.margin_small_medium
@DimenRes const val AVATAR_SIZE_DIMEN = R.dimen.avatar_sz_small
sealed class TrainOfAvatarsItem(val type: TrainOfAvatarsViewType) {
data class AvatarItem(val userAvatarUrl: String) : TrainOfAvatarsItem(AVATAR)
data class TrailingLabelTextItem(val text: UiString, @AttrRes val labelColor: Int) : TrainOfAvatarsItem(
TRAILING_LABEL
)
}
enum class TrainOfAvatarsViewType {
AVATAR,
TRAILING_LABEL
}
| WordPress/src/main/java/org/wordpress/android/ui/avatars/TrainOfAvatarsItem.kt | 1017497614 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.optimizer
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.learningrate.LearningRateMethod
import com.kotlinnlp.simplednn.core.layers.models.feedforward.simple.FeedforwardLayerParameters
import com.kotlinnlp.simplednn.core.optimizer.ParamsOptimizer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class ParamsOptimizerSpec : Spek({
describe("a ParamsOptimizer") {
val learningRateMethod = LearningRateMethod(learningRate = 0.1)
context("update after accumulate") {
val optimizer = ParamsOptimizer(learningRateMethod)
val params: FeedforwardLayerParameters = ParamsOptimizerUtils.buildParams()
val gw1 = params.unit.weights.buildDenseErrors(ParamsOptimizerUtils.buildWeightsErrorsValues1())
val gb1 = params.unit.biases.buildDenseErrors(ParamsOptimizerUtils.buildBiasesErrorsValues1())
val gw2 = params.unit.weights.buildDenseErrors(ParamsOptimizerUtils.buildWeightsErrorsValues2())
val gb2 = params.unit.biases.buildDenseErrors(ParamsOptimizerUtils.buildBiasesErrorsValues2())
optimizer.accumulate(listOf(gw1, gb1, gw2, gb2))
optimizer.update()
val w: DenseNDArray = params.unit.weights.values
val b: DenseNDArray = params.unit.biases.values
it("should match the expected updated weights") {
assertTrue {
w.equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.2, 0.44, 0.17, -0.12),
doubleArrayOf(0.1, -0.15, 0.18, 0.56)
)),
tolerance = 1.0e-06
)
}
}
it("should match the expected updated biases") {
assertTrue {
b.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(0.36, -0.37)),
tolerance = 1.0e-06
)
}
}
}
}
})
| src/test/kotlin/core/optimizer/ParamsOptimizerSpec.kt | 755793468 |
package org.wordpress.android.ui.bloggingreminders
import org.wordpress.android.R
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.HighEmphasisText
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.Illustration
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.Title
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersViewModel.UiState.PrimaryButton
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.config.BloggingPromptsFeatureConfig
import javax.inject.Inject
class PrologueBuilder
@Inject constructor(private val bloggingPromptsFeatureConfig: BloggingPromptsFeatureConfig) {
fun buildUiItems(): List<BloggingRemindersItem> {
return if (bloggingPromptsFeatureConfig.isEnabled()) {
listOf(
Illustration(R.drawable.img_illustration_celebration_150dp),
Title(UiStringRes(R.string.set_your_blogging_prompts_title)),
HighEmphasisText(UiStringRes(R.string.post_publishing_set_up_blogging_prompts_message))
)
} else {
listOf(
Illustration(R.drawable.img_illustration_celebration_150dp),
Title(UiStringRes(R.string.set_your_blogging_reminders_title)),
HighEmphasisText(UiStringRes(R.string.post_publishing_set_up_blogging_reminders_message))
)
}
}
fun buildUiItemsForSettings(): List<BloggingRemindersItem> {
return if (bloggingPromptsFeatureConfig.isEnabled()) {
listOf(
Illustration(R.drawable.img_illustration_celebration_150dp),
Title(UiStringRes(R.string.set_your_blogging_prompts_title)),
HighEmphasisText(UiStringRes(R.string.post_publishing_set_up_blogging_prompts_message))
)
} else {
listOf(
Illustration(R.drawable.img_illustration_celebration_150dp),
Title(UiStringRes(R.string.set_your_blogging_reminders_title)),
HighEmphasisText(UiStringRes(R.string.set_up_blogging_reminders_message))
)
}
}
fun buildPrimaryButton(
isFirstTimeFlow: Boolean,
onContinue: (Boolean) -> Unit
): PrimaryButton {
return PrimaryButton(
UiStringRes(R.string.set_your_blogging_reminders_button),
enabled = true,
ListItemInteraction.create(isFirstTimeFlow, onContinue)
)
}
}
| WordPress/src/main/java/org/wordpress/android/ui/bloggingreminders/PrologueBuilder.kt | 1939824867 |
package com.pawegio.kandroid
import android.content.Context
import android.content.Intent
/**
* @author pawegio
*/
public inline fun IntentFor<reified T>(context: Context): Intent = Intent(context, javaClass<T>()) | kandroid/src/main/java/com/pawegio/kandroid/KIntent.kt | 2763465104 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.coroutine.data
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.JavaStackFrame
import com.intellij.debugger.engine.JavaValue
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener
import com.intellij.icons.AllIcons
import com.intellij.openapi.application.ReadAction
import com.intellij.xdebugger.XSourcePosition
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.impl.frame.XDebuggerFramesList
import com.sun.jdi.Location
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinDebuggerCoroutinesBundle
import org.jetbrains.kotlin.idea.debugger.coroutine.KotlinVariableNameFinder
import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeCoroutineStackFrameProxy
import org.jetbrains.kotlin.idea.debugger.base.util.safeLocation
import org.jetbrains.kotlin.idea.debugger.stackFrame.InlineStackTraceCalculator
import org.jetbrains.kotlin.idea.debugger.stackFrame.KotlinStackFrame
/**
* Coroutine exit frame represented by a stack frames
* invokeSuspend():-1
* resumeWith()
*
*/
class CoroutinePreflightFrame(
val coroutineInfoData: CoroutineInfoData,
val frame: StackFrameProxyImpl,
val threadPreCoroutineFrames: List<StackFrameProxyImpl>,
val mode: SuspendExitMode,
firstFrameVariables: List<JavaValue>
) : CoroutineStackFrame(frame, null, firstFrameVariables) {
override fun isInLibraryContent() = false
override fun isSynthetic() = false
}
class CreationCoroutineStackFrame(
frame: StackFrameProxyImpl,
sourcePosition: XSourcePosition?,
val first: Boolean,
location: Location? = frame.safeLocation()
) : CoroutineStackFrame(frame, sourcePosition, emptyList(), false, location), XDebuggerFramesList.ItemWithSeparatorAbove {
override fun getCaptionAboveOf() =
KotlinDebuggerCoroutinesBundle.message("coroutine.dump.creation.trace")
override fun hasSeparatorAbove() =
first
}
open class CoroutineStackFrame(
frame: StackFrameProxyImpl,
private val position: XSourcePosition?,
private val spilledVariables: List<JavaValue> = emptyList(),
private val includeFrameVariables: Boolean = true,
location: Location? = frame.safeLocation(),
) : KotlinStackFrame(
safeCoroutineStackFrameProxy(location, spilledVariables, frame),
if (spilledVariables.isEmpty() || includeFrameVariables) {
InlineStackTraceCalculator.calculateVisibleVariables(frame)
} else {
listOf()
}
) {
init {
descriptor.updateRepresentation(null, DescriptorLabelListener.DUMMY_LISTENER)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
val frame = other as? JavaStackFrame ?: return false
return descriptor.frameProxy == frame.descriptor.frameProxy
}
override fun hashCode(): Int {
return descriptor.frameProxy.hashCode()
}
override fun buildVariablesThreadAction(debuggerContext: DebuggerContextImpl, children: XValueChildrenList, node: XCompositeNode) {
if (includeFrameVariables || spilledVariables.isEmpty()) {
super.buildVariablesThreadAction(debuggerContext, children, node)
val debugProcess = debuggerContext.debugProcess ?: return
addOptimisedVariables(debugProcess, children)
} else {
// ignore original frame variables
for (variable in spilledVariables) {
children.add(variable)
}
}
}
private fun addOptimisedVariables(debugProcess: DebugProcessImpl, children: XValueChildrenList) {
val visibleVariableNames by lazy { children.getUniqueNames() }
for (variable in spilledVariables) {
val name = variable.name
if (name !in visibleVariableNames) {
children.add(variable)
visibleVariableNames.add(name)
}
}
val declaredVariableNames = findVisibleVariableNames(debugProcess)
for (name in declaredVariableNames) {
if (name !in visibleVariableNames) {
children.add(createOptimisedVariableMessageNode(name))
}
}
}
private fun createOptimisedVariableMessageNode(name: String) =
createMessageNode(
KotlinDebuggerCoroutinesBundle.message("optimised.variable.message", "\'$name\'"),
AllIcons.General.Information
)
private fun XValueChildrenList.getUniqueNames(): MutableSet<String> {
val names = mutableSetOf<String>()
for (i in 0 until size()) {
names.add(getName(i))
}
return names
}
private fun findVisibleVariableNames(debugProcess: DebugProcessImpl): List<String> {
val location = stackFrameProxy.safeLocation() ?: return emptyList()
return ReadAction.nonBlocking<List<String>> {
KotlinVariableNameFinder(debugProcess)
.findVisibleVariableNames(location)
}.executeSynchronously()
}
override fun getSourcePosition() =
position ?: super.getSourcePosition()
}
| plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/data/coroutineStackFrames.kt | 3291088195 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.project.impl.navigation
import com.intellij.navigation.LocationToOffsetConverter
import com.intellij.navigation.NavigatorWithinProject
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.containers.ComparatorUtil.max
import org.junit.ClassRule
import org.junit.Test
import kotlin.test.assertNull
class NavigatorWithinProjectTest: NavigationTestBase() {
companion object {
@JvmField @ClassRule val appRule = ApplicationRule()
}
@Test fun pathTabInLinePositionCharacterOneBased() = runNavigationTest(
navigationAction = { navigateByPath("A.java:3:20", locationToOffsetAsCharacterOneBased) }
) {
assertThat(getCurrentElement().containingFile.name).isEqualTo("A.java")
with(getCurrentCharacterZeroBasedPosition()) {
assertThat(line + 1).isEqualTo(3)
assertThat(column + 1).isEqualTo(20)
}
}
@Test fun pathTabInLinePositionLogical() = runNavigationTest(
navigationAction = { navigateByPath("A.java:2:10", locationToOffsetAsLogicalPosition) }
) {
assertThat(getCurrentElement().containingFile.name).isEqualTo("A.java")
with(getCurrentLogicalPosition()) {
assertThat(line).isEqualTo(2)
assertThat(column).isEqualTo(10)
}
}
@Test fun pathNegativeOffset() = runNavigationTest (
navigationAction = { navigateByPath("A.java:3:5", locationToOffsetNegativeOffset) }
) {
assertThat(getCurrentElement().containingFile.name).isEqualTo("A.java")
with(getCurrentCharacterZeroBasedPosition()) {
assertThat(line).isEqualTo(0)
assertThat(column).isEqualTo(0)
}
}
@Test fun pathNoColumn() = runNavigationTest(
navigationAction = { navigateByPath("A.java:3", locationToOffsetAsCharacterOneBased) }
) {
assertThat(getCurrentElement().containingFile.name).isEqualTo("A.java")
with(getCurrentCharacterZeroBasedPosition()) {
assertThat(line + 1).isEqualTo(3)
assertThat(column).isEqualTo(0)
}
}
@Test fun pathNoLineNoColumn() = runNavigationTest(
navigationAction = { navigateByPath("A.java", locationToOffsetAsCharacterOneBased) }
) {
assertThat(getCurrentElement().containingFile.name).isEqualTo("A.java")
with(getCurrentCharacterZeroBasedPosition()) {
assertThat(line).isEqualTo(0)
assertThat(column).isEqualTo(0)
}
}
@Test fun parseValidNavigationPathFull() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("A.java:1:10")
assertThat(file).isEqualTo("A.java")
assertThat(line).isEqualTo("1")
assertThat(column).isEqualTo("10")
}
@Test fun parseValidNavigationPathNoColumn() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("A.java:1")
assertThat(file).isEqualTo("A.java")
assertThat(line).isEqualTo("1")
assertNull(column)
}
@Test fun parseValidNavigationPathNoLineNoColumn() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("A.java")
assertThat(file).isEqualTo("A.java")
assertNull(line)
assertNull(column)
}
@Test fun parseInvalidNavigationPathNoFile() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath(":1:10")
assertNull(file)
assertNull(line)
assertNull(column)
}
@Test fun parseInvalidNavigationPathNoLine() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("A.java::10")
assertNull(file)
assertNull(line)
assertNull(column)
}
@Test fun parseInvalidNavigationPathNoValues() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("::")
assertNull(file)
assertNull(line)
assertNull(column)
}
@Test fun parseInvalidNavigationPathEmpty() {
val (file, line, column) = NavigatorWithinProject.parseNavigationPath("")
assertNull(file)
assertNull(line)
assertNull(column)
}
private fun navigateByPath(path: String, locationToOffsetConverter: LocationToOffsetConverter) =
NavigatorWithinProject(project, mapOf("path" to path), locationToOffsetConverter)
.navigate(listOf(NavigatorWithinProject.NavigationKeyPrefix.PATH))
private val locationToOffsetAsLogicalPosition: LocationToOffsetConverter = { locationInFile, editor ->
editor.logicalPositionToOffset(LogicalPosition(locationInFile.line, locationInFile.column))
}
private val locationToOffsetAsCharacterOneBased: LocationToOffsetConverter = { locationInFile, editor ->
val offsetOfLine = editor.logicalPositionToOffset(LogicalPosition(max(locationInFile.line - 1, 0), 0))
val offsetInLine = max(locationInFile.column - 1, 0)
offsetOfLine + offsetInLine
}
private val locationToOffsetNegativeOffset: LocationToOffsetConverter = { _, _ -> -1 }
} | platform/platform-tests/testSrc/com/intellij/openapi/project/impl/navigation/NavigatorWithinProjectTest.kt | 2930735315 |
// WITH_STDLIB
import java.util.*
fun foo() {
ArrayList<<caret>>
}
//Text: (<highlight>E</highlight>), Disabled: false, Strikeout: false, Green: false | plugins/kotlin/idea/tests/testData/parameterInfo/typeArguments/JavaClassNoParens.kt | 431819451 |
@Deprecated("lol no more mainstream", replaceWith = ReplaceWith(expression = "kek()"))
fun <caret>lol() {
println("lol")
}
//INFO: <div class='definition'><pre>@Deprecated(message = "lol no more mainstream", replaceWith = kotlin/ReplaceWith(expression = "kek()", ))
//INFO: fun lol(): Unit</pre></div><div class='bottom'><icon src="file"/> DeprecationWithReplaceInfo.kt<br/></div>
| plugins/kotlin/fir/testData/quickDoc/DeprecationWithReplaceInfo.kt | 2001541226 |
package com.eden.orchid.changelog.components
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.theme.components.OrchidComponent
import com.eden.orchid.changelog.model.ChangelogModel
import com.eden.orchid.utilities.resolve
@Description("Display the full changelog", name = "Changelog")
class ChangelogComponent : OrchidComponent("changelog") {
val model: ChangelogModel by lazy {
context.resolve<ChangelogModel>()
}
}
| plugins/OrchidChangelog/src/main/kotlin/com/eden/orchid/changelog/components/ChangelogComponent.kt | 901524657 |
package io.ipoli.android.player
import io.ipoli.android.MyPoliApp
import io.ipoli.android.common.view.asThemedWrapper
import io.ipoli.android.player.view.LevelUpPopup
import kotlinx.coroutines.experimental.Dispatchers
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.launch
/**
* Created by Venelin Valkov <[email protected]>
* on 11/15/17.
*/
interface LevelUpScheduler {
fun schedule(newLevel: Int)
}
class AndroidLevelUpScheduler : LevelUpScheduler {
override fun schedule(newLevel: Int) {
val c = MyPoliApp.instance.asThemedWrapper()
GlobalScope.launch(Dispatchers.Main) {
LevelUpPopup(newLevel).show(c)
}
}
} | app/src/main/java/io/ipoli/android/player/LevelUpScheduler.kt | 626797815 |
package csumissu.weatherforecast.di
import android.app.Application
import android.content.Context
import csumissu.weatherforecast.App
import csumissu.weatherforecast.model.ForecastDataSource
import csumissu.weatherforecast.model.ForecastDataStore
import csumissu.weatherforecast.model.local.ForecastLocalProvider
import csumissu.weatherforecast.model.remote.ForecastApi
import csumissu.weatherforecast.model.remote.ForecastRemoteProvider
import csumissu.weatherforecast.util.BaseSchedulerProvider
import csumissu.weatherforecast.util.SchedulerProvider
import dagger.BindsInstance
import dagger.Component
import dagger.Module
import dagger.Provides
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
/**
* @author yxsun
* @since 07/06/2017
*/
@Module
class AppModule {
@Provides
@Singleton
@ForApplication
fun provideAppContext(app: Application): Context = app.applicationContext
@Provides
@Singleton
@Remote
fun provideForecastRemoteProvider(): ForecastDataSource =
ForecastRemoteProvider(ForecastApi.getApiService())
@Provides
@Singleton
@Local
fun provideForecastLocalProvider(@ForApplication context: Context): ForecastDataStore =
ForecastLocalProvider(context)
@Provides
@Singleton
fun provideScheduleProvider(): BaseSchedulerProvider = SchedulerProvider()
}
@Singleton
@Component(modules = arrayOf(
AndroidSupportInjectionModule::class,
AppModule::class,
ViewModelModule::class,
MainUiModule::class
))
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
fun inject(app: App)
} | app/src/main/java/csumissu/weatherforecast/di/AppDagger.kt | 1263775737 |
import somePackage.NotExcludedClass
// "Import class 'NotExcludedClass'" "true"
// ERROR: Unresolved reference: NotExcludedClass
val x = <caret>NotExcludedClass()
/* IGNORE_FIR */ | plugins/kotlin/idea/tests/testData/quickfix/autoImports/notExcludedClass.after.kt | 1448329918 |
// WITH_STDLIB
fun test() {
arrayOf(1, 2, 3).size<caret> == 0
} | plugins/kotlin/code-insight/inspections-k2/tests/testData/inspectionsLocal/replaceSizeZeroCheckWithIsEmpty/array.kt | 2598713502 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring
import com.intellij.lang.refactoring.NamesValidator
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.junit.Assert
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class KotlinNamesValidatorTest : LightJavaCodeInsightFixtureTestCase() {
val validator: NamesValidator = KotlinNamesValidator()
private fun isKeyword(string: String) = validator.isKeyword(string, null)
private fun isIdentifier(string: String) = validator.isIdentifier(string, null)
override fun setUp() {
super.setUp()
myFixture.configureByFiles()
}
fun testKeywords() {
Assert.assertTrue(isKeyword("val"))
Assert.assertTrue(isKeyword("class"))
Assert.assertTrue(isKeyword("fun"))
Assert.assertFalse(isKeyword("constructor"))
Assert.assertFalse(isKeyword("123"))
Assert.assertFalse(isKeyword("a.c"))
Assert.assertFalse(isKeyword("-"))
}
fun testIdentifiers() {
Assert.assertTrue(isIdentifier("abc"))
Assert.assertTrue(isIdentifier("q_q"))
Assert.assertTrue(isIdentifier("constructor"))
Assert.assertTrue(isIdentifier("`val`"))
Assert.assertFalse(isIdentifier("val"))
Assert.assertFalse(isIdentifier("class"))
Assert.assertFalse(isIdentifier("fun"))
Assert.assertFalse(isIdentifier("123"))
Assert.assertFalse(isIdentifier("a.c"))
Assert.assertFalse(isIdentifier("-"))
Assert.assertFalse(isIdentifier("``"))
Assert.assertFalse(isIdentifier(""))
Assert.assertFalse(isIdentifier(" '"))
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/KotlinNamesValidatorTest.kt | 1799552290 |
package test
import junit.framework.TestCase
import org.junit.Test
class BarNew {
}
class FooBarBazTestCaseNew : TestCase() {
}
class BazBarFooTestNew {
@Test fun testFoo() {}
} | plugins/kotlin/idea/tests/testData/refactoring/rename/automaticRenamerKotlinTestClass/after/test/test.kt | 1818212526 |
/*
* Copyright (C) 2018 Jhon Kenneth Carino
*
* 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.jkcarino.ankieditor.ui.editor
import android.app.Activity
import android.content.Intent
import com.jkcarino.ankieditor.ui.richeditor.RichEditorActivity
import com.jkcarino.ankieditor.util.AnkiDroidHelper
import com.jkcarino.ankieditor.util.PlayStoreUtils
import pub.devrel.easypermissions.AppSettingsDialog
class EditorPresenter(
private var editorView: EditorContract.View?,
private var ankiDroidHelper: AnkiDroidHelper?
) : EditorContract.Presenter {
/** ID of the selected note type */
override var currentNoteTypeId: Long = 0L
/** ID of the selected deck */
override var currentDeckId: Long = 0L
init {
editorView?.setPresenter(this)
}
override fun start() {
}
override fun stop() {
editorView = null
ankiDroidHelper = null
}
override fun setupNoteTypesAndDecks() {
editorView?.let { view ->
try {
// Display all note types
ankiDroidHelper?.noteTypes?.let { noteTypes ->
val noteTypeIds = ArrayList<Long>(noteTypes.keys)
val noteTypesList = ArrayList<String>(noteTypes.values)
view.showNoteTypes(noteTypeIds, noteTypesList)
}
// Display all note decks
ankiDroidHelper?.noteDecks?.let { noteDecks ->
val noteDeckIds = ArrayList<Long>(noteDecks.keys)
val noteDecksList = ArrayList<String>(noteDecks.values)
view.showNoteDecks(noteDeckIds, noteDecksList)
}
} catch (e: IllegalStateException) {
view.showAnkiDroidError(e.localizedMessage)
}
}
}
override fun populateNoteTypeFields() {
editorView?.let { view ->
ankiDroidHelper?.getNoteTypeFields(currentNoteTypeId)?.let { fields ->
view.showNoteTypeFields(fields)
}
}
}
override fun result(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
PlayStoreUtils.RC_OPEN_PLAY_STORE -> {
editorView?.checkAnkiDroidAvailability()
}
AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE -> {
editorView?.checkAnkiDroidReadWritePermission()
}
EditorFragment.RC_FIELD_EDIT -> {
if (resultCode == Activity.RESULT_OK) {
data?.extras?.let {
val index = it.getInt(RichEditorActivity.EXTRA_FIELD_INDEX)
val text = it.getString(RichEditorActivity.EXTRA_FIELD_TEXT, "")
editorView?.setRichEditorFieldText(index, text)
}
}
}
}
}
override fun insertClozeAround(
index: Int,
text: String,
selectionStart: Int,
selectionEnd: Int
) {
editorView?.let { view ->
val selectionMin = Math.min(selectionStart, selectionEnd)
val selectionMax = Math.max(selectionStart, selectionEnd)
val insertedCloze = (text.substring(0, selectionMin)
+ "{{c1::" + text.substring(selectionMin, selectionMax)
+ "}}" + text.substring(selectionMax))
view.setInsertedClozeText(index, insertedCloze)
}
}
override fun addNote(fields: Array<String?>) {
editorView?.let { view ->
val noteId = ankiDroidHelper?.api?.addNote(
currentNoteTypeId,
currentDeckId,
fields,
null
)
if (noteId != null) {
view.setAddNoteSuccess()
} else {
view.setAddNoteFailure()
}
}
}
}
| app/src/main/java/com/jkcarino/ankieditor/ui/editor/EditorPresenter.kt | 2156644972 |
// 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.ui.layout
import com.intellij.openapi.application.invokeAndWaitIfNeed
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.ui.UiTestRule
import com.intellij.ui.changeLafIfNeed
import com.intellij.ui.layout.migLayout.patched.*
import org.junit.*
import org.junit.Assume.assumeTrue
import org.junit.rules.TestName
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.nio.file.Paths
import javax.swing.JPanel
/**
* Set `test.update.snapshots=true` to automatically update snapshots if need.
*/
@RunWith(Parameterized::class)
class UiDslTest {
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun lafNames() = listOf("Darcula", "IntelliJ")
@JvmField
@ClassRule
val uiRule = UiTestRule(Paths.get(PlatformTestUtil.getPlatformTestDataPath(), "ui", "layout"))
init {
System.setProperty("idea.ui.set.password.echo.char", "true")
}
}
@Suppress("MemberVisibilityCanBePrivate")
@Parameterized.Parameter
lateinit var lafName: String
@Rule
@JvmField
val testName = TestName()
@Before
fun beforeMethod() {
if (UsefulTestCase.IS_UNDER_TEAMCITY) {
assumeTrue("macOS or Windows 10 are required", SystemInfoRt.isMac || SystemInfo.isWin10OrNewer)
}
System.setProperty("idea.ui.comment.copyable", "false")
changeLafIfNeed(lafName)
}
@After
fun afterMethod() {
System.clearProperty("idea.ui.comment.copyable")
}
@Test
fun `align fields in the nested grid`() {
doTest { alignFieldsInTheNestedGrid() }
}
@Test
fun `align fields`() {
doTest { labelRowShouldNotGrow() }
}
@Test
fun cell() {
doTest { cellPanel() }
}
@Test
fun `note row in the dialog`() {
doTest { noteRowInTheDialog() }
}
@Test
fun `visual paddings`() {
doTest { visualPaddingsPanel() }
}
@Test
fun `vertical buttons`() {
doTest { withVerticalButtons() }
}
@Test
fun `do not add visual paddings for titled border`() {
doTest { commentAndPanel() }
}
private fun doTest(panelCreator: () -> JPanel) {
invokeAndWaitIfNeed {
val panel = panelCreator()
// otherwise rectangles are not set
(panel.layout as MigLayout).isDebugEnabled = true
uiRule.validate(panel, testName, lafName)
}
}
} | platform/platform-tests/testSrc/com/intellij/ui/layout/UiDslTest.kt | 71751572 |
package org.thoughtcrime.securesms.keyboard.emoji
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import com.google.android.material.appbar.AppBarLayout
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.EmojiEventListener
import org.thoughtcrime.securesms.components.emoji.EmojiPageView
import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter
import org.thoughtcrime.securesms.components.emoji.EmojiPageViewGridAdapter.EmojiHeader
import org.thoughtcrime.securesms.keyboard.KeyboardPageSelected
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.ThemedFragment.themedInflate
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.fragments.requireListener
import java.util.Optional
private val DELETE_KEY_EVENT: KeyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)
class EmojiKeyboardPageFragment : Fragment(), EmojiEventListener, EmojiPageViewGridAdapter.VariationSelectorListener, KeyboardPageSelected {
private lateinit var viewModel: EmojiKeyboardPageViewModel
private lateinit var emojiPageView: EmojiPageView
private lateinit var searchView: View
private lateinit var emojiCategoriesRecycler: RecyclerView
private lateinit var backspaceView: View
private lateinit var eventListener: EmojiEventListener
private lateinit var callback: Callback
private lateinit var categoriesAdapter: EmojiKeyboardPageCategoriesAdapter
private lateinit var searchBar: KeyboardPageSearchView
private lateinit var appBarLayout: AppBarLayout
private val categoryUpdateOnScroll = UpdateCategorySelectionOnScroll()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return themedInflate(R.layout.keyboard_pager_emoji_page_fragment, inflater, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
callback = requireNotNull(requireListener())
emojiPageView = view.findViewById(R.id.emoji_page_view)
emojiPageView.initialize(this, this, true)
emojiPageView.addOnScrollListener(categoryUpdateOnScroll)
searchView = view.findViewById(R.id.emoji_search)
searchBar = view.findViewById(R.id.emoji_keyboard_search_text)
emojiCategoriesRecycler = view.findViewById(R.id.emoji_categories_recycler)
backspaceView = view.findViewById(R.id.emoji_backspace)
appBarLayout = view.findViewById(R.id.emoji_keyboard_search_appbar)
}
@Suppress("DEPRECATION")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(requireActivity(), EmojiKeyboardPageViewModel.Factory(requireContext()))
.get(EmojiKeyboardPageViewModel::class.java)
categoriesAdapter = EmojiKeyboardPageCategoriesAdapter { key ->
scrollTo(key)
viewModel.onKeySelected(key)
}
emojiCategoriesRecycler.adapter = categoriesAdapter
searchBar.callbacks = EmojiKeyboardPageSearchViewCallbacks()
searchView.setOnClickListener {
callback.openEmojiSearch()
}
backspaceView.setOnClickListener { eventListener.onKeyEvent(DELETE_KEY_EVENT) }
viewModel.categories.observe(viewLifecycleOwner) { categories ->
categoriesAdapter.submitList(categories) {
(emojiCategoriesRecycler.parent as View).invalidate()
emojiCategoriesRecycler.parent.requestLayout()
}
}
viewModel.pages.observe(viewLifecycleOwner) { pages ->
emojiPageView.setList(pages) { (emojiPageView.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(1, 0) }
}
viewModel.selectedKey.observe(viewLifecycleOwner) { updateCategoryTab(it) }
eventListener = requireListener()
}
override fun onResume() {
super.onResume()
viewModel.refreshRecentEmoji()
}
override fun onPageSelected() {
viewModel.refreshRecentEmoji()
}
private fun updateCategoryTab(key: String) {
emojiCategoriesRecycler.post {
val index: Int = categoriesAdapter.indexOfFirst(EmojiKeyboardPageCategoryMappingModel::class.java) { it.key == key }
if (index != -1) {
emojiCategoriesRecycler.smoothScrollToPosition(index)
}
}
}
private fun scrollTo(key: String) {
emojiPageView.adapter?.let { adapter ->
val index = adapter.indexOfFirst(EmojiHeader::class.java) { it.key == key }
if (index != -1) {
appBarLayout.setExpanded(false, true)
categoryUpdateOnScroll.startAutoScrolling()
emojiPageView.smoothScrollToPositionTop(index)
}
}
}
override fun onEmojiSelected(emoji: String) {
SignalStore.emojiValues().setPreferredVariation(emoji)
eventListener.onEmojiSelected(emoji)
}
override fun onKeyEvent(keyEvent: KeyEvent?) {
eventListener.onKeyEvent(keyEvent)
}
override fun onVariationSelectorStateChanged(open: Boolean) = Unit
private inner class EmojiKeyboardPageSearchViewCallbacks : KeyboardPageSearchView.Callbacks {
override fun onClicked() {
callback.openEmojiSearch()
}
}
private inner class UpdateCategorySelectionOnScroll : RecyclerView.OnScrollListener() {
private var doneScrolling: Boolean = true
fun startAutoScrolling() {
doneScrolling = false
}
@Override
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (newState == SCROLL_STATE_IDLE && !doneScrolling) {
doneScrolling = true
onScrolled(recyclerView, 0, 0)
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (recyclerView.layoutManager == null || !doneScrolling) {
return
}
emojiPageView.adapter?.let { adapter ->
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
val index = layoutManager.findFirstCompletelyVisibleItemPosition()
val item: Optional<MappingModel<*>> = adapter.getModel(index)
if (item.isPresent && item.get() is EmojiPageViewGridAdapter.HasKey) {
viewModel.onKeySelected((item.get() as EmojiPageViewGridAdapter.HasKey).key)
}
}
}
}
interface Callback {
fun openEmojiSearch()
}
}
| app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/EmojiKeyboardPageFragment.kt | 3540724041 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.RsTraitItem
interface RsStructOrEnumItemElement : RsQualifiedNamedElement, RsTypeBearingItemElement, RsGenericDeclaration
val RsStructOrEnumItemElement.derivedTraits: List<RsTraitItem>
get() = queryAttributes
.deriveAttribute
?.metaItemArgs
?.metaItemList
?.mapNotNull { it.reference.resolve() as? RsTraitItem }
?: emptyList()
| src/main/kotlin/org/rust/lang/core/psi/ext/RsStructOrEnumItemElement.kt | 3079917821 |
package lt.markmerkk.migration
import java.io.File
object ConfigUtils {
fun listConfigs(configDir: File): List<File> {
return if (configDir.exists() && configDir.isDirectory) {
configDir.listFiles()?.asList() ?: emptyList()
} else {
emptyList()
}
}
} | components/src/main/java/lt/markmerkk/migration/ConfigUtils.kt | 1059415064 |
package api.doc.swagger
/**
* Created by kk on 17/4/5.
*/
class Items {
// Required. The internal type of the array.
// The value MUST be one of "string", "number", "integer", "boolean", or "array". Files and models are not allowed.
var type: String = ""
// The extending format for the previously mentioned type. See Data Type Formats for further details.
var format: String? = null
// Required if type is "array". Describes the type of items in the array.
var items: Items? = null
// Determines the format of the array if type array is used. Possible values are:
// csv - comma separated values foo,bar.
// ssv - space separated values foo bar.
// tsv - tab separated values foo\tbar.
// pipes - pipe separated values foo|bar.
// Default value is csv.
var collectionFormat: String = "csv"
var default:Any? = null
var maximum: Number? = null
var exclusiveMaximum: Boolean? = null
var minimum: Number? = null
var exclusiveMinimum: Boolean? = null
var maxLength: Int? = null
var minLength: Int? = null
var pattern: String? = null
var maxItems: Int? = null
var minItems: Int? = null
var uniqueItems: Boolean? = null
var enum: List<Any>? = null
var multipleOf: Number? = null
} | src/main/kotlin/api/doc/swagger/Items.kt | 3905773000 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.tests.routing
import io.ktor.server.routing.*
import kotlin.test.*
internal class RouteSelectorTest {
@Test
fun testEvaluateWithPrefixAndSuffixMatched() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("prefixPARAMsuffix"),
segmentIndex = 0,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = false
)
assertTrue(evaluation is RouteSelectorEvaluation.Success)
assertEquals(evaluation.quality, RouteSelectorEvaluation.qualityParameterWithPrefixOrSuffix)
assertEquals(evaluation.succeeded, true)
assertEquals(evaluation.parameters["param"], "PARAM")
}
@Test
fun testEvaluateWithPrefixNotMatched() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("1prefixPARAMsuffix"),
segmentIndex = 0,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = false
)
assertEquals(evaluation, RouteSelectorEvaluation.FailedPath)
}
@Test
fun testEvaluateWithSuffixNotMatched() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("prefixPARAMsuffix1"),
segmentIndex = 0,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = false
)
assertEquals(evaluation, RouteSelectorEvaluation.FailedPath)
}
@Test
fun testEvaluateWithoutPrefixOrSuffix() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("PARAM"),
segmentIndex = 0,
name = "param",
isOptional = false
)
assertTrue(evaluation is RouteSelectorEvaluation.Success)
assertEquals(evaluation.succeeded, true)
assertEquals(evaluation.quality, RouteSelectorEvaluation.qualityParameter)
}
@Test
fun testEvaluateWithSegmentIndexOutsideOfSegments() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("prefixPARAMsuffix"),
segmentIndex = 1,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = false
)
assertEquals(evaluation, RouteSelectorEvaluation.FailedPath)
}
@Test
fun testEvaluateWithPrefixNotMatchedOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("1prefixPARAMsuffix"),
segmentIndex = 0,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = true
)
assertEquals(evaluation, RouteSelectorEvaluation.Missing)
}
@Test
fun testEvaluateWithSuffixNotMatchedOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("prefixPARAMsuffix1"),
segmentIndex = 0,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = true
)
assertEquals(evaluation, RouteSelectorEvaluation.Missing)
}
@Test
fun testEvaluateWithSegmentIndexOutsideOfSegmentsOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("prefixPARAMsuffix"),
segmentIndex = 1,
name = "param",
prefix = "prefix",
suffix = "suffix",
isOptional = true
)
assertEquals(evaluation, RouteSelectorEvaluation.Missing)
}
@Test
fun testEvaluateWithTrailingSlashAndOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("foo", ""),
segmentIndex = 1,
name = "param",
isOptional = true
)
assertEquals(
evaluation,
RouteSelectorEvaluation
.Success(RouteSelectorEvaluation.qualityMissing, segmentIncrement = 1)
)
}
@Test
fun testEvaluateWithoutTrailingSlashAndOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("foo"),
segmentIndex = 1,
name = "param",
isOptional = true
)
assertEquals(evaluation, RouteSelectorEvaluation.Missing)
}
@Test
fun testEvaluateWithTrailingSlashAndNonOptional() {
val evaluation = evaluatePathSegmentParameter(
segments = listOf("foo", ""),
segmentIndex = 1,
name = "param",
isOptional = false
)
assertEquals(evaluation, RouteSelectorEvaluation.FailedPath)
}
}
| ktor-server/ktor-server-core/jvmAndNix/test/io/ktor/server/routing/RouteSelectorTest.kt | 1891337987 |
package com.beust.kobalt.misc
import com.beust.kobalt.KobaltException
import com.google.inject.Singleton
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
@Singleton
class LocalProperties {
val localProperties: Properties by lazy {
val result = Properties()
val filePath = Paths.get("local.properties")
filePath.let { path ->
if (path.toFile().exists()) {
Files.newInputStream(path).use {
result.load(it)
}
}
}
result
}
fun getNoThrows(name: String, docUrl: String? = null) = localProperties.getProperty(name)
fun get(name: String, docUrl: String? = null) : String {
val result = getNoThrows(name, docUrl)
?: throw KobaltException("Couldn't find $name in local.properties", docUrl = docUrl)
return result as String
}
}
| modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/LocalProperties.kt | 509108628 |
/*
* The MIT License
*
* Copyright (c) 2015 Misakura.
*
* 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 jp.gr.java_conf.kgd.library.buckets.libgdx.util.scripts
import groovy.util.ResourceConnector
import groovy.util.ResourceException
import jp.gr.java_conf.kgd.library.buckets.libgdx.util.config.BaseConfigProvider
import jp.gr.java_conf.kgd.library.buckets.libgdx.util.files.FileHandleResolverProvider
import java.net.URLConnection
class DefaultResourceConnector : ResourceConnector {
override fun getResourceConnection(name: String?): URLConnection? {
val rootPath = BaseConfigProvider.getBaseConfig().getScriptsDirectoryPath()
val fileHandle = FileHandleResolverProvider.getFileHandleResolver().resolve(rootPath + name) ?: throw ResourceException()
return fileHandle.file().toURI().toURL().openConnection()
}
} | libgdx/util/util/src/main/kotlin/jp/gr/java_conf/kgd/library/buckets/libgdx/util/scripts/DefaultResourceConnector.kt | 38392038 |
package io.armcha.ribble.domain.interactor
import io.armcha.ribble.data.network.ApiConstants
import io.armcha.ribble.di.scope.PerActivity
import io.armcha.ribble.domain.entity.Shot
import io.armcha.ribble.domain.repository.ShotRepository
import io.reactivex.Flowable
import javax.inject.Inject
/**
* Created by Chatikyan on 02.08.2017.
*/
@PerActivity
class ShotListInteractor @Inject constructor(private val shotRepository: ShotRepository) {
fun popularShotList(count: Int = 500): Flowable<List<Shot>> {
return shotRepository.getShotList(ApiConstants.TYPE_POPULAR, count)
}
fun recentShotList(count: Int = 500): Flowable<List<Shot>> {
return shotRepository.getShotList(ApiConstants.TYPE_RECENT, count)
}
} | app/src/main/kotlin/io/armcha/ribble/domain/interactor/ShotListInteractor.kt | 1695441922 |
package com.airbnb.lottie.snapshots.tests
import com.airbnb.lottie.snapshots.SnapshotTestCase
import com.airbnb.lottie.snapshots.SnapshotTestCaseContext
import com.airbnb.lottie.snapshots.withDrawable
class PartialFrameProgressTestCase : SnapshotTestCase {
override suspend fun SnapshotTestCaseContext.run() {
withDrawable("Tests/2FrameAnimation.json", "Float Progress", "0") { drawable ->
drawable.progress = 0f
}
withDrawable("Tests/2FrameAnimation.json", "Float Progress", "0.25") { drawable ->
drawable.progress = 0.25f
}
withDrawable("Tests/2FrameAnimation.json", "Float Progress", "0.5") { drawable ->
drawable.progress = 0.5f
}
withDrawable("Tests/2FrameAnimation.json", "Float Progress", "1.0") { drawable ->
drawable.progress = 1f
}
}
} | snapshot-tests/src/androidTest/java/com/airbnb/lottie/snapshots/tests/PartialFrameProgressTestCase.kt | 1904358030 |
// View diseases a plant can get
// @author: Antonio Muscarella & Iskander Gaba
package com.scientists.happy.botanist.ui
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.scientists.happy.botanist.R
import com.scientists.happy.botanist.controller.ActivityController
import com.scientists.happy.botanist.controller.DiseaseController
class DiseaseActivity : AppCompatActivity() {
private var mController:ActivityController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_disease)
mController = DiseaseController(this)
}
override fun onStart() {
mController!!.load()
super.onStart()
}
override fun onSupportNavigateUp(): Boolean {
super.onBackPressed()
return true
}
} | app/src/main/java/com/scientists/happy/botanist/ui/DiseaseActivity.kt | 2564226866 |
package ru.bozaro.gitlfs.client.exceptions
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpUriRequest
/**
* Unauthorized HTTP exception.
*
* @author Artem V. Navrotskiy
*/
class UnauthorizedException(request: HttpUriRequest, response: HttpResponse) : RequestException(request, response)
| gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/exceptions/UnauthorizedException.kt | 939281743 |
package org.growingstems.scouting
import androidx.appcompat.widget.AppCompatImageButton
import android.widget.ImageButton
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import java.util.ArrayList
class SuperImageButton : AppCompatImageButton {
private val memberImgs: MutableList<ImageButton> = ArrayList()
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
fun clearImageButtons() {
memberImgs.clear()
}
fun addImageButton(img: ImageButton) {
memberImgs.add(img)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
for (button in memberImgs) {
button.dispatchTouchEvent(event)
}
return super.onTouchEvent(event)
}
}
| app/src/main/java/org/growingstems/scouting/SuperImageButton.kt | 2152785998 |
/*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.data.remote.entity.mapper
import com.ayatk.biblio.data.remote.entity.NarouIndex
import com.ayatk.biblio.infrastructure.database.entity.IndexEntity
import com.ayatk.biblio.infrastructure.database.entity.enums.ReadingState
import java.util.*
fun List<NarouIndex>.toEntity(): List<IndexEntity> =
map {
IndexEntity(
id = UUID.nameUUIDFromBytes("${it.ncode}-${it.page}".toByteArray()),
code = it.ncode,
subtitle = it.title,
page = it.page,
chapter = it.chapter,
readingState = ReadingState.UNREAD,
publishDate = it.publishDate,
lastUpdate = it.lastUpdate
)
}
| app/src/main/kotlin/com/ayatk/biblio/data/remote/entity/mapper/IndexMapper.kt | 2469984943 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.