repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
shiguredo/sora-android-sdk
sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/util/ZipHelper.kt
1
1140
package jp.shiguredo.sora.sdk.util import java.io.InputStream import java.nio.ByteBuffer import java.util.zip.DeflaterInputStream import java.util.zip.InflaterInputStream class ZipHelper { companion object { fun zip(buffer: ByteBuffer): ByteBuffer { return ByteBuffer.wrap(DeflaterInputStream(ByteBufferBackedInputStream(buffer)).readBytes()) } fun unzip(buffer: ByteBuffer): ByteBuffer { return ByteBuffer.wrap(InflaterInputStream(ByteBufferBackedInputStream(buffer)).readBytes()) } } private class ByteBufferBackedInputStream(private val buf: ByteBuffer) : InputStream() { override fun read(): Int { return if (!buf.hasRemaining()) { -1 } else { buf.get().toInt() and 0xFF } } override fun read(bytes: ByteArray?, off: Int, len: Int): Int { var len = len if (!buf.hasRemaining()) { return -1 } len = Math.min(len, buf.remaining()) buf.get(bytes, off, len) return len } } }
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/VaporQualidadeCommand.kt
1
1526
package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun` import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.escapeMentions import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.common.utils.text.VaporwaveUtils import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import net.perfectdreams.loritta.morenitta.LorittaBot class VaporQualidadeCommand(loritta: LorittaBot) : AbstractCommand(loritta, "vaporqualidade", category = net.perfectdreams.loritta.common.commands.CommandCategory.FUN) { override fun getDescriptionKey() = LocaleKeyData("commands.command.vaporquality.description") override fun getExamplesKey() = LocaleKeyData("commands.command.vaporquality.examples") // TODO: Fix Usage // TODO: Fix Detailed Usage override suspend fun run(context: CommandContext,locale: BaseLocale) { OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "text vaporquality") if (context.args.isNotEmpty()) { val qualidade = VaporwaveUtils.vaporwave(context.args.joinToString(" ").toCharArray().joinToString(" ")).toUpperCase() .escapeMentions() context.reply( LorittaReply(message = qualidade, prefix = "✍") ) } else { this.explain(context) } } }
agpl-3.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/user/GetMutualGuildsRoute.kt
1
1369
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.user import com.github.salomonbrys.kotson.jsonArray import com.github.salomonbrys.kotson.jsonObject import com.github.salomonbrys.kotson.toJsonArray import io.ktor.server.application.ApplicationCall import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.website.routes.api.v1.RequiresAPIAuthenticationRoute import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson class GetMutualGuildsRoute(loritta: LorittaBot) : RequiresAPIAuthenticationRoute(loritta, "/api/v1/users/{userId}/mutual-guilds") { override suspend fun onAuthenticatedRequest(call: ApplicationCall) { val userId = call.parameters["userId"] ?: return val user = loritta.lorittaShards.getUserById(userId) if (user == null) { call.respondJson( jsonObject( "guilds" to jsonArray() ) ) return } val mutualGuilds = loritta.lorittaShards.getMutualGuilds(user) call.respondJson( jsonObject( "guilds" to mutualGuilds.map { val member = it.getMember(user) jsonObject( "id" to it.id, "name" to it.name, "iconUrl" to it.iconUrl, "memberCount" to it.memberCount, "timeJoined" to member?.timeJoined?.toInstant()?.toEpochMilli() ) }.toJsonArray() ) ) } }
agpl-3.0
MaibornWolff/codecharta
analysis/import/TokeiImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/tokeiimporter/analysisObject/AnalysisObject.kt
1
447
package de.maibornwolff.codecharta.importer.tokeiimporter.analysisObject class AnalysisObject( val blanks: Int, val code: Int, val comments: Int, val lines: Int, val stats: List<Stats>?, private val inaccurate: Boolean ) { fun hasChildren(): Boolean { return !stats.isNullOrEmpty() } } class Stats( val blanks: Int, val code: Int, val comments: Int, val lines: Int, val name: String )
bsd-3-clause
MaibornWolff/codecharta
analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/Modification.kt
1
1377
package de.maibornwolff.codecharta.importer.gitlogparser.input class Modification( val currentFilename: String, val oldFilename: String, val additions: Long, val deletions: Long, val type: Type ) { private var initialAdd = false constructor(filename: String, type: Type) : this(filename, 0, 0, type) constructor(filename: String, oldFilename: String, type: Type) : this(filename, oldFilename, 0, 0, type) @JvmOverloads constructor(filename: String, additions: Long = 0, deletions: Long = 0, type: Type = Type.UNKNOWN) : this( filename, "", additions, deletions, type ) enum class Type { ADD, DELETE, MODIFY, RENAME, UNKNOWN } fun isTypeDelete(): Boolean { return type == Type.DELETE } fun isTypeAdd(): Boolean { return type == Type.ADD } fun isTypeModify(): Boolean { return type == Type.MODIFY } fun isTypeRename(): Boolean { return type == Type.RENAME } fun getTrackName(): String { return if (oldFilename.isNotEmpty()) oldFilename else currentFilename } fun markInitialAdd() { initialAdd = true } fun isInitialAdd(): Boolean { return initialAdd } companion object { val EMPTY = Modification("") } }
bsd-3-clause
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/util/OkioExtensions.kt
5
889
package eu.kanade.tachiyomi.util import okio.BufferedSource import okio.Okio import java.io.File import java.io.OutputStream /** * Saves the given source to a file and closes it. Directories will be created if needed. * * @param file the file where the source is copied. */ fun BufferedSource.saveTo(file: File) { try { // Create parent dirs if needed file.parentFile.mkdirs() // Copy to destination saveTo(file.outputStream()) } catch (e: Exception) { close() file.delete() throw e } } /** * Saves the given source to an output stream and closes both resources. * * @param stream the stream where the source is copied. */ fun BufferedSource.saveTo(stream: OutputStream) { use { input -> Okio.buffer(Okio.sink(stream)).use { it.writeAll(input) it.flush() } } }
apache-2.0
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/viewgroup/DriftLayout.kt
1
9379
package com.angcyo.uiview.viewgroup import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.abs import com.angcyo.uiview.kotlin.density import java.util.* /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:浮动布局, 一个中心View, 其他View在周边浮动旋转 * 创建人员:Robi * 创建时间:2018/02/23 10:44 * 修改人员:Robi * 修改时间:2018/02/23 10:44 * 修改备注: * Version: 1.0.0 */ class DriftLayout(context: Context, attributeSet: AttributeSet? = null) : FrameLayout(context, attributeSet) { // init { // val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.DriftLayout) // typedArray.recycle() // } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) updateLayout() } private fun updateLayout() { driftCenterView?.let { //修正布局坐标 for (i in 0 until childCount) { val childAt = getChildAt(i) if (childAt.visibility != View.VISIBLE) { continue } val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (childAt != it) { //围绕的中心点坐标 val cx = it.left + it.measuredWidth / 2 val cy = it.top + it.measuredHeight / 2 //计算出的布局点的坐标 val r = Math.max(childAt.measuredWidth, childAt.measuredHeight) / 2 + layoutParams.driftROffset //距离中心点的半径 val x: Int = (cx + Math.cos(Math.toRadians(layoutParams.animDriftAngle.toDouble())) * r + layoutParams.animDriftXOffset * density).toInt() val y: Int = (cy + Math.sin(Math.toRadians(layoutParams.animDriftAngle.toDouble())) * r + layoutParams.animDriftYOffset * density).toInt() childAt.layout(x - childAt.measuredWidth / 2, y - childAt.measuredHeight / 2, x + childAt.measuredWidth / 2, y + childAt.measuredHeight / 2) } } } } } private var isOnAttachedToWindow = false override fun onAttachedToWindow() { super.onAttachedToWindow() isOnAttachedToWindow = true checkStartDrift() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() isOnAttachedToWindow = false checkStartDrift() } override fun onVisibilityChanged(changedView: View?, visibility: Int) { super.onVisibilityChanged(changedView, visibility) checkStartDrift() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) checkStartDrift() } private fun checkStartDrift() { //检查是否需要浮动 if (isOnAttachedToWindow && visibility == View.VISIBLE && measuredWidth > 0 && measuredHeight > 0 && !driftAnimator.isStarted) { driftAnimator.start() } else { driftAnimator.cancel() } } /**动画*/ private val driftAnimator: ValueAnimator by lazy { ObjectAnimator.ofInt(0, 360).apply { repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE duration = 1000 addUpdateListener { driftCenterView?.let { //修正布局坐标 for (i in 0 until childCount) { val childAt = getChildAt(i) val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (childAt != it) { if (layoutParams.enableDrift) { layoutParams.animDriftAngle += layoutParams.animDriftAngleStep } if (layoutParams.enableShake) { if (layoutParams.animDriftIsOffsetX) { layoutParams.animDriftXOffset += layoutParams.animDriftXOffsetStep } else { layoutParams.animDriftYOffset += layoutParams.animDriftYOffsetStep } } } } } updateLayout() postInvalidateOnAnimation() } } } } override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams { return LayoutParams(context, attrs) } override fun generateLayoutParams(lp: ViewGroup.LayoutParams?): ViewGroup.LayoutParams { return LayoutParams(lp) } override fun generateDefaultLayoutParams(): LayoutParams { return LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) } //居中定位的View private val driftCenterView: View? get() { var view: View? = null for (i in 0 until childCount) { val childAt = getChildAt(i) val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (layoutParams.isDriftCenterView) { view = childAt break } } } return view } class LayoutParams : FrameLayout.LayoutParams { var isDriftCenterView = false var driftAngle = 0 var driftROffset = 0 var enableDrift = true var enableShake = true //每帧旋转的角度 var animDriftAngleStep = 0.1f private val random: Random by lazy { Random(System.nanoTime()) } var animDriftIsOffsetX = true var animDriftXOffsetMax = 10 + random.nextInt(10) //每帧x轴抖动的距离 var animDriftXOffsetStep = 0.15f var animDriftXOffset = 0f //px 自动转换为dp set(value) { field = value if (value > animDriftXOffsetMax) { animDriftXOffsetStep = -animDriftXOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } else if (value < -animDriftXOffsetMax) { animDriftXOffsetStep = animDriftXOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } } var animDriftYOffsetMax = 10 + random.nextInt(10) var animDriftYOffsetStep = animDriftXOffsetStep var animDriftYOffset = 0f set(value) { field = value if (value > animDriftYOffsetMax) { animDriftYOffsetStep = -animDriftYOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } else if (value < -animDriftYOffsetMax) { animDriftYOffsetStep = animDriftYOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } } //动画执行中的角度保存变量 var animDriftAngle = 0f set(value) { field = if (value > 360) { 0f } else { value } } constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) { val a = c.obtainStyledAttributes(attrs, R.styleable.DriftLayout) isDriftCenterView = a.getBoolean(R.styleable.DriftLayout_r_is_drift_center, isDriftCenterView) driftAngle = a.getInt(R.styleable.DriftLayout_r_drift_angle, driftAngle) animDriftAngleStep = a.getFloat(R.styleable.DriftLayout_r_drift_angle_step, animDriftAngleStep) animDriftAngle = driftAngle.toFloat() driftROffset = a.getDimensionPixelOffset(R.styleable.DriftLayout_r_drift_r_offset, driftROffset) enableDrift = a.getBoolean(R.styleable.DriftLayout_r_enable_drift, enableDrift) enableShake = a.getBoolean(R.styleable.DriftLayout_r_enable_shake, enableShake) a.recycle() } constructor(width: Int, height: Int) : super(width, height) constructor(width: Int, height: Int, gravity: Int) : super(width, height, gravity) constructor(source: ViewGroup.LayoutParams?) : super(source) constructor(source: MarginLayoutParams?) : super(source) } }
apache-2.0
pronghorn-tech/server
src/main/kotlin/tech/pronghorn/server/bufferpools/ReusableBufferPoolManager.kt
1
1297
/* * Copyright 2017 Pronghorn Technology LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.pronghorn.server.bufferpools import tech.pronghorn.plugins.internalQueue.InternalQueuePlugin import java.nio.ByteBuffer public class ReusableBufferPoolManager(public val bufferSize: Int, public val direct: Boolean = false) { public fun getBuffer(): ReusableByteBuffer = pool.poll() ?: ReusableByteBuffer( this, if (direct) ByteBuffer.allocateDirect(bufferSize) else ByteBuffer.allocate(bufferSize) ) public fun release(buffer: ReusableByteBuffer) { pool.offer(buffer) } private val pool = InternalQueuePlugin.getUnbounded<ReusableByteBuffer>() }
apache-2.0
ansman/kotshi
tests/src/main/kotlin/se/ansman/kotshi/DefaultValues.kt
1
1028
package se.ansman.kotshi @JsonSerializable data class ClassWithDefaultValues( val v1: Byte = Byte.MAX_VALUE, val v2: Char = Char.MAX_VALUE, val v3: Short = Short.MAX_VALUE, val v4: Int = Int.MAX_VALUE, val v5: Long = Long.MAX_VALUE, val v6: Float = Float.MAX_VALUE, val v7: Double = Double.MAX_VALUE, val v8: String = "n/a", val v9: List<String> = emptyList(), val v10: String ) @JsonSerializable data class WithCompanionFunction(val v: String?) @JsonSerializable data class WithStaticFunction(val v: String?) @JsonSerializable data class WithCompanionProperty(val v: String?) @JsonSerializable data class WithStaticProperty(val v: String?) @JsonSerializable data class GenericClassWithDefault<out T>(val v: T?) @JsonSerializable data class ClassWithConstructorAsDefault(val v: String?) { constructor() : this("ClassWithConstructorAsDefault") } @JsonSerializable data class GenericClassWithConstructorAsDefault<T : CharSequence>(val v: T?) { constructor() : this(null) }
apache-2.0
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/stored/library/sync/SyncChecker.kt
1
696
package com.lasthopesoftware.bluewater.client.stored.library.sync import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryProvider import com.namehillsoftware.handoff.promises.Promise class SyncChecker(private val libraryProvider: ILibraryProvider, private val serviceFilesForSync: CollectServiceFilesForSync) : CheckForSync { override fun promiseIsSyncNeeded(): Promise<Boolean> { return libraryProvider.allLibraries .eventually { libraries -> Promise.whenAll(libraries.map { l -> serviceFilesForSync .promiseServiceFilesToSync(l.libraryId) .then { sf -> sf.isNotEmpty() } }) } .then { emptyStatuses -> emptyStatuses.any { it } } } }
lgpl-3.0
jsargent7089/android
src/main/java/com/owncloud/android/datamodel/ArbitraryDataSet.kt
1
1014
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2020 Tobias Kaminsky * Copyright (C) 2020 Nextcloud GmbH * * 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 <https://www.gnu.org/licenses/>. */ package com.owncloud.android.datamodel /** * Data set for [ArbitraryDataProvider] */ internal class ArbitraryDataSet(val id: Int, val cloudId: String, val key: String, val value: String)
gpl-2.0
zametki/zametki
src/main/java/com/github/zametki/ajax/RenameGroupAjaxCall.kt
1
672
package com.github.zametki.ajax import com.github.zametki.Context import com.github.zametki.annotation.MountPath import com.github.zametki.model.Group //todo: POST? @MountPath("/ajax/rename-group/\${groupId}/\${name}") class RenameGroupAjaxCall : BaseNNGroupActionAjaxCall() { override fun getResponseTextNN(group: Group): String { val name = getParameter("name").toString("") if (name.length < Group.MIN_NAME_LEN || name.length > Group.MAX_NAME_LEN) { return error("Illegal group name") } group.name = name Context.getGroupsDbi().update(group) return AjaxApiUtils.getGroupsListAsResponse(userId) } }
apache-2.0
RyanAndroidTaylor/Rapido
rapidosqlite/src/androidTest/java/com/izeni/rapidosqlite/util/Toy.kt
1
1136
package com.izeni.rapidosqlite.util import android.content.ContentValues import android.database.Cursor import com.izeni.rapidosqlite.DataConnection import com.izeni.rapidosqlite.addAll import com.izeni.rapidosqlite.get import com.izeni.rapidosqlite.item_builder.ItemBuilder import com.izeni.rapidosqlite.table.Column import com.izeni.rapidosqlite.table.DataTable /** * Created by ner on 2/8/17. */ data class Toy(val uuid: String, val name: String) : DataTable { companion object { val TABLE_NAME = "Toy" val UUID = Column(String::class.java, "Uuid", notNull = true, unique = true) val NAME = Column(String::class.java, "Name") val COLUMNS = arrayOf(UUID, NAME) val BUILDER = Builder() } override fun tableName() = TABLE_NAME override fun id() = uuid override fun idColumn() = UUID override fun contentValues() = ContentValues().addAll(COLUMNS, uuid, name) class Builder : ItemBuilder<Toy> { override fun buildItem(cursor: Cursor, dataConnection: DataConnection): Toy { return Toy(cursor.get(UUID), cursor.get(NAME)) } } }
mit
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/util/TagsAdapter.kt
1
2632
package com.newsblur.util import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.newsblur.R import com.newsblur.databinding.RowSavedTagBinding import com.newsblur.domain.StarredCount class TagsAdapter(private val type: Type, private val listener: OnTagClickListener) : RecyclerView.Adapter<TagsAdapter.ViewHolder>() { private val tags = ArrayList<StarredCount>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.row_saved_tag, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val tag = tags[position] holder.binding.containerRow.setBackgroundResource(android.R.color.transparent) holder.binding.rowTagName.text = tag.tag holder.binding.rowSavedTagSum.text = tag.count.toString() holder.binding.root.setOnClickListener { listener.onTagClickListener(tag, type) } } override fun getItemCount(): Int = tags.size fun replaceAll(tags: MutableCollection<StarredCount>) { val diffCallback = TagDiffCallback(this.tags, tags.toList()) val diffResult = DiffUtil.calculateDiff(diffCallback) this.tags.clear() this.tags.addAll(tags) diffResult.dispatchUpdatesTo(this) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = RowSavedTagBinding.bind(view) } enum class Type { OTHER, SAVED } interface OnTagClickListener { fun onTagClickListener(starredTag: StarredCount, type: Type) } class TagDiffCallback(private val oldList: List<StarredCount>, private val newList: List<StarredCount>) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = oldList[oldItemPosition].tag == newList[newItemPosition].tag && oldList[oldItemPosition].count == newList[newItemPosition].count override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = oldList[oldItemPosition].tag == newList[newItemPosition].tag && oldList[oldItemPosition].count == newList[newItemPosition].count override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size } }
mit
thomasvolk/alkali
src/main/kotlin/net/t53k/alkali/test/ActorTest.kt
1
3479
/* * Copyright 2017 Thomas Volk * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package net.t53k.alkali.test import net.t53k.alkali.Actor import net.t53k.alkali.ActorReference import net.t53k.alkali.ActorSystem import net.t53k.alkali.ActorSystemBuilder import kotlin.concurrent.thread fun actorTestBuilder() = ActorTestBuilder() fun actorTest(test: ActorTest.TestRunActor.(ActorReference) -> Unit) { actorTestBuilder().test(test).build().run() } private val TEST_LOOP_DELAY_MS: Long = 1 fun ActorSystem.waitForShutdown(timeout: Long) { var doWait = true thread(start = true) { Thread.sleep(timeout) doWait = false } while(doWait && isActive()) { Thread.sleep(TEST_LOOP_DELAY_MS) } if (isActive()) { shutdown() waitForShutdown() throw RuntimeException("timeout $timeout reached!") } } class ActorTestBuilder { private lateinit var _test: (ActorTest.TestRunActor.(ActorReference) -> Unit) private var _timeout: Long = 2000 private var deadletterHandler: (Any) -> Unit = {} private var mainHandler: ActorSystem.(Any) -> Unit = {} fun test(test: ActorTest.TestRunActor.(ActorReference) -> Unit): ActorTestBuilder { _test = test return this } fun timeout(timeout: Long): ActorTestBuilder { _timeout = timeout return this } fun deadLetterHandler(handler: (Any) -> Unit): ActorTestBuilder { deadletterHandler = handler return this } fun mainHandler(handler: ActorSystem.(Any) -> Unit): ActorTestBuilder { mainHandler = handler return this } fun build(): ActorTest { return ActorTest(_test, _timeout, mainHandler, deadletterHandler) } } class ActorTest(val test: TestRunActor.(ActorReference) -> Unit, val timeout: Long, val mainHandler: ActorSystem.(Any) -> Unit, val deadletterHandler: (Any) -> Unit) { class TestRunActor(val test: TestRunActor.(ActorReference) -> Unit): Actor() { private var messageHandler: (Any) -> (Unit) = { } override fun before() { test(self()) } override fun receive(message: Any) { messageHandler(message) system().shutdown() } fun testSystem() = system() infix fun onMessage(messageHandler: (Any) -> (Unit)) { this.messageHandler = messageHandler } } fun run() { val system = ActorSystemBuilder().onDefaultActorMessage(mainHandler).onDeadLetterMessage(deadletterHandler).build() try { system.actor(this.toString(), TestRunActor(test)) } finally { system.waitForShutdown(timeout) } } }
apache-2.0
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/fragment/AddSocialFragment.kt
1
2401
package com.newsblur.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.newsblur.R import com.newsblur.activity.AddFacebook import com.newsblur.activity.AddTwitter import com.newsblur.databinding.FragmentAddsocialBinding import com.newsblur.network.APIManager import com.newsblur.util.executeAsyncTask import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class AddSocialFragment : Fragment() { @Inject lateinit var apiManager: APIManager private lateinit var binding: FragmentAddsocialBinding private var twitterAuthed = false private var facebookAuthed = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } fun setTwitterAuthed() { twitterAuthed = true authCheck() } fun setFacebookAuthed() { facebookAuthed = true authCheck() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_addsocial, null) binding = FragmentAddsocialBinding.bind(view) binding.addsocialTwitter.setOnClickListener { val i = Intent(activity, AddTwitter::class.java) startActivityForResult(i, 0) } binding.addsocialFacebook.setOnClickListener { val i = Intent(activity, AddFacebook::class.java) startActivityForResult(i, 0) } authCheck() binding.addsocialAutofollowCheckbox.setOnCheckedChangeListener { _, checked -> lifecycleScope.executeAsyncTask( doInBackground = { apiManager.setAutoFollow(checked) } ) } return view } private fun authCheck() { if (twitterAuthed) { binding.addsocialTwitterText.text = "Added Twitter friends!" binding.addsocialTwitter.isEnabled = false } if (facebookAuthed) { binding.addsocialFacebookText.text = "Added Facebook friends!" binding.addsocialFacebook.isEnabled = false } } }
mit
jghoman/workshop-jb
test/i_introduction/_0_Hello_World/_00_Start.kt
6
198
package i_introduction._0_Hello_World.Hello import junit.framework.Assert import org.junit.Test as test class _00_Start { test fun testOk() { Assert.assertEquals("OK", task0()) } }
mit
abdoyassen/OnlyU
X&O geam/StartUp/app/src/androidTest/java/com/example/onlyu/startup/ExampleInstrumentedTest.kt
4
652
package com.example.onlyu.startup import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.example.onlyu.startup", appContext.packageName) } }
mit
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/model/menu/MediaMenuInterface.kt
2
292
package net.halawata.artich.model.menu import net.halawata.artich.entity.SideMenuItem interface MediaMenuInterface { fun get(): ArrayList<String> fun save(data: ArrayList<String>) fun getMenuList(): ArrayList<SideMenuItem> fun getUrlStringFrom(title: String): String? }
mit
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/setup/barcodescanning/barcode/BarcodeScanningProcessor.kt
1
3131
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.particle.mesh.ui.setup.barcodescanning.barcode import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions.Builder import com.google.firebase.ml.vision.common.FirebaseVisionImage import io.particle.mesh.common.android.livedata.setOnMainThread import io.particle.mesh.ui.setup.barcodescanning.FrameMetadata import io.particle.mesh.ui.setup.barcodescanning.GraphicOverlay import io.particle.mesh.ui.setup.barcodescanning.VisionProcessorBase import mu.KotlinLogging import java.io.IOException class BarcodeScanningProcessor : VisionProcessorBase<List<FirebaseVisionBarcode>>() { val foundBarcodes: LiveData<List<FirebaseVisionBarcode>> get() = mutableFoundBarcodes private val mutableFoundBarcodes = MutableLiveData<List<FirebaseVisionBarcode>>() private val detector: FirebaseVisionBarcodeDetector private val log = KotlinLogging.logger {} init { // Note that if you know which format of barcode your app is dealing with, detection will be // faster to specify the supported barcode formats val options = Builder() .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_DATA_MATRIX) .build() detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options) } override fun stop() { try { detector.close() } catch (e: IOException) { log.error(e) { "Exception thrown while trying to close Barcode Detector" } } } override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionBarcode>> { return detector.detectInImage(image) } override fun onSuccess( barcodes: List<FirebaseVisionBarcode>, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay) { graphicOverlay.clear() for (i in barcodes.indices) { // val barcode = barcodes[i] // val barcodeGraphic = BarcodeGraphic(graphicOverlay, barcode) // graphicOverlay.add(barcodeGraphic) } mutableFoundBarcodes.setOnMainThread(barcodes) } override fun onFailure(e: Exception) { log.error(e) { "Barcode detection failed" } } }
apache-2.0
owncloud/android
owncloudApp/src/main/java/com/owncloud/android/utils/MdmConfigurations.kt
1
1383
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * * Copyright (C) 2022 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * 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.owncloud.android.utils import androidx.annotation.StringDef const val CONFIGURATION_LOCK_DELAY_TIME = "lock_delay_time_configuration" const val CONFIGURATION_SERVER_URL = "server_url_configuration" const val CONFIGURATION_SERVER_URL_INPUT_VISIBILITY = "server_url_input_visibility_configuration" const val CONFIGURATION_ALLOW_SCREENSHOTS = "allow_screenshots_configuration" @StringDef( CONFIGURATION_LOCK_DELAY_TIME, CONFIGURATION_SERVER_URL, CONFIGURATION_SERVER_URL_INPUT_VISIBILITY, CONFIGURATION_ALLOW_SCREENSHOTS, ) @Retention(AnnotationRetention.SOURCE) @Target(AnnotationTarget.VALUE_PARAMETER) annotation class MDMConfigurations
gpl-2.0
google/horologist
base-ui/src/debug/java/com/google/android/horologist/base/ui/components/SecondaryChipPreview.kt
1
8469
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistBaseUiApi::class) package com.google.android.horologist.base.ui.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.materialPath import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi import com.google.android.horologist.base.ui.util.rememberVectorPainter @Preview( group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreview() { StandardChip( label = "Primary label", onClick = { }, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabel() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", chipType = StandardChipType.Secondary ) } @Preview( name = "With icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon32dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndIcon() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and large icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndLargeIcon() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icon32dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "Disabled", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewDisabled() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icons.Default.Image, chipType = StandardChipType.Secondary, enabled = false ) } @Preview( name = "With long text", group = "Long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLongText() { StandardChip( label = "Primary label very very very very very very very very very very very very very very very very very long text", onClick = { }, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and long text", group = "Long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndLongText() { StandardChip( label = "Primary label very very very very very very very very long text", onClick = { }, secondaryLabel = "Secondary label very very very very very very very very very long text", icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "Using icon smaller than 24dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewUsingSmallIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon12dp, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon, using icon smaller than 32dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIconUsingSmallIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon12dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "Using icon larger than 24dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewUsingExtraLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon48dp, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon, using icon larger than 32dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIconUsingExtraLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon48dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "With icon placeholder ", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithIconPlaceholder() { StandardChip( label = "Primary label", onClick = { }, icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "Disabled with icon placeholder", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewDisabledWithIconPlaceholder() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = "iconUri", placeholder = rememberVectorPainter( image = Icons.Default.Image, tintColor = Color.White ), chipType = StandardChipType.Secondary, enabled = false ) } private val Icon12dp: ImageVector get() = ImageVector.Builder( name = "Icon Small", defaultWidth = 12f.dp, defaultHeight = 12f.dp, viewportWidth = 12f, viewportHeight = 12f ) .materialPath { horizontalLineToRelative(12.0f) verticalLineToRelative(12.0f) horizontalLineTo(0.0f) close() } .build() private val Icon32dp: ImageVector get() = ImageVector.Builder( name = "Icon Large", defaultWidth = 32f.dp, defaultHeight = 32f.dp, viewportWidth = 32f, viewportHeight = 32f ) .materialPath { horizontalLineToRelative(32.0f) verticalLineToRelative(32.0f) horizontalLineTo(0.0f) close() } .build() private val Icon48dp: ImageVector get() = ImageVector.Builder( name = "Icon Extra Large", defaultWidth = 48f.dp, defaultHeight = 48f.dp, viewportWidth = 48f, viewportHeight = 48f ) .materialPath { horizontalLineToRelative(48.0f) verticalLineToRelative(48.0f) horizontalLineTo(0.0f) close() } .build()
apache-2.0
android/camera-samples
CameraXVideo/app/src/main/java/com/example/android/camerax/video/fragments/CaptureFragment.kt
1
22606
/** * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Simple app to demonstrate CameraX Video capturing with Recorder ( to local files ), with the * following simple control follow: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ package com.example.android.camerax.video.fragments import android.annotation.SuppressLint import android.content.ContentValues import android.content.res.Configuration import java.text.SimpleDateFormat import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.Navigation import com.example.android.camerax.video.R import com.example.android.camerax.video.databinding.FragmentCaptureBinding import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.video.* import androidx.concurrent.futures.await import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.util.Consumer import androidx.core.view.updateLayoutParams import androidx.lifecycle.MutableLiveData import androidx.lifecycle.whenCreated import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.camera.utils.GenericListAdapter import com.example.android.camerax.video.extensions.getAspectRatio import com.example.android.camerax.video.extensions.getAspectRatioString import com.example.android.camerax.video.extensions.getNameString import kotlinx.coroutines.* import java.util.* class CaptureFragment : Fragment() { // UI with ViewBinding private var _captureViewBinding: FragmentCaptureBinding? = null private val captureViewBinding get() = _captureViewBinding!! private val captureLiveStatus = MutableLiveData<String>() /** Host's navigation controller */ private val navController: NavController by lazy { Navigation.findNavController(requireActivity(), R.id.fragment_container) } private val cameraCapabilities = mutableListOf<CameraCapability>() private lateinit var videoCapture: VideoCapture<Recorder> private var currentRecording: Recording? = null private lateinit var recordingState:VideoRecordEvent // Camera UI states and inputs enum class UiState { IDLE, // Not recording, all UI controls are active. RECORDING, // Camera is recording, only display Pause/Resume & Stop button. FINALIZED, // Recording just completes, disable all RECORDING UI controls. RECOVERY // For future use. } private var cameraIndex = 0 private var qualityIndex = DEFAULT_QUALITY_IDX private var audioEnabled = false private val mainThreadExecutor by lazy { ContextCompat.getMainExecutor(requireContext()) } private var enumerationDeferred:Deferred<Unit>? = null // main cameraX capture functions /** * Always bind preview + video capture use case combinations in this sample * (VideoCapture can work on its own). The function should always execute on * the main thread. */ private suspend fun bindCaptureUsecase() { val cameraProvider = ProcessCameraProvider.getInstance(requireContext()).await() val cameraSelector = getCameraSelector(cameraIndex) // create the user required QualitySelector (video resolution): we know this is // supported, a valid qualitySelector will be created. val quality = cameraCapabilities[cameraIndex].qualities[qualityIndex] val qualitySelector = QualitySelector.from(quality) captureViewBinding.previewView.updateLayoutParams<ConstraintLayout.LayoutParams> { val orientation = [email protected] dimensionRatio = quality.getAspectRatioString(quality, (orientation == Configuration.ORIENTATION_PORTRAIT)) } val preview = Preview.Builder() .setTargetAspectRatio(quality.getAspectRatio(quality)) .build().apply { setSurfaceProvider(captureViewBinding.previewView.surfaceProvider) } // build a recorder, which can: // - record video/audio to MediaStore(only shown here), File, ParcelFileDescriptor // - be used create recording(s) (the recording performs recording) val recorder = Recorder.Builder() .setQualitySelector(qualitySelector) .build() videoCapture = VideoCapture.withOutput(recorder) try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle( viewLifecycleOwner, cameraSelector, videoCapture, preview ) } catch (exc: Exception) { // we are on main thread, let's reset the controls on the UI. Log.e(TAG, "Use case binding failed", exc) resetUIandState("bindToLifecycle failed: $exc") } enableUI(true) } /** * Kick start the video recording * - config Recorder to capture to MediaStoreOutput * - register RecordEvent Listener * - apply audio request from user * - start recording! * After this function, user could start/pause/resume/stop recording and application listens * to VideoRecordEvent for the current recording status. */ @SuppressLint("MissingPermission") private fun startRecording() { // create MediaStoreOutputOptions for our recorder: resulting our recording! val name = "CameraX-recording-" + SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) + ".mp4" val contentValues = ContentValues().apply { put(MediaStore.Video.Media.DISPLAY_NAME, name) } val mediaStoreOutput = MediaStoreOutputOptions.Builder( requireActivity().contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() // configure Recorder and Start recording to the mediaStoreOutput. currentRecording = videoCapture.output .prepareRecording(requireActivity(), mediaStoreOutput) .apply { if (audioEnabled) withAudioEnabled() } .start(mainThreadExecutor, captureListener) Log.i(TAG, "Recording started") } /** * CaptureEvent listener. */ private val captureListener = Consumer<VideoRecordEvent> { event -> // cache the recording state if (event !is VideoRecordEvent.Status) recordingState = event updateUI(event) if (event is VideoRecordEvent.Finalize) { // display the captured video lifecycleScope.launch { navController.navigate( CaptureFragmentDirections.actionCaptureToVideoViewer( event.outputResults.outputUri ) ) } } } /** * Retrieve the asked camera's type(lens facing type). In this sample, only 2 types: * idx is even number: CameraSelector.LENS_FACING_BACK * odd number: CameraSelector.LENS_FACING_FRONT */ private fun getCameraSelector(idx: Int) : CameraSelector { if (cameraCapabilities.size == 0) { Log.i(TAG, "Error: This device does not have any camera, bailing out") requireActivity().finish() } return (cameraCapabilities[idx % cameraCapabilities.size].camSelector) } data class CameraCapability(val camSelector: CameraSelector, val qualities:List<Quality>) /** * Query and cache this platform's camera capabilities, run only once. */ init { enumerationDeferred = lifecycleScope.async { whenCreated { val provider = ProcessCameraProvider.getInstance(requireContext()).await() provider.unbindAll() for (camSelector in arrayOf( CameraSelector.DEFAULT_BACK_CAMERA, CameraSelector.DEFAULT_FRONT_CAMERA )) { try { // just get the camera.cameraInfo to query capabilities // we are not binding anything here. if (provider.hasCamera(camSelector)) { val camera = provider.bindToLifecycle(requireActivity(), camSelector) QualitySelector .getSupportedQualities(camera.cameraInfo) .filter { quality -> listOf(Quality.UHD, Quality.FHD, Quality.HD, Quality.SD) .contains(quality) }.also { cameraCapabilities.add(CameraCapability(camSelector, it)) } } } catch (exc: java.lang.Exception) { Log.e(TAG, "Camera Face $camSelector is not supported") } } } } } /** * One time initialize for CameraFragment (as a part of fragment layout's creation process). * This function performs the following: * - initialize but disable all UI controls except the Quality selection. * - set up the Quality selection recycler view. * - bind use cases to a lifecycle camera, enable UI controls. */ private fun initCameraFragment() { initializeUI() viewLifecycleOwner.lifecycleScope.launch { if (enumerationDeferred != null) { enumerationDeferred!!.await() enumerationDeferred = null } initializeQualitySectionsUI() bindCaptureUsecase() } } /** * Initialize UI. Preview and Capture actions are configured in this function. * Note that preview and capture are both initialized either by UI or CameraX callbacks * (except the very 1st time upon entering to this fragment in onCreateView() */ @SuppressLint("ClickableViewAccessibility", "MissingPermission") private fun initializeUI() { captureViewBinding.cameraButton.apply { setOnClickListener { cameraIndex = (cameraIndex + 1) % cameraCapabilities.size // camera device change is in effect instantly: // - reset quality selection // - restart preview qualityIndex = DEFAULT_QUALITY_IDX initializeQualitySectionsUI() enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } isEnabled = false } // audioEnabled by default is disabled. captureViewBinding.audioSelection.isChecked = audioEnabled captureViewBinding.audioSelection.setOnClickListener { audioEnabled = captureViewBinding.audioSelection.isChecked } // React to user touching the capture button captureViewBinding.captureButton.apply { setOnClickListener { if (!this@CaptureFragment::recordingState.isInitialized || recordingState is VideoRecordEvent.Finalize) { enableUI(false) // Our eventListener will turn on the Recording UI. startRecording() } else { when (recordingState) { is VideoRecordEvent.Start -> { currentRecording?.pause() captureViewBinding.stopButton.visibility = View.VISIBLE } is VideoRecordEvent.Pause -> currentRecording?.resume() is VideoRecordEvent.Resume -> currentRecording?.pause() else -> throw IllegalStateException("recordingState in unknown state") } } } isEnabled = false } captureViewBinding.stopButton.apply { setOnClickListener { // stopping: hide it after getting a click before we go to viewing fragment captureViewBinding.stopButton.visibility = View.INVISIBLE if (currentRecording == null || recordingState is VideoRecordEvent.Finalize) { return@setOnClickListener } val recording = currentRecording if (recording != null) { recording.stop() currentRecording = null } captureViewBinding.captureButton.setImageResource(R.drawable.ic_start) } // ensure the stop button is initialized disabled & invisible visibility = View.INVISIBLE isEnabled = false } captureLiveStatus.observe(viewLifecycleOwner) { captureViewBinding.captureStatus.apply { post { text = it } } } captureLiveStatus.value = getString(R.string.Idle) } /** * UpdateUI according to CameraX VideoRecordEvent type: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ private fun updateUI(event: VideoRecordEvent) { val state = if (event is VideoRecordEvent.Status) recordingState.getNameString() else event.getNameString() when (event) { is VideoRecordEvent.Status -> { // placeholder: we update the UI with new status after this when() block, // nothing needs to do here. } is VideoRecordEvent.Start -> { showUI(UiState.RECORDING, event.getNameString()) } is VideoRecordEvent.Finalize-> { showUI(UiState.FINALIZED, event.getNameString()) } is VideoRecordEvent.Pause -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_resume) } is VideoRecordEvent.Resume -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_pause) } } val stats = event.recordingStats val size = stats.numBytesRecorded / 1000 val time = java.util.concurrent.TimeUnit.NANOSECONDS.toSeconds(stats.recordedDurationNanos) var text = "${state}: recorded ${size}KB, in ${time}second" if(event is VideoRecordEvent.Finalize) text = "${text}\nFile saved to: ${event.outputResults.outputUri}" captureLiveStatus.value = text Log.i(TAG, "recording event: $text") } /** * Enable/disable UI: * User could select the capture parameters when recording is not in session * Once recording is started, need to disable able UI to avoid conflict. */ private fun enableUI(enable: Boolean) { arrayOf(captureViewBinding.cameraButton, captureViewBinding.captureButton, captureViewBinding.stopButton, captureViewBinding.audioSelection, captureViewBinding.qualitySelection).forEach { it.isEnabled = enable } // disable the camera button if no device to switch if (cameraCapabilities.size <= 1) { captureViewBinding.cameraButton.isEnabled = false } // disable the resolution list if no resolution to switch if (cameraCapabilities[cameraIndex].qualities.size <= 1) { captureViewBinding.qualitySelection.apply { isEnabled = false } } } /** * initialize UI for recording: * - at recording: hide audio, qualitySelection,change camera UI; enable stop button * - otherwise: show all except the stop button */ private fun showUI(state: UiState, status:String = "idle") { captureViewBinding.let { when(state) { UiState.IDLE -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE it.cameraButton.visibility= View.VISIBLE it.audioSelection.visibility = View.VISIBLE it.qualitySelection.visibility=View.VISIBLE } UiState.RECORDING -> { it.cameraButton.visibility = View.INVISIBLE it.audioSelection.visibility = View.INVISIBLE it.qualitySelection.visibility = View.INVISIBLE it.captureButton.setImageResource(R.drawable.ic_pause) it.captureButton.isEnabled = true it.stopButton.visibility = View.VISIBLE it.stopButton.isEnabled = true } UiState.FINALIZED -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE } else -> { val errorMsg = "Error: showUI($state) is not supported" Log.e(TAG, errorMsg) return } } it.captureStatus.text = status } } /** * ResetUI (restart): * in case binding failed, let's give it another change for re-try. In future cases * we might fail and user get notified on the status */ private fun resetUIandState(reason: String) { enableUI(true) showUI(UiState.IDLE, reason) cameraIndex = 0 qualityIndex = DEFAULT_QUALITY_IDX audioEnabled = false captureViewBinding.audioSelection.isChecked = audioEnabled initializeQualitySectionsUI() } /** * initializeQualitySectionsUI(): * Populate a RecyclerView to display camera capabilities: * - one front facing * - one back facing * User selection is saved to qualityIndex, will be used * in the bindCaptureUsecase(). */ private fun initializeQualitySectionsUI() { val selectorStrings = cameraCapabilities[cameraIndex].qualities.map { it.getNameString() } // create the adapter to Quality selection RecyclerView captureViewBinding.qualitySelection.apply { layoutManager = LinearLayoutManager(context) adapter = GenericListAdapter( selectorStrings, itemLayoutId = R.layout.video_quality_item ) { holderView, qcString, position -> holderView.apply { findViewById<TextView>(R.id.qualityTextView)?.text = qcString // select the default quality selector isSelected = (position == qualityIndex) } holderView.setOnClickListener { view -> if (qualityIndex == position) return@setOnClickListener captureViewBinding.qualitySelection.let { // deselect the previous selection on UI. it.findViewHolderForAdapterPosition(qualityIndex) ?.itemView ?.isSelected = false } // turn on the new selection on UI. view.isSelected = true qualityIndex = position // rebind the use cases to put the new QualitySelection in action. enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } } isEnabled = false } } // System function implementations override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _captureViewBinding = FragmentCaptureBinding.inflate(inflater, container, false) return captureViewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCameraFragment() } override fun onDestroyView() { _captureViewBinding = null super.onDestroyView() } companion object { // default Quality selection if no input from UI const val DEFAULT_QUALITY_IDX = 0 val TAG:String = CaptureFragment::class.java.simpleName private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" } }
apache-2.0
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/appdata/user/local/UserLocalRepositoryImpl.kt
1
1347
package net.yslibrary.monotweety.appdata.user.local import com.gojuno.koptional.Optional import com.gojuno.koptional.toOptional import com.pushtorefresh.storio3.sqlite.StorIOSQLite import io.reactivex.BackpressureStrategy import io.reactivex.Completable import io.reactivex.Flowable import net.yslibrary.monotweety.appdata.local.singleObject import net.yslibrary.monotweety.appdata.local.withObject import net.yslibrary.monotweety.appdata.user.User import net.yslibrary.monotweety.di.UserScope import javax.inject.Inject @UserScope class UserLocalRepositoryImpl @Inject constructor( private val storIOSQLite: StorIOSQLite ) : UserLocalRepository { override fun getById(id: Long): Flowable<Optional<User>> { return storIOSQLite.get() .singleObject(User::class.java) .withQuery(UserTable.queryById(id)) .prepare() .asRxFlowable(BackpressureStrategy.LATEST) .map { it.orNull().toOptional() } } override fun set(entity: User): Completable { return storIOSQLite.put() .withObject(entity) .prepare() .asRxCompletable() } override fun delete(id: Long): Completable { return storIOSQLite.delete() .byQuery(UserTable.deleteById(id)) .prepare() .asRxCompletable() } }
apache-2.0
Zhuinden/simple-stack
tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_3/Step3Screen.kt
1
266
package com.zhuinden.simplestacktutorials.steps.step_3 import android.os.Parcelable abstract class Step3Screen : Parcelable { abstract val titleText: String abstract val centerText: String abstract val buttonConfiguration: Step3ButtonConfiguration? }
apache-2.0
xfournet/intellij-community
plugins/git4idea/src/git4idea/GitApplyChangesProcess.kt
1
19590
/* * 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 git4idea import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.pluralize import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.merge.MergeDialogCustomizer import com.intellij.openapi.vcs.update.RefreshVFsSynchronously import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsFullCommitDetails import com.intellij.vcs.log.util.VcsUserUtil import com.intellij.vcsUtil.VcsUtil import git4idea.commands.* import git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT import git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK import git4idea.merge.GitConflictResolver import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.util.GitUntrackedFilesHelper import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import javax.swing.event.HyperlinkEvent /** * Applies the given Git operation (e.g. cherry-pick or revert) to the current working tree, * waits for the [ChangeListManager] update, shows the commit dialog and removes the changelist after commit, * if the commit was successful. */ class GitApplyChangesProcess(private val project: Project, private val commits: List<VcsFullCommitDetails>, private val autoCommit: Boolean, private val operationName: String, private val appliedWord: String, private val command: (GitRepository, Hash, Boolean, List<GitLineHandlerListener>) -> GitCommandResult, private val emptyCommitDetector: (GitCommandResult) -> Boolean, private val defaultCommitMessageGenerator: (VcsFullCommitDetails) -> String, private val preserveCommitMetadata: Boolean, private val cleanupBeforeCommit: (GitRepository) -> Unit = {}) { private val LOG = logger<GitApplyChangesProcess>() private val git = Git.getInstance() private val repositoryManager = GitRepositoryManager.getInstance(project) private val vcsNotifier = VcsNotifier.getInstance(project) private val changeListManager = ChangeListManager.getInstance(project) as ChangeListManagerEx private val vcsHelper = AbstractVcsHelper.getInstance(project) fun execute() { val commitsInRoots = DvcsUtil.groupCommitsByRoots<GitRepository>(repositoryManager, commits) LOG.info("${operationName}ing commits: " + toString(commitsInRoots)) val successfulCommits = mutableListOf<VcsFullCommitDetails>() val skippedCommits = mutableListOf<VcsFullCommitDetails>() DvcsUtil.workingTreeChangeStarted(project, operationName).use { for ((repository, value) in commitsInRoots) { val result = executeForRepo(repository, value, successfulCommits, skippedCommits) repository.update() if (!result) { return } } notifyResult(successfulCommits, skippedCommits) } } // return true to continue with other roots, false to break execution private fun executeForRepo(repository: GitRepository, commits: List<VcsFullCommitDetails>, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { for (commit in commits) { val conflictDetector = GitSimpleEventDetector(CHERRY_PICK_CONFLICT) val localChangesOverwrittenDetector = GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK) val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(repository.root) val commitMessage = defaultCommitMessageGenerator(commit) val changeList = createChangeList(commitMessage, commit) val previousDefaultChangelist = changeListManager.defaultChangeList try { changeListManager.defaultChangeList = changeList val result = command(repository, commit.id, autoCommit, listOf(conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector)) if (result.success()) { if (autoCommit) { successfulCommits.add(commit) } else { refreshVfsAndMarkDirty(repository) waitForChangeListManagerUpdate() val committed = commit(repository, commit, commitMessage, changeList, successfulCommits, alreadyPicked) if (!committed) return false } } else if (conflictDetector.hasHappened()) { val mergeCompleted = ConflictResolver(project, git, repository.root, commit.id.asString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject, operationName).merge() refreshVfsAndMarkDirty(repository) waitForChangeListManagerUpdate() if (mergeCompleted) { LOG.debug("All conflicts resolved, will show commit dialog. Current default changelist is [$changeList]") val committed = commit(repository, commit, commitMessage, changeList, successfulCommits, alreadyPicked) if (!committed) return false } else { notifyConflictWarning(repository, commit, successfulCommits) return false } } else if (untrackedFilesDetector.wasMessageDetected()) { var description = getSuccessfulCommitDetailsIfAny(successfulCommits) GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, repository.root, untrackedFilesDetector.relativeFilePaths, operationName, description) return false } else if (localChangesOverwrittenDetector.hasHappened()) { notifyError("Your local changes would be overwritten by $operationName.<br/>Commit your changes or stash them to proceed.", commit, successfulCommits) return false } else if (emptyCommitDetector(result)) { alreadyPicked.add(commit) } else { notifyError(result.errorOutputAsHtmlString, commit, successfulCommits) return false } } finally { changeListManager.defaultChangeList = previousDefaultChangelist removeChangeListIfEmpty(changeList) } } return true } private fun createChangeList(commitMessage: String, commit: VcsFullCommitDetails): LocalChangeList { val changeListName = createNameForChangeList(project, commitMessage) val changeListData = if (preserveCommitMetadata) createChangeListData(commit) else null return changeListManager.addChangeList(changeListName, commitMessage, changeListData) } private fun commit(repository: GitRepository, commit: VcsFullCommitDetails, commitMessage: String, changeList: LocalChangeList, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { val actualList = changeListManager.getChangeList(changeList.id) if (actualList == null) { LOG.error("Couldn't find the changelist with id ${changeList.id} and name ${changeList.name} among " + changeListManager.changeLists.joinToString { "${it.id} ${it.name}" }) return false } val changes = actualList.changes if (changes.isEmpty()) { LOG.debug("No changes in the $actualList. All changes in the CLM: ${getAllChangesInLogFriendlyPresentation(changeListManager)}") alreadyPicked.add(commit) return true } LOG.debug("Showing commit dialog for changes: ${changes}") val committed = showCommitDialogAndWaitForCommit(repository, changeList, commitMessage, changes) if (committed) { refreshVfsAndMarkDirty(changes) waitForChangeListManagerUpdate() successfulCommits.add(commit) return true } else { notifyCommitCancelled(commit, successfulCommits) return false } } private fun getAllChangesInLogFriendlyPresentation(changeListManagerEx: ChangeListManagerEx) = changeListManagerEx.changeLists.map { it -> "[${it.name}] ${it.changes}" } private fun waitForChangeListManagerUpdate() { val waiter = CountDownLatch(1) changeListManager.invokeAfterUpdate({ waiter.countDown() }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, operationName.capitalize(), ModalityState.NON_MODAL) var success = false while (!success) { ProgressManager.checkCanceled() try { success = waiter.await(50, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { LOG.warn(e) throw ProcessCanceledException(e) } } } private fun refreshVfsAndMarkDirty(repository: GitRepository) { VfsUtil.markDirtyAndRefresh(false, true, false, repository.root) VcsDirtyScopeManager.getInstance(project).filePathsDirty(null, listOf(VcsUtil.getFilePath(repository.root))) } private fun refreshVfsAndMarkDirty(changes: Collection<Change>) { RefreshVFsSynchronously.updateChanges(changes) VcsDirtyScopeManager.getInstance(project).filePathsDirty(ChangesUtil.getPaths(changes), null) } private fun removeChangeListIfEmpty(changeList: LocalChangeList) { val actualList = changeListManager.getChangeList(changeList.id) if (actualList != null && actualList.changes.isEmpty()) { LOG.debug("Changelist $actualList is empty, removing. " + "All changes in the CLM: ${getAllChangesInLogFriendlyPresentation(changeListManager)}") changeListManager.removeChangeList(actualList) } } private fun showCommitDialogAndWaitForCommit(repository: GitRepository, changeList: LocalChangeList, commitMessage: String, changes: Collection<Change>): Boolean { val commitSucceeded = AtomicBoolean() val sem = Semaphore(0) ApplicationManager.getApplication().invokeAndWait({ try { cleanupBeforeCommit(repository) val commitNotCancelled = vcsHelper.commitChanges(changes, changeList, commitMessage, object : CommitResultHandler { override fun onSuccess(commitMessage1: String) { commitSucceeded.set(true) sem.release() } override fun onFailure() { commitSucceeded.set(false) sem.release() } }) if (!commitNotCancelled) { commitSucceeded.set(false) sem.release() } } catch (t: Throwable) { LOG.error(t) commitSucceeded.set(false) sem.release() } }, ModalityState.NON_MODAL) // need additional waiting, because commitChanges is asynchronous try { sem.acquire() } catch (e: InterruptedException) { LOG.error(e) return false } return commitSucceeded.get() } private fun createChangeListData(commit: VcsFullCommitDetails) = ChangeListData(commit.author, Date(commit.authorTime)) private fun notifyResult(successfulCommits: List<VcsFullCommitDetails>, skipped: List<VcsFullCommitDetails>) { if (skipped.isEmpty()) { vcsNotifier.notifySuccess("${operationName.capitalize()} successful", getCommitsDetails(successfulCommits)) } else if (!successfulCommits.isEmpty()) { val title = String.format("${operationName.capitalize()}ed %d commits from %d", successfulCommits.size, successfulCommits.size + skipped.size) val description = getCommitsDetails(successfulCommits) + "<hr/>" + formSkippedDescription(skipped, true) vcsNotifier.notifySuccess(title, description) } else { vcsNotifier.notifyImportantWarning("Nothing to $operationName", formSkippedDescription(skipped, false)) } } private fun notifyConflictWarning(repository: GitRepository, commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { val resolveLinkListener = ResolveLinkListener(repository.root, commit.id.toShortString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject) var description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>" description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyImportantWarning("${operationName.capitalize()}ed with conflicts", description, resolveLinkListener) } private fun notifyCommitCancelled(commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { if (successfulCommits.isEmpty()) { // don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue. return } var description = commitDetails(commit) description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyMinorWarning("${operationName.capitalize()} cancelled", description, null) } private fun notifyError(content: String, failedCommit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { var description = commitDetails(failedCommit) + "<br/>" + content description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyError("${operationName.capitalize()} Failed", description) } private fun getSuccessfulCommitDetailsIfAny(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" if (!successfulCommits.isEmpty()) { description += "<hr/>However ${operationName} succeeded for the following " + pluralize("commit", successfulCommits.size) + ":<br/>" description += getCommitsDetails(successfulCommits) } return description } private fun formSkippedDescription(skipped: List<VcsFullCommitDetails>, but: Boolean): String { val hashes = StringUtil.join(skipped, { commit -> commit.id.toShortString() }, ", ") if (but) { val was = if (skipped.size == 1) "was" else "were" val it = if (skipped.size == 1) "it" else "them" return String.format("%s %s skipped, because all changes have already been ${appliedWord}.", hashes, was, it) } return String.format("All changes from %s have already been ${appliedWord}", hashes) } private fun getCommitsDetails(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" for (commit in successfulCommits) { description += commitDetails(commit) + "<br/>" } return description.substring(0, description.length - "<br/>".length) } private fun commitDetails(commit: VcsFullCommitDetails): String { return commit.id.toShortString() + " " + StringUtil.escapeXml(commit.subject) } private fun toString(commitsInRoots: Map<GitRepository, List<VcsFullCommitDetails>>): String { return commitsInRoots.entries.joinToString("; ") { entry -> val commits = entry.value.joinToString { it.id.asString() } getShortRepositoryName(entry.key) + ": [" + commits + "]" } } private inner class ResolveLinkListener(private val root: VirtualFile, private val hash: String, private val author: String, private val message: String) : NotificationListener { override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) { if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) { if (event.description == "resolve") { GitApplyChangesProcess.ConflictResolver(project, git, root, hash, author, message, operationName).mergeNoProceed() } } } } class ConflictResolver(project: Project, git: Git, root: VirtualFile, commitHash: String, commitAuthor: String, commitMessage: String, operationName: String ) : GitConflictResolver(project, git, setOf(root), makeParams(commitHash, commitAuthor, commitMessage, operationName)) { override fun notifyUnresolvedRemain() {/* we show a [possibly] compound notification after applying all commits.*/ } } } private fun makeParams(commitHash: String, commitAuthor: String, commitMessage: String, operationName: String): GitConflictResolver.Params { val params = GitConflictResolver.Params() params.setErrorNotificationTitle("${operationName.capitalize()}ed with conflicts") params.setMergeDialogCustomizer(MergeDialogCustomizer(commitHash, commitAuthor, commitMessage, operationName)) return params } private class MergeDialogCustomizer(private val commitHash: String, private val commitAuthor: String, private val commitMessage: String, private val operationName: String) : MergeDialogCustomizer() { override fun getMultipleFileMergeDescription(files: Collection<VirtualFile>) = "<html>Conflicts during ${operationName}ing commit <code>$commitHash</code> " + "made by $commitAuthor<br/><code>\"$commitMessage\"</code></html>" override fun getLeftPanelTitle(file: VirtualFile) = "Local changes" override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?) = "<html>Changes from $operationName <code>$commitHash</code>" }
apache-2.0
xfournet/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUPolyadicExpression.kt
7
1225
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiPolyadicExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UExpression import org.jetbrains.uast.UPolyadicExpression import org.jetbrains.uast.UastBinaryOperator class JavaUPolyadicExpression( override val psi: PsiPolyadicExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UPolyadicExpression { override val operands: List<UExpression> by lz { psi.operands.map { JavaConverter.convertOrEmpty(it, this) } } override val operator: UastBinaryOperator by lz { psi.operationTokenType.getOperatorType() } }
apache-2.0
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/ssl/CustomTrustManager.kt
2
2592
package com.commit451.gitlab.ssl import com.commit451.gitlab.api.X509TrustManagerProvider import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.* /** * Allows for custom configurations, such as custom trusted hostnames, custom trusted certificates, * and private keys */ class CustomTrustManager : X509TrustManager { private var trustedCertificate: String? = null private var trustedHostname: String? = null private var sslSocketFactory: SSLSocketFactory? = null private var hostnameVerifier: HostnameVerifier? = null fun setTrustedCertificate(trustedCertificate: String) { this.trustedCertificate = trustedCertificate sslSocketFactory = null } fun setTrustedHostname(trustedHostname: String) { this.trustedHostname = trustedHostname hostnameVerifier = null } @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { X509TrustManagerProvider.x509TrustManager.checkClientTrusted(chain, authType) } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { val cause: CertificateException try { X509TrustManagerProvider.x509TrustManager.checkServerTrusted(chain, authType) return } catch (e: CertificateException) { cause = e } if (trustedCertificate != null && trustedCertificate == X509Util.getFingerPrint(chain[0])) { return } throw X509CertificateException(cause.message!!, cause, chain) } override fun getAcceptedIssuers(): Array<X509Certificate> { return X509TrustManagerProvider.x509TrustManager.acceptedIssuers } fun getSSLSocketFactory(): SSLSocketFactory { if (sslSocketFactory != null) { return sslSocketFactory!! } val keyManagers: Array<KeyManager>? = null try { val sslContext = SSLContext.getInstance("TLS") sslContext.init(keyManagers, arrayOf<TrustManager>(this), null) sslSocketFactory = CustomSSLSocketFactory(sslContext.socketFactory) } catch (e: Exception) { throw IllegalStateException(e) } return sslSocketFactory!! } fun getHostnameVerifier(): HostnameVerifier { if (hostnameVerifier == null) { hostnameVerifier = CustomHostnameVerifier(trustedHostname) } return hostnameVerifier!! } }
apache-2.0
google/ksp
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/kotlin/KSTypeReferenceImpl.kt
1
6220
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language 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 com.google.devtools.ksp.symbol.impl.kotlin import com.google.devtools.ksp.ExceptionMessage import com.google.devtools.ksp.KSObjectCache import com.google.devtools.ksp.memoized import com.google.devtools.ksp.processing.impl.ResolverImpl import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSReferenceElement import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.KSVisitor import com.google.devtools.ksp.symbol.Location import com.google.devtools.ksp.symbol.Modifier import com.google.devtools.ksp.symbol.Origin import com.google.devtools.ksp.symbol.impl.toLocation import com.google.devtools.ksp.toKSModifiers import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDynamicType import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtFunctionType import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtTypeAlias import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.KtTypeProjection import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.KtUserType class KSTypeReferenceImpl private constructor(val ktTypeReference: KtTypeReference) : KSTypeReference { companion object : KSObjectCache<KtTypeReference, KSTypeReferenceImpl>() { fun getCached(ktTypeReference: KtTypeReference) = cache.getOrPut(ktTypeReference) { KSTypeReferenceImpl(ktTypeReference) } } override val origin = Origin.KOTLIN override val location: Location by lazy { ktTypeReference.toLocation() } override val parent: KSNode? by lazy { var parentPsi = ktTypeReference.parent while ( parentPsi != null && parentPsi !is KtAnnotationEntry && parentPsi !is KtFunctionType && parentPsi !is KtClassOrObject && parentPsi !is KtFunction && parentPsi !is KtUserType && parentPsi !is KtProperty && parentPsi !is KtTypeAlias && parentPsi !is KtTypeProjection && parentPsi !is KtTypeParameter && parentPsi !is KtParameter ) { parentPsi = parentPsi.parent } when (parentPsi) { is KtAnnotationEntry -> KSAnnotationImpl.getCached(parentPsi) is KtFunctionType -> KSCallableReferenceImpl.getCached(parentPsi) is KtClassOrObject -> KSClassDeclarationImpl.getCached(parentPsi) is KtFunction -> KSFunctionDeclarationImpl.getCached(parentPsi) is KtUserType -> KSClassifierReferenceImpl.getCached(parentPsi) is KtProperty -> KSPropertyDeclarationImpl.getCached(parentPsi) is KtTypeAlias -> KSTypeAliasImpl.getCached(parentPsi) is KtTypeProjection -> KSTypeArgumentKtImpl.getCached(parentPsi) is KtTypeParameter -> KSTypeParameterImpl.getCached(parentPsi) is KtParameter -> KSValueParameterImpl.getCached(parentPsi) else -> null } } // Parenthesized type in grammar seems to be implemented as KtNullableType. private fun visitNullableType(visit: (KtNullableType) -> Unit) { var typeElement = ktTypeReference.typeElement while (typeElement is KtNullableType) { visit(typeElement) typeElement = typeElement.innerType } } // Annotations and modifiers are only allowed in one of the parenthesized type. // https://github.com/JetBrains/kotlin/blob/50e12239ef8141a45c4dca2bf0544be6191ecfb6/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java#L608 override val annotations: Sequence<KSAnnotation> by lazy { fun List<KtAnnotationEntry>.toKSAnnotations(): Sequence<KSAnnotation> = asSequence().map { KSAnnotationImpl.getCached(it) } val innerAnnotations = mutableListOf<Sequence<KSAnnotation>>() visitNullableType { innerAnnotations.add(it.annotationEntries.toKSAnnotations()) } (ktTypeReference.annotationEntries.toKSAnnotations() + innerAnnotations.asSequence().flatten()).memoized() } override val modifiers: Set<Modifier> by lazy { val innerModifiers = mutableSetOf<Modifier>() visitNullableType { innerModifiers.addAll(it.modifierList.toKSModifiers()) } ktTypeReference.toKSModifiers() + innerModifiers } override val element: KSReferenceElement by lazy { var typeElement = ktTypeReference.typeElement while (typeElement is KtNullableType) typeElement = typeElement.innerType when (typeElement) { is KtFunctionType -> KSCallableReferenceImpl.getCached(typeElement) is KtUserType -> KSClassifierReferenceImpl.getCached(typeElement) is KtDynamicType -> KSDynamicReferenceImpl.getCached(this) else -> throw IllegalStateException("Unexpected type element ${typeElement?.javaClass}, $ExceptionMessage") } } override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitTypeReference(this, data) } override fun resolve(): KSType = ResolverImpl.instance!!.resolveUserType(this) override fun toString(): String { return element.toString() } }
apache-2.0
beyama/winter
winter/src/main/kotlin/io/jentz/winter/TypeKey.kt
1
2193
package io.jentz.winter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Interface for all type keys. */ interface TypeKey<out R : Any> { val qualifier: Any? /** * Test if [other] has the same type. * Like [equals] without looking onto the [qualifier]. */ fun typeEquals(other: TypeKey<*>): Boolean } class ClassTypeKey<R : Any> @JvmOverloads constructor( val type: Class<R>, override val qualifier: Any? = null ) : TypeKey<R> { private var _hashCode = 0 override fun typeEquals(other: TypeKey<*>): Boolean { if (other === this) return true if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) if (other !is ClassTypeKey) return false return other.type == type } override fun equals(other: Any?): Boolean { return other is TypeKey<*> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type, qualifier) } return _hashCode } override fun toString(): String = "ClassTypeKey($type qualifier = $qualifier)" } abstract class GenericClassTypeKey<R : Any> @JvmOverloads constructor( override val qualifier: Any? = null ) : TypeKey<R> { private var _hashCode = 0 val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] override fun typeEquals(other: TypeKey<*>): Boolean { if (other === this) return true if (other is ClassTypeKey) return Types.equals(other.type, type) if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) return false } override fun equals(other: Any?): Boolean { return other is TypeKey<*> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type) _hashCode = 31 * _hashCode + (qualifier?.hashCode() ?: 0) } return _hashCode } override fun toString(): String = "GenericClassTypeKey($type qualifier = $qualifier)" }
apache-2.0
ac-opensource/Matchmaking-App
app/src/main/java/com/youniversals/playupgo/di/AppComponent.kt
1
335
package com.youniversals.playupgo.di import android.content.Context import dagger.Component import javax.inject.Singleton /** * * * YOYO HOLDINGS * @author A-Ar Andrew Concepcion * @version * @since 21/12/2016 */ @Singleton @Component(modules = arrayOf(AppModule::class)) interface AppComponent { fun context() : Context }
agpl-3.0
zalando/tracer
opentracing-kotlin/src/test/kotlin/org/zalando/opentracing/kotlin/suspend/TracerExtensionsTest.kt
1
1822
package org.zalando.opentracing.kotlin.suspend import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.collections.atLeastSize import io.kotest.matchers.maps.shouldContainAll import io.kotest.matchers.maps.shouldNotContainKey import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldHave import io.opentracing.Span import io.opentracing.mock.MockSpan import io.opentracing.mock.MockTracer import io.opentracing.tag.Tags import org.junit.jupiter.api.assertThrows class TracerExtensionsTest : FunSpec({ test("trace successful") { val tracer = MockTracer() var span: Span? = null tracer.trace( operation = "mock", component = "test" ) { it.setTag("works", true) span = it span shouldBe tracer.currentSpan() span shouldBe coroutineContext.activeSpan() } (span as MockSpan) .tags() shouldContainAll mapOf<String, Any>( "works" to true, Tags.COMPONENT.key to "test" ) } test("trace failure") { val tracer = MockTracer() var span: Span? = null assertThrows<Exception> { tracer.trace( operation = "mock", component = "test" ) { it.setTag("works", true) span = it throw Exception() it.setTag("not_work", true) } } (span as MockSpan).let { it.tags() shouldContainAll mapOf<String, Any>( "works" to true, Tags.COMPONENT.key to "test", Tags.ERROR.key to true ) it.tags() shouldNotContainKey "not_work" it.logEntries() shouldHave atLeastSize(1) } } })
mit
toastkidjp/Yobidashi_kt
editor/src/main/java/jp/toastkid/editor/usecase/PasteAsQuotationUseCase.kt
1
1380
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.editor.usecase import android.widget.EditText import jp.toastkid.editor.Quotation import jp.toastkid.editor.R import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.clip.Clipboard /** * @author toastkidjp */ class PasteAsQuotationUseCase( private val editText: EditText, private val contentViewModel: ContentViewModel ) { operator fun invoke() { val context = editText.context val primary = Clipboard.getPrimary(context) if (primary.isNullOrEmpty()) { return } val currentText = editText.text.toString() val currentCursor = editText.selectionStart editText.text.insert( editText.selectionStart, Quotation()(primary) ) contentViewModel .snackWithAction( context.getString(R.string.paste_as_quotation), context.getString(R.string.undo) ) { editText.setText(currentText) editText.setSelection(currentCursor) } } }
epl-1.0
chrisbanes/tivi
data/src/main/java/app/tivi/data/entities/RecommendedShowEntry.kt
1
1438
/* * 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 * * 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.tivi.data.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import app.tivi.data.PaginatedEntry @Entity( tableName = "recommended_entries", indices = [ Index(value = ["show_id"], unique = true) ], foreignKeys = [ ForeignKey( entity = TiviShow::class, parentColumns = arrayOf("id"), childColumns = arrayOf("show_id"), onUpdate = ForeignKey.CASCADE, onDelete = ForeignKey.CASCADE ) ] ) data class RecommendedShowEntry( @PrimaryKey(autoGenerate = true) override val id: Long = 0, @ColumnInfo(name = "show_id") override val showId: Long, @ColumnInfo(name = "page") override val page: Int ) : PaginatedEntry
apache-2.0
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/model/Teacher.kt
1
108
package ru.dyatel.tsuschedule.model data class Teacher( val id: String, val name: String )
mit
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/interceptor/annotations/jackson/AddJacksonAnnotationInterceptor.kt
1
1058
package wu.seal.jsontokotlin.interceptor.annotations.jackson import wu.seal.jsontokotlin.model.classscodestruct.DataClass import wu.seal.jsontokotlin.model.codeannotations.JacksonPropertyAnnotationTemplate import wu.seal.jsontokotlin.model.codeelements.KPropertyName import wu.seal.jsontokotlin.interceptor.IKotlinClassInterceptor import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass class AddJacksonAnnotationInterceptor : IKotlinClassInterceptor<KotlinClass> { override fun intercept(kotlinClass: KotlinClass): KotlinClass { if (kotlinClass is DataClass) { val addMoshiCodeGenAnnotationProperties = kotlinClass.properties.map { val camelCaseName = KPropertyName.makeLowerCamelCaseLegalName(it.originName) it.copy(annotations = JacksonPropertyAnnotationTemplate(it.originName).getAnnotations(),name = camelCaseName) } return kotlinClass.copy(properties = addMoshiCodeGenAnnotationProperties) } else { return kotlinClass } } }
gpl-3.0
MyDogTom/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/TooGenericExceptionThrown.kt
1
1215
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtThrowExpression /** * @author Artur Bosch */ class TooGenericExceptionThrown(config: Config) : Rule(config) { override val issue = Issue(javaClass.simpleName, Severity.Defect, "Thrown exception is too generic. " + "Prefer throwing project specific exceptions to handle error cases.") private val exceptions: Set<String> = valueOrDefault(THROWN_EXCEPTIONS_PROPERTY, THROWN_EXCEPTIONS).toHashSet() override fun visitThrowExpression(expression: KtThrowExpression) { expression.thrownExpression?.text?.substringBefore("(")?.let { if (it in exceptions) report(CodeSmell(issue, Entity.from(expression))) } super.visitThrowExpression(expression) } } const val THROWN_EXCEPTIONS_PROPERTY = "exceptions" val THROWN_EXCEPTIONS = listOf( "Error", "Exception", "NullPointerException", "Throwable", "RuntimeException" )
apache-2.0
dataloom/conductor-client
src/main/kotlin/com/openlattice/edm/processors/GetEntityTypeFromEntitySetEntryProcessor.kt
1
474
package com.openlattice.edm.processors import com.openlattice.edm.EntitySet import com.openlattice.rhizome.hazelcast.entryprocessors.AbstractReadOnlyRhizomeEntryProcessor import java.util.* class GetEntityTypeFromEntitySetEntryProcessor : AbstractReadOnlyRhizomeEntryProcessor<UUID, EntitySet, UUID?>() { override fun process(entry: MutableMap.MutableEntry<UUID, EntitySet?>): UUID? { val es = entry.value ?: return null return es.entityTypeId } }
gpl-3.0
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/RemoveEntitySetsFromLinkingEntitySetProcessorStreamSerializer.kt
1
1404
package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.SetStreamSerializers import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.hazelcast.processors.RemoveEntitySetsFromLinkingEntitySetProcessor import org.springframework.stereotype.Component @Component class RemoveEntitySetsFromLinkingEntitySetProcessorStreamSerializer: SelfRegisteringStreamSerializer<RemoveEntitySetsFromLinkingEntitySetProcessor> { override fun getTypeId(): Int { return StreamSerializerTypeIds.REMOVE_ENTITY_SETS_FROM_LINKING_ENTITY_SET_PROCESSOR.ordinal } override fun destroy() {} override fun getClazz(): Class<out RemoveEntitySetsFromLinkingEntitySetProcessor> { return RemoveEntitySetsFromLinkingEntitySetProcessor::class.java } override fun write(out: ObjectDataOutput?, `object`: RemoveEntitySetsFromLinkingEntitySetProcessor?) { SetStreamSerializers.fastUUIDSetSerialize( out, `object`!!.entitySetIds ) } override fun read(`in`: ObjectDataInput?): RemoveEntitySetsFromLinkingEntitySetProcessor { return RemoveEntitySetsFromLinkingEntitySetProcessor( SetStreamSerializers.fastUUIDSetDeserialize( `in` ) ) } }
gpl-3.0
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/client/Java8HttpClient.kt
1
3226
package org.http4k.client import org.http4k.core.Body import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.CLIENT_TIMEOUT import org.http4k.core.Status.Companion.CONNECTION_REFUSED import org.http4k.core.Status.Companion.UNKNOWN_HOST import java.io.ByteArrayInputStream import java.net.ConnectException import java.net.HttpURLConnection import java.net.SocketTimeoutException import java.net.URL import java.net.UnknownHostException import java.nio.ByteBuffer import java.time.Duration import java.time.Duration.ZERO /** * Use this legacy Java client when you're not yet on Java 11. */ object Java8HttpClient { @JvmStatic @JvmName("create") operator fun invoke(): HttpHandler = invoke(ZERO) @JvmStatic @JvmName("createWithTimeouts") operator fun invoke( readTimeout: Duration = ZERO, connectionTimeout: Duration = ZERO ): HttpHandler = { request: Request -> try { val connection = (URL(request.uri.toString()).openConnection() as HttpURLConnection).apply { this.readTimeout = readTimeout.toMillis().toInt() this.connectTimeout = connectionTimeout.toMillis().toInt() instanceFollowRedirects = false requestMethod = request.method.name doOutput = true doInput = true request.headers.forEach { addRequestProperty(it.first, it.second) } request.body.apply { if (this != Body.EMPTY) { val content = if (stream.available() == 0) payload.array().inputStream() else stream content.copyTo(outputStream) } } } val status = Status(connection.responseCode, connection.responseMessage.orEmpty()) val baseResponse = Response(status).body(connection.body(status)) connection.headerFields .filterKeys { it != null } // because response status line comes as a header with null key (*facepalm*) .map { header -> header.value.map { header.key to it } } .flatten() .fold(baseResponse) { acc, next -> acc.header(next.first, next.second) } } catch (e: UnknownHostException) { Response(UNKNOWN_HOST.toClientStatus(e)) } catch (e: ConnectException) { Response(CONNECTION_REFUSED.toClientStatus(e)) } catch (e: SocketTimeoutException) { Response(CLIENT_TIMEOUT.toClientStatus(e)) } } // Because HttpURLConnection closes the stream if a new request is made, we are forced to consume it straight away private fun HttpURLConnection.body(status: Status) = Body(resolveStream(status).readBytes().let { ByteBuffer.wrap(it) }) private fun HttpURLConnection.resolveStream(status: Status) = when { status.serverError || status.clientError -> errorStream else -> inputStream } ?: EMPTY_STREAM private val EMPTY_STREAM = ByteArrayInputStream(ByteArray(0)) }
apache-2.0
tutao/tutanota
app-android/app/src/main/java/de/tutao/tutanota/EncryptionUtils.kt
1
783
package de.tutao.tutanota import java.nio.charset.StandardCharsets import java.util.* @Throws(CryptoError::class) fun AndroidNativeCryptoFacade.decryptDate(encryptedData: String, sessionKey: ByteArray): Date { val decBytes = aesDecrypt(sessionKey, encryptedData) return Date(String(decBytes, StandardCharsets.UTF_8).toLong()) } @Throws(CryptoError::class) fun AndroidNativeCryptoFacade.decryptString(encryptedData: String, sessionKey: ByteArray): String { val decBytes = aesDecrypt(sessionKey, encryptedData) return String(decBytes, StandardCharsets.UTF_8) } @Throws(CryptoError::class) fun AndroidNativeCryptoFacade.decryptNumber(encryptedData: String, sessionKey: ByteArray): Long { val stringValue = decryptString(encryptedData, sessionKey) return stringValue.toLong() }
gpl-3.0
http4k/http4k
http4k-core/src/test/kotlin/org/http4k/lens/RequestContextKeyTest.kt
1
1314
package org.http4k.lens import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.throws import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.RequestContext import org.http4k.core.RequestContexts import org.junit.jupiter.api.Test import java.util.UUID class RequestContextKeyTest { private val contexts = RequestContexts() private val request = contexts(RequestContext(UUID.randomUUID()), Request(GET, "")) @Test fun `required key behaviour`() { val key = RequestContextKey.required<String>(contexts) assertThat({ key(request) }, throws(targetIsA<RequestContext>())) key("hello", request) assertThat(key(request), equalTo("hello")) } @Test fun `optional key behaviour`() { val key = RequestContextKey.optional<String>(contexts) assertThat(key(request), absent()) key("hello", request) assertThat(key(request), equalTo("hello")) } @Test fun `defaulted key behaviour`() { val key = RequestContextKey.defaulted(contexts, "world") assertThat(key(request), equalTo("world")) key("hello", request) assertThat(key(request), equalTo("hello")) } }
apache-2.0
http4k/http4k
src/docs/guide/howto/typesafe_your_api_with_lenses/example.kt
1
2262
package guide.howto.typesafe_your_api_with_lenses import org.http4k.core.Body import org.http4k.core.ContentType.Companion.TEXT_PLAIN import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.core.with import org.http4k.filter.ServerFilters import org.http4k.lens.Header import org.http4k.lens.Query import org.http4k.lens.boolean import org.http4k.lens.composite import org.http4k.lens.int import org.http4k.lens.string fun main() { data class Child(val name: String) data class Pageable(val sortAscending: Boolean, val page: Int, val maxResults: Int) val nameHeader = Header.required("name") val ageQuery = Query.int().optional("age") val childrenBody = Body.string(TEXT_PLAIN) .map({ it.split(",").map(::Child) }, { it.joinToString { it.name } }) .toLens() val pageable = Query.composite { Pageable( boolean().defaulted("sortAscending", true)(it), int().defaulted("page", 1)(it), int().defaulted("maxResults", 20)(it) ) } val endpoint = { request: Request -> val name: String = nameHeader(request) val age: Int? = ageQuery(request) val children: List<Child> = childrenBody(request) val pagination = pageable(request) val msg = """ $name is ${age ?: "unknown"} years old and has ${children.size} children (${children.joinToString { it.name }}) Pagination: $pagination """ Response(OK).with( Body.string(TEXT_PLAIN).toLens() of msg ) } val app = ServerFilters.CatchLensFailure.then(endpoint) val goodRequest = Request(GET, "http://localhost:9000").with( nameHeader of "Jane Doe", ageQuery of 25, childrenBody of listOf(Child("Rita"), Child("Sue")) ) println(listOf("", "Request:", goodRequest, app(goodRequest)).joinToString("\n")) val badRequest = Request(GET, "http://localhost:9000") .with(nameHeader of "Jane Doe") .query("age", "some illegal age!") println(listOf("", "Request:", badRequest, app(badRequest)).joinToString("\n")) }
apache-2.0
JanYoStudio/WhatAnime
app/src/main/java/pw/janyo/whatanime/ui/preference/internal/SettingsTileTitle.kt
1
524
package pw.janyo.whatanime.ui.preference.internal import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ProvideTextStyle import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.text.font.FontWeight @Composable internal fun SettingsTileTitle(title: String) { if (title.isBlank()) { return } ProvideTextStyle(value = MaterialTheme.typography.titleMedium) { Text(text = title, fontWeight = FontWeight.Normal) } }
apache-2.0
encircled/jPut
jput-core/src/main/java/cz/encircled/jput/context/ConfigurationBuilder.kt
1
4946
package cz.encircled.jput.context import cz.encircled.jput.annotation.PerformanceTest import cz.encircled.jput.annotation.PerformanceTrend import cz.encircled.jput.model.PerfTestConfiguration import cz.encircled.jput.model.TrendTestConfiguration import org.joda.time.Period import org.joda.time.format.PeriodFormatter import org.joda.time.format.PeriodFormatterBuilder import java.lang.reflect.Method fun Int.toPercentile(): Double = this / 100.0 object ConfigurationBuilder { private val durationFormatter: PeriodFormatter = PeriodFormatterBuilder() .appendHours().appendSuffix("h").appendSeparatorIfFieldsAfter(" ") .appendMinutes().appendSuffix("min").appendSeparatorIfFieldsAfter(" ") .appendSeconds().appendSuffix("sec") .toFormatter() /** * Builds [PerfTestConfiguration] from an [conf] annotation and available properties as well */ fun buildConfig(conf: PerformanceTest, method: Method): PerfTestConfiguration = fromContextParams(fromAnnotation(conf, method)) private val durationPattern: Regex = Regex("[\\d]+h [\\d]+min [\\d]+sec|[\\d]+min [\\d]+sec|[\\d]+sec|[\\d]+min|[\\d]+h [\\d]+min|[\\d]+h") /** * Parse duration in milliseconds from a [src] string in format like "1h 2min 3sec" */ fun parseDuration(src: String): Long { if (src.isBlank()) return 0L check(src.matches(durationPattern)) { "Duration property [$src] is invalid, must be in format: 1h 1min 1sec" } var enriched = src if (!enriched.contains("h")) { if (!enriched.contains("min")) enriched = "0min $enriched" enriched = "0h $enriched" } val formatter = durationFormatter return Period.parse(enriched, formatter).toStandardDuration().millis } // TODO trends via props? private fun fromContextParams(conf: PerfTestConfiguration): PerfTestConfiguration { val p = JPutContext.PROP_TEST_CONFIG + conf.testId val repeats = getOptionalProperty<Int>("$p.repeats") ?: conf.repeats val warmUp = getOptionalProperty<Int>("$p.warmUp") ?: conf.warmUp val delay = getOptionalProperty<Long>("$p.delay") ?: conf.delay val maxTimeLimit = getOptionalProperty<Long>("$p.maxTimeLimit") ?: conf.maxTimeLimit val averageTimeLimit = getOptionalProperty<Long>("$p.averageTimeLimit") ?: conf.avgTimeLimit val parallel = getOptionalProperty<Int>("$p.parallel") ?: conf.parallelCount val rampUp = getOptionalProperty<Long>("$p.rampUp") ?: conf.rampUp val maxAllowedExceptionsCount = getOptionalProperty<Long>("$p.maxAllowedExceptionsCount") ?: conf.maxAllowedExceptionsCount val percentiles = getOptionalMapProperty("$p.percentiles") ?: conf.percentiles return conf.copy(repeats = repeats, warmUp = warmUp, delay = delay, rampUp = rampUp, maxTimeLimit = maxTimeLimit, avgTimeLimit = averageTimeLimit, percentiles = percentiles, parallelCount = parallel, maxAllowedExceptionsCount = maxAllowedExceptionsCount) } private fun fromAnnotation(conf: PerformanceTest, method: Method): PerfTestConfiguration { val trendConfig = if (conf.trends.isNotEmpty()) fromAnnotation(conf.trends[0]) else null val testId = if (conf.testId.isBlank()) defaultTestId(method) else conf.testId val percentiles = conf.percentiles.associate { it.rank.toPercentile() to it.max } val runDuration = parseDuration(conf.runTime) val methodConfiguration = PerfTestConfiguration( testId = testId, warmUp = conf.warmUp, repeats = conf.repeats, runTime = runDuration, delay = conf.delay, maxTimeLimit = conf.maxTimeLimit, avgTimeLimit = conf.averageTimeLimit, percentiles = percentiles, parallelCount = conf.parallel, rampUp = conf.rampUp, isReactive = conf.isReactive, maxAllowedExceptionsCount = conf.maxAllowedExceptionsCount, continueOnException = conf.continueOnException, trendConfiguration = trendConfig ) return methodConfiguration.valid() } private fun fromAnnotation(conf: PerformanceTrend): TrendTestConfiguration = TrendTestConfiguration( sampleSize = conf.sampleSize, averageTimeThreshold = conf.averageTimeThreshold, useStandardDeviationAsThreshold = conf.useStandardDeviationAsThreshold, sampleSelectionStrategy = conf.sampleSelectionStrategy, noisePercentile = conf.noisePercentile.toPercentile() ) private fun defaultTestId(method: Method): String = "${method.declaringClass.simpleName}#${method.name}" }
apache-2.0
kotlin-es/kotlin-JFrame-standalone
03-start-async-message-application/src/main/kotlin/components/panel/PanelImpl.kt
3
948
package components.progressBar import java.awt.Component import java.awt.LayoutManager import javax.swing.BorderFactory import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JPanel /** * Created by vicboma on 05/12/16. */ class PanelImpl internal constructor( val layoutManager: LayoutManager, override val progressBar: ProgressBar?, override val textArea: TextArea) : JPanel(layoutManager) , Panel { companion object { fun create(layout: LayoutManager,progressBar: ProgressBar?, textArea: TextArea): Panel { return PanelImpl(layout,progressBar, textArea) } } init{ setBorder(BorderFactory.createTitledBorder("")) setAlignmentX(Component.CENTER_ALIGNMENT) setLayout(BoxLayout(this, BoxLayout.Y_AXIS)) add(progressBar?.component()!!) add(textArea.component()) } override fun component() : JComponent { return this } }
mit
lewinskimaciej/planner
app/src/main/java/com/atc/planner/commons/GlideAppModule.kt
1
181
package com.atc.planner.commons import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule class GlideModule : AppGlideModule()
mit
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/ui/topic/Reply.kt
1
1508
package im.fdx.v2ex.ui.topic import android.os.Parcelable import im.fdx.v2ex.ui.member.Member import kotlinx.parcelize.Parcelize /** * Created by a708 on 15-9-8. * 评论模型,用于传递从JSON获取到的数据。 * 以后将加入添加评论功能。 */ //{ // "id" : 2826846, // "thanks" : 0, // "content" : "关键你是男还是女?", // "content_rendered" : "关键你是男还是女?", // "member" : { // "id" : 27619, // "username" : "hengzhang", // "tagline" : "我白天是个民工,晚上就是个有抱负的IT人士。", // "avatar_mini" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_mini.png?m=1413707431", // "avatar_normal" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_normal.png?m=1413707431", // "avatar_large" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_large.png?m=1413707431" // }, // "created" : 1453030169, // "last_modified" : 1453030169 // } @Parcelize data class Reply(var id: String = "", var content: String = "", var content_rendered: String = "", var thanks: Int = 0, var created: Long = 0, var isThanked: Boolean = false, var member: Member? = null, var isLouzu: Boolean = false, var showTime: String = "", var rowNum: Int = 0, ) : Parcelable { override fun toString() = "Reply{content='$content_rendered}" }
apache-2.0
LordAkkarin/Beacon
ui/src/main/kotlin/tv/dotstart/beacon/ui/controller/RepositoryEditorController.kt
1
2608
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.ui.controller import com.jfoenix.controls.JFXButton import com.jfoenix.controls.JFXTextField import javafx.beans.binding.Bindings import javafx.beans.property.ObjectProperty import javafx.beans.property.ReadOnlyObjectProperty import javafx.beans.property.SimpleObjectProperty import javafx.fxml.FXML import javafx.fxml.Initializable import tv.dotstart.beacon.core.delegate.logManager import tv.dotstart.beacon.ui.delegate.property import java.net.URI import java.net.URL import java.util.* /** * @author [Johannes Donath](mailto:[email protected]) * @date 10/12/2020 */ class RepositoryEditorController : Initializable { @FXML private lateinit var repositoryUriTextField: JFXTextField @FXML private lateinit var saveButton: JFXButton /** * @see repositoryUriProperty */ private val _repositoryUriProperty: ObjectProperty<URI> = SimpleObjectProperty() /** * Identifies the repository URI given by the user. */ val repositoryUriProperty: ReadOnlyObjectProperty<URI> get() = this._repositoryUriProperty /** * @see repositoryUriProperty */ val repositoryUri by property(_repositoryUriProperty) companion object { private val logger by logManager() } override fun initialize(location: URL?, resources: ResourceBundle?) { val uriBinding = Bindings.createObjectBinding( { try { this.repositoryUriTextField.text .takeIf(String::isNotBlank) ?.trim() ?.let(URI::create) } catch (ex: IllegalArgumentException) { logger.debug("Illegal repository URI passed", ex) null } }, this.repositoryUriTextField.textProperty()) this._repositoryUriProperty.bind(uriBinding) this.saveButton.disableProperty().bind(uriBinding.isNull) } fun onSave() { this.saveButton.scene.window.hide() } }
apache-2.0
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/RuleSet.kt
1
1498
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.api.internal.BaseRule import io.gitlab.arturbosch.detekt.api.internal.PathFilters import io.gitlab.arturbosch.detekt.api.internal.absolutePath import io.gitlab.arturbosch.detekt.api.internal.validateIdentifier import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import java.nio.file.Paths typealias RuleSetId = String /** * A rule set is a collection of rules and must be defined within a rule set provider implementation. */ class RuleSet(val id: RuleSetId, val rules: List<BaseRule>) { init { validateIdentifier(id) } /** * Is used to determine if a given [KtFile] should be analyzed at all. */ @Deprecated("Exposes detekt-core implementation details.") var pathFilters: PathFilters? = null /** * Visits given file with all rules of this rule set, returning a list * of all code smell findings. */ @Deprecated("Exposes detekt-core implementation details.") fun accept(file: KtFile, bindingContext: BindingContext = BindingContext.EMPTY): List<Finding> = if (isFileIgnored(file)) { emptyList() } else { rules.flatMap { it.visitFile(file, bindingContext) it.findings } } @Suppress("DEPRECATION") private fun isFileIgnored(file: KtFile) = pathFilters?.isIgnored(Paths.get(file.absolutePath())) == true }
apache-2.0
tipsy/javalin
javalin/src/main/java/io/javalin/core/util/Util.kt
1
8202
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.core.util import io.javalin.http.Context import io.javalin.http.InternalServerErrorResponse import java.io.ByteArrayInputStream import java.io.File import java.net.URL import java.net.URLEncoder import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.* import java.util.zip.Adler32 import java.util.zip.CheckedInputStream object Util { @JvmStatic fun normalizeContextPath(contextPath: String) = ("/$contextPath").replace("/{2,}".toRegex(), "/").removeSuffix("/") @JvmStatic fun prefixContextPath(contextPath: String, path: String) = if (path == "*") path else ("$contextPath/$path").replace("/{2,}".toRegex(), "/") fun classExists(className: String) = try { Class.forName(className) true } catch (e: ClassNotFoundException) { false } private fun serviceImplementationExists(className: String) = try { val serviceClass = Class.forName(className) val loader = ServiceLoader.load(serviceClass) loader.any() } catch (e: ClassNotFoundException) { false } fun dependencyIsPresent(dependency: OptionalDependency) = try { ensureDependencyPresent(dependency) true } catch (e: Exception) { false } private val dependencyCheckCache = HashMap<String, Boolean>() fun ensureDependencyPresent(dependency: OptionalDependency, startupCheck: Boolean = false) { if (dependencyCheckCache[dependency.testClass] == true) { return } if (!classExists(dependency.testClass)) { val message = missingDependencyMessage(dependency) if (startupCheck) { throw IllegalStateException(message) } else { JavalinLogger.warn(message) throw InternalServerErrorResponse(message) } } dependencyCheckCache[dependency.testClass] = true } internal fun missingDependencyMessage(dependency: OptionalDependency) = """| |------------------------------------------------------------------- |Missing dependency '${dependency.displayName}'. Add the dependency. | |pom.xml: |<dependency> | <groupId>${dependency.groupId}</groupId> | <artifactId>${dependency.artifactId}</artifactId> | <version>${dependency.version}</version> |</dependency> | |build.gradle: |implementation group: '${dependency.groupId}', name: '${dependency.artifactId}', version: '${dependency.version}' | |Find the latest version here: |https://search.maven.org/search?q=${URLEncoder.encode("g:" + dependency.groupId + " AND a:" + dependency.artifactId, "UTF-8")} |-------------------------------------------------------------------""".trimMargin() fun pathToList(pathString: String): List<String> = pathString.split("/").filter { it.isNotEmpty() } @JvmStatic fun printHelpfulMessageIfLoggerIsMissing() { if (!loggingLibraryExists()) { System.err.println(""" |------------------------------------------------------------------- |${missingDependencyMessage(OptionalDependency.SLF4JSIMPLE)} |------------------------------------------------------------------- |OR |------------------------------------------------------------------- |${missingDependencyMessage(OptionalDependency.SLF4J_PROVIDER_API)} and |${missingDependencyMessage(OptionalDependency.SLF4J_PROVIDER_SIMPLE)} |------------------------------------------------------------------- |Visit https://javalin.io/documentation#logging if you need more help""".trimMargin()) } } fun loggingLibraryExists(): Boolean { return classExists(OptionalDependency.SLF4JSIMPLE.testClass) || serviceImplementationExists(OptionalDependency.SLF4J_PROVIDER_API.testClass) } @JvmStatic fun logJavalinBanner(showBanner: Boolean) { if (showBanner) JavalinLogger.info("\n" + """ | __ __ _ __ __ | / /____ _ _ __ ____ _ / /(_)____ / // / | __ / // __ `/| | / // __ `// // // __ \ / // /_ |/ /_/ // /_/ / | |/ // /_/ // // // / / / /__ __/ |\____/ \__,_/ |___/ \__,_//_//_//_/ /_/ /_/ | | https://javalin.io/documentation |""".trimMargin()) } @JvmStatic fun logJavalinVersion() = try { val properties = Properties().also { val propertiesPath = "META-INF/maven/io.javalin/javalin/pom.properties" it.load(this.javaClass.classLoader.getResourceAsStream(propertiesPath)) } val (version, buildTime) = listOf(properties.getProperty("version")!!, properties.getProperty("buildTime")!!) JavalinLogger.startup("You are running Javalin $version (released ${formatBuildTime(buildTime)}).") } catch (e: Exception) { // it's not that important } private fun formatBuildTime(buildTime: String): String? = try { val (release, now) = listOf(Instant.parse(buildTime), Instant.now()) val formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy").withLocale(Locale.US).withZone(ZoneId.of("Z")) formatter.format(release) + if (now.isAfter(release.plus(90, ChronoUnit.DAYS))) { ". Your Javalin version is ${ChronoUnit.DAYS.between(release, now)} days old. Consider checking for a newer version." } else "" } catch (e: Exception) { null // it's not that important } fun getChecksumAndReset(inputStream: ByteArrayInputStream): String { inputStream.mark(Int.MAX_VALUE) //it's all in memory so there is no readAheadLimit val cis = CheckedInputStream(inputStream, Adler32()) var byte = cis.read() while (byte > -1) { byte = cis.read() } inputStream.reset() return cis.checksum.value.toString() } @JvmStatic fun getResourceUrl(path: String): URL? = this.javaClass.classLoader.getResource(path) @JvmStatic fun getWebjarPublicPath(ctx: Context, dependency: OptionalDependency): String { return "${ctx.contextPath()}/webjars/${dependency.artifactId}/${dependency.version}" } @JvmStatic fun assertWebjarInstalled(dependency: OptionalDependency) = try { getWebjarResourceUrl(dependency) } catch (e: Exception) { JavalinLogger.warn(missingDependencyMessage(dependency)) } @JvmStatic fun getWebjarResourceUrl(dependency: OptionalDependency): URL? { val webjarBaseUrl = "META-INF/resources/webjars" return getResourceUrl("$webjarBaseUrl/${dependency.artifactId}/${dependency.version}") } fun getFileUrl(path: String): URL? = if (File(path).exists()) File(path).toURI().toURL() else null fun isKotlinClass(clazz: Class<*>): Boolean { try { for (annotation in clazz.declaredAnnotations) { // Note: annotation.simpleClass can be used if kotlin-reflect is available. if (annotation.annotationClass.toString().contains("kotlin.Metadata")) { return true } } } catch (ignored: Exception) { } return false } @JvmStatic fun getPort(e: Exception) = e.message!!.takeLastWhile { it != ':' } fun <T : Any?> findByClass(map: Map<Class<out Exception>, T>, exceptionClass: Class<out Exception>): T? = map.getOrElse(exceptionClass) { var superclass = exceptionClass.superclass while (superclass != null) { if (map.containsKey(superclass)) { return map[superclass] } superclass = superclass.superclass } return null } }
apache-2.0
tipsy/javalin
javalin-graphql/src/test/kotlin/io/javalin/plugin/graphql/helpers/ContextFactoryExample.kt
1
397
package io.javalin.plugin.graphql.helpers import com.expediagroup.graphql.server.execution.GraphQLContextFactory import io.javalin.http.Context class ContextFactoryExample : GraphQLContextFactory<ContextExample, Context> { override suspend fun generateContext(request: Context): ContextExample { return ContextExample(request.header("Authorization")?.removePrefix("Beare ")) } }
apache-2.0
prfarlow1/nytc-meet
app/src/main/kotlin/org/needhamtrack/nytc/screens/event/EventActivity.kt
1
2812
package org.needhamtrack.nytc.screens.event import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_event.* import org.needhamtrack.nytc.R import org.needhamtrack.nytc.base.BaseMvpActivity import org.needhamtrack.nytc.base.PresenterConfiguration import org.needhamtrack.nytc.models.AttemptResult import org.needhamtrack.nytc.models.Event import org.needhamtrack.nytc.screens.event.editmark.EditMarkDialogFragment import org.needhamtrack.nytc.screens.event.officiate.OfficiateFragment import org.needhamtrack.nytc.screens.event.overview.OverviewFragment class EventActivity : BaseMvpActivity<EventContract.Presenter>(), EventContract.View, EditMarkDialogFragment.SaveMarkClickListener { private val overviewFragment by lazy { supportFragmentManager.findFragmentByTag(OverviewFragment.TAG) as? OverviewFragment ?: OverviewFragment.newInstance(event) } private val officiateFragment by lazy { supportFragmentManager.findFragmentByTag(OfficiateFragment.TAG) as? OfficiateFragment ?: OfficiateFragment.newInstance(event) } private val event by lazy { intent.getSerializableExtra(EVENT_EXTRA) as Event } override fun onViewCreated(savedInstanceState: Bundle?) { super.onViewCreated(savedInstanceState) setSupportActionBar(toolbar) goToOverview() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_event, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.switch_view -> { return presenter.switchViewsClick() } } return super.onOptionsItemSelected(item) } override fun goToOverview() { supportFragmentManager.beginTransaction().replace(R.id.content_frame, overviewFragment, OverviewFragment.TAG).commit() } override fun goToGuidedOfficiate() { supportFragmentManager.beginTransaction().replace(R.id.content_frame, officiateFragment, OfficiateFragment.TAG).commit() } override val layoutResourceId = R.layout.activity_event override fun createPresenter(configuration: PresenterConfiguration): EventContract.Presenter { return EventPresenter(this, configuration, event) } override fun onSaveClick(runnerId: Int, attemptNumber: Int, attemptResult: AttemptResult) { overviewFragment.onSaveClick(runnerId, attemptNumber, attemptResult) } companion object { const val EVENT_EXTRA = "_event-extra_" fun startIntent(context: Context, event: Event) = Intent(context, EventActivity::class.java) .apply { putExtra(EVENT_EXTRA, event) } } }
mit
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/di/qualifiers/LocalRepo.kt
1
201
package com.moviereel.di.qualifiers import javax.inject.Qualifier /** * @author lusinabrian on 26/07/17. * @Notes */ @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class LocalRepo
mit
alyphen/guildford-game-jam-2016
core/src/main/kotlin/com/seventh_root/guildfordgamejam/level/Level.kt
1
340
package com.seventh_root.guildfordgamejam.level import com.badlogic.ashley.core.Entity import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Texture class Level(val file: FileHandle, val buttonTexture: Texture, val name: String, val entities: List<Entity>) { fun dispose() { buttonTexture.dispose() } }
apache-2.0
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/payload/ExternalBackupManager.kt
1
11451
package com.samourai.wallet.payload import android.Manifest import android.app.Activity import android.app.Activity.RESULT_OK import android.app.Application import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Environment import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.samourai.wallet.BuildConfig import com.samourai.wallet.R import com.samourai.wallet.util.PrefsUtil import kotlinx.coroutines.* import java.io.File /** * samourai-wallet-android * * Utility for managing android scope storage and legacy storage for external backups * * Refs: * https://developer.android.com/about/versions/11/privacy/storage * https://developer.android.com/guide/topics/permissions/overview */ object ExternalBackupManager { private lateinit var appContext: Application private const val strOptionalBackupDir = "/samourai" private const val STORAGE_REQ_CODE = 4866 private const val READ_WRITE_EXTERNAL_PERMISSION_CODE = 2009 private var backUpDocumentFile: DocumentFile? = null private const val strBackupFilename = "samourai.txt" private val permissionState = MutableLiveData(false) private val scope = CoroutineScope(Dispatchers.Main) + SupervisorJob() /** * Shows proper dialog for external storage permission * * Invokes API specific storage requests. * scoped storage for API 29 * normal external storage request for API below 29 */ @JvmStatic fun askPermission(activity: Activity) { fun ask() { if (requireScoped()) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION } activity.startActivityForResult(intent, STORAGE_REQ_CODE) } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.requestPermissions( arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ), READ_WRITE_EXTERNAL_PERMISSION_CODE ) } } } var titleId = R.string.permission_alert_dialog_title_external var message = appContext.getString(R.string.permission_dialog_message_external) if (requireScoped()) { titleId = R.string.permission_alert_dialog_title_external_scoped message = appContext.getString(R.string.permission_dialog_scoped) } val builder = MaterialAlertDialogBuilder(activity) builder.setTitle(titleId) .setMessage(message) .setPositiveButton(if (requireScoped()) R.string.choose else R.string.ok) { dialog, _ -> dialog.dismiss() ask() }.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }.show() } /** * Attach to root application object to retrieve context * Ref: [com.samourai.wallet.SamouraiApplication] onCreate */ @JvmStatic fun attach(application: Application) { this.appContext = application if (requireScoped()) { this.initScopeStorage() } } @JvmStatic fun write(content: String) { scope.launch(Dispatchers.IO) { try { if (requireScoped()) { writeScopeStorage(content) } else { writeLegacyStorage(content) } } catch (e: Exception) { throw CancellationException(e.message) } } } @JvmStatic fun read(): String? = if (requireScoped()) { readScoped() } else { readLegacy() } private fun initScopeStorage() { if (PrefsUtil.getInstance(appContext).has(PrefsUtil.BACKUP_FILE_PATH)) { val path: String = PrefsUtil.getInstance(appContext).getValue(PrefsUtil.BACKUP_FILE_PATH, ""); if (path.isNotEmpty()) { if (DocumentFile.fromTreeUri(appContext, path.toUri()) == null) { permissionState.postValue(false) return } val documentsTree = DocumentFile.fromTreeUri(appContext, path.toUri())!! var hasPerm = false appContext.contentResolver.persistedUriPermissions.forEach { uri -> if (uri.uri.toString() == path) { permissionState.postValue(true) hasPerm = true } } if (!hasPerm) { return } documentsTree.listFiles().forEach { doc -> if (BuildConfig.FLAVOR == "staging") { if (doc.isDirectory && doc.name == "staging") { doc.findFile(strBackupFilename)?.let { backUpDocumentFile = it } } } else { if (doc.isFile && doc.name == strBackupFilename) { backUpDocumentFile = doc } } } if (backUpDocumentFile == null) { backUpDocumentFile = if (BuildConfig.FLAVOR == "staging") { val stagingDir = documentsTree.createDirectory("staging") stagingDir?.createFile("text/plain ", strBackupFilename) } else { documentsTree.createFile("text/plain ", strBackupFilename) } } } } } @JvmStatic private fun writeScopeStorage(content: String) { if (backUpDocumentFile == null) { throw Exception("Backup file not available") } if (!backUpDocumentFile!!.canRead()) { throw Exception("Backup file is not readable") } val stream = appContext.contentResolver.openOutputStream(backUpDocumentFile!!.uri) stream?.write(content.encodeToByteArray()) } @JvmStatic private fun writeLegacyStorage(content: String) { if (hasPermission()) { if (!getLegacyBackupFile().exists()) { getLegacyBackupFile().createNewFile() } getLegacyBackupFile().writeText(content) } else { throw Exception("Backup file not available") } } @JvmStatic fun readScoped(): String? { if (backUpDocumentFile == null) { throw Exception("Backup file not available") } if (!backUpDocumentFile!!.canRead()) { throw Exception("Backup file is not readable") } val stream = appContext.contentResolver.openInputStream(backUpDocumentFile!!.uri) return stream?.readBytes()?.decodeToString() } private fun readLegacy(): String? { return if (hasPermission()) { getLegacyBackupFile().readText() } else { null } } @JvmStatic fun lastUpdated(): Long? { return if (requireScoped()) { backUpDocumentFile?.lastModified() } else { if (hasPermission() && getLegacyBackupFile().exists()) { getLegacyBackupFile().lastModified() } else { null } } } /** * Checks both scoped and non-scoped storage permissions * * For scoped storage method will use persistedUriPermissions array from * contentResolver to compare allowed path that store in the prefs * */ @JvmStatic fun hasPermissions(): Boolean { if (requireScoped()) { if (backUpDocumentFile == null) { return false } val path: String = PrefsUtil.getInstance(appContext).getValue(PrefsUtil.BACKUP_FILE_PATH, ""); appContext.contentResolver.persistedUriPermissions.forEach { uri -> if (uri.uri.toString() == path) { return true } } return false } else { return hasPermission() } } @JvmStatic fun backupAvailable(): Boolean { if (requireScoped()) { if (backUpDocumentFile == null ) { return false } if (backUpDocumentFile!!.canRead()) { return backUpDocumentFile!!.exists() } return false } else { return getLegacyBackupFile().exists() } } /** * Handles permission result that received in an activity * * Any Activity that using this class should invoke this method in onActivityResult */ @JvmStatic fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent?, application: Application ) { val directoryUri = data?.data ?: return if (requestCode == STORAGE_REQ_CODE && resultCode == RESULT_OK) { PrefsUtil.getInstance(application) .setValue(PrefsUtil.BACKUP_FILE_PATH, directoryUri.toString()) this.appContext.contentResolver.takePersistableUriPermission( directoryUri, Intent.FLAG_GRANT_READ_URI_PERMISSION ) this.attach(application) permissionState.postValue(true) } } /** * For older api's ( below API 29) */ @Suppress("DEPRECATION") private fun getLegacyBackupFile(): File { val directory = Environment.DIRECTORY_DOCUMENTS val dir: File? = if (appContext.packageName.contains("staging")) { Environment.getExternalStoragePublicDirectory("$directory$strOptionalBackupDir/staging") } else { Environment.getExternalStoragePublicDirectory("$directory$strOptionalBackupDir") } if (!dir?.exists()!!) { dir.mkdirs() dir.setWritable(true) dir.setReadable(true) } val backupFile = File(dir, strBackupFilename); return backupFile } private fun hasPermission(): Boolean { val readPerm = ContextCompat.checkSelfPermission( appContext, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED val writePerm = ContextCompat.checkSelfPermission( appContext, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED return (readPerm && writePerm) } private fun requireScoped() = Build.VERSION.SDK_INT >= 29 @JvmStatic fun getPermissionStateLiveData(): LiveData<Boolean> { return permissionState } @JvmStatic fun dispose() { if (scope.isActive) { scope.cancel() } } }
unlicense
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/ElementDao.kt
1
3411
package de.westnordost.streetcomplete.data.osm.mapdata import javax.inject.Inject import de.westnordost.streetcomplete.data.osm.mapdata.ElementType.* /** Stores OSM elements. Actually, stores nothing, but delegates the work to a NodeDao, WayDao and * a RelationDao. :-P */ class ElementDao @Inject constructor( private val nodeDao: NodeDao, private val wayDao: WayDao, private val relationDao: RelationDao ) { fun put(element: Element) { when (element) { is Node -> nodeDao.put(element) is Way -> wayDao.put(element) is Relation -> relationDao.put(element) } } fun get(type: ElementType, id: Long): Element? { return when (type) { NODE -> nodeDao.get(id) WAY -> wayDao.get(id) RELATION -> relationDao.get(id) } } fun delete(type: ElementType, id: Long) { when (type) { NODE -> nodeDao.delete(id) WAY -> wayDao.delete(id) RELATION -> relationDao.delete(id) } } fun putAll(elements: Iterable<Element>) { nodeDao.putAll(elements.filterIsInstance<Node>()) wayDao.putAll(elements.filterIsInstance<Way>()) relationDao.putAll(elements.filterIsInstance<Relation>()) } fun getAll(keys: Iterable<ElementKey>): List<Element> { val elementIds = keys.toElementIds() if (elementIds.size == 0) return emptyList() val result = ArrayList<Element>(elementIds.size) result.addAll(nodeDao.getAll(elementIds.nodes)) result.addAll(wayDao.getAll(elementIds.ways)) result.addAll(relationDao.getAll(elementIds.relations)) return result } fun deleteAll(keys: Iterable<ElementKey>): Int { val elementIds = keys.toElementIds() if (elementIds.size == 0) return 0 // delete first relations, then ways, then nodes because relations depend on ways depend on nodes return relationDao.deleteAll(elementIds.relations) + wayDao.deleteAll(elementIds.ways) + nodeDao.deleteAll(elementIds.nodes) } fun clear() { relationDao.clear() wayDao.clear() nodeDao.clear() } fun getIdsOlderThan(timestamp: Long, limit: Int? = null): List<ElementKey> { val result = mutableListOf<ElementKey>() // get relations first, then ways, then nodes because relations depend on ways depend on nodes. result.addAll(relationDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(RELATION, it) }) result.addAll(wayDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(WAY, it) }) result.addAll(nodeDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(NODE, it) }) return result } } private data class ElementIds(val nodes: List<Long>, val ways: List<Long>, val relations: List<Long>) { val size: Int get() = nodes.size + ways.size + relations.size } private fun Iterable<ElementKey>.toElementIds(): ElementIds { val nodes = ArrayList<Long>() val ways = ArrayList<Long>() val relations = ArrayList<Long>() for (key in this) { when(key.type) { NODE -> nodes.add(key.id) WAY -> ways.add(key.id) RELATION -> relations.add(key.id) } } return ElementIds(nodes, ways, relations) }
gpl-3.0
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CollectionFragment.kt
1
24465
package com.boardgamegeek.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Bundle import android.util.SparseBooleanArray import android.view.* import android.widget.LinearLayout import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentCollectionBinding import com.boardgamegeek.databinding.RowCollectionBinding import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.filterer.CollectionFilterer import com.boardgamegeek.filterer.CollectionStatusFilterer import com.boardgamegeek.pref.SettingsActivity import com.boardgamegeek.pref.SyncPrefs import com.boardgamegeek.pref.noPreviousCollectionSync import com.boardgamegeek.provider.BggContract import com.boardgamegeek.sorter.CollectionSorter import com.boardgamegeek.sorter.CollectionSorterFactory import com.boardgamegeek.ui.CollectionFragment.CollectionAdapter.CollectionItemViewHolder import com.boardgamegeek.ui.dialog.* import com.boardgamegeek.ui.viewmodel.CollectionViewViewModel import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration.SectionCallback import com.boardgamegeek.util.HttpUtils.encodeForUrl import com.google.android.material.chip.Chip import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase import timber.log.Timber import java.text.NumberFormat class CollectionFragment : Fragment(), ActionMode.Callback { private var _binding: FragmentCollectionBinding? = null private val binding get() = _binding!! private var viewId = CollectionView.DEFAULT_DEFAULT_ID private var viewName = "" private var sorter: CollectionSorter? = null private val filters = mutableListOf<CollectionFilterer>() private var isCreatingShortcut = false private var changingGamePlayId: Long = 0 private var actionMode: ActionMode? = null private lateinit var firebaseAnalytics: FirebaseAnalytics private val viewModel by activityViewModels<CollectionViewViewModel>() private val adapter by lazy { CollectionAdapter() } private val prefs: SharedPreferences by lazy { requireContext().preferences() } private val collectionSorterFactory: CollectionSorterFactory by lazy { CollectionSorterFactory(requireContext()) } private val numberFormat = NumberFormat.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) firebaseAnalytics = Firebase.analytics isCreatingShortcut = arguments?.getBoolean(KEY_IS_CREATING_SHORTCUT) ?: false changingGamePlayId = arguments?.getLong(KEY_CHANGING_GAME_PLAY_ID, BggContract.INVALID_ID.toLong()) ?: BggContract.INVALID_ID.toLong() setHasOptionsMenu(true) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentCollectionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.listView.adapter = adapter if (isCreatingShortcut) { binding.swipeRefreshLayout.longSnackbar(R.string.msg_shortcut_create) } else if (changingGamePlayId != BggContract.INVALID_ID.toLong()) { binding.swipeRefreshLayout.longSnackbar(R.string.msg_change_play_game) } binding.footerToolbar.inflateMenu(R.menu.collection_fragment) binding.footerToolbar.setOnMenuItemClickListener(footerMenuListener) binding.footerToolbar.menu.apply { if (isCreatingShortcut || changingGamePlayId != BggContract.INVALID_ID.toLong()) { findItem(R.id.menu_collection_random_game)?.isVisible = false findItem(R.id.menu_create_shortcut)?.isVisible = false findItem(R.id.menu_collection_view_save)?.isVisible = false findItem(R.id.menu_collection_view_delete)?.isVisible = false findItem(R.id.menu_share)?.isVisible = false } else { findItem(R.id.menu_collection_random_game)?.isVisible = true findItem(R.id.menu_create_shortcut)?.isVisible = true findItem(R.id.menu_collection_view_save)?.isVisible = true findItem(R.id.menu_collection_view_delete)?.isVisible = true findItem(R.id.menu_share)?.isVisible = true } } setEmptyText() binding.emptyButton.setOnClickListener { startActivity(Intent(context, SettingsActivity::class.java)) } binding.swipeRefreshLayout.setBggColors() binding.swipeRefreshLayout.setOnRefreshListener { binding.swipeRefreshLayout.isRefreshing = viewModel.refresh() } binding.progressBar.show() viewModel.selectedViewId.observe(viewLifecycleOwner) { binding.progressBar.show() binding.listView.isVisible = false viewId = it binding.footerToolbar.menu.findItem(R.id.menu_create_shortcut)?.isEnabled = it > 0 } viewModel.selectedViewName.observe(viewLifecycleOwner) { viewName = it } viewModel.views.observe(viewLifecycleOwner) { binding.footerToolbar.menu.findItem(R.id.menu_collection_view_delete)?.isEnabled = it?.isNotEmpty() == true } viewModel.effectiveSortType.observe(viewLifecycleOwner) { sortType: Int -> sorter = collectionSorterFactory.create(sortType) binding.sortDescriptionView.text = if (sorter == null) "" else requireActivity().getString(R.string.by_prefix, sorter?.description.orEmpty()) val hasFiltersApplied = filters.size > 0 val hasSortApplied = sorter?.let { it.type != CollectionSorterFactory.TYPE_DEFAULT } ?: false binding.footerToolbar.menu.findItem(R.id.menu_collection_view_save)?.isEnabled = hasFiltersApplied || hasSortApplied } viewModel.effectiveFilters.observe(viewLifecycleOwner) { filterList -> filters.clear() filterList?.let { filters.addAll(filterList) } setEmptyText() bindFilterButtons() val hasFiltersApplied = filters.size > 0 val hasSortApplied = sorter?.let { it.type != CollectionSorterFactory.TYPE_DEFAULT } ?: false binding.footerToolbar.menu.findItem(R.id.menu_collection_view_save)?.isEnabled = hasFiltersApplied || hasSortApplied } viewModel.items.observe(viewLifecycleOwner) { it?.let { showData(it) } } viewModel.isFiltering.observe(viewLifecycleOwner) { it?.let { if (it) binding.progressBar.show() else binding.progressBar.hide() } } viewModel.isRefreshing.observe(viewLifecycleOwner) { it?.let { binding.swipeRefreshLayout.isRefreshing = it } } viewModel.refresh() } private fun showData(items: List<CollectionItemEntity>) { adapter.items = items binding.footerToolbar.menu.apply { findItem(R.id.menu_collection_random_game)?.isEnabled = items.isNotEmpty() findItem(R.id.menu_share)?.isEnabled = items.isNotEmpty() } binding.listView.addHeader(adapter) binding.rowCountView.text = numberFormat.format(items.size) binding.emptyContainer.isVisible = items.isEmpty() binding.listView.isVisible = items.isNotEmpty() binding.progressBar.hide() } private val footerMenuListener = Toolbar.OnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_collection_random_game -> { firebaseAnalytics.logEvent("RandomGame", null) adapter.items.random().let { GameActivity.start(requireContext(), it.gameId, it.gameName, it.thumbnailUrl, it.heroImageUrl) } return@OnMenuItemClickListener true } R.id.menu_create_shortcut -> if (viewId > 0) { viewModel.createShortcut() return@OnMenuItemClickListener true } R.id.menu_collection_view_save -> { val name = if (viewId <= 0) "" else viewName val dialog = SaveViewDialogFragment.newInstance(name, createViewDescription(sorter, filters)) dialog.show([email protected], "view_save") return@OnMenuItemClickListener true } R.id.menu_collection_view_delete -> { DeleteViewDialogFragment.newInstance().show([email protected], "view_delete") return@OnMenuItemClickListener true } R.id.menu_share -> { shareCollection() return@OnMenuItemClickListener true } R.id.menu_collection_sort -> { CollectionSortDialogFragment.newInstance(sorter?.type ?: CollectionSorterFactory.TYPE_DEFAULT) .show([email protected], "collection_sort") return@OnMenuItemClickListener true } R.id.menu_collection_filter -> { CollectionFilterDialogFragment.newInstance(filters.map { it.type }) .show([email protected], "collection_filter") return@OnMenuItemClickListener true } } launchFilterDialog(item.itemId) } private fun shareCollection() { val description: String = when { viewId > 0 && viewName.isNotEmpty() -> viewName filters.size > 0 -> getString(R.string.title_filtered_collection) else -> getString(R.string.title_collection) } val text = StringBuilder(description) .append("\n") .append("-".repeat(description.length)) .append("\n") val maxGames = 10 adapter.items.take(maxGames).map { text.append("\u2022 ${formatGameLink(it.gameId, it.collectionName)}") } val leftOverCount = adapter.itemCount - maxGames if (leftOverCount > 0) text.append(getString(R.string.and_more, leftOverCount)).append("\n") val username = prefs[AccountPreferences.KEY_USERNAME, ""] text.append("\n") .append(createViewDescription(sorter, filters)) .append("\n") .append("\n") .append(getString(R.string.share_collection_complete_footer, "https://www.boardgamegeek.com/collection/user/${username.encodeForUrl()}")) val fullName = prefs[AccountPreferences.KEY_FULL_NAME, ""] requireActivity().share(getString(R.string.share_collection_subject, fullName, username), text, R.string.title_share_collection) } private fun setEmptyText() { val syncedStatuses = prefs.getStringSet(PREFERENCES_KEY_SYNC_STATUSES, null).orEmpty() if (syncedStatuses.isEmpty()) { setEmptyStateForSettingsAction(R.string.empty_collection_sync_off) } else { if (SyncPrefs.getPrefs(requireContext()).noPreviousCollectionSync()) { setEmptyStateForNoAction(R.string.empty_collection_sync_never) } else if (filters.isNotEmpty()) { val appliedStatuses = filters.filterIsInstance<CollectionStatusFilterer>().firstOrNull()?.getSelectedStatusesSet().orEmpty() if (syncedStatuses.containsAll(appliedStatuses)) { setEmptyStateForNoAction(R.string.empty_collection_filter_on) } else { setEmptyStateForSettingsAction(R.string.empty_collection_filter_on_sync_partial) } } else { setEmptyStateForSettingsAction(R.string.empty_collection) } } } private fun setEmptyStateForSettingsAction(@StringRes textResId: Int) { binding.emptyTextView.setText(textResId) binding.emptyButton.isVisible = true } private fun setEmptyStateForNoAction(@StringRes textResId: Int) { binding.emptyTextView.setText(textResId) binding.emptyButton.isVisible = false } private fun bindFilterButtons() { binding.chipGroup.removeAllViews() for (filter in filters) { if (filter.isValid) { binding.chipGroup.addView(Chip(requireContext(), null, R.style.Widget_MaterialComponents_Chip_Filter).apply { layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) text = filter.chipText() if (filter.iconResourceId != CollectionFilterer.INVALID_ICON) { chipIcon = AppCompatResources.getDrawable(requireContext(), filter.iconResourceId) chipIconTint = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.primary_dark)) } setOnClickListener { launchFilterDialog(filter.type) } setOnLongClickListener { viewModel.removeFilter(filter.type) true } }) } } val show = binding.chipGroup.childCount > 0 if (show) { binding.chipGroupScrollView.slideUpIn() } else { binding.chipGroupScrollView.slideDownOut() } binding.swipeRefreshLayout.updatePadding( bottom = if (show) resources.getDimensionPixelSize(R.dimen.chip_group_height) else 0 ) } fun launchFilterDialog(filterType: Int): Boolean { val dialog = CollectionFilterDialogFactory().create(requireContext(), filterType) return if (dialog != null) { dialog.createDialog(requireActivity(), filters.firstOrNull { it.type == filterType }) true } else { Timber.w("Couldn't find a filter dialog of type %s", filterType) false } } inner class CollectionAdapter : RecyclerView.Adapter<CollectionItemViewHolder>(), SectionCallback { var items: List<CollectionItemEntity> = emptyList() @SuppressLint("NotifyDataSetChanged") set(value) { field = value notifyDataSetChanged() } init { setHasStableIds(true) } private val selectedItems = SparseBooleanArray() fun getItem(position: Int) = items.getOrNull(position) val selectedItemCount: Int get() = selectedItems.filterTrue().size val selectedItemPositions: List<Int> get() = selectedItems.filterTrue() fun getSelectedItems() = selectedItemPositions.mapNotNull { items.getOrNull(it) } @SuppressLint("NotifyDataSetChanged") fun toggleSelection(position: Int) { selectedItems.toggle(position) notifyDataSetChanged() // I'd prefer to call notifyItemChanged(position), but that causes the section header to appear briefly actionMode?.let { if (selectedItemCount == 0) { it.finish() } else { it.invalidate() } } } fun clearSelection() { val oldSelectedItems = selectedItems.clone() selectedItems.clear() oldSelectedItems.filterTrue().forEach { notifyItemChanged(it) } } override fun getItemCount() = items.size override fun getItemId(position: Int) = getItem(position)?.internalId ?: RecyclerView.NO_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollectionItemViewHolder { return CollectionItemViewHolder(parent.inflate(R.layout.row_collection)) } override fun onBindViewHolder(holder: CollectionItemViewHolder, position: Int) { holder.bindView(getItem(position), position) } inner class CollectionItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = RowCollectionBinding.bind(itemView) fun bindView(item: CollectionItemEntity?, position: Int) { if (item == null) return binding.nameView.text = item.collectionName binding.yearView.text = item.yearPublished.asYear(context) binding.timestampView.timestamp = sorter?.getTimestamp(item) ?: 0L binding.favoriteView.isVisible = item.isFavorite val ratingText = sorter?.getRatingText(item).orEmpty() binding.ratingView.setTextOrHide(ratingText) if (ratingText.isNotEmpty()) { sorter?.getRating(item)?.let { binding.ratingView.setTextViewBackground(it.toColor(BggColors.ratingColors)) } binding.infoView.isVisible = false } else { binding.infoView.setTextOrHide(sorter?.getDisplayInfo(item)) } binding.thumbnailView.loadThumbnail(item.thumbnailUrl) itemView.isActivated = selectedItems[position, false] itemView.setOnClickListener { when { isCreatingShortcut -> { GameActivity.createShortcutInfo(requireContext(), item.gameId, item.gameName)?.let { val intent = ShortcutManagerCompat.createShortcutResultIntent(requireContext(), it) requireActivity().setResult(Activity.RESULT_OK, intent) requireActivity().finish() } } changingGamePlayId != BggContract.INVALID_ID.toLong() -> { LogPlayActivity.changeGame( requireContext(), changingGamePlayId, item.gameId, item.gameName, item.thumbnailUrl, item.imageUrl, item.heroImageUrl ) requireActivity().finish() // don't want to come back to collection activity in "pick a new game" mode } actionMode == null -> GameActivity.start(requireContext(), item.gameId, item.gameName, item.thumbnailUrl, item.heroImageUrl) else -> adapter.toggleSelection(position) } } itemView.setOnLongClickListener { if (isCreatingShortcut) return@setOnLongClickListener false if (changingGamePlayId != BggContract.INVALID_ID.toLong()) return@setOnLongClickListener false if (actionMode != null) return@setOnLongClickListener false actionMode = requireActivity().startActionMode(this@CollectionFragment) if (actionMode == null) return@setOnLongClickListener false toggleSelection(position) true } } } override fun isSection(position: Int): Boolean { if (position == RecyclerView.NO_POSITION) return false if (items.isEmpty()) return false if (position == 0) return true if (position < 0 || position >= items.size) return false val thisLetter = getSectionHeader(position) val lastLetter = getSectionHeader(position - 1) return thisLetter != lastLetter } override fun getSectionHeader(position: Int): CharSequence { val item = items.getOrNull(position) ?: return "-" return sorter?.getHeaderText(item) ?: return "-" } } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.game_context, menu) adapter.clearSelection() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val count = adapter.selectedItemCount mode.title = resources.getQuantityString(R.plurals.msg_games_selected, count, count) menu.findItem(R.id.menu_log_play_form)?.isVisible = count == 1 menu.findItem(R.id.menu_log_play_wizard)?.isVisible = count == 1 menu.findItem(R.id.menu_link)?.isVisible = count == 1 return true } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null adapter.clearSelection() } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val items = adapter.getSelectedItems() if (items.isEmpty()) return false when (item.itemId) { R.id.menu_log_play_form -> { items.firstOrNull()?.let { LogPlayActivity.logPlay( requireContext(), it.gameId, it.gameName, it.thumbnailUrl, it.imageUrl, it.heroImageUrl, it.arePlayersCustomSorted ) } } R.id.menu_log_play_quick -> { items.forEach { viewModel.logQuickPlay(it.gameId, it.gameName) } toast(resources.getQuantityString(R.plurals.msg_logging_plays, items.size)) } R.id.menu_log_play_wizard -> { items.firstOrNull()?.let { NewPlayActivity.start(requireContext(), it.gameId, it.gameName) } } R.id.menu_share -> { val shareMethod = "Collection" if (items.size == 1) { items.firstOrNull()?.let { requireActivity().shareGame(it.gameId, it.gameName, shareMethod, firebaseAnalytics) } } else { requireActivity().shareGames(items.map { it.gameId to it.gameName }, shareMethod, firebaseAnalytics) } } R.id.menu_link -> { items.firstOrNull()?.gameId?.let { activity.linkBgg(it) } } else -> return false } mode.finish() return true } private fun createViewDescription(sort: CollectionSorter?, filters: List<CollectionFilterer>): String { val text = StringBuilder() if (filters.isNotEmpty()) { text.append(getString(R.string.filtered_by)) filters.map { "\n\u2022 ${it.description()}" }.forEach { text.append(it) } } text.append("\n\n") sort?.let { if (it.type != CollectionSorterFactory.TYPE_DEFAULT) text.append(getString(R.string.sort_description, it.description)) } return text.trim().toString() } companion object { private const val KEY_IS_CREATING_SHORTCUT = "IS_CREATING_SHORTCUT" private const val KEY_CHANGING_GAME_PLAY_ID = "KEY_CHANGING_GAME_PLAY_ID" fun newInstance(isCreatingShortcut: Boolean): CollectionFragment { return CollectionFragment().apply { arguments = bundleOf(KEY_IS_CREATING_SHORTCUT to isCreatingShortcut) } } fun newInstanceForPlayGameChange(playId: Long): CollectionFragment { return CollectionFragment().apply { arguments = bundleOf(KEY_CHANGING_GAME_PLAY_ID to playId) } } } }
gpl-3.0
mediathekview/MediathekView
src/main/java/mediathek/tool/NetUtils.kt
1
1215
package mediathek.tool import java.io.IOException import java.net.InetSocketAddress import java.net.Socket class NetUtils { companion object { /** * Check if an address is reachable via network. * Replaces InetAddress.isReachable which is unreliable. * @param addr url * @param timeout Timeout in milliseconds * @return true if reachable, otherwise false */ @JvmStatic fun isReachable(addr: String, timeout: Int): Boolean { return try { Socket().use { soc -> // use HTTPS port soc.connect(InetSocketAddress(addr, 443), timeout) } true } catch (ex: IOException) { false } } /** * Check if string may be an URL. * @param str The string to be checked. * @return true if string is an URL, otherwise false */ @JvmStatic fun isUrl(str: String) : Boolean { //TODO it may be better to really check if we are a valid URL. use HttpUrl? return str.startsWith("http") || str.startsWith("www") } } }
gpl-3.0
lllllT/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/interactor/timeline/UnreblogStatusUseCase.kt
2
801
package com.bl_lia.kirakiratter.domain.interactor.timeline import com.bl_lia.kirakiratter.domain.entity.Status import com.bl_lia.kirakiratter.domain.executor.PostExecutionThread import com.bl_lia.kirakiratter.domain.executor.ThreadExecutor import com.bl_lia.kirakiratter.domain.interactor.SingleUseCase import com.bl_lia.kirakiratter.domain.repository.TimelineRepository import io.reactivex.Single class UnreblogStatusUseCase( private val timelineRepository: TimelineRepository, private val threadExecutor: ThreadExecutor, private val postExecutionThread: PostExecutionThread ) : SingleUseCase<Status>(threadExecutor, postExecutionThread) { override fun build(params: Array<out Any>): Single<Status> { return timelineRepository.unReblog(params[0] as Int) } }
mit
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/shows/SyncAnticipatedShows.kt
1
3071
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.shows import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import net.simonvt.cathode.actions.CallAction import net.simonvt.cathode.api.entity.AnticipatedItem import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.ShowsService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.ShowColumns import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.ShowDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.settings.SuggestionsTimestamps import retrofit2.Call import javax.inject.Inject class SyncAnticipatedShows @Inject constructor( private val context: Context, private val showHelper: ShowDatabaseHelper, private val showsService: ShowsService ) : CallAction<Unit, List<AnticipatedItem>>() { override fun key(params: Unit): String = "SyncAnticipatedShows" override fun getCall(params: Unit): Call<List<AnticipatedItem>> = showsService.getAnticipatedShows(LIMIT, Extended.FULL) override suspend fun handleResponse(params: Unit, response: List<AnticipatedItem>) { val ops = arrayListOf<ContentProviderOperation>() val showIds = mutableListOf<Long>() val localShows = context.contentResolver.query(Shows.SHOWS_ANTICIPATED) localShows.forEach { cursor -> showIds.add(cursor.getLong(ShowColumns.ID)) } localShows.close() response.forEachIndexed { index, anticipatedItem -> val show = anticipatedItem.show!! val showId = showHelper.partialUpdate(show) showIds.remove(showId) val values = ContentValues() values.put(ShowColumns.ANTICIPATED_INDEX, index) val op = ContentProviderOperation.newUpdate(Shows.withId(showId)).withValues(values).build() ops.add(op) } for (showId in showIds) { val op = ContentProviderOperation.newUpdate(Shows.withId(showId)) .withValue(ShowColumns.ANTICIPATED_INDEX, -1) .build() ops.add(op) } context.contentResolver.batch(ops) SuggestionsTimestamps.get(context) .edit() .putLong(SuggestionsTimestamps.SHOWS_ANTICIPATED, System.currentTimeMillis()) .apply() } companion object { private const val LIMIT = 50 } }
apache-2.0
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/binding/Bindings.kt
1
306
package com.makeevapps.simpletodolist.binding import android.databinding.BindingAdapter import android.view.View object Bindings { @BindingAdapter("isVisible") @JvmStatic fun setIsVisible(v: View, isVisible: Boolean) { v.visibility = if (isVisible) View.VISIBLE else View.GONE } }
mit
googlecast/CastVideos-android
app-kotlin/src/main/kotlin/com/google/sample/cast/refplayer/utils/CustomVolleyRequest.kt
1
2574
/* * Copyright 2022 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.cast.refplayer.utils import android.content.Context import com.android.volley.toolbox.ImageLoader import kotlin.jvm.Synchronized import com.android.volley.RequestQueue import com.android.volley.toolbox.ImageLoader.ImageCache import android.graphics.Bitmap import androidx.collection.LruCache import com.android.volley.Cache import com.android.volley.Network import com.android.volley.toolbox.DiskBasedCache import com.android.volley.toolbox.BasicNetwork import com.android.volley.toolbox.HurlStack class CustomVolleyRequest private constructor(context: Context) { private var requestQueue: RequestQueue? val imageLoader: ImageLoader private var context: Context init { this.context = context requestQueue = getRequestQueue() imageLoader = ImageLoader(requestQueue, object : ImageCache { private val cache: LruCache<String, Bitmap> = LruCache(20) override fun getBitmap(url: String): Bitmap? { return cache.get(url) } override fun putBitmap(url: String, bitmap: Bitmap) { cache.put(url, bitmap) } }) } private fun getRequestQueue(): RequestQueue { if (requestQueue == null) { val cache: Cache = DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024) val network: Network = BasicNetwork(HurlStack()) requestQueue = RequestQueue(cache, network) requestQueue!!.start() } return requestQueue!! } companion object { private var customVolleyRequest: CustomVolleyRequest? = null @Synchronized fun getInstance(context: Context): CustomVolleyRequest? { if (customVolleyRequest == null) { customVolleyRequest = CustomVolleyRequest(context) } return customVolleyRequest } } }
apache-2.0
actorapp/actor-bots
actor-bots/src/main/java/im/actor/bots/framework/traits/DispatcherTrait.kt
1
883
package im.actor.bots.framework.traits import akka.actor.Actor import akka.actor.Cancellable import scala.concurrent.duration.Duration import java.util.concurrent.TimeUnit interface DispatchTrait { fun initDispatch(actor: Actor) fun schedule(message: Any, delay: Long): Cancellable } class DispatchTraitImpl : DispatchTrait { private var actor: Actor? = null override fun schedule(message: Any, delay: Long): Cancellable { return schedullerSchedule(message, delay) } override fun initDispatch(actor: Actor) { this.actor = actor } private fun schedullerSchedule(message: Any, delay: Long): Cancellable { return actor!!.context().system().scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), { actor!!.self().tell(message, actor!!.self()) }, actor!!.context().dispatcher()) } }
apache-2.0
jamieadkins95/Roach
app/src/main/java/com/jamieadkins/gwent/di/FragmentInjectionModule.kt
1
2208
package com.jamieadkins.gwent.di import com.jamieadkins.gwent.card.detail.CardDetailModule import com.jamieadkins.gwent.card.detail.CardDetailsFragment import com.jamieadkins.gwent.card.list.CardDatabaseFragment import com.jamieadkins.gwent.card.list.CardDatabaseModule import com.jamieadkins.gwent.data.latest.DeckOfTheDayDataModule import com.jamieadkins.gwent.data.latest.NewsDataModule import com.jamieadkins.gwent.deck.create.CreateDeckDialog import com.jamieadkins.gwent.deck.create.CreateDeckModule import com.jamieadkins.gwent.deck.list.DeckListFragment import com.jamieadkins.gwent.deck.list.DeckListModule import com.jamieadkins.gwent.filter.FilterBottomSheetDialogFragment import com.jamieadkins.gwent.filter.FilterModule import com.jamieadkins.gwent.latest.GwentFragment import com.jamieadkins.gwent.latest.GwentLatestModule import com.jamieadkins.gwent.tracker.DeckTrackerSetupFragment import com.jamieadkins.gwent.tracker.DeckTrackerSetupModule import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FragmentInjectionModule private constructor() { @FragmentScoped @ContributesAndroidInjector(modules = [FilterModule::class]) internal abstract fun view(): FilterBottomSheetDialogFragment @FragmentScoped @ContributesAndroidInjector(modules = [DeckListModule::class]) internal abstract fun deckList(): DeckListFragment @FragmentScoped @ContributesAndroidInjector(modules = [CreateDeckModule::class]) internal abstract fun createDeck(): CreateDeckDialog @FragmentScoped @ContributesAndroidInjector(modules = [CardDetailModule::class]) internal abstract fun detail(): CardDetailsFragment @FragmentScoped @ContributesAndroidInjector(modules = [CardDatabaseModule::class]) internal abstract fun cardDatabase(): CardDatabaseFragment @FragmentScoped @ContributesAndroidInjector(modules = [GwentLatestModule::class, NewsDataModule::class, DeckOfTheDayDataModule::class]) internal abstract fun gwent(): GwentFragment @FragmentScoped @ContributesAndroidInjector(modules = [DeckTrackerSetupModule::class]) internal abstract fun deckTrackerSetup(): DeckTrackerSetupFragment }
apache-2.0
AgileVentures/MetPlus_resumeCruncher
web/src/main/kotlin/org/metplus/cruncher/web/rating/AsyncResumeProcess.kt
1
524
package org.metplus.cruncher.web.rating import org.metplus.cruncher.rating.CrunchResumeProcess import org.metplus.cruncher.rating.CruncherList import org.metplus.cruncher.resume.ResumeFileRepository import org.metplus.cruncher.resume.ResumeRepository class AsyncResumeProcess( allCrunchers: CruncherList, resumeRepository: ResumeRepository, resumeFileRepository: ResumeFileRepository ) : CrunchResumeProcess(allCrunchers, resumeRepository, resumeFileRepository) { init { start() } }
gpl-3.0
alfiewm/Keddit
app/src/main/java/meng/keddit/commons/extensions/Extensions.kt
1
1182
@file:JvmName("ExtensionsUtils") // name used in java code, without this line, you have to use ExtensionsKt package meng.keddit.commons.extensions import android.os.Parcel import android.os.Parcelable import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.squareup.picasso.Picasso import meng.keddit.R /** * Created by meng on 2017/7/31. */ fun ViewGroup.inflate(layoutId: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutId, this, attachToRoot) } fun ImageView.loadImg(imageUrl: String) { if (TextUtils.isEmpty(imageUrl)) { Picasso.with(context).load(R.mipmap.ic_launcher).into(this) } else { Picasso.with(context).load(imageUrl).into(this) } } inline fun <reified T : Parcelable> createParcel(crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator<T> = object : Parcelable.Creator<T> { override fun createFromParcel(source: Parcel): T? = createFromParcel(source) override fun newArray(size: Int): Array<out T?> = arrayOfNulls(size) }
mit
ansman/okhttp
okhttp/src/test/java/okhttp3/KotlinSourceModernTest.kt
2
47406
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.io.File import java.io.IOException import java.math.BigInteger import java.net.CookieHandler import java.net.InetAddress import java.net.InetSocketAddress import java.net.Proxy import java.net.ProxySelector import java.net.Socket import java.net.URI import java.net.URL import java.nio.charset.Charset import java.security.KeyPair import java.security.KeyPairGenerator import java.security.Principal import java.security.cert.Certificate import java.security.cert.X509Certificate import java.time.Duration import java.time.Instant import java.util.Date import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import javax.net.ServerSocketFactory import javax.net.SocketFactory import javax.net.ssl.HostnameVerifier import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import javax.net.ssl.X509KeyManager import javax.net.ssl.X509TrustManager import mockwebserver3.MockResponse import mockwebserver3.MockWebServer import mockwebserver3.PushPromise import mockwebserver3.QueueDispatcher import mockwebserver3.RecordedRequest import mockwebserver3.SocketPolicy import okhttp3.Handshake.Companion.handshake import okhttp3.Headers.Companion.headersOf import okhttp3.Headers.Companion.toHeaders import okhttp3.HttpUrl.Companion.toHttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.ResponseBody.Companion.asResponseBody import okhttp3.ResponseBody.Companion.toResponseBody import okhttp3.internal.http2.Settings import okhttp3.internal.proxy.NullProxySelector import okhttp3.internal.tls.OkHostnameVerifier import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.LoggingEventListener import okhttp3.tls.HandshakeCertificates import okhttp3.tls.HeldCertificate import okhttp3.tls.internal.TlsUtil.localhost import okio.Buffer import okio.BufferedSink import okio.BufferedSource import okio.ByteString import okio.Timeout import org.junit.jupiter.api.Assumptions.assumeFalse import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test /** * Access every type, function, and property from Kotlin to defend against unexpected regressions in * modern 4.0.x kotlin source-compatibility. */ @Suppress( "ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_ANONYMOUS_PARAMETER", "UNUSED_VALUE", "UNUSED_VARIABLE", "VARIABLE_WITH_REDUNDANT_INITIALIZER", "RedundantLambdaArrow", "RedundantExplicitType", "IMPLICIT_NOTHING_AS_TYPE_PARAMETER" ) @Disabled class KotlinSourceModernTest { @BeforeEach fun disabled() { assumeFalse(true) } @Test fun address() { val address: Address = newAddress() val url: HttpUrl = address.url val dns: Dns = address.dns val socketFactory: SocketFactory = address.socketFactory val proxyAuthenticator: Authenticator = address.proxyAuthenticator val protocols: List<Protocol> = address.protocols val connectionSpecs: List<ConnectionSpec> = address.connectionSpecs val proxySelector: ProxySelector = address.proxySelector val sslSocketFactory: SSLSocketFactory? = address.sslSocketFactory val hostnameVerifier: HostnameVerifier? = address.hostnameVerifier val certificatePinner: CertificatePinner? = address.certificatePinner } @Test fun authenticator() { var authenticator: Authenticator = object : Authenticator { override fun authenticate(route: Route?, response: Response): Request? = TODO() } } @Test fun cache() { val cache = Cache(File("/cache/"), Integer.MAX_VALUE.toLong()) cache.initialize() cache.delete() cache.evictAll() val urls: MutableIterator<String> = cache.urls() val writeAbortCount: Int = cache.writeAbortCount() val writeSuccessCount: Int = cache.writeSuccessCount() val size: Long = cache.size() val maxSize: Long = cache.maxSize() cache.flush() cache.close() val directory: File = cache.directory val networkCount: Int = cache.networkCount() val hitCount: Int = cache.hitCount() val requestCount: Int = cache.requestCount() } @Test fun cacheControl() { val cacheControl: CacheControl = CacheControl.Builder().build() val noCache: Boolean = cacheControl.noCache val noStore: Boolean = cacheControl.noStore val maxAgeSeconds: Int = cacheControl.maxAgeSeconds val sMaxAgeSeconds: Int = cacheControl.sMaxAgeSeconds val mustRevalidate: Boolean = cacheControl.mustRevalidate val maxStaleSeconds: Int = cacheControl.maxStaleSeconds val minFreshSeconds: Int = cacheControl.minFreshSeconds val onlyIfCached: Boolean = cacheControl.onlyIfCached val noTransform: Boolean = cacheControl.noTransform val immutable: Boolean = cacheControl.immutable val forceCache: CacheControl = CacheControl.FORCE_CACHE val forceNetwork: CacheControl = CacheControl.FORCE_NETWORK val parse: CacheControl = CacheControl.parse(headersOf()) } @Test fun cacheControlBuilder() { var builder: CacheControl.Builder = CacheControl.Builder() builder = builder.noCache() builder = builder.noStore() builder = builder.maxAge(0, TimeUnit.MILLISECONDS) builder = builder.maxStale(0, TimeUnit.MILLISECONDS) builder = builder.minFresh(0, TimeUnit.MILLISECONDS) builder = builder.onlyIfCached() builder = builder.noTransform() builder = builder.immutable() val cacheControl: CacheControl = builder.build() } @Test fun call() { val call: Call = newCall() } @Test fun callback() { val callback = object : Callback { override fun onFailure(call: Call, e: IOException) = TODO() override fun onResponse(call: Call, response: Response) = TODO() } } @Test fun certificatePinner() { val heldCertificate: HeldCertificate = HeldCertificate.Builder().build() val certificate: X509Certificate = heldCertificate.certificate val certificatePinner: CertificatePinner = CertificatePinner.Builder().build() val certificates: List<Certificate> = listOf() certificatePinner.check("", listOf(certificate)) certificatePinner.check("", arrayOf<Certificate>(certificate, certificate).toList()) val pin: String = CertificatePinner.pin(certificate) val default: CertificatePinner = CertificatePinner.DEFAULT } @Test fun certificatePinnerBuilder() { val builder: CertificatePinner.Builder = CertificatePinner.Builder() builder.add("", "pin1", "pin2") } @Test fun challenge() { var challenge = Challenge("", mapOf<String?, String>("" to "")) challenge = Challenge("", "") val scheme: String = challenge.scheme val authParams: Map<String?, String> = challenge.authParams val realm: String? = challenge.realm val charset: Charset = challenge.charset val utf8: Challenge = challenge.withCharset(Charsets.UTF_8) } @Test fun cipherSuite() { var cipherSuite: CipherSuite = CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipherSuite = CipherSuite.forJavaName("") val javaName: String = cipherSuite.javaName } @Test fun connection() { val connection = object : Connection { override fun route(): Route = TODO() override fun socket(): Socket = TODO() override fun handshake(): Handshake? = TODO() override fun protocol(): Protocol = TODO() } } @Test fun connectionPool() { var connectionPool = ConnectionPool() connectionPool = ConnectionPool(0, 0L, TimeUnit.SECONDS) val idleConnectionCount: Int = connectionPool.idleConnectionCount() val connectionCount: Int = connectionPool.connectionCount() connectionPool.evictAll() } @Test fun connectionSpec() { var connectionSpec: ConnectionSpec = ConnectionSpec.RESTRICTED_TLS connectionSpec = ConnectionSpec.MODERN_TLS connectionSpec = ConnectionSpec.COMPATIBLE_TLS connectionSpec = ConnectionSpec.CLEARTEXT val tlsVersions: List<TlsVersion>? = connectionSpec.tlsVersions val cipherSuites: List<CipherSuite>? = connectionSpec.cipherSuites val supportsTlsExtensions: Boolean = connectionSpec.supportsTlsExtensions val compatible: Boolean = connectionSpec.isCompatible( localhost().sslSocketFactory().createSocket() as SSLSocket) } @Test fun connectionSpecBuilder() { var builder = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) builder = builder.allEnabledCipherSuites() builder = builder.cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) builder = builder.cipherSuites("", "") builder = builder.allEnabledTlsVersions() builder = builder.tlsVersions(TlsVersion.TLS_1_3) builder = builder.tlsVersions("", "") val connectionSpec: ConnectionSpec = builder.build() } @Test fun cookie() { val cookie: Cookie = Cookie.Builder().build() val name: String = cookie.name val value: String = cookie.value val persistent: Boolean = cookie.persistent val expiresAt: Long = cookie.expiresAt val hostOnly: Boolean = cookie.hostOnly val domain: String = cookie.domain val path: String = cookie.path val httpOnly: Boolean = cookie.httpOnly val secure: Boolean = cookie.secure val matches: Boolean = cookie.matches("".toHttpUrl()) val parsedCookie: Cookie? = Cookie.parse("".toHttpUrl(), "") val cookies: List<Cookie> = Cookie.parseAll("".toHttpUrl(), headersOf()) } @Test fun cookieBuilder() { var builder: Cookie.Builder = Cookie.Builder() builder = builder.name("") builder = builder.value("") builder = builder.expiresAt(0L) builder = builder.domain("") builder = builder.hostOnlyDomain("") builder = builder.path("") builder = builder.secure() builder = builder.httpOnly() val cookie: Cookie = builder.build() } @Test fun cookieJar() { val cookieJar = object : CookieJar { override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) = TODO() override fun loadForRequest(url: HttpUrl): List<Cookie> = TODO() } } @Test fun credentials() { val basic: String = Credentials.basic("", "") } @Test fun dispatcher() { var dispatcher = Dispatcher() dispatcher = Dispatcher(Executors.newCachedThreadPool()) val maxRequests: Int = dispatcher.maxRequests dispatcher.maxRequests = 0 val maxRequestsPerHost: Int = dispatcher.maxRequestsPerHost dispatcher.maxRequestsPerHost = 0 val executorService: ExecutorService = dispatcher.executorService dispatcher.idleCallback = Runnable { ({ TODO() })() } val queuedCalls: List<Call> = dispatcher.queuedCalls() val runningCalls: List<Call> = dispatcher.runningCalls() val queuedCallsCount: Int = dispatcher.queuedCallsCount() val runningCallsCount: Int = dispatcher.runningCallsCount() dispatcher.cancelAll() } @Test fun dispatcherFromMockWebServer() { val dispatcher = object : mockwebserver3.Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse = TODO() override fun peek(): MockResponse = TODO() override fun shutdown() = TODO() } } @Test fun dns() { var dns: Dns = object : Dns { override fun lookup(hostname: String): List<InetAddress> = TODO() } val system: Dns = Dns.SYSTEM } @Test fun eventListener() { val eventListener = object : EventListener() { override fun callStart(call: Call) = TODO() override fun dnsStart(call: Call, domainName: String) = TODO() override fun dnsEnd( call: Call, domainName: String, inetAddressList: List<InetAddress> ) = TODO() override fun connectStart( call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy ) = TODO() override fun secureConnectStart(call: Call) = TODO() override fun secureConnectEnd(call: Call, handshake: Handshake?) = TODO() override fun connectEnd( call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol? ) = TODO() override fun connectFailed( call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol?, ioe: IOException ) = TODO() override fun connectionAcquired(call: Call, connection: Connection) = TODO() override fun connectionReleased(call: Call, connection: Connection) = TODO() override fun requestHeadersStart(call: Call) = TODO() override fun requestHeadersEnd(call: Call, request: Request) = TODO() override fun requestBodyStart(call: Call) = TODO() override fun requestBodyEnd(call: Call, byteCount: Long) = TODO() override fun requestFailed(call: Call, ioe: IOException) = TODO() override fun responseHeadersStart(call: Call) = TODO() override fun responseHeadersEnd(call: Call, response: Response) = TODO() override fun responseBodyStart(call: Call) = TODO() override fun responseBodyEnd(call: Call, byteCount: Long) = TODO() override fun responseFailed(call: Call, ioe: IOException) = TODO() override fun callEnd(call: Call) = TODO() override fun callFailed(call: Call, ioe: IOException) = TODO() override fun canceled(call: Call) = TODO() } val none: EventListener = EventListener.NONE } @Test fun eventListenerBuilder() { var builder: EventListener.Factory = object : EventListener.Factory { override fun create(call: Call): EventListener = TODO() } } @Test fun formBody() { val formBody: FormBody = FormBody.Builder().build() val size: Int = formBody.size val encodedName: String = formBody.encodedName(0) val name: String = formBody.name(0) val encodedValue: String = formBody.encodedValue(0) val value: String = formBody.value(0) val contentType: MediaType? = formBody.contentType() val contentLength: Long = formBody.contentLength() formBody.writeTo(Buffer()) val requestBody: RequestBody = formBody } @Test fun formBodyBuilder() { var builder: FormBody.Builder = FormBody.Builder() builder = FormBody.Builder(Charsets.UTF_8) builder = builder.add("", "") builder = builder.addEncoded("", "") val formBody: FormBody = builder.build() } @Test fun handshake() { var handshake: Handshake = (localhost().sslSocketFactory().createSocket() as SSLSocket).session.handshake() val listOfCertificates: List<Certificate> = listOf() handshake = Handshake.get( TlsVersion.TLS_1_3, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, listOfCertificates, listOfCertificates ) val tlsVersion: TlsVersion = handshake.tlsVersion val cipherSuite: CipherSuite = handshake.cipherSuite val peerCertificates: List<Certificate> = handshake.peerCertificates val peerPrincipal: Principal? = handshake.peerPrincipal val localCertificates: List<Certificate> = handshake.localCertificates val localPrincipal: Principal? = handshake.localPrincipal } @Test fun headers() { var headers: Headers = headersOf("", "") headers = mapOf("" to "").toHeaders() val get: String? = headers.get("") val date: Date? = headers.getDate("") val instant: Instant? = headers.getInstant("") val size: Int = headers.size val name: String = headers.name(0) val value: String = headers.value(0) val names: Set<String> = headers.names() val values: List<String> = headers.values("") val byteCount: Long = headers.byteCount() val builder: Headers.Builder = headers.newBuilder() val multimap: Map<String, List<String>> = headers.toMultimap() } @Test fun headersBuilder() { var builder: Headers.Builder = Headers.Builder() builder = builder.add("") builder = builder.add("", "") builder = builder.addUnsafeNonAscii("", "") builder = builder.addAll(headersOf()) builder = builder.add("", Date(0L)) builder = builder.add("", Instant.EPOCH) builder = builder.set("", "") builder = builder.set("", Date(0L)) builder = builder.set("", Instant.EPOCH) builder = builder.removeAll("") val get: String? = builder.get("") val headers: Headers = builder.build() } @Test fun httpLoggingInterceptor() { var interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor() interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT) interceptor.redactHeader("") interceptor.level = HttpLoggingInterceptor.Level.BASIC var level: HttpLoggingInterceptor.Level = interceptor.level interceptor.intercept(newInterceptorChain()) } @Test fun httpLoggingInterceptorLevel() { val none: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.NONE val basic: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BASIC val headers: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.HEADERS val body: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY } @Test fun httpLoggingInterceptorLogger() { var logger: HttpLoggingInterceptor.Logger = object : HttpLoggingInterceptor.Logger { override fun log(message: String) = TODO() } val default: HttpLoggingInterceptor.Logger = HttpLoggingInterceptor.Logger.DEFAULT } @Test fun httpUrl() { val httpUrl: HttpUrl = "".toHttpUrl() val isHttps: Boolean = httpUrl.isHttps val url: URL = httpUrl.toUrl() val uri: URI = httpUrl.toUri() val scheme: String = httpUrl.scheme val encodedUsername: String = httpUrl.encodedUsername val username: String = httpUrl.username val encodedPassword: String = httpUrl.encodedPassword val password: String = httpUrl.password val host: String = httpUrl.host val port: Int = httpUrl.port val pathSize: Int = httpUrl.pathSize val encodedPath: String = httpUrl.encodedPath val encodedPathSegments: List<String> = httpUrl.encodedPathSegments val pathSegments: List<String> = httpUrl.pathSegments val encodedQuery: String? = httpUrl.encodedQuery val query: String? = httpUrl.query val querySize: Int = httpUrl.querySize val queryParameter: String? = httpUrl.queryParameter("") val queryParameterNames: Set<String> = httpUrl.queryParameterNames val queryParameterValues: List<String?> = httpUrl.queryParameterValues("") val queryParameterName: String = httpUrl.queryParameterName(0) val queryParameterValue: String? = httpUrl.queryParameterValue(0) val encodedFragment: String? = httpUrl.encodedFragment val fragment: String? = httpUrl.fragment val redact: String = httpUrl.redact() var builder: HttpUrl.Builder = httpUrl.newBuilder() var resolveBuilder: HttpUrl.Builder? = httpUrl.newBuilder("") val topPrivateDomain: String? = httpUrl.topPrivateDomain() val resolve: HttpUrl? = httpUrl.resolve("") val getFromUrl: HttpUrl? = URL("").toHttpUrlOrNull() val getFromUri: HttpUrl? = URI("").toHttpUrlOrNull() val parse: HttpUrl? = "".toHttpUrlOrNull() val defaultPort: Int = HttpUrl.defaultPort("") } @Test fun httpUrlBuilder() { var builder: HttpUrl.Builder = HttpUrl.Builder() builder = builder.scheme("") builder = builder.username("") builder = builder.encodedUsername("") builder = builder.password("") builder = builder.encodedPassword("") builder = builder.host("") builder = builder.port(0) builder = builder.addPathSegment("") builder = builder.addPathSegments("") builder = builder.addEncodedPathSegment("") builder = builder.addEncodedPathSegments("") builder = builder.setPathSegment(0, "") builder = builder.setEncodedPathSegment(0, "") builder = builder.removePathSegment(0) builder = builder.encodedPath("") builder = builder.query("") builder = builder.encodedQuery("") builder = builder.addQueryParameter("", "") builder = builder.addEncodedQueryParameter("", "") builder = builder.setQueryParameter("", "") builder = builder.setEncodedQueryParameter("", "") builder = builder.removeAllQueryParameters("") builder = builder.removeAllEncodedQueryParameters("") builder = builder.fragment("") builder = builder.encodedFragment("") val httpUrl: HttpUrl = builder.build() } @Test fun interceptor() { var interceptor: Interceptor = object : Interceptor { override fun intercept(chain: Interceptor.Chain): Response = TODO() } interceptor = Interceptor { it: Interceptor.Chain -> TODO() } } @Test fun interceptorChain() { val chain: Interceptor.Chain = newInterceptorChain() } @Test fun handshakeCertificates() { val handshakeCertificates = HandshakeCertificates.Builder().build() val keyManager: X509KeyManager = handshakeCertificates.keyManager val trustManager: X509TrustManager = handshakeCertificates.trustManager val sslSocketFactory: SSLSocketFactory = handshakeCertificates.sslSocketFactory() val sslContext: SSLContext = handshakeCertificates.sslContext() } @Test fun handshakeCertificatesBuilder() { var builder: HandshakeCertificates.Builder = HandshakeCertificates.Builder() val heldCertificate = HeldCertificate.Builder().build() builder = builder.heldCertificate(heldCertificate, heldCertificate.certificate) builder = builder.addTrustedCertificate(heldCertificate.certificate) builder = builder.addPlatformTrustedCertificates() val handshakeCertificates: HandshakeCertificates = builder.build() } @Test fun heldCertificate() { val heldCertificate: HeldCertificate = HeldCertificate.Builder().build() val certificate: X509Certificate = heldCertificate.certificate val keyPair: KeyPair = heldCertificate.keyPair val certificatePem: String = heldCertificate.certificatePem() val privateKeyPkcs8Pem: String = heldCertificate.privateKeyPkcs8Pem() val privateKeyPkcs1Pem: String = heldCertificate.privateKeyPkcs1Pem() } @Test fun heldCertificateBuilder() { val keyPair: KeyPair = KeyPairGenerator.getInstance("").genKeyPair() var builder: HeldCertificate.Builder = HeldCertificate.Builder() builder = builder.validityInterval(0L, 0L) builder = builder.duration(0L, TimeUnit.SECONDS) builder = builder.addSubjectAlternativeName("") builder = builder.commonName("") builder = builder.organizationalUnit("") builder = builder.serialNumber(BigInteger.ZERO) builder = builder.serialNumber(0L) builder = builder.keyPair(keyPair) builder = builder.keyPair(keyPair.public, keyPair.private) builder = builder.signedBy(HeldCertificate.Builder().build()) builder = builder.certificateAuthority(0) builder = builder.ecdsa256() builder = builder.rsa2048() val heldCertificate: HeldCertificate = builder.build() } @Test fun javaNetAuthenticator() { val authenticator = JavaNetAuthenticator() val response = Response.Builder().build() var request: Request? = authenticator.authenticate(newRoute(), response) request = authenticator.authenticate(null, response) } @Test fun javaNetCookieJar() { val cookieJar: JavaNetCookieJar = JavaNetCookieJar(newCookieHandler()) val httpUrl = "".toHttpUrl() val loadForRequest: List<Cookie> = cookieJar.loadForRequest(httpUrl) cookieJar.saveFromResponse(httpUrl, listOf(Cookie.Builder().build())) } @Test fun loggingEventListener() { var loggingEventListener: EventListener = LoggingEventListener.Factory().create(newCall()) } @Test fun loggingEventListenerFactory() { var factory: LoggingEventListener.Factory = LoggingEventListener.Factory() factory = LoggingEventListener.Factory(HttpLoggingInterceptor.Logger.DEFAULT) factory = object : LoggingEventListener.Factory() { override fun create(call: Call): EventListener = TODO() } val eventListener: EventListener = factory.create(newCall()) } @Test fun mediaType() { val mediaType: MediaType = "".toMediaType() val defaultCharset: Charset? = mediaType.charset() val charset: Charset? = mediaType.charset(Charsets.UTF_8) val type: String = mediaType.type val subtype: String = mediaType.subtype val parse: MediaType? = "".toMediaTypeOrNull() } @Test fun mockResponse() { var mockResponse: MockResponse = MockResponse() var status: String = mockResponse.status status = mockResponse.status mockResponse.status = "" mockResponse = mockResponse.setResponseCode(0) var headers: Headers = mockResponse.headers var trailers: Headers = mockResponse.trailers mockResponse = mockResponse.clearHeaders() mockResponse = mockResponse.addHeader("") mockResponse = mockResponse.addHeader("", "") mockResponse = mockResponse.addHeaderLenient("", Any()) mockResponse = mockResponse.setHeader("", Any()) mockResponse.headers = headersOf() mockResponse.trailers = headersOf() mockResponse = mockResponse.removeHeader("") var body: Buffer? = mockResponse.getBody() mockResponse = mockResponse.setBody(Buffer()) mockResponse = mockResponse.setChunkedBody(Buffer(), 0) mockResponse = mockResponse.setChunkedBody("", 0) var socketPolicy: SocketPolicy = mockResponse.socketPolicy mockResponse.socketPolicy = SocketPolicy.KEEP_OPEN var http2ErrorCode: Int = mockResponse.http2ErrorCode mockResponse.http2ErrorCode = 0 mockResponse = mockResponse.throttleBody(0L, 0L, TimeUnit.SECONDS) var throttleBytesPerPeriod: Long = mockResponse.throttleBytesPerPeriod throttleBytesPerPeriod = mockResponse.throttleBytesPerPeriod var throttlePeriod: Long = mockResponse.getThrottlePeriod(TimeUnit.SECONDS) mockResponse = mockResponse.setBodyDelay(0L, TimeUnit.SECONDS) val bodyDelay: Long = mockResponse.getBodyDelay(TimeUnit.SECONDS) mockResponse = mockResponse.setHeadersDelay(0L, TimeUnit.SECONDS) val headersDelay: Long = mockResponse.getHeadersDelay(TimeUnit.SECONDS) mockResponse = mockResponse.withPush(PushPromise("", "", headersOf(), MockResponse())) var pushPromises: List<PushPromise> = mockResponse.pushPromises pushPromises = mockResponse.pushPromises mockResponse = mockResponse.withSettings(Settings()) var settings: Settings = mockResponse.settings settings = mockResponse.settings mockResponse = mockResponse.withWebSocketUpgrade(object : WebSocketListener() { }) var webSocketListener: WebSocketListener? = mockResponse.webSocketListener webSocketListener = mockResponse.webSocketListener } @Test fun mockWebServer() { val mockWebServer: MockWebServer = MockWebServer() var port: Int = mockWebServer.port var hostName: String = mockWebServer.hostName hostName = mockWebServer.hostName val toProxyAddress: Proxy = mockWebServer.toProxyAddress() mockWebServer.serverSocketFactory = ServerSocketFactory.getDefault() val url: HttpUrl = mockWebServer.url("") mockWebServer.bodyLimit = 0L mockWebServer.protocolNegotiationEnabled = false mockWebServer.protocols = listOf() val protocols: List<Protocol> = mockWebServer.protocols mockWebServer.useHttps(SSLSocketFactory.getDefault() as SSLSocketFactory, false) mockWebServer.noClientAuth() mockWebServer.requestClientAuth() mockWebServer.requireClientAuth() val request: RecordedRequest = mockWebServer.takeRequest() val nullableRequest: RecordedRequest? = mockWebServer.takeRequest(0L, TimeUnit.SECONDS) var requestCount: Int = mockWebServer.requestCount mockWebServer.enqueue(MockResponse()) mockWebServer.start() mockWebServer.start(0) mockWebServer.start(InetAddress.getLocalHost(), 0) mockWebServer.shutdown() var dispatcher: mockwebserver3.Dispatcher = mockWebServer.dispatcher dispatcher = mockWebServer.dispatcher mockWebServer.dispatcher = QueueDispatcher() mockWebServer.dispatcher = QueueDispatcher() mockWebServer.close() } @Test fun multipartBody() { val multipartBody: MultipartBody = MultipartBody.Builder().build() val type: MediaType = multipartBody.type val boundary: String = multipartBody.boundary val size: Int = multipartBody.size val parts: List<MultipartBody.Part> = multipartBody.parts val part: MultipartBody.Part = multipartBody.part(0) val contentType: MediaType? = multipartBody.contentType() val contentLength: Long = multipartBody.contentLength() multipartBody.writeTo(Buffer()) val mixed: MediaType = MultipartBody.MIXED val alternative: MediaType = MultipartBody.ALTERNATIVE val digest: MediaType = MultipartBody.DIGEST val parallel: MediaType = MultipartBody.PARALLEL val form: MediaType = MultipartBody.FORM } @Test fun multipartBodyPart() { val requestBody: RequestBody = "".toRequestBody(null) var part: MultipartBody.Part = MultipartBody.Part.create(null, requestBody) part = MultipartBody.Part.create(headersOf(), requestBody) part = MultipartBody.Part.create(requestBody) part = MultipartBody.Part.createFormData("", "") part = MultipartBody.Part.createFormData("", "", requestBody) part = MultipartBody.Part.createFormData("", null, requestBody) val headers: Headers? = part.headers val body: RequestBody = part.body } @Test fun multipartBodyBuilder() { val requestBody = "".toRequestBody(null) var builder: MultipartBody.Builder = MultipartBody.Builder() builder = MultipartBody.Builder("") builder = builder.setType("".toMediaType()) builder = builder.addPart(requestBody) builder = builder.addPart(headersOf(), requestBody) builder = builder.addPart(null, requestBody) builder = builder.addFormDataPart("", "") builder = builder.addFormDataPart("", "", requestBody) builder = builder.addFormDataPart("", null, requestBody) builder = builder.addPart(MultipartBody.Part.create(requestBody)) val multipartBody: MultipartBody = builder.build() } @Test fun okHttpClient() { val client: OkHttpClient = OkHttpClient() val dispatcher: Dispatcher = client.dispatcher val proxy: Proxy? = client.proxy val protocols: List<Protocol> = client.protocols val connectionSpecs: List<ConnectionSpec> = client.connectionSpecs val interceptors: List<Interceptor> = client.interceptors val networkInterceptors: List<Interceptor> = client.networkInterceptors val eventListenerFactory: EventListener.Factory = client.eventListenerFactory val proxySelector: ProxySelector = client.proxySelector val cookieJar: CookieJar = client.cookieJar val cache: Cache? = client.cache val socketFactory: SocketFactory = client.socketFactory val sslSocketFactory: SSLSocketFactory = client.sslSocketFactory val hostnameVerifier: HostnameVerifier = client.hostnameVerifier val certificatePinner: CertificatePinner = client.certificatePinner val proxyAuthenticator: Authenticator = client.proxyAuthenticator val authenticator: Authenticator = client.authenticator val connectionPool: ConnectionPool = client.connectionPool val dns: Dns = client.dns val followSslRedirects: Boolean = client.followSslRedirects val followRedirects: Boolean = client.followRedirects val retryOnConnectionFailure: Boolean = client.retryOnConnectionFailure val callTimeoutMillis: Int = client.callTimeoutMillis val connectTimeoutMillis: Int = client.connectTimeoutMillis val readTimeoutMillis: Int = client.readTimeoutMillis val writeTimeoutMillis: Int = client.writeTimeoutMillis val pingIntervalMillis: Int = client.pingIntervalMillis val call: Call = client.newCall(Request.Builder().build()) val webSocket: WebSocket = client.newWebSocket( Request.Builder().build(), object : WebSocketListener() { }) val newBuilder: OkHttpClient.Builder = client.newBuilder() } @Test fun okHttpClientBuilder() { var builder: OkHttpClient.Builder = OkHttpClient.Builder() builder = builder.callTimeout(0L, TimeUnit.SECONDS) builder = builder.callTimeout(Duration.ofSeconds(0L)) builder = builder.connectTimeout(0L, TimeUnit.SECONDS) builder = builder.connectTimeout(Duration.ofSeconds(0L)) builder = builder.readTimeout(0L, TimeUnit.SECONDS) builder = builder.readTimeout(Duration.ofSeconds(0L)) builder = builder.writeTimeout(0L, TimeUnit.SECONDS) builder = builder.writeTimeout(Duration.ofSeconds(0L)) builder = builder.pingInterval(0L, TimeUnit.SECONDS) builder = builder.pingInterval(Duration.ofSeconds(0L)) builder = builder.proxy(Proxy.NO_PROXY) builder = builder.proxySelector(NullProxySelector) builder = builder.cookieJar(CookieJar.NO_COOKIES) builder = builder.cache(Cache(File("/cache/"), Integer.MAX_VALUE.toLong())) builder = builder.dns(Dns.SYSTEM) builder = builder.socketFactory(SocketFactory.getDefault()) builder = builder.sslSocketFactory(localhost().sslSocketFactory(), localhost().trustManager) builder = builder.hostnameVerifier(OkHostnameVerifier) builder = builder.certificatePinner(CertificatePinner.DEFAULT) builder = builder.authenticator(Authenticator.NONE) builder = builder.proxyAuthenticator(Authenticator.NONE) builder = builder.connectionPool(ConnectionPool(0, 0, TimeUnit.SECONDS)) builder = builder.followSslRedirects(false) builder = builder.followRedirects(false) builder = builder.retryOnConnectionFailure(false) builder = builder.dispatcher(Dispatcher()) builder = builder.protocols(listOf(Protocol.HTTP_1_1)) builder = builder.connectionSpecs(listOf(ConnectionSpec.MODERN_TLS)) val interceptors: List<Interceptor> = builder.interceptors() builder = builder.addInterceptor(object : Interceptor { override fun intercept(chain: Interceptor.Chain): Response = TODO() }) builder = builder.addInterceptor { it: Interceptor.Chain -> TODO() } val networkInterceptors: List<Interceptor> = builder.networkInterceptors() builder = builder.addNetworkInterceptor(object : Interceptor { override fun intercept(chain: Interceptor.Chain): Response = TODO() }) builder = builder.addNetworkInterceptor { it: Interceptor.Chain -> TODO() } builder = builder.eventListener(EventListener.NONE) builder = builder.eventListenerFactory(object : EventListener.Factory { override fun create(call: Call): EventListener = TODO() }) val client: OkHttpClient = builder.build() } @Test fun testAddInterceptor() { val builder = OkHttpClient.Builder() val i = HttpLoggingInterceptor() builder.interceptors().add(i) builder.networkInterceptors().add(i) } @Test fun protocol() { var protocol: Protocol = Protocol.HTTP_2 protocol = Protocol.get("") } @Test fun pushPromise() { val pushPromise: PushPromise = PushPromise("", "", headersOf(), MockResponse()) val method: String = pushPromise.method val path: String = pushPromise.path val headers: Headers = pushPromise.headers val response: MockResponse = pushPromise.response } @Test fun queueDispatcher() { var queueDispatcher: QueueDispatcher = object : QueueDispatcher() { override fun dispatch(request: RecordedRequest): MockResponse = TODO() override fun peek(): MockResponse = TODO() override fun enqueueResponse(response: MockResponse) = TODO() override fun shutdown() = TODO() override fun setFailFast(failFast: Boolean) = TODO() override fun setFailFast(failFastResponse: MockResponse?) = TODO() } queueDispatcher = QueueDispatcher() var mockResponse: MockResponse = queueDispatcher.dispatch( RecordedRequest("", headersOf(), listOf(), 0L, Buffer(), 0, Socket())) mockResponse = queueDispatcher.peek() queueDispatcher.enqueueResponse(MockResponse()) queueDispatcher.shutdown() queueDispatcher.setFailFast(false) queueDispatcher.setFailFast(MockResponse()) } @Test fun recordedRequest() { var recordedRequest: RecordedRequest = RecordedRequest( "", headersOf(), listOf(), 0L, Buffer(), 0, Socket()) recordedRequest = RecordedRequest("", headersOf(), listOf(), 0L, Buffer(), 0, Socket()) var requestUrl: HttpUrl? = recordedRequest.requestUrl var requestLine: String = recordedRequest.requestLine var method: String? = recordedRequest.method var path: String? = recordedRequest.path var headers: Headers = recordedRequest.headers val header: String? = recordedRequest.getHeader("") var chunkSizes: List<Int> = recordedRequest.chunkSizes var bodySize: Long = recordedRequest.bodySize var body: Buffer = recordedRequest.body var utf8Body: String = recordedRequest.body.readUtf8() var sequenceNumber: Int = recordedRequest.sequenceNumber var tlsVersion: TlsVersion? = recordedRequest.tlsVersion var handshake: Handshake? = recordedRequest.handshake } @Test fun request() { val request: Request = Request.Builder().build() val isHttps: Boolean = request.isHttps val url: HttpUrl = request.url val method: String = request.method val headers: Headers = request.headers val header: String? = request.header("") val headersForName: List<String> = request.headers("") val body: RequestBody? = request.body var tag: Any? = request.tag() tag = request.tag(Any::class.java) val builder: Request.Builder = request.newBuilder() val cacheControl: CacheControl = request.cacheControl } @Test fun requestBuilder() { val requestBody = "".toRequestBody(null) var builder = Request.Builder() builder = builder.url("".toHttpUrl()) builder = builder.url("") builder = builder.url(URL("")) builder = builder.header("", "") builder = builder.addHeader("", "") builder = builder.removeHeader("") builder = builder.headers(headersOf()) builder = builder.cacheControl(CacheControl.FORCE_CACHE) builder = builder.get() builder = builder.head() builder = builder.post(requestBody) builder = builder.delete(requestBody) builder = builder.delete(null) builder = builder.put(requestBody) builder = builder.patch(requestBody) builder = builder.method("", requestBody) builder = builder.method("", null) builder = builder.tag("") builder = builder.tag(null) builder = builder.tag(String::class.java, "") builder = builder.tag(String::class.java, null) val request: Request = builder.build() } @Test fun requestBody() { var requestBody: RequestBody = object : RequestBody() { override fun contentType(): MediaType? = TODO() override fun contentLength(): Long = TODO() override fun isDuplex(): Boolean = TODO() override fun isOneShot(): Boolean = TODO() override fun writeTo(sink: BufferedSink) = TODO() } requestBody = "".toRequestBody(null) requestBody = "".toRequestBody("".toMediaTypeOrNull()) requestBody = ByteString.EMPTY.toRequestBody(null) requestBody = ByteString.EMPTY.toRequestBody("".toMediaTypeOrNull()) requestBody = byteArrayOf(0, 1).toRequestBody(null, 0, 2) requestBody = byteArrayOf(0, 1).toRequestBody("".toMediaTypeOrNull(), 0, 2) requestBody = byteArrayOf(0, 1).toRequestBody(null, 0, 2) requestBody = byteArrayOf(0, 1).toRequestBody("".toMediaTypeOrNull(), 0, 2) requestBody = File("").asRequestBody(null) requestBody = File("").asRequestBody("".toMediaTypeOrNull()) } @Test fun response() { val response: Response = Response.Builder().build() val request: Request = response.request val protocol: Protocol = response.protocol val code: Int = response.code val successful: Boolean = response.isSuccessful val message: String = response.message val handshake: Handshake? = response.handshake val headersForName: List<String> = response.headers("") val header: String? = response.header("") val headers: Headers = response.headers val trailers: Headers = response.trailers() val peekBody: ResponseBody = response.peekBody(0L) val body: ResponseBody? = response.body val builder: Response.Builder = response.newBuilder() val redirect: Boolean = response.isRedirect val networkResponse: Response? = response.networkResponse val cacheResponse: Response? = response.cacheResponse val priorResponse: Response? = response.priorResponse val challenges: List<Challenge> = response.challenges() val cacheControl: CacheControl = response.cacheControl val sentRequestAtMillis: Long = response.sentRequestAtMillis val receivedResponseAtMillis: Long = response.receivedResponseAtMillis } @Test fun responseBuilder() { var builder: Response.Builder = Response.Builder() builder = builder.request(Request.Builder().build()) builder = builder.protocol(Protocol.HTTP_2) builder = builder.code(0) builder = builder.message("") builder = builder.handshake(Handshake.get( TlsVersion.TLS_1_3, CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, listOf(), listOf()) ) builder = builder.handshake(null) builder = builder.header("", "") builder = builder.addHeader("", "") builder = builder.removeHeader("") builder = builder.headers(headersOf()) builder = builder.body("".toResponseBody(null)) builder = builder.body(null) builder = builder.networkResponse(Response.Builder().build()) builder = builder.networkResponse(null) builder = builder.cacheResponse(Response.Builder().build()) builder = builder.cacheResponse(null) builder = builder.priorResponse(Response.Builder().build()) builder = builder.priorResponse(null) builder = builder.sentRequestAtMillis(0L) builder = builder.receivedResponseAtMillis(0L) val response: Response = builder.build() } @Test fun responseBody() { var responseBody: ResponseBody = object : ResponseBody() { override fun contentType(): MediaType? = TODO() override fun contentLength(): Long = TODO() override fun source(): BufferedSource = TODO() override fun close() = TODO() } val byteStream = responseBody.byteStream() val source = responseBody.source() val bytes = responseBody.bytes() val charStream = responseBody.charStream() val string = responseBody.string() responseBody.close() responseBody = "".toResponseBody("".toMediaType()) responseBody = "".toResponseBody(null) responseBody = ByteString.EMPTY.toResponseBody("".toMediaType()) responseBody = ByteString.EMPTY.toResponseBody(null) responseBody = byteArrayOf(0, 1).toResponseBody("".toMediaType()) responseBody = byteArrayOf(0, 1).toResponseBody(null) responseBody = Buffer().asResponseBody("".toMediaType(), 0L) responseBody = Buffer().asResponseBody(null, 0L) } @Test fun route() { val route: Route = newRoute() val address: Address = route.address val proxy: Proxy = route.proxy val inetSocketAddress: InetSocketAddress = route.socketAddress val requiresTunnel: Boolean = route.requiresTunnel() } @Test fun socketPolicy() { val socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN } @Test fun tlsVersion() { var tlsVersion: TlsVersion = TlsVersion.TLS_1_3 val javaName: String = tlsVersion.javaName tlsVersion = TlsVersion.forJavaName("") } @Test fun webSocket() { val webSocket = object : WebSocket { override fun request(): Request = TODO() override fun queueSize(): Long = TODO() override fun send(text: String): Boolean = TODO() override fun send(bytes: ByteString): Boolean = TODO() override fun close(code: Int, reason: String?): Boolean = TODO() override fun cancel() = TODO() } } @Test fun webSocketListener() { val webSocketListener = object : WebSocketListener() { override fun onOpen(webSocket: WebSocket, response: Response) = TODO() override fun onMessage(webSocket: WebSocket, text: String) = TODO() override fun onMessage(webSocket: WebSocket, bytes: ByteString) = TODO() override fun onClosing(webSocket: WebSocket, code: Int, reason: String) = TODO() override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = TODO() override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = TODO() } } private fun newAddress(): Address { return Address( "", 0, Dns.SYSTEM, SocketFactory.getDefault(), localhost().sslSocketFactory(), OkHostnameVerifier, CertificatePinner.DEFAULT, Authenticator.NONE, Proxy.NO_PROXY, listOf(Protocol.HTTP_1_1), listOf(ConnectionSpec.MODERN_TLS), NullProxySelector ) } private fun newCall(): Call { return object : Call { override fun request(): Request = TODO() override fun execute(): Response = TODO() override fun enqueue(responseCallback: Callback) = TODO() override fun cancel() = TODO() override fun isExecuted(): Boolean = TODO() override fun isCanceled(): Boolean = TODO() override fun timeout(): Timeout = TODO() override fun clone(): Call = TODO() } } private fun newCookieHandler(): CookieHandler { return object : CookieHandler() { override fun put( uri: URI?, responseHeaders: MutableMap<String, MutableList<String>>? ) = TODO() override fun get( uri: URI?, requestHeaders: MutableMap<String, MutableList<String>>? ): MutableMap<String, MutableList<String>> = TODO() } } private fun newInterceptorChain(): Interceptor.Chain { return object : Interceptor.Chain { override fun request(): Request = TODO() override fun proceed(request: Request): Response = TODO() override fun connection(): Connection? = TODO() override fun call(): Call = TODO() override fun connectTimeoutMillis(): Int = TODO() override fun withConnectTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = TODO() override fun readTimeoutMillis(): Int = TODO() override fun withReadTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = TODO() override fun writeTimeoutMillis(): Int = TODO() override fun withWriteTimeout(timeout: Int, unit: TimeUnit): Interceptor.Chain = TODO() } } private fun newRoute(): Route { return Route(newAddress(), Proxy.NO_PROXY, InetSocketAddress.createUnresolved("", 0)) } }
apache-2.0
gumil/basamto
app/src/main/kotlin/io/github/gumil/basamto/common/RxLifecycle.kt
1
2516
/* * The MIT License (MIT) * * Copyright 2017 Miguel Panelo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.gumil.basamto.common import android.arch.lifecycle.Lifecycle import android.arch.lifecycle.LifecycleObserver import android.arch.lifecycle.OnLifecycleEvent import io.reactivex.Observable import io.reactivex.Observer class RxLifecycle : LifecycleObserver, Observable<Lifecycle.Event>() { private var observer: Observer<in Lifecycle.Event>? = null override fun subscribeActual(observer: Observer<in Lifecycle.Event>) { this.observer = observer } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { observer?.onNext(Lifecycle.Event.ON_CREATE) } @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStart() { observer?.onNext(Lifecycle.Event.ON_START) } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { observer?.onNext(Lifecycle.Event.ON_RESUME) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun onPause() { observer?.onNext(Lifecycle.Event.ON_PAUSE) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { observer?.onNext(Lifecycle.Event.ON_STOP) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { observer?.onNext(Lifecycle.Event.ON_DESTROY) } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) fun onAny() { observer?.onNext(Lifecycle.Event.ON_ANY) } }
mit
WonderBeat/suchmarines
src/main/kotlin/org/wow/learning/predict/Predictor.kt
1
184
package org.wow.learning.predict import com.epam.starwors.galaxy.Planet public trait Predictor <RESULT, INPUT> { fun predict(input: INPUT, world: Collection<Planet>): RESULT }
mit
raziel057/FrameworkBenchmarks
frameworks/Kotlin/pronghorn/src/main/kotlin/pronghorn/utils/TestConfig.kt
4
1274
package pronghorn.utils import tech.pronghorn.util.ignoreException import java.util.Properties object TestConfig { private val properties = parsePropertiesConfig() val listenHost = properties.getProperty("listenHost", "0.0.0.0") val listenPort = getIntProperty("listenPort", 8080) val dbHost = properties.getProperty("dbHost", "TFB-database") val dbPort = getIntProperty("dbPort", 27017) val dbName = properties.getProperty("dbName", "hello_world") val fortunesCollectionName = properties.getProperty("fortunesCollectionName", "fortune") val worldCollectionName = properties.getProperty("worldCollectionName", "world") private fun getIntProperty(key: String, default: Int): Int { val result = properties.getProperty(key) return when (result) { null -> default else -> result.toIntOrNull() ?: default } } private fun parsePropertiesConfig(): Properties { val properties = Properties() ignoreException { val stream = javaClass.classLoader.getResource("benchmark.properties")?.openStream() if (stream != null) { properties.load(stream) } } return properties } }
bsd-3-clause
myTargetSDK/mytarget-android
myTargetDemo/app/src/main/java/com/my/targetDemoApp/CustiomAdvertisingType.kt
1
553
package com.my.targetDemoApp import java.util.* class CustomAdvertisingType(val adType: AdType, val slotId: Int?, val params: String? = null) { var name = "Custom ${ adType.toString() .toLowerCase(Locale.getDefault()) .replace("_", " ") }" enum class AdType { STANDARD_320X50, STANDARD_300X250, STANDARD_728X90, STANDARD_ADAPTIVE, INTERSTITIAL, REWARDED, NATIVE_AD, NATIVE_BANNER, INSTREAM; } }
lgpl-3.0
dafi/photoshelf
tumblr-dialog/src/main/java/com/ternaryop/photoshelf/tumblr/dialog/editor/adapter/ThumbnailAdapter.kt
1
1130
package com.ternaryop.photoshelf.tumblr.dialog.editor.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import com.ternaryop.photoshelf.adapter.AbsBaseAdapter import com.ternaryop.photoshelf.tumblr.dialog.R class ThumbnailAdapter( private val context: Context, private val thumbnailSize: Int ) : AbsBaseAdapter<ThumbnailViewHolder>() { private val items: MutableList<String> = mutableListOf() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ThumbnailViewHolder { return ThumbnailViewHolder(LayoutInflater.from(context).inflate(R.layout.thumbnail, parent, false)) } override fun onBindViewHolder(holder: ThumbnailViewHolder, position: Int) { holder.bindModel(items[position], thumbnailSize) } override fun getItemCount() = items.size fun getItem(position: Int) = items[position] fun addAll(list: List<String>) { items.addAll(list) notifyDataSetChanged() } fun clear() { val size = items.size items.clear() notifyItemRangeRemoved(0, size) } }
mit
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/client/DoKitMcClientFragment.kt
1
2253
package com.didichuxing.doraemonkit.kit.mc.oldui.client import android.os.Bundle import android.view.View import android.widget.TextView import androidx.lifecycle.lifecycleScope import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.kit.test.TestMode import com.didichuxing.doraemonkit.kit.core.BaseFragment import com.didichuxing.doraemonkit.kit.mc.oldui.DoKitMcManager import com.didichuxing.doraemonkit.kit.mc.ui.DoKitMcActivity import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McClientHistory import com.didichuxing.doraemonkit.kit.mc.net.DoKitMcClient import com.didichuxing.doraemonkit.kit.mc.net.DokitMcConnectManager import com.didichuxing.doraemonkit.kit.mc.ui.McPages import com.didichuxing.doraemonkit.mc.R import kotlinx.coroutines.launch /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/10-10:52 * 描 述: * 修订历史: * ================================================ */ class DoKitMcClientFragment : BaseFragment() { private var history: McClientHistory? = null override fun onRequestLayout(): Int { return R.layout.dk_fragment_mc_client } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) history = DokitMcConnectManager.itemHistory findViewById<TextView>(R.id.tv_host_info).text = "当前设备已连接主机:ws://${history?.host}:${history?.port}/${history?.path}" findViewById<View>(R.id.btn_close).setOnClickListener { lifecycleScope.launch { DoKitMcManager.WS_MODE = TestMode.UNKNOWN DoKit.removeFloating(ClientDoKitView::class) DoKitMcClient.close() if (activity is DoKitMcActivity) { (activity as DoKitMcActivity).onBackPressed() } } } findViewById<View>(R.id.btn_history).setOnClickListener { lifecycleScope.launch { if (activity is DoKitMcActivity) { (activity as DoKitMcActivity).pushFragment(McPages.CLIENT_HISTORY) } } } } }
apache-2.0
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/webview/CommWebViewFragment.kt
1
1279
package com.didichuxing.doraemonkit.kit.webview import android.os.Bundle import android.view.View import com.didichuxing.doraemonkit.R import com.didichuxing.doraemonkit.kit.core.BaseFragment import com.didichuxing.doraemonkit.kit.network.NetworkManager import com.didichuxing.doraemonkit.widget.titlebar.HomeTitleBar import com.didichuxing.doraemonkit.widget.webview.MyWebView /** * @author jintai * @desc: 全局webview fragment */ class CommWebViewFragment : BaseFragment() { private lateinit var mWebView: MyWebView private lateinit var mTitle: HomeTitleBar override fun onRequestLayout(): Int { return R.layout.dk_fragment_comm_webview } override fun onViewCreated( view: View, savedInstanceState: Bundle? ) { super.onViewCreated(view, savedInstanceState) initView() } private fun initView() { mTitle = findViewById(R.id.title_bar) mTitle.setListener { activity?.finish() } mWebView = findViewById(R.id.webview) WebViewManager.url?.let { url -> mWebView.loadUrl(url) mWebView.setCallBack { title -> title?.let { mTitle.setTitle(it) } } } } }
apache-2.0
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/yllxs.kt
1
3554
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.ownTextListSplitWhitespace import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern /** * Created by AoEiuV020 on 2018.06.02-20:54:12. */ class Yllxs : DslJsoupNovelContext() {init { reason = "官方搜索不可用," hide = true site { name = "166小说" baseUrl = "http://www.166xs.com" logo = "http://m.166xs.com/system/logo.png" } search { get { charset = "GBK" url = "/modules/article/search.php" data { "searchkey" to it // 加上&page=1可以避开搜索时间间隔的限制, // 也可以通过不加载cookies避开搜索时间间隔的限制, "page" to "1" } } document { if (root.ownerDocument().location().endsWith(".html")) { // "http://www.166xs.com/116732.html" single { name("#book_left_a > div.book > div.book_info > div.title > h2") { it.ownText() } author("#book_left_a > div.book > div.book_info > div.title > h2 > address", block = pickString("作\\s*者:(\\S*)")) } } else { items("#Updates_list > ul > li") { name("> div.works > a.name") author("> div.author > a", block = pickString("([^ ]*) 作品集")) } } } } // "http://www.166xs.com/116732.html" // "http://www.166xs.com/xiaoshuo/116/116732/" // "http://www.166xs.com/xiaoshuo/121/121623/34377467.html" // http://www.166xs.com/xiaoshuo/0/121/59420.html // 主要就是这个详情页,和其他网站比,这个详情页地址没有取bookId一部分分隔, bookIdRegex = "(/xiaoshuo/\\d*)?/(\\d+)" bookIdIndex = 1 detailPageTemplate = "/%s.html" detail { document { novel { /* <h2>超品相师<address>作者:西域刀客</address></h2> */ name("#book_left_a > div.book > div.book_info > div.title > h2") { it.ownText() } author("#book_left_a > div.book > div.book_info > div.title > h2 > address", block = pickString("作\\s*者:(\\S*)")) } image("#book_left_a > div.book > div.pic > img") update("#book_left_a > div.book > div.book_info > div.info > p > span:nth-child(8)", format = "yyyy-MM-dd", block = pickString("更新时间:(.*)")) introduction("#book_left_a > div.book > div.book_info > div.intro > p") } } chapterDivision = 1000 chaptersPageTemplate = "/xiaoshuo/%d/%s" chapters { // 七个多余的, // 三个class="book_btn", // 一个最新章, // 三个功能按钮, document { items("body > dl > dd > a") }.drop(3) } // http://www.166xs.com/xiaoshuo/121/121623/34377471.html // http://www.166xs.com/xiaoshuo/31/31008/6750409.html bookIdWithChapterIdRegex = firstThreeIntPattern contentPageTemplate = "/xiaoshuo/%s.html" content { document { items("p.Book_Text") { it.ownTextListSplitWhitespace().dropLastWhile { it == "166小说阅读网" } } } } } }
gpl-3.0
Light-Team/ModPE-IDE-Source
app/src/main/kotlin/com/brackeys/ui/utils/extensions/ViewExtensions2.kt
1
2639
/* * Copyright 2021 Brackeys IDE 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 com.brackeys.ui.utils.extensions import android.content.res.ColorStateList import android.util.TypedValue import android.view.View import android.widget.ImageView import androidx.annotation.ColorRes import androidx.annotation.IdRes import androidx.annotation.MenuRes import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.customview.widget.ViewDragHelper import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.navigation.NavController fun Fragment.setSupportActionBar(toolbar: Toolbar) { val parentActivity = activity as AppCompatActivity parentActivity.setSupportActionBar(toolbar) } val Fragment.supportActionBar: ActionBar? get() = (activity as? AppCompatActivity)?.supportActionBar @Suppress("UNCHECKED_CAST") fun <T : Fragment> FragmentManager.fragment(@IdRes id: Int): T { return findFragmentById(id) as T } fun NavController.popBackStack(n: Int) { for (index in 0 until n) { popBackStack() } } fun ImageView.setTint(@ColorRes colorRes: Int) { imageTintList = ColorStateList.valueOf( context.getColour(colorRes) ) } fun View.setSelectableBackground() = with(TypedValue()) { context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true) setBackgroundResource(resourceId) } fun Toolbar.replaceMenu(@MenuRes menuRes: Int) { menu.clear() inflateMenu(menuRes) } /** * https://stackoverflow.com/a/17802569/4405457 */ fun DrawerLayout.multiplyDraggingEdgeSizeBy(n: Int) { val leftDragger = javaClass.getDeclaredField("mLeftDragger") leftDragger.isAccessible = true val viewDragHelper = leftDragger.get(this) as ViewDragHelper val edgeSize = viewDragHelper.javaClass.getDeclaredField("mEdgeSize") edgeSize.isAccessible = true val edge = edgeSize.getInt(viewDragHelper) edgeSize.setInt(viewDragHelper, edge * n) }
apache-2.0
juxeii/dztools
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/misc/Context.kt
1
1830
package com.jforex.dzjforex.misc import arrow.effects.ForIO import com.dukascopy.api.* import com.jforex.dzjforex.zorro.lotScale lateinit var contextApi: ContextDependencies<ForIO> fun initContextApi(context: IContext) { contextApi = ContextDependencies(context, pluginApi) } interface ContextDependencies<F> : PluginDependencies<F> { val jfContext: IContext val engine: IEngine val account: IAccount val history: IHistory fun Int.toAmount() = Math.abs(this) / lotScale fun Double.toContracts() = (this * lotScale).toInt() fun Double.toSignedContracts(command: IEngine.OrderCommand) = if (command == IEngine.OrderCommand.BUY) toContracts() else -toContracts() fun IOrder.toSignedContracts() = amount.toSignedContracts(orderCommand) fun IOrder.zorroId() = id.toInt() fun IOrder.isFromZorro()= label.startsWith(pluginSettings.labelPrefix()) companion object { operator fun <F> invoke( context: IContext, pluginDependencies: PluginDependencies<F> ): ContextDependencies<F> = object : ContextDependencies<F>, PluginDependencies<F> by pluginDependencies { override val jfContext = context override val engine = context.engine override val account = context.account override val history = context.history } } } object ContextApi { fun <F> ContextDependencies<F>.getSubscribedInstruments() = delay { jfContext.subscribedInstruments } fun <F> ContextDependencies<F>.setSubscribedInstruments(instrumentsToSubscribe: Set<Instrument>) = getSubscribedInstruments().map { subscribedInstruments -> jfContext.setSubscribedInstruments(subscribedInstruments + instrumentsToSubscribe, false) } }
mit
arturbosch/detekt
detekt-rules-exceptions/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/PrintStackTrace.kt
1
2708
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtCatchClause import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression /** * This rule reports code that tries to print the stacktrace of an exception. Instead of simply printing a stacktrace * a better logging solution should be used. * * <noncompliant> * fun foo() { * Thread.dumpStack() * } * * fun bar() { * try { * // ... * } catch (e: IOException) { * e.printStackTrace() * } * } * </noncompliant> * * <compliant> * val LOGGER = Logger.getLogger() * * fun bar() { * try { * // ... * } catch (e: IOException) { * LOGGER.info(e) * } * } * </compliant> */ @ActiveByDefault(since = "1.16.0") class PrintStackTrace(config: Config = Config.empty) : Rule(config) { override val issue = Issue( "PrintStackTrace", Severity.CodeSmell, "Do not print an stack trace. " + "These debug statements should be replaced with a logger or removed.", Debt.TWENTY_MINS ) override fun visitCallExpression(expression: KtCallExpression) { val callNameExpression = expression.getCallNameExpression() if (callNameExpression?.text == "dumpStack" && callNameExpression.getReceiverExpression()?.text == "Thread" ) { report(CodeSmell(issue, Entity.from(expression), issue.description)) } } override fun visitCatchSection(catchClause: KtCatchClause) { catchClause.catchBody?.forEachDescendantOfType<KtNameReferenceExpression> { if (it.text == catchClause.catchParameter?.name && hasPrintStacktraceCallExpression(it)) { report(CodeSmell(issue, Entity.from(it), issue.description)) } } } private fun hasPrintStacktraceCallExpression(expression: KtNameReferenceExpression): Boolean { val methodCall = expression.nextSibling?.nextSibling return methodCall is KtCallExpression && methodCall.text.startsWith("printStackTrace(") } }
apache-2.0
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/utils/SupportUtils.kt
1
4369
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils import android.annotation.TargetApi import android.app.Activity import android.content.ActivityNotFoundException import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.provider.Settings import mozilla.components.browser.session.Session import org.mozilla.focus.ext.components import org.mozilla.focus.locale.Locales import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.util.Locale object SupportUtils { const val HELP_URL = "https://support.mozilla.org/kb/what-firefox-focus-android" const val DEFAULT_BROWSER_URL = "https://support.mozilla.org/kb/set-firefox-focus-default-browser-android" const val REPORT_SITE_ISSUE_URL = "https://webcompat.com/issues/new?url=%s&label=browser-focus-geckoview" const val PRIVACY_NOTICE_URL = "https://www.mozilla.org/privacy/firefox-focus/" const val PRIVACY_NOTICE_KLAR_URL = "https://www.mozilla.org/de/privacy/firefox-klar/" const val OPEN_WITH_DEFAULT_BROWSER_URL = "https://www.mozilla.org/openGeneralSettings" // Fake URL val manifestoURL: String get() { val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://www.mozilla.org/$langTag/about/manifesto/" } enum class SumoTopic( /** The final path segment for a SUMO URL - see {@see #getSumoURLForTopic} */ internal val topicStr: String ) { ADD_SEARCH_ENGINE("add-search-engine"), AUTOCOMPLETE("autofill-domain-android"), TRACKERS("trackers"), USAGE_DATA("usage-data"), WHATS_NEW("whats-new-focus-android-8"), SEARCH_SUGGESTIONS("search-suggestions-focus-android"), ALLOWLIST("focus-android-allowlist") } fun getSumoURLForTopic(context: Context, topic: SumoTopic): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) val appVersion = getAppVersion(context) val osTarget = "Android" val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://support.mozilla.org/1/mobile/$appVersion/$osTarget/$langTag/$escapedTopic" } // For some reason this URL has a different format than the other SUMO URLs fun getSafeBrowsingURL(): String { val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://support.mozilla.org/$langTag/kb/how-does-phishing-and-malware-protection-work" } private fun getEncodedTopicUTF8(topic: String): String { try { return URLEncoder.encode(topic, "UTF-8") } catch (e: UnsupportedEncodingException) { throw IllegalStateException("utf-8 should always be available", e) } } private fun getAppVersion(context: Context): String { try { return context.packageManager.getPackageInfo(context.packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { // This should be impossible - we should always be able to get information about ourselves: throw IllegalStateException("Unable find package details for Focus", e) } } fun openDefaultBrowserSumoPage(context: Context) { val session = Session(SupportUtils.DEFAULT_BROWSER_URL, source = Session.Source.MENU) context.components.sessionManager.add(session, selected = true) if (context is Activity) { context.finish() } else { openDefaultBrowserSumoPage((context as ContextWrapper).baseContext) } } @TargetApi(Build.VERSION_CODES.N) fun openDefaultAppsSettings(context: Context) { try { val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS) context.startActivity(intent) } catch (e: ActivityNotFoundException) { // In some cases, a matching Activity may not exist (according to the Android docs). openDefaultBrowserSumoPage(context) } } }
mpl-2.0
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/music/filters/TimescaleFilter.kt
1
745
package gg.octave.bot.music.filters import com.github.natanbc.lavadsp.timescale.TimescalePcmAudioFilter import com.sedmelluq.discord.lavaplayer.filter.FloatPcmAudioFilter import com.sedmelluq.discord.lavaplayer.format.AudioDataFormat class TimescaleFilter : FilterConfig<TimescalePcmAudioFilter> { private var config: TimescalePcmAudioFilter.() -> Unit = {} override fun configure(transformer: TimescalePcmAudioFilter.() -> Unit): TimescaleFilter { config = transformer return this } override fun build(downstream: FloatPcmAudioFilter, format: AudioDataFormat): FloatPcmAudioFilter { return TimescalePcmAudioFilter(downstream, format.channelCount, format.sampleRate) .also(config) } }
mit
nextcloud/android
app/src/androidTest/java/com/nextcloud/client/migrations/MockSharedPreferencesTest.kt
1
2993
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * 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.nextcloud.client.migrations import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @Suppress("MagicNumber") class MockSharedPreferencesTest { private lateinit var mock: MockSharedPreferences @Before fun setUp() { mock = MockSharedPreferences() } @Test fun getSetStringSet() { val value = setOf("alpha", "bravo", "charlie") mock.edit().putStringSet("key", value).apply() val copy = mock.getStringSet("key", mutableSetOf()) assertNotSame(value, copy) assertEquals(value, copy) } @Test fun getSetInt() { val value = 42 val editor = mock.edit() editor.putInt("key", value) assertEquals(100, mock.getInt("key", 100)) editor.apply() assertEquals(42, mock.getInt("key", 100)) } @Test fun getSetBoolean() { val value = true val editor = mock.edit() editor.putBoolean("key", value) assertFalse(mock.getBoolean("key", false)) editor.apply() assertTrue(mock.getBoolean("key", false)) } @Test fun getSetString() { val value = "a value" val editor = mock.edit() editor.putString("key", value) assertEquals("default", mock.getString("key", "default")) editor.apply() assertEquals("a value", mock.getString("key", "default")) } @Test fun getAll() { // GIVEN // few properties are stored in shared preferences mock.edit() .putInt("int", 1) .putBoolean("bool", true) .putString("string", "value") .putStringSet("stringSet", setOf("alpha", "bravo")) .apply() assertEquals(4, mock.store.size) // WHEN // all properties are retrieved val all = mock.all // THEN // returned map is a different instance // map is equal to internal storage assertNotSame(all, mock.store) assertEquals(all, mock.store) } }
gpl-2.0
genobis/tornadofx
src/main/java/tornadofx/EventBus.kt
1
4488
@file:Suppress("UNCHECKED_CAST") package tornadofx import javafx.application.Platform import tornadofx.EventBus.RunOn.ApplicationThread import java.util.* import java.util.concurrent.atomic.AtomicLong import kotlin.concurrent.thread import kotlin.reflect.KClass open class FXEvent( open val runOn: EventBus.RunOn = ApplicationThread, open val scope: Scope? = null ) class EventContext { internal var unsubscribe = false fun unsubscribe() { unsubscribe = true } } class FXEventRegistration(val eventType: KClass<out FXEvent>, val owner: Component?, val maxCount: Long? = null, val action: EventContext.(FXEvent) -> Unit) { val count = AtomicLong() override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as FXEventRegistration if (eventType != other.eventType) return false if (owner != other.owner) return false if (action != other.action) return false return true } override fun hashCode(): Int { var result = eventType.hashCode() result = 31 * result + (owner?.hashCode() ?: 0) result = 31 * result + action.hashCode() return result } fun unsubscribe() { FX.eventbus.unsubscribe(this) } } class EventBus { enum class RunOn { ApplicationThread, BackgroundThread } private val subscriptions = HashMap<KClass<out FXEvent>, HashSet<FXEventRegistration>>() private val eventScopes = HashMap<EventContext.(FXEvent) -> Unit, Scope>() inline fun <reified T: FXEvent> subscribe(scope: Scope, registration : FXEventRegistration) = subscribe(T::class, scope, registration) fun <T : FXEvent> subscribe(event: KClass<T>, scope: Scope, registration : FXEventRegistration) { subscriptions.getOrPut(event, { HashSet() }).add(registration) eventScopes[registration.action] = scope } inline fun <reified T:FXEvent> subscribe(owner: Component? = null, times: Long? = null, scope: Scope, noinline action: (T) -> Unit) = subscribe(owner, times, T::class, scope, action) fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: KClass<T>, scope: Scope, action: (T) -> Unit) { subscribe(event, scope, FXEventRegistration(event, owner, times, action as EventContext.(FXEvent) -> Unit)) } fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: Class<T>, scope: Scope, action: (T) -> Unit) = subscribe(event.kotlin, scope, FXEventRegistration(event.kotlin, owner, times, action as EventContext.(FXEvent) -> Unit)) inline fun <reified T: FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) = unsubscribe(T::class, action) fun <T : FXEvent> unsubscribe(event: Class<T>, action: EventContext.(T) -> Unit) = unsubscribe(event.kotlin, action) fun <T : FXEvent> unsubscribe(event: KClass<T>, action: EventContext.(T) -> Unit) { subscriptions[event]?.removeAll { it.action == action } eventScopes.remove(action) } fun unsubscribe(registration: FXEventRegistration) { unsubscribe(registration.eventType, registration.action) registration.owner?.subscribedEvents?.get(registration.eventType)?.remove(registration) } fun fire(event: FXEvent) { fun fireEvents() { subscriptions[event.javaClass.kotlin]?.toTypedArray()?.forEach { if (event.scope == null || event.scope == eventScopes[it.action]) { val count = it.count.andIncrement if (it.maxCount == null || count < it.maxCount) { val context = EventContext() it.action.invoke(context, event) if (context.unsubscribe) unsubscribe(it) } else { unsubscribe(it) } } } } if (Platform.isFxApplicationThread()) { if (event.runOn == ApplicationThread) { fireEvents() } else { thread(true) { fireEvents() } } } else { if (event.runOn == ApplicationThread) { Platform.runLater { fireEvents() } } else { fireEvents() } } } }
apache-2.0
glureau/kotlin-design-patterns
src/glureau/kdp/structural/adapter/kotlin/JavaAdapter.kt
1
529
package glureau.kdp.structural.adapter.kotlin /** * Adapt a java class from Kotlin */ internal class JavaAdapter(val adaptee: JavaAdaptee) : TargetInterface { override val operands: List<Double> get() = arrayListOf(adaptee.firstOperand, adaptee.secondOperand) override fun sum(): Double { return adaptee.computeSum() } override fun multiply(): Double { return adaptee.firstOperand * adaptee.secondOperand } override fun max(): Double { return adaptee.max(); } }
unlicense
gameofbombs/kt-postgresql-async
db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/NettyUtils.kt
2
998
package com.github.mauricio.async.db.util import io.netty.channel.nio.NioEventLoopGroup import io.netty.util.internal.logging.InternalLoggerFactory import io.netty.util.internal.logging.Slf4JLoggerFactory /* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * 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. */ object NettyUtils { init { InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE) } val DefaultEventLoopGroup by lazy { NioEventLoopGroup(0, DaemonThreadsFactory("db-async-netty")) } }
apache-2.0
sinnerschrader/account-tool
src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/messaging/GlobalMessageFactory.kt
1
1818
package com.sinnerschrader.s2b.accounttool.presentation.messaging import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.MessageSource import org.springframework.stereotype.Component import java.util.* import javax.servlet.http.HttpServletRequest @Deprecated("remove") @Component(value = "globalMessageFactory") class GlobalMessageFactory { @Autowired private val messageSource: MessageSource? = null fun create(type: GlobalMessageType, messageKey: String, vararg args: String): GlobalMessage { return GlobalMessage(messageKey, messageSource!!.getMessage(messageKey, args, Locale.ENGLISH), type) } fun createError(messageKey: String, vararg args: String): GlobalMessage { return create(GlobalMessageType.ERROR, messageKey, *args) } fun createInfo(messageKey: String, vararg args: String): GlobalMessage { return create(GlobalMessageType.INFO, messageKey, *args) } fun store(request: HttpServletRequest, message: GlobalMessage) { val session = request.session if (session.getAttribute(SESSION_KEY) == null) { session.setAttribute(SESSION_KEY, LinkedList<GlobalMessage>()) } val messages = session.getAttribute(SESSION_KEY) as MutableList<GlobalMessage> messages.add(message) } fun pop(request: HttpServletRequest): List<GlobalMessage> { val session = request.session if (session.getAttribute(SESSION_KEY) == null) { return ArrayList() } val messages = session.getAttribute(SESSION_KEY) as List<GlobalMessage> session.removeAttribute(SESSION_KEY) return messages } companion object { private val SESSION_KEY = GlobalMessageFactory::class.java.name } }
mit
Setekh/Gleipnir-Graphics
src/main/kotlin/eu/corvus/corax/graphics/material/MatcapMaterial.kt
1
4017
/** * Copyright (c) 2013-2019 Corvus Corax Entertainment * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - 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. * * - Neither the name of Corvus Corax Entertainment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.corvus.corax.graphics.material import eu.corvus.corax.graphics.context.RendererContext import eu.corvus.corax.graphics.material.shaders.MatcapShader import eu.corvus.corax.graphics.material.textures.Texture import eu.corvus.corax.scene.Camera import eu.corvus.corax.scene.assets.AssetManager import eu.corvus.corax.scene.geometry.Geometry import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import org.joml.Matrix3f import org.joml.Matrix4f import org.koin.core.KoinComponent /** * @author Vlad Ravenholm on 1/6/2020 */ class MatcapMaterial(val matcapTexture: MatcapTexture = MatcapTexture.MatcapBlue): Material(), KoinComponent { enum class MatcapTexture(val texturePath: String) { MatcapBlue("textures/matcap.png"), MatcapBrown("textures/matcap2.png"), Matcap3("textures/matcap3.png") } override val shader = MatcapShader() var texture: Texture? = null var isLoadingTexture = false private val normalMatrix = Matrix4f() override fun applyParams( renderContext: RendererContext, camera: Camera, geometry: Geometry ) { shader.setUniformValue(shader.viewProjection, camera.viewProjectionMatrix) shader.setUniformValue(shader.modelMatrix, geometry.worldMatrix) shader.setUniformValue(shader.eye, camera.dir) normalMatrix.set(camera.viewMatrix).mul(geometry.worldMatrix).invert().transpose() shader.setUniformValue(shader.normalMatrix, normalMatrix) val texture = texture ?: return shader.setUniformValue(shader.texture, 0) renderContext.useTexture(texture, 0) } override fun cleanRender(renderContext: RendererContext) { val texture = texture ?: return renderContext.unbindTexture(texture) } override fun prepareUpload(assetManager: AssetManager, rendererContext: RendererContext) { super.prepareUpload(assetManager, rendererContext) val texture = texture if (texture == null && !isLoadingTexture) { isLoadingTexture = true scope.launch { [email protected] = assetManager.loadTexture(matcapTexture.texturePath) } } if (texture != null && !texture.isUploaded) { rendererContext.createTexture(texture) } } override fun free() { super.free() texture?.free() } }
bsd-3-clause
valeter/difk
src/test/kotlin/ru/anisimov/difk/DifkInjectorTest.kt
1
8091
/* * Copyright 2017 Ivan Anisimov * * 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 ru.anisimov.difk import org.junit.Assert.* import org.junit.Test import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** * @author Ivan Anisimov * * [email protected] * * 11.06.17 */ class DifkInjectorTest { @Test fun loadProperties() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.init() assertEquals("my_url", injector.getProperty("db.url")) } @Test(expected = RuntimeException::class) fun loadPropertiesAfterInit() { val injector = DifkInjector() injector.init() injector.loadPropertiesFromClasspath("test.properties") } @Test fun setProperty() { val injector = DifkInjector() injector.setProperty("db.url.2", "my_url_2") injector.init() assertEquals("my_url_2", injector.getProperty("db.url.2")) } @Test(expected = RuntimeException::class) fun setPropertyAfterInit() { val injector = DifkInjector() injector.init() injector.setProperty("my.property", "my_value") } @Test fun getPropertyOrNull() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.init() assertEquals(null, injector.getPropertyOrNull("db.url.2")) } /*@Test fun getInstances() { val injector = DifkInjector() val first = Any() val second = Any() injector.addSingleton("first", { first }) injector.addSingleton("second", { second }) injector.init() val instances: List<Any> = injector.getInstances(Any::class) assertEquals(2, instances.size) assertTrue(first === instances[0]) assertTrue(second === instances[1]) }*/ @Test fun singletonIsAlwaysTheSame() { val injector = DifkInjector() injector.addSingleton("single", { Any() }) injector.init() val instance: Any = injector.getInstance("single") for (i in 99 downTo 0) { assertEquals(instance, injector.getInstance("single")) } } @Test fun prototypeIsAlwaysNew() { val injector = DifkInjector() injector.addPrototype("proto", { Any() }) injector.init() val set: MutableSet<Any> = HashSet() for (i in 99 downTo 0) { set.add(injector.getInstance("proto")) } assertEquals(100, set.size) } @Test fun destructorRunOnClose() { val injector = DifkInjector() val destructed = AtomicBoolean(false) injector.addDestructor { destructed.set(true) } injector.init() injector.close() assertTrue(destructed.get()) } @Test fun registerShutdownHookRegisterHookForDestructors() { val injector = DifkInjector() val destructed = AtomicBoolean(false) injector.addDestructor { destructed.set(true) } assertNull(injector.shutdownHook) injector.registerShutdownHook() assertNotNull(injector.shutdownHook) assertFalse(destructed.get()) injector.shutdownHook!!.start() injector.shutdownHook!!.join() assertTrue(destructed.get()) } @Test fun registerShutdownHookRegistersInRuntime() { val injector = DifkInjector() injector.registerShutdownHook() assertTrue(Runtime.getRuntime().removeShutdownHook(injector.shutdownHook)) } @Test fun notExistingBeanReturnsNull() { val injector = DifkInjector() injector.init() assertNull(injector.getInstanceOrNull("not_existing")) } @Test(expected = RuntimeException::class) fun notExistingBeanThrowsException() { val injector = DifkInjector() injector.init() assertNull(injector.getInstance("not_existing")) } @Test fun threadLocalIsUniqueForEachThread() { val injector = DifkInjector() val counter = AtomicInteger(-1) injector.addThreadLocal("counter", { counter.incrementAndGet() }) injector.init() val values = Array(100, { 0 }) val threads = ArrayList<Thread>() (99 downTo 0).mapTo(threads) { object : Thread() { override fun run() { values[it] = injector.getInstance("counter") } } } threads.forEach { it.start() it.join() } assertEquals(99, counter.get()) values.sort() for(i in 99 downTo 0) { assertEquals(i, values[i]) } } @Test fun threadLocalIsSingletonInsideThread() { val injector = DifkInjector() val counter = AtomicInteger(-1) injector.addThreadLocal("counter", { counter.incrementAndGet() }) injector.init() for (i in 99 downTo 0) { assertEquals(0, injector.getInstance("counter")) } } @Test fun simpleScenario() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.addSingleton("dataSource", { DataSource( injector.getProperty("db.url"), injector.getProperty("db.driver.class.name"), injector.getProperty("db.username"), injector.getProperty("db.password") ) }) injector.addSingleton("dao", { Dao(injector.getInstance("dataSource")) }) injector.addSingleton("service", { val s = Service(injector.getInstance("dao")); s.init(); s }) injector.addDestructor { val service: Service = injector.getInstance("service") service.close() } injector.init() val service: Service = injector.getInstance("service") assertFalse(service.closed!!) val difkService: Service = injector.getInstance("service") assertTrue(service === difkService) assertEquals("my_url", difkService.dao.dataSource.url) assertEquals("my_class", difkService.dao.dataSource.driverClassName) assertEquals("my_user", difkService.dao.dataSource.username) assertEquals("my_password", difkService.dao.dataSource.password) injector.close() assertTrue(service.closed!!) } @Test fun sortRelations() { val injector = DifkInjector() val graph: MutableMap<String, MutableSet<String>> = HashMap() graph.put("1", HashSet(listOf("2", "3"))) graph.put("2", HashSet(listOf("4", "5"))) graph.put("3", HashSet(listOf("6", "7"))) assertEquals("1234567".split("").subList(1, 8), injector.sortRelations(graph)) } @Test(expected = RuntimeException::class) fun sortRelationsWithCycle() { val injector = DifkInjector() val graph: MutableMap<String, MutableSet<String>> = HashMap() graph.put("1", HashSet(listOf("2", "3"))) graph.put("2", HashSet(listOf("4", "5"))) graph.put("3", HashSet(listOf("6", "1"))) injector.sortRelations(graph) } class DataSource(val url: String, val driverClassName: String, val username: String, val password: String) class Dao(val dataSource: DataSource) class Service(val dao: Dao) { var closed: Boolean? = null fun init() { closed = false } fun close() { closed = true } } }
apache-2.0
samtstern/quickstart-android
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/LivePreviewActivity.kt
1
13113
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.samples.apps.mlkit.kotlin import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.hardware.Camera import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.CompoundButton import com.google.android.gms.common.annotation.KeepName import com.google.firebase.ml.common.FirebaseMLException import com.google.firebase.samples.apps.mlkit.R import com.google.firebase.samples.apps.mlkit.common.CameraSource import com.google.firebase.samples.apps.mlkit.kotlin.barcodescanning.BarcodeScanningProcessor import com.google.firebase.samples.apps.mlkit.kotlin.custommodel.CustomImageClassifierProcessor import com.google.firebase.samples.apps.mlkit.kotlin.facedetection.FaceContourDetectorProcessor import com.google.firebase.samples.apps.mlkit.kotlin.facedetection.FaceDetectionProcessor import com.google.firebase.samples.apps.mlkit.kotlin.imagelabeling.ImageLabelingProcessor import com.google.firebase.samples.apps.mlkit.kotlin.textrecognition.TextRecognitionProcessor import java.io.IOException import com.google.firebase.samples.apps.mlkit.kotlin.objectdetection.ObjectDetectorProcessor import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions import com.google.firebase.samples.apps.mlkit.common.preference.SettingsActivity import com.google.firebase.samples.apps.mlkit.common.preference.SettingsActivity.LaunchSource import com.google.firebase.samples.apps.mlkit.databinding.ActivityLivePreviewBinding import com.google.firebase.samples.apps.mlkit.kotlin.automl.AutoMLImageLabelerProcessor import com.google.firebase.samples.apps.mlkit.kotlin.automl.AutoMLImageLabelerProcessor.Mode /** Demo app showing the various features of ML Kit for Firebase. This class is used to * set up continuous frame processing on frames from a camera source. */ @KeepName class LivePreviewActivity : AppCompatActivity(), OnRequestPermissionsResultCallback, OnItemSelectedListener, CompoundButton.OnCheckedChangeListener { private var cameraSource: CameraSource? = null private var selectedModel = FACE_CONTOUR private lateinit var binding: ActivityLivePreviewBinding private val requiredPermissions: Array<String?> get() { return try { val info = this.packageManager .getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS) val ps = info.requestedPermissions if (ps != null && ps.isNotEmpty()) { ps } else { arrayOfNulls(0) } } catch (e: Exception) { arrayOfNulls(0) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") binding = ActivityLivePreviewBinding.inflate(layoutInflater) setContentView(binding.root) val options = arrayListOf( FACE_CONTOUR, FACE_DETECTION, OBJECT_DETECTION, AUTOML_IMAGE_LABELING, TEXT_DETECTION, BARCODE_DETECTION, IMAGE_LABEL_DETECTION, CLASSIFICATION_QUANT, CLASSIFICATION_FLOAT ) // Creating adapter for spinner val dataAdapter = ArrayAdapter(this, R.layout.spinner_style, options) // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // attaching data adapter to spinner with(binding) { spinner.adapter = dataAdapter spinner.onItemSelectedListener = this@LivePreviewActivity facingSwitch.setOnCheckedChangeListener(this@LivePreviewActivity) // Hide the toggle button if there is only 1 camera if (Camera.getNumberOfCameras() == 1) { facingSwitch.visibility = View.GONE } } if (allPermissionsGranted()) { createCameraSource(selectedModel) } else { getRuntimePermissions() } } @Synchronized override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) selectedModel = parent.getItemAtPosition(pos).toString() Log.d(TAG, "Selected model: $selectedModel") binding.firePreview.stop() if (allPermissionsGranted()) { createCameraSource(selectedModel) startCameraSource() } else { getRuntimePermissions() } } override fun onNothingSelected(parent: AdapterView<*>) { // Do nothing. } override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { Log.d(TAG, "Set facing") cameraSource?.let { if (isChecked) { it.setFacing(CameraSource.CAMERA_FACING_FRONT) } else { it.setFacing(CameraSource.CAMERA_FACING_BACK) } } binding.firePreview.stop() startCameraSource() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.live_preview_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.settings) { val intent = Intent(this, SettingsActivity::class.java) intent.putExtra(SettingsActivity.EXTRA_LAUNCH_SOURCE, LaunchSource.LIVE_PREVIEW) startActivity(intent) return true } return super.onOptionsItemSelected(item) } private fun createCameraSource(model: String) { // If there's no existing cameraSource, create one. if (cameraSource == null) { cameraSource = CameraSource(this, binding.fireFaceOverlay) } try { when (model) { CLASSIFICATION_QUANT -> { Log.i(TAG, "Using Custom Image Classifier (quant) Processor") cameraSource?.setMachineLearningFrameProcessor( CustomImageClassifierProcessor( this, true ) ) } CLASSIFICATION_FLOAT -> { Log.i(TAG, "Using Custom Image Classifier (float) Processor") cameraSource?.setMachineLearningFrameProcessor( CustomImageClassifierProcessor( this, false ) ) } TEXT_DETECTION -> { Log.i(TAG, "Using Text Detector Processor") cameraSource?.setMachineLearningFrameProcessor(TextRecognitionProcessor()) } FACE_DETECTION -> { Log.i(TAG, "Using Face Detector Processor") cameraSource?.setMachineLearningFrameProcessor(FaceDetectionProcessor(resources)) } OBJECT_DETECTION -> { Log.i(TAG, "Using Object Detector Processor") val objectDetectorOptions = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification().build() cameraSource?.setMachineLearningFrameProcessor( ObjectDetectorProcessor(objectDetectorOptions) ) } AUTOML_IMAGE_LABELING -> { cameraSource?.setMachineLearningFrameProcessor(AutoMLImageLabelerProcessor(this, Mode.LIVE_PREVIEW)) } BARCODE_DETECTION -> { Log.i(TAG, "Using Barcode Detector Processor") cameraSource?.setMachineLearningFrameProcessor(BarcodeScanningProcessor()) } IMAGE_LABEL_DETECTION -> { Log.i(TAG, "Using Image Label Detector Processor") cameraSource?.setMachineLearningFrameProcessor(ImageLabelingProcessor()) } FACE_CONTOUR -> { Log.i(TAG, "Using Face Contour Detector Processor") cameraSource?.setMachineLearningFrameProcessor(FaceContourDetectorProcessor()) } else -> Log.e(TAG, "Unknown model: $model") } } catch (e: FirebaseMLException) { Log.e(TAG, "can not create camera source: $model") } } /** * Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet * (e.g., because onResume was called before the camera source was created), this will be called * again when the camera source is created. */ private fun startCameraSource() { cameraSource?.let { try { binding.firePreview.start(cameraSource, binding.fireFaceOverlay) } catch (e: IOException) { Log.e(TAG, "Unable to start camera source.", e) cameraSource?.release() cameraSource = null } } } public override fun onResume() { super.onResume() Log.d(TAG, "onResume") startCameraSource() } /** Stops the camera. */ override fun onPause() { super.onPause() binding.firePreview.stop() } public override fun onDestroy() { super.onDestroy() cameraSource?.release() } private fun allPermissionsGranted(): Boolean { for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission!!)) { return false } } return true } private fun getRuntimePermissions() { val allNeededPermissions = arrayListOf<String>() for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission!!)) { allNeededPermissions.add(permission) } } if (allNeededPermissions.isNotEmpty()) { ActivityCompat.requestPermissions( this, allNeededPermissions.toTypedArray(), PERMISSION_REQUESTS ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { Log.i(TAG, "Permission granted!") if (allPermissionsGranted()) { createCameraSource(selectedModel) } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } companion object { private const val FACE_DETECTION = "Face Detection" private const val TEXT_DETECTION = "Text Detection" private const val OBJECT_DETECTION = "Object Detection" private const val AUTOML_IMAGE_LABELING = "AutoML Vision Edge" private const val BARCODE_DETECTION = "Barcode Detection" private const val IMAGE_LABEL_DETECTION = "Label Detection" private const val CLASSIFICATION_QUANT = "Classification (quantized)" private const val CLASSIFICATION_FLOAT = "Classification (float)" private const val FACE_CONTOUR = "Face Contour" private const val TAG = "LivePreviewActivity" private const val PERMISSION_REQUESTS = 1 private fun isPermissionGranted(context: Context, permission: String): Boolean { if (ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_GRANTED ) { Log.i(TAG, "Permission granted: $permission") return true } Log.i(TAG, "Permission NOT granted: $permission") return false } } }
apache-2.0
Ztiany/Repository
Kotlin/Kotlin-Coroutine-V1.1.2/src/main/kotlin/cn/kotliner/coroutine/async/BaseContinuation.kt
2
474
package cn.kotliner.coroutine.async import kotlin.coroutines.experimental.Continuation import kotlin.coroutines.experimental.CoroutineContext import kotlin.coroutines.experimental.EmptyCoroutineContext /** * Created by benny on 5/29/17. */ class BaseContinuation: Continuation<Unit> { override val context: CoroutineContext = EmptyCoroutineContext override fun resume(value: Unit) { } override fun resumeWithException(exception: Throwable) { } }
apache-2.0
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/datatype/datatypes/RotationVectorNorthObject.kt
1
393
package com.telenav.osv.data.collector.datatype.datatypes import com.telenav.osv.data.collector.datatype.util.LibraryUtil /** * Class which retrieves the north rotation vector value of the device */ class RotationVectorNorthObject(statusCode: Int) : ThreeAxesObject(statusCode, LibraryUtil.ROTATION_VECTOR_NORTH_REFERENCE) { init { dataSource = LibraryUtil.PHONE_SOURCE } }
lgpl-3.0
cicakhq/potato
contrib/rqjava/src/com/dhsdevelopments/rqjava/PotatoConnection.kt
1
2414
package com.dhsdevelopments.rqjava import com.google.gson.Gson import com.rabbitmq.client.* import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.nio.charset.Charset import java.util.logging.Level import java.util.logging.Logger class PotatoConnection(val host: String, val virtualHost: String, val username: String, val password: String) { companion object { val SEND_MESSAGE_EXCHANGE_NAME = "chat-image-response-ex" } private var conn: Connection? = null val amqpConn: Connection get() = conn!! fun connect() { val fac = ConnectionFactory() fac.virtualHost = virtualHost fac.username = username fac.password = password fac.host = host conn = fac.newConnection() } fun disconnect() { val connCopy = synchronized(this) { conn.apply { conn = null } } if (connCopy == null) { throw IllegalStateException("Already disconnected") } connCopy.close() } fun subscribeChannel(cid: String, callback: (Message) -> Unit): ChannelSubscription { return ChannelSubscription(this, cid, callback) } fun registerCmd(cmd: String, callback: (Command) -> Unit): CmdRegistration { return CmdRegistration(this, cmd, callback) } fun sendMessage(sender: String, cid: String, text: String, extraHtml: String? = null) { val channel = amqpConn.createChannel() try { val content = StringBuilder() content.append("(:POST (\"") content.append(cid) content.append("\" :SENDER \"") content.append(sender) content.append("\" :TEXT \"") content.append(escapeSexpString(text)) content.append("\"") if(extraHtml != null) { content.append(" :EXTRA-HTML \"") content.append(escapeSexpString(extraHtml)) content.append("\"") } content.append("))") channel.basicPublish(SEND_MESSAGE_EXCHANGE_NAME, cid, null, content.toString().toByteArray(CHARSET_NAME_UTF8)) } finally { channel.close() } } private fun escapeSexpString(text: String) = text.replace("\"", "\\\"") }
apache-2.0
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/ClientAppVersionCollector.kt
1
1576
package com.telenav.osv.data.collector.phonedata.collector import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Handler import com.telenav.osv.data.collector.datatype.datatypes.ClientAppVersionObject import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener import timber.log.Timber /** * Collects the version of the client application */ class ClientAppVersionCollector(phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) { /** * Retrieve the client app name */ fun sendClientVersion(context: Context?) { var pinfo: PackageInfo? = null var clientVersion: String? = null try { if (context != null && context.packageManager != null && context.packageName != null) { pinfo = context.packageManager.getPackageInfo(context.packageName, 0) } if (pinfo != null) { clientVersion = pinfo.versionName } } catch (e: PackageManager.NameNotFoundException) { Timber.tag("ClientVersionCollector").e(e) } if (clientVersion != null && !clientVersion.isEmpty()) { onNewSensorEvent(ClientAppVersionObject(clientVersion, LibraryUtil.PHONE_SENSOR_READ_SUCCESS)) } else { onNewSensorEvent(ClientAppVersionObject(clientVersion, LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE)) } } }
lgpl-3.0
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/service/community/CommunityServicesApi.kt
1
930
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app.health.service.community import ffc.entity.healthcare.CommunityService import retrofit2.Call import retrofit2.http.GET interface CommunityServicesApi { @GET("homehealth") fun getHomeHealthService(): Call<List<CommunityService.ServiceType>> }
apache-2.0
xmementoit/practiseSamples
kotlin/interface/interface.kt
1
568
interface ExampleInterface { var myVar: Int // abstract property fun absMethod():String // abstract method fun hello() { println("Hello there, Welcome to TutorialsPoint.Com!") } } class InterfaceImp : ExampleInterface { override var myVar: Int = 25 override fun absMethod() = "Happy Learning " } fun main(args: Array<String>) { val obj = InterfaceImp() println("My Variable Value is = ${obj.myVar}") print("Calling hello(): ") obj.hello() print("Message from the Website-- ") println(obj.absMethod()) }
apache-2.0
ivaneye/kt-jvm
src/com/ivaneye/ktjvm/model/FieldInfo.kt
1
690
package com.ivaneye.ktjvm.model import com.ivaneye.ktjvm.model.attr.Attribute import com.ivaneye.ktjvm.type.U2 /** * Created by wangyifan on 2017/5/17. */ class FieldInfo(val accFlag: U2, val nameIdx: U2, val descIdx: U2, val attrCount: U2, val attrs: Array<Attribute>, val classInfo: ClassInfo) { override fun toString(): String { var str = "" for(attr in attrs){ str += attr.toString() } return "FieldInfo(accFlag=${accFlag.toHexString()},name=${classInfo.cpInfos[nameIdx.toInt()]!!.value()}," + "desc=${classInfo.cpInfos[descIdx.toInt()]!!.value()},attrCount=${attrCount.toInt() },attrs=[$str])" } }
apache-2.0
slartus/4pdaClient-plus
qms/qms-api/src/main/java/ru/softeg/slartus/qms/api/models/QmsContact.kt
1
237
package ru.softeg.slartus.qms.api.models data class QmsContact( val id: String, val nick: String, val avatarUrl: String?, val newMessagesCount: Int ) class QmsContacts(list: List<QmsContact>) : List<QmsContact> by list
apache-2.0
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/modules/eventbroadcast/LocalEventBroadcaster.kt
1
262
package com.projectcitybuild.modules.eventbroadcast interface LocalEventBroadcaster { /** * Broadcasts an event to all listeners on the current server * * @param event The event to broadcast */ fun emit(event: BroadcastableEvent) }
mit
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/di/NativeModuleDepsProvider.kt
2
3340
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.di import android.app.Application import android.content.Context import android.os.Handler import android.os.Looper import com.facebook.proguard.annotations.DoNotStrip import expo.modules.updates.db.DatabaseHolder import expo.modules.updates.db.UpdatesDatabase import host.exp.exponent.ExpoHandler import host.exp.exponent.ExponentManifest import host.exp.exponent.analytics.EXL import host.exp.exponent.kernel.services.ExpoKernelServiceRegistry import host.exp.exponent.network.ExponentNetwork import host.exp.exponent.storage.ExponentSharedPreferences import java.lang.reflect.Field import javax.inject.Inject class NativeModuleDepsProvider(application: Application) { @Inject @DoNotStrip val mContext: Context = application @Inject @DoNotStrip val mApplicationContext: Application = application @Inject @DoNotStrip val mExpoHandler: ExpoHandler = ExpoHandler(Handler(Looper.getMainLooper())) @Inject @DoNotStrip val mExponentSharedPreferences: ExponentSharedPreferences = ExponentSharedPreferences(mContext) @Inject @DoNotStrip val mExponentNetwork: ExponentNetwork = ExponentNetwork(mContext, mExponentSharedPreferences) @Inject @DoNotStrip var mExponentManifest: ExponentManifest = ExponentManifest(mContext, mExponentSharedPreferences) @Inject @DoNotStrip var mKernelServiceRegistry: ExpoKernelServiceRegistry = ExpoKernelServiceRegistry(mContext, mExponentSharedPreferences) @Inject @DoNotStrip val mUpdatesDatabaseHolder: DatabaseHolder = DatabaseHolder(UpdatesDatabase.getInstance(mContext)) private val classToInstanceMap = mutableMapOf<Class<*>, Any>() fun add(clazz: Class<*>, instance: Any) { classToInstanceMap[clazz] = instance } fun inject(clazz: Class<*>, target: Any) { for (field in clazz.declaredFields) { injectFieldInTarget(target, field) } } private fun injectFieldInTarget(target: Any, field: Field) { if (field.isAnnotationPresent(Inject::class.java)) { val fieldClazz = field.type if (!classToInstanceMap.containsKey(fieldClazz)) { throw RuntimeException("NativeModuleDepsProvider could not find object for class $fieldClazz") } val instance = classToInstanceMap[fieldClazz] try { field.isAccessible = true field[target] = instance } catch (e: IllegalAccessException) { EXL.e(TAG, e.toString()) } } } companion object { private val TAG = NativeModuleDepsProvider::class.java.simpleName @JvmStatic lateinit var instance: NativeModuleDepsProvider private set private var useTestInstance = false fun initialize(application: Application) { if (!useTestInstance) { instance = NativeModuleDepsProvider(application) } } // Only for testing! fun setTestInstance(instance: NativeModuleDepsProvider) { Companion.instance = instance useTestInstance = true } } init { for (field in NativeModuleDepsProvider::class.java.declaredFields) { if (field.isAnnotationPresent(Inject::class.java)) { try { classToInstanceMap[field.type] = field[this] } catch (e: IllegalAccessException) { EXL.e(TAG, e.toString()) } } } } }
bsd-3-clause
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/lock/LockImageView.kt
1
1935
/* * Copyright 2019 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.pyamsoft.padlock.lock import android.os.Bundle import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.pyamsoft.padlock.R import com.pyamsoft.padlock.loader.AppIconLoader import com.pyamsoft.pydroid.arch.BaseUiView import com.pyamsoft.pydroid.loader.Loaded import javax.inject.Inject import javax.inject.Named internal class LockImageView @Inject internal constructor( private val appIconImageLoader: AppIconLoader, @Named("locked_package_name") private val packageName: String, @Named("locked_app_icon") private val icon: Int, parent: ViewGroup ) : BaseUiView<Unit>(parent, Unit) { private val lockedIcon by lazyView<ImageView>(R.id.lock_image_icon) private var imageBinder: Loaded? = null override val layout: Int = R.layout.layout_lock_image override val layoutRoot by lazyView<ViewGroup>(R.id.lock_image_root) override fun onInflated( view: View, savedInstanceState: Bundle? ) { super.onInflated(view, savedInstanceState) loadAppIcon() } private fun clearBinder() { imageBinder?.dispose() imageBinder = null } private fun loadAppIcon() { clearBinder() imageBinder = appIconImageLoader.loadAppIcon(packageName, icon) .into(lockedIcon) } override fun onTeardown() { clearBinder() } }
apache-2.0