repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
luhaoaimama1/AndroidZone
JavaTest_Zone/src/kotlinHolderPayloads/可见性更改/ShowHideArrayList.kt
2
2464
/* * Copyright (c) 2015-2019 BiliBili Inc. */ package com.bilibili.bplus.followingcard.helper.sys /* * [19-4-29] by Zone */ fun main(args: Array<String>) { val arrlist = ShowHideArrayList<String>() arrlist.visibilityListener=object : ShowHideArrayList.VisibilityListener<String> { override fun hide(data: String) { println("hide:$data") } override fun show(data: String) { println("show:$data") } } val a1="1" val a2="2" val a3="3" val a4="4" arrlist.beginLoop() arrlist.loopShow(a1) arrlist.loopShow(a2) arrlist.loopShow(a3) arrlist.loopShow(a4) arrlist.endLoop() println("预期结果——show: 1,2,3,4") arrlist.beginLoop() arrlist.loopShow(a1) arrlist.loopShow(a2) arrlist.loopShow(a4) arrlist.endLoop() println("预期结果——hide:3") val a5="5" arrlist.beginLoop() arrlist.loopShow(a1) arrlist.loopShow(a2) arrlist.loopShow(a5) arrlist.endLoop() println("预期结果——show:5,hide:4") } class ShowHideArrayList<E> : ArrayList<E>() { var removeVisiIndex = -1 var visibilityListener: VisibilityListener<E>? = null fun beginLoop() { // [A.B..removeVisiIndex] 这时候来个可见B 序列变为[A...removeVisiIndex,B],要移除的就是A...removeVisiIndex // 总结 就是 [0,removeVisiIndex] 要移除,(removeVisiIndex,size)之后的是可见的数据 removeVisiIndex = size - 1 } fun loopShow(data: E) { val index = indexOf(data) if (index != -1) { if (index <= removeVisiIndex) { //数据有,但是小于限定移除的index,把数据移动到最后的为止,并把index向前移动 removeVisiIndex-- remove(data) add(data) } else { // 如果数据 有,并且是限定移除的index之后 则不管 } }else{ add(data) visibilityListener?.show(data) } } fun endLoop() { //倒序移除 可见列表中的 不可见数据 for (index in removeVisiIndex downTo 0) { //可以触发不可见 val element = get(index) visibilityListener?.hide(element) remove(element) } } interface VisibilityListener<E> { fun show(data: E) fun hide(data: E) } }
epl-1.0
3645ee1a3006a47720a95e4ba912d0fa
23.119565
96
0.56853
3.168571
false
false
false
false
google/grpc-kapt
example-with-google-api/src/main/kotlin/com/google/api/example/Example.kt
1
2373
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.example import com.google.api.grpc.kapt.GrpcClient import com.google.api.grpc.kapt.GrpcMarshaller import com.google.auth.oauth2.GoogleCredentials import com.google.cloud.language.v1.AnalyzeEntitiesRequest import com.google.cloud.language.v1.Document import com.google.protobuf.Message import io.grpc.CallOptions import io.grpc.MethodDescriptor import io.grpc.auth.MoreCallCredentials import io.grpc.protobuf.ProtoUtils import kotlinx.coroutines.runBlocking /** * You must set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to use a * valid credentials file and have permission to use the [Language API](https://cloud.google.com/natural-language). */ fun main(): Unit = runBlocking { // configure the client to use Google auth credentials val options = CallOptions.DEFAULT .withCallCredentials( MoreCallCredentials.from( GoogleCredentials.getApplicationDefault() ) ) LanguageService.forAddress("language.googleapis.com", 443, callOptions = options).use { client -> val response = client.analyzeEntities(with(AnalyzeEntitiesRequest.newBuilder()) { document = with(Document.newBuilder()) { content = "Hi there Joe!" type = Document.Type.PLAIN_TEXT build() } build() }) println(response) } } // generate a gRPC client @GrpcClient(definedBy = "google.cloud.language.v1.LanguageService") interface GoogleLanguageService @GrpcMarshaller object MyMarshallerProvider { @Suppress("UNCHECKED_CAST") fun <T : Message> of(type: Class<T>): MethodDescriptor.Marshaller<T> = ProtoUtils.marshaller(type.getMethod("getDefaultInstance").invoke(null) as T) }
apache-2.0
9cf4464c1ad220f8ff721e09ae9ac780
34.954545
115
0.717657
4.283394
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/declarations/XpCommand.kt
1
1400
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.declarations import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper import net.perfectdreams.loritta.common.commands.CommandCategory import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.ViewXpExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.xprank.XpRankExecutor import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.common.locale.LanguageManager import net.perfectdreams.loritta.common.utils.TodoFixThisData class XpCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) { companion object { val XP_VIEW_I18N_PREFIX = I18nKeysData.Commands.Command.Xpview val XP_RANK_I18N_PREFIX = I18nKeysData.Commands.Command.Xprank val I18N_PREFIX = I18nKeysData.Commands.Command.Xp } override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.SOCIAL, TodoFixThisData) { dmPermission = false subcommand(XP_VIEW_I18N_PREFIX.Label, XP_VIEW_I18N_PREFIX.Description) { executor = { ViewXpExecutor(it) } } subcommand(XP_RANK_I18N_PREFIX.Label, XP_RANK_I18N_PREFIX.Description) { executor = { XpRankExecutor(it) } } } }
agpl-3.0
bcf23cb99561f530852d2c27c145b2ae
47.310345
110
0.781429
4.057971
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/social/RepCommand.kt
1
3731
package net.perfectdreams.loritta.morenitta.commands.vanilla.social import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.dao.Reputation import net.perfectdreams.loritta.morenitta.tables.Reputations import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.DateUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.commands.arguments import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.utils.AccountUtils import net.perfectdreams.loritta.common.utils.Emotes import net.perfectdreams.loritta.morenitta.LorittaBot class RepCommand(loritta: LorittaBot) : AbstractCommand(loritta, "rep", listOf("reputation", "reputação", "reputacao"), net.perfectdreams.loritta.common.commands.CommandCategory.SOCIAL) { override fun getDescriptionKey() = LocaleKeyData("commands.command.reputation.description") override fun getExamplesKey() = LocaleKeyData("commands.command.reputation.examples") override fun canUseInPrivateChannel(): Boolean { return false } override fun getUsage() = arguments { argument(ArgumentType.USER) {} } override suspend fun run(context: CommandContext, locale: BaseLocale) { val arg0 = context.rawArgs.getOrNull(0) val user = context.getUserAt(0) val lastReputationGiven = loritta.newSuspendedTransaction { Reputation.find { (Reputations.givenById eq context.userHandle.idLong) }.sortedByDescending { it.receivedAt }.firstOrNull() } if (lastReputationGiven != null) { val diff = System.currentTimeMillis() - lastReputationGiven.receivedAt if (3_600_000 > diff) { val fancy = DateUtils.formatDateDiff(lastReputationGiven.receivedAt + 3.6e+6.toLong(), locale) context.sendMessage(Constants.ERROR + " **|** " + context.getAsMention(true) + context.locale["commands.command.reputation.wait", fancy]) return } } if (user != null) { if (user == context.userHandle) { context.reply( LorittaReply( message = locale["commands.command.reputation.repSelf"], prefix = Constants.ERROR ) ) return } val dailyReward = AccountUtils.getUserTodayDailyReward(loritta, context.lorittaUser.profile) if (dailyReward == null) { // Nós apenas queremos permitir que a pessoa aposte na rifa caso já tenha pegado sonhos alguma vez hoje context.reply( LorittaReply( locale["commands.youNeedToGetDailyRewardBeforeDoingThisAction", context.config.commandPrefix], Constants.ERROR ) ) return } var url = "${loritta.config.loritta.website.url}user/${user.id}/rep" if (!context.isPrivateChannel) url += "?guild=${context.guild.id}&channel=${context.message.channel.id}" context.reply( LorittaReply( locale["commands.command.reputation.reputationLink", url], Emotes.LORI_HAPPY ) ) } else { if (context.args.isEmpty()) { this.explain(context) } else { context.reply( LorittaReply( message = locale["commands.userDoesNotExist", arg0?.stripCodeMarks()], prefix = Constants.ERROR ) ) } } } }
agpl-3.0
1bbd9399cd6ab91a86315591cff26fab
37.43299
187
0.699759
4.18764
false
false
false
false
indy256/codelibrary
kotlin/Determinant.kt
1
947
import kotlin.math.abs // https://en.wikipedia.org/wiki/Determinant fun det(matrix: Array<DoubleArray>): Double { val EPS = 1e-10 val a = matrix.map { it.copyOf() }.toTypedArray() val n = a.size var res = 1.0 for (i in 0 until n) { val p = (i until n).maxByOrNull { abs(a[it][i]) }!! if (abs(a[p][i]) < EPS) return 0.0 if (i != p) { res = -res a[i] = a[p].also { a[p] = a[i] } } res *= a[i][i] for (j in i + 1 until n) a[i][j] /= a[i][i] for (j in 0 until n) if (j != i && abs(a[j][i]) > EPS /*optimizes overall complexity to O(n^2) for sparse matrices*/) for (k in i + 1 until n) a[j][k] -= a[i][k] * a[j][i] } return res } // Usage example fun main() { val d = det(arrayOf(doubleArrayOf(0.0, 1.0), doubleArrayOf(-1.0, 0.0))) println(abs(d - 1) < 1e-10) }
unlicense
611fa1203711ac434a68b99a39dd4a4b
28.59375
108
0.469905
2.896024
false
false
false
false
spaceisstrange/ToListen
ToListen/app/src/main/java/io/spaceisstrange/tolisten/data/model/Album.kt
1
1898
/* * Made with <3 by Fran González (@spaceisstrange) * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package io.spaceisstrange.tolisten.data.model import io.realm.RealmModel import io.realm.annotations.PrimaryKey import io.realm.annotations.RealmClass /** * Represents an album in the database by its artist, name, album art (cover) URL and track-list */ @RealmClass open class Album() : RealmModel { @PrimaryKey open var id: String = "0" open var artist: Artist? = null open var name: String? = null open var coverUrl: String? = null /** * Adds an ID to the current instance and returns it */ fun id(id: String): Album { this.id = id return this } /** * Adds an artist to the current instance and returns it */ fun artist(artist: Artist): Album { this.artist = artist return this } /** * Adds a name to the current instance and returns it */ fun name(name: String): Album { this.name = name return this } /** * Adds a cover URL to the current instance and returns it */ fun coverUrl(url: String): Album { this.coverUrl = url return this } }
gpl-3.0
a9522915f08da583eba1450370f173bd
27.757576
96
0.666842
4.114967
false
false
false
false
alessio-b-zak/myRivers
android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToMyAreaCatchments.kt
1
2660
package com.epimorphics.android.myrivers.models import android.util.JsonReader import com.epimorphics.android.myrivers.data.MyArea import com.epimorphics.android.myrivers.helpers.InputStreamHelper import java.io.IOException import java.io.InputStream import java.io.InputStreamReader /** * Consumes an InputStream and populates relevant fields of MyArea relating to the nearest river * catchment * * @see MyArea */ class InputStreamToMyAreaCatchments : InputStreamHelper() { /** * Converts InputStream to JsonReader and consumes it. * * @param inputStream InputStream to be consumed * @param myArea an object which is to be populated with catchment data * * @throws IOException */ @Throws(IOException::class) fun readJsonStream(inputStream: InputStream, myArea: MyArea) { val reader = JsonReader(InputStreamReader(inputStream, "UTF-8")) reader.isLenient = true reader.use { readMessagesArray(reader, myArea) } } /** * Focuses on the object that contains relevant data to be converted to MyArea fields. * * @param reader JsonReader to be consumed * @param myArea an object which is to be populated with catchment data * * @throws IOException */ @Throws(IOException::class) fun readMessagesArray(reader: JsonReader, myArea: MyArea) { reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "items") { reader.beginArray() while (reader.hasNext()) { readMessage(reader, myArea) } reader.endArray() } else { reader.skipValue() } } reader.endObject() } /** * Converts single JsonObject to relevant MyArea catchment records.. * * @param reader JsonReader to be consumed * @param myArea an object which is to be populated with catchment data * * @throws IOException */ @Throws(IOException::class) fun readMessage(reader: JsonReader, myArea: MyArea) { reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() when (name) { "inManagementCatchment" -> myArea.managementCatchment = readItemToString(reader) "inRiverBasinDistrict" -> myArea.riverBasinDistrict = readItemToString(reader) "label" -> myArea.operationalCatchment = reader.nextString() else -> reader.skipValue() } } reader.endObject() } }
mit
758feac18d139ff2ddd74a8b8d3bbaef
31.060241
96
0.622556
4.691358
false
false
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/utils/System.kt
1
1977
package com.mcxiaoke.koi.utils import android.content.Intent import android.os.BatteryManager import android.os.Environment import android.os.StatFs import com.mcxiaoke.koi.Const /** * User: mcxiaoke * Date: 16/1/27 * Time: 11:06 */ val isLargeHeap: Boolean get() = Runtime.getRuntime().maxMemory() > Const.HEAP_SIZE_LARGE fun noSdcard(): Boolean { return Environment.MEDIA_MOUNTED != Environment.getExternalStorageState() } /** * check if free size of SDCARD and CACHE dir is OK * @param needSize how much space should release at least * * * @return true if has enough space */ fun noFreeSpace(needSize: Long): Boolean { val freeSpace = freeSpace() return freeSpace < needSize * 3 } fun freeSpace(): Long { val stat = StatFs(Environment.getExternalStorageDirectory().path) val blockSize = stat.blockSize.toLong() val availableBlocks = stat.availableBlocks.toLong() return availableBlocks * blockSize } fun getBatteryLevel(batteryIntent: Intent): Float { val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) return level / scale.toFloat() } fun getBatteryInfo(batteryIntent: Intent): String { val status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL val chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) val usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB val acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) val batteryPct = level / scale.toFloat() return "Battery Info: isCharging=$isCharging usbCharge=$usbCharge acCharge=$acCharge batteryPct=$batteryPct" }
apache-2.0
48486cd9a268905ba6af2e5033da7ff3
31.95
114
0.742033
4.076289
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/observation/sync/ObservationSyncWorker.kt
1
7201
package mil.nga.giat.mage.observation.sync import android.content.Context import android.util.Log import androidx.core.app.NotificationCompat import androidx.hilt.work.HiltWorker import androidx.work.* import dagger.assisted.Assisted import dagger.assisted.AssistedInject import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import mil.nga.giat.mage.MageApplication import mil.nga.giat.mage.R import mil.nga.giat.mage.data.observation.ObservationRepository import mil.nga.giat.mage.sdk.datastore.observation.Observation import mil.nga.giat.mage.sdk.datastore.observation.ObservationFavorite import mil.nga.giat.mage.sdk.datastore.observation.ObservationHelper import mil.nga.giat.mage.sdk.datastore.observation.State import java.net.HttpURLConnection import java.util.concurrent.TimeUnit @HiltWorker class ObservationSyncWorker @AssistedInject constructor( @Assisted context: Context, @Assisted params: WorkerParameters, private val observationRepository: ObservationRepository ) : CoroutineWorker(context, params) { private val observationHelper = ObservationHelper.getInstance(applicationContext) override suspend fun doWork(): Result { // Lock to ensure previous running work will complete when cancelled before new work is started. return mutex.withLock { var result = RESULT_SUCCESS_FLAG try { result = syncObservations().withFlag(result) result = syncObservationImportant().withFlag(result) result = syncObservationFavorites().withFlag(result) } catch (e: Exception) { result = RESULT_RETRY_FLAG Log.e(LOG_NAME, "Error trying to sync observations with server", e) } if (result.containsFlag(RESULT_RETRY_FLAG)) Result.retry() else Result.success() } } override suspend fun getForegroundInfo(): ForegroundInfo { val notification = NotificationCompat.Builder(applicationContext, MageApplication.MAGE_NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.ic_sync_preference_24dp) .setContentTitle("Sync Observations") .setContentText("Pushing observation updates to MAGE.") .setPriority(NotificationCompat.PRIORITY_MAX) .setAutoCancel(true) .build() return ForegroundInfo(OBSERVATION_SYNC_NOTIFICATION_ID, notification) } private suspend fun syncObservations(): Int { var result = RESULT_SUCCESS_FLAG for (observation in observationHelper.dirty) { result = syncObservation(observation).withFlag(result) } return result } private suspend fun syncObservation(observation: Observation): Int { val result = RESULT_SUCCESS_FLAG return if (observation.state == State.ARCHIVE) { archive(observation).withFlag(result) } else { save(observation).withFlag(result) } } private suspend fun syncObservationImportant(): Int { var result = RESULT_SUCCESS_FLAG for (observation in observationHelper.dirtyImportant) { result = updateImportant(observation).withFlag(result) } return result } private suspend fun syncObservationFavorites(): Int { var result = RESULT_SUCCESS_FLAG for (favorite in observationHelper.dirtyFavorites) { result = updateFavorite(favorite).withFlag(result) } return result } private suspend fun save(observation: Observation): Result { return if (observation.remoteId.isNullOrEmpty()) { create(observation) } else { update(observation) } } private suspend fun create(observation: Observation): Result { val response = observationRepository.create(observation) return if (response.isSuccessful) { Result.success() } else { if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) Result.failure() else Result.retry() } } private suspend fun update(observation: Observation): Result { val response = observationRepository.update(observation) return if (response.isSuccessful) { Result.success() } else { if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) Result.failure() else Result.retry() } } private suspend fun archive(observation: Observation): Result { val response = observationRepository.archive(observation) return when { response.isSuccessful -> Result.success() response.code() == HttpURLConnection.HTTP_NOT_FOUND -> Result.success() response.code() == HttpURLConnection.HTTP_UNAUTHORIZED -> Result.failure() else -> Result.retry() } } private suspend fun updateImportant(observation: Observation): Result { val response = observationRepository.updateImportant(observation) return if (response.isSuccessful) { Result.success() } else { if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) Result.failure() else Result.retry() } } private suspend fun updateFavorite(favorite: ObservationFavorite): Result { val response = observationRepository.updateFavorite(favorite) return if (response.isSuccessful) { Result.success() } else { if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) Result.failure() else Result.retry() } } private fun Result.withFlag(flag: Int): Int { return when(this) { is Result.Failure -> RESULT_FAILURE_FLAG or flag is Result.Retry -> RESULT_RETRY_FLAG or flag else -> RESULT_SUCCESS_FLAG or flag } } private fun Int.containsFlag(flag: Int): Boolean { return (this or flag) == this } private fun Int.withFlag(flag: Int): Int { return this or flag } companion object { private val LOG_NAME = ObservationSyncWorker::class.java.simpleName private const val OBSERVATION_SYNC_WORK = "mil.nga.mage.OBSERVATION_SYNC_WORK" private const val OBSERVATION_SYNC_NOTIFICATION_ID = 100 private const val RESULT_SUCCESS_FLAG = 0 private const val RESULT_FAILURE_FLAG = 1 private const val RESULT_RETRY_FLAG = 2 private val mutex = Mutex() fun scheduleWork(context: Context) { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val request = OneTimeWorkRequest.Builder(ObservationSyncWorker::class.java) .setConstraints(constraints) .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) .setBackoffCriteria(BackoffPolicy.LINEAR, 15, TimeUnit.SECONDS) .build() WorkManager .getInstance(context) .beginUniqueWork(OBSERVATION_SYNC_WORK, ExistingWorkPolicy.REPLACE, request) .enqueue() } } }
apache-2.0
2e9994704eebb7ed9c17ea73a7a16ffd
34.830846
119
0.659492
4.905313
false
false
false
false
thermatk/FastHub-Libre
app/src/main/java/com/fastaccess/ui/modules/profile/org/project/OrgProjectActivity.kt
6
2179
package com.fastaccess.ui.modules.profile.org.project import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.AppBarLayout import butterknife.BindView import com.evernote.android.state.State import com.fastaccess.R import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.ui.base.BaseActivity import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.modules.repos.projects.RepoProjectsFragmentPager /** * Created by Hashemsergani on 24.09.17. */ class OrgProjectActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { @State var org: String? = null @BindView(R.id.appbar) lateinit var appBar: AppBarLayout override fun layout(): Int = R.layout.activity_fragment_layout override fun isTransparent(): Boolean = true override fun canBack(): Boolean = true override fun isSecured(): Boolean = false override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) appBar.elevation = 0f appBar.stateListAnimator = null if (savedInstanceState == null) { org = intent.extras.getString(BundleConstant.ITEM) val org = org if (org != null) { supportFragmentManager.beginTransaction() .replace(R.id.container, RepoProjectsFragmentPager.newInstance(org), RepoProjectsFragmentPager.TAG) .commit() } } toolbar?.apply { subtitle = org } } companion object { fun startActivity(context: Context, org: String, isEnterprise: Boolean) { val intent = Intent(context, OrgProjectActivity::class.java) intent.putExtras(Bundler.start().put(BundleConstant.ITEM, org) .put(BundleConstant.IS_ENTERPRISE, isEnterprise) .end()) context.startActivity(intent) } } }
gpl-3.0
7bac025dddbbff67e32dca0e0c60f6c7
33.603175
92
0.680128
4.655983
false
false
false
false
springboot-angular2-tutorial/boot-app
src/main/kotlin/com/myapp/repository/RelatedUserRepositoryImpl.kt
1
2079
package com.myapp.repository import com.myapp.domain.RelatedUser import com.myapp.domain.UserStats import com.myapp.dto.request.PageParams import com.myapp.generated.tables.Relationship.RELATIONSHIP import com.myapp.generated.tables.User.USER import com.myapp.generated.tables.UserStats.USER_STATS import org.jooq.DSLContext import org.jooq.Record import org.springframework.stereotype.Repository import com.myapp.generated.tables.User as UserTable @Repository class RelatedUserRepositoryImpl( private val dsl: DSLContext ) : RelatedUserRepository, Pager { override fun findFollowers(userId: Long, pageParams: PageParams): List<RelatedUser> { return dsl.select() .from(USER) .join(RELATIONSHIP) .on(USER.ID.eq(RELATIONSHIP.FOLLOWER_ID)) .join(USER_STATS) .on(USER.ID.eq(USER_STATS.USER_ID)) .where(RELATIONSHIP.FOLLOWED_ID.eq(userId)) .and(pageParams.toCondition(RELATIONSHIP.ID)) .orderBy(RELATIONSHIP.ID.desc()) .limit(pageParams.count) .fetch(mapper()) } override fun findFollowings(userId: Long, pageParams: PageParams): List<RelatedUser> { return dsl.select() .from(USER) .join(RELATIONSHIP) .on(USER.ID.eq(RELATIONSHIP.FOLLOWED_ID)) .join(USER_STATS) .on(USER.ID.eq(USER_STATS.USER_ID)) .where(RELATIONSHIP.FOLLOWER_ID.eq(userId)) .and(pageParams.toCondition(RELATIONSHIP.ID)) .orderBy(RELATIONSHIP.ID.desc()) .limit(pageParams.count) .fetch(mapper()) } private fun mapper() = { r: Record -> val userRecord = r.into(USER) val relationshipRecord = r.into(RELATIONSHIP) val userStatsRecord = r.into(USER_STATS) RelatedUser( _id = userRecord.id, username = userRecord.username, name = userRecord.name, relationshipId = relationshipRecord.id, userStats = UserStats(userStatsRecord) ) } }
mit
5b7d4c6f6fb87484e33b1be824fce1ee
33.666667
90
0.645022
4.021277
false
false
false
false
jabbink/PokemonGoAPI
src/main/kotlin/ink/abb/pogo/api/cache/Map.kt
1
3618
package ink.abb.pogo.api.cache import com.google.common.geometry.MutableInteger import com.google.common.geometry.S2CellId import com.google.common.geometry.S2LatLng import com.google.protobuf.ProtocolStringList import java.util.* import java.util.concurrent.TimeUnit class Map { val mapCells = mutableMapOf<Long, MapCell>() fun getPokestops(latitude: Double, longitude: Double, width: Int = 3): List<Pokestop> { return getCellIds(latitude, longitude, width).flatMap { getMapCell(it).pokestops } } fun getGyms(latitude: Double, longitude: Double, width: Int = 3): List<Gym> { return getCellIds(latitude, longitude, width).flatMap { getMapCell(it).gyms } } fun getPokemon(latitude: Double, longitude: Double, width: Int = 3): List<MapPokemon> { return getCellIds(latitude, longitude, width).flatMap { getMapCell(it).pokemon.filter { it.valid } } } fun getMapCell(cellId: Long): MapCell { return mapCells.getOrPut(cellId, { MapCell(cellId) }) } fun setPokemon(cellId: Long, time: Long, mapPokemon: Set<MapPokemon>) { val mapCell = getMapCell(cellId) /*if (time >= mapCell.lastUpdated + TimeUnit.HOURS.toMillis(1)) { mapCell.pokemon = mutableSetOf() }*/ mapCell.lastUpdated = time // only keep valids and ones that we did not just receive new info about mapCell.pokemon = (mapCell.pokemon.filter { it.valid && !mapPokemon.contains(it) }.toSet() + mapPokemon).toMutableSet() } fun setPokestops(cellId: Long, pokestops: Collection<Pokestop>) { val mapCell = getMapCell(cellId) mapCell.pokestops.addAll(pokestops) } fun setGyms(cellId: Long, gyms: Collection<Gym>) { val mapCell = getMapCell(cellId) mapCell.gyms.addAll(gyms) } fun removeObjects(cellId: Long, deletedObjectsList: ProtocolStringList) { val mapCell = getMapCell(cellId) deletedObjectsList.forEach { if (it != null) { val objectId = it val deleteStop = mapCell.pokestops.find { it.fortData.id == objectId } if (deleteStop != null) { mapCell.pokestops.remove(deleteStop) } val deleteGym = mapCell.gyms.find { it.fortData.id == objectId } if (deleteGym != null) { mapCell.gyms.remove(deleteGym) } val deletePokemon = mapCell.pokemon.find { it.spawnPointId == objectId } if (deletePokemon != null) { mapCell.pokemon.remove(deletePokemon) } } } } companion object { fun getCellIds(latitude: Double, longitude: Double, width: Int): List<Long> { val latLng = S2LatLng.fromDegrees(latitude, longitude) val cellId = S2CellId.fromLatLng(latLng).parent(15) val i = MutableInteger(0) val j = MutableInteger(0) val level = cellId.level() val size = 1 shl S2CellId.MAX_LEVEL - level val face = cellId.toFaceIJOrientation(i, j, null) val cells = ArrayList<Long>() val halfWidth = Math.floor(width.toDouble() / 2.0).toInt() for (x in -halfWidth..halfWidth) { for (y in -halfWidth..halfWidth) { cells.add(S2CellId.fromFaceIJ(face, i.intValue() + x * size, j.intValue() + y * size).parent(15).id()) } } return cells } } }
gpl-3.0
0e50d073685fd7b4a8acea8591f17188
35.19
127
0.593698
4.011086
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/app/FrameworkExtensions.kt
1
1362
@file:Suppress("NOTHING_TO_INLINE") package net.xpece.android.app import android.content.res.ColorStateList import android.support.annotation.ColorInt import net.xpece.android.text.Truss import java.util.* inline fun @receiver:ColorInt Int.toColorStateList() = ColorStateList.valueOf(this)!! inline fun <E> List<E>.asArrayList(): ArrayList<E> = this as? ArrayList<E> ?: ArrayList(this) inline fun Iterable<CharSequence>.joinToCharSequence( separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = ""): CharSequence = joinToCharSequence(separator, prefix, postfix, { it }) inline fun Iterable<CharSequence>.joinToCharSequence( separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", transformation: (CharSequence) -> CharSequence): CharSequence { val t = Truss().append(prefix) forEachIndexed { i, it -> if (i > 0) t.append(separator) val x = transformation(it) t.append(x) } return t.append(postfix).build() } inline fun <T> T?.intIfNotNull(number: T.() -> Int): Int = this?.number() ?: 0 inline fun <T> T?.intIfNotNull(number: Int): Int = if (this != null) number else 0 inline fun <T> T?.oneIfNotNull(): Int = intIfNotNull(1) inline fun equalsNotNull(a: Any?, b: Any?) = a != null && a == b
apache-2.0
5816fe88762b4d7b10285fa9808acc6b
34.842105
93
0.667401
3.880342
false
false
false
false
MichBogus/PINZ-ws
src/main/kotlin/controller/item/UserItemsControllerMappings.kt
1
2086
package controller.item import controller.base.WSResponseEntity import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import workflow.request.* import javax.validation.Valid interface UserItemsControllerMappings { @RequestMapping(value = "/addItem", method = arrayOf(RequestMethod.POST), consumes = arrayOf("application/json"), produces = arrayOf("application/json")) fun addItem(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: AddItemRequest): WSResponseEntity @RequestMapping(value = "/deleteItem", method = arrayOf(RequestMethod.POST), consumes = arrayOf("application/json"), produces = arrayOf("application/json")) fun deleteItem(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: DeleteItemRequest): WSResponseEntity @RequestMapping(value = "/getAllCompanyItems", method = arrayOf(RequestMethod.POST), consumes = arrayOf("application/json"), produces = arrayOf("application/json")) fun getCompanyItems(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: CompanyCodeItemsRequest): WSResponseEntity @RequestMapping(value = "/getItemByToken", method = arrayOf(RequestMethod.POST), consumes = arrayOf("application/json"), produces = arrayOf("application/json")) fun getItemByToken(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String, @Valid @RequestBody request: ItemTokenRequest): WSResponseEntity @RequestMapping(value = "/getUserItems", method = arrayOf(RequestMethod.GET)) fun getUserItems(@Valid @RequestHeader(value = "AUTH_TOKEN") authToken: String): WSResponseEntity }
apache-2.0
51c0948b58236c0f3aea1c064dc45aa2
46.431818
101
0.69511
5.137931
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/CommandMetaEntity.kt
1
1834
package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.business.annotation.YamlSerialize import com.github.shynixn.blockball.api.business.enumeration.CommandMode import com.github.shynixn.blockball.api.persistence.entity.CommandMeta /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p>B * 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. */ class CommandMetaEntity : CommandMeta { /** Mode how the command gets executed. */ @YamlSerialize(value = "mode", orderNumber = 1) override var mode: CommandMode = CommandMode.CONSOLE_PER_PLAYER /** Command to be executed. */ @YamlSerialize(value = "command", orderNumber = 2) override var command: String? = null }
apache-2.0
f91bb91be06c1607527c756d806a7eb3
43.756098
81
0.750818
4.216092
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/MatchTimesPage.kt
1
10535
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.business.service.ProxyService import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.api.persistence.entity.MatchTimeMeta import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity import com.github.shynixn.blockball.core.logic.persistence.entity.MatchTimeMetaEntity import com.google.inject.Inject /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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 OTHERwwt * 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. */ class MatchTimesPage @Inject constructor(private val proxyService: ProxyService) : Page(ID, GameSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 34 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.MATCHTIMES } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute( player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String> ): MenuCommandResult { val arena = cache[0] as Arena if (command == MenuCommand.MATCHTIMES_OPEN) { cache[5] = null } else if (command == MenuCommand.MATCHTIMES_CREATE) { val matchTime = MatchTimeMetaEntity() arena.meta.minigameMeta.matchTimes.add(matchTime) cache[5] = matchTime } else if (command == MenuCommand.MATCHTIMES_CALLBACK && args.size >= 3) { val index = args[2].toInt() if (index >= 0 && index < arena.meta.minigameMeta.matchTimes.size) { cache[5] = arena.meta.minigameMeta.matchTimes[index] } } else if (command == MenuCommand.MATCHTIMES_DELETE) { arena.meta.minigameMeta.matchTimes.remove(cache[5]) cache[5] = null } else if (command == MenuCommand.MATCHTIMES_DURATION && args[2].toIntOrNull() != null) { val matchTime = cache[5] as MatchTimeMeta matchTime.duration = args[2].toInt() } else if (command == MenuCommand.MATCHTIMES_SWITCHGOAL) { val matchTime = cache[5] as MatchTimeMeta matchTime.isSwitchGoalsEnabled = !matchTime.isSwitchGoalsEnabled } else if (command == MenuCommand.MATCHTIMES_BALLAVAILABLE) { val matchTime = cache[5] as MatchTimeMeta matchTime.playAbleBall = !matchTime.playAbleBall } else if (command == MenuCommand.MATCHTIMES_RESPAWN) { val matchTime = cache[5] as MatchTimeMeta matchTime.respawnEnabled = !matchTime.respawnEnabled } else if (command == MenuCommand.MATCHTIMES_STARTTITLEMESSAGE && args.size >= 3) { val matchTime = cache[5] as MatchTimeMeta matchTime.startMessageTitle = mergeArgs(2, args) } else if (command == MenuCommand.MATCHTIMES_STARTSUBTITLEMESSAGE && args.size >= 3) { val matchTime = cache[5] as MatchTimeMeta matchTime.startMessageSubTitle = mergeArgs(2, args) } else if (command == MenuCommand.MATCHTIMES_CALLBACKCLOSETYPE) { val index = args[2].toInt() val matchTime = cache[5] as MatchTimeMeta if (index >= 0 && index < MatchTimeCloseType.values().size) { matchTime.closeType = MatchTimeCloseType.values()[index] } } cache[2] = arena.meta.minigameMeta.matchTimes.mapIndexed { index, e -> (index + 1).toString() + ". ${e.closeType.name}\\nDuration: ${e.duration} seconds"} return super.execute(player, command, cache, args) } /** * Builds the page content. * * @param cache cache * @return content */ override fun buildPage(cache: Array<Any?>): ChatBuilder { val arena = cache[0] as Arena val selectedMatchTime = cache[5] val matchTimeListText = (cache[2] as List<String>).toSingleLine() val builder = ChatBuilderEntity() .component("- Match Times:").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(matchTimeListText) .builder().component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_MATCHTIMES.command) .setHoverText("Opens the selectionbox for existing match times.") .builder().component(" [add..]").setColor(MenuClickableItem.ADD.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_CREATE.command) .setHoverText("Adds a new match time and selects it.") .builder().nextLine() if (selectedMatchTime != null && selectedMatchTime is MatchTimeMeta) { val index = (arena.meta.minigameMeta.matchTimes.indexOf(selectedMatchTime) + 1).toString() val selectedMatchTimeText = "Number $index" val selectedMatchTimeHover = index + ". ${selectedMatchTime.closeType.name}\\nDuration: ${selectedMatchTime.duration} seconds\\nSwitch goals: ${selectedMatchTime.isSwitchGoalsEnabled}" builder.component("- Selected match time: $selectedMatchTimeText").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(selectedMatchTimeHover).builder() .component(MenuClickableItem.DELETE.text).setColor(MenuClickableItem.DELETE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_DELETE.command) .setHoverText("Deletes the selected match time.") .builder().nextLine() .component("- Close Condition: " + selectedMatchTime.closeType.name).builder() .component(MenuClickableItem.SELECT.text).setColor(MenuClickableItem.SELECT.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.LIST_MATCHCLOSETYPES.command) .setHoverText("Opens the selectionbox for close conditions.") .builder().nextLine() .component("- Duration: " + selectedMatchTime.duration + " seconds").builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.MATCHTIMES_DURATION.command) .setHoverText("Changes the duration (seconds) of this part of the match.") .builder().nextLine() .component("- Switch goals: " + selectedMatchTime.isSwitchGoalsEnabled).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_SWITCHGOAL.command) .setHoverText("Toggles if the team should switch goals when this match time starts.") .builder().nextLine() .component("- Playable Ball: " + selectedMatchTime.playAbleBall).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_BALLAVAILABLE.command) .setHoverText("Toggles if the ball should be spawned during this match time.") .builder().nextLine() .component("- Respawn: " + selectedMatchTime.respawnEnabled).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.MATCHTIMES_RESPAWN.command) .setHoverText("Toggles if players should respawn when this match time starts.") .builder().nextLine() .component("- StartTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(selectedMatchTime.startMessageTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.MATCHTIMES_STARTTITLEMESSAGE.command) .setHoverText("Changes the title message getting played when the match time starts.") .builder().nextLine() .component("- StartSubTitle Message: ").builder() .component(MenuClickableItem.PREVIEW.text).setColor(MenuClickableItem.PREVIEW.color) .setHoverText(selectedMatchTime.startMessageSubTitle).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.MATCHTIMES_STARTSUBTITLEMESSAGE.command) .setHoverText("Changes the subtitle message getting played when the match time starts.") .builder() } return builder } }
apache-2.0
3c93e85001dd1a922f23a4556914e2ef
53.309278
171
0.667869
4.638926
false
false
false
false
Balthair94/PokedexMVP
app/src/main/java/baltamon/mx/pokedexmvp/pokemon_detail/TabPokemonFragmentAdapter.kt
1
1384
package baltamon.mx.pokedexmvp.pokemon_detail import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import baltamon.mx.pokedexmvp.ability.AbilitiesFragment import baltamon.mx.pokedexmvp.about_pokemon.AboutPokemonFragment import baltamon.mx.pokedexmvp.models.NamedAPIResource import baltamon.mx.pokedexmvp.models.Pokemon import baltamon.mx.pokedexmvp.move.MovesFragment /** * Created by Baltazar Rodriguez on 02/07/2017. */ class TabPokemonFragmentAdapter(fm: FragmentManager, val pokemon: Pokemon): FragmentPagerAdapter(fm) { val titles = arrayOf("About", "Abilities", "Moves") override fun getItem(position: Int): Fragment = when (position) { 0 -> AboutPokemonFragment.newInstance(pokemon) 1 -> { val abilities: ArrayList<NamedAPIResource> = ArrayList() pokemon.abilities.mapTo(abilities) { it.ability } AbilitiesFragment.newInstance(abilities) } else -> { val moves: ArrayList<NamedAPIResource> = ArrayList() pokemon.moves.mapTo(moves) { it.move } MovesFragment.newInstance(moves) } } override fun getCount(): Int = titles.size override fun getPageTitle(position: Int): CharSequence = titles[position] }
mit
2545a194b2b4f8e811063d92a925b0db
35.447368
102
0.692919
4.537705
false
false
false
false
Sefford/kor
modules/kor-repositories/src/main/kotlin/com/sefford/kor/repositories/ExpirationRepository.kt
1
2878
/* * Copyright (C) 2018 Saúl Díaz * * 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.sefford.kor.repositories import arrow.core.Either import arrow.core.left import com.sefford.kor.repositories.components.* /** * Repository that allows to apply a keep-alive policy over a repository. * * @author Saul Diaz <[email protected]> */ class ExpirationRepository<K, V : RepoElement<K>>(private val repository: Repository<K, V>, private val policy: ExpirationPolicy<K>) : StubDataSource<K, V> { override fun clear() { this.policy.clear() this.repository.clear() } override fun contains(id: K): Boolean { if (elementIsAvailable(id)) { delete(id) return false } return repository.contains(id) } override fun delete(id: K) { policy.notifyDeleted(id) repository.delete(id) } override fun delete(id: K, element: V) { policy.notifyDeleted(id) repository.delete(id, element) } override fun delete(elements: Iterator<V>) { elements.forEach { element -> policy.notifyDeleted(element.id) repository.delete(element.id, element) } } override fun get(id: K): Either<RepositoryError, V> { if (elementIsAvailable(id)) { delete(id) return RepositoryError.NotFound(id).left() } return repository[id] } override fun get(ids: Iterator<K>): Collection<V> { val result = repository.get(ids).partition { element -> !policy.isExpired(element.id) } result.second.forEach { element -> delete(element.id) } return result.first } override fun save(element: V): Either<RepositoryError, V> { val result = repository.save(element) result.map { policy.notifyCreated(it.id) } return result } override val all: Collection<V> get() : Collection<V> { val result = repository.all.partition { element -> !policy.isExpired(element.id) } result.second.forEach { element -> delete(element.id) } return result.first } override val isReady: Boolean get() = repository.isReady private fun elementIsAvailable(id: K) = policy.isExpired(id) or !repository.contains(id) }
apache-2.0
0661c2a81eb44483b00968392a84270e
30.955556
115
0.635605
4.168116
false
false
false
false
http4k/http4k
http4k-contract/src/main/kotlin/org/http4k/contract/routeMeta.kt
1
7391
package org.http4k.contract import org.http4k.contract.security.Security import org.http4k.core.ContentType import org.http4k.core.HttpMessage import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.with import org.http4k.format.AutoContentNegotiator import org.http4k.lens.BiDiBodyLens import org.http4k.lens.BodyLens import org.http4k.lens.Header import org.http4k.lens.Lens import org.http4k.util.Appendable open class HttpMessageMeta<out T : HttpMessage>( val message: T, val description: String, val definitionId: String?, val example: Any?, val schemaPrefix: String? = null ) class RequestMeta(request: Request, definitionId: String? = null, example: Any? = null, schemaPrefix: String? = null) : HttpMessageMeta<Request>(request, "request", definitionId, example, schemaPrefix) class ResponseMeta(description: String, response: Response, definitionId: String? = null, example: Any? = null, schemaPrefix: String? = null) : HttpMessageMeta<Response>(response, description, definitionId, example, schemaPrefix) class RouteMetaDsl internal constructor() { var summary: String = "<unknown>" var description: String? = null val tags = Appendable<Tag>() val produces = Appendable<ContentType>() val consumes = Appendable<ContentType>() internal val requests = Appendable<HttpMessageMeta<Request>>() internal val responses = Appendable<HttpMessageMeta<Response>>() val headers = Appendable<Lens<Request, *>>() val queries = Appendable<Lens<Request, *>>() val cookies = Appendable<Lens<Request, *>>() internal var requestBody: BodyLens<*>? = null var operationId: String? = null var security: Security? = null var preFlightExtraction: PreFlightExtraction? = null internal var deprecated: Boolean = false /** * Add possible responses to this Route. */ @JvmName("returningResponse") fun returning(vararg descriptionToResponse: Pair<String, Response>) = descriptionToResponse.forEach { (description, status) -> returning(ResponseMeta(description, status)) } /** * Add possible response metadata to this Route. A route supports multiple possible responses. */ @JvmName("returningResponseMeta") fun returning(vararg responseMetas: HttpMessageMeta<Response>) { responseMetas.forEach { responses += it } responseMetas.forEach { produces += Header.CONTENT_TYPE(it.message)?.let { listOf(it) } ?: emptyList() } } /** * Add a possible response description/reason and status to this Route */ @JvmName("returningStatus") fun returning(vararg statusesToDescriptions: Pair<Status, String>) = statusesToDescriptions.forEach { (status, d) -> returning(d to Response(status)) } /** * Add possible response statuses to this Route with no example. */ @JvmName("returningStatus") fun returning(vararg statuses: Status) = statuses.forEach { returning(ResponseMeta("", Response(it))) } /** * Add an example response (using a Lens and a value) to this Route. It is also possible to pass in the definitionId * for this response body which will override the naturally generated one. */ @JvmName("returningStatus") fun <T> returning(status: Status, body: Pair<BiDiBodyLens<T>, T>, description: String? = null, definitionId: String? = null, schemaPrefix: String? = null ) { returning(ResponseMeta(description ?: status.description, Response(status).with(body.first of body.second), definitionId, body.second, schemaPrefix)) } /** * Add all negotiated responses, with samples. It is also possible to pass in the definitionId * for this response body which will override the naturally generated one. */ @JvmName("returningStatusNegotiated") fun <T: Any> returning( status: Status, negotiated: Pair<AutoContentNegotiator<T>, T>, description: String? = null, definitionId: String? = null, schemaPrefix: String? = null ) { for (lens in negotiated.first) { returning(status, lens to negotiated.second, description, definitionId, schemaPrefix) } } /** * Add an example request (using a Lens and a value) to this Route. It is also possible to pass in the definitionId * for this request body which will override the naturally generated one. */ fun <T> receiving(body: Pair<BiDiBodyLens<T>, T>, definitionId: String? = null, schemaPrefix: String? = null ) { requestBody = body.first receiving(RequestMeta(Request(POST, "").with(body.first of body.second), definitionId, body.second, schemaPrefix)) } /** * Add negotiated example requests to this route. It is also possible to pass in the definitionId * for this request body which will override the naturally generated one. */ @JvmName("receivingNegotiated") fun <T> receiving( negotiated: Pair<AutoContentNegotiator<T>, T>, definitionId: String? = null, schemaPrefix: String? = null ) { for (lens in negotiated.first) { receiving(lens to negotiated.second, definitionId, schemaPrefix) } requestBody = negotiated.first.toBodyLens() } /** * Add request metadata to this Route. A route only supports a single possible request. */ fun receiving(requestMeta: HttpMessageMeta<Request>) { requests += requestMeta consumes += Header.CONTENT_TYPE(requestMeta.message)?.let { listOf(it) } ?: emptyList() } /** * Set the input body type for this request WITHOUT an example. Hence the content-type will be registered but no * example schema will be generated. */ fun <T> receiving(bodyLens: BiDiBodyLens<T>) { requestBody = bodyLens receiving(RequestMeta(Request(POST, "").with(Header.CONTENT_TYPE of bodyLens.contentType))) } fun markAsDeprecated() { deprecated = true } } fun routeMetaDsl(fn: RouteMetaDsl.() -> Unit = {}) = RouteMetaDsl().apply(fn).run { RouteMeta( summary, description, tags.all.toSet(), requestBody, produces.all.toSet(), consumes.all.toSet(), queries.all + headers.all + cookies.all, requests.all, responses.all, preFlightExtraction, security, operationId, deprecated ) } data class RouteMeta(val summary: String = "<unknown>", val description: String? = null, val tags: Set<Tag> = emptySet(), val body: BodyLens<*>? = null, val produces: Set<ContentType> = emptySet(), val consumes: Set<ContentType> = emptySet(), val requestParams: List<Lens<Request, *>> = emptyList(), val requests: List<HttpMessageMeta<Request>> = emptyList(), val responses: List<HttpMessageMeta<Response>> = emptyList(), val preFlightExtraction: PreFlightExtraction? = null, val security: Security? = null, val operationId: String? = null, val deprecated: Boolean = false)
apache-2.0
ccc88f38717b6a8538762928b5373558
40.290503
229
0.657962
4.350206
false
false
false
false
msebire/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutBuilder.kt
1
8633
// 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.migLayout import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.ui.components.noteComponent import com.intellij.ui.layout.* import com.intellij.ui.layout.migLayout.patched.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.JBUI import net.miginfocom.layout.* import java.awt.Component import java.awt.Container import javax.swing.ButtonGroup import javax.swing.JComponent import javax.swing.JDialog import javax.swing.JLabel internal class MigLayoutBuilder(val spacing: SpacingConfiguration, val isUseMagic: Boolean = true) : LayoutBuilderImpl { companion object { private var hRelatedGap = -1 private var vRelatedGap = -1 init { JBUI.addPropertyChangeListener(JBUI.USER_SCALE_FACTOR_PROPERTY) { updatePlatformDefaults() } } private fun updatePlatformDefaults() { if (hRelatedGap != -1 && vRelatedGap != -1) { PlatformDefaults.setRelatedGap(createUnitValue(hRelatedGap, true), createUnitValue(vRelatedGap, false)) } } private fun setRelatedGap(h: Int, v: Int) { if (hRelatedGap == h && vRelatedGap == v) { return } hRelatedGap = h vRelatedGap = v updatePlatformDefaults() } } init { setRelatedGap(spacing.horizontalGap, spacing.verticalGap) } /** * Map of component to constraints shared among rows (since components are unique) */ private val componentConstraints: MutableMap<Component, CC> = ContainerUtil.newIdentityTroveMap() private val rootRow = MigLayoutRow(parent = null, componentConstraints = componentConstraints, builder = this, indent = 0) val defaultComponentConstraintCreator = DefaultComponentConstraintCreator(spacing) // keep in mind - MigLayout always creates one more than need column constraints (i.e. for 2 will be 3) // it doesn't lead to any issue. val columnConstraints = AC() override fun newRow(label: JLabel?, buttonGroup: ButtonGroup?, isSeparated: Boolean): Row { return rootRow.createChildRow(label = label, buttonGroup = buttonGroup, isSeparated = isSeparated) } override fun newTitledRow(title: String): Row { return rootRow.createChildRow(isSeparated = true, title = title) } override fun noteRow(text: String, linkHandler: ((url: String) -> Unit)?) { addNoteOrComment(noteComponent(text, linkHandler)) } override fun commentRow(text: String) { addNoteOrComment(ComponentPanelBuilder.createCommentComponent(text, true)) } private fun addNoteOrComment(component: JComponent) { val cc = CC() cc.vertical.gapBefore = gapToBoundSize(if (rootRow.subRows == null) spacing.verticalGap else spacing.largeVerticalGap, false) cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap, false) val row = rootRow.createChildRow(label = null, noGrid = true) row.addComponent(component, lazyOf(cc)) } override fun build(container: Container, layoutConstraints: Array<out LCFlags>) { val lc = createLayoutConstraints() lc.gridGapY = gapToBoundSize(spacing.verticalGap, false) if (layoutConstraints.isEmpty()) { lc.fillX() // not fillY because it leads to enormously large cells - we use cc `push` in addition to cc `grow` as a more robust and easy solution } else { lc.apply(layoutConstraints) } lc.isVisualPadding = spacing.isCompensateVisualPaddings // if 3, invisible component will be disregarded completely and it means that if it is last component, it's "wrap" constraint will be not taken in account lc.hideMode = 2 val rowConstraints = AC() (container as JComponent).putClientProperty("isVisualPaddingCompensatedOnComponentLevel", false) var isLayoutInsetsAdjusted = false container.layout = object : MigLayout(lc, columnConstraints, rowConstraints) { override fun layoutContainer(parent: Container) { if (!isLayoutInsetsAdjusted) { isLayoutInsetsAdjusted = true var topParent = parent.parent while (topParent != null) { if (topParent is JDialog) { val topBottom = createUnitValue(spacing.dialogTopBottom, false) val leftRight = createUnitValue(spacing.dialogLeftRight, true) // since we compensate visual padding, child components should be not clipped, so, we do not use content pane DialogWrapper border (returns null), // but instead set insets to our content panel (so, child components are not clipped) lc.insets = arrayOf(topBottom, leftRight, topBottom, leftRight) break } topParent = topParent.parent } } super.layoutContainer(parent) } } val isNoGrid = layoutConstraints.contains(LCFlags.noGrid) var rowIndex = 0 fun configureComponents(row: MigLayoutRow) { val lastComponent = row.components.lastOrNull() for ((index, component) in row.components.withIndex()) { // MigLayout in any case always creates CC, so, create instance even if it is not required val cc = componentConstraints.get(component) ?: CC() if (isNoGrid) { container.add(component, cc) continue } // we cannot use columnCount as an indicator of whether to use spanX/wrap or not because component can share cell with another component, // in any case MigLayout is smart enough and unnecessary spanX doesn't harm if (component === lastComponent) { cc.spanX() cc.isWrap = true } if (index == 0) { if (row.noGrid) { rowConstraints.noGrid(rowIndex) } else { row.gapAfter?.let { rowConstraints.gap(it, rowIndex) } } // if constraint specified only for rows 0 and 1, MigLayout will use constraint 1 for any rows with index 1+ (see LayoutUtil.getIndexSafe - use last element if index > size) // so, we set for each row to make sure that constraints from previous row will be not applied rowConstraints.align(if (isUseMagic) "baseline" else "top", rowIndex) } if (index >= row.rightIndex) { cc.horizontal.gapBefore = BoundSize(null, null, null, true, null) } container.add(component, cc) } rowIndex++ } fun processRows(rows: List<MigLayoutRow>) { for (row in rows) { // configureComponents will increase rowIndex, but if row doesn't have components, it is synthetic row (e.g. titled row that contains only sub rows) if (!row.components.isEmpty()) { configureComponents(row) } row.subRows?.let { processRows(it) } } } rootRow.subRows?.let { configureGapBetweenColumns(it) processRows(it) } // do not hold components componentConstraints.clear() } private fun configureGapBetweenColumns(subRows: List<MigLayoutRow>) { var startColumnIndexToApplyHorizontalGap = 0 if (subRows.any { it.isLabeledIncludingSubRows }) { // using columnConstraints instead of component gap allows easy debug (proper painting of debug grid) columnConstraints.gap("${spacing.labelColumnHorizontalGap}px!", 0) columnConstraints.grow(0f, 0) startColumnIndexToApplyHorizontalGap = 1 } val gapAfter = "${spacing.horizontalGap}px!" for (i in startColumnIndexToApplyHorizontalGap until rootRow.columnIndexIncludingSubRows) { columnConstraints.gap(gapAfter, i) } } } internal fun gapToBoundSize(value: Int, isHorizontal: Boolean): BoundSize { val unitValue = createUnitValue(value, isHorizontal) return BoundSize(unitValue, unitValue, null, false, null) } fun createLayoutConstraints(): LC { val lc = LC() lc.gridGapX = gapToBoundSize(0, true) lc.insets("0px") return lc } private fun createUnitValue(value: Int, isHorizontal: Boolean): UnitValue { return UnitValue(value.toFloat(), "px", isHorizontal, UnitValue.STATIC, null) } private fun LC.apply(flags: Array<out LCFlags>): LC { for (flag in flags) { @Suppress("NON_EXHAUSTIVE_WHEN") when (flag) { LCFlags.noGrid -> isNoGrid = true LCFlags.flowY -> isFlowX = false LCFlags.fill -> fill() LCFlags.fillX -> isFillX = true LCFlags.fillY -> isFillY = true LCFlags.lcWrap -> wrapAfter = 0 LCFlags.debug -> debug() } } return this }
apache-2.0
da5a8e115880923df32109b7225c11e6
34.385246
183
0.68354
4.39115
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-core/src/main/kotlin/org/microg/gms/ui/PushNotificationFragment.kt
1
2682
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.ui import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import com.google.android.gms.R import com.google.android.gms.databinding.PushNotificationFragmentBinding import org.microg.gms.checkin.getCheckinServiceInfo import org.microg.gms.gcm.ServiceInfo import org.microg.gms.gcm.getGcmServiceInfo import org.microg.gms.gcm.setGcmServiceConfiguration class PushNotificationFragment : Fragment(R.layout.push_notification_fragment) { lateinit var binding: PushNotificationFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = PushNotificationFragmentBinding.inflate(inflater, container, false) binding.switchBarCallback = object : PreferenceSwitchBarCallback { override fun onChecked(newStatus: Boolean) { setEnabled(newStatus) } } return binding.root } fun setEnabled(newStatus: Boolean) { lifecycleScope.launchWhenResumed { val info = getGcmServiceInfo(requireContext()) val newConfiguration = info.configuration.copy(enabled = newStatus) displayServiceInfo(setGcmServiceConfiguration(requireContext(), newConfiguration)) } } fun displayServiceInfo(serviceInfo: ServiceInfo) { binding.gcmEnabled = serviceInfo.configuration.enabled } override fun onResume() { super.onResume() lifecycleScope.launchWhenResumed { displayServiceInfo(getGcmServiceInfo(requireContext())) binding.checkinEnabled = getCheckinServiceInfo(requireContext()).configuration.enabled } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.add(0, MENU_ADVANCED, 0, R.string.menu_advanced) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { MENU_ADVANCED -> { findNavController().navigate(requireContext(), R.id.openGcmAdvancedSettings) true } else -> super.onOptionsItemSelected(item) } } companion object { private const val MENU_ADVANCED = Menu.FIRST } }
apache-2.0
2f075ef97bbf9d43e60d60f5ef92920f
34.289474
116
0.708427
5.108571
false
true
false
false
google/play-services-plugins
strict-version-matcher-plugin/src/test/java/com/google/android/gms/dependencies/TestUtil.kt
1
1755
package com.google.android.gms.dependencies // These are constants used to refer to artifacts and constants across all of the test classes to increase readability. @JvmField val ARTIFACT_A_100 = ArtifactVersion.fromGradleRef("com.google.firebase:artA:1.0.0") @JvmField val ARTIFACT_A_200 = ArtifactVersion.fromGradleRef("com.google.firebase:artA:2.0.0") @JvmField val ARTIFACT_B_100 = ArtifactVersion.fromGradleRef("com.google.firebase:artB:1.0.0") @JvmField val ARTIFACT_B_200 = ArtifactVersion.fromGradleRef("com.google.firebase:artB:2.0.0") @JvmField val ARTIFACT_B_300 = ArtifactVersion.fromGradleRef("com.google.firebase:artB:3.0.0") @JvmField val ARTIFACT_C_100 = ArtifactVersion.fromGradleRef("com.google.android.gms:artC:1.0.0") @JvmField val ARTIFACT_C_200 = ArtifactVersion.fromGradleRef("com.google.android.gms:artC:2.0.0") @JvmField val ARTIFACT_D_100 = ArtifactVersion.fromGradleRef("com.google.android.gms:artD:1.0.0") @JvmField val ARTIFACT_D_200 = ArtifactVersion.fromGradleRef("com.google.android.gms:artD:2.0.0") @JvmField val ART_A_100_TO_ART_B_100 = Dependency.fromArtifactVersions(ARTIFACT_A_100, ARTIFACT_B_100) @JvmField val ART_A_200_TO_ART_B_200 = Dependency.fromArtifactVersions(ARTIFACT_A_200, ARTIFACT_B_200) @JvmField val ART_A_100_TO_ART_C_100 = Dependency.fromArtifactVersions(ARTIFACT_A_100, ARTIFACT_C_100) @JvmField val ART_A_100_TO_ART_C_200 = Dependency.fromArtifactVersions(ARTIFACT_A_100, ARTIFACT_C_200) @JvmField val ART_B_100_TO_ART_D_100 = Dependency.fromArtifactVersions(ARTIFACT_B_100, ARTIFACT_D_100) @JvmField val ART_C_100_TO_ART_D_100 = Dependency.fromArtifactVersions(ARTIFACT_C_100, ARTIFACT_D_100) @JvmField val ART_C_200_TO_ART_D_200 = Dependency.fromArtifactVersions(ARTIFACT_C_200, ARTIFACT_D_200)
apache-2.0
7a74f800e62aa3e4b98e2742b9a7ab78
82.571429
119
0.789174
3.015464
false
false
false
false
valich/intellij-markdown
buildSrc/src/main/kotlin/org/jetbrains/PublicationChannel.kt
1
982
package org.jetbrains import org.gradle.api.Project internal enum class PublicationChannel { Bintray, MavenCentral, MavenCentralSnapshot; val isBintrayRepository get() = this == Bintray val isMavenRepository get() = when (this) { MavenCentral, MavenCentralSnapshot -> true else -> false } companion object { fun fromPropertyString(value: String) = when (value) { "bintray" -> Bintray "maven-central" -> MavenCentral "maven-central-snapshot" -> MavenCentralSnapshot else -> throw IllegalArgumentException("Unknown publication_channel=$value") } } } internal val Project.publicationChannels: Set<PublicationChannel> get() = properties["publication_channels"] ?.toString() ?.split(",") ?.map { channel -> PublicationChannel.fromPropertyString(channel) } ?.toSet() .orEmpty()
apache-2.0
440a0c450b97be9fccf7ee993fb04c68
27.057143
88
0.605906
4.91
false
false
false
false
mehulsbhatt/emv-bertlv
src/main/java/io/github/binaryfoo/decoders/CVRule.kt
1
1490
package io.github.binaryfoo.decoders public class CVRule(hexString: String) { private val failIfUnsuccessful: Boolean private val verificationMethod: CardholderVerificationMethod? private val conditionCode: CardholderVerificationConditionCode? { val leftByte = Integer.parseInt(hexString.substring(0, 2), 16) val rightByte = Integer.parseInt(hexString.substring(2, 4), 16) failIfUnsuccessful = (leftByte and 0x40) == 0 verificationMethod = CardholderVerificationMethod.fromCode(leftByte and 0x3F) conditionCode = CardholderVerificationConditionCode.fromCode(rightByte) } public fun getDescription(x: Int, y: Int): String { var baseRule = "$verificationMethodDescription, $conditionCodeDescription, ${if (failIfUnsuccessful) "FAIL" else "next"}" if (conditionCode == CardholderVerificationConditionCode.TxLessThanX || conditionCode == CardholderVerificationConditionCode.TxMoreThanX) { baseRule += " (x = $x)" } else if (conditionCode == CardholderVerificationConditionCode.TxLessThanY || conditionCode == CardholderVerificationConditionCode.TxMoreThanY) { baseRule += " (y = $y)" } return baseRule } public val verificationMethodDescription: String = if (verificationMethod == null) "Unknown" else verificationMethod.description public val conditionCodeDescription: String = if (conditionCode == null) "Unknown" else conditionCode.description }
mit
55003d0ba99bb0efab6334fc8c7e6080
48.7
154
0.731544
4.570552
false
false
false
false
mingdroid/tumbviewer
app/src/main/java/com/nutrition/express/ui/post/tagged/TaggedActivity.kt
1
5506
package com.nutrition.express.ui.post.tagged import android.app.SearchManager import android.content.Context import android.media.AudioManager.STREAM_MUSIC import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.inputmethod.InputMethodManager import androidx.activity.viewModels import androidx.appcompat.widget.SearchView import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.nutrition.express.R import com.nutrition.express.application.BaseActivity import com.nutrition.express.application.toast import com.nutrition.express.common.CommonRVAdapter import com.nutrition.express.common.MyExoPlayer import com.nutrition.express.databinding.ActivityTaggedBinding import com.nutrition.express.model.api.Resource import com.nutrition.express.model.data.bean.PhotoPostsItem import com.nutrition.express.model.data.bean.VideoPostsItem import com.nutrition.express.model.api.bean.PostsItem import com.nutrition.express.ui.post.blog.BlogViewModel import com.nutrition.express.ui.post.blog.PhotoPostVH import com.nutrition.express.ui.post.blog.VideoPostVH class TaggedActivity : BaseActivity() { private lateinit var binding: ActivityTaggedBinding private lateinit var adapter: CommonRVAdapter private val taggedViewModel: TaggedViewModel by viewModels() private val blogViewModel: BlogViewModel by viewModels() private var featuredTimestamp: Long? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTaggedBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolBar) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.recyclerView.layoutManager = LinearLayoutManager(this) adapter = getAdapter() adapter.append(null, false) binding.recyclerView.adapter = adapter volumeControlStream = STREAM_MUSIC taggedViewModel.postData.observe(this, Observer { when (it) { is Resource.Success -> { val list = it.data if (list != null && list.isNotEmpty()) { featuredTimestamp = list[list.size - 1].postsItem.featured_timestamp } var hasNextPage = true featuredTimestamp?.let { time -> hasNextPage = time > 0 } adapter.append(list?.toTypedArray(), hasNextPage) } is Resource.Error -> adapter.showLoadingFailure(getString(R.string.load_failure_des, it.code, it.message)) is Resource.Loading -> {} } }) blogViewModel.deletePostData.observe(this, Observer { when (it) { is Resource.Success -> { val list = adapter.getData() for (index in list.indices) { val item = list[index] if (item is PostsItem) { if (it.data == item.id.toString()) { adapter.remove(index) } } } } is Resource.Error -> toast(it.message) is Resource.Loading -> {} } }) } private fun getAdapter() : CommonRVAdapter { return CommonRVAdapter.adapter { addViewType(PhotoPostsItem::class, R.layout.item_post) { PhotoPostVH(it) } addViewType(VideoPostsItem::class, R.layout.item_video_post) { VideoPostVH(it) } loadListener = object : CommonRVAdapter.OnLoadListener { override fun retry() { taggedViewModel.retryIfFailed() } override fun loadNextPage() { taggedViewModel.getNextPage(featuredTimestamp) } } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_search, menu) val menuItem = menu.findItem(R.id.action_search) val searchView: SearchView? = menuItem?.actionView as SearchView searchView?.run { val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager setSearchableInfo(searchManager.getSearchableInfo(componentName)) setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { query?.let { taggedViewModel.setTag(query) adapter.showReloading() } val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) searchView.clearFocus() return true } override fun onQueryTextChange(newText: String?): Boolean { return false } }) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } override fun onStop() { super.onStop() MyExoPlayer.stop() } }
apache-2.0
7d04e60881bfd5f72af569acb6e7116b
38.611511
122
0.618053
5.214015
false
false
false
false
vovagrechka/k2php
k2php/src/org/jetbrains/kotlin/js/translate/context/DeclarationExporter.kt
1
8824
/* * Copyright 2010-2016 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.kotlin.js.translate.context import k2php.* import org.jetbrains.kotlin.js.backend.ast.metadata.staticRef import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.isInlineOnlyOrReifiable import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isLibraryObject import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils.isNativeObject import org.jetbrains.kotlin.js.translate.utils.JsAstUtils import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.assignment import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils import org.jetbrains.kotlin.js.translate.utils.TranslationUtils import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.DescriptorUtils internal class DeclarationExporter(val context: StaticContext) { private val objectLikeKinds = setOf(ClassKind.OBJECT, ClassKind.ENUM_ENTRY) private val exportedDeclarations = mutableSetOf<MemberDescriptor>() private val localPackageNames = mutableMapOf<FqName, JsName>() val statements = mutableListOf<JsStatement>() fun export(descriptor: MemberDescriptor, force: Boolean) { if (exportedDeclarations.contains(descriptor)) return if (descriptor is ConstructorDescriptor && descriptor.isPrimary) return if (isNativeObject(descriptor) || isLibraryObject(descriptor)) return if (descriptor.isInlineOnlyOrReifiable()) return val suggestedName = context.nameSuggestion.suggest(descriptor) ?: return val container = suggestedName.scope if (!descriptor.shouldBeExported(force)) return exportedDeclarations.add(descriptor) val qualifier = when { container is PackageFragmentDescriptor -> { getLocalPackageReference(container.fqName) } DescriptorUtils.isObject(container) -> { JsAstUtils.prototypeOf(context.getInnerNameForDescriptor(container).makeRef()) } else -> { context.getInnerNameForDescriptor(container).makeRef() } } when { descriptor is ClassDescriptor && descriptor.kind in objectLikeKinds -> { exportObject(descriptor, qualifier) } descriptor is PropertyDescriptor && container is PackageFragmentDescriptor -> { exportProperty(descriptor, qualifier) } else -> { // @possibly-needed // assign(descriptor, qualifier, context.getInnerNameForDescriptor(descriptor).makeRef().setKind(PHPNameRefKind.STRING_LITERAL)) // assign(descriptor, qualifier, context.getInnerNameForDescriptor(descriptor).makeRef()) } } } private fun assign(descriptor: DeclarationDescriptor, qualifier: JsExpression, expression: JsExpression) { val propertyName = context.getNameForDescriptor(descriptor) if (propertyName.staticRef == null) { if (expression !is JsNameRef || expression.name !== propertyName) { propertyName.staticRef = expression } } statements += assignment(JsNameRef(propertyName, qualifier), expression).makeStmt() } // @fucking Export object private fun exportObject(declaration: ClassDescriptor, qualifier: JsExpression) { val name = context.getNameForDescriptor(declaration) if (qualifier is JsNameRef && qualifier.qualifier == null) { qualifier.kind = PHPNameRefKind.VAR } val statement = JsInvocation( JsNameRef("__photlin_defineProperty", qualifier), JsStringLiteral(name.ident), JsObjectLiteral(listOf(JsPropertyInitializer(JsNameRef("get"), JsFunction(context.rootScope, JsBlock( JsReturn(JsInvocation(context.getNameForObjectInstance(declaration).makeRef())) ), "description?")))) ).makeStmt() if (qualifier is JsNameRef && qualifier.ident == "prototype") { (statement as AbstractNode).commentedOut = true } statements += statement // statements += JsAstUtils.defineGetter(context.program, qualifier, name.ident, // context.getNameForObjectInstance(declaration).makeRef()) } private fun exportProperty(declaration: PropertyDescriptor, qualifier: JsExpression) { val propertyLiteral = JsObjectLiteral(true) val name = context.getNameForDescriptor(declaration).ident val simpleProperty = JsDescriptorUtils.isSimpleFinalProperty(declaration) && !TranslationUtils.shouldAccessViaFunctions(declaration) val getterBody: JsExpression = if (simpleProperty) { val accessToField = JsReturn(context.getInnerNameForDescriptor(declaration).makePHPVarRef()) JsFunction(context.rootFunction.scope, JsBlock(accessToField), "$declaration getter") } else { JsFunction(context.rootFunction.scope, JsBlock( JsReturn( JsInvocation(context.getInnerNameForDescriptor(declaration.getter!!).makeRef())) ), "pizda") } propertyLiteral.propertyInitializers += JsPropertyInitializer(JsNameRef("get"), getterBody) if (declaration.isVar) { val setterBody: JsExpression = if (simpleProperty) { val statements = mutableListOf<JsStatement>() val function = JsFunction(context.rootFunction.scope, JsBlock(statements), "$declaration setter") val valueName = function.scope.declareTemporaryName("value") function.parameters += JsParameter(valueName) statements += assignment(context.getInnerNameForDescriptor(declaration).makePHPVarRef(), valueName.makeRef()).makeStmt() function } else { val block = JsBlock() val function = JsFunction(context.rootFunction.scope, block, "pizda") val pizdaParameterName = function.scope.declareFreshName("pizda") block.statements += JsReturn(JsInvocation( context.getInnerNameForDescriptor(declaration.setter!!).makeRef(), pizdaParameterName.makePHPVarRef())) function.parameters.add(JsParameter(pizdaParameterName)) function } propertyLiteral.propertyInitializers += JsPropertyInitializer(JsNameRef("set"), setterBody) } statements += JsInvocation( JsNameRef("__photlin_defineProperty", qualifier), JsStringLiteral(name), propertyLiteral) .makeStmt() // statements += JsAstUtils.defineProperty(qualifier, name, propertyLiteral, context.program).makeStmt() } private fun getLocalPackageReference(packageName: FqName): JsExpression { val res = run { if (packageName.isRoot) { return@run context.rootFunction.scope.declareName(Namer.getRootPackageName()).makePHPVarRef() } var name = localPackageNames[packageName] if (name == null) { name = context.rootFunction.scope.declareTemporaryName("package$" + packageName.shortName().asString()) localPackageNames.put(packageName, name) val parentRef = getLocalPackageReference(packageName.parent()) val selfRef = JsNameRef(packageName.shortName().asString(), parentRef) selfRef.suppressWarnings = true val rhs = JsAstUtils.elvis(selfRef, assignment(selfRef.deepCopy(), JsObjectLiteral(false))) // @fucking packages statements.add(JsAstUtils.newVar(name, rhs)) } return@run name.makePHPVarRef() } return res } } private fun MemberDescriptor.shouldBeExported(force: Boolean) = force || effectiveVisibility(checkPublishedApi = true).publicApi || AnnotationsUtils.getJsNameAnnotation(this) != null
apache-2.0
38b61af823213091ff515f61f6d0b4c4
44.958333
144
0.669311
5.115362
false
false
false
false
bs616/Note
app/src/main/java/com/dev/bins/note/bean/Account.kt
1
622
package com.dev.bins.note.bean import com.dev.bins.note.model.DataBase import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel /** * Created by bin on 21/11/2017. */ @Table(name = "Account",database = DataBase::class) class Account :BaseModel(){ var isOk = false var msg="" var localUserId:Long = -1 var userId = "" var userName = "" var email = "" var verified = false var avatar = "" var accessToken = "" var host = "" var usn = 0 var noteUsn = 0 var noteBookUsn = 0 var lastSyncUsn:Long = 0 }
apache-2.0
003b785a3b5ac4cbbff71da01e32726a
13.833333
54
0.633441
3.616279
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/viewmodel/PlaysViewModel.kt
1
6863
package com.boardgamegeek.ui.viewmodel import android.app.Application import androidx.lifecycle.* import com.boardgamegeek.BggApplication import com.boardgamegeek.R import com.boardgamegeek.entities.PlayEntity import com.boardgamegeek.entities.RefreshableResource import com.boardgamegeek.extensions.PREFERENCES_KEY_SYNC_PLAYS import com.boardgamegeek.livedata.Event import com.boardgamegeek.livedata.LiveSharedPreference import com.boardgamegeek.provider.BggContract import com.boardgamegeek.repository.GameRepository import com.boardgamegeek.repository.PlayRepository import com.boardgamegeek.service.SyncService import com.boardgamegeek.util.RateLimiter import kotlinx.coroutines.launch import java.lang.Exception import java.util.concurrent.TimeUnit class PlaysViewModel(application: Application) : AndroidViewModel(application) { private val syncPlays = LiveSharedPreference<Boolean>(getApplication(), PREFERENCES_KEY_SYNC_PLAYS) private val playsRateLimiter = RateLimiter<Int>(10, TimeUnit.MINUTES) private val playRepository = PlayRepository(getApplication()) private val gameRepository = GameRepository(getApplication()) private data class PlayInfo( val mode: Mode, val name: String = "", val id: Int = BggContract.INVALID_ID, val filter: FilterType = FilterType.ALL, val sort: SortType = SortType.DATE ) enum class Mode { ALL, GAME, BUDDY, PLAYER, LOCATION } enum class FilterType { ALL, DIRTY, PENDING } enum class SortType { DATE, LOCATION, GAME, LENGTH } private val playInfo = MutableLiveData<PlayInfo>() private val locationRenameCount = MutableLiveData<PlayRepository.RenameLocationResults>() val updateMessage: LiveData<Event<String>> = locationRenameCount.map { result -> setLocation(result.newLocationName) SyncService.sync(getApplication(), SyncService.FLAG_SYNC_PLAYS_UPLOAD) Event( getApplication<BggApplication>().resources.getQuantityString( R.plurals.msg_play_location_change, result.count, result.count, result.oldLocationName, result.newLocationName ) ) } private val _errorMessage = MutableLiveData<String>() val errorMessage: LiveData<Event<String>> = _errorMessage.map { Event(it) } private val _syncingStatus = MutableLiveData<Boolean>() val syncingStatus: LiveData<Boolean> get() = _syncingStatus val plays: LiveData<RefreshableResource<List<PlayEntity>>> = playInfo.switchMap { liveData { try { val list = loadPlays(it) val refreshedList = if (syncPlays.value == true && playsRateLimiter.shouldProcess(it.id)) { emit(RefreshableResource.refreshing(list)) SyncService.sync(getApplication(), SyncService.FLAG_SYNC_PLAYS_UPLOAD) when (it.mode) { Mode.GAME -> gameRepository.refreshPlays(it.id) // TODO - full or partial? else -> playRepository.refreshPlays() } loadPlays(it) } else list emit(RefreshableResource.success(refreshedList)) } catch (e: Exception) { playsRateLimiter.reset(0) emit(RefreshableResource.error(e, getApplication())) } } } fun refresh() { playInfo.value.let { playInfo.value = it } } private suspend fun loadPlays(it: PlayInfo) = when (it.mode) { Mode.ALL -> { val sortType = when (it.sort) { SortType.DATE -> PlayRepository.SortBy.DATE SortType.LOCATION -> PlayRepository.SortBy.LOCATION SortType.GAME -> PlayRepository.SortBy.GAME SortType.LENGTH -> PlayRepository.SortBy.LENGTH } when (it.filter) { FilterType.ALL -> playRepository.getPlays(sortType) FilterType.DIRTY -> playRepository.getDraftPlays() FilterType.PENDING -> playRepository.getPendingPlays() } } Mode.GAME -> gameRepository.getPlays(it.id) Mode.LOCATION -> playRepository.loadPlaysByLocation(it.name) Mode.BUDDY -> playRepository.loadPlaysByUsername(it.name) Mode.PLAYER -> playRepository.loadPlaysByPlayerName(it.name) } val filterType: LiveData<FilterType> = playInfo.map { it.filter } val sortType: LiveData<SortType> = playInfo.map { it.sort } val location: LiveData<String> = playInfo.map { if (it.mode == Mode.LOCATION) it.name else "" } fun setGame(gameId: Int) { playInfo.value = PlayInfo(Mode.GAME, id = gameId) } fun setLocation(locationName: String) { playInfo.value = PlayInfo(Mode.LOCATION, locationName) } fun setUsername(username: String) { playInfo.value = PlayInfo(Mode.BUDDY, username) } fun setPlayerName(playerName: String) { playInfo.value = PlayInfo(Mode.PLAYER, playerName) } fun setFilter(type: FilterType) { if (playInfo.value?.filter != type) { playInfo.value = PlayInfo(Mode.ALL, filter = type, sort = playInfo.value?.sort ?: SortType.DATE) } } fun setSort(type: SortType) { if (playInfo.value?.sort != type) { playInfo.value = PlayInfo(Mode.ALL, filter = playInfo.value?.filter ?: FilterType.ALL, sort = type) } } fun renameLocation(oldLocationName: String, newLocationName: String) { viewModelScope.launch { val results = playRepository.renameLocation(oldLocationName, newLocationName) locationRenameCount.postValue(results) } } fun syncPlaysByDate(timeInMillis: Long) { viewModelScope.launch { try { _syncingStatus.postValue(true) playRepository.refreshPlays(timeInMillis) refresh() } catch (e: Exception) { _errorMessage.postValue(e.localizedMessage ?: e.message ?: e.toString()) } finally { _syncingStatus.postValue(false) } } } fun send(plays: List<PlayEntity>) { viewModelScope.launch { plays.forEach { playRepository.markAsUpdated(it.internalId) } SyncService.sync(getApplication(), SyncService.FLAG_SYNC_PLAYS_UPLOAD) } } fun delete(plays: List<PlayEntity>) { viewModelScope.launch { plays.forEach { playRepository.markAsDeleted(it.internalId) } SyncService.sync(getApplication(), SyncService.FLAG_SYNC_PLAYS_UPLOAD) } } }
gpl-3.0
cd712daf538c70d45fe35a1ed4eab934
34.376289
111
0.632085
4.637162
false
false
false
false
MichaelRocks/Sunny
app/src/main/kotlin/io/michaelrocks/forecast/model/repository/sqlite/CachingForecastRepository.kt
1
6501
/* * Copyright 2016 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.forecast.model.repository.sqlite import android.location.Location import android.util.Log import io.michaelrocks.forecast.model.City import io.michaelrocks.forecast.model.Forecast import io.michaelrocks.forecast.model.MainThread import io.michaelrocks.forecast.model.Temperature import io.michaelrocks.forecast.model.Weather import io.michaelrocks.forecast.model.WeatherType import io.michaelrocks.forecast.model.forecast.WeatherFetcher import io.michaelrocks.forecast.model.repository.ForecastRepository import io.michaelrocks.forecast.model.repository.Operation import rx.Observable import rx.Scheduler import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import java.util.ArrayList import java.util.Date import java.util.UUID import java.util.concurrent.TimeUnit import javax.inject.Inject private const val TAG = "CachingForecastRepository" internal class CachingForecastRepository @Inject private constructor( private val preferences: LocationStorage, private val storage: SqliteForecastStorage, private val fetcher: WeatherFetcher, @MainThread private val mainThreadScheduler: Scheduler ) : ForecastRepository { private val distanceResult = FloatArray(1) private val forecasts = ArrayList<Forecast>() private val operationsSubject = PublishSubject.create<Operation<Forecast>>() override val operations: Observable<Operation<Forecast>> = getInitialOperation().concatWith(operationsSubject) override val refreshing = BehaviorSubject.create(false) override fun updateCurrentLocation(latitude: Double, longitude: Double) { val oldLatitude = preferences.latitude val oldLongitude = preferences.longitude distanceResult[0] = Float.NaN if (!oldLatitude.isNaN() && !oldLongitude.isNaN()) { Location.distanceBetween(oldLatitude, oldLongitude, latitude, longitude, distanceResult) } if (distanceResult[0].isNaN() || distanceResult[0] >= 1000f) { preferences.updateCoordinates(latitude, longitude) updateForecastByCoordinates(CURRENT_LOCATION_UUID, latitude, longitude) } } override fun addForecast(id: UUID, city: City) { val forecast = Forecast(id, Date(0L), city, Temperature(0f, 0f, 0f, 0f, 0f), Weather(WeatherType.INVALID, "")) performAddForecastOperation(forecast) storage.createForecast(id, city) .concatWith(updateForecast(id, city)) .subscribe({}, { Log.e(TAG, "Failed to add $city with id $id", it) }) } override fun removeForecast(id: UUID) { performRemoveForecastOperation(id) storage.removeForecast(id) .subscribe({}, { Log.e(TAG, "Failed to remove a city with id $id", it) }) } override fun refreshForecasts(): Boolean { if (refreshing.value) { return false } refreshing.onNext(true) storage .getForecasts() .observeOn(mainThreadScheduler) .doOnNext { forecasts.clear() forecasts.addAll(it) operationsSubject.onNext(Operation.ReplaceOperation(ArrayList(it))) } .flatMap { Observable.from(it) } .concatMap { updateForecast(it.id, it.city) } .observeOn(mainThreadScheduler) .doOnTerminate { refreshing.onNext(false) } .subscribe({}, { Log.e(TAG, "Failed to refresh forecasts", it) }) return true } private fun updateForecast(id: UUID, city: City): Observable<Unit> = if (city.id == CURRENT_LOCATION_ID) { updateForecastByCoordinates(id, preferences.latitude, preferences.longitude) } else { updateForecastByCityId(id, city) } private fun updateForecastByCoordinates(id: UUID, latitude: Double, longitude: Double): Observable<Unit> = if (latitude.isNaN() || longitude.isNaN()) { Observable.empty() } else { fetcher .getForecast(id, latitude, longitude) .process { "Failed to update forecast for ($latitude, $longitude)" } } private fun updateForecastByCityId(id: UUID, city: City): Observable<Unit> = fetcher .getForecast(id, city.id) .process { "Failed to update forecast for ${city.name}, ${city.country}" } private fun Observable<Forecast>.process(error: () -> String) = retry(3) { Observable.timer(1L, TimeUnit.SECONDS) } .observeOn(mainThreadScheduler) .persist() .doOnError { Log.e(TAG, error(), it) } .onErrorResumeNext { Observable.empty() } .subscribeOn(Schedulers.io()) private fun <T> Observable<T>.retry(count: Int, delay: (Int) -> Observable<in Nothing>) = retryWhen { errors -> errors .zipWith(Observable.range(1, count)) { error, index -> index } .flatMap { delay(it) } } private fun Observable<Forecast>.persist() = doOnNext { performUpdateForecastOperation(it) } .concatMap { storage.updateForecast(it) } private fun getInitialOperation(): Observable<Operation<Forecast>> = Observable.defer { val operation: Operation<Forecast> = Operation.AddOperation(0, ArrayList(forecasts)) Observable.just(operation) } private fun performAddForecastOperation(forecast: Forecast) { forecasts.add(forecast) operationsSubject.onNext(Operation.AddOperation(forecasts.lastIndex, listOf(forecast))) } private fun performUpdateForecastOperation(forecast: Forecast) { val index = forecasts.indexOfFirst { it.id == forecast.id } if (index >= 0) { forecasts[index] = forecast operationsSubject.onNext(Operation.ChangeOperation(index, listOf(forecast))) } } private fun performRemoveForecastOperation(id: UUID) { val index = forecasts.indexOfFirst { it.id == id } if (index >= 0) { forecasts.removeAt(index) operationsSubject.onNext(Operation.RemoveOperation(index, 1)) } } }
apache-2.0
0783909478f9e1d4e4691c1000940243
36.148571
114
0.706199
4.325349
false
false
false
false
googleapis/gapic-generator-kotlin
generator/src/test/kotlin/com/google/api/kotlin/config/ConfigurationTest.kt
1
4612
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.kotlin.config import com.google.api.kotlin.BaseClientGeneratorTest import com.google.common.truth.Truth.assertThat import com.google.rpc.Code import kotlin.test.Test import kotlin.test.fail internal class ConfigurationTest : BaseClientGeneratorTest("test_annotations", "AnnotationServiceClient") { @Test fun `can use default for file level proto annotations`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) // assertThat(config.branding.name).isEqualTo("") assertThat(config.packageName).isEqualTo("google.example") } @Test fun `can parse file level proto annotations`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) // assertThat(config.branding.name).isEqualTo("The Test Product") assertThat(config.packageName).isEqualTo("google.example") } @Test fun `can detected a long running method`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) val method = config["google.example.AnnotationService"].methods.first { it.name == "AnnotationLongRunningTest" } val operation = method.longRunningResponse ?: fail("long running response is null") assertThat(operation.responseType).isEqualTo(".google.example.TheLongRunningResponse") assertThat(operation.metadataType).isEqualTo(".google.example.TheLongRunningMetadata") } @Test fun `can detect method signatures`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) val method = config["google.example.AnnotationService"].methods.find { it.name == "AnnotationSignatureTest" } val signatures = method?.flattenedMethods ?: fail("method signatures not found") assertThat(signatures).hasSize(2) assertThat(signatures[0].parameters).containsExactly( "foo".asPropertyPath() ).inOrder() assertThat(signatures[1].parameters).containsExactly( "foo".asPropertyPath(), "other.foo".asPropertyPath() ).inOrder() } @Test fun `does not make up method signatures`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) val method = config["google.example.AnnotationService"].methods.find { it.name == "AnnotationTest" } val signatures = method?.flattenedMethods ?: fail("method signatures not found") assertThat(signatures).isEmpty() } // @Test // fun `can detect retry settings`() { // val factory = AnnotationConfigurationFactory(AuthOptions(), getMockedTypeMap()) // val config = factory.fromProto(testAnnotationsProto) // // val method = config["google.example.AnnotationService"].methods.first { it.name == "AnnotationRetryTest" } // // assertThat(method.retry).isNotNull() // assertThat(method.retry!!.codes).containsExactly(Code.UNKNOWN, Code.NOT_FOUND).inOrder() // } @Test fun `can detect default retry settings`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) val method = config["google.example.AnnotationService"].methods.first { it.name == "AnnotationRetryDefaultTest" } assertThat(method.retry).isNotNull() assertThat(method.retry!!.codes).containsExactly(Code.UNAVAILABLE, Code.DEADLINE_EXCEEDED) } @Test fun `does not make up retry settings`() { val factory = AnnotationConfigurationFactory(AuthOptions(), typeMap) val config = factory.fromProto(proto) val method = config["google.example.AnnotationService"].methods.first { it.name == "AnnotationTest" } assertThat(method.retry).isNull() } }
apache-2.0
0dde7ab26fd2fe858d6eb9700e40cdaa
38.084746
120
0.694926
4.639839
false
true
false
false
WindSekirun/RichUtilsKt
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/DimenSet.kt
1
1728
package pyxis.uzuki.live.richutilskt.demo.set import android.content.Context import pyxis.uzuki.live.richutilskt.demo.R import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem import pyxis.uzuki.live.richutilskt.utils.* /** * Created by pyxis on 06/11/2017. */ fun Context.getDimenSet(): ArrayList<ExecuteItem> { val list = arrayListOf<ExecuteItem>() val dip2px = generateExecuteItem(CategoryItem.DIMEN, "dip2px", getString(R.string.dimen_message_dip2px), "dip2px(15)", "RichUtils.dip2px(this, 15);") { it.toast(it.dip2px(15).toString()) } list.add(dip2px) val sp2px = generateExecuteItem(CategoryItem.DIMEN, "sp2px", getString(R.string.dimen_message_sp2px), "sp2px(15)", "RichUtils.sp2px(this, 15);") { it.toast(it.sp2px(15).toString()) } list.add(sp2px) val px2dip = generateExecuteItem(CategoryItem.DIMEN, "px2dip", getString(R.string.dimen_message_px2dip), "px2dip(15)", "RichUtils.px2dip(this, 15);") { it.toast(it.px2dip(15).toString()) } list.add(px2dip) val px2sp = generateExecuteItem(CategoryItem.DIMEN, "px2sp", getString(R.string.dimen_message_px2sp), "px2sp(15)", "RichUtils.px2sp(this, 15);") { it.toast(it.px2sp(15).toString()) } list.add(px2sp) val dimen = generateExecuteItem(CategoryItem.DIMEN, "dimen", getString(R.string.dimen_message_dimen), "dimen(R.dimen.pixel_size)", "RichUtils.dimen(this, R.dimen.pixel_size);") list.add(dimen) return list }
apache-2.0
5c325481b911a46a5e226a597c18f66e
28.810345
108
0.66088
3.375
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/ui/adapter/LazyFragmentPagerAdapter.kt
1
3261
package taiwan.no1.app.ui.adapter import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.view.View import android.view.ViewGroup /** * * @author Jieyi * @since 3/19/17 */ abstract class LazyFragmentPagerAdapter(private val fragmentManager: FragmentManager): LazyPagerAdapter<Fragment>() { companion object { private fun makeFragmentName(viewId: Int, id: Long): String = "android:switcher:$viewId:$id" } private var currTransaction: FragmentTransaction? = null override fun instantiateItem(container: ViewGroup, position: Int): Any { if (null == this.currTransaction) this.currTransaction = this.fragmentManager.beginTransaction() val itemId = this.getItemId(position) // Do we already have this fragment? val name = makeFragmentName(container.id, itemId) var fragment = this.fragmentManager.findFragmentByTag(name) // FIXME: 4/25/17 : 4/25/17 這邊有問題,導致沒辦法 1 -> 4 -> 2 顯示畫面。 if (null != fragment) { this.currTransaction?.attach(fragment) } else { fragment = this.getItem(container, position) if (fragment is Laziable) this.lazyItems.put(position, fragment) else this.currTransaction?.add(container.id, fragment, name) } if (fragment !== this.currentItem) { fragment.setMenuVisibility(false) fragment.userVisibleHint = false } return fragment } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { if (null == this.currTransaction) this.currTransaction = this.fragmentManager.beginTransaction() val itemId = this.getItemId(position) val name = makeFragmentName(container.id, itemId) if (null == this.fragmentManager.findFragmentByTag(name)) this.currTransaction?.detach(`object` as Fragment) else this.lazyItems.remove(position) } override fun addLazyItem(container: ViewGroup, position: Int): Fragment? { val fragment = lazyItems.get(position) ?: return null val itemId = this.getItemId(position) val name = makeFragmentName(container.id, itemId) if (null == this.fragmentManager.findFragmentByTag(name)) { if (null == this.currTransaction) this.currTransaction = this.fragmentManager.beginTransaction() this.currTransaction!!.add(container.id, fragment, name) this.lazyItems.remove(position) } return fragment } override fun finishUpdate(container: ViewGroup) { if (null != this.currTransaction) { this.currTransaction!!.commitAllowingStateLoss() this.currTransaction = null this.fragmentManager.executePendingTransactions() } } override fun isViewFromObject(view: View, `object`: Any): Boolean = (`object` as Fragment).view === view fun getItemId(position: Int): Long = position.toLong() /** * Mark the fragment can be added lazily. */ interface Laziable }
apache-2.0
8a62ad0cfef3c63de262d372ae51a6c8
33
117
0.649427
4.478502
false
false
false
false
andreyfomenkov/green-cat
plugin/src/ru/fomenkov/plugin/repository/ArtifactDependencyResolver.kt
1
5252
package ru.fomenkov.plugin.repository import ru.fomenkov.plugin.repository.data.PomDescriptor import ru.fomenkov.plugin.repository.parser.PomFileParser import ru.fomenkov.plugin.util.Telemetry import ru.fomenkov.plugin.util.noTilda import java.io.File import java.lang.StringBuilder class ArtifactDependencyResolver( private val jetifiedJarRepository: JetifiedJarRepository, private val pomFileParser: PomFileParser, ) { private val cacheDir = "~/.gradle/caches/modules-2/files-2.1".noTilda() // TODO: search between modules-X private val output = mutableMapOf<PomDescriptor, Set<String>>() // POM -> JAR/AAR paths init { if (!File(cacheDir).exists()) { error("Gradle cache path doesn't exist: $cacheDir") } jetifiedJarRepository.scan() } fun resolvePaths(groupId: String, artifactId: String, version: String): Set<String> { try { resolve(groupId, artifactId, version, 0) output.forEach { (desc, _) -> val paths = jetifiedJarRepository.getArtifactPaths(desc.artifactId, desc.version) if (paths.isNotEmpty()) { output[desc] = paths } } } catch (error: Throwable) { Telemetry.verboseErr("Failed to resolve paths (message = ${error.localizedMessage})") } val result = mutableSetOf<String>() output.values.forEach { paths -> result += paths } return result } private fun resolve(groupId: String, artifactId: String, version: String, level: Int) { val descriptor = PomDescriptor(groupId, artifactId, version) if (descriptor in output) { return } var versionDir = File(getVersionDir(groupId, artifactId, version)) if (!versionDir.exists()) { val artifactDir = getArtifactDir(groupId, artifactId) val allVersions = File(artifactDir).list { file, _ -> file.isDirectory } ?: emptyArray() val latestVersion = getLatestVersion(artifactDir, allVersions) versionDir = File(getVersionDir(groupId, artifactId, latestVersion)) } if (versionDir.exists()) { val resources = listVersionDirResources(versionDir.absolutePath) val pomPaths = resources.filter { path -> path.endsWith(".pom") } val archivePaths = resources .filter { path -> path.endsWith(".jar") || path.endsWith(".aar") } .filterNot { path -> path.endsWith("-sources.jar") } .filterNot { path -> path.endsWith("-javadoc.jar") } val pom = when (pomPaths.size) { 0 -> null // No POM file can be found 1 -> pomFileParser.parse(pomPaths.first()) else -> error("Multiple POM files found at ${versionDir.absolutePath}") } val archives = when (archivePaths.size) { 0 -> null else -> archivePaths.toSet() } if (archives == null) { Telemetry.verboseErr("No archives found at ${versionDir.absolutePath}") } else { output += descriptor to archives } pom?.dependencies?.forEach { dep -> if (dep.scope.isTransitive()) { val artifactDir = getArtifactDir(dep.descriptor.groupId, dep.descriptor.artifactId) if (File(artifactDir).exists()) { val allVersions = File(artifactDir).list { file, _ -> file.isDirectory } ?: emptyArray() val latestVersion = getLatestVersion(artifactDir, allVersions) resolve(dep.descriptor.groupId, dep.descriptor.artifactId, latestVersion, level + 1) } else { Telemetry.verboseErr("No artifact directory: $artifactDir") } } } } else { error("No artifact directory: ${versionDir.absolutePath}") } } private fun listVersionDirResources(path: String): List<String> { val resources = mutableListOf<String>() val hashDirs = File(path).list { file, _ -> file.isDirectory } ?: emptyArray() hashDirs.forEach { hashDir -> resources += File("$path/$hashDir") .listFiles() ?.map { file -> file.absolutePath } ?: emptyList() } return resources } private fun getVersionDir(groupId: String, artifactId: String, version: String) = "$cacheDir/$groupId/$artifactId/$version" private fun getArtifactDir(groupId: String, artifactId: String) = "$cacheDir/$groupId/$artifactId" private fun getLatestVersion(artifactDir: String, versions: Array<String>) = when { versions.isEmpty() -> error("No available versions for artifact: $artifactDir") else -> versions.maxOrNull()!! } private fun spaces(level: Int): String { return if (level > 0) { val builder = StringBuilder() for (i in 0 until level) { builder.append("-") } builder.toString() } else { "" } } }
apache-2.0
8230fc688c1b1d304764d408d6dfd897
40.362205
127
0.581874
4.818349
false
true
false
false
FHannes/intellij-community
java/java-tests/testSrc/com/intellij/find/impl/JavaReadWriteAccessTest.kt
2
3391
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.find.impl import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector import com.intellij.psi.PsiFile import com.intellij.psi.PsiMethodCallExpression import com.intellij.psi.PsiNameValuePair import com.intellij.psi.util.PsiTreeUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase class JavaReadWriteAccessTest : LightCodeInsightFixtureTestCase() { fun testWriteAnnotationsMethodExplicitCall() { val anno = myFixture.addClass("@interface Anno {String value() default \"\";}") val detector = ReadWriteAccessDetector.findDetector(anno.methods[0]) assertNotNull(detector) val file: PsiFile = myFixture.configureByText("A.java", "@Anno(val<caret>ue = \"foo\") class A {}") val element = file.findElementAt(myFixture.editor.caretModel.offset) assertNotNull(element) val expressionAccess = detector!!.getExpressionAccess(element!!) assertEquals(ReadWriteAccessDetector.Access.Write, expressionAccess) } fun testWriteAnnotationsMethodImplicitCall() { val anno = myFixture.addClass("@interface Anno {String value() default \"\";}") val detector = ReadWriteAccessDetector.findDetector(anno.methods[0]) assertNotNull(detector) val file: PsiFile = myFixture.configureByText("A.java", "@Anno(\"fo<caret>o\") class A {}") val element = file.findElementAt(myFixture.editor.caretModel.offset) assertNotNull(element) val expressionAccess = detector!!.getExpressionAccess(PsiTreeUtil.getParentOfType(element, PsiNameValuePair::class.java, true)!!) assertEquals(ReadWriteAccessDetector.Access.Write, expressionAccess) } fun testExplicitCallToAnnotationMethod() { val anno = myFixture.addClass("@interface Anno {String value() default \"\";}") val detector = ReadWriteAccessDetector.findDetector(anno.methods[0]) assertNotNull(detector) val file: PsiFile = myFixture.configureByText("A.java", "import java.lang.reflect.Field;" + "class A { " + " void m(Field field) { " + " Anno a = field.getAnnotation(Anno.class);" + " System.out.println(a.val<caret>ue());" + " }" + "}") val element = file.findElementAt(myFixture.editor.caretModel.offset) assertNotNull(element) val expressionAccess = detector!!.getExpressionAccess(PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression::class.java, true)!!) assertEquals(ReadWriteAccessDetector.Access.Read, expressionAccess) } }
apache-2.0
c560b02c63bb1149198d7f69713cf200
49.626866
140
0.676792
5.008863
false
true
false
false
andrei-heidelbacher/metanalysis
analyzers/chronolens-decapsulations/src/main/kotlin/org/chronolens/decapsulations/DecapsulationAnalyzer.kt
1
2064
/* * Copyright 2018-2021 Andrei Heidelbacher <[email protected]> * * 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.chronolens.decapsulations import org.chronolens.core.model.SourceTree import org.chronolens.core.model.sourcePath import java.util.ServiceLoader internal abstract class DecapsulationAnalyzer { protected abstract fun canProcess(sourcePath: String): Boolean protected abstract fun getField(sourceTree: SourceTree, nodeId: String): String? protected abstract fun getVisibility(sourceTree: SourceTree, nodeId: String): Int protected abstract fun isConstant(sourceTree: SourceTree, nodeId: String): Boolean companion object { private val analyzers = ServiceLoader.load(DecapsulationAnalyzer::class.java) private fun findAnalyzer( sourceTree: SourceTree, id: String, ): DecapsulationAnalyzer? { if (id !in sourceTree) return null val sourcePath = id.sourcePath return analyzers.find { it.canProcess(sourcePath) } } fun getField(sourceTree: SourceTree, nodeId: String): String? = findAnalyzer(sourceTree, nodeId)?.getField(sourceTree, nodeId) fun getVisibility(sourceTree: SourceTree, nodeId: String): Int? = findAnalyzer(sourceTree, nodeId)?.getVisibility(sourceTree, nodeId) fun isConstant(sourceTree: SourceTree, nodeId: String): Boolean = findAnalyzer(sourceTree, nodeId)?.isConstant(sourceTree, nodeId) == true } }
apache-2.0
28f2aaa1dbc3946aa82e7fb8c57cdad1
37.222222
86
0.714632
4.627803
false
false
false
false
didi/DoraemonKit
Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/extension/CommExt.kt
2
1185
package com.didichuxing.doraemonkit.plugin.extension /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/4/28-14:56 * 描 述: * 修订历史: * ================================================ */ open class CommExt( var gpsSwitch: Boolean = true, var networkSwitch: Boolean = true, var bigImgSwitch: Boolean = true, var webViewSwitch: Boolean = true, var didinetSwitch: Boolean = true ) { fun gpsSwitch(gpsSwitch: Boolean) { this.gpsSwitch = gpsSwitch } fun networkSwitch(networkSwitch: Boolean) { this.networkSwitch = networkSwitch } fun didinetSwitch(didinetSwitch: Boolean) { this.didinetSwitch = didinetSwitch } fun bigImgSwitch(bigImgSwitch: Boolean) { this.bigImgSwitch = bigImgSwitch } fun webViewSwitch(webViewSwitch: Boolean) { this.webViewSwitch = webViewSwitch } override fun toString(): String { return "CommExt(gpsSwitch=$gpsSwitch, networkSwitch=$networkSwitch,didinetSwitch=$didinetSwitch, bigImgSwitch=$bigImgSwitch, webviewSwitch=$webViewSwitch)" } }
apache-2.0
aacc3bcde8da832d1492ff15b5eb83cd
23.782609
163
0.609306
4.024735
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/processmanagers/ActionOnCountdownProcessManager.kt
1
3165
package com.flexpoker.processmanagers import com.flexpoker.framework.command.CommandSender import com.flexpoker.framework.processmanager.ProcessManager import com.flexpoker.game.command.repository.GameEventRepository import com.flexpoker.table.command.commands.ExpireActionOnTimerCommand import com.flexpoker.table.command.commands.TableCommand import com.flexpoker.table.command.commands.TickActionOnTimerCommand import com.flexpoker.table.command.events.ActionOnChangedEvent import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Component import java.util.HashMap import java.util.UUID import java.util.concurrent.ScheduledFuture import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.TimeUnit import javax.inject.Inject @Component class ActionOnCountdownProcessManager @Inject constructor( private val tableCommandSender: CommandSender<TableCommand>, private val gameEventRepository: GameEventRepository ) : ProcessManager<ActionOnChangedEvent> { private val actionOnPlayerScheduledFutureMap: MutableMap<UUID, ScheduledFuture<*>> = HashMap() private val scheduledThreadPoolExecutor: ScheduledThreadPoolExecutor = ScheduledThreadPoolExecutor(16) init { scheduledThreadPoolExecutor.removeOnCancelPolicy = true } @Async override fun handle(event: ActionOnChangedEvent) { clearExistingTimer(event.aggregateId) addNewActionOnTimer(event) } private fun clearExistingTimer(tableId: UUID) { val scheduledFuture = actionOnPlayerScheduledFutureMap[tableId] scheduledFuture?.cancel(true) actionOnPlayerScheduledFutureMap.remove(tableId) } private fun addNewActionOnTimer(event: ActionOnChangedEvent) { val gameCreatedEvent = gameEventRepository.fetchGameCreatedEvent(event.gameId)!! val numberOfSecondsForActionOnTimer = gameCreatedEvent.numberOfSecondsForActionOnTimer val scheduledFuture = scheduledThreadPoolExecutor.scheduleAtFixedRate( ActionOnCounter(event, numberOfSecondsForActionOnTimer), 0, 1, TimeUnit.SECONDS ) actionOnPlayerScheduledFutureMap[event.aggregateId] = scheduledFuture } private inner class ActionOnCounter(event: ActionOnChangedEvent, numberOfSecondsForActionOnTimer: Int) : Runnable { private var runCount = 0 private val gameId: UUID = event.gameId private val tableId: UUID = event.aggregateId private val handId: UUID = event.handId private val playerId: UUID = event.playerId private val numberOfSecondsForActionOnTimer: Int = numberOfSecondsForActionOnTimer override fun run() { if (runCount == numberOfSecondsForActionOnTimer) { clearExistingTimer(handId) tableCommandSender.send(ExpireActionOnTimerCommand(tableId, gameId, handId, playerId)) } else { runCount++ tableCommandSender.send(TickActionOnTimerCommand(tableId, gameId, handId, numberOfSecondsForActionOnTimer - runCount) ) } } } }
gpl-2.0
cf96be2d240c1b25b10c356621beb6db
40.657895
119
0.756082
5.205592
false
false
false
false
lambdasoup/watchlater
app/src/main/java/com/lambdasoup/watchlater/ui/launcher/LauncherActivity.kt
1
4420
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.ui.launcher import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.widget.Toast import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import com.lambdasoup.watchlater.BuildConfig import com.lambdasoup.watchlater.R import com.lambdasoup.watchlater.ui.AboutActivity import com.lambdasoup.watchlater.ui.HelpActivity import com.lambdasoup.watchlater.ui.MenuAction import com.lambdasoup.watchlater.viewmodel.LauncherViewModel import com.lambdasoup.watchlater.viewmodel.LauncherViewModel.Event import org.koin.androidx.viewmodel.ext.android.viewModel class LauncherActivity : AppCompatActivity() { private val vm: LauncherViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LauncherScreen( onOverflowAction = this::onOverflowActionSelected ) } vm.events.observe(this) { event -> when (event) { Event.OpenYouTubeSettings -> openYoutubeSettings() Event.OpenExample -> openExampleVideo() Event.OpenWatchLaterSettings -> openWatchLaterSettings() } } } override fun onResume() { super.onResume() vm.onResume() } private fun onOverflowActionSelected(menuAction: MenuAction) { when (menuAction) { MenuAction.About -> { startActivity(Intent(this, AboutActivity::class.java)) } MenuAction.Help -> { startActivity(Intent(this, HelpActivity::class.java)) } MenuAction.PrivacyPolicy -> { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://lambdasoup.com/privacypolicy-watchlater/") ) ) } MenuAction.Store -> { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID) ) ) } } } private fun openExampleVideo() { startActivity(EXAMPLE_INTENT) } private fun openYoutubeSettings() { val action = when { Build.VERSION.SDK_INT >= 31 -> Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS else -> Settings.ACTION_APPLICATION_DETAILS_SETTINGS } val intent = Intent(action, Uri.parse("package:com.google.android.youtube")) if (packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) == null) { Toast.makeText(this, R.string.no_youtube_settings_activity, Toast.LENGTH_SHORT).show() return } startActivity(intent) } private fun openWatchLaterSettings() { val action = when { Build.VERSION.SDK_INT >= 31 -> Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS else -> Settings.ACTION_APPLICATION_DETAILS_SETTINGS } val intent = Intent(action, Uri.parse("package:$packageName")) startActivity(intent) } companion object { private val EXAMPLE_URI = Uri.parse("https://www.youtube.com/watch?v=dGFSjKuJfrI") private val EXAMPLE_INTENT = Intent(Intent.ACTION_VIEW, EXAMPLE_URI) } }
gpl-3.0
6dabdd7cfde39e0aa1e53a84fa9911b2
34.36
112
0.64276
4.637985
false
false
false
false
ofalvai/BPInfo
app/src/main/java/com/ofalvai/bpinfo/util/Analytics.kt
1
5551
/* * Copyright 2018 Olivér Falvai * * 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.ofalvai.bpinfo.util import android.app.ActivityManager import android.app.usage.UsageStatsManager import android.content.Context import android.os.Build import android.os.Bundle import androidx.core.app.NotificationManagerCompat import androidx.core.content.getSystemService import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.crashlytics.FirebaseCrashlytics import com.ofalvai.bpinfo.model.Alert import com.ofalvai.bpinfo.model.RouteType class Analytics(private val context: Context) { companion object { const val DATA_SOURCE_BKKINFO = "bkkinfo" const val DATA_SOURCE_FUTAR = "futar" } fun setDataSource(dataSource: String) { FirebaseAnalytics.getInstance(context) .setUserProperty("data_source", dataSource) } /** * Checks if notifications are enabled or disabled for the app, and sets the result as a * user property. */ fun setSystemNotificationState() { val enabled = NotificationManagerCompat.from(context).areNotificationsEnabled() FirebaseAnalytics.getInstance(context) .setUserProperty("notifications_enabled", enabled.toString()) } fun setRestrictions() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) return val activityManager = context.getSystemService<ActivityManager>() val isBackgroundRestricted: String = activityManager?.isBackgroundRestricted.toString() FirebaseAnalytics.getInstance(context) .setUserProperty("background_restricted", isBackgroundRestricted) val usageStatsManager = context.getSystemService<UsageStatsManager>() FirebaseAnalytics.getInstance(context) .setUserProperty("app_standby_bucket", usageStatsManager?.appStandbyBucket.toString()) } fun logAlertContentView(alert: Alert?) { alert?.let { val bundle = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, alert.id) putString(FirebaseAnalytics.Param.ITEM_NAME, alert.header) } FirebaseAnalytics.getInstance(context) .logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle) } } fun logAlertUrlClick(alert: Alert?) { alert?.let { val bundle = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, alert.id) } FirebaseAnalytics.getInstance(context).logEvent("alert_url_click", bundle) } } fun logLanguageChange(newValue: String?) { newValue?.let { val bundle = Bundle() bundle.putString("settings_new_language", newValue) FirebaseAnalytics.getInstance(context).logEvent("settings_changed_language", bundle) } } fun logManualRefresh() { FirebaseAnalytics.getInstance(context).logEvent("alert_list_manual_refresh", null) } fun logFilterDialogOpened() { FirebaseAnalytics.getInstance(context).logEvent("alert_filter_open", null) } fun logFilterApplied(routeTypes: Set<RouteType>) { val bundle = Bundle() bundle.putString("alert_filters", routeTypes.toString()) FirebaseAnalytics.getInstance(context).logEvent("alert_filter_apply", bundle) } fun logNoticeDialogView() { FirebaseAnalytics.getInstance(context).logEvent("notice_dialog_view", null) } fun logDataSourceChange() { val bundle = Bundle() FirebaseAnalytics.getInstance(context).logEvent("settings_data_source_changed", bundle) } fun logNotificationSubscribe(routeId: String) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, routeId) FirebaseAnalytics.getInstance(context).logEvent("notif_subscribe_route", bundle) } fun logNotificationUnsubscribe(routeId: String) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, routeId) FirebaseAnalytics.getInstance(context).logEvent("notif_unsubscribe_route", bundle) } fun logNotificationOpen(alertId: String) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, alertId) FirebaseAnalytics.getInstance(context).logEvent("notif_open", bundle) } fun logNotificationChannelsOpened() { FirebaseAnalytics.getInstance(context).logEvent("notif_channels_opened", null) } fun logNotificationFromSettingsOpened() { FirebaseAnalytics.getInstance(context).logEvent("notif_from_settings_opened", null) } fun logDeviceTokenUpdate(newToken: String) { val bundle = Bundle() bundle.putString(FirebaseAnalytics.Param.ITEM_ID, newToken) FirebaseAnalytics.getInstance(context).logEvent("notif_token_update", bundle) } fun logException(exception: Throwable) { FirebaseCrashlytics.getInstance().recordException(exception) } }
apache-2.0
a393e12875d529eb731b2b082a7bd3d3
35.27451
98
0.697658
4.792746
false
false
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/player/FiltersManager.kt
1
2694
package be.florien.anyflow.player import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import be.florien.anyflow.data.DataRepository import be.florien.anyflow.data.view.Filter import be.florien.anyflow.data.view.FilterGroup import javax.inject.Inject import javax.inject.Singleton @Singleton class FiltersManager @Inject constructor(private val dataRepository: DataRepository) { private var currentFilters: List<Filter<*>> = listOf() private val unCommittedFilters = mutableSetOf<Filter<*>>() private var areFiltersChanged = false val filtersInEdition: LiveData<Set<Filter<*>>> = MutableLiveData(setOf()) val filterGroups = dataRepository.getFilterGroups() val hasChange: LiveData<Boolean> = MediatorLiveData<Boolean>().apply { addSource(filtersInEdition) { value = !currentFilters.toTypedArray().contentEquals(it.toTypedArray()) } } init { dataRepository.getCurrentFilters().observeForever { filters -> currentFilters = filters if (!areFiltersChanged) { unCommittedFilters.clear() unCommittedFilters.addAll(filters) (filtersInEdition as MutableLiveData).value = unCommittedFilters } } } fun addFilter(filter: Filter<*>) { unCommittedFilters.add(filter) (filtersInEdition as MutableLiveData).value = unCommittedFilters areFiltersChanged = true } fun removeFilter(filter: Filter<*>) { unCommittedFilters.remove(filter) (filtersInEdition as MutableLiveData).value = unCommittedFilters areFiltersChanged = true } fun clearFilters() { unCommittedFilters.clear() (filtersInEdition as MutableLiveData).value = unCommittedFilters areFiltersChanged = true } suspend fun commitChanges() { if (!isFiltersTheSame()) { dataRepository.setCurrentFilters(unCommittedFilters.toList()) areFiltersChanged = false } } suspend fun saveCurrentFilterGroup(name: String) = dataRepository.createFilterGroup(unCommittedFilters.toList(), name) suspend fun loadSavedGroup(filterGroup: FilterGroup) = dataRepository.setSavedGroupAsCurrentFilters(filterGroup) private fun isFiltersTheSame() = unCommittedFilters.containsAll(currentFilters) && currentFilters.containsAll(unCommittedFilters) fun abandonChanges() { clearFilters() unCommittedFilters.addAll(currentFilters) areFiltersChanged = false } fun isFilterInEdition(filter: Filter<*>): Boolean = unCommittedFilters.contains(filter) }
gpl-3.0
0670ee4d35f7d908413545a8ed3339bb
34.460526
133
0.71121
4.988889
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/util/TimeUtil.kt
1
1170
package com.engineer.imitate.util import java.text.SimpleDateFormat import java.util.* object TimeUtilTool { private const val BASE = 1000 private const val ONE_MINUTE = 60f private const val ONE_HOUR = ONE_MINUTE * ONE_MINUTE private const val ONE_DAY = ONE_HOUR * 24 private const val ONE_YEAR = ONE_DAY * 365 fun millionSecondsToMinutes(timeInMillionSeconds: Long): Float { val second = timeInMillionSeconds / BASE return second / ONE_MINUTE } fun millionSecondsToHour(timeInMillionSeconds: Long): Float { val second = timeInMillionSeconds / BASE return second / ONE_HOUR } fun millionSecondsToDay(timeInMillionSeconds: Long): Float { val second = timeInMillionSeconds / BASE return second / ONE_DAY } fun millionSecondsToYear(timeInMillionSeconds: Long): Float { val second = timeInMillionSeconds / BASE return second / ONE_YEAR } fun timeStampToDate(timeInMillionSeconds: Long): String { val format = "yyyy-MM-dd HH:mm:ss" val sdf = SimpleDateFormat(format) return sdf.format(Date(timeInMillionSeconds)) } }
apache-2.0
6bb7b9bc8846d09d8c70baec90982e22
27.560976
68
0.682906
4.148936
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/handlers/injectionPoint/ReturnInjectionPoint.kt
1
5517
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.handlers.injectionPoint import com.demonwav.mcdev.platform.mixin.reference.MixinSelector import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.LambdaUtil import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassInitializer import com.intellij.psi.PsiCodeBlock import com.intellij.psi.PsiElement import com.intellij.psi.PsiLambdaExpression import com.intellij.psi.PsiMethod import com.intellij.psi.PsiMethodReferenceExpression import com.intellij.psi.PsiReturnStatement import com.intellij.psi.PsiType import com.intellij.psi.controlFlow.ControlFlowUtil import org.objectweb.asm.Opcodes import org.objectweb.asm.tree.AbstractInsnNode import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodNode abstract class AbstractReturnInjectionPoint(private val tailOnly: Boolean) : InjectionPoint<PsiElement>() { override fun createNavigationVisitor( at: PsiAnnotation, target: MixinSelector?, targetClass: PsiClass ): NavigationVisitor { return MyNavigationVisitor(tailOnly) } override fun doCreateCollectVisitor( at: PsiAnnotation, target: MixinSelector?, targetClass: ClassNode, mode: CollectVisitor.Mode ): CollectVisitor<PsiElement> { return MyCollectVisitor(at.project, mode, tailOnly) } override fun createLookup( targetClass: ClassNode, result: CollectVisitor.Result<PsiElement> ): LookupElementBuilder? { return null } private class MyNavigationVisitor(private val tailOnly: Boolean) : NavigationVisitor() { override fun visitReturnStatement(statement: PsiReturnStatement) { if (tailOnly) { result.clear() } addResult(statement) super.visitReturnStatement(statement) } override fun visitEnd(executableElement: PsiElement) { val codeBlockToAnalyze = when (executableElement) { is PsiMethodReferenceExpression -> { if (tailOnly) { result.clear() } addResult(executableElement) return } is PsiLambdaExpression -> { val body = executableElement.body ?: return if (body !is PsiCodeBlock) { if (tailOnly) { result.clear() } addResult(body) return } val returnType = LambdaUtil.getFunctionalInterfaceReturnType(executableElement) ?: return if (returnType != PsiType.VOID) { return } body } is PsiMethod -> { if (executableElement.returnType != PsiType.VOID && !executableElement.isConstructor) { return } executableElement.body ?: return } is PsiClassInitializer -> { executableElement.body } else -> return } val rBrace = codeBlockToAnalyze.rBrace ?: return val controlFlow = HighlightControlFlowUtil.getControlFlowNoConstantEvaluate(codeBlockToAnalyze) if (ControlFlowUtil.canCompleteNormally(controlFlow, 0, controlFlow.size)) { if (tailOnly) { result.clear() } addResult(rBrace) } } } private class MyCollectVisitor( private val project: Project, mode: Mode, private val tailOnly: Boolean ) : CollectVisitor<PsiElement>(mode) { override fun accept(methodNode: MethodNode) { val insns = methodNode.instructions ?: return val elementFactory = JavaPsiFacade.getElementFactory(project) fun insnHandler(insn: AbstractInsnNode): Boolean { if (insn.opcode !in Opcodes.IRETURN..Opcodes.RETURN) { return false } val statementText = when (insn.opcode) { Opcodes.RETURN -> "return;" Opcodes.ARETURN -> "return null;" else -> "return 0;" } val fakeStatement = elementFactory.createStatementFromText(statementText, null) as PsiReturnStatement addResult(insn, fakeStatement) return true } if (tailOnly) { var insn = insns.last while (insn != null) { if (insnHandler(insn)) { break } insn = insn.previous } } else { insns.iterator().forEach(::insnHandler) } } } } class ReturnInjectionPoint : AbstractReturnInjectionPoint(false) class TailInjectionPoint : AbstractReturnInjectionPoint(true)
mit
854e3993745fcdf77095eba382780b7c
34.593548
109
0.583469
5.528056
false
false
false
false
samtstern/quickstart-android
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt
1
4096
package com.google.firebase.quickstart.auth.kotlin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.View import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.auth.R import com.google.firebase.quickstart.auth.databinding.ActivityCustomBinding /** * Demonstrate Firebase Authentication using a custom minted token. For more information, see: * https://firebase.google.com/docs/auth/android/custom-auth */ class CustomAuthActivity : AppCompatActivity(), View.OnClickListener { // [START declare_auth] private lateinit var auth: FirebaseAuth // [END declare_auth] private lateinit var binding: ActivityCustomBinding private var customToken: String? = null private lateinit var tokenReceiver: TokenBroadcastReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCustomBinding.inflate(layoutInflater) setContentView(binding.root) // Button click listeners binding.buttonSignIn.setOnClickListener(this) // Create token receiver (for demo purposes only) tokenReceiver = object : TokenBroadcastReceiver() { override fun onNewToken(token: String?) { Log.d(TAG, "onNewToken:$token") setCustomToken(token.toString()) } } // [START initialize_auth] // Initialize Firebase Auth auth = Firebase.auth // [END initialize_auth] } // [START on_start_check_user] public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) } // [END on_start_check_user] override fun onResume() { super.onResume() registerReceiver(tokenReceiver, TokenBroadcastReceiver.filter) } override fun onPause() { super.onPause() unregisterReceiver(tokenReceiver) } private fun startSignIn() { // Initiate sign in with custom token // [START sign_in_custom] customToken?.let { auth.signInWithCustomToken(it) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCustomToken:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCustomToken:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } } } // [END sign_in_custom] } private fun updateUI(user: FirebaseUser?) { if (user != null) { binding.textSignInStatus.text = getString(R.string.custom_auth_signin_status_user, user.uid) } else { binding.textSignInStatus.text = getString(R.string.custom_auth_signin_status_failed) } } private fun setCustomToken(token: String) { customToken = token val status = "Token:$customToken" // Enable/disable sign-in button and show the token binding.buttonSignIn.isEnabled = true binding.textTokenStatus.text = status } override fun onClick(v: View) { val i = v.id if (i == R.id.buttonSignIn) { startSignIn() } } companion object { private const val TAG = "CustomAuthActivity" } }
apache-2.0
04e7cf88312ee16feaf7527490040758
32.57377
104
0.613037
4.796253
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/SqlDelightClassCompletionContributor.kt
1
5385
/* * Copyright (C) 2016 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 app.cash.sqldelight.intellij import app.cash.sqldelight.core.lang.SqlDelightFile import app.cash.sqldelight.core.lang.psi.JavaTypeMixin import app.cash.sqldelight.core.lang.util.findChildrenOfType import app.cash.sqldelight.core.psi.SqlDelightImportStmt import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionUtil.findReferenceOrAlphanumericPrefix import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.JavaClassNameCompletionContributor import com.intellij.codeInsight.completion.JavaPsiClassReferenceElement import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import kotlin.math.max class SqlDelightClassCompletionContributor : JavaClassNameCompletionContributor() { private val insertHandler = AutoImportInsertionHandler() override fun fillCompletionVariants( parameters: CompletionParameters, resultSet: CompletionResultSet, ) { if (parameters.position.getNonStrictParentOfType<JavaTypeMixin>() == null) return val result = resultSet.withPrefixMatcher(findReferenceOrAlphanumericPrefix(parameters)) val prefixMatcher = result.prefixMatcher addAllClasses(parameters, parameters.invocationCount <= 1, prefixMatcher) { lookupElement -> if (lookupElement is JavaPsiClassReferenceElement) { lookupElement.setInsertHandler(insertHandler) } resultSet.addElement(lookupElement) } val file = parameters.originalFile val project = file.project val module = ModuleUtil.findModuleForFile(file) val scope = if (module != null) { GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) } else { GlobalSearchScope.allScope(project) } getKotlinClasses(project, prefixMatcher, scope) .forEach { classOrObject: KtClassOrObject -> val tailText = if (classOrObject.fqName != null) { (" ${classOrObject.fqName!!.asString().substringBeforeLast('.')}") } else { "" } val elementBuilder = LookupElementBuilder.createWithIcon(classOrObject) .withTailText(tailText) .withInsertHandler(insertHandler) result.addElement(elementBuilder) } } private fun getKotlinClasses( project: Project, prefixMatcher: PrefixMatcher, scope: GlobalSearchScope, ): List<KtClassOrObject> { val index = KotlinFullClassNameIndex.getInstance() return index.getAllKeys(project) .filter { fqName -> ProgressManager.checkCanceled() val substringAfterLast = fqName.substringAfterLast('.') prefixMatcher.prefixMatches(substringAfterLast) } .flatMap { fqName -> index[fqName, project, scope] } .filterNotNull() } } private class AutoImportInsertionHandler : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { val qname = when (val element = item.psiElement) { is PsiClass -> element.qualifiedName is KtClassOrObject -> element.fqName?.asString() else -> null } ?: return val imports = (context.file as SqlDelightFile).sqlStmtList ?.findChildrenOfType<SqlDelightImportStmt>().orEmpty() val ref = imports.map { it.javaType }.find { it.textMatches(qname) } val refEnd = context.trackOffset(context.tailOffset, false) if (ref == null) { if (imports.isEmpty()) { context.document.insertString(0, "import $qname;\n\n") } else { context.insertAndOrganizeImports(imports, "import $qname;") } } context.tailOffset = context.getOffset(refEnd) context.commitDocument() } private fun InsertionContext.insertAndOrganizeImports( imports: Collection<SqlDelightImportStmt>, newImport: String, ) { val newImports = arrayListOf(newImport) var endOffset = 0 for (importElement in imports) { newImports.add(importElement.text) endOffset = max(endOffset, importElement.textOffset + importElement.textLength) } document.replaceString(0, endOffset, newImports.sorted().joinToString("\n")) } }
apache-2.0
173a7f32a1e2162d8aef3ff823560f15
37.741007
96
0.750232
4.851351
false
false
false
false
sksamuel/akka-patterns
rxhive-core/src/test/kotlin/com/sksamuel/rxhive/StaticPartitionerTest.kt
1
1943
package com.sksamuel.rxhive import arrow.core.Try import com.sksamuel.rxhive.HiveTestConfig.client import com.sksamuel.rxhive.HiveTestConfig.fs import com.sksamuel.rxhive.evolution.NoopSchemaEvolver import com.sksamuel.rxhive.formats.ParquetFormat import com.sksamuel.rxhive.partitioners.StaticPartitioner import com.sksamuel.rxhive.resolver.LenientStructResolver import io.kotlintest.shouldThrowAny import io.kotlintest.specs.FunSpec import org.apache.hadoop.hive.metastore.TableType import org.apache.hadoop.hive.metastore.api.Database class StaticPartitionerTest : FunSpec() { init { val schema = StructType( StructField("name", StringType), StructField("title", StringType), StructField("salary", Float64Type), StructField("employed", BooleanType) ) val users = listOf( Struct(schema, "sam", "mr", 100.43, false), Struct(schema, "ben", "mr", 230.523, false), Struct(schema, "tom", "mr", 60.98, true), Struct(schema, "laura", "ms", 421.512, true), Struct(schema, "kelly", "ms", 925.162, false) ) Try { client.createDatabase(Database("tests", null, "/user/hive/warehouse/sink_test", emptyMap())) } test("fail if a partition doesn't exist with static partitioning") { Try { client.dropTable("tests", "static_test") } val writer = HiveWriter( DatabaseName("tests"), TableName("static_test"), WriteMode.Overwrite, createConfig = CreateTableConfig(schema, PartitionPlan(PartitionKey("title")), TableType.MANAGED_TABLE, ParquetFormat, null), fileManager = OptimisticFileManager(), evolver = NoopSchemaEvolver, resolver = LenientStructResolver, partitioner = StaticPartitioner, client = client, fs = fs ) shouldThrowAny { writer.write(users) } writer.close() } } }
apache-2.0
ff61365034e09561273658015a4fb2a8
29.375
135
0.665466
4.178495
false
true
false
false
Jasper-Hilven/dynamic-extensions-for-alfresco
annotations-runtime/src/main/java/com/github/dynamicextensionsalfresco/webscripts/AnnotationWebScriptBuilder.kt
1
16607
package com.github.dynamicextensionsalfresco.webscripts import com.github.dynamicextensionsalfresco.util.hasText import com.github.dynamicextensionsalfresco.webscripts.annotations.* import java.lang.reflect.Method import java.util.ArrayList import java.util.Arrays import java.util.HashSet import java.util.LinkedHashSet import com.github.dynamicextensionsalfresco.webscripts.arguments.HandlerMethodArgumentsResolver import org.springframework.beans.factory.BeanFactory import org.springframework.beans.factory.BeanFactoryAware import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.ConfigurableListableBeanFactory import org.springframework.core.annotation.AnnotationUtils import org.springframework.extensions.webscripts.Description import org.springframework.extensions.webscripts.Description.RequiredAuthentication import org.springframework.extensions.webscripts.Description.RequiredTransaction import org.springframework.extensions.webscripts.Description.TransactionCapability import org.springframework.extensions.webscripts.DescriptionImpl import org.springframework.extensions.webscripts.TransactionParameters import org.springframework.util.Assert import org.springframework.util.ClassUtils import org.springframework.util.ReflectionUtils import org.springframework.util.StringUtils import kotlin.properties.Delegates /** * Creates [AnnotationWebScript] instances from beans defined in a [BeanFactory]. * @author Laurens Fridael * @author Laurent Van der Linden */ public class AnnotationWebScriptBuilder constructor( ) : BeanFactoryAware { @Autowired private var handlerMethodArgumentsResolver: HandlerMethodArgumentsResolver? = null public fun setHandlerMethodArgumentsResolver(value:HandlerMethodArgumentsResolver){ this.handlerMethodArgumentsResolver = value; } /* Dependencies */ protected var beanFactory: ConfigurableListableBeanFactory? = null private val trailingSlashExpression = "/$".toRegex() private val leadingSlashExpression = "^/".toRegex() /* Main operations */ /** * Creates [AnnotationWebScript]s from a given named bean by scanning methods annotated with [Uri]. * @param beanName * * * @return The [AnnotationWebScript] or null if the implementation does not consider the bean to be a handler * * for an [AnnotationWebScript]. */ public fun createWebScripts(beanName: String): List<org.springframework.extensions.webscripts.WebScript> { Assert.hasText(beanName, "Bean name cannot be empty.") val beanFactory = beanFactory val beanType = beanFactory!!.getType(beanName) ?: return emptyList() val webScriptAnnotation = beanFactory.findAnnotationOnBean<WebScript>(beanName, WebScript::class.java) ?: getDefaultWebScriptAnnotation() val baseUri = webScriptAnnotation.baseUri if (StringUtils.hasText(baseUri) && baseUri.startsWith("/") == false) { throw RuntimeException("@WebScript baseUri for class '$beanType' does not start with a slash: '$baseUri'") } val handlerMethods = HandlerMethods() ReflectionUtils.doWithMethods(beanType) { method: Method -> val before = AnnotationUtils.findAnnotation<Before>(method, Before::class.java) if (before != null) { if (AnnotationUtils.findAnnotation<Attribute>(method, Attribute::class.java) != null || AnnotationUtils.findAnnotation<Uri>(method, Uri::class.java) != null) { throw RuntimeException("Cannot combine @Before, @Attribute and @Uri on a single method. Method: ${ClassUtils.getQualifiedMethodName(method)}") } handlerMethods.beforeMethods.add(method) } } ReflectionUtils.doWithMethods(beanType) { method: Method -> val attribute = AnnotationUtils.findAnnotation<Attribute>(method, Attribute::class.java) if (attribute != null) { if (AnnotationUtils.findAnnotation<Before>(method, Before::class.java) != null || AnnotationUtils.findAnnotation<Uri>(method, Uri::class.java) != null) { throw RuntimeException(("Cannot combine @Before, @Attribute and @Uri on a single method. Method: ${ClassUtils.getQualifiedMethodName(method)}")) } if (method.returnType == Void.TYPE) { throw RuntimeException("@Attribute methods cannot have a void return type.") } handlerMethods.attributeMethods.add(method) } } ReflectionUtils.doWithMethods(beanType) { method: Method -> val exceptionHandler = AnnotationUtils.findAnnotation<ExceptionHandler>(method, ExceptionHandler::class.java) if (exceptionHandler != null) { if (AnnotationUtils.findAnnotation<Attribute>(method, Attribute::class.java) != null || AnnotationUtils.findAnnotation<Before>(method, Before::class.java) != null || AnnotationUtils.findAnnotation<Uri>(method, Uri::class.java) != null) { throw RuntimeException("Cannot combine @Before, @Attribute @ExceptionHandler or @Uri on a single method. Method: ${ClassUtils.getQualifiedMethodName(method)}") } handlerMethods.exceptionHandlerMethods.add(ExceptionHandlerMethod(exceptionHandler, method)) } } val webScripts = ArrayList<org.springframework.extensions.webscripts.WebScript>() ReflectionUtils.doWithMethods(beanType) { method: Method -> val uri = AnnotationUtils.findAnnotation<Uri>(method, Uri::class.java) if (uri != null) { val webScript = createWebScript(beanName, webScriptAnnotation, uri, handlerMethods.createForUriMethod(method)) webScripts.add(webScript) } } val ids = HashSet<String>() for (webScript in webScripts) { val webscriptId = webScript.description.id val notContained = ids.add(webscriptId) if (!notContained) { throw IllegalStateException("Duplicate Web Script ID \"" + webscriptId + "\" Make sure handler methods of annotation-based Web Scripts have unique names.") } } return webScripts } /* Utility operations */ protected fun createWebScript(beanName: String, webScript: WebScript, uri: Uri, handlerMethods: HandlerMethods): AnnotationWebScript { val description = DescriptionImpl() if (webScript.defaultFormat.hasText()) { description.defaultFormat = webScript.defaultFormat } val baseUri = webScript.baseUri handleHandlerMethodAnnotation(uri, handlerMethods.uriMethod, description, baseUri) handleTypeAnnotations(beanName, webScript, description) val id = "%s.%s.%s".format(generateId(beanName), handlerMethods.uriMethod.name, description.method.toLowerCase()) description.id = id val handler = beanFactory!!.getBean(beanName) description.store = DummyStore() return createWebScript(description, handler, handlerMethods) } protected fun createWebScript(description: Description, handler: Any, handlerMethods: HandlerMethods): AnnotationWebScript { return AnnotationWebScript(description, handler, handlerMethods, handlerMethodArgumentsResolver) } protected fun handleHandlerMethodAnnotation(uri: Uri, method: Method, description: DescriptionImpl, baseUri: String) { Assert.notNull(uri, "Uri cannot be null.") Assert.notNull(method, "HttpMethod cannot be null.") Assert.notNull(description, "Description cannot be null.") val uris: Array<String> if (uri.value.size > 0) { uris = uri.value.map { "${baseUri.replace(trailingSlashExpression, "")}/${it.replace(leadingSlashExpression, "")}" }.toTypedArray() } else if (StringUtils.hasText(baseUri)) { uris = arrayOf(baseUri.replace(trailingSlashExpression, "")) } else { throw RuntimeException( "No value specified for @Uri on method '%s' and no base URI found for @WebScript on class." .format(ClassUtils.getQualifiedMethodName(method)) ) } description.setUris(uris) /* * For the sake of consistency we translate the HTTP method from the HttpMethod enum. This also shields us from * changes in the HttpMethod enum names. */ description.method = when (uri.method) { HttpMethod.GET -> "GET" HttpMethod.POST -> "POST" HttpMethod.PUT -> "PUT" HttpMethod.DELETE -> "DELETE" HttpMethod.OPTIONS -> "OPTIONS" } /* * Idem dito for FormatStyle. */ description.formatStyle = when (uri.formatStyle) { FormatStyle.ANY -> Description.FormatStyle.any FormatStyle.ARGUMENT -> Description.FormatStyle.argument FormatStyle.EXTENSION -> Description.FormatStyle.extension } if (uri.defaultFormat.hasText()) { description.defaultFormat = uri.defaultFormat } description.multipartProcessing = uri.multipartProcessing val methodAuthentication = method.getAnnotation<Authentication>(Authentication::class.java) if (methodAuthentication != null) { handleAuthenticationAnnotation(methodAuthentication, description) } val methodTransaction = method.getAnnotation<Transaction>(Transaction::class.java) if (methodTransaction != null) { handleTransactionAnnotation(methodTransaction, description) } } protected fun handleTypeAnnotations(beanName: String, webScript: WebScript, description: DescriptionImpl) { handleWebScriptAnnotation(webScript, beanName, description) if (description.requiredAuthentication == null) { var authentication = beanFactory!!.findAnnotationOnBean<Authentication>(beanName, Authentication::class.java) ?: getDefaultAuthenticationAnnotation() handleAuthenticationAnnotation(authentication, description) } if (description.requiredTransactionParameters == null) { var transaction = beanFactory!!.findAnnotationOnBean<Transaction>(beanName, Transaction::class.java) if (transaction == null) { if (description.method.equals("GET")) { transaction = getDefaultReadonlyTransactionAnnotation() } else { transaction = getDefaultReadWriteTransactionAnnotation() } } handleTransactionAnnotation(transaction, description) } val cache = beanFactory!!.findAnnotationOnBean<Cache>(beanName, Cache::class.java) ?: getDefaultCacheAnnotation() handleCacheAnnotation(cache, beanName, description) description.descPath = "" } protected fun handleWebScriptAnnotation(webScript: WebScript, beanName: String, description: DescriptionImpl) { Assert.notNull(webScript, "Annotation cannot be null.") Assert.hasText(beanName, "Bean name cannot be empty.") Assert.notNull(description, "Description cannot be null.") Assert.hasText(description.method, "Description method is not specified.") if (webScript.value.hasText()) { description.shortName = webScript.value } else { description.shortName = generateShortName(beanName) } if (webScript.description.hasText()) { description.description = webScript.description } else { description.description = "Annotation-based WebScript for class %s".format(beanFactory!!.getType(beanName).name) } if (webScript.families.size > 0) { description.familys = LinkedHashSet(Arrays.asList(*webScript.families)) } description.lifecycle = when (webScript.lifecycle) { Lifecycle.NONE -> Description.Lifecycle.none Lifecycle.DRAFT -> Description.Lifecycle.draft Lifecycle.DRAFT_PUBLIC_API -> Description.Lifecycle.draft_public_api Lifecycle.DEPRECATED -> Description.Lifecycle.deprecated Lifecycle.INTERNAL -> Description.Lifecycle.internal Lifecycle.PUBLIC_API -> Description.Lifecycle.public_api Lifecycle.SAMPLE -> Description.Lifecycle.sample } } protected fun handleAuthenticationAnnotation(authentication: Authentication, description: DescriptionImpl) { Assert.notNull(authentication, "Annotation cannot be null.") Assert.notNull(description, "Description cannot be null.") if (authentication.runAs.hasText()) { description.runAs = authentication.runAs } description.requiredAuthentication = when (authentication.value) { AuthenticationType.NONE -> RequiredAuthentication.none AuthenticationType.GUEST -> RequiredAuthentication.guest AuthenticationType.USER -> RequiredAuthentication.user AuthenticationType.ADMIN -> RequiredAuthentication.admin } } protected fun handleTransactionAnnotation(transaction: Transaction, description: DescriptionImpl) { Assert.notNull(transaction, "Annotation cannot be null.") Assert.notNull(description, "Description cannot be null.") val transactionParameters = TransactionParameters() transactionParameters.required = when (transaction.value) { TransactionType.NONE -> RequiredTransaction.none TransactionType.REQUIRED -> RequiredTransaction.required TransactionType.REQUIRES_NEW -> RequiredTransaction.requiresnew } if (transaction.readOnly) { transactionParameters.capability = TransactionCapability.readonly } else { transactionParameters.capability = TransactionCapability.readwrite } transactionParameters.bufferSize = transaction.bufferSize description.requiredTransactionParameters = transactionParameters } protected fun handleCacheAnnotation(cache: Cache, beanName: String, description: DescriptionImpl) { Assert.notNull(cache, "Annotation cannot be null.") Assert.hasText(beanName, "Bean name cannot be empty.") Assert.notNull(description, "Description cannot be null.") val requiredCache = org.springframework.extensions.webscripts.Cache() requiredCache.neverCache = cache.neverCache requiredCache.isPublic = cache.isPublic requiredCache.mustRevalidate = cache.mustRevalidate description.requiredCache = requiredCache } protected fun generateId(beanName: String): String { Assert.hasText(beanName, "Bean name cannot be empty") val clazz = beanFactory!!.getType(beanName) return clazz.name } protected fun generateShortName(beanName: String): String { Assert.hasText(beanName, "Bean name cannot be empty") val clazz = beanFactory!!.getType(beanName) return ClassUtils.getShortName(clazz) } /* * These methods use local classes to obtain annotations with default settings. */ private fun getDefaultAuthenticationAnnotation(): Authentication { @Authentication class Default return Default::class.java.getAnnotation(Authentication::class.java) } private fun getDefaultReadWriteTransactionAnnotation(): Transaction { @Transaction class Default return Default::class.java.getAnnotation(Transaction::class.java) } private fun getDefaultReadonlyTransactionAnnotation(): Transaction { @Transaction(readOnly = true) class Default return Default::class.java.getAnnotation(Transaction::class.java) } private fun getDefaultCacheAnnotation(): Cache { @Cache class Default return Default::class.java.getAnnotation(Cache::class.java) } private fun getDefaultWebScriptAnnotation(): WebScript { @WebScript class Default return Default::class.java.getAnnotation(WebScript::class.java) } /* Dependencies */ override fun setBeanFactory(beanFactory: BeanFactory) { Assert.isInstanceOf(ConfigurableListableBeanFactory::class.java, beanFactory, "BeanFactory is not of type ConfigurableListableBeanFactory.") this.beanFactory = beanFactory as ConfigurableListableBeanFactory } }
apache-2.0
960b8b4dbb3d0a6c28d7f612d741fcd9
46.045326
253
0.691817
5.167082
false
false
false
false
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/core/infrastructure/network/APIClientMock.kt
1
489
package com.projectcitybuild.core.infrastructure.network import dagger.Reusable @Reusable class APIClientMock : APIClient { var result: Any? = null var exception: Throwable? = null override suspend fun <T> execute(apiCall: suspend () -> T): T { val exception = exception if (exception != null) { throw exception } if (result == null) { throw Exception("No result mocked") } return result as T } }
mit
e800fbd63cf3fb0ed0ae0612849df68f
22.285714
67
0.601227
4.445455
false
false
false
false
vimeo/vimeo-networking-java
model-generator/plugin/src/main/java/com/vimeo/modelgenerator/GenerateModelsPlugin.kt
1
2377
package com.vimeo.modelgenerator import com.vimeo.modelgenerator.tasks.GenerateModelsTask import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.Task class GenerateModelsPlugin : Plugin<Project> { override fun apply(project: Project) { val extension = project.extensions.create(EXTENSION_NAME, GenerateModelsExtension::class.java, project) project.pluginManager.withPlugin(KOTLIN_ANDROID) { registerTask(project, extension) project.afterEvaluate { project.tasks.findByName(PRE_BUILD)?.dependsOn(project.tasks.findByName(GENERATE_MODELS)) } } project.pluginManager.withPlugin(KOTLIN_JVM) { registerTask(project, extension) // kaptGenerateStubsKotlin is used as the set up task instead of build // because kapt code generation happens before build is called and // we need to generate the models prior to kapt so the Moshi adapters // can also be generated. val kaptTask: Task? = project.tasks.findByName(KAPT_GENERATE_STUBS) // When generating to a module that doesn't use kapt this task will be null // in that case compileKotlin is the earliest task run when the module is being // built so we can attach generateModels to that instead. if (kaptTask != null) { kaptTask.dependsOn(GENERATE_MODELS) } else { project.tasks.findByName(COMPILE_KOTLIN)?.dependsOn(GENERATE_MODELS) } } } private fun registerTask( project: Project, extension: GenerateModelsExtension ) { project.tasks.register(GENERATE_MODELS, GenerateModelsTask::class.java) { it.typeToGenerate = extension.typeGenerated!! it.inputModelPath = extension.inputPath!! } } companion object { private const val KAPT_GENERATE_STUBS = "kaptGenerateStubsKotlin" private const val COMPILE_KOTLIN = "compileKotlin" private const val PRE_BUILD = "preBuild" private const val EXTENSION_NAME = "generated" private const val KOTLIN_JVM = "org.jetbrains.kotlin.jvm" private const val KOTLIN_ANDROID = "kotlin-android" private const val GENERATE_MODELS = "generateModels" } }
mit
19dd76fa592eaa17b977b900a6af96a4
38.616667
105
0.655448
4.821501
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/profile/ProfileManager.kt
1
12892
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model.profile import de.sudoq.model.ObservableModelImpl import de.sudoq.model.game.Assistances import de.sudoq.model.game.GameSettings import de.sudoq.model.persistence.IRepo import de.sudoq.model.persistence.xml.profile.IProfilesListRepo import java.io.File import java.util.* import kotlin.collections.ArrayList /** * This static class is a wrapper for the currently loaded player profile * which is maintained by SharedPreferences of the Android-API. * */ open class ProfileManager() : ObservableModelImpl<ProfileManager>() { //private constructor because class is static //TODO split into profile handler and profile lateinit var currentProfile: Profile //initialized in loadCurrentProfile /** * Name of the current player profiles */ var name: String? get() = currentProfile.name set(value) { currentProfile.name = value } /** * ID of the player profile */ var currentProfileID = -1 get() = currentProfile.id private set //todo should not be used, try val /** * ID of the current [Game] */ var currentGame get() = currentProfile.currentGame set(value) { currentProfile.currentGame = value profileRepo!!.update(currentProfile) } /** * AssistanceSet representing the available Assistances */ var assistances = GameSettings() get() = currentProfile.assistances private set /** * AppSettings object representing settings bound to the app in general */ var appSettings = AppSettings() //todo read from currentProfile instead, same above get() = currentProfile.appSettings private set var statistics: IntArray? get() = currentProfile.statistics set(value) { currentProfile.statistics = value } var profileRepo: IRepo<Profile>? = null //TODO refactor initialization, set it right var profilesListRepo: IProfilesListRepo? = null //TODO refactor initialization, set it right var currentProfileDir: File? = null get() = File(profilesDir!!.absolutePath, "profile_$currentProfileID") private set var profilesDir: File? = null //todo remove noargs constructor, make non-nullable set(value) { if (value == null) throw IllegalArgumentException("profiles dir is null") if (!value.canWrite()) throw IllegalArgumentException("profiles dir cannot write") field = value } constructor(profilesDir: File, profileRepo: IRepo<Profile>, profilesListRepo: IProfilesListRepo) : this() { this.profileRepo = profileRepo this.profilesListRepo = profilesListRepo if (!profilesDir.canWrite()) throw IllegalArgumentException("profiles dir cannot write") this.profilesDir = profilesDir } /** assumes an empty directory */ fun initialize() { if (!profilesDir!!.exists()) profilesDir!!.mkdirs() //create a new profile //currentProfile = profileRepo!!.create() createInitialProfile() } /** * Loads the current [ProfileManager] from profiles.xml */ fun loadCurrentProfile() {//todo if all works bundle similarities //if the profiles (list) file doesn't exist if (!profilesDir!!.exists()) { profilesListRepo!!.createProfilesFile() currentProfile = profileRepo!!.create() profilesListRepo!!.addProfile(currentProfile) notifyListeners(this) return } if (profilesDir!!.list().isEmpty() || !File(profilesDir, "profiles.xml").exists()) { profilesListRepo!!.createProfilesFile() } //if there are no profiles if (profilesListRepo!!.getProfileNamesList().isEmpty()) { currentProfile = profileRepo!!.create() profilesListRepo!!.addProfile(currentProfile) notifyListeners(this) return } val currentProfileID = profilesListRepo!!.getCurrentProfileId()//todo put directly into setter of currentProfileID??? currentProfile = profileRepo!!.read(currentProfileID) notifyListeners(this) } /** * Deletes the current [ProfileManager], if another one exists. * Cooses the next one that isn't deleted from profiles.xml */ fun deleteProfile() { if (numberOfAvailableProfiles > 1) { profilesListRepo!!.deleteProfileFromList(currentProfileID) profileRepo!!.delete(currentProfileID) setProfile(profilesListRepo!!.getNextProfile()) } } /** * Gibt die Anzahl der nicht geloeschten Profile zurueck * * @return Anzahl nicht geloeschter Profile */ val numberOfAvailableProfiles: Int get() = profilesListRepo!!.getProfilesCount() // Profiles todo move all to profileManager /** * Determines whether there are any profiles saved as files * todo merge with numberOfAvailableProfiles * * @return die Anzahl der Profile */ fun noProfiles(): Boolean { //query profileRepo directly if (!profilesDir!!.exists()) return true /*System.out.println("getnrp"); for(String s: profiles.list()) System.out.println(profiles.list()); System.out.println("getnrpEND");*/ var count = profilesDir!!.list()!!.size //one folder for each profile + file listing all profiles if (File(profilesDir, "profiles.xml").exists()) { //if profiles.xml exists subtract it from count count-- } return count == 0 } /** * Diese Methode ändert die Einstellungen, die mit dieser Klasse abgerufen * werden können auf die spezifizierten SharedPreferences. Sind diese null, * so wird nichts geändert und es wird false zurückgegeben. War die Änderung * erfolgreich, so wird true zurückgegeben. * * @param profileID * Die ID des Profils, zu dem gewechselt werden soll. * * @return boolean true, falls die Änderung erfolgreich war, false * andernfalls */ fun changeProfile(profileID: Int): Boolean { val oldProfileID = currentProfileID if (profileID == oldProfileID) return true profileRepo!!.update(currentProfile)// save current return setProfile(profileID) } /** * Setzt das neue Profil ohne das alte zu speichern (zB nach löschen) */ private fun setProfile(profileID: Int): Boolean { currentProfile = profileRepo!!.read(profileID) // load new values // set current profile in profiles.xml profilesListRepo!!.setCurrentProfileId(profileID) notifyListeners(this) return false } /** * Wird von der PlayerPreference aufgerufen, falls sie verlassen wird und * speichert Aenderungen an der profile.xml fuer dieses Profil sowie an der * profiles.xml, welche Informationen ueber alle Profile enthaelt */ fun saveChanges() { profileRepo!!.update(currentProfile) profilesListRepo!!.updateProfilesList(currentProfile) } /** * Diese Methode erstellt ein neues Profil. */ fun createAnotherProfile() { if (currentProfileID != -1) { profileRepo!!.update(currentProfile) // save current profile xml } currentProfile = profileRepo!!.create() profilesListRepo!!.addProfile(currentProfile) notifyListeners(this) } /** * Diese Methode erstellt ein neues Profil. */ fun createInitialProfile() { if(!profilesListRepo!!.profilesFileExists()) { profilesListRepo!!.createProfilesFile() } currentProfile = profileRepo!!.create() profilesListRepo!!.addProfile(currentProfile) } /** * Diese Methode gibt zurück, ob die Gesteneingabe im aktuellen * Spielerprofil aktiv ist oder nicht. * * @return true, falls die Gesteneingabe im aktuellen Profil aktiv ist, * false andernfalls */ /** * Setzt die Verwendung von Gesten in den Preferences auf den übergebenen * Wert. * * @param value * true, falls Gesten gesetzt werden sollen, false falls nicht */ var isGestureActive: Boolean get() = assistances.isGesturesSet set(value) { assistances.setGestures(value) } /** * Gibt die Datei zurück, in der die Gesten des Benutzers gespeichert werden * * @return File, welcher auf die Gesten-Datei des Benutzers zeigt */ fun getCurrentGestureFile(): File = File(profilesDir, "gestures") /*Advanced Settings*/ fun setLefthandActive(value: Boolean) { assistances.setLefthandMode(value) } fun setHelperActive(value: Boolean) { assistances.setHelper(value) } fun setDebugActive(value: Boolean) { appSettings.setDebug(value) } /** * Gibt eine String Liste mit allen Profilnamen zurück. * * @return die Namensliste */ val profilesNameList: ArrayList<String> //todo change return type to just List<String> get() { return ArrayList(profilesListRepo!!.getProfileNamesList()) } /** * Gibt eine Integer Liste mit allen Profilids zurück. * * @return die Idliste */ val profilesIdList: ArrayList<Int> //todo change return type to just List<Int> get() { return ArrayList(profilesListRepo!!.getProfileIdsList()) } /** * Setzt eine Assistance in den Preferences auf true oder false. * * @param assistance * Assistance, welche gesetzt werden soll * @param value * true um die Assistance anzuschalten, sonst false */ fun setAssistance(assistance: Assistances?, value: Boolean) { if (value) assistances.setAssistance(assistance!!) else assistances.clearAssistance( assistance!! ) // notifyListeners(this); } /** * Diese Methode teilt mit, ob die spezifizierte Hilfestellung im aktuellen * Spielerprofil aktiviert ist. Ist dies der Fall, so wird true * zurückgegeben. Ist die Hilfestellung nicht aktiv oder ungültig, so wird * false zurückgegeben. * * @param asst * Die Hilfestellung von der überprüft werden soll, ob sie im * aktuellen Profil aktiviert ist * @return boolean true, falls die spezifizierte Hilfestellung im aktuellen * Profil aktiviert ist, false falls sie es nicht oder ungültig ist */ fun getAssistance(asst: Assistances?): Boolean { return assistances.getAssistance(asst!!) } /** * Setzt den Wert der gegebenen Statistik für dieses Profil auf den * gegebenen Wert * * @param stat * die zu setzende Statistik * @param value * der einzutragende Wert */ fun setStatistic(stat: Statistics?, value: Int) { if (stat == null) return statistics!![stat.ordinal] = value } /** * Diese Methode gibt den Wert der spezifizierten Statistik im aktuellen * Spielerprofil zurück. Ist die spezifizierte Statistik ungültig, so wird * null zurückgegeben. * * @param stat * Die Statistik, dessen Wert abgerufen werden soll * @return Der Wert der spezifizierten Statistik als String, oder null falls * diese ungültig ist */ fun getStatistic(stat: Statistics?): Int { return if (stat == null) -1 else statistics!![stat.ordinal] } companion object { const val INITIAL_TIME_RECORD = 5999 /** * Konstante die signalisiert, dass es kein aktuelles Spiel gibt */ const val NO_GAME = -1 /** * Konstante die signalisiert, dass ein neues Profil noch keinen namen hat */ const val DEFAULT_PROFILE_NAME = "unnamed" } }
gpl-3.0
30d22a329c8428eb61717d0e4fd35a35
30.694581
243
0.64545
4.345491
false
false
false
false
exponent/exponent
packages/expo-updates/android/src/main/java/expo/modules/updates/loader/LoaderFiles.kt
2
2566
package expo.modules.updates.loader import android.content.Context import android.util.Log import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.UpdatesUtils import expo.modules.updates.db.entity.AssetEntity import expo.modules.updates.manifest.EmbeddedManifest import expo.modules.updates.manifest.UpdateManifest import java.io.File import java.io.IOException import java.security.NoSuchAlgorithmException /** * Utility class for Loader and its subclasses, to allow for easy mocking */ open class LoaderFiles { fun fileExists(destination: File): Boolean { return destination.exists() } fun readEmbeddedManifest( context: Context, configuration: UpdatesConfiguration ): UpdateManifest? { return EmbeddedManifest.get(context, configuration) } @Throws(NoSuchAlgorithmException::class, IOException::class) fun copyAssetAndGetHash(asset: AssetEntity, destination: File, context: Context): ByteArray { return if (asset.embeddedAssetFilename != null) { copyContextAssetAndGetHash(asset, destination, context) } else if (asset.resourcesFilename != null && asset.resourcesFolder != null) { copyResourceAndGetHash(asset, destination, context) } else { throw AssertionError("Failed to copy embedded asset " + asset.key + " from APK assets or resources because not enough information was provided.") } } @Throws(NoSuchAlgorithmException::class, IOException::class) internal fun copyContextAssetAndGetHash( asset: AssetEntity, destination: File, context: Context ): ByteArray { try { context.assets.open(asset.embeddedAssetFilename!!) .use { inputStream -> return UpdatesUtils.sha256AndWriteToFile(inputStream, destination) } } catch (e: Exception) { Log.e(TAG, "Failed to copy asset " + asset.embeddedAssetFilename, e) throw e } } @Throws(NoSuchAlgorithmException::class, IOException::class) internal fun copyResourceAndGetHash( asset: AssetEntity, destination: File, context: Context ): ByteArray { val id = context.resources.getIdentifier( asset.resourcesFilename, asset.resourcesFolder, context.packageName ) try { context.resources.openRawResource(id) .use { inputStream -> return UpdatesUtils.sha256AndWriteToFile(inputStream, destination) } } catch (e: Exception) { Log.e(TAG, "Failed to copy asset " + asset.embeddedAssetFilename, e) throw e } } companion object { private val TAG = LoaderFiles::class.java.simpleName } }
bsd-3-clause
df39b912bb70ab7dec68aeea2208266c
31.897436
151
0.732658
4.533569
false
true
false
false
ftomassetti/LangSandbox
src/main/kotlin/me/tomassetti/sandy/ast/Model.kt
1
4426
package me.tomassetti.sandy.ast import java.util.* import kotlin.reflect.KParameter import kotlin.reflect.full.memberProperties import kotlin.reflect.full.primaryConstructor // // Generic part: valid for all languages // interface Node { val position: Position? } fun Node.isBefore(other: Node) : Boolean = position!!.start.isBefore(other.position!!.start) fun Point.isBefore(other: Point) : Boolean = line < other.line || (line == other.line && column < other.column) data class Point(val line: Int, val column: Int) { override fun toString() = "Line $line, Column $column" } data class Position(val start: Point, val end: Point) fun pos(startLine:Int, startCol:Int, endLine:Int, endCol:Int) = Position(Point(startLine,startCol),Point(endLine,endCol)) fun Node.process(operation: (Node) -> Unit) { operation(this) this.javaClass.kotlin.memberProperties.forEach { p -> val v = p.get(this) when (v) { is Node -> v.process(operation) is Collection<*> -> v.forEach { if (it is Node) it.process(operation) } } } } fun <T: Node> Node.specificProcess(klass: Class<T>, operation: (T) -> Unit) { process { if (klass.isInstance(it)) { operation(it as T) } } } fun Node.transform(operation: (Node) -> Node) : Node { operation(this) val changes = HashMap<String, Any>() this.javaClass.kotlin.memberProperties.forEach { p -> val v = p.get(this) when (v) { is Node -> { val newValue = v.transform(operation) if (newValue != v) changes[p.name] = newValue } is Collection<*> -> { val newValue = v.map { if (it is Node) it.transform(operation) else it } if (newValue != v) changes[p.name] = newValue } } } var instanceToTransform = this if (!changes.isEmpty()) { val constructor = this.javaClass.kotlin.primaryConstructor!! val params = HashMap<KParameter, Any?>() constructor.parameters.forEach { param -> if (changes.containsKey(param.name)) { params[param] = changes[param.name] } else { params[param] = this.javaClass.kotlin.memberProperties.find { param.name == it.name }!!.get(this) } } instanceToTransform = constructor.callBy(params) } return operation(instanceToTransform) } // // Sandy specific part // data class SandyFile(val statements : List<Statement>, override val position: Position? = null) : Node interface Statement : Node { } interface Expression : Node { } interface Type : Node { } // // Types // data class IntType(override val position: Position? = null) : Type data class DecimalType(override val position: Position? = null) : Type // // Expressions // interface BinaryExpression : Expression { val left: Expression val right: Expression } data class SumExpression(override val left: Expression, override val right: Expression, override val position: Position? = null) : BinaryExpression data class SubtractionExpression(override val left: Expression, override val right: Expression, override val position: Position? = null) : BinaryExpression data class MultiplicationExpression(override val left: Expression, override val right: Expression, override val position: Position? = null) : BinaryExpression data class DivisionExpression(override val left: Expression, override val right: Expression, override val position: Position? = null) : BinaryExpression data class UnaryMinusExpression(val value: Expression, override val position: Position? = null) : Expression data class TypeConversion(val value: Expression, val targetType: Type, override val position: Position? = null) : Expression data class VarReference(val varName: String, override val position: Position? = null) : Expression data class IntLit(val value: String, override val position: Position? = null) : Expression data class DecLit(val value: String, override val position: Position? = null) : Expression // // Statements // data class VarDeclaration(val varName: String, val value: Expression, override val position: Position? = null) : Statement data class Assignment(val varName: String, val value: Expression, override val position: Position? = null) : Statement data class Print(val value: Expression, override val position: Position? = null) : Statement
apache-2.0
fdf95627ee52e5cf9dd47fc1f0940707
33.046154
158
0.684365
4.064279
false
false
false
false
charleskorn/batect
app/src/main/kotlin/batect/os/windows/WindowsNativeMethods.kt
1
19546
/* 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.os.windows import batect.os.Dimensions import batect.os.NativeMethodException import batect.os.NativeMethods import batect.os.NoConsoleException import batect.os.windows.namedpipes.NamedPipe import jnr.constants.platform.windows.LastError import jnr.ffi.LibraryLoader import jnr.ffi.LibraryOption import jnr.ffi.Pointer import jnr.ffi.Runtime import jnr.ffi.Struct import jnr.ffi.annotations.Direct import jnr.ffi.annotations.In import jnr.ffi.annotations.Out import jnr.ffi.annotations.SaveError import jnr.ffi.annotations.StdCall import jnr.ffi.annotations.Transient import jnr.ffi.byref.IntByReference import jnr.ffi.byref.NativeLongByReference import jnr.ffi.mapper.TypeMapper import jnr.posix.HANDLE import jnr.posix.POSIX import jnr.posix.WindowsLibC import jnr.posix.util.WindowsHelpers import java.io.FileDescriptor import java.io.FileNotFoundException import java.net.SocketTimeoutException import java.nio.ByteBuffer import java.time.Duration import kotlin.math.max import kotlin.reflect.KFunction class WindowsNativeMethods( private val posix: POSIX, private val win32: Win32, private val runtime: Runtime ) : NativeMethods { constructor(posix: POSIX) : this( LibraryLoader.create(Win32::class.java) .option(LibraryOption.TypeMapper, createTypeMapper()) .library("msvcrt") .library("kernel32") .library("Advapi32") .load(), posix ) constructor(win32: Win32, posix: POSIX) : this( posix, win32, Runtime.getRuntime(win32) ) override fun getConsoleDimensions(): Dimensions { val console = win32.GetStdHandle(WindowsLibC.STD_OUTPUT_HANDLE) if (!console.isValid) { throwNativeMethodFailed(Win32::GetStdHandle) } val info = ConsoleScreenBufferInfo(runtime) val succeeded = win32.GetConsoleScreenBufferInfo(console, info) if (!succeeded) { val errno = posix.errno() if (errno == ERROR_INVALID_HANDLE) { throw NoConsoleException() } throwNativeMethodFailed(Win32::GetConsoleScreenBufferInfo) } val height = info.srWindow.bottom.intValue() - info.srWindow.top.intValue() + 1 val width = info.srWindow.right.intValue() - info.srWindow.left.intValue() + 1 return Dimensions(height, width) } override fun determineIfStdinIsTTY(): Boolean = isTTY(FileDescriptor.`in`, WindowsLibC.STD_INPUT_HANDLE) override fun determineIfStdoutIsTTY(): Boolean = isTTY(FileDescriptor.out, WindowsLibC.STD_OUTPUT_HANDLE) override fun determineIfStderrIsTTY(): Boolean = isTTY(FileDescriptor.err, WindowsLibC.STD_ERROR_HANDLE) // See http://archives.miloush.net/michkap/archive/2008/03/18/8306597.140100.html for an explanation of this. private fun isTTY(fd: FileDescriptor, stdHandle: Int): Boolean { if (!posix.isatty(fd)) { return false } val console = win32.GetStdHandle(stdHandle) if (!console.isValid) { throwNativeMethodFailed(Win32::GetStdHandle) } val currentConsoleMode = IntByReference() if (!win32.GetConsoleMode(console, currentConsoleMode)) { val errno = posix.errno() if (errno == ERROR_INVALID_HANDLE) { return false } throwNativeMethodFailed(Win32::GetConsoleMode) } return true } fun enableConsoleEscapeSequences() { updateConsoleMode(WindowsLibC.STD_OUTPUT_HANDLE) { currentMode -> currentMode or ENABLE_VIRTUAL_TERMINAL_PROCESSING or DISABLE_NEWLINE_AUTO_RETURN } } // This is based on MakeRaw from term_windows.go in the Docker CLI. fun enableConsoleRawMode(): Int = updateConsoleMode(WindowsLibC.STD_INPUT_HANDLE) { currentMode -> ( currentMode or ENABLE_EXTENDED_FLAGS or ENABLE_INSERT_MODE or ENABLE_QUICK_EDIT_MODE or ENABLE_VIRTUAL_TERMINAL_INPUT and ENABLE_ECHO_INPUT.inv() and ENABLE_LINE_INPUT.inv() and ENABLE_MOUSE_INPUT.inv() and ENABLE_WINDOW_INPUT.inv() and ENABLE_PROCESSED_INPUT.inv() ) } private fun updateConsoleMode(handle: Int, transform: (Int) -> Int): Int { val console = win32.GetStdHandle(handle) if (!console.isValid) { throwNativeMethodFailed(Win32::GetStdHandle) } val currentConsoleMode = IntByReference() if (!win32.GetConsoleMode(console, currentConsoleMode)) { throwNativeMethodFailed(Win32::GetConsoleMode) } val newConsoleMode = transform(currentConsoleMode.toInt()) if (!win32.SetConsoleMode(console, newConsoleMode)) { throwNativeMethodFailed(Win32::SetConsoleMode) } return currentConsoleMode.toInt() } fun restoreConsoleMode(previousMode: Int) { val console = win32.GetStdHandle(WindowsLibC.STD_INPUT_HANDLE) if (!console.isValid) { throwNativeMethodFailed(Win32::GetStdHandle) } if (!win32.SetConsoleMode(console, previousMode)) { throwNativeMethodFailed(Win32::SetConsoleMode) } } override fun getUserName(): String { val bytesPerCharacter = 2 val maxLengthInCharacters = 256 val buffer = ByteArray(maxLengthInCharacters * bytesPerCharacter) val length = IntByReference(maxLengthInCharacters) val succeeded = win32.GetUserNameW(ByteBuffer.wrap(buffer), length) if (!succeeded) { throwNativeMethodFailed(Win32::GetUserNameW) } val bytesReturned = (length.toInt() - 1) * bytesPerCharacter return String(buffer, 0, bytesReturned, Charsets.UTF_16LE) } override fun getUserId(): Int = throw UnsupportedOperationException("Getting the user ID is not supported on Windows.") override fun getGroupId(): Int = throw UnsupportedOperationException("Getting the group ID is not supported on Windows.") override fun getGroupName(): String = throw UnsupportedOperationException("Getting the group name is not supported on Windows.") fun openNamedPipe(path: String, connectionTimeoutInMilliseconds: Int): NamedPipe { val timeout = Duration.ofMillis(connectionTimeoutInMilliseconds.toLong()) val startTime = System.nanoTime() do { val result = win32.CreateFileW(WindowsHelpers.toWPath(path), GENERIC_READ or GENERIC_WRITE, 0L, null, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, null) if (!result.isValid) { if (posix.errno() == ERROR_FILE_NOT_FOUND) { throw FileNotFoundException("The named pipe $path does not exist.") } if (posix.errno() == ERROR_PIPE_BUSY) { waitForPipeToBeAvailable(path, startTime, timeout) continue } throwNativeMethodFailed(WindowsLibC::CreateFileW) } return NamedPipe(result, this) } while (!hasTimedOut(startTime, timeout)) throw connectionTimedOut(path, connectionTimeoutInMilliseconds) } private fun waitForPipeToBeAvailable(path: String, startTime: Long, timeout: Duration) { val currentTime = System.nanoTime() val endTime = startTime + timeout.toNanos() val remainingTime = Duration.ofNanos(endTime - currentTime) // We add one below as toMillis() rounds down and a value of 0 means 'use default wait' win32.WaitNamedPipeW(WindowsHelpers.toWPath(path), max(remainingTime.toMillis(), 1)) } private fun hasTimedOut(startTime: Long, timeout: Duration): Boolean { if (timeout.isZero) { return false } val elapsedTime = System.nanoTime() - startTime // We can't use A > B here due to overflow issues with nanoTime() // (see the nanoTime() docs for more details) return elapsedTime - timeout.toNanos() > 0 } private fun connectionTimedOut(path: String, connectionTimeoutInMilliseconds: Int) = SocketTimeoutException("Could not connect to $path within $connectionTimeoutInMilliseconds milliseconds.") fun closeNamedPipe(pipe: NamedPipe) { cancelIo(pipe, null) closeHandle(pipe.handle) } private fun closeHandle(handle: HANDLE) { if (!win32.CloseHandle(handle)) { if (posix.errno() == ERROR_INVALID_HANDLE) { return } throwNativeMethodFailed(Win32::CloseHandle) } } fun writeToNamedPipe(pipe: NamedPipe, buffer: ByteArray, offset: Int, length: Int) { val event = createEvent() try { val overlapped = Overlapped(runtime) overlapped.event.set(event.toPointer()) val bufferPointer = runtime.memoryManager.allocateDirect(length, true) bufferPointer.put(0, buffer, offset, length) startWrite(pipe, bufferPointer, overlapped) val bytesWritten = waitForOverlappedOperation(pipe, overlapped, event, WindowsLibC.INFINITE) if (bytesWritten != length) { throw RuntimeException("Expected to write $length bytes, but wrote $bytesWritten") } } finally { closeHandle(event) } } private fun startWrite(pipe: NamedPipe, buffer: Pointer, overlapped: Overlapped) { if (win32.WriteFile(pipe.handle, buffer, buffer.size(), null, overlapped)) { return } when (posix.errno()) { ERROR_IO_PENDING -> return else -> throwNativeMethodFailed(Win32::WriteFile) } } fun readFromNamedPipe(pipe: NamedPipe, buffer: ByteArray, offset: Int, maxLength: Int, timeoutInMilliseconds: Int): Int { val event = createEvent() try { val overlapped = Overlapped(runtime) overlapped.event.set(event.toPointer()) val bufferPointer = runtime.memoryManager.allocateDirect(maxLength, true) if (!startRead(pipe, bufferPointer, overlapped)) { return -1 } val bytesRead = waitForOverlappedOperation(pipe, overlapped, event, translateTimeout(timeoutInMilliseconds)) bufferPointer.get(0, buffer, offset, bytesRead) if (bytesRead == 0) { return -1 } return bytesRead } finally { closeHandle(event) } } private fun translateTimeout(timeoutInMilliseconds: Int): Int = if (timeoutInMilliseconds == 0) { WindowsLibC.INFINITE } else { timeoutInMilliseconds } private fun startRead(pipe: NamedPipe, buffer: Pointer, overlapped: Overlapped): Boolean { if (win32.ReadFile(pipe.handle, buffer, buffer.size(), null, overlapped)) { return true } return when (posix.errno()) { ERROR_IO_PENDING -> true ERROR_BROKEN_PIPE -> false else -> throwNativeMethodFailed(win32::ReadFile) } } private fun waitForOverlappedOperation(pipe: NamedPipe, overlapped: Overlapped, event: HANDLE, timeoutInMilliseconds: Int): Int { if (waitForEvent(event, timeoutInMilliseconds) == WaitResult.TimedOut) { cancelIo(pipe, overlapped) throw SocketTimeoutException("Operation timed out after $timeoutInMilliseconds ms.") } return getOverlappedResult(pipe, overlapped) } private fun getOverlappedResult(pipe: NamedPipe, overlapped: Overlapped): Int { val bytesTransferred = NativeLongByReference() if (!win32.GetOverlappedResult(pipe.handle, overlapped, bytesTransferred, false)) { if (posix.errno() == ERROR_OPERATION_ABORTED) { return 0 } throwNativeMethodFailed(Win32::GetOverlappedResult) } return bytesTransferred.toInt() } private fun createEvent(): HANDLE { val result = win32.CreateEventW(null, true, false, null) if (!result.isValid) { throwNativeMethodFailed(Win32::CreateEventW) } return result } private fun waitForEvent(event: HANDLE, timeoutInMilliseconds: Int): WaitResult { when (win32.WaitForSingleObject(event, timeoutInMilliseconds)) { WAIT_OBJECT_0 -> return WaitResult.Signaled WAIT_TIMEOUT -> return WaitResult.TimedOut WAIT_ABANDONED -> throw RuntimeException("WaitForSingleObject returned WAIT_ABANDONED") else -> throwNativeMethodFailed(Win32::WaitForSingleObject) } } private fun cancelIo(pipe: NamedPipe, overlapped: Overlapped?) { if (win32.CancelIoEx(pipe.handle, overlapped)) { return } when (posix.errno()) { // There was nothing to cancel, or the pipe has already been closed. ERROR_NOT_FOUND, ERROR_INVALID_HANDLE -> return else -> throwNativeMethodFailed(Win32::CancelIoEx) } } private fun <R> throwNativeMethodFailed(function: KFunction<R>): Nothing { val errno = posix.errno() val error = LastError.values().singleOrNull { it.intValue() == errno } if (error != null) { throw WindowsNativeMethodException(function.name, error) } throw WindowsNativeMethodException(function.name, "0x${errno.toString(16)}", "unknown", null) } private enum class WaitResult { Signaled, TimedOut } interface Win32 : WindowsLibC { @SaveError @StdCall fun GetConsoleScreenBufferInfo(@In hConsoleOutput: HANDLE, @Out @Transient lpConsoleScreenBufferInfo: ConsoleScreenBufferInfo): Boolean @SaveError @StdCall fun SetConsoleMode(@In hConsoleHandle: HANDLE, @In dwMode: Int): Boolean @SaveError @StdCall fun GetConsoleMode(@In hConsoleHandle: HANDLE, @Out lpMode: IntByReference): Boolean @SaveError fun GetUserNameW(@Out lpBuffer: ByteBuffer, @In @Out pcbBuffer: IntByReference): Boolean @StdCall fun CreateFileW( @In lpFileName: ByteArray, @In dwDesiredAccess: Long, @In dwShareMode: Long, @In lpSecurityAttributes: Pointer?, @In dwCreationDisposition: Long, @In dwFlagsAndAttributes: Long, @In hTemplateFile: HANDLE? ): HANDLE @SaveError fun WaitNamedPipeW(@In lpNamedPipeName: ByteArray, @In nTimeOut: Long): Boolean @SaveError fun WriteFile(@In hFile: HANDLE, @Direct lpBuffer: Pointer, @In nNumberOfBytesToWrite: Long, @Out lpNumberOfBytesWritten: NativeLongByReference?, @Direct lpOverlapped: Overlapped): Boolean @SaveError fun ReadFile(@In hFile: HANDLE, @Direct lpBuffer: Pointer, @In nNumberOfBytesToRead: Long, @Out lpNumberOfBytesRead: NativeLongByReference?, @Direct lpOverlapped: Overlapped): Boolean @SaveError fun CreateEventW(@In lpEventAttributes: Pointer?, @In bManualReset: Boolean, @In bInitialState: Boolean, @In lpName: ByteArray?): HANDLE @SaveError fun CancelIoEx(@In hFile: HANDLE, @Direct lpOverlapped: Overlapped?): Boolean @SaveError fun GetOverlappedResult(@In hFile: HANDLE, @Direct lpOverlapped: Overlapped, @Out lpNumberOfBytesTransferred: NativeLongByReference, @In bWait: Boolean): Boolean } class ConsoleScreenBufferInfo(runtime: Runtime) : Struct(runtime) { val dwSize = inner(Coord(runtime)) val dwCursorPosition = inner(Coord(runtime)) val wAttributes = WORD() val srWindow = inner(SmallRect(runtime)) val dwMaximumWindowSize = inner(Coord(runtime)) } class Coord(runtime: Runtime) : Struct(runtime) { val x = int16_t() val y = int16_t() } class SmallRect(runtime: Runtime) : Struct(runtime) { val left = int16_t() val top = int16_t() val right = int16_t() val bottom = int16_t() } class Overlapped(runtime: Runtime) : Struct(runtime) { val internal = UnsignedLong() val intervalHigh = UnsignedLong() val offsetHigh = DWORD() val offsetLow = DWORD() val pointer = Pointer() val event = Pointer() init { this.useMemory(runtime.memoryManager.allocateDirect(size(this), true)) } } companion object { private const val GENERIC_READ: Long = 0x80000000 private const val GENERIC_WRITE: Long = 0x40000000 private const val OPEN_EXISTING: Long = 0x00000003 private const val FILE_FLAG_OVERLAPPED: Long = 0x40000000 private const val ERROR_FILE_NOT_FOUND: Int = 0x00000002 private const val ERROR_INVALID_HANDLE: Int = 0x00000006 private const val ERROR_IO_PENDING: Int = 0x000003E5 private const val ERROR_OPERATION_ABORTED: Int = 0x000003E3 private const val ERROR_NOT_FOUND: Int = 0x00000490 private const val ERROR_PIPE_BUSY: Int = 0x000000E7 private const val ERROR_BROKEN_PIPE: Int = 0x0000006D private const val WAIT_ABANDONED: Int = 0x00000080 private const val WAIT_OBJECT_0: Int = 0x00000000 private const val WAIT_TIMEOUT: Int = 0x00000102 private const val ENABLE_ECHO_INPUT: Int = 0x4 private const val ENABLE_LINE_INPUT: Int = 0x2 private const val ENABLE_MOUSE_INPUT: Int = 0x10 private const val ENABLE_WINDOW_INPUT: Int = 0x8 private const val ENABLE_PROCESSED_INPUT: Int = 0x1 private const val ENABLE_EXTENDED_FLAGS: Int = 0x80 private const val ENABLE_INSERT_MODE: Int = 0x20 private const val ENABLE_QUICK_EDIT_MODE: Int = 0x40 private const val ENABLE_VIRTUAL_TERMINAL_INPUT: Int = 0x200 private const val ENABLE_VIRTUAL_TERMINAL_PROCESSING: Int = 0x4 private const val DISABLE_NEWLINE_AUTO_RETURN: Int = 0x8 // HACK: This is a hack to workaround the fact that POSIXTypeMapper isn't public, but we // need it to translate a number of different Win32 types to their JVM equivalents. fun createTypeMapper(): TypeMapper { val constructor = Class.forName("jnr.posix.POSIXTypeMapper").getDeclaredConstructor() constructor.isAccessible = true return constructor.newInstance() as TypeMapper } } } class WindowsNativeMethodException(method: String, errorName: String, errorDescription: String, val error: LastError?) : NativeMethodException(method, errorName, errorDescription) { constructor(method: String, error: LastError) : this(method, error.name, error.toString(), error) }
apache-2.0
7f70a8b182817dd69edd135f98bb2b15
34.996317
196
0.653433
4.463576
false
false
false
false
deva666/anko
anko/idea-plugin/preview/src/org/jetbrains/kotlin/android/dslpreview/AnkoViewLoaderExtension.kt
4
4972
package org.jetbrains.kotlin.android.dslpreview import org.jetbrains.android.uipreview.ViewLoaderExtension import org.jetbrains.org.objectweb.asm.ClassWriter import org.jetbrains.org.objectweb.asm.Opcodes import java.net.URL import java.net.URLClassLoader class AnkoViewLoaderExtension : ViewLoaderExtension { internal var description: PreviewClassDescription? = null override fun loadClass(className: String, delegateClassLoader: ClassLoader): Class<*>? { val description = this.description if (className == "__anko.preview.View" && description != null) { val clazz = generateStubViewClass(delegateClassLoader, description) if (clazz != null) return clazz } return null } private fun generateStubViewClass(delegateClassLoader: ClassLoader, description: PreviewClassDescription): Class<*>? { val uiInternalName = description.internalName val viewFqName = "__anko.preview.View" val viewInternalName = viewFqName.replace('.', '/') val superClassInternalName = "android/widget/FrameLayout" val bytes = with (ClassWriter(0)) { visit(49, Opcodes.ACC_PUBLIC, viewInternalName, null, superClassInternalName, null) visitSource(null, null) fun visitConstructor(vararg params: String) { val signature = "(${params.joinToString("")})V" with (visitMethod(Opcodes.ACC_PUBLIC, "<init>", signature, null, null)) { visitVarInsn(Opcodes.ALOAD, 0) params.forEachIndexed { i, param -> when (param) { "I" -> visitVarInsn(Opcodes.ILOAD, i + 1) else -> visitVarInsn(Opcodes.ALOAD, i + 1) } } visitMethodInsn(Opcodes.INVOKESPECIAL, superClassInternalName, "<init>", signature) visitVarInsn(Opcodes.ALOAD, 0) visitMethodInsn(Opcodes.INVOKEVIRTUAL, viewInternalName, "init", "()V") visitInsn(Opcodes.RETURN) visitMaxs(1 + params.size /*max stack*/, 1 + params.size /*max locals*/) visitEnd() } } visitConstructor("Landroid/content/Context;") visitConstructor("Landroid/content/Context;", "Landroid/util/AttributeSet;") visitConstructor("Landroid/content/Context;", "Landroid/util/AttributeSet;", "I") /* private fun init() { addView(MainActivityUi().createView(AnkoContext.create(getContext()))) } */ with (visitMethod(Opcodes.ACC_PRIVATE, "init", "()V", null, null)) { visitVarInsn(Opcodes.ALOAD, 0) visitTypeInsn(Opcodes.NEW, uiInternalName) visitInsn(Opcodes.DUP) visitMethodInsn(Opcodes.INVOKESPECIAL, uiInternalName, "<init>", "()V") visitFieldInsn(Opcodes.GETSTATIC, "org/jetbrains/anko/AnkoContext", "Companion", "Lorg/jetbrains/anko/AnkoContext" + '$' + "Companion;") visitVarInsn(Opcodes.ALOAD, 0) visitMethodInsn(Opcodes.INVOKEVIRTUAL, viewInternalName, "getContext", "()Landroid/content/Context;") visitInsn(Opcodes.ICONST_0) visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/jetbrains/anko/AnkoContext" + '$' + "Companion", "create", "(Landroid/content/Context;Z)Lorg/jetbrains/anko/AnkoContext;") visitMethodInsn(Opcodes.INVOKEVIRTUAL, uiInternalName, "createView", "(Lorg/jetbrains/anko/AnkoContext;)Landroid/view/View;") visitMethodInsn(Opcodes.INVOKEVIRTUAL, viewInternalName, "addView", "(Landroid/view/View;)V") visitInsn(Opcodes.RETURN) visitMaxs(5 /*max stack*/, 1 /*max locals*/) visitEnd() } visitEnd() toByteArray() } return loadClass(viewFqName, bytes, delegateClassLoader) } private fun loadClass(fqName: String, bytes: ByteArray, delegateClassLoader: ClassLoader): Class<*>? { class ByteClassLoader( urls: Array<out URL>?, parent: ClassLoader?, private var extraClasses: MutableMap<String, ByteArray> ) : URLClassLoader(urls, parent) { override fun findClass(name: String): Class<*>? { return extraClasses.remove(name)?.let { defineClass(name, it, 0, it.size) } ?: super.findClass(name) } } try { val classLoader = ByteClassLoader(emptyArray(), delegateClassLoader, hashMapOf(fqName to bytes)) return Class.forName(fqName, false, classLoader) } catch (e: Throwable) { return null } } }
apache-2.0
39f1c9c15446bfaa5b802adb9755498c
43.00885
122
0.587289
5.052846
false
false
false
false
charleskorn/batect
app/src/main/kotlin/batect/ui/EventLoggerProvider.kt
1
3943
/* 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.ui import batect.execution.ContainerDependencyGraph import batect.execution.RunOptions import batect.ui.containerio.TaskContainerOnlyIOStreamingOptions import batect.ui.fancy.CleanupProgressDisplay import batect.ui.fancy.FancyEventLogger import batect.ui.fancy.StartupProgressDisplayProvider import batect.ui.interleaved.InterleavedEventLogger import batect.ui.interleaved.InterleavedOutput import batect.ui.quiet.QuietEventLogger import batect.ui.simple.SimpleEventLogger import batect.utils.mapToSet import java.io.InputStream import java.io.PrintStream class EventLoggerProvider( private val failureErrorMessageFormatter: FailureErrorMessageFormatter, private val console: Console, private val errorConsole: Console, private val stdout: PrintStream, private val stdin: InputStream, private val startupProgressDisplayProvider: StartupProgressDisplayProvider, private val consoleInfo: ConsoleInfo, private val requestedOutputStyle: OutputStyle?, private val disableColorOutput: Boolean ) { fun getEventLogger(graph: ContainerDependencyGraph, runOptions: RunOptions): EventLogger { return when (requestedOutputStyle) { OutputStyle.Quiet -> createQuietLogger(graph, runOptions) OutputStyle.Fancy -> createFancyLogger(graph, runOptions) OutputStyle.Simple -> createSimpleLogger(graph, runOptions) OutputStyle.All -> createInterleavedLogger(graph, runOptions) null -> { if (!consoleInfo.supportsInteractivity || disableColorOutput) { createSimpleLogger(graph, runOptions) } else { createFancyLogger(graph, runOptions) } } } } private fun createQuietLogger(graph: ContainerDependencyGraph, runOptions: RunOptions) = QuietEventLogger(failureErrorMessageFormatter, runOptions, errorConsole, createTaskContainerOnlyIOStreamingOptions(graph)) private fun createFancyLogger(graph: ContainerDependencyGraph, runOptions: RunOptions): FancyEventLogger = FancyEventLogger(failureErrorMessageFormatter, runOptions, console, errorConsole, startupProgressDisplayProvider.createForDependencyGraph(graph), CleanupProgressDisplay(), graph.taskContainerNode.container, createTaskContainerOnlyIOStreamingOptions(graph)) private fun createSimpleLogger(graph: ContainerDependencyGraph, runOptions: RunOptions): SimpleEventLogger { val containers = graph.allNodes.mapToSet { it.container } return SimpleEventLogger(containers, graph.taskContainerNode.container, failureErrorMessageFormatter, runOptions, console, errorConsole, createTaskContainerOnlyIOStreamingOptions(graph)) } private fun createTaskContainerOnlyIOStreamingOptions(graph: ContainerDependencyGraph) = TaskContainerOnlyIOStreamingOptions(graph.taskContainerNode.container, stdout, stdin, consoleInfo) private fun createInterleavedLogger(graph: ContainerDependencyGraph, runOptions: RunOptions): InterleavedEventLogger { val containers = graph.allNodes.mapToSet { it.container } val output = InterleavedOutput(graph.task.name, containers, console) return InterleavedEventLogger(graph.taskContainerNode.container, containers, output, failureErrorMessageFormatter, runOptions) } }
apache-2.0
00a97946fc939e906abc73fb7805d15e
48.911392
264
0.775805
5.18134
false
false
false
false
scenerygraphics/SciView
src/main/kotlin/sc/iview/commands/view/ToggleUnlimitedFramerate.kt
1
2246
/*- * #%L * Scenery-backed 3D visualization package for ImageJ. * %% * Copyright (C) 2016 - 2021 SciView developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package sc.iview.commands.view import org.scijava.command.Command import org.scijava.plugin.Menu import org.scijava.plugin.Parameter import org.scijava.plugin.Plugin import sc.iview.SciView import sc.iview.commands.MenuWeights /** * Command to toggle scenery's PushMode. If this is true the scene only renders when it is changed, otherwise it is * continuously rendered * * @author Kyle Harrington */ @Plugin(type = Command::class, menuRoot = "SciView", menu = [Menu(label = "View", weight = MenuWeights.VIEW), Menu(label = "Toggle Unlimited Framerate", weight = MenuWeights.VIEW_TOGGLE_UNLIMITED_FRAMERATE)]) class ToggleUnlimitedFramerate : Command { @Parameter private lateinit var sciView: SciView override fun run() { sciView.setPushMode(!sciView.getPushMode()) } }
bsd-2-clause
b5f5f85866a65fdba03b04798c1b8596
42.192308
208
0.755565
4.26186
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/Scrollable.kt
3
22734
/* * 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.foundation.gestures import androidx.compose.animation.core.AnimationState import androidx.compose.animation.core.DecayAnimationSpec import androidx.compose.animation.core.animateDecay import androidx.compose.animation.rememberSplineBasedDecay import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.OverscrollEffect import androidx.compose.foundation.focusGroup import androidx.compose.foundation.gestures.Orientation.Horizontal import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.rememberOverscrollEffect import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.MotionDurationScale import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.ScrollContainerInfo import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.NestedScrollSource.Companion.Drag import androidx.compose.ui.input.nestedscroll.NestedScrollSource.Companion.Fling import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.PointerType import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.provideScrollContainerInfo import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.Velocity import androidx.compose.ui.util.fastAll import androidx.compose.ui.util.fastForEach import kotlin.math.abs import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Configure touch scrolling and flinging for the UI element in a single [Orientation]. * * Users should update their state themselves using default [ScrollableState] and its * `consumeScrollDelta` callback or by implementing [ScrollableState] interface manually and reflect * their own state in UI when using this component. * * If you don't need to have fling or nested scroll support, but want to make component simply * draggable, consider using [draggable]. * * @sample androidx.compose.foundation.samples.ScrollableSample * * @param state [ScrollableState] state of the scrollable. Defines how scroll events will be * interpreted by the user land logic and contains useful information about on-going events. * @param orientation orientation of the scrolling * @param enabled whether or not scrolling in enabled * @param reverseDirection reverse the direction of the scroll, so top to bottom scroll will * behave like bottom to top and left to right will behave like right to left. * @param flingBehavior logic describing fling behavior when drag has finished with velocity. If * `null`, default from [ScrollableDefaults.flingBehavior] will be used. * @param interactionSource [MutableInteractionSource] that will be used to emit * drag events when this scrollable is being dragged. */ @OptIn(ExperimentalFoundationApi::class) fun Modifier.scrollable( state: ScrollableState, orientation: Orientation, enabled: Boolean = true, reverseDirection: Boolean = false, flingBehavior: FlingBehavior? = null, interactionSource: MutableInteractionSource? = null ): Modifier = scrollable( state = state, orientation = orientation, enabled = enabled, reverseDirection = reverseDirection, flingBehavior = flingBehavior, interactionSource = interactionSource, overscrollEffect = null ) /** * Configure touch scrolling and flinging for the UI element in a single [Orientation]. * * Users should update their state themselves using default [ScrollableState] and its * `consumeScrollDelta` callback or by implementing [ScrollableState] interface manually and reflect * their own state in UI when using this component. * * If you don't need to have fling or nested scroll support, but want to make component simply * draggable, consider using [draggable]. * * This overload provides the access to [OverscrollEffect] that defines the behaviour of the * over scrolling logic. Consider using [ScrollableDefaults.overscrollEffect] for the platform * look-and-feel. * * @sample androidx.compose.foundation.samples.ScrollableSample * * @param state [ScrollableState] state of the scrollable. Defines how scroll events will be * interpreted by the user land logic and contains useful information about on-going events. * @param orientation orientation of the scrolling * @param overscrollEffect effect to which the deltas will be fed when the scrollable have * some scrolling delta left. Pass `null` for no overscroll. If you pass an effect you should * also apply [androidx.compose.foundation.overscroll] modifier. * @param enabled whether or not scrolling in enabled * @param reverseDirection reverse the direction of the scroll, so top to bottom scroll will * behave like bottom to top and left to right will behave like right to left. * @param flingBehavior logic describing fling behavior when drag has finished with velocity. If * `null`, default from [ScrollableDefaults.flingBehavior] will be used. * @param interactionSource [MutableInteractionSource] that will be used to emit * drag events when this scrollable is being dragged. */ @ExperimentalFoundationApi fun Modifier.scrollable( state: ScrollableState, orientation: Orientation, overscrollEffect: OverscrollEffect?, enabled: Boolean = true, reverseDirection: Boolean = false, flingBehavior: FlingBehavior? = null, interactionSource: MutableInteractionSource? = null ): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "scrollable" properties["orientation"] = orientation properties["state"] = state properties["overscrollEffect"] = overscrollEffect properties["enabled"] = enabled properties["reverseDirection"] = reverseDirection properties["flingBehavior"] = flingBehavior properties["interactionSource"] = interactionSource }, factory = { val coroutineScope = rememberCoroutineScope() val keepFocusedChildInViewModifier = remember(coroutineScope, orientation, state, reverseDirection) { ContentInViewModifier(coroutineScope, orientation, state, reverseDirection) } Modifier .focusGroup() .then(keepFocusedChildInViewModifier.modifier) .pointerScrollable( interactionSource, orientation, reverseDirection, state, flingBehavior, overscrollEffect, enabled ) } ) /** * Contains the default values used by [scrollable] */ object ScrollableDefaults { /** * Create and remember default [FlingBehavior] that will represent natural fling curve. */ @Composable fun flingBehavior(): FlingBehavior { val flingSpec = rememberSplineBasedDecay<Float>() return remember(flingSpec) { DefaultFlingBehavior(flingSpec) } } /** * Create and remember default [OverscrollEffect] that will be used for showing over scroll * effects. */ @Composable @ExperimentalFoundationApi fun overscrollEffect(): OverscrollEffect { return rememberOverscrollEffect() } /** * Used to determine the value of `reverseDirection` parameter of [Modifier.scrollable] * in scrollable layouts. * * @param layoutDirection current layout direction (e.g. from [LocalLayoutDirection]) * @param orientation orientation of scroll * @param reverseScrolling whether scrolling direction should be reversed * * @return `true` if scroll direction should be reversed, `false` otherwise. */ fun reverseDirection( layoutDirection: LayoutDirection, orientation: Orientation, reverseScrolling: Boolean ): Boolean { // A finger moves with the content, not with the viewport. Therefore, // always reverse once to have "natural" gesture that goes reversed to layout var reverseDirection = !reverseScrolling // But if rtl and horizontal, things move the other way around val isRtl = layoutDirection == LayoutDirection.Rtl if (isRtl && orientation != Orientation.Vertical) { reverseDirection = !reverseDirection } return reverseDirection } } internal interface ScrollConfig { fun Density.calculateMouseWheelScroll(event: PointerEvent, bounds: IntSize): Offset } @Composable internal expect fun platformScrollConfig(): ScrollConfig @Suppress("ComposableModifierFactory") @Composable @OptIn(ExperimentalFoundationApi::class) private fun Modifier.pointerScrollable( interactionSource: MutableInteractionSource?, orientation: Orientation, reverseDirection: Boolean, controller: ScrollableState, flingBehavior: FlingBehavior?, overscrollEffect: OverscrollEffect?, enabled: Boolean ): Modifier { val fling = flingBehavior ?: ScrollableDefaults.flingBehavior() val nestedScrollDispatcher = remember { mutableStateOf(NestedScrollDispatcher()) } val scrollLogic = rememberUpdatedState( ScrollingLogic( orientation, reverseDirection, nestedScrollDispatcher, controller, fling, overscrollEffect ) ) val nestedScrollConnection = remember(enabled) { scrollableNestedScrollConnection(scrollLogic, enabled) } val draggableState = remember { ScrollDraggableState(scrollLogic) } val scrollConfig = platformScrollConfig() val scrollContainerInfo = remember(orientation, enabled) { object : ScrollContainerInfo { override fun canScrollHorizontally() = enabled && orientation == Horizontal override fun canScrollVertically() = enabled && orientation == Orientation.Vertical } } return draggable( draggableState, orientation = orientation, enabled = enabled, interactionSource = interactionSource, reverseDirection = false, startDragImmediately = { scrollLogic.value.shouldScrollImmediately() }, onDragStopped = { velocity -> nestedScrollDispatcher.value.coroutineScope.launch { scrollLogic.value.onDragStopped(velocity) } }, canDrag = { down -> down.type != PointerType.Mouse } ) .mouseWheelScroll(scrollLogic, scrollConfig) .nestedScroll(nestedScrollConnection, nestedScrollDispatcher.value) .provideScrollContainerInfo(scrollContainerInfo) } private fun Modifier.mouseWheelScroll( scrollingLogicState: State<ScrollingLogic>, mouseWheelScrollConfig: ScrollConfig, ) = pointerInput(scrollingLogicState, mouseWheelScrollConfig) { awaitPointerEventScope { while (true) { val event = awaitScrollEvent() if (event.changes.fastAll { !it.isConsumed }) { with(mouseWheelScrollConfig) { val scrollAmount = calculateMouseWheelScroll(event, size) with(scrollingLogicState.value) { val delta = scrollAmount.toFloat().reverseIfNeeded() val consumedDelta = scrollableState.dispatchRawDelta(delta) if (consumedDelta != 0f) { event.changes.fastForEach { it.consume() } } } } } } } } private suspend fun AwaitPointerEventScope.awaitScrollEvent(): PointerEvent { var event: PointerEvent do { event = awaitPointerEvent() } while (event.type != PointerEventType.Scroll) return event } @OptIn(ExperimentalFoundationApi::class) private class ScrollingLogic( val orientation: Orientation, val reverseDirection: Boolean, val nestedScrollDispatcher: State<NestedScrollDispatcher>, val scrollableState: ScrollableState, val flingBehavior: FlingBehavior, val overscrollEffect: OverscrollEffect? ) { private val isNestedFlinging = mutableStateOf(false) fun Float.toOffset(): Offset = when { this == 0f -> Offset.Zero orientation == Horizontal -> Offset(this, 0f) else -> Offset(0f, this) } fun Offset.singleAxisOffset(): Offset = if (orientation == Horizontal) copy(y = 0f) else copy(x = 0f) fun Offset.toFloat(): Float = if (orientation == Horizontal) this.x else this.y fun Velocity.toFloat(): Float = if (orientation == Horizontal) this.x else this.y fun Velocity.singleAxisVelocity(): Velocity = if (orientation == Horizontal) copy(y = 0f) else copy(x = 0f) fun Velocity.update(newValue: Float): Velocity = if (orientation == Horizontal) copy(x = newValue) else copy(y = newValue) fun Float.reverseIfNeeded(): Float = if (reverseDirection) this * -1 else this fun Offset.reverseIfNeeded(): Offset = if (reverseDirection) this * -1f else this /** * @return the amount of scroll that was consumed */ fun ScrollScope.dispatchScroll(availableDelta: Offset, source: NestedScrollSource): Offset { val scrollDelta = availableDelta.singleAxisOffset() val overscrollPreConsumed = overscrollPreConsumeDelta(scrollDelta, source) val afterPreOverscroll = scrollDelta - overscrollPreConsumed val nestedScrollDispatcher = nestedScrollDispatcher.value val preConsumedByParent = nestedScrollDispatcher .dispatchPreScroll(afterPreOverscroll, source) val scrollAvailable = afterPreOverscroll - preConsumedByParent // Consume on a single axis val axisConsumed = scrollBy(scrollAvailable.reverseIfNeeded().toFloat()).toOffset().reverseIfNeeded() val leftForParent = scrollAvailable - axisConsumed val parentConsumed = nestedScrollDispatcher.dispatchPostScroll( axisConsumed, leftForParent, source ) overscrollPostConsumeDelta( scrollAvailable, leftForParent - parentConsumed, source ) return overscrollPreConsumed + preConsumedByParent + axisConsumed + parentConsumed } private val shouldDispatchOverscroll get() = scrollableState.canScrollForward || scrollableState.canScrollBackward fun overscrollPreConsumeDelta( scrollDelta: Offset, source: NestedScrollSource ): Offset { return if (overscrollEffect != null && shouldDispatchOverscroll) { overscrollEffect.consumePreScroll(scrollDelta, source) } else { Offset.Zero } } private fun overscrollPostConsumeDelta( consumedByChain: Offset, availableForOverscroll: Offset, source: NestedScrollSource ) { if (overscrollEffect != null && shouldDispatchOverscroll) { overscrollEffect.consumePostScroll( consumedByChain, availableForOverscroll, source ) } } fun performRawScroll(scroll: Offset): Offset { return if (scrollableState.isScrollInProgress) { Offset.Zero } else { scrollableState.dispatchRawDelta(scroll.toFloat().reverseIfNeeded()) .reverseIfNeeded().toOffset() } } suspend fun onDragStopped(initialVelocity: Velocity) { // Self started flinging, set registerNestedFling(true) val availableVelocity = initialVelocity.singleAxisVelocity() val preOverscrollConsumed = if (overscrollEffect != null && shouldDispatchOverscroll) { overscrollEffect.consumePreFling(availableVelocity) } else { Velocity.Zero } val velocity = (availableVelocity - preOverscrollConsumed) val preConsumedByParent = nestedScrollDispatcher .value.dispatchPreFling(velocity) val available = velocity - preConsumedByParent val velocityLeft = doFlingAnimation(available) val consumedPost = nestedScrollDispatcher.value.dispatchPostFling( (available - velocityLeft), velocityLeft ) val totalLeft = velocityLeft - consumedPost if (overscrollEffect != null && shouldDispatchOverscroll) { overscrollEffect.consumePostFling(totalLeft) } // Self stopped flinging, reset registerNestedFling(false) } suspend fun doFlingAnimation(available: Velocity): Velocity { var result: Velocity = available scrollableState.scroll { val outerScopeScroll: (Offset) -> Offset = { delta -> dispatchScroll(delta.reverseIfNeeded(), Fling).reverseIfNeeded() } val scope = object : ScrollScope { override fun scrollBy(pixels: Float): Float { return outerScopeScroll.invoke(pixels.toOffset()).toFloat() } } with(scope) { with(flingBehavior) { result = result.update( performFling(available.toFloat().reverseIfNeeded()).reverseIfNeeded() ) } } } return result } fun shouldScrollImmediately(): Boolean { return scrollableState.isScrollInProgress || isNestedFlinging.value || overscrollEffect?.isInProgress ?: false } fun registerNestedFling(isFlinging: Boolean) { isNestedFlinging.value = isFlinging } } private class ScrollDraggableState( val scrollLogic: State<ScrollingLogic> ) : DraggableState, DragScope { var latestScrollScope: ScrollScope = NoOpScrollScope override fun dragBy(pixels: Float) { with(scrollLogic.value) { with(latestScrollScope) { dispatchScroll(pixels.toOffset(), Drag) } } } override suspend fun drag(dragPriority: MutatePriority, block: suspend DragScope.() -> Unit) { scrollLogic.value.scrollableState.scroll(dragPriority) { latestScrollScope = this block() } } override fun dispatchRawDelta(delta: Float) { with(scrollLogic.value) { performRawScroll(delta.toOffset()) } } } private val NoOpScrollScope: ScrollScope = object : ScrollScope { override fun scrollBy(pixels: Float): Float = pixels } private fun scrollableNestedScrollConnection( scrollLogic: State<ScrollingLogic>, enabled: Boolean ): NestedScrollConnection = object : NestedScrollConnection { override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { // child will fling, set if (source == Fling) { scrollLogic.value.registerNestedFling(true) } return Offset.Zero } override fun onPostScroll( consumed: Offset, available: Offset, source: NestedScrollSource ): Offset = if (enabled) { scrollLogic.value.performRawScroll(available) } else { Offset.Zero } override suspend fun onPostFling( consumed: Velocity, available: Velocity ): Velocity { return if (enabled) { val velocityLeft = scrollLogic.value.doFlingAnimation(available) available - velocityLeft } else { Velocity.Zero }.also { // Flinging child finished flinging, reset scrollLogic.value.registerNestedFling(false) } } } internal class DefaultFlingBehavior( private val flingDecay: DecayAnimationSpec<Float>, private val motionDurationScale: MotionDurationScale = DefaultScrollMotionDurationScale ) : FlingBehavior { // For Testing var lastAnimationCycleCount = 0 override suspend fun ScrollScope.performFling(initialVelocity: Float): Float { lastAnimationCycleCount = 0 // come up with the better threshold, but we need it since spline curve gives us NaNs return withContext(motionDurationScale) { if (abs(initialVelocity) > 1f) { var velocityLeft = initialVelocity var lastValue = 0f AnimationState( initialValue = 0f, initialVelocity = initialVelocity, ).animateDecay(flingDecay) { val delta = value - lastValue val consumed = scrollBy(delta) lastValue = value velocityLeft = this.velocity // avoid rounding errors and stop if anything is unconsumed if (abs(delta - consumed) > 0.5f) this.cancelAnimation() lastAnimationCycleCount++ } velocityLeft } else { initialVelocity } } } } private const val DefaultScrollMotionDurationScaleFactor = 1f internal val DefaultScrollMotionDurationScale = object : MotionDurationScale { override val scaleFactor: Float get() = DefaultScrollMotionDurationScaleFactor }
apache-2.0
02b47957f147e1af93ac944e34c395b6
36.953255
100
0.689628
5.310441
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/BufferObject.kt
1
1648
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl import org.lwjgl.generator.* class BufferObject(val binding: String): ParameterModifier() { companion object: ModifierKey<BufferObject> override val isSpecial = true override fun validate(param: Parameter) { if ( !((param.nativeType is PointerType && param.nativeType.mapping !== PointerMapping.OPAQUE_POINTER) || param.nativeType.mapping === PrimitiveMapping.POINTER) ) throw IllegalArgumentException("The BufferObject modifier can only be applied on data pointer types or long primitives.") when ( this ) { PIXEL_PACK_BUFFER, QUERY_BUFFER_AMD -> { if ( param.paramType !== ParameterType.OUT ) throw IllegalArgumentException("The specified BufferObject modifier can only be applied on output parameters.") } else -> { if ( param.paramType !== ParameterType.IN ) throw IllegalArgumentException("The specified BufferObject modifier can only be applied on input parameters.") } } } } val ARRAY_BUFFER = BufferObject("GL15.GL_ARRAY_BUFFER_BINDING") val ELEMENT_ARRAY_BUFFER = BufferObject("GL15.GL_ELEMENT_ARRAY_BUFFER_BINDING") val PIXEL_PACK_BUFFER = BufferObject("GL21.GL_PIXEL_PACK_BUFFER_BINDING") val PIXEL_UNPACK_BUFFER = BufferObject("GL21.GL_PIXEL_UNPACK_BUFFER_BINDING") val DRAW_INDIRECT_BUFFER = BufferObject("GL40.GL_DRAW_INDIRECT_BUFFER_BINDING") val DISPATCH_INDIRECT_BUFFER = BufferObject("GL43.GL_DISPATCH_INDIRECT_BUFFER_BINDING") val QUERY_BUFFER_AMD = BufferObject("AMDQueryBufferObject.GL_QUERY_BUFFER_BINDING_AMD")
bsd-3-clause
0983126147fb9eb8c7a103bc0a707b3b
41.282051
164
0.737864
3.971084
false
false
false
false
codebutler/odyssey
retrograde-storage-gdrive/src/main/java/com/codebutler/retrograde/storage/gdrive/GDriveBrowser.kt
1
4942
/* * GDriveBrowser.kt * * Copyright (C) 2017 Retrograde Project * * 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.codebutler.retrograde.storage.gdrive import com.google.api.client.http.ByteArrayContent import com.google.api.services.drive.Drive import com.google.api.services.drive.model.File import io.reactivex.Single import java.io.FileOutputStream class GDriveBrowser(private val driveFactory: DriveFactory) { fun downloadById(fileId: String, stream: FileOutputStream) { val drive = driveFactory.create().toNullable() ?: throw IllegalStateException() drive.files() .get(fileId) .executeMediaAndDownloadTo(stream) } fun downloadByName(space: String = "drive", parentFolderId: String?, fileName: String): ByteArray? { val drive = driveFactory.create().toNullable() ?: throw IllegalStateException() val existingFile = getFileMetadata(drive, space, parentFolderId, fileName) val fileId = existingFile?.id ?: return null return drive.files() .get(fileId) .executeMediaAsInputStream() .use { stream -> stream.readBytes() } } fun uploadByName(space: String = "drive", parentFolderId: String?, fileName: String, data: ByteArray): File? { val drive = driveFactory.create().toNullable() ?: throw IllegalStateException() val content = ByteArrayContent("application/octet-stream", data) val existingFile = getFileMetadata(drive, space, parentFolderId, fileName) return if (existingFile != null) { drive.files().update(existingFile.id, null, content) .execute() } else { val newFileMetadata = File() newFileMetadata.name = fileName if (parentFolderId != null) { newFileMetadata.parents = listOf(space, parentFolderId) } else { newFileMetadata.parents = listOf(space) } drive.files() .create(newFileMetadata, content) .setFields("id, parents, name") .execute() } } fun list(parentId: String): Single<List<File>> = Single.fromCallable { val drive = driveFactory.create().toNullable() ?: return@fromCallable listOf<File>() val mutableList = mutableListOf<File>() var pageToken: String? = null do { val result = drive.files().list() .setQ("'$parentId' in parents") .setFields("nextPageToken, files(id, name, mimeType, size)") .setPageToken(pageToken) .execute() mutableList.addAll(result.files) pageToken = result.nextPageToken } while (pageToken != null) mutableList.toList() } fun listRecursive(folderId: String): Sequence<File> { val drive = driveFactory.create().toNullable() ?: return emptySequence() return listRecursive(drive, folderId) } private fun getFileMetadata(drive: Drive, space: String, parentId: String?, fileName: String): File? { val q = if (parentId != null) { "'$parentId' in parents and name = '$fileName'" } else { "name = '$fileName'" } return drive.files().list() .setSpaces(space) .setQ(q) .execute() .files .firstOrNull() } private fun listRecursive(drive: Drive, folderId: String): Sequence<File> { var pageToken: String? = null return sequence { do { val result = drive.files().list() .setQ("'$folderId' in parents") .setFields("nextPageToken, files(id, name, mimeType, size)") .setPageToken(pageToken) .execute() for (file in result.files) { if (file.mimeType == "application/vnd.google-apps.folder") { yieldAll(listRecursive(drive, file.id)) } else { yield(file) } } pageToken = result.nextPageToken } while (pageToken != null) } } }
gpl-3.0
b9ea163520d8fa89477c6b2a9374d85e
38.854839
114
0.587616
4.774879
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
app/src/main/java/com/pedro/rtpstreamer/rotation/RotationExampleActivity.kt
1
6542
package com.pedro.rtpstreamer.rotation import android.app.ActivityManager import android.content.Context import android.content.Intent import android.media.projection.MediaProjectionManager import android.os.Build import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.SurfaceHolder import android.view.WindowManager import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.pedro.rtplibrary.util.sources.VideoManager import com.pedro.rtpstreamer.R import com.pedro.rtpstreamer.databinding.ActivityExampleBinding import com.pedro.rtpstreamer.utils.PathUtils import java.text.SimpleDateFormat import java.util.* /** * Created by pedro on 22/3/22. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) class RotationExampleActivity: AppCompatActivity(), SurfaceHolder.Callback { private val REQUEST_CODE_SCREEN_VIDEO = 1 private val REQUEST_CODE_INTERNAL_AUDIO = 2 private var askingMediaProjection = false private lateinit var binding: ActivityExampleBinding private var service: StreamService? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) binding = ActivityExampleBinding.inflate(layoutInflater) setContentView(binding.root) binding.etRtpUrl.setHint(R.string.hint_rtmp) binding.surfaceView.holder.addCallback(this) StreamService.observer.observe(this) { if (it != null) { service = if (!it.prepare()) { Toast.makeText(this, "Prepare method failed", Toast.LENGTH_SHORT).show() null } else it } startPreview() } binding.bStartStop.setOnClickListener { if (service?.isStreaming() != true) { service?.startStream(binding.etRtpUrl.text.toString()) binding.bStartStop.setText(R.string.stop_button) } else { service?.stopStream() binding.bStartStop.setText(R.string.start_button) } } binding.bRecord.setOnClickListener { if (service?.isRecording() != true) { val folder = PathUtils.getRecordPath() if (!folder.exists()) folder.mkdir() val sdf = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()) val fileName = sdf.format(Date()) service?.startRecord("${folder.absolutePath}/$fileName.mp4") binding.bRecord.setText(R.string.stop_record) } else { service?.stopRecord() binding.bRecord.setText(R.string.start_record) } } binding.switchCamera.setOnClickListener { service?.switchCamera() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.rotation_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.video_source_camera1 -> { service?.changeVideoSourceCamera(VideoManager.Source.CAMERA1) } R.id.video_source_camera2 -> { service?.changeVideoSourceCamera(VideoManager.Source.CAMERA2) } R.id.video_source_screen -> { askingMediaProjection = true val mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager val intent = mediaProjectionManager.createScreenCaptureIntent() startActivityForResult(intent, REQUEST_CODE_SCREEN_VIDEO) } R.id.audio_source_microphone -> { service?.changeAudioSourceMicrophone() } R.id.audio_source_internal -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { askingMediaProjection = true val mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager val intent = mediaProjectionManager.createScreenCaptureIntent() startActivityForResult(intent, REQUEST_CODE_INTERNAL_AUDIO) } else { Toast.makeText(this, "Android 10+ required", Toast.LENGTH_SHORT).show() } } else -> return false } return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data != null && resultCode == RESULT_OK) { if (requestCode == REQUEST_CODE_SCREEN_VIDEO) { askingMediaProjection = false service?.changeVideoSourceScreen(this, resultCode, data) } else if (requestCode == REQUEST_CODE_INTERNAL_AUDIO && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { askingMediaProjection = false service?.changeAudioSourceInternal(this, resultCode, data) } } } override fun onResume() { super.onResume() if (!isMyServiceRunning(StreamService::class.java)) { val intent = Intent(applicationContext, StreamService::class.java) startService(intent) } if (service?.isStreaming() == true) { binding.bStartStop.setText(R.string.stop_button) } else { binding.bStartStop.setText(R.string.start_button) } if (service?.isRecording() == true) { binding.bRecord.setText(R.string.stop_record) } else { binding.bRecord.setText(R.string.start_record) } } override fun onPause() { super.onPause() if (!isChangingConfigurations && !askingMediaProjection) { //stop if no rotation activity if (service?.isStreaming() == true) service?.stopStream() if (service?.isOnPreview() == true) service?.stopPreview() service = null stopService(Intent(applicationContext, StreamService::class.java)) } } override fun surfaceChanged(holder: SurfaceHolder, p1: Int, p2: Int, p3: Int) { startPreview() } override fun surfaceDestroyed(holder: SurfaceHolder) { if (service?.isOnPreview() == true) service?.stopPreview() } override fun surfaceCreated(holder: SurfaceHolder) { } private fun startPreview() { //check if onPreview and if surface is valid if (service?.isOnPreview() != true && binding.surfaceView.holder.surface.isValid) { service?.startPreview(binding.surfaceView) } } @Suppress("DEPRECATION") private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name == service.service.className) { return true } } return false } }
apache-2.0
592440f925060c0262201b92784c5ce8
34.177419
112
0.69948
4.32386
false
false
false
false
devromik/black-and-white
sources/src/main/kotlin/net/devromik/bw/x/SingleChildXResult.kt
1
1606
package net.devromik.bw.x import net.devromik.bw.Color import net.devromik.bw.Color.* import net.devromik.bw.Coloring import net.devromik.bw.FixedRootColorMaxWhiteMap /** * @author Shulnyaev Roman */ class SingleChildXResult<D>( val rootBlackResult: XResult<D>, val rootWhiteResult: XResult<D>, val rootGrayResult: XResult<D>) : XResult<D> { val results: Array<XResult<D>> val maxWhiteMaps: Array<FixedRootColorMaxWhiteMap> val maxWhiteMap: FixedRootColorMaxWhiteMap val subtreeSize = rootBlackResult.subtreeSize() // ****************************** // init { results = arrayOf(rootBlackResult, rootWhiteResult, rootGrayResult) maxWhiteMaps = arrayOf(rootBlackResult.maxWhiteMap(), rootWhiteResult.maxWhiteMap(), rootGrayResult.maxWhiteMap()) maxWhiteMap = object : FixedRootColorMaxWhiteMap(subtreeSize()) { override fun get(rootColor: Color, black: Int) = maxWhiteMaps[rootColor.index][black] } } // ****************************** // override fun maxWhiteMap() = maxWhiteMap override fun color(coloring: Coloring<D>, rootColor: Color, black: Int, maxWhite: Int) { val maxWhiteMap = maxWhiteMaps[rootColor.index] val lastChainNodeColor = when (maxWhite) { maxWhiteMap[BLACK, black] -> BLACK maxWhiteMap[WHITE, black] -> WHITE else -> GRAY } val result = results[rootColor.index] result.color(coloring, lastChainNodeColor, black, maxWhite) } override fun subtreeSize() = subtreeSize }
mit
d7bb73df17852c450835dd3eefba8c2b
29.903846
122
0.646949
4.473538
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/TimelinePosition.kt
1
2051
/* * Copyright (C) 2013 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.social import android.net.Uri import org.andstatus.app.util.IsEmpty import org.andstatus.app.util.StringUtil import org.andstatus.app.util.UriUtils import java.util.* /** * Since introducing support for Pump.Io it appeared that * Position in the Timeline and Id of the Note may be different things. * @author [email protected] */ class TimelinePosition private constructor(position: String?) : IsEmpty { private val position: String = if (position.isNullOrEmpty()) "" else position fun getPosition(): String { return position } fun optUri(): Optional<Uri> { return UriUtils.toDownloadableOptional(position) } override fun toString(): String { return position } fun isTemp(): Boolean { return StringUtil.isTemp(position) } override val isEmpty: Boolean get() { return position.isEmpty() } override fun equals(other: Any?): Boolean { if (this === other) return true return if (other !is TimelinePosition) false else position == other.position } override fun hashCode(): Int { return position.hashCode() } companion object { val EMPTY: TimelinePosition = TimelinePosition("") fun of(position: String?): TimelinePosition = if (position.isNullOrEmpty()) EMPTY else TimelinePosition(position) } }
apache-2.0
057fa8798d21957a7e28faaf685fd91a
28.724638
84
0.685519
4.429806
false
false
false
false
mvosske/comlink
app/src/main/java/org/tnsfit/dragon/comlink/matrix/MatrixService.kt
1
3267
package org.tnsfit.dragon.comlink.matrix import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.IBinder import android.support.v4.app.NotificationManagerCompat import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.tnsfit.dragon.comlink.misc.AppConstants import org.tnsfit.dragon.comlink.misc.registerIfRequired /** * Created by dragon on 11.10.16. * * */ class MatrixService: Service(), ImageEventListener, KillEventListener, DownloadEventListener { companion object { fun start(context: Context) { context.startService(Intent(context, MatrixService::class.java)) } } private val socketPool = SocketPool() private val mMatrix: MatrixConnection by lazy { MatrixConnection() } private val notificationManager: NotificationManagerCompat by lazy { NotificationManagerCompat.from(applicationContext) } private val notificationId = AppConstants.NOTIFICATION_ID_SERVICE_ALIVE private val eventBus = EventBus.getDefault() private val notificationActionReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { intent.action?.let { action -> if (action == ServiceNotification.NOTIFICATION_ACTION_DISMISS) { eventBus.post(KillEvent(MessagePacket.MATRIX)) [email protected]() [email protected]() } } } } override fun onCreate() { super.onCreate() //this.notificationManager.notify(notificationId, // ServiceNotification.buildNotificationServiceAlive(this.applicationContext).build()) this.registerReceiver(this.notificationActionReceiver, ServiceNotification.filter) this.mMatrix.startServer() this.eventBus.registerIfRequired(this) this.eventBus.registerIfRequired(mMatrix) } override fun onDestroy() { socketPool.stop() this.unregisterReceiver(this.notificationActionReceiver) this.eventBus.unregister(this.mMatrix) this.eventBus.unregister(this) this.mMatrix.stop() socketPool.closeAllSockets() this.notificationManager.cancel(AppConstants.NOTIFICATION_ID_SERVICE_ALIVE) // this.notificationManager.notify(notificationId, ServiceNotification.buildNotificationServiceNotAlive(this.applicationContext).build()) super.onDestroy() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForeground(notificationId, ServiceNotification.buildNotificationServiceAlive(this.applicationContext).build()) return START_NOT_STICKY } override fun onBind(intent: Intent): IBinder? = null @Subscribe override fun onKillEvent(event: KillEvent) { if (event.source == MessagePacket.COMLINK) stopForeground(false) } @Subscribe(threadMode = ThreadMode.BACKGROUND) override fun onDownloadEvent(event: DownloadEvent) { if (event.source == MessagePacket.COMLINK) { RetrieveAgent(socketPool, event, getExternalFilesDir(null)).start() } } @Subscribe(threadMode = ThreadMode.BACKGROUND) override fun onImageEvent(imageUri: ImageEvent) { if (imageUri.source == MessagePacket.COMLINK) { SendAgent(socketPool, contentResolver.openInputStream(imageUri.image)).start() } } }
gpl-3.0
ddbd240f641ea8007e35cc02b60dd4a2
31.029412
139
0.788185
4.013514
false
false
false
false
esofthead/mycollab
mycollab-dao/src/main/java/com/mycollab/db/persistence/service/DefaultCrudService.kt
3
4291
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.db.persistence.service import com.mycollab.core.MyCollabException import com.mycollab.core.cache.CacheKey import com.mycollab.core.utils.StringUtils import com.mycollab.db.persistence.ICrudGenericDAO import org.apache.commons.beanutils.PropertyUtils import java.io.Serializable import java.lang.reflect.Method import java.time.LocalDateTime import java.util.* /** * The generic class that serves the basic operations in data access layer: * Create, Retrieve, Update and Delete. * * @param <T> * @param <K> * @author MyCollab Ltd. * @since 1.0 </K></T> */ abstract class DefaultCrudService<K : Serializable, T> : ICrudService<K, T> { abstract val crudMapper: ICrudGenericDAO<K, T> private var cacheUpdateMethod: Method? = null override fun findByPrimaryKey(primaryKey: K, sAccountId: Int): T? = crudMapper.selectByPrimaryKey(primaryKey) override fun saveWithSession(record: T, username: String?): Int { if (!StringUtils.isBlank(username)) { try { PropertyUtils.setProperty(record, "createduser", username) } catch (e: Exception) { } } try { PropertyUtils.setProperty(record, "createdtime", LocalDateTime.now()) PropertyUtils.setProperty(record, "lastupdatedtime", LocalDateTime.now()) } catch (e: Exception) { } crudMapper.insertAndReturnKey(record) return try { PropertyUtils.getProperty(record, "id") as Int } catch (e: Exception) { 0 } } override fun updateWithSession(record: T, username: String?): Int { try { PropertyUtils.setProperty(record, "lastupdatedtime", LocalDateTime.now()) } catch (e: Exception) { } if (cacheUpdateMethod == null) { findCacheUpdateMethod() } try { cacheUpdateMethod!!.invoke(crudMapper, record) return 1 } catch (e: Exception) { throw MyCollabException(e) } } private fun findCacheUpdateMethod() { val crudMapper = crudMapper val crudMapperCls = crudMapper.javaClass for (method in crudMapperCls.methods) { if ("updateByPrimaryKeyWithBLOBs" == method.name) { cacheUpdateMethod = method return } else if ("updateByPrimaryKey" == method.name) { cacheUpdateMethod = method } } } override fun updateSelectiveWithSession(@CacheKey record: T, username: String?): Int? { try { PropertyUtils.setProperty(record, "lastupdatedtime", LocalDateTime.now()) } catch (e: Exception) { } return crudMapper.updateByPrimaryKeySelective(record) } override fun removeWithSession(item: T, username: String?, sAccountId: Int) { massRemoveWithSession(listOf(item), username, sAccountId) } override fun massRemoveWithSession(items: List<T>, username: String?, sAccountId: Int) { val primaryKeys = ArrayList<T>(items.size) items.forEach { try { val primaryKey = PropertyUtils.getProperty(it, "id") as T primaryKeys.add(primaryKey) } catch (e: Exception) { throw MyCollabException(e) } } crudMapper.removeKeysWithSession(primaryKeys) } override fun massUpdateWithSession(record: T, primaryKeys: List<K>, accountId: Int?) { crudMapper.massUpdateWithSession(record, primaryKeys) } }
agpl-3.0
b494fc4a2980b6fe8b484f16a3895d6f
32.255814
113
0.645688
4.515789
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/project/LuaModuleBuilder.kt
2
2079
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.project import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.util.Pair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import java.io.File /** * lua ModuleBuilder * Created by tangzx on 2016/12/24. */ class LuaModuleBuilder : ModuleBuilder() { override fun setupRootModel(rootModel: ModifiableRootModel) { rootModel.sdk = StdSDK.sdk val contentEntry = doAddContentEntry(rootModel) if (contentEntry != null) { val sourcePaths = getSourcePaths() for (sourcePath in sourcePaths) { val path = sourcePath.first File(path).mkdirs() val sourceRoot = LocalFileSystem.getInstance() .refreshAndFindFileByPath(FileUtil.toSystemIndependentName(path)) if (sourceRoot != null) { contentEntry.addSourceFolder(sourceRoot, false, sourcePath.second) } } } } override fun getModuleType() = LuaModuleType.instance private fun getSourcePaths(): List<Pair<String, String>> { val sourcePaths = mutableListOf<Pair<String, String>>() val path = contentEntryPath + File.separator + "src" File(path).mkdirs() sourcePaths.add(Pair.create(path, "")) return sourcePaths } }
apache-2.0
77dfe33df4960529b7b7dded1a6c4d65
33.65
89
0.67773
4.62
false
false
false
false
yichiuan/Moedict-Android
moedict-android/app/src/main/java/com/yichiuan/moedict/ui/main/HeteronymAdapter.kt
1
3061
package com.yichiuan.moedict.ui.main import android.arch.lifecycle.Lifecycle import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import com.yichiuan.moedict.BuildConfig import com.yichiuan.moedict.R import com.yichiuan.moedict.common.TextUtil import com.yichiuan.moedict.common.VoicePlayer import com.yichiuan.moedict.common.ui.StaticTextView import moe.Word class HeteronymAdapter(context: Context, private var word: Word?,lifecycle: Lifecycle) : RecyclerView.Adapter<HeteronymAdapter.HeteronymViewHolder>() { companion object { private const val VOICE_URL = BuildConfig.VOICE_BASE_URL + "%s.mp3" } private val inflater: LayoutInflater = LayoutInflater.from(context) internal var voicePlayer: VoicePlayer = VoicePlayer(context, lifecycle) fun setWord(word: Word) { this.word = word notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeteronymAdapter.HeteronymViewHolder { return HeteronymAdapter.HeteronymViewHolder( inflater.inflate(R.layout.item_heteronym, parent, false)) } override fun onBindViewHolder(holder: HeteronymViewHolder, position: Int) { holder.title.setText( TextUtil.obtainSpannedFrom(word!!.titleAsByteBuffer())) val heteronym = word!!.heteronyms(position) holder.playButton.setOnClickListener { v -> val button = v as Button val voiceId = heteronym.audioId() if (voicePlayer.isPlaying) { voicePlayer.stopVoice() button.text = "Play" } else { playVoice(voiceId) voicePlayer.setOnLoadedListener(object : VoicePlayer.OnLoadedListener { override fun onLoaded() { button.text = "Stop" } }) button.text = "Loading" } } val bopomofo = heteronym.bopomofo() holder.title.setPinyin(bopomofo!!) holder.recyclerView.adapter = DefinitionAdapter(holder.recyclerView.context, heteronym) } internal fun playVoice(voiceId: String?) { val url = String.format(VOICE_URL, voiceId) voicePlayer.playVoice(url) } override fun getItemCount(): Int { return word!!.heteronymsLength() } class HeteronymViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var title: StaticTextView = itemView.findViewById(R.id.staticview_title) var playButton: Button = itemView.findViewById(R.id.button_play) var recyclerView: RecyclerView = itemView.findViewById(R.id.recyclerview_definition) init { recyclerView.layoutManager = LinearLayoutManager(itemView.context, LinearLayoutManager.VERTICAL, false) } } }
apache-2.0
4f0dab9ba562e13f5ae793f7cd73c32e
33.011111
109
0.673636
4.329562
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/grammar/dumb/LazyLLParser.kt
1
10860
package org.jetbrains.grammar.dumb import com.intellij.psi.tree.IElementType import org.jetbrains.haskell.parser.HaskellTokenType import java.util.ArrayList import org.jetbrains.grammar.HaskellLexerTokens import java.util.HashMap import org.jetbrains.haskell.parser.CachedTokens import org.jetbrains.haskell.parser.newLexerState import org.jetbrains.haskell.parser.LexerState class ParserResult(val children: List<ResultTree>, val state: LexerState, val elementType: IElementType?) { fun size(): Int { var size = 0; for (child in children) { size += child.size() } return size; } } abstract class TreeCallback() { abstract fun done(tree: NonTerminalTree, lexerState: LexerState): ParserState; abstract fun fail(): ParserState; } abstract class ParserResultCallBack() { abstract fun done(result: ParserResult): ParserState; abstract fun fail(): ParserState; } class LazyLLParser(val grammar: Map<String, Rule>, val cached: CachedTokens) { var cache = ArrayList<HashMap<String, Pair<NonTerminalTree, LexerState>>>() var lastSeen = 0; var lastCurlyPosition = -1 var lastCurlyState: RecoveryCallback? = null; var recoveryState: ParserState? = null; public var writeLog: Boolean = false; fun parse(): NonTerminalTree? { val rule = grammar["module"]!! var state = parseRule(rule, newLexerState(cached), object : TreeCallback() { override fun done(tree: NonTerminalTree, lexerState: LexerState) = FinalState(tree) override fun fail(): ParserState = FinalState(null) }) while (true) { if (state is FinalState) { val result = state.result if (result == null && lastSeen <= lastCurlyPosition) { state = lastCurlyState!!.recover() lastCurlyPosition = -1 lastCurlyState = null } else { return result } } state = state.next() } } fun parseRule(rule: Rule, state: LexerState, next: TreeCallback): ParserState { //log({ "rule ${rule.name}, state = ${state.lexemNumber}" }) if (state.readedLexemNumber < cache.size()) { val pair = cache[state.readedLexemNumber][rule.name] if (pair != null) { return next.done(pair.first, pair.second) } } return parseVariants(state, rule.variants, listOf(), object : ParserResultCallBack() { override fun done(result: ParserResult): ParserState { val tree = NonTerminalTree(rule.name, result.elementType, result.children) return if (rule.left.isNotEmpty()) { parseLeft(rule, tree, result.state, next) } else { putToCache(state, rule.name, tree, result.state) next.done(tree, result.state) } } override fun fail(): ParserState = next.fail() }) } fun parseVariants(state: LexerState, variants: List<Variant>, children: List<ResultTree>, next: ParserResultCallBack): ParserState { if (variants.size() == 1) { return parseVariant(state, variants.first(), children, next) } else { var i = 0; val token = state.getToken() while (!variants[i].accepts(token)) { i++ if (i == variants.size()) { return next.fail() } } return ListCombineState(null, variants, i, state, children, next) } } inner class ListCombineState(val bestResult: ParserResult?, val variants: List<Variant>, val index: Int, val state: LexerState, val children: List<ResultTree>, val next: ParserResultCallBack) : ParserState() { override fun next(): ParserState { return if (index == variants.size()) { throw RuntimeException() } else if (index == variants.size() - 1) { parseVariant(state, variants[index], children, object : ParserResultCallBack() { override fun done(result: ParserResult): ParserState { val nextResult = if (bestResult == null || bestResult.size() < result.size()) { result } else { bestResult } return next.done(nextResult) } override fun fail(): ParserState = if (bestResult != null) next.done(bestResult) else next.fail() }); } else { parseVariant(state, variants[index], children, object : ParserResultCallBack() { override fun done(result: ParserResult): ParserState { val nextResult = if (bestResult == null || bestResult.size() < result.size()) { result } else { bestResult } var nextIndex = index + 1; val token = state.getToken() while (!variants[nextIndex].accepts(token)) { nextIndex++ if (nextIndex == variants.size()) { return next.done(nextResult) } } return ListCombineState(nextResult, variants, nextIndex, state, children, next) } override fun fail(): ParserState = ListCombineState(bestResult, variants, index + 1, state, children, next) }) } } } fun parseVariant(state: LexerState, variant: Variant, children: List<ResultTree>, next: ParserResultCallBack): ParserState { if (variant is TerminalVariant) { return next.done(ParserResult(children, state, variant.elementType)) } else { val nonTerminalVariant = variant as NonTerminalVariant val term = nonTerminalVariant.term when (term) { is Terminal -> { return if (state.match(term.tokenType)) { if (lastSeen < state.readedLexemNumber) { lastSeen = state.readedLexemNumber } val nextChildren = ArrayList(children) nextChildren.add(TerminalTree(term.tokenType)) parseVariants(state.next(), nonTerminalVariant.next, nextChildren, next) } else { if (term.tokenType == HaskellLexerTokens.VCCURLY) { if (state.readedLexemNumber > lastCurlyPosition) { lastCurlyPosition = state.readedLexemNumber lastCurlyState = RecoveryCallback(state, nonTerminalVariant, children, next) } } next.fail() } } is NonTerminal -> { val ruleToParse = grammar[term.rule]!! if (!ruleToParse.first!!.contains(state.getToken()) && !ruleToParse.first!!.contains(HaskellLexerTokens.VCCURLY)) { if (ruleToParse.canBeEmpty) { val nextChildren = ArrayList(children) nextChildren.add(NonTerminalTree(ruleToParse.name, null, listOf())) return parseVariants(state, variant.next, nextChildren, next) } else { return next.fail() } } else { return parseRule(ruleToParse, state, NextVariantStateProducer(children, variant, next)) } } else -> { throw RuntimeException() } } } } fun parseLeft(rule: Rule, leftTree: NonTerminalTree, state: LexerState, next: TreeCallback): ParserState { return parseVariants(state, (rule.left.first() as NonTerminalVariant).next, listOf(leftTree), object : ParserResultCallBack() { override fun done(result: ParserResult): ParserState { val tree = NonTerminalTree(rule.name, result.elementType, result.children) return parseLeft(rule, tree, result.state, next) } override fun fail(): ParserState { return next.done(leftTree, state) } }) } fun log(text: () -> String) { if (writeLog) { println(text()) } } inner class RecoveryCallback(val state: LexerState, val variant: NonTerminalVariant, val children: List<ResultTree>, val next: ParserResultCallBack) { fun recover(): ParserState { val lexerState = state.dropIndent().next() val nextChildren = ArrayList(children) nextChildren.add(TerminalTree(HaskellLexerTokens.VCCURLY)) return parseVariants(lexerState, variant.next, nextChildren, next) } } inner class NextVariantStateProducer(val children: List<ResultTree>, val variant: NonTerminalVariant, val next: ParserResultCallBack) : TreeCallback() { override fun fail(): ParserState = next.fail(); override fun done(tree: NonTerminalTree, lexerState: LexerState): ParserState { val children = ArrayList(children) children.add(tree) return parseVariants(lexerState, variant.next, children, next) } } fun putToCache(start: LexerState, ruleName: String, tree: NonTerminalTree, end: LexerState) { val lexemNumber = start.readedLexemNumber while (lexemNumber >= cache.size()) { cache.add(HashMap()) } val hashMap = cache[lexemNumber] hashMap[ruleName] = Pair(tree, end) } }
apache-2.0
69df8edf7713b7c86bb75d55d2260640
38.638686
135
0.511786
5.339233
false
false
false
false
y2k/JoyReactor
android/src/main/kotlin/y2k/joyreactor/common/ViewExtensions.kt
1
1993
package y2k.joyreactor.common import android.content.res.TypedArray import android.support.v4.view.ViewCompat import android.support.v4.view.ViewPropertyAnimatorCompat import android.view.View import android.view.ViewGroup /** * Created by y2k on 2/6/16. */ fun ViewGroup.replaceViews(views: List<View>) { removeAllViews() views.forEach { addView(it) } } fun View.setVisible(visible: Boolean) { visibility = if (visible) View.VISIBLE else View.GONE } inline fun View.setOnClick(id: Int, crossinline onClick: () -> Unit) { findViewById(id).setOnClickListener { onClick() } } fun TypedArray.use(f: TypedArray.() -> Unit) { try { f() } finally { recycle() } } fun View.compatAnimate(): ViewPropertyAnimatorCompat { return ViewCompat.animate(this) } var View.compatScaleY: Float get() = ViewCompat.getScaleY(this) set(value) = ViewCompat.setScaleY(this, value) fun ViewGroup.switchByScaleFromTo(firstPosition: Int, secondPosition: Int) { val first = getChildAt(firstPosition) val second = getChildAt(secondPosition) first.compatAnimate() .scaleY(0f) .withEndAction { first.isVisible = false second.isVisible = true second.compatScaleY = 0f second.compatAnimate().scaleY(1f) } } @Suppress("UNCHECKED_CAST") inline fun <T> View.find(id: Int): T { return findViewById(id) as T } @Suppress("UNCHECKED_CAST") fun <T> View.findOrNull(id: Int): T? { return findViewById(id) as T? } fun ViewGroup.getChildren(): List<View> { return (0..childCount - 1).map { getChildAt(it) } } fun View.updateMargin(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) { val lp = layoutParams as ViewGroup.MarginLayoutParams if (left != null) lp.leftMargin = left if (top != null) lp.topMargin = top if (right != null) lp.rightMargin = right if (bottom != null) lp.bottomMargin = bottom layoutParams = lp }
gpl-2.0
16f50f3956b6f8b0017a569723a77f0a
25.236842
101
0.672855
3.64351
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt
3
6366
package info.nightscout.androidaps.dialogs import android.app.Activity import android.os.Bundle import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager import androidx.fragment.app.DialogFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.BolusProgressHelperActivity import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.utils.FabricPrivacy import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.dialog_bolusprogress.* import org.slf4j.LoggerFactory class BolusProgressDialog : DialogFragment() { private val log = LoggerFactory.getLogger(L.UI) private val disposable = CompositeDisposable() companion object { private val DEFAULT_STATE = MainApp.gs(R.string.waitingforpump) @JvmField var bolusEnded = false @JvmField var stopPressed = false } private var running = true private var amount = 0.0 private var state: String? = null private var helpActivity: BolusProgressHelperActivity? = null fun setInsulin(amount: Double): BolusProgressDialog { this.amount = amount bolusEnded = false return this } fun setHelperActivity(activity: BolusProgressHelperActivity): BolusProgressDialog { helpActivity = activity return this } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) isCancelable = false dialog?.setCanceledOnTouchOutside(false) return inflater.inflate(R.layout.dialog_bolusprogress, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { savedInstanceState?.let { amount = it.getDouble("amount") } overview_bolusprogress_title.text = String.format(MainApp.gs(R.string.overview_bolusprogress_goingtodeliver), amount) overview_bolusprogress_stop.setOnClickListener { if (L.isEnabled(L.UI)) log.debug("Stop bolus delivery button pressed") stopPressed = true overview_bolusprogress_stoppressed.visibility = View.VISIBLE overview_bolusprogress_stop.visibility = View.INVISIBLE ConfigBuilderPlugin.getPlugin().commandQueue.cancelAllBoluses() } overview_bolusprogress_progressbar.max = 100 state = savedInstanceState?.getString("state", DEFAULT_STATE) ?: DEFAULT_STATE overview_bolusprogress_status.text = state stopPressed = false } override fun onStart() { super.onStart() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } override fun onResume() { super.onResume() if (L.isEnabled(L.UI)) log.debug("onResume") if (!ConfigBuilderPlugin.getPlugin().commandQueue.bolusInQueue()) bolusEnded = true if (bolusEnded) dismiss() else running = true disposable.add(toObservable(EventPumpStatusChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ overview_bolusprogress_status.text = it.getStatus() }) { FabricPrivacy.logException(it) } ) disposable.add(toObservable(EventDismissBolusProgressIfRunning::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (running) dismiss() }) { FabricPrivacy.logException(it) } ) disposable.add(toObservable(EventOverviewBolusProgress::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (L.isEnabled(L.UI)) log.debug("Status: " + it.status + " Percent: " + it.percent) overview_bolusprogress_status.text = it.status overview_bolusprogress_progressbar.progress = it.percent if (it.percent == 100) { overview_bolusprogress_stop.visibility = View.INVISIBLE scheduleDismiss() } state = it.status }) { FabricPrivacy.logException(it) } ) } override fun dismiss() { if (L.isEnabled(L.UI)) log.debug("dismiss") try { super.dismiss() } catch (e: IllegalStateException) { // dialog not running yet. onResume will try again. Set bolusEnded to make extra // sure onResume will catch this bolusEnded = true log.error("Unhandled exception", e) } helpActivity?.finish() } override fun onPause() { super.onPause() if (L.isEnabled(L.UI)) log.debug("onPause") running = false disposable.clear() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("state", state) outState.putDouble("amount", amount) } private fun scheduleDismiss() { if (L.isEnabled(L.UI)) log.debug("scheduleDismiss") Thread(Runnable { SystemClock.sleep(5000) bolusEnded = true val activity: Activity? = activity activity?.runOnUiThread { if (running) { if (L.isEnabled(L.UI)) log.debug("executing") try { dismiss() } catch (e: Exception) { log.error("Unhandled exception", e) } } } }).start() } }
agpl-3.0
049f0d77109e44c8f2acaa2ab398978e
37.581818
125
0.660069
4.919629
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/LocationAwareMapFragment.kt
1
11295
package de.westnordost.streetcomplete.map import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.graphics.PointF import android.hardware.SensorManager import android.location.Location import android.location.LocationManager import android.view.WindowManager import android.view.animation.DecelerateInterpolator import androidx.core.content.edit import androidx.core.content.getSystemService import com.mapzen.tangram.MapController import de.westnordost.osmapi.map.data.LatLon import de.westnordost.osmapi.map.data.OsmLatLon import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.getBitmapDrawable import de.westnordost.streetcomplete.ktx.toDp import de.westnordost.streetcomplete.location.FineLocationManager import de.westnordost.streetcomplete.map.tangram.Marker import de.westnordost.streetcomplete.util.EARTH_CIRCUMFERENCE import kotlin.math.PI import kotlin.math.cos import kotlin.math.pow /** Manages a map that shows the device's GPS location and orientation as markers on the map with * the option to let the screen follow the location and rotation */ open class LocationAwareMapFragment : MapFragment() { private lateinit var compass: Compass private lateinit var locationManager: FineLocationManager // markers showing the user's location, direction and accuracy of location protected var locationMarker: Marker? = null private set protected var accuracyMarker: Marker? = null private set protected var directionMarker: Marker? = null private set /** The location of the GPS location dot on the map. Null if none (yet) */ var displayedLocation: Location? = null private set /** Whether the view rotation is displayed on the map. False if the device orientation is unknown (yet) */ var isShowingDirection = false private set private var directionMarkerSize: PointF? = null private val displayedPosition: LatLon? get() = displayedLocation?.let { OsmLatLon(it.latitude, it.longitude) } /** Whether the view should automatically center on the GPS location */ var isFollowingPosition = false set(value) { field = value centerCurrentPositionIfFollowing() } /** When the view follows the GPS position, whether the view already zoomed to the location once*/ private var zoomedYet = false /** Whether the view should automatically rotate with the compass (like during navigation) */ // Since the with-compass rotation happens with no animation, it's better to start the tilt // animation abruptly and slide out, rather than sliding in and out (the default interpolator) private val interpolator = DecelerateInterpolator() var isCompassMode: Boolean = false set(value) { if (field != value) { field = value controller?.updateCameraPosition(300, interpolator) { tilt = if (value) PI.toFloat() / 5f else 0f } } } private var viewDirection: Float? = null interface Listener { /** Called after the map fragment updated its displayed location */ fun onLocationDidChange() } private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener /* ------------------------------------ Lifecycle ------------------------------------------- */ override fun onAttach(context: Context) { super.onAttach(context) compass = Compass(context.getSystemService<SensorManager>()!!, context.getSystemService<WindowManager>()!!.defaultDisplay, this::onCompassRotationChanged ) locationManager = FineLocationManager(context.getSystemService<LocationManager>()!!, this::onLocationChanged) } override fun onResume() { super.onResume() compass.onResume() } override fun onPause() { super.onPause() compass.onPause() saveMapState() } override fun onStop() { super.onStop() stopPositionTracking() } override fun onDestroy() { super.onDestroy() compass.onDestroy() controller = null locationMarker = null directionMarker = null accuracyMarker = null } /* ---------------------------------- Map State Callbacks ----------------------------------- */ override fun onMapReady() { super.onMapReady() restoreMapState() initMarkers() centerCurrentPositionIfFollowing() showLocation() } override fun onMapIsChanging(position: LatLon, rotation: Float, tilt: Float, zoom: Float) { super.onMapIsChanging(position, rotation, tilt, zoom) updateAccuracy() } /* ---------------------------------------- Markers ----------------------------------------- */ private fun initMarkers() { locationMarker = createLocationMarker() directionMarker = createDirectionMarker() accuracyMarker = createAccuracyMarker() } private fun createLocationMarker(): Marker? { val ctx = context ?: return null val dot = ctx.resources.getBitmapDrawable(R.drawable.location_dot) val dotWidth = dot.intrinsicWidth.toFloat().toDp(ctx) val dotHeight = dot.intrinsicHeight.toFloat().toDp(ctx) val marker = controller?.addMarker() ?: return null marker.setStylingFromString( "{ style: 'points', color: 'white', size: [${dotWidth}px, ${dotHeight}px], order: 2000, flat: true, collide: false, interactive: true }" ) marker.setDrawable(dot) marker.setDrawOrder(9) return marker } private fun createDirectionMarker(): Marker? { val ctx = context ?: return null val directionImg = ctx.resources.getBitmapDrawable(R.drawable.location_direction) directionMarkerSize = PointF( directionImg.intrinsicWidth.toFloat().toDp(ctx), directionImg.intrinsicHeight.toFloat().toDp(ctx) ) val marker = controller?.addMarker() ?: return null marker.setDrawable(directionImg) marker.setDrawOrder(2) return marker } private fun createAccuracyMarker(): Marker? { val ctx = context ?: return null val accuracyImg = ctx.resources.getBitmapDrawable(R.drawable.accuracy_circle) val marker = controller?.addMarker() ?: return null marker.setDrawable(accuracyImg) marker.setDrawOrder(1) return marker } private fun showLocation() { val pos = displayedPosition ?: return accuracyMarker?.isVisible = true accuracyMarker?.setPointEased(pos, 1000, MapController.EaseType.CUBIC) locationMarker?.isVisible = true locationMarker?.setPointEased(pos, 1000, MapController.EaseType.CUBIC) directionMarker?.isVisible = isShowingDirection directionMarker?.setPointEased(pos, 1000, MapController.EaseType.CUBIC) updateAccuracy() } private fun updateAccuracy() { val location = displayedLocation ?: return if (accuracyMarker?.isVisible != true) return val zoom = controller!!.cameraPosition.zoom val size = location.accuracy * pixelsPerMeter(location.latitude, zoom) accuracyMarker?.setStylingFromString( "{ style: 'points', color: 'white', size: ${size}px, order: 2000, flat: true, collide: false }" ) } private fun pixelsPerMeter(latitude: Double, zoom: Float): Double { val numberOfTiles = (2.0).pow(zoom.toDouble()) val metersPerTile = cos(latitude * PI / 180.0) * EARTH_CIRCUMFERENCE / numberOfTiles return 256 / metersPerTile } /* --------------------------------- Position tracking -------------------------------------- */ @SuppressLint("MissingPermission") fun startPositionTracking() { zoomedYet = false displayedLocation = null locationManager.requestUpdates(2000, 5f) } fun stopPositionTracking() { locationMarker?.isVisible = false accuracyMarker?.isVisible = false directionMarker?.isVisible = false displayedLocation = null zoomedYet = false locationManager.removeUpdates() } protected open fun shouldCenterCurrentPosition(): Boolean { return isFollowingPosition } fun centerCurrentPosition() { val controller = controller ?: return val targetPosition = displayedPosition ?: return controller.updateCameraPosition(600) { position = targetPosition if (!zoomedYet) { zoomedYet = true zoom = 19f } } } protected fun centerCurrentPositionIfFollowing() { if (shouldCenterCurrentPosition()) centerCurrentPosition() } private fun onLocationChanged(location: Location) { displayedLocation = location compass.setLocation(location) showLocation() centerCurrentPositionIfFollowing() listener?.onLocationDidChange() } /* --------------------------------- Rotation tracking -------------------------------------- */ private fun onCompassRotationChanged(rot: Float, tilt: Float) { // we received an event from the compass, so compass is working - direction can be displayed on screen isShowingDirection = true if (displayedLocation != null) { directionMarker?.let { if (!it.isVisible) it.isVisible = true val angle = rot * 180 / PI val size = directionMarkerSize if (size != null) { it.setStylingFromString( "{ style: 'points', color: '#cc536dfe', size: [${size.x}px, ${size.y}px], order: 2000, collide: false, flat: true, angle: $angle}" ) } } } if (isCompassMode) { viewDirection = if (viewDirection == null) -rot else smoothenAngle(-rot, viewDirection ?: 0f, 0.05f) controller?.updateCameraPosition { rotation = viewDirection } } } private fun smoothenAngle( newValue: Float, oldValue: Float, factor: Float): Float { var delta = newValue - oldValue while (delta > +PI) delta -= 2 * PI.toFloat() while (delta < -PI) delta += 2 * PI.toFloat() return oldValue + factor * delta } /* -------------------------------- Save and Restore State ---------------------------------- */ private fun restoreMapState() { val prefs = activity?.getPreferences(Activity.MODE_PRIVATE) ?: return isFollowingPosition = prefs.getBoolean(PREF_FOLLOWING, true) isCompassMode = prefs.getBoolean(PREF_COMPASS_MODE, false) } private fun saveMapState() { activity?.getPreferences(Activity.MODE_PRIVATE)?.edit { putBoolean(PREF_FOLLOWING, isFollowingPosition) putBoolean(PREF_COMPASS_MODE, isCompassMode) } } companion object { const val PREF_FOLLOWING = "map_following" const val PREF_COMPASS_MODE = "map_compass_mode" } }
gpl-3.0
6fa5a89eab586966a9c971c6f4803422
34.630915
154
0.629659
5.062752
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/execution/ui/TextConsoleView.kt
1
12942
/* * Copyright (C) 2019-2021 Reece H. Dunn * Copyright 2000-2020 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 uk.co.reecedunn.intellij.plugin.core.execution.ui import com.intellij.execution.filters.FileHyperlinkInfo import com.intellij.execution.filters.HyperlinkInfo import com.intellij.execution.impl.ConsoleViewUtil import com.intellij.execution.impl.EditorHyperlinkSupport import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionManagerEx import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.editor.actions.ScrollToTheEndToolbarAction import com.intellij.openapi.editor.actions.ToggleUseSoftWrapsToolbarAction import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.MarkupModelEx import com.intellij.openapi.editor.ex.RangeHighlighterEx import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.components.panels.Wrapper import com.intellij.util.Alarm import com.intellij.util.SystemProperties import com.intellij.util.ui.UIUtil import uk.co.reecedunn.intellij.plugin.core.execution.ui.impl.ConsoleViewToken import uk.co.reecedunn.intellij.plugin.core.execution.ui.impl.ConsoleViewTokenBuffer import uk.co.reecedunn.intellij.plugin.core.ui.Borders import java.awt.BorderLayout import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JComponent import javax.swing.border.Border import kotlin.math.min // The IntelliJ ConsoleViewImpl should be used when the following issues are fixed: // 1. IDEA-256363 : Support custom TokenBuffer sizes for ConsoleViewImpl instances. // 2. IDEA-256612 : ConsoleViewImpl overrides syntax highlighting on the output text. open class TextConsoleView(val project: Project) : ConsoleViewImpl(), ConsoleViewEx { companion object { private val CONTENT_TYPE = Key.create<ConsoleViewContentType>("ConsoleViewContentType") private val FLUSH_DELAY = SystemProperties.getIntProperty("console.flush.delay.ms", 200).toLong() private const val FLUSH_IMMEDIATELY = 0.toLong() } init { @Suppress("LeakingThis") ApplicationManager.getApplication().messageBus.connect(this).subscribe( EditorColorsManager.TOPIC, EditorColorsListener { ApplicationManager.getApplication().assertIsDispatchThread() if (project.isDisposed || editor == null) return@EditorColorsListener val model = DocumentMarkupModel.forDocument(editor!!.document, project, false) model.allHighlighters.asSequence().filterIsInstance<RangeHighlighterEx>().forEach { tokenMarker -> val contentType = tokenMarker.getUserData(CONTENT_TYPE) if (contentType != null && contentType.attributesKey == null) { tokenMarker.setTextAttributes(contentType.attributes) } } } ) } var editor: EditorEx? = null private set private var hyperlinks: EditorHyperlinkSupport? = null private var emulateCarriageReturn: Boolean = false set(value) { field = value (editor?.document as? DocumentImpl)?.setAcceptSlashR(value) } @Suppress("LeakingThis") private val alarm = Alarm(this) private val lock = Any() private val tokens = ConsoleViewTokenBuffer() private fun createConsoleEditor(): JComponent { if (editor != null) return editor!!.component editor = ConsoleViewUtil.setupConsoleEditor(project, true, false) editor?.contextMenuGroupId = null // disabling default context menu (editor?.document as? DocumentImpl)?.setAcceptSlashR(emulateCarriageReturn) hyperlinks = EditorHyperlinkSupport(editor!!, project) return editor!!.component } private fun flushDeferredText() { lateinit var deferred: Array<ConsoleViewToken> synchronized(lock) { if (tokens.isEmpty()) return try { deferred = tokens.toTypedArray() } finally { tokens.clear() } } val document = editor!!.document var startLength = document.textLength document.insertString(startLength, deferred.joinToString("") { it.text }) var contentTypeStart = startLength var previousContentType: ConsoleViewContentType? = null deferred.forEach { val endLength = startLength + it.text.length when { it.contentType == null || previousContentType === it.contentType -> { } previousContentType == null -> { previousContentType = it.contentType } else -> { createTokenRangeHighlighter(previousContentType!!, contentTypeStart, startLength) contentTypeStart = startLength previousContentType = it.contentType } } if (it.hyperlinkInfo != null) { hyperlinks!!.createHyperlink(startLength, endLength, null, it.hyperlinkInfo) } startLength = endLength } if (previousContentType != null) { createTokenRangeHighlighter(previousContentType!!, contentTypeStart, document.textLength) } } private fun createTokenRangeHighlighter(contentType: ConsoleViewContentType, startOffset: Int, endOffset: Int) { ApplicationManager.getApplication().assertIsDispatchThread() val model = DocumentMarkupModel.forDocument(editor!!.document, project, true) as MarkupModelEx val layer = HighlighterLayer.SYNTAX - 1 model.addRangeHighlighterAndChangeAttributes( contentType.attributesKey, startOffset, endOffset, layer, HighlighterTargetArea.EXACT_RANGE, false ) { ex: RangeHighlighterEx -> if (ex.textAttributesKey == null) { ex.setTextAttributes(contentType.attributes) } ex.putUserData(CONTENT_TYPE, contentType) } } private val flush = object : Runnable { private val requested = AtomicBoolean() fun queue(delay: Long) { if (alarm.isDisposed) return if (delay == FLUSH_IMMEDIATELY || requested.compareAndSet(false, true)) { alarm.addRequest(this, delay, null) } } override fun run() { requested.set(false) flushDeferredText() } } // region ConsoleViewEx override val offset: Int get() = editor!!.caretModel.offset override fun scrollToTop(offset: Int) { ApplicationManager.getApplication().invokeLater { flush.queue(FLUSH_IMMEDIATELY) val moveOffset = min(offset, contentSize) val scrolling = editor!!.scrollingModel val caret = editor!!.caretModel caret.moveToOffset(moveOffset) scrolling.scrollVertically(editor!!.visualPositionToXY(caret.visualPosition).y) } } override fun setConsoleBorder(border: Border) { editor?.setBorder(border) } override fun createActionToolbar(place: String) { val actions = DefaultActionGroup() actions.addAll(*createConsoleActions()) val toolbar = ActionManagerEx.getInstanceEx().createActionToolbar(place, actions, false) toolbar.setTargetComponent(this) // Setting a border on the toolbar removes the standard padding/spacing, // so set the border on a panel that wraps the toolbar element. val wrapper = Wrapper() wrapper.add(toolbar.component) wrapper.border = Borders.ConsoleToolbarRight add(wrapper, BorderLayout.LINE_START) } override fun setConsoleText(text: String) { val newText = StringUtil.convertLineSeparators(text, emulateCarriageReturn) editor!!.document.setText(newText) synchronized(lock) { tokens.clear() } } // endregion // region ConsoleView override fun hasDeferredOutput(): Boolean = synchronized(lock) { return tokens.isNotEmpty() } override fun performWhenNoDeferredOutput(runnable: Runnable) { flushDeferredText() runnable.run() } override fun clear() { editor!!.document.setText("") synchronized(lock) { tokens.clear() } } override fun print(text: String, contentType: ConsoleViewContentType) { val newText = StringUtil.convertLineSeparators(text, emulateCarriageReturn) synchronized(lock) { tokens.add(ConsoleViewToken(newText, contentType)) } flush.queue(FLUSH_DELAY) } override fun printHyperlink(hyperlinkText: String, info: HyperlinkInfo?) { val newText = StringUtil.convertLineSeparators(hyperlinkText, emulateCarriageReturn) synchronized(lock) { tokens.add(ConsoleViewToken(newText, info)) } flush.queue(FLUSH_DELAY) } override fun getContentSize(): Int { val document = editor?.document ?: return 0 return document.textLength + synchronized(lock) { tokens.length } } override fun createConsoleActions(): Array<AnAction> { val actions = arrayOf( object : ToggleUseSoftWrapsToolbarAction(SoftWrapAppliancePlaces.CONSOLE) { override fun getEditor(e: AnActionEvent): Editor? = editor }, ScrollToTheEndToolbarAction(editor!!), ActionManager.getInstance().getAction("Print"), ClearAllAction(this) ) val additional = createAdditionalConsoleActions() if (additional.isNotEmpty()) { val primary = DefaultActionGroup() primary.addAll(*actions) val secondary = DefaultActionGroup() secondary.addAll(*additional) return arrayOf(primary, Separator(), secondary) } return actions } open fun createAdditionalConsoleActions(): Array<AnAction> = arrayOf() override fun getComponent(): JComponent { if (editor == null) { add(createConsoleEditor(), BorderLayout.CENTER) } return this } override fun scrollTo(offset: Int) { ApplicationManager.getApplication().invokeLater { flush.queue(FLUSH_IMMEDIATELY) val moveOffset = min(offset, contentSize) editor!!.caretModel.moveToOffset(moveOffset) editor!!.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) } } override fun dispose() { hyperlinks = null if (editor != null) { UIUtil.invokeAndWaitIfNeeded(Runnable { if (!editor!!.isDisposed) { EditorFactory.getInstance().releaseEditor(editor!!) } }) synchronized(lock) { tokens.clear() } editor = null } } // endregion // region DataProvider override fun getData(dataId: String): Any? = when (dataId) { CommonDataKeys.EDITOR.name -> editor CommonDataKeys.NAVIGATABLE.name -> { val pos = editor!!.caretModel.logicalPosition val info = hyperlinks!!.getHyperlinkInfoByLineAndCol(pos.line, pos.column) val openFileDescriptor = (info as? FileHyperlinkInfo)?.descriptor if (openFileDescriptor?.file?.isValid == true) openFileDescriptor else null } else -> super.getData(dataId) } // endregion }
apache-2.0
6ce32443c4b2bdf7f63910b8216be5a1
35.871795
116
0.664349
5.095276
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/tasks/RewardViewHolder.kt
1
4376
package com.habitrpg.android.habitica.ui.viewHolders.tasks import android.view.MotionEvent import android.view.View import androidx.core.content.ContextCompat import androidx.core.graphics.ColorUtils import androidx.core.graphics.drawable.toDrawable import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.RewardItemCardBinding import com.habitrpg.android.habitica.helpers.GroupPlanInfoProvider import com.habitrpg.android.habitica.models.tasks.Task import com.habitrpg.android.habitica.ui.ItemDetailDialog import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.common.habitica.helpers.NumberAbbreviator import com.habitrpg.shared.habitica.models.responses.TaskDirection class RewardViewHolder( itemView: View, scoreTaskFunc: ((Task, TaskDirection) -> Unit), openTaskFunc: ((Pair<Task, View>) -> Unit), brokenTaskFunc: ((Task) -> Unit), assignedTextProvider: GroupPlanInfoProvider? ) : BaseTaskViewHolder( itemView, scoreTaskFunc, openTaskFunc, brokenTaskFunc, assignedTextProvider ) { private val binding = RewardItemCardBinding.bind(itemView) private val isItem: Boolean get() = this.task?.specialTag == "item" init { binding.buyButton.setOnClickListener { buyReward() } binding.goldIcon.setImageBitmap(HabiticaIconsHelper.imageOfGold()) } override fun canContainMarkdown(): Boolean { return !isItem } private fun buyReward() { task?.let { scoreTaskFunc(it, TaskDirection.DOWN) } } override fun onTouch(view: View?, motionEvent: MotionEvent?): Boolean { if (task?.isValid != true) { return true } if (isItem) { val dialog = ItemDetailDialog(context) dialog.setTitle(task?.text) dialog.setDescription(task?.notes ?: "") dialog.setImage("shop_" + this.task?.id) dialog.setCurrency("gold") dialog.setValue(task?.value) dialog.setBuyListener { _, _ -> this.buyReward() } dialog.show() } else { super.onTouch(view, motionEvent) } return true } override fun setDisabled(openTaskDisabled: Boolean, taskActionsDisabled: Boolean) { super.setDisabled(openTaskDisabled, taskActionsDisabled) binding.buyButton.isEnabled = !taskActionsDisabled } fun bind(reward: Task, position: Int, canBuy: Boolean, displayMode: String, ownerID: String?) { this.task = reward streakTextView.visibility = View.GONE super.bind(reward, position, displayMode, ownerID) binding.priceLabel.text = NumberAbbreviator.abbreviate(itemView.context, this.task?.value ?: 0.0) if (isLocked) { binding.priceLabel.setCompoundDrawablesWithIntrinsicBounds( HabiticaIconsHelper.imageOfLocked( ContextCompat.getColor(context, R.color.gray_1_30), 10, 12 ).toDrawable(context.resources), null, null, null ) binding.priceLabel.compoundDrawablePadding = 2.dpToPx(context) } else { binding.priceLabel.setCompoundDrawables(null, null, null, null) } if (canBuy && !isLocked) { binding.goldIcon.alpha = 1.0f binding.priceLabel.setTextColor( ContextCompat.getColor( context, R.color.reward_buy_button_text ) ) binding.buyButton.setBackgroundColor( ContextCompat.getColor( context, R.color.reward_buy_button_bg ) ) } else { binding.goldIcon.alpha = 0.6f binding.priceLabel.setTextColor(ContextCompat.getColor(context, R.color.text_quad)) binding.buyButton.setBackgroundColor( ColorUtils.setAlphaComponent( ContextCompat.getColor( context, R.color.offset_background ), 127 ) ) } } }
gpl-3.0
eec264286480485d8c09125c0aa68c9d
34.773109
99
0.613574
4.766885
false
false
false
false
robfletcher/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/spek/api.kt
6
1343
/* * Copyright 2017 Netflix, 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.netflix.spinnaker.spek import org.jetbrains.spek.api.dsl.Pending import org.jetbrains.spek.api.dsl.SpecBody /** * Creates a [group][SpecBody.group]. */ fun SpecBody.and(description: String, body: SpecBody.() -> Unit) { group("and $description", body = body) } fun SpecBody.xand(description: String, reason: String? = null, body: SpecBody.() -> Unit) { group("and $description", Pending.Yes(reason), body = body) } /** * Creates a [group][SpecBody.group]. */ fun SpecBody.but(description: String, body: SpecBody.() -> Unit) { group("but $description", body = body) } fun SpecBody.but(description: String, reason: String? = null, body: SpecBody.() -> Unit) { group("but $description", Pending.Yes(reason), body = body) }
apache-2.0
639f6ff83356c152559471bc390ac89c
30.97619
91
0.709605
3.581333
false
false
false
false
universal-ctags/ctags
Units/parser-kotlin.r/kotlin-strings.d/input.kt
2
192
var used1 = "var unused1 = 1" var used2 = "\"var\" unused2 = 2" var used3 = "" var used4 = "${process("var unused4 = 4")}" // quote in character literal must not break parser var used5 = '\"'
gpl-2.0
35e46d3aa27f1ef224ff3c5d8da0fa7a
31
51
0.630208
3.147541
false
false
false
false
PEXPlugins/PermissionsEx
platform/sponge7/src/main/kotlin/ca/stellardrift/permissionsex/sponge/PEXSubjectData.kt
1
6436
/* * PermissionsEx * Copyright (C) zml and PermissionsEx contributors * * 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 ca.stellardrift.permissionsex.sponge import ca.stellardrift.permissionsex.subject.ImmutableSubjectData import ca.stellardrift.permissionsex.subject.Segment import ca.stellardrift.permissionsex.subject.SubjectRef import ca.stellardrift.permissionsex.util.Change import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap import java.util.function.Consumer import org.spongepowered.api.service.context.Context import org.spongepowered.api.service.permission.SubjectData import org.spongepowered.api.service.permission.SubjectReference import org.spongepowered.api.util.Tristate /** * Wrapper around ImmutableSubjectData that writes to backend each change */ class PEXSubjectData(private val data: SubjectRef.ToData<*>, private val plugin: PermissionsExPlugin) : SubjectData { private val parentsCache: ConcurrentMap<ContextSet, List<SubjectReference>> = ConcurrentHashMap() init { data.onUpdate { clearCache() } } /** * Provide a boolean representation of success for the Sponge returns. * * @return Whether or not the old data object is different from the new data object */ private fun CompletableFuture<Change<ImmutableSubjectData?>>.boolSuccess(): CompletableFuture<Boolean> { return thenApply { it.old() != it.current() } } private fun clearCache() { synchronized(parentsCache) { parentsCache.clear() } } override fun getAllOptions(): Map<Set<Context>, Map<String, String>> { return data.get().mapSegmentValues(Segment::options).keysToSponge() } override fun getOptions(contexts: Set<Context>): Map<String, String> { return data.get().segment(contexts.toPex(plugin.manager)).options() } override fun setOption(contexts: Set<Context>, key: String, value: String?): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.withOption(key, value) }.boolSuccess() } override fun clearOptions(contexts: Set<Context>): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.withoutOptions() }.boolSuccess() } override fun clearOptions(): CompletableFuture<Boolean> { return data.update { it.withSegments { _, s -> s.withoutOptions() } }.boolSuccess() } override fun getAllPermissions(): Map<Set<Context>, Map<String, Boolean>> { return data.get().mapSegmentValues { it.permissions().mapValues { (_, v) -> v > 0 } }.keysToSponge() } override fun getPermissions(contexts: Set<Context>): Map<String, Boolean> { return data.get().segment(contexts.toPex(plugin.manager)).permissions() .mapValues { (_, v) -> v > 0 } } override fun setPermission(contexts: Set<Context>, permission: String, state: Tristate): CompletableFuture<Boolean> { val value = when (state) { Tristate.TRUE -> 1 Tristate.FALSE -> -1 Tristate.UNDEFINED -> 0 else -> throw IllegalStateException("Unknown tristate provided $state") } return data.update(contexts.toPex(plugin.manager)) { it.withPermission(permission, value) }.thenApply { true } } override fun clearPermissions(): CompletableFuture<Boolean> { return data.update { it.withSegments { _, s -> s.withoutPermissions() } }.boolSuccess() } override fun clearPermissions(contexts: Set<Context>): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.withoutPermissions() }.boolSuccess() } override fun getAllParents(): Map<Set<Context>, List<SubjectReference>> { synchronized(parentsCache) { data.get().activeContexts().forEach(Consumer { getParentsInternal(it) }) return parentsCache.keysToSponge() } } override fun getParents(contexts: Set<Context>): List<SubjectReference> { return getParentsInternal(contexts.toPex(plugin.manager)) } private fun getParentsInternal(contexts: ContextSet): List<SubjectReference> { val existing = parentsCache[contexts] if (existing != null) { return existing } val parents: List<SubjectReference> synchronized(parentsCache) { val rawParents = data.get().segment(contexts).parents() parents = if (rawParents.isEmpty()) { emptyList() } else { rawParents.map { PEXSubjectReference.of(it, plugin) } } val existingParents = parentsCache.putIfAbsent(contexts, parents) if (existingParents != null) { return existingParents } } return parents } override fun addParent(contexts: Set<Context>, subject: SubjectReference): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.plusParent(PEXSubjectReference.of(subject, plugin)) }.boolSuccess() } override fun removeParent(contexts: Set<Context>, subject: SubjectReference): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.minusParent(PEXSubjectReference.of(subject, plugin)) }.boolSuccess() } override fun clearParents(): CompletableFuture<Boolean> { return data.update { it.withSegments { _, s -> s.withoutParents() } }.boolSuccess() } override fun clearParents(contexts: Set<Context>): CompletableFuture<Boolean> { return data.update(contexts.toPex(plugin.manager)) { it.withoutParents() }.boolSuccess() } } private fun <T> Map<ContextSet, T>.keysToSponge(): Map<Set<Context>, T> { return mapKeys { (key, _) -> key.toSponge() } }
apache-2.0
02409068fc6733d3d2b791f7d5072b9b
39.477987
121
0.684897
4.334007
false
false
false
false
rolandvitezhu/TodoCloud
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/dialogfragment/MoveListDialogFragment.kt
1
2754
package com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatDialogFragment import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import com.rolandvitezhu.todocloud.R import com.rolandvitezhu.todocloud.app.AppController import com.rolandvitezhu.todocloud.data.Category import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao import com.rolandvitezhu.todocloud.databinding.DialogMovelistBinding import com.rolandvitezhu.todocloud.helper.setSoftInputMode import com.rolandvitezhu.todocloud.ui.activity.main.fragment.MainListFragment import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel import kotlinx.android.synthetic.main.dialog_movelist.* import javax.inject.Inject class MoveListDialogFragment : AppCompatDialogFragment() { @Inject lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao private val listsViewModel by lazy { ViewModelProvider(requireActivity()).get(ListsViewModel::class.java) } override fun onAttach(context: Context) { super.onAttach(context) (requireActivity().application as AppController).appComponent. fragmentComponent().create().inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogTheme) listsViewModel.categoriesViewModel?.initializeCategoriesForSpinner() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dialogMovelistBinding: DialogMovelistBinding = DialogMovelistBinding.inflate(inflater, container, false) val view: View = dialogMovelistBinding.root dialogMovelistBinding.moveListDialogFragment = this dialogMovelistBinding.listsViewModel = listsViewModel dialogMovelistBinding.executePendingBindings() requireDialog().setTitle(R.string.movelist_title) setSoftInputMode() return view } fun onButtonOkClick(view: View) { listsViewModel.isListNotInCategoryBeforeMove = listsViewModel.isListNotInCategory() listsViewModel.categoriesViewModel?.category?.categoryOnlineId = (this.spinner_movelist_category.selectedItem as Category).categoryOnlineId (targetFragment as MainListFragment?)?. let { listsViewModel.onMoveList(it) } dismiss() } fun onButtonCancelClick(view: View) { dismiss() } }
mit
b673c3410426eeffe9bd737c3f649abd
36.22973
91
0.761801
5.090573
false
false
false
false
javaslang/javaslang-circuitbreaker
resilience4j-kotlin/src/test/kotlin/io/github/resilience4j/kotlin/timelimiter/CoroutineTimeLimiterTest.kt
1
4807
/* * * Copyright 2019: Brad Newman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package io.github.resilience4j.kotlin.timelimiter import io.github.resilience4j.kotlin.CoroutineHelloWorldService import io.github.resilience4j.timelimiter.TimeLimiter import io.github.resilience4j.timelimiter.event.TimeLimiterOnErrorEvent import io.github.resilience4j.timelimiter.event.TimeLimiterOnSuccessEvent import io.github.resilience4j.timelimiter.event.TimeLimiterOnTimeoutEvent import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions import org.junit.Test import java.time.Duration import java.util.concurrent.TimeoutException class CoroutineTimeLimiterTest { @Test fun `should execute successful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val successfulEvents = mutableListOf<TimeLimiterOnSuccessEvent>() timelimiter.eventPublisher.onSuccess(successfulEvents::add) //When val result = timelimiter.executeSuspendFunction { helloWorldService.returnHelloWorld() } //Then Assertions.assertThat(result).isEqualTo("Hello world") // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(successfulEvents).hasSize(1) } } @Test fun `should execute unsuccessful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val errorEvents = mutableListOf<TimeLimiterOnErrorEvent>() timelimiter.eventPublisher.onError(errorEvents::add) //When try { timelimiter.executeSuspendFunction { helloWorldService.throwException() } Assertions.failBecauseExceptionWasNotThrown<Nothing>(IllegalStateException::class.java) } catch (e: IllegalStateException) { // nothing - proceed } //Then // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(errorEvents).hasSize(1) } } @Test fun `should cancel operation that times out`() { runBlocking { val timelimiter = TimeLimiter.of(TimeLimiterConfig { timeoutDuration(Duration.ofMillis(10)) }) val helloWorldService = CoroutineHelloWorldService() val timeoutEvents = mutableListOf<TimeLimiterOnTimeoutEvent>() timelimiter.eventPublisher.onTimeout(timeoutEvents::add) //When try { timelimiter.executeSuspendFunction { helloWorldService.wait() } Assertions.failBecauseExceptionWasNotThrown<Nothing>(TimeoutException::class.java) } catch (e: TimeoutException) { // nothing - proceed } //Then // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(timeoutEvents).hasSize(1) } } @Test fun `should decorate successful function`() { runBlocking { val timelimiter = TimeLimiter.ofDefaults() val helloWorldService = CoroutineHelloWorldService() val successfulEvents = mutableListOf<TimeLimiterOnSuccessEvent>() timelimiter.eventPublisher.onSuccess(successfulEvents::add) //When val function = timelimiter.decorateSuspendFunction { helloWorldService.returnHelloWorld() } //Then Assertions.assertThat(function()).isEqualTo("Hello world") // Then the helloWorldService should be invoked 1 time Assertions.assertThat(helloWorldService.invocationCounter).isEqualTo(1) Assertions.assertThat(successfulEvents).hasSize(1) } } }
apache-2.0
f212835f5ad3fca0215b393f233f209e
37.456
106
0.661951
5.213666
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/storage/driver/RamDiskDriverProviderTest.kt
1
3925
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage.driver import arcs.core.common.ArcId import arcs.core.storage.CapabilitiesResolver import arcs.core.storage.StorageKey import arcs.core.storage.StorageKeyProtocol import arcs.core.storage.keys.RamDiskStorageKey import arcs.core.storage.keys.VolatileStorageKey import arcs.core.type.Tag import arcs.core.type.Type import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** Tests for [RamDiskDriverProvider]. */ @RunWith(JUnit4::class) class RamDiskDriverProviderTest { private val provider = RamDiskDriverProvider() @After fun teardown() = runBlocking { CapabilitiesResolver.reset() RamDisk.clear() } @Test fun differentInstances_treatedAsEqual() { val providerA = RamDiskDriverProvider() val providerB = RamDiskDriverProvider() assertThat(providerA).isEqualTo(providerB) assertThat(providerA.hashCode()).isEqualTo(providerB.hashCode()) } @Test fun willSupport_returnsTrue_whenRamDiskKey() { val key = RamDiskStorageKey("foo") assertThat(provider.willSupport(key)).isTrue() } @Test fun willSupport_returnsFalse_whenNotRamDiskKey() { val volatile = VolatileStorageKey(ArcId.newForTest("myarc"), "foo") val other = object : StorageKey(StorageKeyProtocol.Dummy) { override fun toKeyString(): String = "something" override fun newKeyWithComponent(component: String): StorageKey = this } assertThat(provider.willSupport(volatile)).isFalse() assertThat(provider.willSupport(other)).isFalse() } @Test(expected = IllegalArgumentException::class) fun getDriver_throwsOnInvalidKey() = runBlocking { val volatile = VolatileStorageKey(ArcId.newForTest("myarc"), "foo") provider.getDriver(volatile, Int::class, DummyType) Unit } @Test fun drivers_shareTheSameData() = runBlocking { val provider2 = RamDiskDriverProvider() val key = RamDiskStorageKey("foo") val driver1 = provider.getDriver(key, Int::class, DummyType) val driver2 = provider.getDriver(key, Int::class, DummyType) val driver3 = provider2.getDriver(key, Int::class, DummyType) var driver2Value: Int? = null var driver2Version: Int? = null driver2.registerReceiver(driver2.token) { value, version -> driver2Value = value driver2Version = version } var driver3Value: Int? = null var driver3Version: Int? = null driver3.registerReceiver(driver3.token) { value, version -> driver3Value = value driver3Version = version } driver1.send(42, 1) assertThat(driver2Value).isEqualTo(42) assertThat(driver2Version).isEqualTo(1) assertThat(driver3Value).isEqualTo(42) assertThat(driver3Version).isEqualTo(1) } @Test fun removeAllEntities() = runBlocking { val key = RamDiskStorageKey("foo") val driver = provider.getDriver(key, Int::class, DummyType) driver.send(42, 1) provider.removeAllEntities() // Receiver are not updated, so check memory directly. assertThat(RamDisk.memory.contains(key)).isFalse() } @Test fun removeEntitiesBetween() = runBlocking { val key = RamDiskStorageKey("foo") val driver = provider.getDriver(key, Int::class, DummyType) driver.send(42, 1) provider.removeEntitiesCreatedBetween(1, 2) // Receiver are not updated, so check memory directly. assertThat(RamDisk.memory.contains(key)).isFalse() } companion object { object DummyType : Type { override val tag = Tag.Count } } }
bsd-3-clause
fcecca2eefdcfcfcf85714ddca83c6e8
27.649635
96
0.725605
4.075805
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinColorSettingsPage.kt
2
16488
// 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.highlighter import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import com.intellij.openapi.options.colors.RainbowColorSettingsPage import com.intellij.openapi.util.NlsSafe import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.highlighter.dsl.DslKotlinHighlightingVisitorExtension import java.lang.reflect.Modifier class KotlinColorSettingsPage : ColorSettingsPage, RainbowColorSettingsPage { override fun getLanguage() = KotlinLanguage.INSTANCE override fun getIcon() = KotlinIcons.SMALL_LOGO override fun getHighlighter(): SyntaxHighlighter = KotlinHighlighter() override fun getDemoText(): String { return """/* Block comment */ <KEYWORD>package</KEYWORD> hello <KEYWORD>import</KEYWORD> kotlin.collections.* // line comment /** * Doc comment here for `SomeClass` * @see <KDOC_LINK>Iterator#next()</KDOC_LINK> */ <ANNOTATION>@Deprecated</ANNOTATION>(<ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES>message</ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES> = "Deprecated class") <BUILTIN_ANNOTATION>private</BUILTIN_ANNOTATION> class <CLASS>MyClass</CLASS><<BUILTIN_ANNOTATION>out</BUILTIN_ANNOTATION> <TYPE_PARAMETER>T</TYPE_PARAMETER> : <TRAIT>Iterable</TRAIT><<TYPE_PARAMETER>T</TYPE_PARAMETER>>>(var <PARAMETER><MUTABLE_VARIABLE><INSTANCE_PROPERTY>prop1</INSTANCE_PROPERTY></MUTABLE_VARIABLE></PARAMETER> : Int) { fun <FUNCTION_DECLARATION>foo</FUNCTION_DECLARATION>(<PARAMETER>nullable</PARAMETER> : String<QUEST>?</QUEST>, <PARAMETER>r</PARAMETER> : <TRAIT>Runnable</TRAIT>, <PARAMETER>f</PARAMETER> : () -> Int, <PARAMETER>fl</PARAMETER> : <TRAIT>FunctionLike</TRAIT>, dyn: <KEYWORD>dynamic</KEYWORD>) { <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>("length\nis ${"$"}{<PARAMETER>nullable</PARAMETER><SAFE_ACCESS>?.</SAFE_ACCESS><INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>} <STRING_ESCAPE><INVALID_STRING_ESCAPE>\e</INVALID_STRING_ESCAPE></STRING_ESCAPE>") <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<PARAMETER>nullable</PARAMETER><EXCLEXCL>!!</EXCLEXCL>.<INSTANCE_PROPERTY>length</INSTANCE_PROPERTY>) val <LOCAL_VARIABLE>ints</LOCAL_VARIABLE> = java.util.<CONSTRUCTOR_CALL>ArrayList</CONSTRUCTOR_CALL><Int?>(2) <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>[0] = 102 + <PARAMETER><VARIABLE_AS_FUNCTION_CALL>f</VARIABLE_AS_FUNCTION_CALL></PARAMETER>() + <PARAMETER><VARIABLE_AS_FUNCTION_LIKE_CALL>fl</VARIABLE_AS_FUNCTION_LIKE_CALL></PARAMETER>() val <LOCAL_VARIABLE>myFun</LOCAL_VARIABLE> = <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <FUNCTION_LITERAL_BRACES_AND_ARROW>-></FUNCTION_LITERAL_BRACES_AND_ARROW> "" <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW>; var <LOCAL_VARIABLE><MUTABLE_VARIABLE>ref</MUTABLE_VARIABLE></LOCAL_VARIABLE> = <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<INSTANCE_PROPERTY>size</INSTANCE_PROPERTY> ints.<EXTENSION_PROPERTY>lastIndex</EXTENSION_PROPERTY> + <PACKAGE_PROPERTY>globalCounter</PACKAGE_PROPERTY> <LOCAL_VARIABLE>ints</LOCAL_VARIABLE>.<EXTENSION_FUNCTION_CALL>forEach</EXTENSION_FUNCTION_CALL> <LABEL>lit@</LABEL> <FUNCTION_LITERAL_BRACES_AND_ARROW>{</FUNCTION_LITERAL_BRACES_AND_ARROW> <KEYWORD>if</KEYWORD> (<FUNCTION_LITERAL_DEFAULT_PARAMETER>it</FUNCTION_LITERAL_DEFAULT_PARAMETER> == null) return<LABEL>@lit</LABEL> <PACKAGE_FUNCTION_CALL>println</PACKAGE_FUNCTION_CALL>(<FUNCTION_LITERAL_DEFAULT_PARAMETER><SMART_CAST_VALUE>it</SMART_CAST_VALUE></FUNCTION_LITERAL_DEFAULT_PARAMETER> + <LOCAL_VARIABLE><MUTABLE_VARIABLE><WRAPPED_INTO_REF>ref</WRAPPED_INTO_REF></MUTABLE_VARIABLE></LOCAL_VARIABLE>) <FUNCTION_LITERAL_BRACES_AND_ARROW>}</FUNCTION_LITERAL_BRACES_AND_ARROW> dyn.<DYNAMIC_FUNCTION_CALL>dynamicCall</DYNAMIC_FUNCTION_CALL>() dyn.<DYNAMIC_PROPERTY_CALL>dynamicProp</DYNAMIC_PROPERTY_CALL> = 5 val <LOCAL_VARIABLE>klass</LOCAL_VARIABLE> = <CLASS>MyClass</CLASS>::<KEYWORD>class</KEYWORD> val year = java.time.LocalDate.now().<SYNTHETIC_EXTENSION_PROPERTY>year</SYNTHETIC_EXTENSION_PROPERTY> } <BUILTIN_ANNOTATION>override</BUILTIN_ANNOTATION> fun hashCode(): Int { return <KEYWORD>super</KEYWORD>.<FUNCTION_CALL>hashCode</FUNCTION_CALL>() * 31 } } fun Int?.bar() { <KEYWORD>if</KEYWORD> (this != null) { println(<NAMED_ARGUMENT>message =</NAMED_ARGUMENT> <SMART_CAST_RECEIVER>toString</SMART_CAST_RECEIVER>()) } else { println(<SMART_CONSTANT>this</SMART_CONSTANT>.toString()) } } var <PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION><MUTABLE_VARIABLE>globalCounter</MUTABLE_VARIABLE></PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> : Int = <NUMBER>5</NUMBER> <KEYWORD>get</KEYWORD>() = <LOCAL_VARIABLE><MUTABLE_VARIABLE><BACKING_FIELD_VARIABLE>field</BACKING_FIELD_VARIABLE></MUTABLE_VARIABLE></LOCAL_VARIABLE> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS> { val <INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> <KEYWORD>get</KEYWORD>() = 1 fun <FUNCTION_DECLARATION>test</FUNCTION_DECLARATION>() { <INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION>bar</INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION> } } <KEYWORD>object</KEYWORD> <OBJECT>Obj</OBJECT> <KEYWORD>enum</KEYWORD> <KEYWORD>class</KEYWORD> <ENUM>E</ENUM> { <ENUM_ENTRY>A</ENUM_ENTRY>, <ENUM_ENTRY>B</ENUM_ENTRY> } <KEYWORD>interface</KEYWORD> <TRAIT>FunctionLike</TRAIT> { <BUILTIN_ANNOTATION>operator</BUILTIN_ANNOTATION> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>invoke</FUNCTION_DECLARATION>() = <NUMBER>1</NUMBER> } <KEYWORD>typealias</KEYWORD> <TYPE_ALIAS>Predicate</TYPE_ALIAS><<TYPE_PARAMETER>T</TYPE_PARAMETER>> = (<TYPE_PARAMETER>T</TYPE_PARAMETER>) -> <CLASS>Boolean</CLASS> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>baz</FUNCTION_DECLARATION>(<PARAMETER>p</PARAMETER>: <TYPE_ALIAS>Predicate</TYPE_ALIAS><<CLASS>Int</CLASS>>) = <PARAMETER><VARIABLE_AS_FUNCTION_CALL>p</VARIABLE_AS_FUNCTION_CALL></PARAMETER>(<NUMBER>42</NUMBER>) <KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendCall</FUNCTION_DECLARATION>() = <SUSPEND_FUNCTION_CALL>suspendFn</SUSPEND_FUNCTION_CALL>() <KEYWORD>suspend</KEYWORD> <KEYWORD>fun</KEYWORD> <FUNCTION_DECLARATION>suspendFn</FUNCTION_DECLARATION>() {} """ } override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey> { val map = HashMap<String, TextAttributesKey>() for (field in KotlinHighlightingColors::class.java.fields) { if (Modifier.isStatic(field.modifiers)) { try { map.put(field.name, field.get(null) as TextAttributesKey) } catch (e: IllegalAccessException) { assert(false) } } } map.putAll(DslKotlinHighlightingVisitorExtension.descriptionsToStyles) return map } override fun getAttributeDescriptors(): Array<AttributesDescriptor> { infix fun String.to(key: TextAttributesKey) = AttributesDescriptor(this, key) return arrayOf( KotlinBundle.message("highlighter.descriptor.text.builtin.keyword") to KotlinHighlightingColors.KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.val") to KotlinHighlightingColors.VAL_KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.keyword.var") to KotlinHighlightingColors.VAR_KEYWORD, KotlinBundle.message("highlighter.descriptor.text.builtin.annotation") to KotlinHighlightingColors.BUILTIN_ANNOTATION, OptionsBundle.message("options.java.attribute.descriptor.number") to KotlinHighlightingColors.NUMBER, OptionsBundle.message("options.java.attribute.descriptor.string") to KotlinHighlightingColors.STRING, KotlinBundle.message("highlighter.descriptor.text.string.escape") to KotlinHighlightingColors.STRING_ESCAPE, OptionsBundle.message("options.java.attribute.descriptor.invalid.escape.in.string") to KotlinHighlightingColors.INVALID_STRING_ESCAPE, OptionsBundle.message("options.java.attribute.descriptor.operator.sign") to KotlinHighlightingColors.OPERATOR_SIGN, OptionsBundle.message("options.java.attribute.descriptor.parentheses") to KotlinHighlightingColors.PARENTHESIS, OptionsBundle.message("options.java.attribute.descriptor.braces") to KotlinHighlightingColors.BRACES, KotlinBundle.message("highlighter.descriptor.text.closure.braces") to KotlinHighlightingColors.FUNCTION_LITERAL_BRACES_AND_ARROW, KotlinBundle.message("highlighter.descriptor.text.arrow") to KotlinHighlightingColors.ARROW, OptionsBundle.message("options.java.attribute.descriptor.brackets") to KotlinHighlightingColors.BRACKETS, OptionsBundle.message("options.java.attribute.descriptor.comma") to KotlinHighlightingColors.COMMA, OptionsBundle.message("options.java.attribute.descriptor.semicolon") to KotlinHighlightingColors.SEMICOLON, KotlinBundle.message("highlighter.descriptor.text.colon") to KotlinHighlightingColors.COLON, KotlinBundle.message("highlighter.descriptor.text.double.colon") to KotlinHighlightingColors.DOUBLE_COLON, OptionsBundle.message("options.java.attribute.descriptor.dot") to KotlinHighlightingColors.DOT, KotlinBundle.message("highlighter.descriptor.text.safe.access") to KotlinHighlightingColors.SAFE_ACCESS, KotlinBundle.message("highlighter.descriptor.text.quest") to KotlinHighlightingColors.QUEST, KotlinBundle.message("highlighter.descriptor.text.exclexcl") to KotlinHighlightingColors.EXCLEXCL, OptionsBundle.message("options.java.attribute.descriptor.line.comment") to KotlinHighlightingColors.LINE_COMMENT, OptionsBundle.message("options.java.attribute.descriptor.block.comment") to KotlinHighlightingColors.BLOCK_COMMENT, KotlinBundle.message("highlighter.descriptor.text.kdoc.comment") to KotlinHighlightingColors.DOC_COMMENT, KotlinBundle.message("highlighter.descriptor.text.kdoc.tag") to KotlinHighlightingColors.KDOC_TAG, KotlinBundle.message("highlighter.descriptor.text.kdoc.value") to KotlinHighlightingColors.KDOC_LINK, OptionsBundle.message("options.java.attribute.descriptor.class") to KotlinHighlightingColors.CLASS, OptionsBundle.message("options.java.attribute.descriptor.type.parameter") to KotlinHighlightingColors.TYPE_PARAMETER, OptionsBundle.message("options.java.attribute.descriptor.abstract.class") to KotlinHighlightingColors.ABSTRACT_CLASS, OptionsBundle.message("options.java.attribute.descriptor.interface") to KotlinHighlightingColors.TRAIT, KotlinBundle.message("highlighter.descriptor.text.annotation") to KotlinHighlightingColors.ANNOTATION, KotlinBundle.message("highlighter.descriptor.text.annotation.attribute.name") to KotlinHighlightingColors.ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES, KotlinBundle.message("highlighter.descriptor.text.object") to KotlinHighlightingColors.OBJECT, KotlinBundle.message("highlighter.descriptor.text.enum") to KotlinHighlightingColors.ENUM, KotlinBundle.message("highlighter.descriptor.text.enumEntry") to KotlinHighlightingColors.ENUM_ENTRY, KotlinBundle.message("highlighter.descriptor.text.typeAlias") to KotlinHighlightingColors.TYPE_ALIAS, KotlinBundle.message("highlighter.descriptor.text.var") to KotlinHighlightingColors.MUTABLE_VARIABLE, KotlinBundle.message("highlighter.descriptor.text.local.variable") to KotlinHighlightingColors.LOCAL_VARIABLE, OptionsBundle.message("options.java.attribute.descriptor.parameter") to KotlinHighlightingColors.PARAMETER, KotlinBundle.message("highlighter.descriptor.text.captured.variable") to KotlinHighlightingColors.WRAPPED_INTO_REF, KotlinBundle.message("highlighter.descriptor.text.instance.property") to KotlinHighlightingColors.INSTANCE_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.instance.property.custom.property.declaration") to KotlinHighlightingColors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.package.property.custom.property.declaration") to KotlinHighlightingColors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.package.property") to KotlinHighlightingColors.PACKAGE_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.field") to KotlinHighlightingColors.BACKING_FIELD_VARIABLE, KotlinBundle.message("highlighter.descriptor.text.extension.property") to KotlinHighlightingColors.EXTENSION_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.synthetic.extension.property") to KotlinHighlightingColors.SYNTHETIC_EXTENSION_PROPERTY, KotlinBundle.message("highlighter.descriptor.text.dynamic.property") to KotlinHighlightingColors.DYNAMIC_PROPERTY_CALL, KotlinBundle.message("highlighter.descriptor.text.android.extensions.property") to KotlinHighlightingColors.ANDROID_EXTENSIONS_PROPERTY_CALL, KotlinBundle.message("highlighter.descriptor.text.it") to KotlinHighlightingColors.FUNCTION_LITERAL_DEFAULT_PARAMETER, KotlinBundle.message("highlighter.descriptor.text.fun") to KotlinHighlightingColors.FUNCTION_DECLARATION, KotlinBundle.message("highlighter.descriptor.text.fun.call") to KotlinHighlightingColors.FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.dynamic.fun.call") to KotlinHighlightingColors.DYNAMIC_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.suspend.fun.call") to KotlinHighlightingColors.SUSPEND_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.package.fun.call") to KotlinHighlightingColors.PACKAGE_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.extension.fun.call") to KotlinHighlightingColors.EXTENSION_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.constructor.call") to KotlinHighlightingColors.CONSTRUCTOR_CALL, KotlinBundle.message("highlighter.descriptor.text.variable.as.function.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_CALL, KotlinBundle.message("highlighter.descriptor.text.variable.as.function.like.call") to KotlinHighlightingColors.VARIABLE_AS_FUNCTION_LIKE_CALL, KotlinBundle.message("highlighter.descriptor.text.smart.cast") to KotlinHighlightingColors.SMART_CAST_VALUE, KotlinBundle.message("highlighter.descriptor.text.smart.constant") to KotlinHighlightingColors.SMART_CONSTANT, KotlinBundle.message("highlighter.descriptor.text.smart.cast.receiver") to KotlinHighlightingColors.SMART_CAST_RECEIVER, KotlinBundle.message("highlighter.descriptor.text.label") to KotlinHighlightingColors.LABEL, KotlinBundle.message("highlighter.descriptor.text.named.argument") to KotlinHighlightingColors.NAMED_ARGUMENT ) + DslKotlinHighlightingVisitorExtension.descriptionsToStyles.map { (description, key) -> description to key }.toTypedArray() } override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY override fun getDisplayName(): String { @Suppress("UnnecessaryVariable") @NlsSafe val name = KotlinLanguage.NAME return name } override fun isRainbowType(type: TextAttributesKey): Boolean { return type == KotlinHighlightingColors.LOCAL_VARIABLE || type == KotlinHighlightingColors.PARAMETER } }
apache-2.0
de9838ff8612212ec16127e271ac8b47
82.272727
338
0.757885
4.709512
false
false
false
false
Applandeo/Material-Calendar-View
library/src/main/java/com/applandeo/materialcalendarview/utils/DateUtils.kt
1
4405
@file:JvmName("DateUtils") package com.applandeo.materialcalendarview.utils import android.content.Context import com.applandeo.materialcalendarview.R import java.util.* import java.util.concurrent.TimeUnit /** * Created by Applandeo Team. */ /** * @return An instance of the Calendar object with hour set to 00:00:00:00 */ val midnightCalendar: Calendar get() = Calendar.getInstance().apply { this.setMidnight() } @Deprecated("Use getMidnightCalendar()") val calendar: Calendar get() = Calendar.getInstance().apply { this.setMidnight() } /** * This method sets an hour in the calendar object to 00:00:00:00 * * @param this Calendar object which hour should be set to 00:00:00:00 */ fun Calendar.setMidnight() = this.apply { set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } /** * This method compares calendars using month and year * * @param this First calendar object to compare * @param secondCalendar Second calendar object to compare * @return Boolean value if second calendar is before the first one */ fun Calendar?.isMonthBefore(secondCalendar: Calendar?): Boolean { if (this == null || secondCalendar == null) return false val firstDay = (this.clone() as Calendar).apply { setMidnight() set(Calendar.DAY_OF_MONTH, 1) } val secondDay = (secondCalendar.clone() as Calendar).apply { setMidnight() set(Calendar.DAY_OF_MONTH, 1) } return secondDay.before(firstDay) } /** * This method compares calendars using month and year * * @param this First calendar object to compare * @param secondCalendar Second calendar object to compare * @return Boolean value if second calendar is after the first one */ fun Calendar?.isMonthAfter(secondCalendar: Calendar) = secondCalendar.isMonthBefore(this) /** * This method returns a string containing a month's name and a year (in number). * It's used instead of new SimpleDateFormat("MMMM yyyy", Locale.getDefault()).format([Date]); * because that method returns a month's name in incorrect form in some languages (i.e. in Polish) * * @param this A Calendar object containing date which will be formatted * @param context An array of months names * @return A string of the formatted date containing a month's name and a year (in number) */ internal fun Calendar.getMonthAndYearDate(context: Context) = String.format( "%s %s", context.resources.getStringArray(R.array.material_calendar_months_array)[this.get(Calendar.MONTH)], this.get(Calendar.YEAR) ) /** * This method is used to count a number of months between two dates * * @param this Calendar representing a first date * @param endCalendar Calendar representing a last date * @return Number of months */ fun Calendar.getMonthsToDate(endCalendar: Calendar): Int { val years = endCalendar.get(Calendar.YEAR) - this.get(Calendar.YEAR) return years * 12 + endCalendar.get(Calendar.MONTH) - this.get(Calendar.MONTH) } /** * This method checks whether date is correctly between min and max date or not * * @param calendarProperties Calendar properties */ fun Calendar.isBetweenMinAndMax(calendarProperties: CalendarProperties) = !(calendarProperties.minimumDate != null && this.before(calendarProperties.minimumDate) || calendarProperties.maximumDate != null && this.after(calendarProperties.maximumDate)) /** * This method is used to count a number of days between two dates * * @param this Calendar representing a first date * @param endCalendar Calendar representing a last date * @return Number of days * * +1 is necessary because method counts from the beginning of start day to beginning of end day * and 1, means whole end day */ private fun Calendar.getDaysToDate(endCalendar: Calendar) = TimeUnit.MILLISECONDS.toDays(endCalendar.timeInMillis - this.timeInMillis) + 1 internal fun List<Calendar>.isFullDatesRange(): Boolean { val selectedDates = this.distinct().sortedBy { it.timeInMillis } if (this.isEmpty() || selectedDates.size == 1) return true return selectedDates.size.toLong() == selectedDates.first().getDaysToDate(selectedDates.last()) } val Calendar.isToday get() = this == midnightCalendar fun Calendar.isEqual(calendar: Calendar) = this.setMidnight() == calendar.setMidnight()
apache-2.0
1192daf60ba3c6ff192f82979fdcdf42
32.633588
107
0.723042
3.997278
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/deeplinks/handlers/ReaderLinkHandler.kt
1
6314
package org.wordpress.android.ui.deeplinks.handlers import android.content.Intent import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat.READER_VIEWPOST_INTERCEPTED import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenInReader import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.OpenReader import org.wordpress.android.ui.deeplinks.DeepLinkNavigator.NavigateAction.ViewPostInReader import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.APPLINK_SCHEME import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.HOST_WORDPRESS_COM import org.wordpress.android.ui.deeplinks.DeepLinkingIntentReceiverViewModel.Companion.SITE_DOMAIN import org.wordpress.android.ui.reader.ReaderConstants import org.wordpress.android.ui.utils.IntentUtils import org.wordpress.android.util.UriWrapper import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper import org.wordpress.android.viewmodel.Event import java.lang.StringBuilder import javax.inject.Inject class ReaderLinkHandler @Inject constructor( private val intentUtils: IntentUtils, private val analyticsUtilsWrapper: AnalyticsUtilsWrapper ) : DeepLinkHandler { private val _toast = MutableLiveData<Event<Int>>() val toast = _toast as LiveData<Event<Int>> /** * URIs supported by the Reader are already defined as intent filters in the manifest. Instead of replicating * that logic here, we simply check if we can resolve an [Intent] that uses [ReaderConstants.ACTION_VIEW_POST]. * Since that's a custom action that is only handled by the Reader, we can then assume it supports this URI. * Other deeplinks handled: * `wordpress://read` * `wordpress://viewpost?blogId={blogId}&postId={postId}` */ override fun shouldHandleUrl(uri: UriWrapper): Boolean { return DEEP_LINK_HOST_READ == uri.host || DEEP_LINK_HOST_VIEWPOST == uri.host || intentUtils.canResolveWith( ReaderConstants.ACTION_VIEW_POST, uri ) } override fun buildNavigateAction(uri: UriWrapper): NavigateAction { return when (uri.host) { DEEP_LINK_HOST_READ -> OpenReader DEEP_LINK_HOST_VIEWPOST -> { val blogId = uri.getQueryParameter(BLOG_ID)?.toLongOrNull() val postId = uri.getQueryParameter(POST_ID)?.toLongOrNull() if (blogId != null && postId != null) { analyticsUtilsWrapper.trackWithBlogPostDetails(READER_VIEWPOST_INTERCEPTED, blogId, postId) ViewPostInReader(blogId, postId, uri) } else { _toast.value = Event(R.string.error_generic) OpenReader } } else -> OpenInReader(uri) } } /** * URLs handled here * `wordpress://read` * `wordpress://viewpost?blogId={blogId}&postId={postId}` * wordpress.com/read/feeds/feedId/posts/feedItemId * wordpress.com/read/blogs/feedId/posts/feedItemId * domain.wordpress.com/2.../../../postId * domain.wordpress.com/19../../../postId */ override fun stripUrl(uri: UriWrapper): String { return when (uri.host) { DEEP_LINK_HOST_READ -> "$APPLINK_SCHEME$DEEP_LINK_HOST_READ" DEEP_LINK_HOST_VIEWPOST -> { val hasBlogId = uri.getQueryParameter(BLOG_ID) != null val hasPostId = uri.getQueryParameter(POST_ID) != null buildString { append("$APPLINK_SCHEME$DEEP_LINK_HOST_VIEWPOST") if (hasBlogId || hasPostId) { append("?") if (hasBlogId) { append("$BLOG_ID=$BLOG_ID") if (hasPostId) { append("&") } } if (hasPostId) { append("$POST_ID=$POST_ID") } } } } else -> { buildString { val segments = uri.pathSegments // Handled URLs look like this: http[s]://wordpress.com/read/feeds/{feedId}/posts/{feedItemId} // with the first segment being 'read'. append(stripHost(uri)) if (segments.firstOrNull() == "read") { appendReadPath(segments) } else if (segments.size > DATE_URL_SEGMENTS) { append("/YYYY/MM/DD/$POST_ID") } }.ifEmpty { uri.host + uri.pathSegments.firstOrNull() } } } } private fun stripHost(uri: UriWrapper): String { val domains = uri.host?.split(".") ?: listOf() return if (domains.size >= CUSTOM_DOMAIN_POSITION && domains[domains.size - CUSTOM_DOMAIN_POSITION] != "www") { "$SITE_DOMAIN.$HOST_WORDPRESS_COM" } else { uri.host ?: HOST_WORDPRESS_COM } } private fun StringBuilder.appendReadPath(segments: List<String>) { append("/read") when (segments.getOrNull(BLOGS_FEEDS_PATH_POSITION)) { "blogs" -> { append("/blogs/$FEED_ID") } "feeds" -> { append("/feeds/$FEED_ID") } } if (segments.getOrNull(POSTS_PATH_POSITION) == "posts") { append("/posts/feedItemId") } } companion object { private const val DEEP_LINK_HOST_READ = "read" private const val DEEP_LINK_HOST_VIEWPOST = "viewpost" private const val BLOG_ID = "blogId" private const val POST_ID = "postId" private const val FEED_ID = "feedId" private const val CUSTOM_DOMAIN_POSITION = 3 private const val BLOGS_FEEDS_PATH_POSITION = 1 private const val POSTS_PATH_POSITION = 3 private const val DATE_URL_SEGMENTS = 3 } }
gpl-2.0
a3a232f4a1715f940b97a69fbbc3f763
41.952381
116
0.601837
4.545716
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt
3
16759
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.psi2ir.deparenthesize import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.references.ReferenceAccess import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.safeAs class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>( KtExpression::class.java, KotlinIdeaAnalysisBundle.lazyMessage("replace.overloaded.operator.with.function.call"), ) { companion object { fun replaceExplicitInvokeCallWithImplicit(qualifiedExpression: KtDotQualifiedExpression): KtExpression? { /* * `a.b.invoke<>(){}` -> `a.b<>(){}` * `a.b<>(){}.invoke<>(){}` -> `a.b<>(){}<>(){}` * `b.invoke<>(){}` -> `b<>(){}` * `b<>(){}.invoke<>(){}` -> `b<>(){}<>(){}` * `invoke<>(){}` -> not applicable */ val callExpression = qualifiedExpression.selectorExpression.safeAs<KtCallExpression>()?.copied() ?: return null val calleExpression = callExpression.calleeExpression as KtNameReferenceExpression val receiverExpression = qualifiedExpression.receiverExpression val selectorInReceiver = receiverExpression.safeAs<KtDotQualifiedExpression>()?.selectorExpression return if (selectorInReceiver is KtNameReferenceExpression) { calleExpression.rawReplace(selectorInReceiver.copied()) selectorInReceiver.rawReplace(callExpression) qualifiedExpression.replaced(receiverExpression) } else { if ((receiverExpression is KtCallExpression || receiverExpression is KtDotQualifiedExpression) && callExpression.valueArgumentList == null && callExpression.typeArgumentList == null) { calleExpression.replace(receiverExpression) } else { calleExpression.rawReplace(receiverExpression) } qualifiedExpression.replaced(callExpression) } } private fun isApplicableUnary(element: KtUnaryExpression, caretOffset: Int): Boolean { if (element.baseExpression == null) return false val opRef = element.operationReference if (!opRef.textRange.containsOffset(caretOffset)) return false return when (opRef.getReferencedNameElementType()) { KtTokens.PLUS, KtTokens.MINUS, KtTokens.EXCL -> true KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> !isUsedAsExpression(element) else -> false } } // TODO: replace to `element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))` after fix KT-25682 private fun isUsedAsExpression(element: KtExpression): Boolean { val parent = element.parent return if (parent is KtBlockExpression) parent.lastBlockStatementOrThis() == element && parentIsUsedAsExpression(parent.parent) else parentIsUsedAsExpression(parent) } private fun parentIsUsedAsExpression(element: PsiElement): Boolean = when (val parent = element.parent) { is KtLoopExpression, is KtFile -> false is KtIfExpression, is KtWhenExpression -> (parent as KtExpression).isUsedAsExpression(parent.analyze(BodyResolveMode.PARTIAL_WITH_CFA)) else -> true } private fun isApplicableBinary(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.left == null || element.right == null) return false val opRef = element.operationReference if (!opRef.textRange.containsOffset(caretOffset)) return false return when (opRef.getReferencedNameElementType()) { KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL, KtTokens.DIV, KtTokens.PERC, KtTokens.RANGE, KtTokens.RANGE_UNTIL, KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ, KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> true KtTokens.EQEQ, KtTokens.EXCLEQ -> listOf(element.left, element.right).none { it?.node?.elementType == KtNodeTypes.NULL } KtTokens.EQ -> element.left is KtArrayAccessExpression else -> false } } private fun isApplicableArrayAccess(element: KtArrayAccessExpression, caretOffset: Int): Boolean { val lbracket = element.leftBracket ?: return false val rbracket = element.rightBracket ?: return false val access = element.readWriteAccess(useResolveForReadWrite = true) if (access == ReferenceAccess.READ_WRITE) return false // currently not supported return lbracket.textRange.containsOffset(caretOffset) || rbracket.textRange.containsOffset(caretOffset) } private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean { val lbrace = (element.valueArgumentList?.leftParenthesis ?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace ?: return false) as PsiElement if (!lbrace.textRange.containsOffset(caretOffset)) return false val resolvedCall = element.resolveToCall(BodyResolveMode.FULL) val descriptor = resolvedCall?.resultingDescriptor if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) { if (element.parent is KtDotQualifiedExpression && element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString() ) return false return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty() } return false } private fun convertUnary(element: KtUnaryExpression): KtExpression { val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> return convertUnaryWithAssignFix(element) KtTokens.PLUS -> OperatorNameConventions.UNARY_PLUS KtTokens.MINUS -> OperatorNameConventions.UNARY_MINUS KtTokens.EXCL -> OperatorNameConventions.NOT else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern("$0.$1()", element.baseExpression!!, operatorName) return element.replace(transformed) as KtExpression } private fun convertUnaryWithAssignFix(element: KtUnaryExpression): KtExpression { val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS -> OperatorNameConventions.INC KtTokens.MINUSMINUS -> OperatorNameConventions.DEC else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern("$0 = $0.$1()", element.baseExpression!!, operatorName) return element.replace(transformed) as KtExpression } //TODO: don't use creation by plain text private fun convertBinary(element: KtBinaryExpression): KtExpression { val op = element.operationReference.getReferencedNameElementType() val left = element.left!! val right = element.right!! if (op == KtTokens.EQ) { if (left is KtArrayAccessExpression) { convertArrayAccess(left) } return element } val context = element.analyze(BodyResolveMode.PARTIAL) val functionCandidate = element.getResolvedCall(context) val functionName = functionCandidate?.candidateDescriptor?.name.toString() val elemType = context.getType(left) @NonNls val pattern = when (op) { KtTokens.PLUS -> "$0.plus($1)" KtTokens.MINUS -> "$0.minus($1)" KtTokens.MUL -> "$0.times($1)" KtTokens.DIV -> "$0.div($1)" KtTokens.PERC -> "$0.rem($1)" KtTokens.RANGE -> "$0.rangeTo($1)" KtTokens.RANGE_UNTIL -> "$0.rangeUntil($1)" KtTokens.IN_KEYWORD -> "$1.contains($0)" KtTokens.NOT_IN -> "!$1.contains($0)" KtTokens.PLUSEQ -> if (functionName == "plusAssign") "$0.plusAssign($1)" else "$0 = $0.plus($1)" KtTokens.MINUSEQ -> if (functionName == "minusAssign") "$0.minusAssign($1)" else "$0 = $0.minus($1)" KtTokens.MULTEQ -> if (functionName == "timesAssign") "$0.timesAssign($1)" else "$0 = $0.times($1)" KtTokens.DIVEQ -> if (functionName == "divAssign") "$0.divAssign($1)" else "$0 = $0.div($1)" KtTokens.PERCEQ -> { val remSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem) if (remSupported && functionName == "remAssign") "$0.remAssign($1)" else if (functionName == "modAssign") "$0.modAssign($1)" else if (remSupported) "$0 = $0.rem($1)" else "$0 = $0.mod($1)" } KtTokens.EQEQ -> if (elemType?.isMarkedNullable != false) "$0?.equals($1) ?: ($1 == null)" else "$0.equals($1)" KtTokens.EXCLEQ -> if (elemType?.isMarkedNullable != false) "!($0?.equals($1) ?: ($1 == null))" else "!$0.equals($1)" KtTokens.GT -> "$0.compareTo($1) > 0" KtTokens.LT -> "$0.compareTo($1) < 0" KtTokens.GTEQ -> "$0.compareTo($1) >= 0" KtTokens.LTEQ -> "$0.compareTo($1) <= 0" else -> return element } val transformed = KtPsiFactory(element).createExpressionByPattern(pattern, left, right) return element.replace(transformed) as KtExpression } private fun convertArrayAccess(element: KtArrayAccessExpression): KtExpression { var expressionToReplace: KtExpression = element val transformed = KtPsiFactory(element).buildExpression { appendExpression(element.arrayExpression) appendFixedText(".") if (isAssignmentLeftSide(element)) { val parent = element.parent expressionToReplace = parent as KtBinaryExpression appendFixedText("set(") appendExpressions(element.indexExpressions) appendFixedText(",") appendExpression(parent.right) } else { appendFixedText("get(") appendExpressions(element.indexExpressions) } appendFixedText(")") } return expressionToReplace.replace(transformed) as KtExpression } private fun isAssignmentLeftSide(element: KtArrayAccessExpression): Boolean { val parent = element.parent return parent is KtBinaryExpression && parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left } //TODO: don't use creation by plain text private fun convertCall(element: KtCallExpression): KtExpression { val callee = element.calleeExpression!! val receiver = element.parent?.safeAs<KtQualifiedExpression>()?.receiverExpression val isAnonymousFunctionWithReceiver = receiver != null && callee.deparenthesize() is KtNamedFunction val argumentsList = element.valueArgumentList val argumentString = argumentsList?.text?.removeSurrounding("(", ")") ?: "" val argumentsWithReceiverIfNeeded = if (isAnonymousFunctionWithReceiver) { val receiverText = receiver?.text ?: "" val delimiter = if (receiverText.isNotEmpty() && argumentString.isNotEmpty()) ", " else "" receiverText + delimiter + argumentString } else { argumentString } val funcLitArgs = element.lambdaArguments val calleeText = callee.text val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + "($argumentsWithReceiverIfNeeded)" val transformed = KtPsiFactory(element).createExpression(transformation) val callExpression = transformed.getCalleeExpressionIfAny()?.parent as? KtCallExpression if (callExpression != null && funcLitArgs.isNotEmpty()) { funcLitArgs.forEach { callExpression.add(it) } if (argumentsWithReceiverIfNeeded.isEmpty()) { callExpression.valueArgumentList?.delete() } } val elementToReplace = if (isAnonymousFunctionWithReceiver) element.parent else callee.parent return elementToReplace.replace(transformed) as KtExpression } fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> { var elementToBeReplaced = element if (element is KtArrayAccessExpression && isAssignmentLeftSide(element)) { elementToBeReplaced = element.parent as KtExpression } val commentSaver = CommentSaver(elementToBeReplaced, saveLineBreaks = true) val result = when (element) { is KtUnaryExpression -> convertUnary(element) is KtBinaryExpression -> convertBinary(element) is KtArrayAccessExpression -> convertArrayAccess(element) is KtCallExpression -> convertCall(element) else -> throw IllegalArgumentException(element.toString()) } commentSaver.restore(result) val callName = findCallName(result) ?: error("No call name found in ${result.text}") return result to callName } private fun findCallName(result: KtExpression): KtSimpleNameExpression? = when (result) { is KtBinaryExpression -> { if (KtPsiUtil.isAssignment(result)) findCallName(result.right!!) else findCallName(result.left!!) } is KtUnaryExpression -> result.baseExpression?.let { findCallName(it) } is KtParenthesizedExpression -> result.expression?.let { findCallName(it) } else -> result.getQualifiedElementSelector() as KtSimpleNameExpression? } } override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean = when (element) { is KtUnaryExpression -> isApplicableUnary(element, caretOffset) is KtBinaryExpression -> isApplicableBinary(element, caretOffset) is KtArrayAccessExpression -> isApplicableArrayAccess(element, caretOffset) is KtCallExpression -> isApplicableCall(element, caretOffset) else -> false } override fun applyTo(element: KtExpression, editor: Editor?) { convert(element) } }
apache-2.0
31c45bb66c3af6ae69bad4d7835ba784
51.53605
158
0.640253
5.593792
false
false
false
false
android/play-billing-samples
PlayBillingCodelab/start/src/main/java/com/sample/subscriptionscodelab/ui/MainViewModel.kt
1
5168
/* * Copyright 2022 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sample.subscriptionscodelab.ui import android.app.Activity import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.ProductDetails import com.android.billingclient.api.Purchase import com.sample.subscriptionscodelab.billing.BillingClientWrapper import com.sample.subscriptionscodelab.repository.SubscriptionDataRepository import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch /** * The [AndroidViewModel] implementation combines all flows from the repo into a single one * that is collected in the Composable. * * It, also, has helper methods that are used to launch the Google Play Billing purchase flow. * */ class MainViewModel(application: Application) : AndroidViewModel(application) { var billingClient: BillingClientWrapper = BillingClientWrapper(application) private var repo: SubscriptionDataRepository = SubscriptionDataRepository(billingClientWrapper = billingClient) private val _billingConnectionState = MutableLiveData(false) val billingConnectionState: LiveData<Boolean> = _billingConnectionState private val _destinationScreen = MutableLiveData<DestinationScreen>() val destinationScreen: LiveData<DestinationScreen> = _destinationScreen // Start the billing connection when the viewModel is initialized. init { billingClient.startBillingConnection(billingConnectionState = _billingConnectionState) } // The productsForSaleFlows object combines all the Product flows into one for emission. // The userCurrentSubscriptionFlow object combines all the possible subscription flows into one // for emission. // Current purchases. /** * Retrieves all eligible base plans and offers using tags from ProductDetails. * * @param offerDetails offerDetails from a ProductDetails returned by the library. * @param tag string representing tags associated with offers and base plans. * * @return the eligible offers and base plans in a list. * */ /** * Calculates the lowest priced offer amongst all eligible offers. * In this implementation the lowest price of all offers' pricing phases is returned. * It's possible the logic can be implemented differently. * For example, the lowest average price in terms of month could be returned instead. * * @param offerDetails List of of eligible offers and base plans. * * @return the offer id token of the lowest priced offer. */ /** * BillingFlowParams Builder for upgrades and downgrades. * * @param productDetails ProductDetails object returned by the library. * @param offerToken the least priced offer's offer id token returned by * [leastPricedOfferToken]. * @param oldToken the purchase token of the subscription purchase being upgraded or downgraded. * * @return [BillingFlowParams] builder. */ /** * BillingFlowParams Builder for normal purchases. * * @param productDetails ProductDetails object returned by the library. * @param offerToken the least priced offer's offer id token returned by * [leastPricedOfferToken]. * * @return [BillingFlowParams] builder. */ /** * Use the Google Play Billing Library to make a purchase. * * @param productDetails ProductDetails object returned by the library. * @param currentPurchases List of current [Purchase] objects needed for upgrades or downgrades. * @param billingClient Instance of [BillingClientWrapper]. * @param activity [Activity] instance. * @param tag String representing tags associated with offers and base plans. */ // When an activity is destroyed the viewModel's onCleared is called, so we terminate the // billing connection. /** * Enum representing the various screens a user can be redirected to. */ enum class DestinationScreen { SUBSCRIPTIONS_OPTIONS_SCREEN, BASIC_PREPAID_PROFILE_SCREEN, BASIC_RENEWABLE_PROFILE, PREMIUM_PREPAID_PROFILE_SCREEN, PREMIUM_RENEWABLE_PROFILE; } companion object { private const val TAG: String = "MainViewModel" private const val MAX_CURRENT_PURCHASES_ALLOWED = 1 } }
apache-2.0
e504bdcbd084f08512c79ecfcfed98e4
34.39726
100
0.735875
4.838951
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/challenge/preset/add/AddPresetChallengeInfoViewController.kt
1
15399
package io.ipoli.android.challenge.preset.add import android.os.Bundle import android.support.v4.widget.TextViewCompat import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.TextView import com.mikepenz.iconics.IconicsDrawable import io.ipoli.android.R import io.ipoli.android.challenge.add.TextWatcherAdapter import io.ipoli.android.challenge.entity.Challenge import io.ipoli.android.challenge.preset.PresetChallenge import io.ipoli.android.common.redux.android.BaseViewController import io.ipoli.android.common.view.* import io.ipoli.android.quest.subquest.view.ReadOnlySubQuestAdapter import kotlinx.android.synthetic.main.controller_add_preset_challenge_info.view.* import kotlinx.android.synthetic.main.item_edit_repeating_quest_sub_quest.view.* import java.util.* /** * Created by Polina Zhelyazkova <[email protected]> * on 11/1/18. */ class AddPresetChallengeInfoViewController(args: Bundle? = null) : BaseViewController<AddPresetChallengeAction, AddPresetChallengeViewState>(args) { override val stateKey = AddPresetChallengeReducer.stateKey private val nameWatcher = TextWatcherAdapter { e -> view?.let { val text = if (e.isBlank()) stringRes(R.string.name_hint) else stringRes(R.string.name_hint) + " (${e.length}/50)" it.challengeNameLayout.hint = text } } private val shortDescriptionWatcher = TextWatcherAdapter { e -> view?.let { val text = if (e.isBlank()) stringRes(R.string.short_desc_hint) else stringRes(R.string.short_desc_hint) + " (${e.length}/80)" it.challengeShortDescriptionLayout.hint = text } } private val newExpectedResultWatcher = TextWatcherAdapter { e -> if (e.isBlank()) { view?.challengeAddExpectedResult?.invisible() } else { view?.challengeAddExpectedResult?.visible() } } private val newRequirementsWatcher = TextWatcherAdapter { e -> if (e.isBlank()) { view?.challengeAddRequirement?.invisible() } else { view?.challengeAddRequirement?.visible() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { applyStatusBarColors = false val view = container.inflate(R.layout.controller_add_preset_challenge_info) initExpectedResults(view) initRequirements(view) view.challengeName.addTextChangedListener(nameWatcher) view.challengeShortDescription.addTextChangedListener(shortDescriptionWatcher) return view } override fun onCreateLoadAction() = AddPresetChallengeAction.LoadInfo override fun onAttach(view: View) { super.onAttach(view) toolbarTitle = stringRes(R.string.add_preset_challenge_info_title) } private fun initExpectedResults(view: View) { val adapter = ReadOnlySubQuestAdapter(view.challengeExpectedResultList, useLightTheme = true) view.challengeExpectedResultList.layoutManager = LinearLayoutManager(view.context) view.challengeExpectedResultList.adapter = adapter view.expectedResultName.addTextChangedListener(newExpectedResultWatcher) view.challengeAddExpectedResult.onDebounceClick { val res = view.expectedResultName.text.toString() addExpectedResult(res, view) } view.expectedResultName.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val res = view.expectedResultName.text.toString() addExpectedResult(res, view) } true } } private fun addExpectedResult(result: String, view: View) { (view.challengeExpectedResultList.adapter as ReadOnlySubQuestAdapter).add( ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel(UUID.randomUUID().toString(), result) ) view.expectedResultName.setText("") view.expectedResultName.requestFocus() view.challengeAddExpectedResult.invisible() } private fun initRequirements(view: View) { val adapter = ReadOnlySubQuestAdapter(view.challengeRequirementList, useLightTheme = true) view.challengeRequirementList.layoutManager = LinearLayoutManager(view.context) view.challengeRequirementList.adapter = adapter view.requirementName.addTextChangedListener(newRequirementsWatcher) view.challengeAddRequirement.onDebounceClick { val req = view.requirementName.text.toString() addRequirement(req, view) } view.requirementName.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { val req = view.requirementName.text.toString() addRequirement(req, view) } true } } private fun addRequirement(requirement: String, view: View) { (view.challengeRequirementList.adapter as ReadOnlySubQuestAdapter).add( ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel( UUID.randomUUID().toString(), requirement ) ) view.requirementName.setText("") view.requirementName.requestFocus() view.challengeAddRequirement.invisible() } override fun onDestroyView(view: View) { view.challengeName.removeTextChangedListener(nameWatcher) view.challengeShortDescription.removeTextChangedListener(shortDescriptionWatcher) view.expectedResultName.removeTextChangedListener(newExpectedResultWatcher) view.requirementName.removeTextChangedListener(newRequirementsWatcher) super.onDestroyView(view) } override fun render(state: AddPresetChallengeViewState, view: View) { when (state.type) { AddPresetChallengeViewState.StateType.DATA_LOADED -> { if (state.name.isNotBlank()) { view.challengeName.setText(state.name) } if (state.shortDescription.isNotBlank()) { view.challengeShortDescription.setText(state.shortDescription) } renderColor(view, state) renderIcon(view, state) renderCategory(view, state) renderDuration(view, state) renderDifficulty(view, state) renderDescription(view, state) renderExpectedResults(view, state) renderRequirements(view, state) } AddPresetChallengeViewState.StateType.COLOR_CHANGED -> { renderColor(view, state) } AddPresetChallengeViewState.StateType.ICON_CHANGED -> { renderIcon(view, state) } AddPresetChallengeViewState.StateType.DESCRIPTION_CHANGED -> renderDescription(view, state) AddPresetChallengeViewState.StateType.VALIDATE_TEXTS -> { val expectedResults = view.challengeExpectedResultList.children.map { it.editSubQuestName.text.toString() }.toList() val requirements = view.challengeRequirementList.children.map { it.editSubQuestName.text.toString() }.toList() dispatch( AddPresetChallengeAction.ValidateInfo( view.challengeName.text.toString(), view.challengeShortDescription.text.toString(), expectedResults, requirements ) ) } AddPresetChallengeViewState.StateType.ERROR_INFO -> { if (state.infoErrors.contains(AddPresetChallengeViewState.InfoError.EMPTY_NAME)) { view.challengeName.error = stringRes(R.string.think_of_a_name) } if (state.infoErrors.contains(AddPresetChallengeViewState.InfoError.EMPTY_SHORT_DESCRIPTION)) { view.challengeShortDescription.error = stringRes(R.string.error_empty_short_description) } if (state.infoErrors.contains(AddPresetChallengeViewState.InfoError.EMPTY_DESCRIPTION)) { showShortToast(R.string.error_empty_challenge_description) } if (state.infoErrors.contains(AddPresetChallengeViewState.InfoError.EMPTY_EXPECTED_RESULTS)) { showShortToast(R.string.error_empty_challenge_expected_results) } } else -> { } } } private fun renderIcon( view: View, state: AddPresetChallengeViewState ) { view.challengeSelectedIcon.setImageDrawable( IconicsDrawable(view.context) .largeIcon(state.icon.androidIcon.icon) ) view.challengeIcon.onDebounceClick { navigate().toIconPicker({ ic -> dispatch(AddPresetChallengeAction.ChangeIcon(ic ?: state.icon)) }, state.icon) } } private fun renderColor( view: View, state: AddPresetChallengeViewState ) { view.challengeColor.onDebounceClick { navigate().toColorPicker({ c -> dispatch( AddPresetChallengeAction.ChangeColor(c) ) }, state.color) } } private fun renderExpectedResults(view: View, state: AddPresetChallengeViewState) { (view.challengeExpectedResultList.adapter as ReadOnlySubQuestAdapter).updateAll(state.expectedResultsViewModels) } private fun renderRequirements(view: View, state: AddPresetChallengeViewState) { (view.challengeRequirementList.adapter as ReadOnlySubQuestAdapter).updateAll(state.requirementViewModels) } private fun renderDuration( view: View, state: AddPresetChallengeViewState ) { view.challengeDuration.onItemSelectedListener = null val durations = listOf(7, 15, 30) view.challengeDuration.adapter = ArrayAdapter<String>( view.context, R.layout.item_dropdown_number_spinner, durations.map { it.toString() } ) view.challengeDuration.setSelection(durations.indexOf(state.duration.intValue)) view.challengeDuration.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, v: View?, position: Int, id: Long ) { styleSelectedSpinnerItem(view.challengeDuration) dispatch(AddPresetChallengeAction.ChangeDuration(durations[position])) } } } private fun renderCategory( view: View, state: AddPresetChallengeViewState ) { view.challengeCategory.onItemSelectedListener = null val categories = PresetChallenge.Category.values() view.challengeCategory.adapter = ArrayAdapter<String>( view.context, R.layout.item_dropdown_number_spinner, categories.map { it.name.toLowerCase().capitalize() } ) view.challengeCategory.setSelection(categories.indexOf(state.category)) view.challengeCategory.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, v: View?, position: Int, id: Long ) { styleSelectedSpinnerItem(view.challengeCategory) dispatch(AddPresetChallengeAction.ChangeCategory(categories[position])) } } } private fun renderDifficulty( view: View, state: AddPresetChallengeViewState ) { view.challengeDifficulty.onItemSelectedListener = null val difficulties = Challenge.Difficulty.values().toList() view.challengeDifficulty.adapter = ArrayAdapter<String>( view.context, R.layout.item_dropdown_number_spinner, view.resources.getStringArray(R.array.difficulties) ) view.challengeDifficulty.setSelection(difficulties.indexOf(state.difficulty)) view.challengeDifficulty.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected( parent: AdapterView<*>?, v: View?, position: Int, id: Long ) { styleSelectedSpinnerItem(view.challengeDifficulty) dispatch(AddPresetChallengeAction.ChangeDifficulty(difficulties[position])) } } } private fun renderDescription(view: View, state: AddPresetChallengeViewState) { view.challengeDescription.text = state.descriptionText view.challengeDescription.onDebounceClick { navigate() .toNotePicker( note = state.description, resultListener = { d -> dispatch(AddPresetChallengeAction.ChangeDescription(d)) } ) } } private fun styleSelectedSpinnerItem(view: Spinner) { if (view.selectedView == null) { return } val item = view.selectedView as TextView TextViewCompat.setTextAppearance(item, R.style.TextAppearance_AppCompat_Subhead) item.setTextColor(colorRes(R.color.md_light_text_100)) item.setPadding(0, 0, 0, 0) } private val AddPresetChallengeViewState.descriptionText: String get() = if (description.isBlank()) stringRes(R.string.preset_challenge_description_hint) else description private val AddPresetChallengeViewState.expectedResultsViewModels: List<ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel> get() = expectedResults.map { ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel( id = it, name = it ) } private val AddPresetChallengeViewState.requirementViewModels: List<ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel> get() = requirements.map { ReadOnlySubQuestAdapter.ReadOnlySubQuestViewModel( id = it, name = it ) } }
gpl-3.0
60275404275a395a9caae17aed488db1
35.150235
126
0.624002
5.374869
false
false
false
false
Davids89/KotlinChuck
app/src/main/java/com/example/david/kotlinchuck/favoriteJokes/ui/FavoriteFragment.kt
1
2581
package com.example.david.kotlinchuck.favoriteJokes.ui import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.david.kotlinchuck.MyApp import com.example.david.kotlinchuck.R import com.example.david.kotlinchuck.entities.Joke import com.example.david.kotlinchuck.favoriteJokes.presenter.FavoriteJokesPresenter import com.example.david.kotlinchuck.favoriteJokes.ui.adapter.JokesAdapter import kotlinx.android.synthetic.main.fragment_favorite.* import org.jetbrains.anko.design.snackbar import org.jetbrains.anko.find import javax.inject.Inject /** * A simple [Fragment] subclass. */ class FavoriteFragment : Fragment(), FavoriteView { @Inject lateinit var presenter: FavoriteJokesPresenter lateinit var adapter: JokesAdapter lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MyApp.favoriteFragmentComponent(this).inject(this) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view: View = inflater!!.inflate(R.layout.fragment_favorite, container, false) setupAdapter() setupRecyclerView(view) presenter.onCreate() return view } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun onDestroy() { super.onDestroy() presenter.onDestroy() } override fun onListJokesSuccess(jokeList: List<Joke>?) { adapter.setJokes(jokeList) } override fun onListJokesError() { snackbar(favoriteContext, "Error") } override fun onDeleteSuccess(jokes: List<Joke>?) { adapter.setJokes(jokes) snackbar(favoriteContext, "Borrado con exito") } override fun onDeleteError() { snackbar(favoriteContext, "Error al borrar") } override fun onDeleteClick(text: String) { presenter.deleteJoke(text) } private fun setupRecyclerView(view: View?) { recyclerView = view!!.find(R.id.savedJokesRecyclerView) recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.adapter = adapter } private fun setupAdapter() { adapter = JokesAdapter(this) } }
apache-2.0
e071bc25095b7d94bfe3a8a28c21ca76
27.677778
89
0.718326
4.434708
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/LinkHeader.kt
1
2124
/* * 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.http /** * Represents a `Link` header value as per RFC 5988 */ public class LinkHeader( uri: String, params: List<HeaderValueParam> ) : HeaderValueWithParameters("<$uri>", params) { @Suppress("unused") public constructor(uri: String, rel: String) : this(uri, listOf(HeaderValueParam(Parameters.Rel, rel))) public constructor(uri: String, vararg rel: String) : this( uri, listOf(HeaderValueParam(Parameters.Rel, rel.joinToString(" "))) ) @Suppress("unused") public constructor( uri: String, rel: List<String>, type: ContentType ) : this( uri, listOf( HeaderValueParam(Parameters.Rel, rel.joinToString(" ")), HeaderValueParam(Parameters.Type, type.toString()) ) ) /** * Link URI part */ public val uri: String get() = content.removePrefix("<").removeSuffix(">") /** * Known Link header parameters */ @Suppress("unused", "KDocMissingDocumentation", "PublicApiImplicitType") public object Parameters { public const val Rel: String = "rel" public const val Anchor: String = "anchor" public const val Rev: String = "Rev" public const val HrefLang: String = "hreflang" public const val Media: String = "media" public const val Title: String = "title" public const val Type: String = "type" } /** * Known rel parameter values */ @Suppress("unused", "KDocMissingDocumentation", "PublicApiImplicitType") public object Rel { public const val Stylesheet: String = "stylesheet" public const val Prefetch: String = "prefetch" public const val DnsPrefetch: String = "dns-prefetch" public const val PreConnect: String = "preconnect" public const val PreLoad: String = "preload" public const val PreRender: String = "prerender" public const val Next: String = "next" } }
apache-2.0
52f26c9c5eca8999ed6dbd88da580ebd
29.342857
118
0.625706
4.37037
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/CacheControl.kt
1
4008
/* * 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.http /** * Represents a value for a `Cache-Control` header * * @param visibility specifies an optional visibility such as private or public */ public sealed class CacheControl(public val visibility: Visibility?) { /** * Controls caching by proxies */ public enum class Visibility(internal val headerValue: String) { /** * Specifies that the response is cacheable by clients and shared (proxy) caches. */ Public("public"), /** * Specifies that the response is cacheable only on the client and not by shared (proxy server) caches. */ Private("private") } /** * Represents a no-cache cache control value */ public class NoCache(visibility: Visibility?) : CacheControl(visibility) { override fun toString(): String = if (visibility == null) { "no-cache" } else { "no-cache, ${visibility.headerValue}" } override fun equals(other: Any?): Boolean { return other is NoCache && visibility == other.visibility } override fun hashCode(): Int { return visibility.hashCode() } } /** * Represents a no-store cache control value */ public class NoStore(visibility: Visibility?) : CacheControl(visibility) { override fun toString(): String = if (visibility == null) { "no-store" } else { "no-store, ${visibility.headerValue}" } override fun equals(other: Any?): Boolean { return other is NoStore && other.visibility == visibility } override fun hashCode(): Int { return visibility.hashCode() } } /** * Represents a cache control value with the specified max ages and re-validation strategies * @property maxAgeSeconds max-age in seconds * @property proxyMaxAgeSeconds max-age in seconds for caching proxies * @property mustRevalidate `true` if a client must validate in spite of age * @property proxyRevalidate `true` if a caching proxy must revalidate in spite of age */ public class MaxAge( public val maxAgeSeconds: Int, public val proxyMaxAgeSeconds: Int? = null, public val mustRevalidate: Boolean = false, public val proxyRevalidate: Boolean = false, visibility: Visibility? = null ) : CacheControl(visibility) { override fun toString(): String { val parts = ArrayList<String>(5) parts.add("max-age=$maxAgeSeconds") if (proxyMaxAgeSeconds != null) { parts.add("s-maxage=$proxyMaxAgeSeconds") } if (mustRevalidate) { parts.add("must-revalidate") } if (proxyRevalidate) { parts.add("proxy-revalidate") } if (visibility != null) { parts.add(visibility.headerValue) } return parts.joinToString(", ") } override fun equals(other: Any?): Boolean { return other === this || ( other is MaxAge && other.maxAgeSeconds == maxAgeSeconds && other.proxyMaxAgeSeconds == proxyMaxAgeSeconds && other.mustRevalidate == mustRevalidate && other.proxyRevalidate == proxyRevalidate && other.visibility == visibility ) } override fun hashCode(): Int { var result = maxAgeSeconds result = 31 * result + (proxyMaxAgeSeconds ?: 0) result = 31 * result + mustRevalidate.hashCode() result = 31 * result + proxyRevalidate.hashCode() result = 31 * result + visibility.hashCode() return result } } }
apache-2.0
5428569551769569f79bde61c513eebd
32.4
118
0.574601
5.171613
false
false
false
false
carrotengineer/Warren
src/main/kotlin/engineer/carrot/warren/warren/handler/CapAckHandler.kt
2
2203
package engineer.carrot.warren.warren.handler import engineer.carrot.warren.kale.IKaleHandler import engineer.carrot.warren.kale.irc.message.extension.cap.CapAckMessage import engineer.carrot.warren.kale.irc.message.extension.sasl.AuthenticateMessage import engineer.carrot.warren.warren.IMessageSink import engineer.carrot.warren.warren.extension.cap.CapLifecycle import engineer.carrot.warren.warren.extension.cap.CapState import engineer.carrot.warren.warren.extension.cap.ICapManager import engineer.carrot.warren.warren.extension.sasl.SaslState import engineer.carrot.warren.warren.handler.helper.RegistrationHelper import engineer.carrot.warren.warren.loggerFor import engineer.carrot.warren.warren.state.AuthLifecycle class CapAckHandler(val capState: CapState, val saslState: SaslState, val sink: IMessageSink, val capManager: ICapManager) : IKaleHandler<CapAckMessage> { private val LOGGER = loggerFor<CapAckHandler>() override val messageType = CapAckMessage::class.java override fun handle(message: CapAckMessage, tags: Map<String, String?>) { val caps = message.caps val lifecycle = capState.lifecycle LOGGER.trace("server ACKed following caps: $caps") capState.accepted += caps caps.forEach { capManager.capEnabled(it) } if (caps.contains("sasl") && saslState.shouldAuth) { LOGGER.trace("server acked sasl - starting authentication for user: ${saslState.credentials?.account}") saslState.lifecycle = AuthLifecycle.AUTHING sink.write(AuthenticateMessage(payload = "PLAIN", isEmpty = false)) } when (lifecycle) { CapLifecycle.NEGOTIATING -> { LOGGER.trace("server ACKed some caps, checked if it's the last reply") if (RegistrationHelper.shouldEndCapNegotiation(saslState, capState)) { RegistrationHelper.endCapNegotiation(sink, capState) } else { LOGGER.trace("didn't think we should end the registration process, waiting") } } else -> LOGGER.trace("server ACKed caps but we don't think we're negotiating") } } }
isc
de0a928d080c95c7c54282f24c354bf0
39.796296
154
0.711303
4.26938
false
false
false
false
rs3vans/krypto
src/main/kotlin/com/github/rs3vans/krypto/ciphers.kt
1
7127
package com.github.rs3vans.krypto import java.security.* import javax.crypto.* import javax.crypto.Cipher.* import javax.crypto.spec.* /** * A simple base class that defines a cipher which wraps an instance [Cipher] along with a [Key]. */ abstract class ConcreteCipher { abstract val jdkCipher: Cipher abstract val key: Key abstract val provider: KryptoProvider val algorithm: String get() = jdkCipher.algorithm val blockSize: Int get() = jdkCipher.blockSize protected inline fun <X> withCipher(action: Cipher.() -> X): X = synchronized(jdkCipher) { action.invoke(jdkCipher) } } /** * Represents data that is _not_ encrypted (and may have been the result of a [decryption][DecryptCipher.decrypt]). */ data class Decrypted(val bytes: Bytes, val initVector: Bytes? = null, val additionalAuthenticatedData: Bytes? = null) /** * Represents data that _is_ encrypted (and may have been the result of an [encryption][EncryptCipher.encrypt]). */ data class Encrypted(val bytes: Bytes, val initVector: Bytes? = null, val authenticationTag: Bytes? = null, val additionalAuthenticatedData: Bytes? = null) /** * A contract for a cipher that can [encrypt] an instance of [Decrypted], producing an instance of [Encrypted]. */ interface EncryptCipher { fun encrypt(decrypted: Decrypted): Encrypted } /** * A contract for a cipher that can [decrypt] an instance of [Encrypted], producing an instance of [Decrypted]. */ interface DecryptCipher { fun decrypt(encrypted: Encrypted): Decrypted } /** * An [encrypting][EncryptCipher]/[decrypting][DecryptCipher] cipher which uses the chained-block mode (CBC). */ class BlockCipher(override val key: SecretKey, padded: Boolean = true, override val provider: KryptoProvider = KryptoProvider.defaultInstance) : ConcreteCipher(), EncryptCipher, DecryptCipher { override val jdkCipher = provider.cipher("${key.algorithm}/CBC/${if (padded) "PKCS5Padding" else "NoPadding"}") override fun encrypt(decrypted: Decrypted): Encrypted = withCipher { if (decrypted.initVector != null) { init(ENCRYPT_MODE, key, IvParameterSpec(decrypted.initVector.byteArray)) } else { init(ENCRYPT_MODE, key) } Encrypted( Bytes(doFinal(decrypted.bytes.byteArray)), initVector = Bytes(iv) ) } override fun decrypt(encrypted: Encrypted): Decrypted = withCipher { val iv = encrypted.initVector ?: throw IllegalArgumentException( "initialization vector (IV) required for decryption" ) init(DECRYPT_MODE, key, IvParameterSpec(iv.byteArray)) Decrypted(Bytes(doFinal(encrypted.bytes.byteArray))) } } /** * An [encrypting][EncryptCipher]/[decrypting][DecryptCipher] cipher which uses the Galois-counter mode (GCM). */ class AuthenticatingBlockCipher(override val key: SecretKey, override val provider: KryptoProvider = KryptoProvider.defaultInstance) : ConcreteCipher(), EncryptCipher, DecryptCipher { override val jdkCipher = provider.cipher("${key.algorithm}/GCM/NoPadding") override fun encrypt(decrypted: Decrypted): Encrypted = withCipher { if (decrypted.initVector != null) { init(ENCRYPT_MODE, key, GCMParameterSpec(blockSize * 8, decrypted.initVector.byteArray)) } else { init(ENCRYPT_MODE, key) } if (decrypted.additionalAuthenticatedData != null) { updateAAD(decrypted.additionalAuthenticatedData.byteArray) } val encBytes = doFinal(decrypted.bytes.byteArray) val tagOffset = encBytes.size - blockSize Encrypted( Bytes(encBytes.copyOfRange(0, tagOffset)), initVector = Bytes(iv), authenticationTag = Bytes(encBytes.copyOfRange(tagOffset, encBytes.size)) ) } override fun decrypt(encrypted: Encrypted): Decrypted = withCipher { val iv = encrypted.initVector ?: throw IllegalArgumentException( "initialization vector (IV) required for decryption" ) val tag = encrypted.authenticationTag ?: throw IllegalArgumentException( "authentication tag required for decryption" ) init(DECRYPT_MODE, key, GCMParameterSpec(blockSize * 8, iv.byteArray)) if (encrypted.additionalAuthenticatedData != null) { updateAAD(encrypted.additionalAuthenticatedData.byteArray) } Decrypted(Bytes(doFinal(encrypted.bytes.byteArray + tag.byteArray))) } } /** * An [encrypting-only][EncryptCipher] cipher which uses an RSA-based [PublicKey] for encryption. */ class AsymmetricEncryptCipher(override val key: PublicKey, override val provider: KryptoProvider = KryptoProvider.defaultInstance) : ConcreteCipher(), EncryptCipher { init { if (key.algorithm != "RSA") { throw IllegalArgumentException("invalid key algorithm: ${key.algorithm} (expected: RSA)") } } override val jdkCipher = provider.cipher("RSA/ECB/PKCS1Padding") override fun encrypt(decrypted: Decrypted): Encrypted = withCipher { init(ENCRYPT_MODE, key) Encrypted(Bytes(doFinal(decrypted.bytes.byteArray))) } } /** * An [decrypting-only][DecryptCipher] cipher which uses an RSA-based [PrivateKey] for decryption. */ class AsymmetricDecryptCipher(override val key: PrivateKey, override val provider: KryptoProvider = KryptoProvider.defaultInstance) : ConcreteCipher(), DecryptCipher { init { if (key.algorithm != "RSA") { throw IllegalArgumentException("invalid key algorithm: ${key.algorithm} (expected: RSA)") } } override val jdkCipher = provider.cipher("RSA/ECB/PKCS1Padding") override fun decrypt(encrypted: Encrypted): Decrypted = withCipher { init(DECRYPT_MODE, key) Decrypted(Bytes(doFinal(encrypted.bytes.byteArray))) } } /** * An [encrypting][EncryptCipher]/[decrypting][DecryptCipher] cipher which wraps both an [AsymmetricEncryptCipher] and * a [AsymmetricDecryptCipher]. */ class AsymmetricCipherPair(val encryptCipher: AsymmetricEncryptCipher, val decryptCipher: AsymmetricDecryptCipher) : EncryptCipher by encryptCipher, DecryptCipher by decryptCipher { constructor(publicKey: PublicKey, privateKey: PrivateKey, provider: KryptoProvider = KryptoProvider.defaultInstance) : this( AsymmetricEncryptCipher(publicKey, provider), AsymmetricDecryptCipher(privateKey, provider) ) constructor(keyPair: KeyPair, provider: KryptoProvider = KryptoProvider.defaultInstance) : this( keyPair.public, keyPair.private, provider ) }
mit
47062cf6079a90d42c1310924d2a8960
34.819095
118
0.654132
4.618924
false
false
false
false
e16din/LightUtils
LightUtils/src/main/java/com/e16din/lightutils/utils/IdUtils.kt
1
2415
package com.e16din.lightutils.utils import android.app.Activity import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.provider.Settings import android.telephony.TelephonyManager import com.e16din.topactivity.app import java.util.* /** * Created by e16din on 14.08.15. */ open class IdUtils : SocialUtils() { companion object { val imei: String get() { val tm = app?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager return tm.deviceId } // for android sdk >= 9 val udid: String get() = Settings.Secure.getString(app?.contentResolver, Settings.Secure.ANDROID_ID) val packageVersionName: String @Throws(PackageManager.NameNotFoundException::class) get() = packageInfo.versionName val versionCode: Int @Throws(PackageManager.NameNotFoundException::class) get() = packageInfo.versionCode val packageInfo: PackageInfo @Throws(PackageManager.NameNotFoundException::class) get() { val context = app!! return context.packageManager.getPackageInfo(context.packageName, 0) } fun getDevGuid(activity: Activity): String { val tm = activity.baseContext .getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val tmDevice = "" + tm.deviceId val tmSerial = "" + tm.simSerialNumber val androidId = "" + android.provider.Settings.Secure.getString(activity.contentResolver, android.provider.Settings.Secure.ANDROID_ID) val deviceUuid = UUID(androidId.hashCode().toLong(), tmDevice.hashCode().toLong() shl 32 or tmSerial.hashCode().toLong()) return deviceUuid.toString() } fun getAppGuid(activity: Activity): String { val androidId = "" + android.provider.Settings.Secure.getString(activity.contentResolver, android.provider.Settings.Secure.ANDROID_ID) val deviceUuid = UUID(androidId.hashCode().toLong(), System.currentTimeMillis()) return deviceUuid.toString() } fun randomUUID(): String { return UUID.randomUUID().toString() } } }
mit
e6e83e7891c631ba68402cf1d296fe28
33.014085
101
0.629814
5
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/internal/api/inputs.kt
2
2021
package imgui.internal.api import gli_.has import imgui.* import imgui.ImGui.io import imgui.api.g /** Inputs * FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. */ internal interface inputs { fun setItemUsingMouseWheel() { val id = g.currentWindow!!.dc.lastItemId if (g.hoveredId == id) g.hoveredIdUsingMouseWheel = true if (g.activeId == id) g.activeIdUsingMouseWheel = true } infix fun isActiveIdUsingNavDir(dir: Dir): Boolean = g.activeIdUsingNavDirMask has (1 shl dir) infix fun isActiveIdUsingNavInput(input: NavInput): Boolean = g.activeIdUsingNavInputMask has (1 shl input) infix fun isActiveIdUsingKey(key: Key): Boolean { assert(key.i < 64) return g.activeIdUsingKeyInputMask.and(1L shl key.i) != 0L // TODO Long.has } /** Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. * [Internal] This doesn't test if the button is pressed */ fun isMouseDragPastThreshold(button: MouseButton, lockThreshold_: Float): Boolean { assert(button.i in io.mouseDown.indices) if (!io.mouseDown[button.i]) return false var lockThreshold = lockThreshold_ if (lockThreshold < 0f) lockThreshold = io.mouseDragThreshold return io.mouseDragMaxDistanceSqr[button.i] >= lockThreshold * lockThreshold } // the rest of inputs functions are in the NavInput enum /** ~GetMergedKeyModFlags */ val mergedKeyModFlags: KeyModFlags get() { var keyModFlags: KeyModFlags = KeyMod.None.i if (ImGui.io.keyCtrl) keyModFlags = keyModFlags or KeyMod.Ctrl.i if (ImGui.io.keyShift) keyModFlags = keyModFlags or KeyMod.Shift.i if (ImGui.io.keyAlt) keyModFlags = keyModFlags or KeyMod.Alt.i if (ImGui.io.keySuper) keyModFlags = keyModFlags or KeyMod.Super.i return keyModFlags } }
mit
06781498392bf6dd2b436c934e66bc35
37.150943
113
0.67046
3.894027
false
false
false
false
octarine-noise/BetterFoliage
src/main/kotlin/mods/betterfoliage/client/render/Utils.kt
1
2504
@file:JvmName("Utils") package mods.betterfoliage.client.render import mods.octarinecore.PI2 import mods.octarinecore.client.render.* import mods.octarinecore.common.Double3 import mods.octarinecore.common.Int3 import mods.octarinecore.common.Rotation import mods.octarinecore.common.times import net.minecraft.block.Block import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.util.BlockRenderLayer import net.minecraft.util.EnumFacing import net.minecraft.util.EnumFacing.* val up1 = Int3(1 to UP) val up2 = Int3(2 to UP) val down1 = Int3(1 to DOWN) val snowOffset = UP * 0.0625 val normalLeavesRot = arrayOf(Rotation.identity) val denseLeavesRot = arrayOf(Rotation.identity, Rotation.rot90[EAST.ordinal], Rotation.rot90[SOUTH.ordinal]) val whitewash: PostProcessLambda = { _, _, _, _, _ -> setGrey(1.4f) } val greywash: PostProcessLambda = { _, _, _, _, _ -> setGrey(1.0f) } val IBlockState.isSnow: Boolean get() = material.let { it == Material.SNOW || it == Material.CRAFTED_SNOW } fun Quad.toCross(rotAxis: EnumFacing, trans: (Quad)->Quad) = (0..3).map { rotIdx -> trans(rotate(Rotation.rot90[rotAxis.ordinal] * rotIdx).mirrorUV(rotIdx > 1, false)) } fun Quad.toCross(rotAxis: EnumFacing) = toCross(rotAxis) { it } fun xzDisk(modelIdx: Int) = (PI2 * modelIdx / 64.0).let { Double3(Math.cos(it), 0.0, Math.sin(it)) } val rotationFromUp = arrayOf( Rotation.rot90[EAST.ordinal] * 2, Rotation.identity, Rotation.rot90[WEST.ordinal], Rotation.rot90[EAST.ordinal], Rotation.rot90[SOUTH.ordinal], Rotation.rot90[NORTH.ordinal] ) fun Model.mix(first: Model, second: Model, predicate: (Int)->Boolean) { first.quads.forEachIndexed { qi, quad -> val otherQuad = second.quads[qi] Quad( if (predicate(0)) otherQuad.v1.copy() else quad.v1.copy(), if (predicate(1)) otherQuad.v2.copy() else quad.v2.copy(), if (predicate(2)) otherQuad.v3.copy() else quad.v3.copy(), if (predicate(3)) otherQuad.v4.copy() else quad.v4.copy() ).add() } } val BlockRenderLayer.isCutout: Boolean get() = (this == BlockRenderLayer.CUTOUT) || (this == BlockRenderLayer.CUTOUT_MIPPED) fun IBlockState.canRenderInLayer(layer: BlockRenderLayer) = this.block.canRenderInLayer(this, layer) fun IBlockState.canRenderInCutout() = this.block.canRenderInLayer(this, BlockRenderLayer.CUTOUT) || this.block.canRenderInLayer(this, BlockRenderLayer.CUTOUT_MIPPED)
mit
dad78b6921f56b411a22a59a8cdd12f2
39.403226
165
0.717252
3.273203
false
false
false
false
CrystalLord/plounge-quoter
src/main/kotlin/org/crystal/ploungequoter/SetupParser.kt
1
12495
package org.crystal.ploungequoter import java.awt.Color import java.io.File import java.awt.Font class SetupParser { companion object { /** * Read a quote file. * * @param[file] The File object of the quote file to read. * @return Returns a quoteInfo object, from which a set of text * objects can be generated. */ fun readQuoteFile(file: File): SetupOutput { // Background quote file var bgFile: File? = null // The type of file output. (png, jpg) var outputType: String = PNGTYPE // The source for the quote. var source: String = "" // Make a new QuoteInfo list to represent all the quotes. val quoteInfos: ArrayList<QuoteInfo> = arrayListOf() // Grab all the lines in the files val lines: List<String> = file.readLines() // The index of the current quote we are parsing. var quoteInd: Int = -1 // "i" is the iteration index for the key value pair. // It technically represents the line index, but due to the // ability for a parameter to span several lines, it's important // to allow i to arbitrarily jump around. var i: Int = 0 while (i < lines.size) { val stripedLine = Utils.stripBlank(lines[i]) // First, check the empty line case. If the line is empty, // skip it. if (stripedLine == "") { i++ continue } // If a line says "quote", then the following parameters // belong to that quote. if (stripedLine == "quote") { quoteInd++ quoteInfos.add(QuoteInfo()) i++ continue } // ------------------------------------------------------------- // Strip the line on the first colon. val lineList: List<String> = stripedLine.split(':', limit=2) // Make sure there actually is a colon in there. if (lineList.size < 2) { throw RuntimeException( "Parameter line "+(i+1).toString()+" did not " + "have a colon" ) } // ------------------------------------------------------------- // Retrieve the parameter name and the value. val parameterName: String = lineList[0] var value: String = Utils.stripBlank(lineList[1]) // ------------------------------------------------------------- // Does the value line end in a backslash? var lineContinues: Boolean = (lineList[1].last() == '\\') // Handle continuation lines if there's a backslash at the end. var count: Int = 0 while (lineContinues) { count++ // Go to the next line. val nextLine = Utils.stripBlank(lines[i+count]) value = value.substring(0,value.length-1) + nextLine lineContinues = (nextLine.last() == '\\') } i += count // Make sure the entire parser also moves forwards. // ------------------------------------------------------------- // Catch cases where a quote line hasn't been set. if (quoteInd < 0) { when (parameterName) { "background" -> { // Allow both local file reading and URL parsing. // Retrieve the background regardless if it's a URL // or a local file. val backgroundRetriever: BackgroundRetriever = BackgroundRetriever(value) // Set the retrieved file. bgFile = backgroundRetriever.file i++ // Remember to increment i } "source" -> { source = value i++ } "outputtype" -> { outputType = value i++ } else -> { // If the global variable doesn't exist... throw RuntimeException("Global parameter \"" + parameterName + "\" not found.") } } continue } // Send the parameter and value off to the interpreter. // This will modify the QuoteInfo object we need. SetupParser.interpretQuoteParameter( quoteInfos[quoteInd], parameterName, value ) // Remember to increment i i++ } // Return the combined output in SetupOutput object. if (bgFile != null) { return SetupOutput(bgFile, quoteInfos, outputType, source) } else { throw RuntimeException("Background File Not Set.") } } /** * Edit a quoteInfo object with the given parameter and value. * * @param[quoteInfo] QuoteInfo object to modify. * @param[param] Parameter name. * @param[value] Value of the parameter. Note, it cannot have any * leading or trailing spaces. * @post The input [quoteInfo] is modified with the new param's value. */ private fun interpretQuoteParameter( quoteInfo: QuoteInfo, param: String, value: String ) { when (param) { "anchor" -> { when (Utils.stripBlank(value.toLowerCase())) { "topleft" -> quoteInfo.anchor = Anchor.TOP_LEFT "topright" -> quoteInfo.anchor = Anchor.TOP_RIGHT "botleft" -> quoteInfo.anchor = Anchor.BOT_LEFT "botright" -> quoteInfo.anchor = Anchor.BOT_RIGHT "topcentre" -> quoteInfo.anchor = Anchor.TOP_CENTER "botcentre" -> quoteInfo.anchor = Anchor.BOT_CENTER "centrecentre" -> quoteInfo.anchor = Anchor.CENTER_CENTER else -> throw RuntimeException("Invalid Anchor") } } "alignment" -> { when (value) { "left" -> quoteInfo.alignment = Alignment.LEFT "right" -> quoteInfo.alignment = Alignment.RIGHT "centre" -> quoteInfo.alignment = Alignment.CENTER else -> throw RuntimeException("Invalid Alignment") } } "author" -> quoteInfo.author = value.replace("\\n","\n") "authorfontsize" -> quoteInfo.authorFontSize = value.toInt() "authorfontstyle" -> { when (value) { "plain" -> quoteInfo.authorFontStyle = Font.PLAIN "italic" -> quoteInfo.authorFontStyle = Font.ITALIC "bold" -> quoteInfo.authorFontStyle = Font.BOLD "italicbold" -> quoteInfo.authorFontStyle = Font.ITALIC + Font.BOLD } } "authormargin" -> { val xy: List<String> = value.split(",") try { quoteInfo.authorXMargin = Utils.stripBlank(xy[0]).toInt() quoteInfo.authorYMargin = Utils.stripBlank(xy[1]).toInt() } catch (e: RuntimeException) { throw RuntimeException("authormargin parameter not in" + " correct format.") } } "authorposition" -> { when (value) { "botleft" -> quoteInfo.authorPos = AuthorPos.BOT_LEFT "botright" -> quoteInfo.authorPos = AuthorPos.BOT_RIGHT "botleftattached" -> quoteInfo.authorPos = AuthorPos .BOT_LEFT_ATTACHED "botrightattached" -> quoteInfo.authorPos = AuthorPos .BOT_RIGHT_ATTACHED } } "typeface" -> quoteInfo.typefaceName = value "content" -> quoteInfo.content = value.replace("\\n","\n") "contentfontsize" -> quoteInfo.contentFontSize = value.toInt() "contentfontstyle" -> { when (value) { "plain" -> quoteInfo.contentFontStyle = Font.PLAIN "italic" -> quoteInfo.contentFontStyle = Font.ITALIC "bold" -> quoteInfo.contentFontStyle = Font.BOLD "italicbold" -> quoteInfo.contentFontStyle = Font.ITALIC + Font.BOLD } } "contentwrap" -> { val xy: List<String> = value.split(",") if (xy.size != 2) { throw RuntimeException("contentwrap not in correct " + "format.") } quoteInfo.contentLeftBound = Utils.stripBlank(xy[0]) .toFloat() quoteInfo.contentRightBound = Utils.stripBlank(xy[1]) .toFloat() } "fillcolour" -> { val cl: List<Int> = value.split(",").map { s -> Utils.stripBlank(s).toInt() } try { quoteInfo.fillColor = Color(cl[0], cl[1], cl[2], cl[3]) } catch (e: IllegalArgumentException) { throw IllegalArgumentException( "Colour parameter not using valid values." ) } } "outlinecolour" -> { val cl: List<Int> = value.split(",").map { s -> s.toInt() } try { quoteInfo.outlineColor = Color(cl[0], cl[1], cl[2], cl[3]) } catch (e: IllegalArgumentException) { throw IllegalArgumentException( "Colour parameter not using valid values." ) } } "position" -> { val xy: List<String> = value.split(",") if (xy.size != 2) { throw RuntimeException("contentwrap not in correct " + "format.") } quoteInfo.position = Vector2( Utils.stripBlank(xy[0]).toFloat(), Utils.stripBlank(xy[1]).toFloat() ) } "positiontype" -> { when (value) { "img" -> quoteInfo.positionType = QuotePosType.IMAGE "abs" -> quoteInfo.positionType = QuotePosType.ABS else -> throw RuntimeException("Invalid positiontype.") } } else -> { throw RuntimeException( "Unknown Parameter given: " +param ) } } } } }
apache-2.0
98930b42dc705e412ebadc12df733a88
42.688811
80
0.410964
5.90222
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/constructors/genericIdentifier.kt
13
657
class Identifier<T> { val name: T private var myHasDollar = false private var myNullable = true constructor(name: T) { this.name = name } constructor(name: T, isNullable: Boolean) { this.name = name myNullable = isNullable } constructor(name: T, hasDollar: Boolean, isNullable: Boolean) { this.name = name myHasDollar = hasDollar myNullable = isNullable } } object User { fun main() { val i1: Identifier<*> = Identifier("name", false, true) val i2: Identifier<*> = Identifier("name", false) val i3: Identifier<*> = Identifier("name") } }
apache-2.0
0c1fee8a4bb1a4e8d117ca8750540e94
22.5
67
0.587519
4.055556
false
false
false
false
dahlstrom-g/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/authentication/ui/GitLabAccountsDetailsLoader.kt
5
2395
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gitlab.authentication.ui import com.intellij.collaboration.auth.ui.AccountsDetailsLoader import com.intellij.collaboration.auth.ui.AccountsDetailsLoader.Result import com.intellij.openapi.components.service import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import org.jetbrains.plugins.gitlab.api.GitLabApi import org.jetbrains.plugins.gitlab.api.GitLabApiManager import org.jetbrains.plugins.gitlab.api.dto.GitLabUserDto import org.jetbrains.plugins.gitlab.api.request.getCurrentUser import org.jetbrains.plugins.gitlab.api.request.loadImage import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccount import org.jetbrains.plugins.gitlab.authentication.accounts.GitLabAccountManager import org.jetbrains.plugins.gitlab.ui.GitLabBundle import java.awt.Image internal class GitLabAccountsDetailsLoader(private val coroutineScope: CoroutineScope, private val accountManager: GitLabAccountManager, private val accountsModel: GitLabAccountsListModel) : AccountsDetailsLoader<GitLabAccount, GitLabUserDto> { override fun loadDetailsAsync(account: GitLabAccount): Deferred<Result<GitLabUserDto>> = coroutineScope.async { loadDetails(account) } private suspend fun loadDetails(account: GitLabAccount): Result<GitLabUserDto> { val api = getApiClient(account) ?: return Result.Error(GitLabBundle.message("account.token.missing"), true) val details = api.getCurrentUser(account.server) ?: return Result.Error(GitLabBundle.message("account.token.invalid"), true) return Result.Success(details) } override fun loadAvatarAsync(account: GitLabAccount, url: String): Deferred<Image?> = coroutineScope.async { loadAvatar(account, url) } private suspend fun loadAvatar(account: GitLabAccount, url: String): Image? { val api = getApiClient(account) ?: return null return api.loadImage(url) } private fun getApiClient(account: GitLabAccount): GitLabApi? { val token = accountsModel.newCredentials.getOrElse(account) { accountManager.findCredentials(account) } ?: return null return service<GitLabApiManager>().getClient(token) } }
apache-2.0
209480ff34f3148b70c154b21ae28bf7
46.92
128
0.778706
4.518868
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/vma/src/templates/kotlin/vma/VMATypes.kt
1
34938
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package vma import org.lwjgl.generator.* import vulkan.* val VmaAllocation = "VmaAllocation".handle val VmaAllocator = "VmaAllocator".handle val VmaDefragmentationContext = "VmaDefragmentationContext".handle val VmaPool = "VmaPool".handle val VmaVirtualAllocation = "VmaVirtualAllocation".handle val VmaVirtualBlock = "VmaVirtualBlock".handle val VmaAllocationCreateFlags = "VmaAllocationCreateFlags".enumType val VmaAllocatorCreateFlags = "VmaAllocatorCreateFlags".enumType val VmaDefragmentationFlags = "VmaDefragmentationFlags".enumType val VmaMemoryUsage = "VmaMemoryUsage".enumType val VmaPoolCreateFlags = "VmaPoolCreateFlags".enumType val VmaVirtualAllocationCreateFlags = typedef(VkFlags, "VmaVirtualAllocationCreateFlags") val VmaVirtualBlockCreateFlagBits = "VmaVirtualBlockCreateFlagBits".enumType val PFN_vmaAllocateDeviceMemoryFunction = Module.VMA.callback { void( "VmaAllocateDeviceMemoryFunction", "Called after successful {@code vkAllocateMemory}.", VmaAllocator("allocator", ""), uint32_t("memoryType", ""), VkDeviceMemory("memory", ""), VkDeviceSize("size", ""), nullable..opaque_p("pUserData", ""), nativeType = "PFN_vmaAllocateDeviceMemoryFunction" ) { documentation = "Instances of this interface may be set to the ##VmaDeviceMemoryCallbacks struct." } } val PFN_vmaFreeDeviceMemoryFunction = Module.VMA.callback { void( "VmaFreeDeviceMemoryFunction", "Called before {@code vkFreeMemory}.", VmaAllocator("allocator", ""), uint32_t("memoryType", ""), VkDeviceMemory("memory", ""), VkDeviceSize("size", ""), nullable..opaque_p("pUserData", ""), nativeType = "PFN_vmaFreeDeviceMemoryFunction" ) { documentation = "Instances of this interface may be set to the ##VmaDeviceMemoryCallbacks struct." } } val VmaDeviceMemoryCallbacks = struct(Module.VMA, "VmaDeviceMemoryCallbacks") { documentation = """ Set of callbacks that the library will call for {@code vkAllocateMemory} and {@code vkFreeMemory}. Provided for informative purpose, e.g. to gather statistics about number of allocations or total amount of memory allocated in Vulkan. Used in ##VmaAllocatorCreateInfo{@code ::pDeviceMemoryCallbacks}. """ nullable..PFN_vmaAllocateDeviceMemoryFunction("pfnAllocate", "") nullable..PFN_vmaFreeDeviceMemoryFunction("pfnFree", "") nullable..opaque_p("pUserData", "") } val VmaVulkanFunctions = struct(Module.VMA, "VmaVulkanFunctions", skipBuffer = true) { javaImport("org.lwjgl.vulkan.*") documentation = """ Pointers to some Vulkan functions - a subset used by the library. Used in ##VmaAllocatorCreateInfo{@code ::pVulkanFunctions}. """ nullable.."PFN_vkGetInstanceProcAddr".handle("vkGetInstanceProcAddr", "") nullable.."PFN_vkGetDeviceProcAddr".handle("vkGetDeviceProcAddr", "") "PFN_vkGetPhysicalDeviceProperties".handle("vkGetPhysicalDeviceProperties", "") "PFN_vkGetPhysicalDeviceMemoryProperties".handle("vkGetPhysicalDeviceMemoryProperties", "") "PFN_vkAllocateMemory".handle("vkAllocateMemory", "") "PFN_vkFreeMemory".handle("vkFreeMemory", "") "PFN_vkMapMemory".handle("vkMapMemory", "") "PFN_vkUnmapMemory".handle("vkUnmapMemory", "") "PFN_vkFlushMappedMemoryRanges".handle("vkFlushMappedMemoryRanges", "") "PFN_vkInvalidateMappedMemoryRanges".handle("vkInvalidateMappedMemoryRanges", "") "PFN_vkBindBufferMemory".handle("vkBindBufferMemory", "") "PFN_vkBindImageMemory".handle("vkBindImageMemory", "") "PFN_vkGetBufferMemoryRequirements".handle("vkGetBufferMemoryRequirements", "") "PFN_vkGetImageMemoryRequirements".handle("vkGetImageMemoryRequirements", "") "PFN_vkCreateBuffer".handle("vkCreateBuffer", "") "PFN_vkDestroyBuffer".handle("vkDestroyBuffer", "") "PFN_vkCreateImage".handle("vkCreateImage", "") "PFN_vkDestroyImage".handle("vkDestroyImage", "") "PFN_vkCmdCopyBuffer".handle("vkCmdCopyBuffer", "") nullable.."PFN_vkGetBufferMemoryRequirements2KHR".handle( "vkGetBufferMemoryRequirements2KHR", """ {@code vkGetBufferMemoryRequirements2} on Vulkan &ge; 1.1, {@code vkGetBufferMemoryRequirements2KHR} when using {@code VK_KHR_dedicated_allocation} extension. """ ) nullable.."PFN_vkGetImageMemoryRequirements2KHR".handle( "vkGetImageMemoryRequirements2KHR", """ {@code vkGetImageMemoryRequirements2} on Vulkan &ge; 1.1, {@code vkGetImageMemoryRequirements2KHR} when using {@code VK_KHR_dedicated_allocation} extension. """ ) nullable.."PFN_vkBindBufferMemory2KHR".handle( "vkBindBufferMemory2KHR", "{@code vkBindBufferMemory2} on Vulkan &ge; 1.1, {@code vkBindBufferMemory2KHR} when using {@code VK_KHR_bind_memory2} extension." ) nullable.."PFN_vkBindImageMemory2KHR".handle( "vkBindImageMemory2KHR", "{@code vkBindImageMemory2} on Vulkan &ge; 1.1, {@code vkBindImageMemory2KHR} when using {@code VK_KHR_bind_memory2} extension." ) nullable.."PFN_vkGetPhysicalDeviceMemoryProperties2KHR".handle("vkGetPhysicalDeviceMemoryProperties2KHR", "") nullable.."PFN_vkGetDeviceBufferMemoryRequirements".handle("vkGetDeviceBufferMemoryRequirements", "") nullable.."PFN_vkGetDeviceImageMemoryRequirements".handle("vkGetDeviceImageMemoryRequirements", "") customMethod(""" /** * Helper method that populates this struct with required Vulkan function pointers from the specified Vulkan instance and device. * * @param instance a Vulkan instance * @param device a Vulkan device */ public VmaVulkanFunctions set(VkInstance instance, VkDevice device) { VKCapabilitiesInstance ic = instance.getCapabilities(); VKCapabilitiesDevice dc = device.getCapabilities(); this .vkGetInstanceProcAddr(NULL) .vkGetDeviceProcAddr(NULL) .vkGetPhysicalDeviceProperties(ic.vkGetPhysicalDeviceProperties) .vkGetPhysicalDeviceMemoryProperties(ic.vkGetPhysicalDeviceMemoryProperties) .vkAllocateMemory(dc.vkAllocateMemory) .vkFreeMemory(dc.vkFreeMemory) .vkMapMemory(dc.vkMapMemory) .vkUnmapMemory(dc.vkUnmapMemory) .vkFlushMappedMemoryRanges(dc.vkFlushMappedMemoryRanges) .vkInvalidateMappedMemoryRanges(dc.vkInvalidateMappedMemoryRanges) .vkBindBufferMemory(dc.vkBindBufferMemory) .vkBindImageMemory(dc.vkBindImageMemory) .vkGetBufferMemoryRequirements(dc.vkGetBufferMemoryRequirements) .vkGetImageMemoryRequirements(dc.vkGetImageMemoryRequirements) .vkCreateBuffer(dc.vkCreateBuffer) .vkDestroyBuffer(dc.vkDestroyBuffer) .vkCreateImage(dc.vkCreateImage) .vkDestroyImage(dc.vkDestroyImage) .vkCmdCopyBuffer(dc.vkCmdCopyBuffer) .vkGetBufferMemoryRequirements2KHR(dc.vkGetBufferMemoryRequirements2 != NULL ? dc.vkGetBufferMemoryRequirements2 : dc.vkGetBufferMemoryRequirements2KHR) .vkGetImageMemoryRequirements2KHR(dc.vkGetImageMemoryRequirements2 != NULL ? dc.vkGetImageMemoryRequirements2 : dc.vkGetImageMemoryRequirements2KHR) .vkBindBufferMemory2KHR(dc.vkBindBufferMemory2 != NULL ? dc.vkBindBufferMemory2 : dc.vkBindBufferMemory2KHR) .vkBindImageMemory2KHR(dc.vkBindImageMemory2 != NULL ? dc.vkBindImageMemory2 : dc.vkBindImageMemory2KHR) .vkGetPhysicalDeviceMemoryProperties2KHR(ic.vkGetPhysicalDeviceMemoryProperties2 != NULL ? ic.vkGetPhysicalDeviceMemoryProperties2 : ic.vkGetPhysicalDeviceMemoryProperties2KHR) .vkGetDeviceBufferMemoryRequirements(dc.vkGetDeviceBufferMemoryRequirements != NULL ? dc.vkGetDeviceBufferMemoryRequirements : dc.vkGetDeviceBufferMemoryRequirementsKHR) .vkGetDeviceImageMemoryRequirements(dc.vkGetDeviceImageMemoryRequirements != NULL ? dc.vkGetDeviceImageMemoryRequirements : dc.vkGetDeviceImageMemoryRequirementsKHR); return this; }""") } val VmaAllocatorCreateInfo = struct(Module.VMA, "VmaAllocatorCreateInfo", skipBuffer = true) { javaImport("org.lwjgl.vulkan.*") documentation = "Description of an Allocator to be created." VmaAllocatorCreateFlags("flags", "flags for created allocator. Use {@code VmaAllocatorCreateFlagBits} enum.").links("ALLOCATOR_CREATE_\\w+") VkPhysicalDevice("physicalDevice", "Vulkan physical device. It must be valid throughout whole lifetime of created allocator.") VkDevice("device", "Vulkan device. It must be valid throughout whole lifetime of created allocator.") VkDeviceSize( "preferredLargeHeapBlockSize", """ preferred size of a single {@code VkDeviceMemory} block to be allocated from large heaps &gt; 1 GiB. Set to 0 to use default, which is currently 256 MiB. Optional. """ ) nullable..VkAllocationCallbacks.const.p( "pAllocationCallbacks", "custom CPU memory allocation callbacks. Optional, can be null. When specified, will also be used for all CPU-side memory allocations. Optional." ) nullable..VmaDeviceMemoryCallbacks.const.p( "pDeviceMemoryCallbacks", "informative callbacks for {@code vkAllocateMemory}, {@code vkFreeMemory}. Optional." ) nullable..VkDeviceSize.const.p( "pHeapSizeLimit", """ Either #NULL or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap. If not #NULL, it must be a pointer to an array of {@code VkPhysicalDeviceMemoryProperties::memoryHeapCount} elements, defining limit on maximum number of bytes that can be allocated out of particular Vulkan memory heap. Any of the elements may be equal to {@code VK_WHOLE_SIZE}, which means no limit on that heap. This is also the default in case of {@code pHeapSizeLimit = NULL}. If there is a limit defined for a heap: ${ul( "If user tries to allocate more memory from that heap using this allocator, the allocation fails with {@code VK_ERROR_OUT_OF_DEVICE_MEMORY}.", """ If the limit is smaller than heap size reported in {@code VkMemoryHeap::size}, the value of this limit will be reported instead when using #GetMemoryProperties(). """ )} Warning! Using this feature may not be equivalent to installing a GPU with smaller amount of memory, because graphics driver doesn't necessary fail new allocations with {@code VK_ERROR_OUT_OF_DEVICE_MEMORY} result when memory capacity is exceeded. It may return success and just silently migrate some device memory blocks to system RAM. This driver behavior can also be controlled using {@code VK_AMD_memory_overallocation_behavior} extension. """ ) VmaVulkanFunctions.const.p("pVulkanFunctions", "pointers to Vulkan functions") VkInstance("instance", "handle to Vulkan instance object.") uint32_t( "vulkanApiVersion", """ the highest version of Vulkan that the application is designed to use. (optional) It must be a value in the format as created by macro {@code VK_MAKE_VERSION} or a constant like: {@code VK_API_VERSION_1_1}, {@code VK_API_VERSION_1_0}. The patch version number specified is ignored. Only the major and minor versions are considered. It must be less or equal (preferably equal) to value as passed to {@code vkCreateInstance} as {@code VkApplicationInfo::apiVersion}. Only versions 1.0, 1.1, 1.2 and 1.3 are supported by the current implementation. Leaving it initialized to zero is equivalent to {@code VK_API_VERSION_1_0}. """ ) nullable..VkExternalMemoryHandleTypeFlagsKHR.const.p( "pTypeExternalMemoryHandleTypes", """ Either null or a pointer to an array of external memory handle types for each Vulkan memory type. If not #NULL, it must be a pointer to an array of {@code VkPhysicalDeviceMemoryProperties::memoryTypeCount} elements, defining external memory handle types of particular Vulkan memory type, to be passed using {@code VkExportMemoryAllocateInfoKHR}. Any of the elements may be equal to 0, which means not to use {@code VkExportMemoryAllocateInfoKHR} on this memory type. This is also the default in case of {@code pTypeExternalMemoryHandleTypes = NULL}. """ ) } val VmaAllocatorInfo = struct(Module.VMA, "VmaAllocatorInfo", mutable = false) { documentation = "Information about existing {@code VmaAllocator} object." VkInstance( "instance", """ Handle to Vulkan instance object. This is the same value as has been passed through ##VmaAllocatorCreateInfo{@code ::instance}. """ ) VkPhysicalDevice( "physicalDevice", """ Handle to Vulkan physical device object. This is the same value as has been passed through ##VmaAllocatorCreateInfo{@code ::physicalDevice}. """ ) VkDevice( "device", """ Handle to Vulkan device object. This is the same value as has been passed through ##VmaAllocatorCreateInfo{@code ::device}. """ ) } val VmaStatInfo = struct(Module.VMA, "VmaStatInfo", mutable = false) { documentation = "Calculated statistics of memory usage in entire allocator." uint32_t("blockCount", "number of {@code VkDeviceMemory} Vulkan memory blocks allocated") uint32_t("allocationCount", "number of {@code VmaAllocation} allocation objects allocated") uint32_t("unusedRangeCount", "number of free ranges of memory between allocations") VkDeviceSize("usedBytes", "total number of bytes occupied by all allocations") VkDeviceSize("unusedBytes", "total number of bytes occupied by unused ranges") VkDeviceSize("allocationSizeMin", "") VkDeviceSize("allocationSizeAvg", "") VkDeviceSize("allocationSizeMax", "") VkDeviceSize("unusedRangeSizeMin", "") VkDeviceSize("unusedRangeSizeAvg", "") VkDeviceSize("unusedRangeSizeMax", "") } private const val VK_MAX_MEMORY_TYPES = 32 private const val VK_MAX_MEMORY_HEAPS = 16 /// General statistics from current state of Allocator. val VmaStats = struct(Module.VMA, "VmaStats", mutable = false) { documentation = "General statistics from current state of Allocator." VmaStatInfo("memoryType", "")[VK_MAX_MEMORY_TYPES] VmaStatInfo("memoryHeap", "")[VK_MAX_MEMORY_HEAPS] VmaStatInfo("total", "") } val VmaBudget = struct(Module.VMA, "VmaBudget", mutable = false) { documentation = "Statistics of current memory usage and available budget, in bytes, for specific memory heap." VkDeviceSize("blockBytes", "Sum size of all {@code VkDeviceMemory} blocks allocated from particular heap, in bytes.") VkDeviceSize( "allocationBytes", """ Sum size of all allocations created in particular heap, in bytes. Usually less or equal than {@code blockBytes}. Difference {@code blockBytes - allocationBytes} is the amount of memory allocated but unused - available for new allocations or wasted due to fragmentation. """ ) VkDeviceSize( "usage", """ Estimated current memory usage of the program, in bytes. Fetched from system using {@code VK_EXT_memory_budget} extension if enabled. It might be different than {@code blockBytes} (usually higher) due to additional implicit objects also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or {@code VkDeviceMemory} blocks allocated outside of this library, if any. """ ) VkDeviceSize( "budget", """ Estimated amount of memory available to the program, in bytes. Fetched from system using {@code VK_EXT_memory_budget} extension if enabled. It might be different (most probably smaller) than {@code VkMemoryHeap::size[heapIndex]} due to factors external to the program, like other programs also consuming system resources. Difference {@code budget - usage} is the amount of additional memory that can probably be allocated without problems. Exceeding the budget may result in various problems. """ ) } val VmaAllocationCreateInfo = struct(Module.VMA, "VmaAllocationCreateInfo") { VmaAllocationCreateFlags("flags", "use {@code VmaAllocationCreateFlagBits} enum").links("ALLOCATION_CREATE_\\w+", LinkMode.BITFIELD) VmaMemoryUsage( "usage", """ intended usage of memory. You can leave #MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. If {@code pool} is not null, this member is ignored. """ ).links("MEMORY_USAGE_\\w+") VkMemoryPropertyFlags( "requiredFlags", """ flags that must be set in a Memory Type chosen for an allocation. Leave 0 if you specify memory requirements in other way. If {@code pool} is not null, this member is ignored. """ ) VkMemoryPropertyFlags( "preferredFlags", """ flags that preferably should be set in a memory type chosen for an allocation. Set to 0 if no additional flags are preferred. If {@code pool} is not null, this member is ignored. """ ) uint32_t( "memoryTypeBits", """ bitmask containing one bit set for every memory type acceptable for this allocation. Value 0 is equivalent to {@code UINT32_MAX} - it means any memory type is accepted if it meets other requirements specified by this structure, with no further restrictions on memory type index. If {@code pool} is not null, this member is ignored. """ ) nullable..VmaPool( "pool", """ pool that this allocation should be created in. Leave {@code VK_NULL_HANDLE} to allocate from default pool. If not null, members: {@code usage}, {@code requiredFlags}, {@code preferredFlags}, {@code memoryTypeBits} are ignored. """ ) nullable..opaque_p( "pUserData", """ custom general-purpose pointer that will be stored in {@code VmaAllocation}, can be read as ##VmaAllocationInfo{@code ::pUserData} and changed using #SetAllocationUserData(). If #ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either null or pointer to a null-terminated string. The string will be then copied to internal buffer, so it doesn't need to be valid after allocation call. """ ) float( "priority", """ A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations. It is used only when #ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the {@code VmaAllocator} object and this allocation ends up as dedicated or is explicitly forced as dedicated using #ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. Otherwise, it has the priority of a memory block where it is placed and this variable is ignored. """ ) } val VmaPoolCreateInfo = struct(Module.VMA, "VmaPoolCreateInfo") { javaImport("org.lwjgl.vulkan.*") documentation = "Describes parameter of created {@code VmaPool}." uint32_t("memoryTypeIndex", "Vulkan memory type index to allocate this pool from") VmaPoolCreateFlags("flags", "Use combination of {@code VmaPoolCreateFlagBits}.").links("POOL_CREATE_\\w+", LinkMode.BITFIELD) VkDeviceSize( "blockSize", """ size of a single {@code VkDeviceMemory} block to be allocated as part of this pool, in bytes. Optional. Specify nonzero to set explicit, constant size of memory blocks used by this pool. Leave 0 to use default and let the library manage block sizes automatically. Sizes of particular blocks may vary. In this case, the pool will also support dedicated allocations. """ ) size_t( "minBlockCount", """ minimum number of blocks to be always allocated in this pool, even if they stay empty. Set to 0 to have no preallocated blocks and allow the pool be completely empty. """ ) size_t( "maxBlockCount", """ maximum number of blocks that can be allocated in this pool. Optional. Set to 0 to use default, which is {@code SIZE_MAX}, which means no limit. Set to same value as ##VmaPoolCreateInfo{@code ::minBlockCount} to have fixed amount of memory allocated throughout whole lifetime of this pool. """ ) float( "priority", """ A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations. It is used only when #ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the {@code VmaAllocator} object. Otherwise, this variable is ignored. """ ) VkDeviceSize( "minAllocationAlignment", """ Additional minimum alignment to be used for all allocations created from this pool. Can be 0. Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two. It can be useful in cases where alignment returned by Vulkan by functions like {@code vkGetBufferMemoryRequirements} is not enough, e.g. when doing interop with OpenGL. """ ) PointerSetter( *VkMemoryAllocateInfo.definition["pNext"].get<PointerSetter>().types, prepend = true, targetSetter = "pNext" )..nullable..opaque_p( "pMemoryAllocateNext", """ Additional {@code pNext} chain to be attached to {@code VkMemoryAllocateInfo} used for every allocation made by this pool. Optional. Optional, can be null. If not null, it must point to a {@code pNext} chain of structures that can be attached to {@code VkMemoryAllocateInfo}. It can be useful for special needs such as adding {@code VkExportMemoryAllocateInfoKHR}. Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool. Please note that some structures, e.g. {@code VkMemoryPriorityAllocateInfoEXT}, {@code VkMemoryDedicatedAllocateInfoKHR}, can be attached automatically by this library when using other, more convenient of its features. """ ) } val VmaPoolStats = struct(Module.VMA, "VmaPoolStats", mutable = false) { documentation = "Describes parameter of existing {@code VmaPool}." VkDeviceSize("size", "total amount of {@code VkDeviceMemory} allocated from Vulkan for this pool, in bytes") VkDeviceSize("unusedSize", "total number of bytes in the pool not used by any {@code VmaAllocation}") size_t("allocationCount", "number of {@code VmaAllocation} objects created from this pool that were not destroyed") size_t("unusedRangeCount", "number of continuous memory ranges in the pool not used by any {@code VmaAllocation}") size_t("blockCount", "number of {@code VkDeviceMemory} blocks allocated for this pool") } val VmaAllocationInfo = struct(Module.VMA, "VmaAllocationInfo", mutable = false) { documentation = "Parameters of {@code VmaAllocation} objects, that can be retrieved using function #GetAllocationInfo()." uint32_t( "memoryType", """ memory type index that this allocation was allocated from. It never changes. """ ) VkDeviceMemory( "deviceMemory", """ handle to Vulkan memory object. Same memory object can be shared by multiple allocations. It can change after call to #Defragment() if this allocation is passed to the function. """ ) VkDeviceSize( "offset", """ offset in {@code VkDeviceMemory} object to the beginning of this allocation, in bytes. {@code (deviceMemory, offset)} pair is unique to this allocation. You usually don't need to use this offset. If you create a buffer or an image together with the allocation using e.g. function #CreateBuffer(), #CreateImage(), functions that operate on these resources refer to the beginning of the buffer or image, not entire device memory block. Functions like #MapMemory(), #BindBufferMemory() also refer to the beginning of the allocation and apply this offset automatically. It can change after call to #Defragment() if this allocation is passed to the function. """ ) VkDeviceSize( "size", """ size of this allocation, in bytes. It never changes. ${note(""" Allocation size returned in this variable may be greater than the size requested for the resource e.g. as {@code VkBufferCreateInfo::size}. Whole size of the allocation is accessible for operations on memory e.g. using a pointer after mapping with #MapMemory(), but operations on the resource e.g. using {@code vkCmdCopyBuffer} must be limited to the size of the resource.""")} """ ) nullable..opaque_p( "pMappedData", """ pointer to the beginning of this allocation as mapped data. If the allocation hasn't been mapped using #MapMemory() and hasn't been created with #ALLOCATION_CREATE_MAPPED_BIT flag, this value is null. It can change after call to #MapMemory(), #UnmapMemory(). It can also change after call to #Defragment() if this allocation is passed to the function. """ ) nullable..opaque_p( "pUserData", """ custom general-purpose pointer that was passed as ##VmaAllocationCreateInfo{@code ::pUserData} or set using #SetAllocationUserData(). It can change after call to #SetAllocationUserData() for this allocation. """ ) } val VmaDefragmentationInfo2 = struct(Module.VMA, "VmaDefragmentationInfo2") { javaImport("org.lwjgl.vulkan.*") documentation = """ Parameters for defragmentation. To be used with function #DefragmentationBegin(). """ VmaDefragmentationFlags("flags", "reserved for future use. Should be 0.") AutoSize("pAllocations", "pAllocationsChanged")..uint32_t("allocationCount", "number of allocations in {@code pAllocations} array") VmaAllocation.p( "pAllocations", """ pointer to array of allocations that can be defragmented. The array should have {@code allocationCount} elements. The array should not contain nulls. Elements in the array should be unique - same allocation cannot occur twice. All allocations not present in this array are considered non-moveable during this defragmentation. """ ) nullable..VkBool32.p( "pAllocationsChanged", """ Optional, output. Pointer to array that will be filled with information whether the allocation at certain index has been changed during defragmentation. The array should have {@code allocationCount} elements. You can pass null if you are not interested in this information. """ ) AutoSize("pPools")..uint32_t("poolCount", "number of pools in {@code pPools} array") nullable..VmaPool.const.p( "pPools", """ Either null or pointer to array of pools to be defragmented. All the allocations in the specified pools can be moved during defragmentation and there is no way to check if they were really moved as in {@code pAllocationsChanged}, so you must query all the allocations in all these pools for new {@code VkDeviceMemory} and offset using #GetAllocationInfo() if you might need to recreate buffers and images bound to them. The array should have {@code poolCount} elements. The array should not contain nulls. Elements in the array should be unique - same pool cannot occur twice. Using this array is equivalent to specifying all allocations from the pools in {@code pAllocations}. It might be more efficient. """ ) VkDeviceSize( "maxCpuBytesToMove", """ maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on CPU side, like {@code memcpy()}, {@code memmove()}. {@code VK_WHOLE_SIZE} means no limit. """ ) uint32_t( "maxCpuAllocationsToMove", """ maximum number of allocations that can be moved to a different place using transfers on CPU side, like {@code memcpy()}, {@code memmove()}. {@code UINT32_MAX} means no limit. """ ) VkDeviceSize( "maxGpuBytesToMove", """ maximum total numbers of bytes that can be copied while moving allocations to different places using transfers on GPU side, posted to {@code commandBuffer}. {@code VK_WHOLE_SIZE} means no limit. """ ) uint32_t( "maxGpuAllocationsToMove", """ maximum number of allocations that can be moved to a different place using transfers on GPU side, posted to {@code commandBuffer}. {@code UINT32_MAX} means no limit. """ ) nullable..VkCommandBuffer( "commandBuffer", """ command buffer where GPU copy commands will be posted. Optional. If not null, it must be a valid command buffer handle that supports Transfer queue type. It must be in the recording state and outside of a render pass instance. You need to submit it and make sure it finished execution before calling #DefragmentationEnd(). Passing null means that only CPU defragmentation will be performed. """ ) } val VmaDefragmentationPassMoveInfo = struct(Module.VMA, "VmaDefragmentationPassMoveInfo", mutable = false) { VmaAllocation("allocation", "") VkDeviceMemory("memory", "") VkDeviceSize("offset", "") } val VmaDefragmentationPassInfo = struct(Module.VMA, "VmaDefragmentationPassInfo", mutable = false) { documentation = """ Parameters for incremental defragmentation steps. To be used with function #BeginDefragmentationPass(). """ AutoSize("pMoves")..uint32_t("moveCount", "") VmaDefragmentationPassMoveInfo.p("pMoves", "") } val VmaDefragmentationInfo = struct(Module.VMA, "VmaDefragmentationInfo") { documentation = """ Deprecated. Optional configuration parameters to be passed to function #Defragment(). This is a part of the old interface. It is recommended to use structure ##VmaDefragmentationInfo2 and function #DefragmentationBegin() instead. """ VkDeviceSize( "maxBytesToMove", """ maximum total numbers of bytes that can be copied while moving allocations to different places. Default is {@code VK_WHOLE_SIZ}E, which means no limit. """ ) uint32_t( "maxAllocationsToMove", """ maximum number of allocations that can be moved to different place. Default is {@code UINT32_MAX}, which means no limit. """ ) } val VmaDefragmentationStats = struct(Module.VMA, "VmaDefragmentationStats", mutable = false) { documentation = "Statistics returned by function #Defragment()." VkDeviceSize("bytesMoved", "total number of bytes that have been copied while moving allocations to different places") VkDeviceSize("bytesFreed", "total number of bytes that have been released to the system by freeing empty {@code VkDeviceMemory} objects") uint32_t("allocationsMoved", "number of allocations that have been moved to different places") uint32_t("deviceMemoryBlocksFreed", "number of empty {@code VkDeviceMemory} objects that have been released to the system") } val VmaVirtualBlockCreateInfo = struct(Module.VMA, "VmaVirtualBlockCreateInfo") { javaImport("org.lwjgl.vulkan.*") documentation = "Parameters of created {@code VmaVirtualBlock} object to be passed to #CreateVirtualBlock()." VkDeviceSize( "size", """ total size of the virtual block. Sizes can be expressed in bytes or any units you want as long as you are consistent in using them. For example, if you allocate from some array of structures, 1 can mean single instance of entire structure. """ ) VmaVirtualBlockCreateFlagBits("flags", "use combination of {@code VmaVirtualBlockCreateFlagBits}").links("VIRTUAL_BLOCK_CREATE_\\w+", LinkMode.BITFIELD) nullable..VkAllocationCallbacks.const.p( "pAllocationCallbacks", """ custom CPU memory allocation callbacks. Optional. Optional, can be null. When specified, they will be used for all CPU-side memory allocations. """ ) } val VmaVirtualAllocationCreateInfo = struct(Module.VMA, "VmaVirtualAllocationCreateInfo") { documentation = "Parameters of created virtual allocation to be passed to #VirtualAllocate()." VkDeviceSize( "size", """ size of the allocation. Cannot be zero. """ ) VkDeviceSize( "alignment", """ required alignment of the allocation. Optional. Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset. """ ) VmaVirtualAllocationCreateFlags("flags", "use combination of {@code VmaVirtualAllocationCreateFlagBits}").links("VIRTUAL_ALLOCATION_CREATE_\\w+", LinkMode.BITFIELD) nullable..opaque_p( "pUserData", """ custom pointer to be associated with the allocation. Optional. It can be any value and can be used for user-defined purposes. It can be fetched or changed later. """ ) } val VmaVirtualAllocationInfo = struct(Module.VMA, "VmaVirtualAllocationInfo", mutable = false) { documentation = "Parameters of an existing virtual allocation, returned by #GetVirtualAllocationInfo()." VkDeviceSize( "offset", """ offset of the allocation. Offset at which the allocation was made. """ ) VkDeviceSize( "size", """ size of the allocation. Same value as passed in ##VmaVirtualAllocationCreateInfo{@code ::size}. """ ) nullable..opaque_p( "pUserData", """ custom pointer associated with the allocation. Same value as passed in ##VmaVirtualAllocationCreateInfo{@code ::pUserData} or to #SetVirtualAllocationUserData(). """ ) }
bsd-3-clause
997d73d22e0c66fc631ac8d586d9df61
44.139535
188
0.689965
4.576031
false
false
false
false
RockinRoel/FrameworkBenchmarks
frameworks/Kotlin/hexagon/src/main/kotlin/store/BenchmarkMongoDbStore.kt
1
2094
package com.hexagonkt.store import com.hexagonkt.CachedWorld import com.hexagonkt.Fortune import com.hexagonkt.Settings import com.hexagonkt.World import com.hexagonkt.helpers.Jvm import com.hexagonkt.helpers.fail import com.hexagonkt.store.mongodb.MongoDbStore import org.cache2k.Cache internal class BenchmarkMongoDbStore(engine: String, private val settings: Settings = Settings()) : BenchmarkStore(settings) { data class MongoDbWorld(val _id: Int, val id: Int, val randomNumber: Int) data class MongoDbFortune(val _id: Int, val message: String) private val dbHost: String by lazy { Jvm.systemSetting("${engine.uppercase()}_DB_HOST") ?: "localhost" } private val dbUrl: String by lazy { "mongodb://$dbHost/${settings.databaseName}" } private val worldRepository: MongoDbStore<MongoDbWorld, Int> by lazy { MongoDbStore(MongoDbWorld::class, MongoDbWorld::_id, dbUrl, settings.worldName) } private val fortuneRepository by lazy { MongoDbStore(MongoDbFortune::class, MongoDbFortune::_id, dbUrl, settings.fortuneName) } override fun findAllFortunes(): List<Fortune> = fortuneRepository.findAll().map { Fortune(it._id, it.message) } override fun findWorlds(ids: List<Int>): List<World> = ids.mapNotNull { worldRepository.findOne(it) }.map { World(it.id, it.randomNumber) } override fun replaceWorlds(worlds: List<World>) { worlds.forEach { val world = worldRepository.findOne(it.id) ?: fail val worldCopy = world.copy(randomNumber = it.randomNumber) worldRepository.replaceOne(worldCopy) } } override fun initWorldsCache(cache: Cache<Int, CachedWorld>) { worldRepository.findAll().forEach { cache.put(it.id, CachedWorld(it.id, it.randomNumber)) } } override fun loadCachedWorld(id: Int): CachedWorld = worldRepository.findOne(id) ?.let { world -> CachedWorld(world.id, world.randomNumber) } ?: error("World not found: $id") override fun close() { /* Not needed */ } }
bsd-3-clause
29c2ec2a97572e42ceeb25d2511a4d93
35.754386
115
0.689589
4.05029
false
false
false
false
github/codeql
java/ql/test/kotlin/library-tests/types/types.kt
1
1071
class Foo { val propByte: Byte = 1 val propShort: Short = 1 val propInt: Int = 1 val propLong: Long = 1 val propUByte: UByte = 1u val propUShort: UShort = 1u val propUInt: UInt = 1u val propULong: ULong = 1u val propFloat: Float = 1.0f val propDouble: Double = 1.0 val propBoolean: Boolean = true val propChar: Char = 'c' val propString: String = "str" val propNullableString: String? = "str" val propNullableNothing: Nothing? = null val propArray: Array<Int> = arrayOf(1, 2, 3) val propByteArray: ByteArray = byteArrayOf(1, 2, 3) val propShortArray: ShortArray = shortArrayOf(1, 2, 3) val propIntArray: IntArray = intArrayOf(1, 2, 3) val propLongArray: LongArray = longArrayOf(1, 2, 3) } class Gen<T> { fun fn1(a: T) { val x: Gen<Gen<Int>> = Gen<Gen<Int>>() class Local<U> {} val y: Gen<Local<Int>> = Gen<Local<Int>>() val z = object { } } fun fn2(a: Gen<out String>, b: Gen<in String>, c: Gen<in Nothing>, d: Gen<out Any?>) { } }
mit
6c15936ae3654e0f71449e979d88175b
23.906977
90
0.598506
3.255319
false
false
false
false
yippeesoft/NotifyTools
BingWallpage/src/main/java/org/github/yippeesoft/bingwallpage/Net.kt
1
5479
package org.github.yippeesoft.bingwallpage import android.util.Log import com.orhanobut.logger.Logger import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Function import io.reactivex.schedulers.Schedulers import okhttp3.Cache import okhttp3.CacheControl import okhttp3.Interceptor import okhttp3.Interceptor.Chain import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody import org.dom4j.Document import org.dom4j.DocumentHelper import org.dom4j.Element import org.dom4j.Node import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.simplexml.SimpleXmlConverterFactory import retrofit2.http.GET import retrofit2.http.Query import retrofit2.http.Url import java.util.concurrent.TimeUnit import org.simpleframework.xml.core.Persister import org.simpleframework.xml.convert.AnnotationStrategy import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory /** * Created by sf on 2017/6/8. */ class Net { val BASE_URL: String = "http://cn.bing.com/" data class BingWallBean(val url:String,val copyright:String) fun getBingWall():Observable<List<BingWallBean>>{ var retrofit=BaseRetrofit.retrofit(BASE_URL) var netService:NetService=retrofit.create(NetService::class.java) return netService.getWallList("/HPImageArchive.aspx?format=xml",0,20) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(Function<retrofit2.Response<ResponseBody>,Observable<List<BingWallBean>>?> { rep-> var beans = mutableListOf<BingWallBean>() if(rep!=null && !rep.isSuccessful){ Logger.d(rep.errorBody().toString()) } if (rep != null && rep.body() != null){ val resp = rep.body()!!.string() Logger.d("body:" + resp) val strategy = AnnotationStrategy() val serializer = Persister(strategy) // var wall:BingWallBean =serializer.read(BingWallBean::class.java,resp) val document: Document = DocumentHelper.parseText(resp) val xpath:String="images/image" val nodes:List<Node> = document.selectNodes(xpath) for (n in nodes){ val e:Element = n as Element val b:BingWallBean =BingWallBean(e.element("url").text,e.element("copyright").text) beans.add(b) // Logger.d("node "+e.element("url").text) } // Observable.just<BingWallBean>(wall) } Observable.just(beans) }) } } fun Net.add(){ Logger.d("测试") } interface NetService { @GET fun getWallList(@Url url:String,@Query("idx")idx:Int,@Query("n")n:Int): Observable<retrofit2.Response<ResponseBody>> } object BaseRetrofit { private const val cacheSize: Long = 10 * 1024 * 1024 // // var interceptor = Interceptor { // //获取原始Request对象,并在原始Request对象的基础上增加请求头信息 // val request = it.request().newBuilder() // .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") // .addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6") // .addHeader("Connection", "keep-alive") // .build() // //执行请求并返回响应对象 // it.proceed(request) // } // // var test =Interceptor{ // // val response =it.proceed(it.request()) // response // } private var REWRITE_CACHE_CONTROL_INTERCEPTOR: Interceptor = Interceptor { chain -> val response = chain?.proceed(chain.request()) if (App.isNetOk()) { val maxAge: Int = 0 response?.newBuilder()!!.removeHeader("Cache-Control") .removeHeader("Pragma") .header("Cache-Control", "public, max-age=" + maxAge) .build() } else { val maxAge = 60 * 60 * 24 * 7 response?.newBuilder()!!.removeHeader("Cache-Control") .removeHeader("Pragma") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxAge) .build() } } private fun getClient(): OkHttpClient { val builder = OkHttpClient.Builder() if (builder.interceptors() != null) { builder.interceptors().clear() } builder.addInterceptor { chain -> val request = chain?.request() if (!App.isNetOk()) { chain!!.proceed(request!! .newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build()) } else { chain!!.proceed( request!!.newBuilder().build()) } }.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) .cache(Cache(App.getContext().cacheDir, cacheSize)) .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) return builder.build() } fun retrofit(url: String): Retrofit { val retrofit: Retrofit = Retrofit.Builder() .baseUrl(url) .client(getClient()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(SimpleXmlConverterFactory.create()) .build() return retrofit } }
apache-2.0
a86715bd326282a669a8fa758f26c211
30.769697
118
0.638668
3.846975
false
false
false
false
airbnb/epoxy
epoxy-processor/src/main/java/com/airbnb/epoxy/processor/ControllerClassInfo.kt
1
2212
package com.airbnb.epoxy.processor import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XTypeElement import com.airbnb.epoxy.processor.resourcescanning.ResourceScanner import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import java.util.HashSet private const val GENERATED_HELPER_CLASS_SUFFIX = "_EpoxyHelper" class ControllerClassInfo( // Not holding on to any symbols so that this can be stored across rounds controllerClassElement: XTypeElement, val resourceProcessor: ResourceScanner, memoizer: Memoizer ) { // Exception to the rule of not reusing symbols across rounds - should be safe for originating // elements since those just report the file information which should not change. val originatingElement: XElement = controllerClassElement val classPackage: String = controllerClassElement.packageName val models: MutableSet<ControllerModelField> = HashSet() val modelsImmutable: Set<ControllerModelField> get() = synchronized(models) { models.toSet() } val generatedClassName: ClassName = getGeneratedClassName(controllerClassElement) val controllerClassType: TypeName = controllerClassElement.type.typeNameWithWorkaround(memoizer) val imports: List<String> by lazy { resourceProcessor.getImports(controllerClassElement) } fun addModel(controllerModelField: ControllerModelField) = synchronized(models) { models.add(controllerModelField) } fun addModels(controllerModelFields: Collection<ControllerModelField>) = synchronized(models) { models.addAll(controllerModelFields) } private fun getGeneratedClassName(controllerClass: XTypeElement): ClassName { val packageName = controllerClass.packageName val packageLen = packageName.length + 1 val className = controllerClass.qualifiedName.substring(packageLen).replace('.', '$') return ClassName.get(packageName, "$className$GENERATED_HELPER_CLASS_SUFFIX") } override fun toString() = "ControllerClassInfo(models=$models, generatedClassName=$generatedClassName, " + "controllerClassType=$controllerClassType)" }
apache-2.0
0d84e369352fd65122d6bd37366a4426
40.735849
100
0.764467
4.981982
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/user/Participant.kt
1
2021
@file:JvmName("Participant") package backend.model.user import backend.exceptions.DomainException import backend.model.event.Event import backend.model.event.Team import backend.model.location.Location import java.time.LocalDate import java.util.* import javax.persistence.* @Entity @DiscriminatorValue("PARTICIPANT") class Participant : UserRole { var emergencynumber: String = "" var tshirtsize: String? = null var hometown: String? = null var phonenumber: String? = null var birthdate: LocalDate? = null @ManyToOne private var currentTeam: Team? = null @ManyToMany(mappedBy = "members") private var teams: MutableSet<Team> @OneToMany(mappedBy = "uploader") val locations: MutableList<Location> = ArrayList() /** * Private constructor for JPA */ private constructor() : super() { teams = mutableSetOf() } constructor(account: UserAccount) : super(account) { teams = mutableSetOf() } fun getCurrentTeam(): Team? { return this.currentTeam } fun getAllTeams(): Set<Team> { return this.teams } fun clearAllTeams() { this.currentTeam = null this.teams.clear() } fun setCurrentTeam(team: Team?) { if (team != null) { this.teams.add(team) } this.currentTeam = team } @PreRemove fun preRemove() { this.locations.forEach { it.uploader = null } this.locations.clear() } fun removeTeam(team: Team) { if (this.getCurrentTeam() == team) { this.setCurrentTeam(null) } if (!this.teams.remove(team)) { throw DomainException("Can't remove team ${team.id} from participant $id. " + "The participant has never been a part of this team") } } fun participatedAtEvent(event: Event): Boolean { return this.getAllTeams().any { it.event == event } } override fun getAuthority(): String = "PARTICIPANT" }
agpl-3.0
e06833beb0babe6056ade2c0245a6942
22.776471
89
0.621969
4.17562
false
false
false
false