content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.aglushkov.modelcore.extensions import android.app.Application import androidx.lifecycle.AndroidViewModel fun AndroidViewModel.getString(res: Int) = getApplication<Application>().getString(res)
modelcore/src/main/java/com/aglushkov/modelcore/extensions/AndroidViewModel.kt
1719651050
package com.adrianfaciu.teamcity.flowdockPlugin.notifications /** * Who created the notification * Email will be used to fetch image from Gravatar */ data class NotificationAuthor(val name: String?, val avatar: String?, val email: String?)
flowdock-teamcity-plugin-server/src/main/kotlin/com/adrianfaciu/teamcity/flowdockPlugin/notifications/NotificationAuthor.kt
3342840025
package com.braintreepayments.api import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertFalse import org.json.JSONException import org.json.JSONObject import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class UnionPayCardUnitTest { @Test fun getApiPath_returnsExpected() { assertEquals("credit_cards", UnionPayCard().apiPath) } @Test @Throws(JSONException::class) fun cardNumber_addsToJson() { val sut = UnionPayCard() sut.number = "myCardNumber" assertEquals("myCardNumber", sut.buildEnrollment() .getJSONObject("unionPayEnrollment") .getString("number")) } @Test @Throws(JSONException::class) fun expirationMonth_addsToJson() { val sut = UnionPayCard() sut.expirationMonth = "12" assertEquals("12", sut.buildEnrollment() .getJSONObject("unionPayEnrollment") .getString("expirationMonth")) } @Test @Throws(JSONException::class) fun expirationYear_addsToJson() { val sut = UnionPayCard() sut.expirationYear = "2020" assertEquals("2020", sut.buildEnrollment() .getJSONObject("unionPayEnrollment") .getString("expirationYear")) } @Test @Throws(JSONException::class) fun expirationDate_addsToJsonAsExpirationMonthAndExpirationYear() { val sut = UnionPayCard() sut.expirationDate = "12/2020" val enrollment = sut.buildEnrollment().getJSONObject("unionPayEnrollment") assertEquals("12", enrollment.getString("expirationMonth")) assertEquals("2020", enrollment.getString("expirationYear")) } @Test @Throws(JSONException::class) fun mobileCountryCode_addsToJson() { val sut = UnionPayCard() sut.mobileCountryCode = "1" assertEquals("1", sut.buildEnrollment() .getJSONObject("unionPayEnrollment") .getString("mobileCountryCode")) } @Test @Throws(JSONException::class) fun mobilePhoneNumber_addsToJson() { val sut = UnionPayCard() sut.mobilePhoneNumber = "867-5309" assertEquals("867-5309", sut.buildEnrollment() .getJSONObject("unionPayEnrollment") .getString("mobileNumber")) } @Test @Throws(JSONException::class) fun smsCode_addsToOptionsJson() { val sut = UnionPayCard() sut.smsCode = "mySmsCode" val jsonObject = sut.buildJSON() assertEquals("mySmsCode", jsonObject.getJSONObject("creditCard") .getJSONObject("options") .getJSONObject("unionPayEnrollment") .getString("smsCode")) } @Test @Throws(JSONException::class) fun enrollmentId_addsToOptionsJson() { val sut = UnionPayCard() sut.enrollmentId = "myEnrollmentId" val jsonObject = sut.buildJSON() assertEquals("myEnrollmentId", jsonObject.getJSONObject("creditCard") .getJSONObject("options") .getJSONObject("unionPayEnrollment") .getString("id")) } @Test @Throws(JSONException::class) fun doesNotIncludeEmptyStrings() { val sut = UnionPayCard() sut.number = "" sut.expirationDate = "" sut.expirationMonth = "" sut.expirationYear = "" sut.cvv = "" sut.postalCode = "" sut.cardholderName = "" sut.firstName = "" sut.lastName = "" sut.streetAddress = "" sut.locality = "" sut.postalCode = "" sut.region = "" sut.enrollmentId = "" sut.mobileCountryCode = "" sut.mobilePhoneNumber = "" sut.smsCode = "" val json = sut.buildJSON() assertEquals("{\"options\":{\"unionPayEnrollment\":{}}}", json.getJSONObject(BaseCard.CREDIT_CARD_KEY).toString()) assertFalse(json.has(BaseCard.BILLING_ADDRESS_KEY)) } @Test @Throws(JSONException::class) fun buildEnrollment_createsUnionPayEnrollmentJson() { val sut = UnionPayCard() sut.cvv = "123" sut.enrollmentId = "enrollment-id" sut.expirationYear = "expiration-year" sut.expirationMonth = "expiration-month" sut.number = "card-number" sut.mobileCountryCode = "mobile-country-code" sut.mobilePhoneNumber = "mobile-phone-number" sut.smsCode = "sms-code" sut.setIntegration("integration") sut.setSessionId("session-id") sut.setSource("source") val unionPayEnrollment = sut.buildEnrollment().getJSONObject("unionPayEnrollment") assertEquals("card-number", unionPayEnrollment.getString("number")) assertEquals("expiration-month", unionPayEnrollment.getString("expirationMonth")) assertEquals("expiration-year", unionPayEnrollment.getString("expirationYear")) assertEquals("mobile-country-code", unionPayEnrollment.getString("mobileCountryCode")) assertEquals("mobile-phone-number", unionPayEnrollment.getString("mobileNumber")) } @Test @Throws(JSONException::class) fun build_createsUnionPayTokenizeJson() { val sut = UnionPayCard() sut.cvv = "123" sut.enrollmentId = "enrollment-id" sut.expirationYear = "expiration-year" sut.expirationMonth = "expiration-month" sut.number = "card-number" sut.mobileCountryCode = "mobile-country-code" sut.mobilePhoneNumber = "mobile-phone-number" sut.smsCode = "sms-code" sut.setIntegration("integration") sut.setSessionId("session-id") sut.setSource("source") val tokenizePayload = sut.buildJSON() val creditCard = tokenizePayload.getJSONObject("creditCard") assertEquals("card-number", creditCard.getString("number")) assertEquals("expiration-month", creditCard.getString("expirationMonth")) assertEquals("expiration-year", creditCard.getString("expirationYear")) assertEquals("123", creditCard.getString("cvv")) val options = creditCard.getJSONObject("options") val unionPayEnrollment = options.getJSONObject("unionPayEnrollment") assertEquals("enrollment-id", unionPayEnrollment.getString("id")) assertEquals("sms-code", unionPayEnrollment.getString("smsCode")) } @Test @Throws(JSONException::class) fun build_doesNotIncludeValidate() { val unionPayCard = UnionPayCard() val unionPayOptions = unionPayCard.buildJSON() .getJSONObject("creditCard") .getJSONObject("options") assertFalse(unionPayOptions.has("validate")) } @Test @Throws(JSONException::class) fun build_standardPayload() { val sut = UnionPayCard() sut.number = "someCardNumber" sut.expirationMonth = "expirationMonth" sut.expirationYear = "expirationYear" sut.cvv = "cvv" sut.enrollmentId = "enrollmentId" sut.smsCode = "smsCode" val tokenizePayload = sut.buildJSON() val creditCardPayload = tokenizePayload.getJSONObject("creditCard") val optionsPayload = creditCardPayload.getJSONObject("options") val unionPayEnrollmentPayload = optionsPayload.getJSONObject("unionPayEnrollment") assertEquals("someCardNumber", creditCardPayload.getString("number")) assertEquals("expirationMonth", creditCardPayload.getString("expirationMonth")) assertEquals("expirationYear", creditCardPayload.getString("expirationYear")) assertEquals("cvv", creditCardPayload.getString("cvv")) assertFalse(optionsPayload.has("validate")) assertEquals("enrollmentId", unionPayEnrollmentPayload.getString("id")) assertEquals("smsCode", unionPayEnrollmentPayload.getString("smsCode")) } @Test @Throws(JSONException::class) fun build_optionalSmsCode() { val sut = UnionPayCard() sut.number = "someCardNumber" sut.expirationMonth = "expirationMonth" sut.expirationYear = "expirationYear" sut.cvv = "cvv" sut.enrollmentId = "enrollmentId" val tokenizePayload = sut.buildJSON() val creditCardPayload = tokenizePayload.getJSONObject("creditCard") val optionsPayload = creditCardPayload.getJSONObject("options") val unionPayEnrollmentPayload = optionsPayload.getJSONObject("unionPayEnrollment") assertEquals("someCardNumber", creditCardPayload.getString("number")) assertEquals("expirationMonth", creditCardPayload.getString("expirationMonth")) assertEquals("expirationYear", creditCardPayload.getString("expirationYear")) assertEquals("cvv", creditCardPayload.getString("cvv")) assertFalse(optionsPayload.has("validate")) assertEquals("enrollmentId", unionPayEnrollmentPayload.getString("id")) assertFalse(unionPayEnrollmentPayload.has("smsCode")) } @Test @Throws(JSONException::class) fun build_doesNotIncludeCvv() { val sut = UnionPayCard() sut.number= "some-card-number" sut.cvv = "123" val unionPayEnrollmentPayload = sut.buildJSON() assertFalse(unionPayEnrollmentPayload.has("cvv")) } @Test @Throws(JSONException::class) fun buildEnrollment_basicPayload() { val sut = UnionPayCard() sut.number = "someCardNumber" sut.expirationMonth = "expirationMonth" sut.expirationYear = "expirationYear" sut.mobileCountryCode = "mobileCountryCode" sut.mobilePhoneNumber = "mobilePhoneNumber" val result = JSONObject(sut.buildEnrollment().toString()) val unionPayEnrollment = result.getJSONObject("unionPayEnrollment") assertEquals("someCardNumber", unionPayEnrollment.getString("number")) assertEquals("expirationMonth", unionPayEnrollment.getString("expirationMonth")) assertEquals("expirationYear", unionPayEnrollment.getString("expirationYear")) assertEquals("mobileCountryCode", unionPayEnrollment.getString("mobileCountryCode")) assertEquals("mobilePhoneNumber", unionPayEnrollment.getString("mobileNumber")) } }
UnionPay/src/test/java/com/braintreepayments/api/UnionPayCardUnitTest.kt
3635730420
package ch.bailu.aat_gtk.view.search import ch.bailu.aat_gtk.app.GtkAppContext import ch.bailu.aat_lib.lib.filter_list.FilterList import ch.bailu.aat_lib.lib.filter_list.FilterListUtil import ch.bailu.aat_lib.preferences.SolidPoiDatabase import ch.bailu.aat_lib.search.poi.PoiListItem import ch.bailu.foc.Foc import ch.bailu.gtk.GTK import ch.bailu.gtk.bridge.ListIndex import ch.bailu.gtk.gtk.ListItem import ch.bailu.gtk.gtk.ListView import ch.bailu.gtk.gtk.ScrolledWindow import ch.bailu.gtk.gtk.SignalListItemFactory import org.mapsforge.poi.storage.PoiCategory class PoiList( private val sdatabase: SolidPoiDatabase, private val selected: Foc, private val onSelected: (model: PoiListItem) -> Unit ) { private val listIndex = ListIndex() private val filterList = FilterList() private val items = HashMap<ListItem, PoiListItemView>() private val list = ListView(listIndex.inSelectionModel(), SignalListItemFactory().apply { onSetup { items[it] = PoiListItemView(it) } onBind { val view = items[it] if (view is PoiListItemView) { val model = filterList.getFromVisible(it.position) if (model is PoiListItem) { view.set(model) } } } onTeardown { val view = items.remove(it) if (view is PoiListItemView) { view.onTeardown() } } }).apply { onActivate { val model = filterList.getFromVisible(it) if (model is PoiListItem) { onSelected(model) } } } val scrolled = ScrolledWindow().apply { child = list hexpand = GTK.TRUE vexpand = GTK.TRUE } init { readList() } private fun readList() { FilterListUtil.readList(filterList, GtkAppContext, sdatabase.valueAsString, selected) listIndex.size = filterList.sizeVisible() } fun updateList() { filterList.filterAll() listIndex.size = filterList.sizeVisible() } fun updateList(text: String) { filterList.filter(text) listIndex.size = filterList.sizeVisible() } fun getSelectedCategories(): ArrayList<PoiCategory> { val export = ArrayList<PoiCategory>(10) for (i in 0 until filterList.sizeVisible()) { val e = filterList.getFromVisible(i) as PoiListItem if (e.isSelected) { export.add(e.category) } } return export } }
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/search/PoiList.kt
3226275087
/* * Nextcloud Android client application * * @author TSI-mc * Copyright (C) 2022 TSI-mc * Copyright (C) 2022 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.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.nextcloud.client.di.Injectable import com.owncloud.android.databinding.FragmentGalleryBottomSheetBinding import com.owncloud.android.utils.theme.ViewThemeUtils import javax.inject.Inject class GalleryFragmentBottomSheetDialog( private val actions: GalleryFragmentBottomSheetActions ) : BottomSheetDialogFragment(), Injectable { @Inject lateinit var viewThemeUtils: ViewThemeUtils private lateinit var binding: FragmentGalleryBottomSheetBinding private lateinit var mBottomBehavior: BottomSheetBehavior<*> private var currentMediaState: MediaState = MediaState.MEDIA_STATE_DEFAULT override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentGalleryBottomSheetBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupLayout() setupClickListener() mBottomBehavior = BottomSheetBehavior.from(binding.root.parent as View) } public override fun onStart() { super.onStart() mBottomBehavior.state = BottomSheetBehavior.STATE_EXPANDED } fun setupLayout() { listOf( binding.tickMarkShowImages, binding.tickMarkShowVideo, binding.hideImagesImageview, binding.hideVideoImageView, binding.selectMediaFolderImageView ).forEach { viewThemeUtils.platform.colorImageView(it) } when (currentMediaState) { MediaState.MEDIA_STATE_PHOTOS_ONLY -> { binding.tickMarkShowImages.visibility = View.VISIBLE binding.tickMarkShowVideo.visibility = View.GONE } MediaState.MEDIA_STATE_VIDEOS_ONLY -> { binding.tickMarkShowImages.visibility = View.GONE binding.tickMarkShowVideo.visibility = View.VISIBLE } else -> { binding.tickMarkShowImages.visibility = View.VISIBLE binding.tickMarkShowVideo.visibility = View.VISIBLE } } } private fun setupClickListener() { binding.hideImages.setOnClickListener { v: View? -> currentMediaState = if (currentMediaState == MediaState.MEDIA_STATE_VIDEOS_ONLY) { MediaState.MEDIA_STATE_DEFAULT } else { MediaState.MEDIA_STATE_VIDEOS_ONLY } notifyStateChange() dismiss() } binding.hideVideo.setOnClickListener { v: View? -> currentMediaState = if (currentMediaState == MediaState.MEDIA_STATE_PHOTOS_ONLY) { MediaState.MEDIA_STATE_DEFAULT } else { MediaState.MEDIA_STATE_PHOTOS_ONLY } notifyStateChange() dismiss() } binding.selectMediaFolder.setOnClickListener { v: View? -> actions.selectMediaFolder() dismiss() } } private fun notifyStateChange() { setupLayout() actions.updateMediaContent(currentMediaState) } val currMediaState: MediaState get() = currentMediaState enum class MediaState { MEDIA_STATE_DEFAULT, MEDIA_STATE_PHOTOS_ONLY, MEDIA_STATE_VIDEOS_ONLY } }
app/src/main/java/com/owncloud/android/ui/fragment/GalleryFragmentBottomSheetDialog.kt
2624589342
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.insight import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.codeInspection.reference.RefElement import com.intellij.codeInspection.visibility.EntryPointWithVisibilityLevel import com.intellij.psi.PsiElement import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiUtil import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element class MixinEntryPoint : EntryPointWithVisibilityLevel() { @JvmField var MIXIN_ENTRY_POINT = true override fun getId() = "mixin" override fun getDisplayName() = "Mixin injectors" override fun getTitle() = "Suggest private visibility level for Mixin injectors" override fun getIgnoreAnnotations() = MixinConstants.Annotations.ENTRY_POINTS override fun isEntryPoint(element: PsiElement): Boolean { val modifierList = (element as? PsiMethod)?.modifierList ?: return false return MixinConstants.Annotations.ENTRY_POINTS.any { modifierList.findAnnotation(it) != null } } override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement) override fun getMinVisibilityLevel(member: PsiMember): Int { if (member !is PsiMethod) return -1 val modifierList = member.modifierList return if (MixinConstants.Annotations.METHOD_INJECTORS.any { modifierList.findAnnotation(it) != null }) { PsiUtil.ACCESS_LEVEL_PRIVATE } else { -1 } } override fun isSelected() = MIXIN_ENTRY_POINT override fun setSelected(selected: Boolean) { MIXIN_ENTRY_POINT = selected } override fun readExternal(element: Element) = XmlSerializer.serializeInto(this, element) override fun writeExternal(element: Element) = XmlSerializer.serializeInto(this, element) }
src/main/kotlin/platform/mixin/insight/MixinEntryPoint.kt
4130275291
package com.emogoth.android.phone.mimi.widget import android.content.Context import android.util.Log import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import java.lang.Exception class WrappedLinearLayoutManager(context: Context?, orientation: Int, reverseLayout: Boolean) : LinearLayoutManager(context, orientation, reverseLayout) { companion object { var LOG_TAG = WrappedLinearLayoutManager::class.java.simpleName } override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) { try { super.onLayoutChildren(recycler, state) } catch (e: IndexOutOfBoundsException) { Log.e(LOG_TAG, "Caught IndexOutOfBoundsException in LinearLayoutManager", e) } } } class WrappedGridLayoutManager(context: Context?, spanCount: Int) : GridLayoutManager(context, spanCount) { companion object { var LOG_TAG = WrappedGridLayoutManager::class.java.simpleName } override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) { try { super.onLayoutChildren(recycler, state) } catch (e: IndexOutOfBoundsException) { Log.e(LOG_TAG, "Caught IndexOutOfBoundsException in GridLayoutManager", e) } } } class WrappedStaggeredGridLayoutManager(spanCount: Int, orientation: Int) : StaggeredGridLayoutManager(spanCount, orientation) { companion object { var LOG_TAG = WrappedStaggeredGridLayoutManager::class.java.simpleName } override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) { try { super.onLayoutChildren(recycler, state) } catch (e: IndexOutOfBoundsException) { Log.e(LOG_TAG, "Caught IndexOutOfBoundsException in StaggeredGridLayoutManager", e) } } }
mimi-app/src/main/java/com/emogoth/android/phone/mimi/widget/WrappedLayoutManager.kt
3404405177
/** * The MIT License (MIT) * * Copyright (c) 2012-2018 DragonBones team and other contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.dragonbones.animation import com.dragonbones.armature.* import com.dragonbones.core.* import com.dragonbones.event.* import com.dragonbones.model.* import com.soywiz.kmem.* import kotlin.math.* /** * @internal */ class ActionTimelineState(pool: SingleObjectPool<ActionTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.ActionTimelineState]" } private fun _onCrossFrame(frameIndex: Int) { val eventDispatcher = this._armature!!.eventDispatcher if (this._animationState!!.actionEnabled) { val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![(this._timelineData!!).offset + BinaryOffset.TimelineFrameOffset + frameIndex].toInt() val actionCount = this._frameArray!![frameOffset + 1].toInt() val actions = this._animationData!!.parent!!.actions // May be the animaton data not belong to this armature data. //for (var i = 0; i < actionCount; ++i) { for (i in 0 until actionCount) { val actionIndex = this._frameArray!![frameOffset + 2 + i].toInt() val action = actions[actionIndex] if (action.type == ActionType.Play) { val eventObject = pool.eventObject.borrow() // eventObject.time = this._frameArray[frameOffset] * this._frameRateR; // Precision problem eventObject.time = this._frameArray!![frameOffset].toDouble() / this._frameRate eventObject.animationState = this._animationState!! EventObject.actionDataToInstance(action, eventObject, this._armature!!) this._armature!!._bufferAction(eventObject, true) } else { val eventType = if (action.type == ActionType.Frame) EventObject.FRAME_EVENT else EventObject.SOUND_EVENT if (action.type == ActionType.Sound || eventDispatcher.hasDBEventListener(eventType)) { val eventObject = pool.eventObject.borrow() // eventObject.time = this._frameArray[frameOffset] * this._frameRateR; // Precision problem eventObject.time = this._frameArray!![frameOffset].toDouble() / this._frameRate eventObject.animationState = this._animationState!! EventObject.actionDataToInstance(action, eventObject, this._armature!!) this._armature?.eventDispatcher?.queueEvent(eventObject) } } } } } override fun _onArriveAtFrame() {} override fun _onUpdateFrame() {} override fun update(passedTime: Double) { val prevState = this.playState var prevPlayTimes = this.currentPlayTimes val prevTime = this._currentTime if (this._setCurrentTime(passedTime)) { val eventActive = this._animationState?._parent == null && this._animationState!!.actionEnabled val eventDispatcher = this._armature?.eventDispatcher if (prevState < 0) { if (this.playState != prevState) { if (this._animationState!!.displayControl && this._animationState!!.resetToPose) { // Reset zorder to pose. this._armature?._sortZOrder(null, 0) } prevPlayTimes = this.currentPlayTimes if (eventActive && eventDispatcher!!.hasDBEventListener(EventObject.START)) { val eventObject = pool.eventObject.borrow() eventObject.type = EventObject.START eventObject.armature = this._armature!! eventObject.animationState = this._animationState!! this._armature?.eventDispatcher?.queueEvent(eventObject) } } else { return } } val isReverse = this._animationState!!.timeScale < 0.0 var loopCompleteEvent: EventObject? = null var completeEvent: EventObject? = null if (eventActive && this.currentPlayTimes != prevPlayTimes) { if (eventDispatcher!!.hasDBEventListener(EventObject.LOOP_COMPLETE)) { loopCompleteEvent = pool.eventObject.borrow() loopCompleteEvent.type = EventObject.LOOP_COMPLETE loopCompleteEvent.armature = this._armature!! loopCompleteEvent.animationState = this._animationState!! } if (this.playState > 0) { if (eventDispatcher.hasDBEventListener(EventObject.COMPLETE)) { completeEvent = pool.eventObject.borrow() completeEvent.type = EventObject.COMPLETE completeEvent.armature = this._armature!! completeEvent.animationState = this._animationState!! } } } if (this._frameCount > 1) { val timelineData = this._timelineData as TimelineData val timelineFrameIndex = floor(this._currentTime * this._frameRate).toInt() // uint val frameIndex = this._frameIndices!![timelineData.frameIndicesOffset + timelineFrameIndex] if (this._frameIndex != frameIndex) { // Arrive at frame. var crossedFrameIndex = this._frameIndex this._frameIndex = frameIndex if (this._timelineArray != null) { this._frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + this._frameIndex].toInt() if (isReverse) { if (crossedFrameIndex < 0) { val prevFrameIndex = floor(prevTime * this._frameRate).toInt() crossedFrameIndex = this._frameIndices!![timelineData.frameIndicesOffset + prevFrameIndex] if (this.currentPlayTimes == prevPlayTimes) { // Start. if (crossedFrameIndex == frameIndex) { // Uncrossed. crossedFrameIndex = -1 } } } while (crossedFrameIndex >= 0) { val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset] / this._frameRate if ( this._position <= framePosition && framePosition <= this._position + this._duration ) { // Support interval play. this._onCrossFrame(crossedFrameIndex) } if (loopCompleteEvent != null && crossedFrameIndex == 0) { // Add loop complete event after first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } if (crossedFrameIndex > 0) { crossedFrameIndex-- } else { crossedFrameIndex = this._frameCount - 1 } if (crossedFrameIndex == frameIndex) { break } } } else { if (crossedFrameIndex < 0) { val prevFrameIndex = floor(prevTime * this._frameRate).toInt() crossedFrameIndex = this._frameIndices!![timelineData.frameIndicesOffset + prevFrameIndex] val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset].toDouble() / this._frameRate if (this.currentPlayTimes == prevPlayTimes) { // Start. if (prevTime <= framePosition) { // Crossed. if (crossedFrameIndex > 0) { crossedFrameIndex-- } else { crossedFrameIndex = this._frameCount - 1 } } else if (crossedFrameIndex == frameIndex) { // Uncrossed. crossedFrameIndex = -1 } } } while (crossedFrameIndex >= 0) { if (crossedFrameIndex < this._frameCount - 1) { crossedFrameIndex++ } else { crossedFrameIndex = 0 } val frameOffset = this._animationData!!.frameOffset + this._timelineArray!![timelineData.offset + BinaryOffset.TimelineFrameOffset + crossedFrameIndex].toInt() // val framePosition = this._frameArray[frameOffset] * this._frameRateR; // Precision problem val framePosition = this._frameArray!![frameOffset].toDouble() / this._frameRate if ( this._position <= framePosition && framePosition <= this._position + this._duration // ) { // Support interval play. this._onCrossFrame(crossedFrameIndex) } if (loopCompleteEvent != null && crossedFrameIndex == 0) { // Add loop complete event before first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } if (crossedFrameIndex == frameIndex) { break } } } } } } else if (this._frameIndex < 0) { this._frameIndex = 0 if (this._timelineData != null) { this._frameOffset = this._animationData!!.frameOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameOffset].toInt() // Arrive at frame. val framePosition = this._frameArray!![this._frameOffset].toDouble() / this._frameRate if (this.currentPlayTimes == prevPlayTimes) { // Start. if (prevTime <= framePosition) { this._onCrossFrame(this._frameIndex) } } else if (this._position <= framePosition) { // Loop complete. if (!isReverse && loopCompleteEvent != null) { // Add loop complete event before first frame. this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) loopCompleteEvent = null } this._onCrossFrame(this._frameIndex) } } } if (loopCompleteEvent != null) { this._armature?.eventDispatcher?.queueEvent(loopCompleteEvent) } if (completeEvent != null) { this._armature?.eventDispatcher?.queueEvent(completeEvent) } } } fun setCurrentTime(value: Double) { this._setCurrentTime(value) this._frameIndex = -1 } } /** * @internal */ class ZOrderTimelineState(pool: SingleObjectPool<ZOrderTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.ZOrderTimelineState]" } override fun _onArriveAtFrame() { if (this.playState >= 0) { val count = this._frameArray!![this._frameOffset + 1].toInt() if (count > 0) { this._armature?._sortZOrder(this._frameArray!!, this._frameOffset + 2) } else { this._armature?._sortZOrder(null, 0) } } } override fun _onUpdateFrame() {} } /** * @internal */ class BoneAllTimelineState(pool: SingleObjectPool<BoneAllTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneAllTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._isTween && this._frameIndex == this._frameCount - 1) { this._rd[2] = TransformDb.normalizeRadian(this._rd[2]) this._rd[3] = TransformDb.normalizeRadian(this._rd[3]) } if (this._timelineData == null) { // Pose. this._rd[4] = 1.0 this._rd[5] = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = 6 this._valueArray = this._animationData?.parent?.parent?.frameFloatArray!! } override fun fadeOut() { this.dirty = false this._rd[2] = TransformDb.normalizeRadian(this._rd[2]) this._rd[3] = TransformDb.normalizeRadian(this._rd[3]) } override fun blend(_isDirty: Boolean) { val valueScale = this._armature!!.armatureData.scale val rd = this._rd // val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose if (blendState.dirty > 1) { result.xf += (rd[0] * blendWeight * valueScale).toFloat() result.yf += (rd[1] * blendWeight * valueScale).toFloat() result.rotation += (rd[2] * blendWeight).toFloat() result.skew += (rd[3] * blendWeight).toFloat() result.scaleX += ((rd[4] - 1.0) * blendWeight).toFloat() result.scaleY += ((rd[5] - 1.0) * blendWeight).toFloat() } else { result.xf = (rd[0] * blendWeight * valueScale).toFloat() result.yf = (rd[1] * blendWeight * valueScale).toFloat() result.rotation = (rd[2] * blendWeight).toFloat() result.skew = (rd[3] * blendWeight).toFloat() result.scaleX = ((rd[4] - 1.0) * blendWeight + 1.0).toFloat() // result.scaleY = ((rd[5] - 1.0) * blendWeight + 1.0).toFloat() // } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneTranslateTimelineState(pool: SingleObjectPool<BoneTranslateTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneTranslateTimelineState]" } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.xf += (this._resultA * blendWeight).toFloat() result.yf += (this._resultB * blendWeight).toFloat() } blendWeight != 1.0 -> { result.xf = (this._resultA * blendWeight).toFloat() result.yf = (this._resultB * blendWeight).toFloat() } else -> { result.xf = this._resultA.toFloat() result.yf = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneRotateTimelineState(pool: SingleObjectPool<BoneRotateTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneRotateTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._isTween && this._frameIndex == this._frameCount - 1) { this._differenceA = TransformDb.normalizeRadian(this._differenceA) this._differenceB = TransformDb.normalizeRadian(this._differenceB) } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun fadeOut() { this.dirty = false this._resultA = TransformDb.normalizeRadian(this._resultA) this._resultB = TransformDb.normalizeRadian(this._resultB) } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.rotation += (this._resultA * blendWeight).toFloat() result.skew += (this._resultB * blendWeight).toFloat() } blendWeight != 1.0 -> { result.rotation = (this._resultA * blendWeight).toFloat() result.skew = (this._resultB * blendWeight).toFloat() } else -> { result.rotation = this._resultA.toFloat() result.skew = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class BoneScaleTimelineState(pool: SingleObjectPool<BoneScaleTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.BoneScaleTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. this._resultA = 1.0 this._resultB = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameFloatOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameFloatArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val bone = blendState.targetBone!! val blendWeight = blendState.blendWeight val result = bone.animationPose when { blendState.dirty > 1 -> { result.scaleX += ((this._resultA - 1.0) * blendWeight).toFloat() result.scaleY += ((this._resultB - 1.0) * blendWeight).toFloat() } blendWeight != 1.0 -> { result.scaleX = ((this._resultA - 1.0) * blendWeight + 1.0).toFloat() result.scaleY = ((this._resultB - 1.0) * blendWeight + 1.0).toFloat() } else -> { result.scaleX = this._resultA.toFloat() result.scaleY = this._resultB.toFloat() } } if (_isDirty || this.dirty) { this.dirty = false bone._transformDirty = true } } } /** * @internal */ class SurfaceTimelineState(pool: SingleObjectPool<SurfaceTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SurfaceTimelineState]" } private var _deformCount: Int = 0 private var _deformOffset: Int = 0 private var _sameValueOffset: Int = 0 override fun _onClear() { super._onClear() this._deformCount = 0 this._deformOffset = 0 this._sameValueOffset = 0 } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) if (this._timelineData != null) { val dragonBonesData = this._animationData!!.parent!!.parent val frameIntArray = dragonBonesData!!.frameIntArray!! val frameIntOffset = this._animationData!!.frameIntOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameValueCount].toInt() this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount].toInt() this._deformCount = frameIntArray[frameIntOffset + BinaryOffset.DeformCount].toInt() this._deformOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset].toInt() this._sameValueOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset].toInt() + this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = dragonBonesData.frameFloatArray!! this._rd = DoubleArray(this._valueCount * 2) } else { this._deformCount = ((this.targetBlendState)!!.targetSurface)!!._deformVertices.size } } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val surface = blendState.targetSurface ?: error("blendState.targetSurface=null: target=${blendState.targetCommon}") val blendWeight = blendState.blendWeight val result = surface._deformVertices val valueArray = this._valueArray if (valueArray != null) { val valueCount = this._valueCount val deformOffset = this._deformOffset val sameValueOffset = this._sameValueOffset val rd = this._rd for (i in 0 until this._deformCount) { var value: Double value = if (i < deformOffset) { valueArray[sameValueOffset + i].toDouble() } else if (i < deformOffset + valueCount) { rd[i - deformOffset] } else { valueArray[sameValueOffset + i - valueCount].toDouble() } if (blendState.dirty > 1) { result[i] += (value * blendWeight).toFloat() } else { result[i] = (value * blendWeight).toFloat() } } } else if (blendState.dirty == 1) { for (i in 0 until this._deformCount) { result[i] = 0f } } if (_isDirty || this.dirty) { this.dirty = false surface._transformDirty = true } } } /** * @internal */ class AlphaTimelineState(pool: SingleObjectPool<AlphaTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AlphaTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. this._result = 1.0 } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.01 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val alphaTarget = blendState.targetTransformObject!! val blendWeight = blendState.blendWeight if (blendState.dirty > 1) { alphaTarget._alpha += this._result * blendWeight if (alphaTarget._alpha > 1.0) { alphaTarget._alpha = 1.0 } } else { alphaTarget._alpha = this._result * blendWeight } if (_isDirty || this.dirty) { this.dirty = false this._armature?._alphaDirty = true } } } /** * @internal */ class SlotDisplayTimelineState(pool: SingleObjectPool<SlotDisplayTimelineState>) : TimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotDisplayTimelineState]" } override fun _onArriveAtFrame() { if (this.playState >= 0) { val slot = this.targetSlot!! val displayIndex: Int = if (this._timelineData != null) this._frameArray!![this._frameOffset + 1].toInt() else slot._slotData!!.displayIndex if (slot.displayIndex != displayIndex) { slot._setDisplayIndex(displayIndex, true) } } } override fun _onUpdateFrame() { } } /** * @internal */ class SlotColorTimelineState(pool: SingleObjectPool<SlotColorTimelineState>) : TweenTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotColorTimelineState]" } private val _current: IntArray = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0) private val _difference: IntArray = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0) private val _result: DoubleArray = doubleArrayOf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) @Suppress("UNUSED_CHANGED_VALUE") override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData != null) { val dragonBonesData = this._animationData!!.parent!!.parent val colorArray = dragonBonesData!!.colorArray!! val frameIntArray = dragonBonesData.frameIntArray!! val valueOffset = this._animationData!!.frameIntOffset + this._frameValueOffset + this._frameIndex var colorOffset = frameIntArray[valueOffset].toInt() if (colorOffset < 0) { colorOffset += 65536 // Fixed out of bounds bug. } if (this._isTween) { this._current[0] = colorArray[colorOffset++].toInt() this._current[1] = colorArray[colorOffset++].toInt() this._current[2] = colorArray[colorOffset++].toInt() this._current[3] = colorArray[colorOffset++].toInt() this._current[4] = colorArray[colorOffset++].toInt() this._current[5] = colorArray[colorOffset++].toInt() this._current[6] = colorArray[colorOffset++].toInt() this._current[7] = colorArray[colorOffset++].toInt() colorOffset = if (this._frameIndex == this._frameCount - 1) { frameIntArray[this._animationData!!.frameIntOffset + this._frameValueOffset].toInt() } else { frameIntArray[valueOffset + 1].toInt() } if (colorOffset < 0) { colorOffset += 65536 // Fixed out of bounds bug. } this._difference[0] = colorArray[colorOffset++] - this._current[0] this._difference[1] = colorArray[colorOffset++] - this._current[1] this._difference[2] = colorArray[colorOffset++] - this._current[2] this._difference[3] = colorArray[colorOffset++] - this._current[3] this._difference[4] = colorArray[colorOffset++] - this._current[4] this._difference[5] = colorArray[colorOffset++] - this._current[5] this._difference[6] = colorArray[colorOffset++] - this._current[6] this._difference[7] = colorArray[colorOffset++] - this._current[7] } else { this._result[0] = colorArray[colorOffset++] * 0.01 this._result[1] = colorArray[colorOffset++] * 0.01 this._result[2] = colorArray[colorOffset++] * 0.01 this._result[3] = colorArray[colorOffset++] * 0.01 this._result[4] = colorArray[colorOffset++].toDouble() this._result[5] = colorArray[colorOffset++].toDouble() this._result[6] = colorArray[colorOffset++].toDouble() this._result[7] = colorArray[colorOffset++].toDouble() } } else { // Pose. val slot = this.targetSlot!! val color = slot.slotData.color!! this._result[0] = color.alphaMultiplier this._result[1] = color.redMultiplier this._result[2] = color.greenMultiplier this._result[3] = color.blueMultiplier this._result[4] = color.alphaOffset.toDouble() this._result[5] = color.redOffset.toDouble() this._result[6] = color.greenOffset.toDouble() this._result[7] = color.blueOffset.toDouble() } } override fun _onUpdateFrame() { super._onUpdateFrame() if (this._isTween) { this._result[0] = (this._current[0] + this._difference[0] * this._tweenProgress) * 0.01 this._result[1] = (this._current[1] + this._difference[1] * this._tweenProgress) * 0.01 this._result[2] = (this._current[2] + this._difference[2] * this._tweenProgress) * 0.01 this._result[3] = (this._current[3] + this._difference[3] * this._tweenProgress) * 0.01 this._result[4] = this._current[4] + this._difference[4] * this._tweenProgress this._result[5] = this._current[5] + this._difference[5] * this._tweenProgress this._result[6] = this._current[6] + this._difference[6] * this._tweenProgress this._result[7] = this._current[7] + this._difference[7] * this._tweenProgress } } override fun fadeOut() { this._isTween = false } override fun update(passedTime: Double) { super.update(passedTime) // Fade animation. if (this._isTween || this.dirty) { val slot = this.targetSlot!! val result = slot._colorTransform if (this._animationState!!._fadeState != 0 || this._animationState!!._subFadeState != 0) { if ( result.alphaMultiplier != this._result[0] || result.redMultiplier != this._result[1] || result.greenMultiplier != this._result[2] || result.blueMultiplier != this._result[3] || result.alphaOffset != this._result[4].toInt() || result.redOffset != this._result[5].toInt() || result.greenOffset != this._result[6].toInt() || result.blueOffset != this._result[7].toInt() ) { val fadeProgress = this._animationState!!._fadeProgress.pow(4.0) result.alphaMultiplier += (this._result[0] - result.alphaMultiplier) * fadeProgress result.redMultiplier += (this._result[1] - result.redMultiplier) * fadeProgress result.greenMultiplier += (this._result[2] - result.greenMultiplier) * fadeProgress result.blueMultiplier += (this._result[3] - result.blueMultiplier) * fadeProgress result.alphaOffset += ((this._result[4] - result.alphaOffset) * fadeProgress).toInt() result.redOffset += ((this._result[5] - result.redOffset) * fadeProgress).toInt() result.greenOffset += ((this._result[6] - result.greenOffset) * fadeProgress).toInt() result.blueOffset += ((this._result[7] - result.blueOffset) * fadeProgress).toInt() slot._colorDirty = true } } else if (this.dirty) { this.dirty = false if ( result.alphaMultiplier != this._result[0] || result.redMultiplier != this._result[1] || result.greenMultiplier != this._result[2] || result.blueMultiplier != this._result[3] || result.alphaOffset != this._result[4].toInt() || result.redOffset != this._result[5].toInt() || result.greenOffset != this._result[6].toInt() || result.blueOffset != this._result[7].toInt() ) { result.alphaMultiplier = this._result[0] result.redMultiplier = this._result[1] result.greenMultiplier = this._result[2] result.blueMultiplier = this._result[3] result.alphaOffset = this._result[4].toInt() result.redOffset = this._result[5].toInt() result.greenOffset = this._result[6].toInt() result.blueOffset = this._result[7].toInt() slot._colorDirty = true } } } } } /** * @internal */ class SlotZIndexTimelineState(pool: SingleObjectPool<SlotZIndexTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.SlotZIndexTimelineState]" } override fun _onArriveAtFrame() { super._onArriveAtFrame() if (this._timelineData == null) { // Pose. val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! this._result = slot.slotData.zIndex.toDouble() } } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! val blendWeight = blendState.blendWeight if (blendState.dirty > 1) { // @TODO: Kotlin conversion original (no toInt): slot._zIndex += this._result * blendWeight slot._zIndex += (this._result * blendWeight).toInt() } else { // @TODO: Kotlin conversion original (no toInt): slot._zIndex = this._result * blendWeight slot._zIndex = (this._result * blendWeight).toInt() } if (_isDirty || this.dirty) { this.dirty = false this._armature?._zIndexDirty = true } } } /** * @internal */ class DeformTimelineState(pool: SingleObjectPool<DeformTimelineState>) : MutilpleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.DeformTimelineState]" } var geometryOffset: Int = 0 var displayFrame: DisplayFrame? = null private var _deformCount: Int = 0 private var _deformOffset: Int = 0 private var _sameValueOffset: Int = 0 override fun _onClear() { super._onClear() this.geometryOffset = 0 this.displayFrame = null this._deformCount = 0 this._deformOffset = 0 this._sameValueOffset = 0 } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) if (this._timelineData != null) { val frameIntOffset = this._animationData!!.frameIntOffset + this._timelineArray!![this._timelineData!!.offset + BinaryOffset.TimelineFrameValueCount] val dragonBonesData = this._animationData?.parent?.parent val frameIntArray = dragonBonesData!!.frameIntArray val slot = (this.targetBlendState)!!.targetSlot!! this.geometryOffset = frameIntArray!![frameIntOffset + BinaryOffset.DeformVertexOffset].toInt() if (this.geometryOffset < 0) { this.geometryOffset += 65536 // Fixed out of bounds bug. } for (i in 0 until slot.displayFrameCount) { val displayFrame = slot.getDisplayFrameAt(i) val geometryData = displayFrame.getGeometryData() ?: continue if (geometryData.offset == this.geometryOffset) { this.displayFrame = displayFrame this.displayFrame?.updateDeformVertices() break } } if (this.displayFrame == null) { this.returnToPool() // return } this._valueOffset = this._animationData!!.frameFloatOffset this._valueCount = frameIntArray[frameIntOffset + BinaryOffset.DeformValueCount].toInt() this._deformCount = frameIntArray[frameIntOffset + BinaryOffset.DeformCount].toInt() this._deformOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformValueOffset].toInt() this._sameValueOffset = frameIntArray[frameIntOffset + BinaryOffset.DeformFloatOffset].toInt() + this._animationData!!.frameFloatOffset this._valueScale = this._armature!!.armatureData.scale this._valueArray = dragonBonesData.frameFloatArray!! this._rd = DoubleArray(this._valueCount * 2) } else { this._deformCount = this.displayFrame!!.deformVertices.size } } override fun blend(_isDirty: Boolean) { val blendState = this.targetBlendState!! val slot = blendState.targetSlot!! val blendWeight = blendState.blendWeight val result = this.displayFrame!!.deformVertices val valueArray = this._valueArray if (valueArray != null) { val valueCount = this._valueCount val deformOffset = this._deformOffset val sameValueOffset = this._sameValueOffset val rd = this._rd for (i in 0 until this._deformCount) { val value = when { i < deformOffset -> valueArray[sameValueOffset + i].toDouble() i < deformOffset + valueCount -> rd[i - deformOffset] else -> valueArray[sameValueOffset + i - valueCount].toDouble() } if (blendState.dirty > 1) { result[i] += value * blendWeight } else { result[i] = value * blendWeight } } } else if (blendState.dirty == 1) { //for (var i = 0; i < this._deformCount; ++i) { for (i in 0 until this._deformCount) { result[i] = 0.0 } } if (_isDirty || this.dirty) { this.dirty = false if (slot._geometryData == this.displayFrame!!.getGeometryData()) { slot._verticesDirty = true } } } } /** * @internal */ class IKConstraintTimelineState(pool: SingleObjectPool<IKConstraintTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.IKConstraintTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val ikConstraint = this.targetIKConstraint!! if (this._timelineData != null) { ikConstraint._bendPositive = this._currentA > 0.0 ikConstraint._weight = this._currentB } else { val ikConstraintData = ikConstraint._constraintData as IKConstraintData ikConstraint._bendPositive = ikConstraintData.bendPositive ikConstraint._weight = ikConstraintData.weight } ikConstraint.invalidUpdate() this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.01 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationProgressTimelineState(pool: SingleObjectPool<AnimationProgressTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationProgressTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.currentTime = this._result * animationState.totalTime } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationWeightTimelineState(pool: SingleObjectPool<AnimationWeightTimelineState>) : SingleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationWeightTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.weight = this._result } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } } /** * @internal */ class AnimationParametersTimelineState(pool: SingleObjectPool<AnimationParametersTimelineState>) : DoubleValueTimelineState(pool) { override fun toString(): String { return "[class dragonBones.AnimationParametersTimelineState]" } override fun _onUpdateFrame() { super._onUpdateFrame() val animationState = this.targetAnimationState!! if (animationState._parent != null) { animationState.parameterX = this._resultA animationState.parameterY = this._resultB } this.dirty = false } override fun init(armature: Armature, animationState: AnimationState, timelineData: TimelineData?) { super.init(armature, animationState, timelineData) this._valueOffset = this._animationData!!.frameIntOffset this._valueScale = 0.0001 this._valueArray = this._animationData!!.parent!!.parent!!.frameIntArray!! } }
korge-dragonbones/src/commonMain/kotlin/com/dragonbones/animation/TimelineState.kt
3827234863
/* * Copyright (c) 2017-2020 by Oliver Boehm * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 06.10.17 by oliver ([email protected]) */ /** * In diesem Package sind Klassen und Aufzaehlungstypen wie * 'Anrede' oder 'Geschlecht', die ueblicherweise in Formularen * und Vertraege anzufinden sind, * * @author [email protected] * @since 2.0 */ package de.jfachwert.formular
src/main/kotlin/de/jfachwert/formular/package-info.kt
3090120476
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.text import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidPhrasingContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for a <var> element. */ internal class KatydidVar<Msg>( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, contenteditable: Boolean?, dir: EDirection?, draggable: Boolean?, hidden: Boolean?, lang: String?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, defineContent: KatydidPhrasingContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { phrasingContent.withNoAddedRestrictions(this).defineContent() this.freeze() } //// override val nodeName = "VAR" } //---------------------------------------------------------------------------------------------------------------------
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/text/KatydidVar.kt
721869229
/* * Copyright (C) 2017 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.marklogic.tests.query import com.intellij.execution.executors.DefaultDebugExecutor import com.intellij.execution.executors.DefaultRunExecutor import junit.framework.TestCase import uk.co.reecedunn.intellij.plugin.marklogic.server.* import uk.co.reecedunn.intellij.plugin.marklogic.ui.profile.ProfileExecutor import uk.co.reecedunn.intellij.plugin.marklogic.query.Function import uk.co.reecedunn.intellij.plugin.marklogic.query.SPARQLQueryBuilder import org.hamcrest.CoreMatchers.* import org.hamcrest.MatcherAssert.assertThat class SPARQLQueryBuilderTest : TestCase() { fun testEvalRun() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createEvalBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(Function.SEM_SPARQL_70)) assertThat<Function>(sparql.createEvalBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(Function.SEM_SPARQL_70)) assertThat<Function>(sparql.createEvalBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(Function.SEM_SPARQL_70)) } fun testEvalProfile() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createEvalBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(nullValue())) } fun testEvalDebug() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createEvalBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(nullValue())) assertThat<Function>(sparql.createEvalBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(nullValue())) } fun testInvokeRun() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createInvokeBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultRunExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(nullValue())) } fun testInvokeProfile() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createInvokeBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(ProfileExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(nullValue())) } fun testInvokeDebug() { val sparql = SPARQLQueryBuilder assertThat<Function>(sparql.createInvokeBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_5), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_6), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_7), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_8), `is`(nullValue())) assertThat<Function>(sparql.createInvokeBuilder(DefaultDebugExecutor.EXECUTOR_ID, MARKLOGIC_9), `is`(nullValue())) } }
src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/query/SPARQLQueryBuilderTest.kt
444725675
package tornadofx.testapps import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.scene.control.SelectionMode import javafx.scene.control.TableView import javafx.scene.control.TableView.CONSTRAINED_RESIZE_POLICY import javafx.scene.text.FontWeight import tornadofx.* import java.util.* class TableViewDirtyTestApp : WorkspaceApp(TableViewDirtyTest::class) class TableViewDirtyTest : View("Dirty Tables") { val customers = FXCollections.observableArrayList(Customer("Thomas", "Nield"), Customer("Matthew", "Turnblom"), Customer("Edvin", "Syse")) var table: TableView<Customer> by singleAssign() override val root = borderpane { center { tableview(customers) { table = this prefHeight = 200.0 column("First Name", Customer::firstNameProperty) { makeEditable() cellDecorator { style { fontWeight = FontWeight.BOLD } } } column("Last Name", Customer::lastNameProperty).makeEditable() enableCellEditing() regainFocusAfterEdit() enableDirtyTracking() selectOnDrag() contextmenu { item(stringBinding(selectionModel.selectedCells) { "Rollback ${selectedColumn?.text}" }) { disableWhen { editModel.selectedItemDirty.not() } action { editModel.rollback(selectedItem, selectedColumn) } } item(stringBinding(selectionModel.selectedCells) { "Commit ${selectedColumn?.text}" }) { disableWhen { editModel.selectedItemDirty.not() } action { editModel.commit(selectedItem, selectedColumn) } } } selectionModel.selectionMode = SelectionMode.MULTIPLE columnResizePolicy = CONSTRAINED_RESIZE_POLICY } } bottom { hbox(10) { paddingAll = 4 button("Commit row") { disableWhen { table.editModel.selectedItemDirty.not() } action { table.editModel.commitSelected() } } button("Rollback row") { disableWhen { table.editModel.selectedItemDirty.not() } action { table.editModel.rollbackSelected() } } } } } override fun onSave() { table.editModel.commit() } override fun onRefresh() { table.editModel.rollback() } init { icon = FX.icon } class Customer(firstName: String, lastName: String) { val idProperty = SimpleObjectProperty<UUID>(UUID.randomUUID()) var id by idProperty val firstNameProperty = SimpleStringProperty(firstName) var firstName by firstNameProperty val lastNameProperty = SimpleStringProperty(lastName) val lastName by lastNameProperty override fun toString() = "$firstName $lastName" override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Customer if (id != other.id) return false return true } override fun hashCode(): Int { return id.hashCode() } } }
src/test/kotlin/tornadofx/testapps/TableViewDirtyTest.kt
2069106854
package com.squareup.sqldelight.driver.test import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.db.QueryResult import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.db.SqlSchema import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue abstract class TransacterTest { protected lateinit var transacter: TransacterImpl private lateinit var driver: SqlDriver abstract fun setupDatabase(schema: SqlSchema): SqlDriver @BeforeTest fun setup() { val driver = setupDatabase( object : SqlSchema { override val version = 1 override fun create(driver: SqlDriver): QueryResult<Unit> = QueryResult.Unit override fun migrate( driver: SqlDriver, oldVersion: Int, newVersion: Int, ): QueryResult<Unit> = QueryResult.Unit }, ) transacter = object : TransacterImpl(driver) {} this.driver = driver } @AfterTest fun teardown() { driver.close() } @Test fun afterCommitRunsAfterTransactionCommits() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) } assertEquals(1, counter) } @Test fun afterCommitDoesNotRunAfterTransactionRollbacks() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) rollback() } assertEquals(0, counter) } @Test fun afterCommitRunsAfterEnclosingTransactionCommits() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } assertEquals(0, counter) } assertEquals(0, counter) } assertEquals(2, counter) } @Test fun afterCommitDoesNotRunInNestedTransactionWhenEnclosingRollsBack() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } } rollback() } assertEquals(0, counter) } @Test fun afterCommitDoesNotRunInNestedTransactionWhenNestedRollsBack() { var counter = 0 transacter.transaction { afterCommit { counter++ } assertEquals(0, counter) transaction { afterCommit { counter++ } rollback() } throw AssertionError() } assertEquals(0, counter) } @Test fun afterRollbackNoOpsIfTheTransactionNeverRollsBack() { var counter = 0 transacter.transaction { afterRollback { counter++ } } assertEquals(0, counter) } @Test fun afterRollbackRunsAfterARollbackOccurs() { var counter = 0 transacter.transaction { afterRollback { counter++ } rollback() } assertEquals(1, counter) } @Test fun afterRollbackRunsAfterAnInnerTransactionRollsBack() { var counter = 0 transacter.transaction { afterRollback { counter++ } transaction { rollback() } throw AssertionError() } assertEquals(1, counter) } @Test fun afterRollbackRunsInAnInnerTransactionWhenTheOuterTransactionRollsBack() { var counter = 0 transacter.transaction { transaction { afterRollback { counter++ } } rollback() } assertEquals(1, counter) } @Test fun transactionsCloseThemselvesOutProperly() { var counter = 0 transacter.transaction { afterCommit { counter++ } } transacter.transaction { afterCommit { counter++ } } assertEquals(2, counter) } @Test fun settingNoEnclosingFailsIfThereIsACurrentlyRunningTransaction() { transacter.transaction(noEnclosing = true) { assertFailsWith<IllegalStateException> { transacter.transaction(noEnclosing = true) { throw AssertionError() } } } } @Test fun anExceptionThrownInPostRollbackFunctionIsCombinedWithTheExceptionInTheMainBody() { class ExceptionA : RuntimeException() class ExceptionB : RuntimeException() val t = assertFailsWith<Throwable>() { transacter.transaction { afterRollback { throw ExceptionA() } throw ExceptionB() } } assertTrue("Exception thrown in body not in message($t)") { t.toString().contains("ExceptionA") } assertTrue("Exception thrown in rollback not in message($t)") { t.toString().contains("ExceptionB") } } @Test fun weCanReturnAValueFromATransaction() { val result: String = transacter.transactionWithResult { return@transactionWithResult "sup" } assertEquals(result, "sup") } @Test fun weCanRollbackWithValueFromATransaction() { val result: String = transacter.transactionWithResult { rollback("rollback") @Suppress("UNREACHABLE_CODE") return@transactionWithResult "sup" } assertEquals(result, "rollback") } }
drivers/driver-test/src/commonMain/kotlin/com/squareup/sqldelight/driver/test/TransacterTest.kt
3316141594
package com.chilangolabs.mdb.utils import android.util.Log /** * @author Gorro. */ object Logger { var isDebug = true } fun Any.loge(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.e(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logi(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.i(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logd(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.d(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logw(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.w(this::class.java.simpleName, "----> $msg", thr) } } fun Any.logv(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.v(this::class.java.simpleName, "----> $msg", thr) } } fun Any.loga(msg: Any, thr: Throwable? = null) { if (Logger.isDebug) { Log.wtf(this::class.java.simpleName, "----> $msg", thr) } }
app/src/main/java/com/chilangolabs/mdb/utils/Logger.kt
774559732
package com.dhsdevelopments.rqjava import com.google.gson.Gson import com.rabbitmq.client.AMQP import com.rabbitmq.client.Channel import com.rabbitmq.client.DefaultConsumer import com.rabbitmq.client.Envelope import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.nio.charset.Charset import java.util.logging.Level import java.util.logging.Logger class ChannelSubscription(val conn: PotatoConnection, val cid: String, val callback: (Message) -> Unit) { private val rqChannel: Channel companion object { private val logger = Logger.getLogger(ChannelSubscription::class.qualifiedName) private val UTF8 = Charset.forName("UTF-8") } init { rqChannel = conn.amqpConn.createChannel() try { val q = rqChannel.queueDeclare("", true, false, true, null) // routing key format: DOMAIN.CHANNEL.SENDER rqChannel.queueBind(q.queue, "message-send-ex", "*.$cid.*") val consumer = object : DefaultConsumer(rqChannel) { override fun handleDelivery(consumerTag: String, envelope: Envelope, properties: AMQP.BasicProperties, body: ByteArray) { val gson = Gson() val message = InputStreamReader(ByteArrayInputStream(body), UTF8).use { gson.fromJson(it, Message::class.java) } callback(message) } } rqChannel.basicConsume(q.queue, true, consumer) } catch(e: Exception) { try { rqChannel.close() } catch(e2: Exception) { logger.log(Level.SEVERE, "Error closing channel when handling exception in subscribeChannel", e2) } throw e } } fun disconnect() { rqChannel.close() } }
contrib/rqjava/src/com/dhsdevelopments/rqjava/ChannelSubscription.kt
1015149041
package org.lrs.kmodernlrs.services import org.lrs.kmodernlrs.domain.Activity interface ActivitiesService { fun getActivity(id: String) : Activity? fun getAll() : List<Activity>? fun get10Activities(from: Int) : List<Activity>? fun get20Activities(from: Int) : List<Activity>? fun get50Activities(from: Int) : List<Activity>? fun getActivitiesLimitFrom(limit: Int, from: Int) : List<Activity>? fun getCount() : Long fun exists(activity: Activity) : Boolean }
src/main/org/lrs/kmodernlrs/services/ActivitiesService.kt
2513689466
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.task.compose import android.content.Context import android.net.Uri import org.mariotaku.abstask.library.AbstractTask import de.vanita5.twittnuker.util.Utils import java.lang.ref.WeakReference open class AbsDeleteMediaTask<Callback>( context: Context, val sources: Array<Uri> ) : AbstractTask<Unit, BooleanArray, Callback>() { private val contextRef = WeakReference(context) val context: Context? get() = contextRef.get() override fun doLongOperation(params: Unit?): BooleanArray { val context = contextRef.get() ?: return kotlin.BooleanArray(sources.size) { false } return BooleanArray(sources.size) { Utils.deleteMedia(context, sources[it]) } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/compose/AbsDeleteMediaTask.kt
1840968911
package com.stripe.android.ui.core.elements import android.app.Application import androidx.lifecycle.asLiveData import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth import com.stripe.android.ui.core.address.AddressRepository import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) internal class CardBillingAddressElementTest { private val addressRepository = AddressRepository( ApplicationProvider.getApplicationContext<Application>().resources ) val dropdownFieldController = DropdownFieldController( CountryConfig(emptySet()) ) val cardBillingElement = CardBillingAddressElement( IdentifierSpec.Generic("billing_element"), rawValuesMap = emptyMap(), addressRepository, emptySet(), dropdownFieldController, null, null ) init { // We want to use fields that are easy to set in error addressRepository.add( "US", listOf( EmailElement( IdentifierSpec.Email, controller = SimpleTextFieldController(EmailConfig()) ) ) ) addressRepository.add( "JP", listOf( IbanElement( IdentifierSpec.Generic("sepa_debit[iban]"), SimpleTextFieldController(IbanConfig()) ) ) ) } @Test fun `Verify that when US is selected postal is not hidden`() { val hiddenIdFlowValues = mutableListOf<Set<IdentifierSpec>>() cardBillingElement.hiddenIdentifiers.asLiveData() .observeForever { hiddenIdFlowValues.add(it) } dropdownFieldController.onRawValueChange("US") verifyPostalShown(hiddenIdFlowValues[0]) } @Test fun `Verify that when GB is selected postal is not hidden`() { val hiddenIdFlowValues = mutableListOf<Set<IdentifierSpec>>() cardBillingElement.hiddenIdentifiers.asLiveData() .observeForever { hiddenIdFlowValues.add(it) } dropdownFieldController.onRawValueChange("GB") verifyPostalShown(hiddenIdFlowValues[1]) } @Test fun `Verify that when CA is selected postal is not hidden`() { val hiddenIdFlowValues = mutableListOf<Set<IdentifierSpec>>() cardBillingElement.hiddenIdentifiers.asLiveData() .observeForever { hiddenIdFlowValues.add(it) } dropdownFieldController.onRawValueChange("CA") verifyPostalShown(hiddenIdFlowValues[0]) } @Test fun `Verify that when DE is selected postal IS hidden`() { val hiddenIdFlowValues = mutableListOf<Set<IdentifierSpec>>() cardBillingElement.hiddenIdentifiers.asLiveData() .observeForever { hiddenIdFlowValues.add(it) } dropdownFieldController.onRawValueChange("DE") verifyPostalHidden(hiddenIdFlowValues[1]) } fun verifyPostalShown(hiddenIdentifiers: Set<IdentifierSpec>) { Truth.assertThat(hiddenIdentifiers).doesNotContain(IdentifierSpec.PostalCode) Truth.assertThat(hiddenIdentifiers).doesNotContain(IdentifierSpec.Country) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.Line1) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.Line2) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.State) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.City) } fun verifyPostalHidden(hiddenIdentifiers: Set<IdentifierSpec>) { Truth.assertThat(hiddenIdentifiers).doesNotContain(IdentifierSpec.Country) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.PostalCode) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.Line1) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.Line2) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.State) Truth.assertThat(hiddenIdentifiers).contains(IdentifierSpec.City) } }
payments-ui-core/src/test/java/com/stripe/android/ui/core/elements/CardBillingAddressElementTest.kt
2982991892
package tech.aroma.data.sql.serializers import com.google.inject.AbstractModule import com.google.inject.binder.AnnotatedBindingBuilder import tech.aroma.data.bind import tech.aroma.data.sql.DatabaseSerializer import tech.aroma.data.to import tech.aroma.thrift.* import tech.aroma.thrift.authentication.AuthenticationToken import tech.aroma.thrift.channels.MobileDevice import tech.aroma.thrift.events.Event import tech.aroma.thrift.reactions.Reaction /** * * @author SirWellington */ class ModuleSerializers : AbstractModule() { override fun configure() { bind<DatabaseSerializer<Application>>().to<ApplicationSerializer>().asEagerSingleton() bind<DatabaseSerializer<AuthenticationToken>>().to<TokenSerializer>().asEagerSingleton() bind<DatabaseSerializer<Event>>().to<EventSerializer>().asEagerSingleton() bind<DatabaseSerializer<Image>>().to<ImageSerializer>().asEagerSingleton() bind<DatabaseSerializer<Message>>().to<MessageSerializer>().asEagerSingleton() bind<DatabaseSerializer<MutableSet<MobileDevice>>>().to<DevicesSerializer>().asEagerSingleton() bind<DatabaseSerializer<Organization>>().to<OrganizationSerializer>().asEagerSingleton() bind<DatabaseSerializer<MutableList<Reaction>>>().to<ReactionsSerializer>().asEagerSingleton() bind<DatabaseSerializer<User>>().to<UserSerializer>().asEagerSingleton() } private inline fun <reified T : Any> AbstractModule.bind(): AnnotatedBindingBuilder<T> = binder().bind<T>() }
src/main/java/tech/aroma/data/sql/serializers/ModuleSerializers.kt
3548575050
package com.stripe.android.model import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class DateOfBirth( val day: Int, val month: Int, val year: Int ) : StripeParamsModel, Parcelable { override fun toParamMap(): Map<String, Any> { return mapOf( PARAM_DAY to day, PARAM_MONTH to month, PARAM_YEAR to year ) } private companion object { private const val PARAM_DAY = "day" private const val PARAM_MONTH = "month" private const val PARAM_YEAR = "year" } }
payments-core/src/main/java/com/stripe/android/model/DateOfBirth.kt
1594756582
package com.ivantrogrlic.leaguestats.main.summoner.games import com.hannesdorfmann.mosby3.mvp.MvpView import com.ivantrogrlic.leaguestats.model.Match import java.util.* /** * Created by ivan on 8/9/2017. */ interface GamesView : MvpView { fun setMatches(matches: List<Match>) }
app/src/main/java/com/ivantrogrlic/leaguestats/main/summoner/games/GamesView.kt
868676605
package dwallet.core.bitcoin.protocol.messages import dwallet.core.extensions.readInt64LE import dwallet.core.extensions.toInt64LEBytes /** * Created by unsignedint8 on 8/16/17. */ class Ping(val nonce: Long) { companion object { fun fromBytes(bytes: ByteArray): Ping { val nonce = bytes.readInt64LE() return Ping(nonce) } val text = "ping" val pong = "pong" } fun toBytes() = nonce.toInt64LEBytes() }
android/lib/src/main/java/dWallet/core/bitcoin/protocol/messages/Ping.kt
2910444766
package com.example.chadrick.datalabeling.Fragments import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.example.chadrick.datalabeling.Models.* import com.example.chadrick.datalabeling.R import com.example.chadrick.datalabeling.Adapters.RAAdapter import kotlinx.android.synthetic.main.usermainfragment_layout.* import org.json.JSONArray import org.json.JSONObject import java.io.File /** * Created by chadrick on 17. 12. 2. */ class UserMainFragment : Fragment() { private val serverFectchedDSlist: ArrayList<DataSet> = ArrayList<DataSet>() lateinit var allDSrecyclerviewAdapter: RAAdapter lateinit var RArvAdapter: RAAdapter private val RAlist: ArrayList<DataSet> = ArrayList<DataSet>() lateinit var recentactivitylogmanager: RecentActivityLogManager companion object { val TAG = "UserMainFragment" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG,"bitcoin: Usermainfragment created") for( frag in fragmentManager.fragments){ Log.d("bitcoin","print frags in settingsfragment frag = "+frag.toString()) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root: View? = inflater?.inflate(R.layout.usermainfragment_layout, container, false) // setup adapter for RA allDSrecyclerviewAdapter = RAAdapter.newInstance(context, serverFectchedDSlist, ::getfragmentmanager) recentactivitylogmanager = RecentActivityLogManager.getInstance(App.applicationContext()) RArvAdapter = RAAdapter.newInstance(context, RAlist, ::getfragmentmanager) for(frag in fragmentManager.fragments){ Log.d("bitcoin","in Usermainfragment oncreateview frag = "+frag.toString()) } return root } fun getfragmentmanager():FragmentManager{ return fragmentManager } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) AllDSrecyclerview.adapter = allDSrecyclerviewAdapter AllDSrecyclerview.layoutManager = LinearLayoutManager(context.applicationContext, LinearLayoutManager.HORIZONTAL, false) RArecyclerview.adapter = RArvAdapter RArecyclerview.layoutManager = LinearLayoutManager(context.applicationContext, LinearLayoutManager.HORIZONTAL, false) } override fun onResume() { Log.d(TAG, "fuck: inside onresume") super.onResume() updateElements() } private fun populateDSrv() { serverFectchedDSlist.clear() // prepare jsonarray request val reqobj: JSONArray = JSONArray() reqobj.put(JSONObject("{'ds_request_id':'anything'}")) val jsonarrayreq: JsonArrayRequest = JsonArrayRequest(Request.Method.POST, ServerInfo.instance.serveraddress + "/dslist", reqobj, { response: JSONArray -> for (i in 0..(response.length() - 1)) { val item = response.getJSONObject(i) var direxist: Boolean = false val filename = item.get("id").toString() val file: File = File(App.applicationContext().filesDir, filename) if (file.exists()) { direxist = true } val ds: DataSet = DataSet(item.getInt("id"), item.getString("title"), direxist, App.applicationContext().filesDir.toString()) serverFectchedDSlist.add(ds) allDSrecyclerviewAdapter.notifyDataSetChanged() } }, { error -> Toast.makeText(context.applicationContext, "failed to fetch dslist", Toast.LENGTH_SHORT).show() } ) // val queue = Volley.newRequestQueue(context.applicationContext) val queue = requestqueueSingleton.getQueue() queue.add(jsonarrayreq) } fun populateRAlist() { Log.d(TAG, "inside populateRAlist") RAlist.clear() val newlist = recentactivitylogmanager.getsortedlist() for (item in newlist) { RAlist.add(item) } if (RAlist.size == 0) { RArecyclerview.visibility = View.INVISIBLE nonefound_tv.visibility = View.VISIBLE } else { RArecyclerview.visibility = View.VISIBLE nonefound_tv.visibility = View.INVISIBLE } RArvAdapter.notifyDataSetChanged() } fun updateElements(){ populateDSrv() populateRAlist() } }
app/src/main/java/com/example/chadrick/datalabeling/Fragments/UserMainFragment.kt
2093695106
package pl.wendigo.chrome import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import okhttp3.Request import org.slf4j.Logger import org.slf4j.LoggerFactory import org.testcontainers.utility.DockerImageName import pl.wendigo.chrome.api.ProtocolDomains import pl.wendigo.chrome.api.target.TargetInfo import pl.wendigo.chrome.protocol.ProtocolConnection import pl.wendigo.chrome.targets.Manager import pl.wendigo.chrome.targets.Target import java.io.Closeable import kotlin.math.max /** * Creates new browser that allows querying remote Chrome instance for debugging sessions * * @sample pl.wendigo.chrome.samples.Containerized.main */ open class Browser internal constructor( private val browserInfo: BrowserInfo, private val options: Options, connection: ProtocolConnection, private val manager: Manager ) : ProtocolDomains(connection), Closeable, AutoCloseable { /** * Creates new target and opens new debugging session via debugging protocol. * * If incognito is true then new browser context is created (similar to incognito mode but you can have many of those). */ @JvmOverloads fun target(url: String = options.blankPage, incognito: Boolean = options.incognito, width: Int = options.viewportWidth, height: Int = options.viewportHeight): Target { return manager.create( url = url, incognito = incognito, width = width, height = height ) } /** * Lists all targets that can be attached to. */ fun targets(): List<TargetInfo> = manager.list() /** * Returns information on browser. */ fun browserInfo(): BrowserInfo = browserInfo /** * Attaches to existing target creating new session if multiplexed connections is used. */ fun attach(target: TargetInfo): Target = manager.attach(target) /** * Closes target releasing all resources on the browser side and connections. */ fun close(target: Target) { manager.close(target) } /** * Closes session manager and established connection to the debugger. */ override fun close() { try { manager.close() connection.close() } catch (e: Exception) { logger.info("Caught exception while closing Browser", e) } } override fun toString(): String { return "Browser($browserInfo, $options, $manager)" } companion object { private val logger: Logger = LoggerFactory.getLogger(Browser::class.java) private val decoder = Json { ignoreUnknownKeys = true; isLenient = true } /** * Returns library build info. */ @JvmStatic fun buildInfo(): BuildInfo { return Browser.javaClass.getResource("/version.json")!!.readText().run { decoder.decodeFromString(BuildInfo.serializer(), this) } } /** * Creates new Browser instance by connecting to remote chrome debugger. */ private fun connect(chromeAddress: String = "localhost:9222", options: Options): Browser { val info = fetchInfo(chromeAddress) val connection = ProtocolConnection.open(info.webSocketDebuggerUrl, options.eventsBufferSize) val protocol = ProtocolDomains(connection) return Browser( info, options, connection, Manager( info.webSocketDebuggerUrl, options.multiplexConnections, options.eventsBufferSize, protocol ) ) } /** * Fetches browser info. */ internal fun fetchInfo(chromeAddress: String): BrowserInfo { val client = OkHttpClient.Builder().build() val info = client.newCall(Request.Builder().url("http://$chromeAddress/json/version").build()).execute() return when (info.isSuccessful) { true -> decoder.decodeFromString(info.body?.string()!!) false -> throw BrowserInfoDiscoveryFailedException("Could not query browser info - response code was ${info.code}") } } @JvmStatic fun builder() = Builder() } /** * [Builder] is responsible for setting options and defaults while creating new instance of [Browser]. */ class Builder { private var address: String = "localhost:9222" private var blankPage: String = "about:blank" private var eventsBufferSize: Int = 128 private var viewportWidth: Int = 1024 private var viewportHeight: Int = 768 private var multiplexConnections: Boolean = true // see https://crbug.com/991325 private var incognito: Boolean = true private var dockerImage: String = "eu.gcr.io/zenika-hub/alpine-chrome:89" private var runDockerImage: Boolean = false /** * Sets browser debugger address (default: localhost:9222) */ fun withAddress(address: String): Builder = this.apply { this.address = address } /** * Sets default blank page location (default: about:blank) */ fun withBlankPage(address: String): Builder = this.apply { this.blankPage = address } /** * Sets frames buffer size for underlying [pl.wendigo.chrome.protocol.WebSocketFramesStream]'s reactive replaying subject (default: 128) * * High buffer size allows to observe N frames prior to subscribing. */ fun withEventsBufferSize(size: Int): Builder = this.apply { this.eventsBufferSize = max(size, 1) } /** * Sets default viewport height while creating sessions (default; 768, min: 100) */ fun withViewportHeight(height: Int): Builder = this.apply { this.viewportHeight = max(100, height) } /** * Sets default viewport width while creating sessions (default: 1024, min: 100) */ fun withViewportWidth(width: Int): Builder = this.apply { this.viewportWidth = max(100, width) } /** * Enables [Manager] to share single, underlying WebSocket connection to debugger with multiple sessions (default: true) * * @see [https://bugs.chromium.org/p/chromium/issues/detail?id=991325](https://bugs.chromium.org/p/chromium/issues/detail?id=991325) */ fun multiplexConnections(enabled: Boolean): Builder = this.apply { this.multiplexConnections = enabled } /** * Enables incognito mode while creating new targets (default: true) * * Incognito mode uses [pl.wendigo.chrome.api.browser.BrowserContextID] to separate different targets from each other (separating cookies, caches, storages...) */ fun incognito(enabled: Boolean): Builder = this.apply { this.incognito = enabled } /** * Sets docker image name that will be used to create headless Chrome instance (default: eu.gcr.io/zenika-hub/alpine-chrome:89) */ fun withDockerImage(dockerImage: String): Builder = this.apply { this.dockerImage = dockerImage } /** * Enabled creating headless Chrome instance when [Browser] is created (default: false) */ fun runInDocker(enabled: Boolean): Builder = this.apply { this.runDockerImage = enabled } private fun toOptions(): Options = Options( eventsBufferSize = eventsBufferSize, viewportHeight = viewportHeight, viewportWidth = viewportWidth, incognito = incognito, blankPage = blankPage, multiplexConnections = multiplexConnections ) /** * Creates new instance of [Browser] with configuration passed to builder */ fun build(): Browser = when (runDockerImage) { true -> ContainerizedBrowser.connect(DockerImageName.parse(dockerImage), toOptions()) false -> connect(address, toOptions()) } } @Serializable data class BrowserInfo( @SerialName("Browser") val browser: String, @SerialName("Protocol-Version") val protocolVersion: String, @SerialName("User-Agent") val userAgent: String, @SerialName("V8-Version") val v8Version: String? = null, @SerialName("WebKit-Version") val webKitVersion: String, @SerialName("webSocketDebuggerUrl") val webSocketDebuggerUrl: String ) internal data class Options( val eventsBufferSize: Int, val viewportWidth: Int, val viewportHeight: Int, val multiplexConnections: Boolean, val incognito: Boolean, val blankPage: String ) }
src/main/kotlin/pl/wendigo/chrome/Browser.kt
3340894764
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.rxjava2 import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import io.reactivex.disposables.Disposable import io.reactivex.plugins.RxJavaPlugins /** * Subscribes to this [Observable] and represents its values via [State]. Every time there would * be new value posted into the [Observable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Observable.onErrorReturn] or [Observable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.ObservableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Observable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Flowable] and represents its values via [State]. Every time there would * be new value posted into the [Flowable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Flowable.onErrorReturn] or [Flowable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.FlowableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Flowable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Single] and represents its value via [State]. Once the value would be * posted into the [Single] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Single.onErrorReturn] or [Single.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.SingleSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Single<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Maybe] and represents its value via [State]. Once the value would be * posted into the [Maybe] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Maybe.onErrorComplete], [Maybe.onErrorReturn] or [Maybe.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.MaybeSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Maybe<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Completable] and represents its completed state via [State]. Once the * [Completable] will be completed the returned [State] will be updated with `true` value * causing recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Completable.onErrorComplete] or [Completable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava2.samples.CompletableSample */ @Composable fun Completable.subscribeAsState(): State<Boolean> = asState(false) { callback -> subscribe { callback(true) } } @Composable private inline fun <T, S> S.asState( initial: T, crossinline subscribe: S.((T) -> Unit) -> Disposable ): State<T> { val state = remember { mutableStateOf(initial) } DisposableEffect(this) { val disposable = subscribe { state.value = it } onDispose { disposable.dispose() } } return state }
compose/runtime/runtime-rxjava2/src/main/java/androidx/compose/runtime/rxjava2/RxJava2Adapter.kt
566583514
package expo.modules.print import android.content.Context import expo.modules.core.BasePackage import expo.modules.core.ExportedModule class PrintPackage : BasePackage() { override fun createExportedModules(context: Context): List<ExportedModule> { return listOf(PrintModule(context)) } }
packages/expo-print/android/src/main/java/expo/modules/print/PrintPackage.kt
3314718389
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.socketing open class SocketCommand(string: String) { var runner: SocketCommandRunner var command: String var permissions: List<String> = emptyList() init { val indexOfFirstColon = string.indexOf(":") if (indexOfFirstColon == -1) { runner = SocketCommandRunner.DEFAULT command = string.trim { it <= ' ' } } else { var run: SocketCommandRunner? = SocketCommandRunner.fromName(string.substring(0, indexOfFirstColon)) if (run == null) { run = SocketCommandRunner.DEFAULT } runner = run var commandS: String commandS = if (string.substring(0, runner.name.length).equals(runner.name, ignoreCase = true)) { string.substring(runner.name.length, string.length).trim { it <= ' ' } } else { string.trim { it <= ' ' } } if (commandS.substring(0, 1).equals(":", ignoreCase = true)) { commandS = commandS.substring(1, commandS.length).trim { it <= ' ' } } command = commandS.trim { it <= ' ' } } } override fun toString(): String { return "SocketCommand(runner=$runner, command='$command', permissions=$permissions)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SocketCommand) return false if (runner != other.runner) return false if (command != other.command) return false if (permissions != other.permissions) return false return true } override fun hashCode(): Int { var result = runner.hashCode() result = 31 * result + command.hashCode() result = 31 * result + permissions.hashCode() return result } }
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/socketing/SocketCommand.kt
1826463482
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.generator import org.jetbrains.android.anko.* import org.jetbrains.android.anko.utils.MethodNodeWithClass import org.jetbrains.android.anko.utils.fqName import org.jetbrains.android.anko.utils.toProperty import org.jetbrains.android.anko.utils.unique import org.objectweb.asm.tree.MethodNode class PropertyGenerator : Generator<PropertyElement> { override fun generate(state: GenerationState) = with (state) { val propertyGetters = availableMethods .filter { it.clazz.isView && it.method.isGetter() && !it.method.isOverridden && !it.method.isListenerGetter && !config.excludedProperties.contains(it.clazz.fqName + "#" + it.method.name) && !config.excludedProperties.contains(it.clazz.fqName + "#*") } .sortedBy { it.identifier } val propertySetters = availableMethods .filter { it.clazz.isView && it.method.isNonListenerSetter() && !it.method.isOverridden && !config.excludedProperties.contains(it.clazz.fqName + "#" + it.method.name) && !config.excludedProperties.contains(it.clazz.fqName + "#*") } .groupBy { it.identifier } genProperties(propertyGetters, propertySetters) } private fun GenerationState.genProperties( getters: Collection<MethodNodeWithClass>, setters: Map<String, List<MethodNodeWithClass>>): List<PropertyElement> { val existingProperties = hashSetOf<String>() val propertyWithGetters = getters.map { getter -> val property = getter.toProperty() val settersList = setters[property.setterIdentifier] ?: emptyList() val (best, others) = settersList.partition { it.method.parameterRawTypes.unique == getter.method.returnType } existingProperties.add(property.setterIdentifier) PropertyElement(property.name, getter, best + others) } val propertyWithoutGetters = setters.values.map { s -> val property = s.first().toProperty() val id = property.setterIdentifier if (id !in existingProperties) { if (property.propertyFqName in config.propertiesWithoutGetters) { PropertyElement(property.name, null, s) } else { logger.d("PropertyGenerator # Property was not generated for $id") null } } else null }.filterNotNull() return propertyWithoutGetters + propertyWithGetters } private val MethodNode.isListenerGetter: Boolean get() = name.startsWith("get") && name.endsWith("Listener") }
anko/library/generator/src/org/jetbrains/android/anko/generator/PropertyGenerator.kt
3419935006
package com.habitrpg.android.habitica.ui.views import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.widget.LinearLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.isUsingNightModeResources class CurrencyViews : LinearLayout { var lightBackground: Boolean = false set(value) { field = value hourglassTextView.lightBackground = value gemTextView.lightBackground = value goldTextView.lightBackground = value } private val hourglassTextView: CurrencyView = CurrencyView(context, "hourglasses", lightBackground) private val goldTextView: CurrencyView = CurrencyView(context, "gold", lightBackground) private val gemTextView: CurrencyView = CurrencyView(context, "gems", lightBackground) var gold: Double get() = goldTextView.value set(value) { goldTextView.value = value } var gems: Double get() = gemTextView.value set(value) { gemTextView.value = value } var hourglasses: Double get() = hourglassTextView.value set(value) { hourglassTextView.value = value } var hourglassVisibility get() = hourglassTextView.visibility set(value) { hourglassTextView.visibility = value hourglassTextView.hideWhenEmpty = false } var goldVisibility: Int get() = goldTextView.visibility set(value) { goldTextView.visibility = value } var gemVisibility get() = gemTextView.visibility set(value) { gemTextView.visibility = value } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { val attributes = context?.theme?.obtainStyledAttributes( attrs, R.styleable.CurrencyViews, 0, 0 ) setupViews() val fallBackLight = context?.isUsingNightModeResources() != true lightBackground = attributes?.getBoolean(R.styleable.CurrencyViews_hasLightBackground, fallBackLight) ?: fallBackLight } constructor(context: Context?) : super(context) { setupViews() } private fun setupViews() { val margin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12f, context.resources.displayMetrics).toInt() setupView(hourglassTextView, margin) setupView(goldTextView, margin) setupView(gemTextView, margin) } private fun setupView(view: CurrencyView, margin: Int) { this.addView(view) view.textSize = 12f val params = view.layoutParams as? LayoutParams params?.marginStart = margin view.layoutParams = params } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/CurrencyViews.kt
3097374085
package de.tum.`in`.tumcampusapp.component.ui.studyroom import android.content.Context import de.tum.`in`.tumcampusapp.component.ui.studyroom.model.StudyRoom import de.tum.`in`.tumcampusapp.component.ui.studyroom.model.StudyRoomGroup import de.tum.`in`.tumcampusapp.database.TcaDb import org.jetbrains.anko.doAsync /** * Handles content for the study room feature, fetches external data. */ class StudyRoomGroupManager(context: Context) { private val roomsDao: StudyRoomDao private val groupsDao: StudyRoomGroupDao init { val db = TcaDb.getInstance(context) roomsDao = db.studyRoomDao() groupsDao = db.studyRoomGroupDao() } fun updateDatabase(groups: List<StudyRoomGroup>, callback: () -> Unit) { doAsync { groupsDao.removeCache() roomsDao.removeCache() groupsDao.insert(*groups.toTypedArray()) groups.forEach { group -> roomsDao.insert(*group.rooms.toTypedArray()) } callback() } } fun getAllStudyRoomsForGroup(groupId: Int): List<StudyRoom> { return roomsDao.getAll(groupId).sorted() } }
app/src/main/java/de/tum/in/tumcampusapp/component/ui/studyroom/StudyRoomGroupManager.kt
2327498323
package com.habitrpg.android.habitica.models.auth class UserAuthSocial { var network: String? = null var authResponse: UserAuthSocialTokens? = null }
Habitica/src/main/java/com/habitrpg/android/habitica/models/auth/UserAuthSocial.kt
2430463448
package com.quijotelui.repository import com.quijotelui.model.Informacion import com.quijotelui.model.Parametro import com.quijotelui.model.Retencion import com.quijotelui.model.RetencionDetalle import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import javax.persistence.EntityManager import javax.persistence.PersistenceContext @Transactional @Repository class RetencionDaoImpl : IRetencionDao { @PersistenceContext lateinit var entityMAnager : EntityManager override fun findAll(): MutableList<Retencion> { return entityMAnager.createQuery("from Retencion").resultList as MutableList<Retencion> } override fun findByComprobante(codigo: String, numero: String): MutableList<Retencion> { return entityMAnager.createQuery("from Retencion " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<Retencion> } override fun findContribuyenteByComprobante(codigo: String, numero: String): MutableList<Any> { val result = entityMAnager.createQuery("from Contribuyente c, " + "Retencion r " + "WHERE c.id = r.idContribuyente " + "and r.codigo = :codigo " + "and r.numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero) .resultList return result as MutableList<Any> } override fun findRetencionDetalleByComprobante(codigo : String, numero : String) : MutableList<RetencionDetalle> { return entityMAnager.createQuery("from RetencionDetalle " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<RetencionDetalle> } override fun findParametroByNombre(nombre : String) : MutableList<Parametro> { return entityMAnager.createQuery("from Parametro " + "where nombre = :nombre " + "and estado = 'Activo'") .setParameter("nombre", nombre).resultList as MutableList<Parametro> } override fun findInformacionByDocumento(documento: String): MutableList<Informacion> { return entityMAnager.createQuery("from Informacion " + "where documento = :documento") .setParameter("documento", documento) .resultList as MutableList<Informacion> } override fun findEstadoByComprobante(codigo: String, numero: String): MutableList<Any> { return entityMAnager.createQuery("select estado from ReporteRetencion " + "where codigo = :codigo " + "and numero = :numero") .setParameter("codigo", codigo) .setParameter("numero", numero).resultList as MutableList<Any> } }
src/main/kotlin/com/quijotelui/repository/RetencionDaoImpl.kt
2785985085
package org.jtalks.pochta.util import javax.mail.MessagingException import javax.mail.Session import javax.mail.PasswordAuthentication import javax.mail.internet.MimeMessage import javax.mail.internet.InternetAddress import javax.mail.Message import javax.mail.Transport import java.io.StringReader import java.io.ByteArrayInputStream /** * Simple testing utility to send mails */ public fun main(args: Array<String>) { Transport.send(multipartMail()) System.out.println("Sent message successfully....") } fun plainMail(): MimeMessage { val to = "[email protected]" val from = "[email protected]" val properties = System.getProperties() properties?.put("mail.smtp.host", "localhost") properties?.put("mail.smtp.port", "9025") properties?.put("mail.smtp.auth", "true") val session = Session.getDefaultInstance(properties, object : javax.mail.Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication("user", "secret") } }) val message = MimeMessage(session) message.setFrom(InternetAddress(from)) message.addRecipient(Message.RecipientType.TO, InternetAddress(to)) message.setSubject("This is the long long long long long long long longSubject Line!") message.setText("This is actual message") return message } fun b64Mail(): MimeMessage { val message = plainMail() message.setHeader("Content-Transfer-Encoding", "base64"); return message } fun multipartMail(): MimeMessage { val properties = System.getProperties() properties?.put("mail.smtp.host", "localhost") properties?.put("mail.smtp.port", "9025") properties?.put("mail.smtp.auth", "true") val session = Session.getDefaultInstance(properties, object : javax.mail.Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication("user", "secret") } }) val stream = ByteArrayInputStream(("From: [email protected] \n" + "To: [email protected] \n" + "Message-ID: <1799061474.01422213640062.JavaMail.i_autotests@jtalks-infra-1> \n" + "Subject: =?UTF-8?B?0JDQutGC0LjQstCw0YbQuNGPINCw0LrQutCw0YPQvdGC0LAgSlRhbGtz?= \n" + "MIME-Version: 1.0 \n" + "Content-Type: multipart/mixed; \n" + "boundary=\"----=_Part_0_980719463.1422213640036\" \n" + "Date: Sun, 25 Jan 2015 20:20:40 +0100 (CET) \n" + "\n" + "------=_Part_0_980719463.1422213640036 \n" + "Content-Type: multipart/related; \n" + "boundary=\"----=_Part_1_2012376838.1422213640046\" \n" + "\n" + "------=_Part_1_2012376838.1422213640046 \n" + "Content-Type: multipart/alternative; \n" + "boundary=\"----=_Part_2_1297559663.1422213640047\" \n" + "\n" + "------=_Part_2_1297559663.1422213640047 \n" + "Content-Type: text/plain; charset=UTF-8 \n" + "Content-Transfer-Encoding: base64 \n" + "\n" + "CtCf0YDQuNCy0LXRgiwganRYaEVPeE44bzJhVllEeE5tM1lJeURPTyEKCtCt0YLQviDQv9C40YHR\n" + "jNC80L4g0LTQu9GPINC/0L7QtNGC0LLQtdGA0LbQtNC10L3QuNGPINGA0LXQs9C40YHRgtGA0LDR\n" + "htC40Lgg0L3QsCBKVGFsa3Mg0YTQvtGA0YPQvNC1LgrQn9C+0LbQsNC70YPQudGB0YLQsCwg0L/R\n" + "gNC+0YHQu9C10LTRg9C50YLQtSDQv9C+INGB0YHRi9C70LrQtSDQvdC40LbQtSDQtNC70Y8g0LDQ\n" + "utGC0LjQstCw0YbQuNC4INCS0LDRiNC10LPQviDQsNC60LrQsNGD0L3RgtCwLiDQrdGC0LAg0YHR\n" + "gdGL0LvQutCwINC00LXQudGB0YLQstC40YLQtdC70YzQvdCwIDI0INGH0LDRgdCwLgrQktC90LjQ\n" + "vNCw0L3QuNC1LCDQsNC60LrQsNGD0L3RgiDQsdGD0LTQtdGCINCw0LLRgtC+0LzQsNGC0LjRh9C1\n" + "0YHQutC4INGD0LTQsNC70LXQvSDRh9C10YDQtdC3IDI0INGH0LDRgdCwLCDQtdGB0LvQuCDQvdC1\n" + "INCx0YPQtNC10YIg0LDQutGC0LjQstC40YDQvtCy0LDQvS4K0JDQutGC0LjQstCw0YbQuNC+0L3Q\n" + "vdCw0Y8g0YHRgdGL0LvQutCwOiBodHRwOi8vYXV0b3Rlc3RzLmp0YWxrcy5vcmc6ODAvamNvbW11\n" + "bmUvdXNlci9hY3RpdmF0ZS83ODQxNmRmYi1lM2FjLTRkOGEtYWIzMy03OWM4MGQwZjFjMGUKCtCh\n" + "INC90LDQuNC70YPRh9GI0LjQvNC4INC/0L7QttC10LvQsNC90LjRj9C80LgsCtCk0L7RgNGD0Lwg\n" + "SlRhbGtzLg== \n" + "------=_Part_2_1297559663.1422213640047 \n" + "Content-Type: text/html;charset=UTF-8 \n" + "Content-Transfer-Encoding: base64 \n" + "\n" + "CjxwPtCf0YDQuNCy0LXRgiwganRYaEVPeE44bzJhVllEeE5tM1lJeURPTyE8L3A+Cjxici8+Cjxw \n" + "PtCt0YLQviDQv9C40YHRjNC80L4g0LTQu9GPINC/0L7QtNGC0LLQtdGA0LbQtNC10L3QuNGPINGA\n" + "0LXQs9C40YHRgtGA0LDRhtC40Lgg0L3QsCBKVGFsa3Mg0YTQvtGA0YPQvNC1LjwvcD4KPHA+0J/Q\n" + "vtC20LDQu9GD0LnRgdGC0LAsINC/0YDQvtGB0LvQtdC00YPQudGC0LUg0L/QviDRgdGB0YvQu9C6\n" + "0LUg0L3QuNC20LUg0LTQu9GPINCw0LrRgtC40LLQsNGG0LjQuCDQktCw0YjQtdCz0L4g0LDQutC6\n" + "0LDRg9C90YLQsC4g0K3RgtCwINGB0YHRi9C70LrQsCDQtNC10LnRgdGC0LLQuNGC0LXQu9GM0L3Q\n" + "sCAyNCDRh9Cw0YHQsC48L3A+CjxwPtCS0L3QuNC80LDQvdC40LUsINCw0LrQutCw0YPQvdGCINCx\n" + "0YPQtNC10YIg0LDQstGC0L7QvNCw0YLQuNGH0LXRgdC60Lgg0YPQtNCw0LvQtdC9INGH0LXRgNC1\n" + "0LcgMjQg0YfQsNGB0LAsINC10YHQu9C4INC90LUg0LHRg9C00LXRgiDQsNC60YLQuNCy0LjRgNC+\n" + "0LLQsNC9LjwvcD4KPHA+0JDQutGC0LjQstCw0YbQuNC+0L3QvdCw0Y8g0YHRgdGL0LvQutCwOiA8\n" + "YSBocmVmPSJodHRwOi8vYXV0b3Rlc3RzLmp0YWxrcy5vcmc6ODAvamNvbW11bmUvdXNlci9hY3Rp\n" + "dmF0ZS83ODQxNmRmYi1lM2FjLTRkOGEtYWIzMy03OWM4MGQwZjFjMGUiPmh0dHA6Ly9hdXRvdGVz\n" + "dHMuanRhbGtzLm9yZy9qY29tbXVuZS91c2VyL2FjdGl2YXRlLzc4NDE2ZGZiLWUzYWMtNGQ4YS1h\n" + "YjMzLTc5YzgwZDBmMWMwZTwvYT48L3A+CjxiciAvPgo8cD7QoSDQvdCw0LjQu9GD0YfRiNC40LzQ\n" + "uCDQv9C+0LbQtdC70LDQvdC40Y/QvNC4LDwvcD4KPHA+0KTQvtGA0YPQvCBKVGFsa3MuPC9wPg==\n" + "------=_Part_2_1297559663.1422213640047-- \n" + "\n" + "------=_Part_1_2012376838.1422213640046-- \n" + "\n" + "------=_Part_0_980719463.1422213640036-- \n" + "").getBytes("UTF-8")) return MimeMessage(session, stream) }
src/main/kotlin/org/jtalks/pochta/util/SendEmail.kt
3295690209
package org.thoughtcrime.securesms.database import android.database.Cursor import org.signal.core.util.requireLong import org.signal.spinner.ColumnTransformer import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BAD_DECRYPT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_DRAFT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_INBOX_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_OUTBOX_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_PENDING_INSECURE_SMS_FALLBACK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_PENDING_SECURE_SMS_FALLBACK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENDING_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENT_FAILED_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_SENT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BASE_TYPE_MASK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.BOOST_REQUEST_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.CHANGE_NUMBER_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_DUPLICATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_FAILED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_LEGACY_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.ENCRYPTION_REMOTE_NO_SESSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.END_SESSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.EXPIRATION_TIMER_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_LEAVE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_V2_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GROUP_V2_LEAVE_BITS import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.GV1_MIGRATION_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INCOMING_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INCOMING_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.INVALID_MESSAGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.JOINED_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_BUNDLE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_CONTENT_FORMAT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_CORRUPTED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_DEFAULT_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_UPDATE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_IDENTITY_VERIFIED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.KEY_EXCHANGE_INVALID_VERSION_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MESSAGE_FORCE_SMS_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MESSAGE_RATE_LIMITED_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MISSED_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.MISSED_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_AUDIO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_MESSAGE_TYPES import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.OUTGOING_VIDEO_CALL_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.PROFILE_CHANGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.PUSH_MESSAGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SECURE_MESSAGE_BIT import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SMS_EXPORT_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPES_MASK import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_GIFT_BADGE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_ACTIVATED import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_ACTIVATE_REQUEST import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_PAYMENTS_NOTIFICATION import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.SPECIAL_TYPE_STORY_REACTION import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.THREAD_MERGE_TYPE import org.thoughtcrime.securesms.database.MmsSmsColumns.Types.UNSUPPORTED_MESSAGE_TYPE object MessageBitmaskColumnTransformer : ColumnTransformer { override fun matches(tableName: String?, columnName: String): Boolean { return columnName == "type" || columnName == "msg_box" } override fun transform(tableName: String?, columnName: String, cursor: Cursor): String { val type = cursor.requireLong(columnName) val describe = """ isOutgoingMessageType:${isOutgoingMessageType(type)} isForcedSms:${type and MESSAGE_FORCE_SMS_BIT != 0L} isDraftMessageType:${type and BASE_TYPE_MASK == BASE_DRAFT_TYPE} isFailedMessageType:${type and BASE_TYPE_MASK == BASE_SENT_FAILED_TYPE} isPendingMessageType:${type and BASE_TYPE_MASK == BASE_OUTBOX_TYPE || type and BASE_TYPE_MASK == BASE_SENDING_TYPE } isSentType:${type and BASE_TYPE_MASK == BASE_SENT_TYPE} isPendingSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_INSECURE_SMS_FALLBACK || type and BASE_TYPE_MASK == BASE_PENDING_SECURE_SMS_FALLBACK} isPendingSecureSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_SECURE_SMS_FALLBACK} isPendingInsecureSmsFallbackType:${type and BASE_TYPE_MASK == BASE_PENDING_INSECURE_SMS_FALLBACK} isInboxType:${type and BASE_TYPE_MASK == BASE_INBOX_TYPE} isJoinedType:${type and BASE_TYPE_MASK == JOINED_TYPE} isUnsupportedMessageType:${type and BASE_TYPE_MASK == UNSUPPORTED_MESSAGE_TYPE} isInvalidMessageType:${type and BASE_TYPE_MASK == INVALID_MESSAGE_TYPE} isBadDecryptType:${type and BASE_TYPE_MASK == BAD_DECRYPT_TYPE} isSecureType:${type and SECURE_MESSAGE_BIT != 0L} isPushType:${type and PUSH_MESSAGE_BIT != 0L} isEndSessionType:${type and END_SESSION_BIT != 0L} isKeyExchangeType:${type and KEY_EXCHANGE_BIT != 0L} isIdentityVerified:${type and KEY_EXCHANGE_IDENTITY_VERIFIED_BIT != 0L} isIdentityDefault:${type and KEY_EXCHANGE_IDENTITY_DEFAULT_BIT != 0L} isCorruptedKeyExchange:${type and KEY_EXCHANGE_CORRUPTED_BIT != 0L} isInvalidVersionKeyExchange:${type and KEY_EXCHANGE_INVALID_VERSION_BIT != 0L} isBundleKeyExchange:${type and KEY_EXCHANGE_BUNDLE_BIT != 0L} isContentBundleKeyExchange:${type and KEY_EXCHANGE_CONTENT_FORMAT != 0L} isIdentityUpdate:${type and KEY_EXCHANGE_IDENTITY_UPDATE_BIT != 0L} isRateLimited:${type and MESSAGE_RATE_LIMITED_BIT != 0L} isExpirationTimerUpdate:${type and EXPIRATION_TIMER_UPDATE_BIT != 0L} isIncomingAudioCall:${type == INCOMING_AUDIO_CALL_TYPE} isIncomingVideoCall:${type == INCOMING_VIDEO_CALL_TYPE} isOutgoingAudioCall:${type == OUTGOING_AUDIO_CALL_TYPE} isOutgoingVideoCall:${type == OUTGOING_VIDEO_CALL_TYPE} isMissedAudioCall:${type == MISSED_AUDIO_CALL_TYPE} isMissedVideoCall:${type == MISSED_VIDEO_CALL_TYPE} isGroupCall:${type == GROUP_CALL_TYPE} isGroupUpdate:${type and GROUP_UPDATE_BIT != 0L} isGroupV2:${type and GROUP_V2_BIT != 0L} isGroupQuit:${type and GROUP_LEAVE_BIT != 0L && type and GROUP_V2_BIT == 0L} isChatSessionRefresh:${type and ENCRYPTION_REMOTE_FAILED_BIT != 0L} isDuplicateMessageType:${type and ENCRYPTION_REMOTE_DUPLICATE_BIT != 0L} isDecryptInProgressType:${type and 0x40000000 != 0L} isNoRemoteSessionType:${type and ENCRYPTION_REMOTE_NO_SESSION_BIT != 0L} isLegacyType:${type and ENCRYPTION_REMOTE_LEGACY_BIT != 0L || type and ENCRYPTION_REMOTE_BIT != 0L} isProfileChange:${type == PROFILE_CHANGE_TYPE} isGroupV1MigrationEvent:${type == GV1_MIGRATION_TYPE} isChangeNumber:${type == CHANGE_NUMBER_TYPE} isBoostRequest:${type == BOOST_REQUEST_TYPE} isThreadMerge:${type == THREAD_MERGE_TYPE} isSmsExport:${type == SMS_EXPORT_TYPE} isGroupV2LeaveOnly:${type and GROUP_V2_LEAVE_BITS == GROUP_V2_LEAVE_BITS} isSpecialType:${type and SPECIAL_TYPES_MASK != 0L} isStoryReaction:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_STORY_REACTION} isGiftBadge:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_GIFT_BADGE} isPaymentsNotificaiton:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_NOTIFICATION} isRequestToActivatePayments:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_ACTIVATE_REQUEST} isPaymentsActivated:${type and SPECIAL_TYPES_MASK == SPECIAL_TYPE_PAYMENTS_ACTIVATED} """.trimIndent() return "$type<br><br>" + describe.replace(Regex("is[A-Z][A-Za-z0-9]*:false\n?"), "").replace("\n", "<br>") } private fun isOutgoingMessageType(type: Long): Boolean { for (outgoingType in OUTGOING_MESSAGE_TYPES) { if (type and BASE_TYPE_MASK == outgoingType) return true } return false } }
app/src/spinner/java/org/thoughtcrime/securesms/database/MessageBitmaskColumnTransformer.kt
1861637629
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.screens.gamelist import android.view.View import android.widget.Button import androidx.recyclerview.widget.RecyclerView import com.app.playhvz.R class JoinButtonViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val button = view.findViewById<Button>(R.id.join_button) fun onBind(labelId: Int, onClickListener: View.OnClickListener) { button.setText(labelId) button.setOnClickListener(onClickListener) } }
Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/gamelist/JoinButtonViewHolder.kt
3306394192
package misplaced.second class ClassWithMisplacedIdenticalSource {}
kotlin-eclipse-ui-test/testData/navigation/lib/src/misplaced-source-folder/second/misplaced.kt
2177544226
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.egl.templates import org.lwjgl.generator.* import org.lwjgl.egl.* val KHR_stream_fifo = "KHRStreamFIFO".nativeClassEGL("KHR_stream_fifo", postfix = KHR) { documentation = """ Native bindings to the $registryLink extension. This extension allows an EGLStream to operate as a fifo rather than as a mailbox. The EGL_KHR_stream extension defines the EGLStream object. The EGLStream object works like a 1 entry mailbox, allowing the consumer to consume the frame that the producer most recently inserted. If the consumer requests image frames faster than the producer creates them then it gets the most recent one over and over until a new one is inserted. If the producer inserts frames faster than the consumer can consume them then the extra frames are discarded. The producer is never stalled. This extension allows an EGLStream to be placed into fifo mode. In fifo mode no images are discarded. If the producer attempts to insert a frame and the fifo is full then the producer will stall until there is room in the fifo. When the consumer retrieves an image frame from the EGLStream it will see the image frame that immediately follows the image frame that it last retrieved (unless no such frame has been inserted yet in which case it retrieves the same image frame that it retrieved last time). Timing of the EGLStream in mailbox mode, as described by the EGL_KHR_stream extension, is the responsibility of the producer (with help from the consumer in the form of the EGL_CONSUMER_LATENCY_USEC_KHR hint). In contrast, timing of an EGLStream in fifo mode is the responsibility of the consumer. Each image frame in the fifo has an associated timestamp set by the producer. The consumer can use this timestamp to determine when the image frame is intended to be displayed to the user. Requires ${EGL12.core} and ${KHR_stream.link}. """ IntConstant( "", "STREAM_FIFO_LENGTH_KHR"..0x31FC, "STREAM_TIME_NOW_KHR"..0x31FD, "STREAM_TIME_CONSUMER_KHR"..0x31FE, "STREAM_TIME_PRODUCER_KHR"..0x31FF ) EGLBoolean( "QueryStreamTimeKHR", "", EGLDisplay.IN("dpy", ""), EGLStreamKHR.IN("stream", ""), EGLenum.IN("attribute", ""), Check(1)..EGLTimeKHR_p.OUT("value", "") ) }
modules/templates/src/main/kotlin/org/lwjgl/egl/templates/KHR_stream_fifo.kt
313140444
/* * Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.data.checker import android.provider.BaseColumns import org.andstatus.app.data.ActorSql import org.andstatus.app.data.DbUtils import org.andstatus.app.data.MyProvider import org.andstatus.app.database.table.ActorTable import org.andstatus.app.net.social.Actor import org.andstatus.app.user.User import org.andstatus.app.util.MyLog import org.andstatus.app.util.StringUtil import org.andstatus.app.util.TriState import java.util.* import java.util.stream.IntStream /** * @author [email protected] */ internal class CheckUsers : DataChecker() { private class CheckResults { var actorsToMergeUsers: MutableMap<String, MutableSet<Actor>> = HashMap() var usersToSave: MutableSet<User> = HashSet() var actorsWithoutUsers: MutableSet<Actor> = HashSet() var actorsToFixWebFingerId: MutableSet<Actor> = HashSet() var actorsWithoutOrigin: MutableSet<Actor> = HashSet() var problems: MutableList<String> = ArrayList() } override fun fixInternal(): Long { val results = getResults() logResults(results) if (countOnly) return results.problems.size.toLong() var changedCount: Long = 0 for (user in results.usersToSave) { user.save(myContext) changedCount++ } changedCount += results.actorsToMergeUsers.values.stream().mapToLong { actors: MutableSet<Actor> -> mergeUsers(actors) }.sum() for (actor in results.actorsWithoutOrigin) { val parent = actor.getParent() if (parent.nonEmpty) { // The error affects development database only val groupUsername: String = actor.groupType.name + ".of." + parent.getUsername() + "." + parent.actorId val groupTempOid = StringUtil.toTempOid(groupUsername) val sql = "UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.ORIGIN_ID + "=" + parent.origin.id + ", " + ActorTable.USERNAME + "='" + groupUsername + "', " + ActorTable.ACTOR_OID + "='" + groupTempOid + "'" + " WHERE " + BaseColumns._ID + "=" + actor.actorId myContext.database?.execSQL(sql) changedCount++ } else { MyLog.w(this, "Couldn't fix origin for $actor") } } for (actor in results.actorsToFixWebFingerId) { val sql = ("UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.WEBFINGER_ID + "='" + actor.getWebFingerId() + "' WHERE " + BaseColumns._ID + "=" + actor.actorId) myContext.database?.execSQL(sql) changedCount++ } for (actor1 in results.actorsWithoutUsers) { val actor = actor1.lookupUser() actor.saveUser() val sql = ("UPDATE " + ActorTable.TABLE_NAME + " SET " + ActorTable.USER_ID + "=" + actor.user.userId + " WHERE " + BaseColumns._ID + "=" + actor.actorId) myContext.database?.execSQL(sql) changedCount++ } return changedCount } private fun logResults(results: CheckResults) { if (results.problems.isEmpty()) { MyLog.d(this, "No problems found") return } MyLog.i(this, "Problems found: " + results.problems.size) IntStream.range(0, results.problems.size) .mapToObj { i: Int -> (i + 1).toString() + ". " + results.problems[i] } .forEachOrdered { s: String? -> MyLog.i(this, s) } } private fun getResults(): CheckResults { val results = CheckResults() val sql = ("SELECT " + ActorSql.selectFullProjection() + " FROM " + ActorSql.tables(isFullProjection = true, userOnly = false, userIsOptional = true) + " ORDER BY " + ActorTable.WEBFINGER_ID + " COLLATE NOCASE") var rowsCount: Long = 0 MyLog.v(this) { sql } myContext.database?.rawQuery(sql, null).use { c -> var key = "" var actors: MutableSet<Actor> = HashSet() while (c?.moveToNext() == true) { rowsCount++ val actor: Actor = Actor.fromCursor(myContext, c, false) val webFingerId = DbUtils.getString(c, ActorTable.WEBFINGER_ID) if (actor.isWebFingerIdValid() && actor.getWebFingerId() != webFingerId) { results.actorsToFixWebFingerId.add(actor) results.problems.add("Fix webfingerId: '$webFingerId' $actor") } if (myContext.accounts.fromWebFingerId(actor.getWebFingerId()).isValid && actor.user.isMyUser.untrue ) { actor.user.isMyUser = TriState.TRUE results.usersToSave.add(actor.user) results.problems.add("Fix user isMy: $actor") } else if (actor.user.userId == 0L) { results.actorsWithoutUsers.add(actor) results.problems.add("Fix userId==0: $actor") } if (actor.origin.isEmpty) { results.actorsWithoutOrigin.add(actor) results.problems.add("Fix no Origin: $actor") } if (key.isEmpty() || actor.getWebFingerId() != key) { if (shouldMerge(actors)) { results.actorsToMergeUsers[key] = actors results.problems.add("Fix merge users 1 \"$key\": $actors") } key = actor.getWebFingerId() actors = HashSet() } actors.add(actor) } if (shouldMerge(actors)) { results.actorsToMergeUsers[key] = actors results.problems.add("Fix merge users 2 \"$key\": $actors") } } logger.logProgress("Check completed, " + rowsCount + " actors checked." + " Users of actors to be merged: " + results.actorsToMergeUsers.size + ", to fix WebfingerId: " + results.actorsToFixWebFingerId.size + ", to add users: " + results.actorsWithoutUsers.size + ", to save users: " + results.usersToSave.size ) return results } private fun shouldMerge(actors: MutableSet<Actor>): Boolean { return actors.size > 1 && (actors.stream().anyMatch { a: Actor -> a.user.userId == 0L } || actors.stream().mapToLong { a: Actor -> a.user.userId }.distinct().count() > 1) } private fun mergeUsers(actors: MutableSet<Actor>): Long { val userWith = actors.stream().map { a: Actor -> a.user }.reduce { a: User, b: User -> if (a.userId < b.userId) a else b } .orElse(User.EMPTY) return if (userWith.userId == 0L) 0 else actors.stream().map { actor: Actor -> val logMsg = "Linking $actor with $userWith" if (logger.loggedMoreSecondsAgoThan(5)) logger.logProgress(logMsg) MyProvider.update(myContext, ActorTable.TABLE_NAME, ActorTable.USER_ID + "=" + userWith.userId, BaseColumns._ID + "=" + actor.actorId ) if (actor.user.userId != 0L && actor.user.userId != userWith.userId && userWith.isMyUser.isTrue) { actor.user.isMyUser = TriState.FALSE actor.user.save(myContext) } 1 }.count() } }
app/src/main/kotlin/org/andstatus/app/data/checker/CheckUsers.kt
2199803004
package io.github.crabzilla.stack import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import java.util.* /** * An event record */ data class EventRecord(val metadata: EventMetadata, val payload: JsonObject) { companion object { fun List<EventRecord>.toJsonArray() = JsonArray(this.map { it.toJsonObject() }) fun fromJsonObject(asJsonObject: JsonObject): EventRecord { val eventMetadata = EventMetadata( asJsonObject.getString("stateType"), UUID.fromString(asJsonObject.getString("stateId")), UUID.fromString(asJsonObject.getString("eventId")), UUID.fromString(asJsonObject.getString("correlationId")), UUID.fromString(asJsonObject.getString("causationId")), asJsonObject.getLong("eventSequence"), asJsonObject.getInteger("version"), asJsonObject.getString("eventType") ) return EventRecord(eventMetadata, asJsonObject.getJsonObject("eventPayload")) } } fun toJsonObject(): JsonObject { return metadata.toJsonObject() .put("eventPayload", payload) } fun extract() = Triple(payload, metadata, metadata.stateId) }
crabzilla-stack/src/main/kotlin/io/github/crabzilla/stack/EventRecord.kt
1708658864
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.test.completion class ParsingTest : TestCompletionBase() { fun `test parse chinese non-java characters`() { doTest(""" --- test_parse_chinese_characters.lua ---@class 类型1 local 对象 = { 名字 = "name" } ---@return number, 类型1 local function 获得一个什么东西(一)() end local 鬼知道我是什么, 天晓得我是什么 = 获得一个什么东西(一)() 天晓得我是什么.--[[caret]] """) { assertTrue("名字" in it) } } }
src/test/kotlin/com/tang/intellij/test/completion/ParsingTest.kt
2733887407
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.reporting import com.mycollab.core.MyCollabException import com.mycollab.core.utils.DateTimeUtils import net.sf.dynamicreports.report.builder.DynamicReports.cmp import net.sf.dynamicreports.report.builder.DynamicReports.hyperLink import net.sf.dynamicreports.report.builder.component.ComponentBuilder import net.sf.dynamicreports.report.constant.HorizontalTextAlignment import net.sf.dynamicreports.report.exception.DRException import org.slf4j.LoggerFactory import java.io.* import java.time.LocalDateTime import java.time.ZoneId import java.util.* import java.util.concurrent.CountDownLatch /** * @author MyCollab Ltd * @since 5.1.4 */ abstract class ReportTemplateExecutor(protected var timeZone: ZoneId, protected var locale: Locale, protected var reportTitle: String, protected var outputForm: ReportExportType) { lateinit var parameters: MutableMap<String, Any> protected var reportStyles: ReportStyles = ReportStyles.instance() val defaultExportFileName: String get() = outputForm.defaultFileName @Throws(Exception::class) abstract fun initReport() @Throws(DRException::class) abstract fun fillReport() @Throws(IOException::class, DRException::class) abstract fun outputReport(outputStream: OutputStream) protected fun defaultTitleComponent(): ComponentBuilder<*, *> { val link = hyperLink("https://www.mycollab.com") val dynamicReportsComponent = cmp.horizontalList( cmp.image(ReportTemplateExecutor::class.java.classLoader.getResourceAsStream("images/logo.png")) .setFixedDimension(150, 28), cmp.horizontalGap(20), cmp.verticalList( cmp.text("https://www.mycollab.com").setStyle(reportStyles.italicStyle).setHyperLink(link) .setHorizontalTextAlignment(HorizontalTextAlignment.RIGHT), cmp.text("Generated at: ${DateTimeUtils.formatDate(LocalDateTime.now(), "yyyy-MM-dd'T'HH:mm:ss", Locale.US, timeZone)}") .setHorizontalTextAlignment(HorizontalTextAlignment.RIGHT)) ) return cmp.horizontalList().add(dynamicReportsComponent).newRow().add(reportStyles.line()).newRow().add(cmp.verticalGap(10)) } fun exportStream(): InputStream { val latch = CountDownLatch(1) val inStream = PipedInputStream() val `in` = object : InputStream() { @Throws(IOException::class) override fun read(b: ByteArray): Int { return inStream.read(b) } @Throws(IOException::class) override fun read(): Int { return inStream.read() } @Throws(IOException::class) override fun close() { super.close() latch.countDown() } } val outputStream = PipedOutputStream() Thread(Runnable { val out = object : OutputStream() { @Throws(IOException::class) override fun write(b: Int) { outputStream.write(b) } @Throws(IOException::class) override fun close() { while (latch.count != 0L) { try { latch.await() } catch (e: InterruptedException) { e.printStackTrace() break } } super.close() } } try { parameters = parameters initReport() fillReport() outputReport(out) } catch (e: Exception) { LOG.error("Error report", e) } finally { try { outputStream.close() out.close() } catch (e: IOException) { LOG.error("Try to close reporting stream error", e) } } }).start() try { outputStream.connect(inStream) } catch (e: IOException) { throw MyCollabException(e) } return `in` } companion object { private val LOG = LoggerFactory.getLogger(ReportTemplateExecutor::class.java) } }
mycollab-reporting/src/main/java/com/mycollab/reporting/ReportTemplateExecutor.kt
259567419
package org.wordpress.aztec.spans class AztecCursorSpan { companion object { val AZTEC_CURSOR_TAG = "aztec_cursor" } }
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecCursorSpan.kt
1981046576
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.codeInsight.inspection import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.tang.intellij.lua.Constants import com.tang.intellij.lua.psi.LuaLiteralExpr import com.tang.intellij.lua.psi.LuaLocalDef import com.tang.intellij.lua.psi.LuaVisitor import org.jetbrains.annotations.Nls /** * * Created by tangzx on 2016/12/16. */ class SimplifyLocalAssignment : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : LuaVisitor() { override fun visitLocalDef(o: LuaLocalDef) { val exprList = o.exprList if (exprList != null) { val list = exprList.exprList if (list.size == 1) { val expr = list[0] if (expr is LuaLiteralExpr && Constants.WORD_NIL == expr.getText()) { holder.registerProblem(expr, "Local assignment can be simplified", ProblemHighlightType.LIKE_UNUSED_SYMBOL, Fix()) } } } } } } inner class Fix : LocalQuickFix { @Nls override fun getFamilyName(): String { return "Simplify local assignment" } override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) { val localDef = PsiTreeUtil.getParentOfType(problemDescriptor.endElement, LuaLocalDef::class.java) val assign = localDef?.assign val exprList = localDef?.exprList if (localDef != null && assign != null && exprList != null) localDef.deleteChildRange(assign, exprList) } } }
src/main/java/com/tang/intellij/lua/codeInsight/inspection/SimplifyLocalAssignment.kt
3636646184
package y2k.joyreactor import android.os.Bundle import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import y2k.joyreactor.common.* import y2k.joyreactor.viewmodel.MainViewModel import y2k.joyreactor.viewmodel.MenuViewModel import y2k.joyreactor.widget.TagComponent class MainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initPostList() initTagList() } private fun initPostList() { find<RecyclerView>(R.id.list).apply { addItemDecoration(ItemDividerDecoration(this)) } val vm = ServiceLocator.resolve<MainViewModel>(lifeCycleService) bindingBuilder(this) { spinnerTemp(R.id.tabs, vm.quality) visibility(R.id.apply, vm.hasNewPosts) visibility(R.id.error, vm.isError) command(R.id.apply) { vm.applyNew() } refreshLayout(R.id.refresher) { isRefreshing(vm.isBusy) command { vm.reloadFirstPage() } } bind(R.id.list, vm.posts) command(R.id.list, "commandLoadMore") { vm.loadMore() } menu(R.menu.main) { command(R.id.profile) { vm.openProfile() } command(R.id.messages) { vm.openMessages() } command(R.id.addTag) { vm.openAddTag() } command(R.id.feedback) { vm.openFeedback() } } } } private fun initTagList() { val vm = ServiceLocator.resolve<MenuViewModel>(lifeCycleService) bindingBuilder(this) { viewResolver(R.id.listTags) command(R.id.selectFeatured, { vm.selectedFeatured() }) command(R.id.selectFavorite, { vm.selectedFavorite() }) recyclerView(R.id.listTags, vm.tags) { itemId { it.id } component { TagComponent(context) { vm.selectTag(it) } } } } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) val toolbar = findViewById(R.id.toolbar) as Toolbar toolbar.title = "" setSupportActionBar(toolbar) ActionBarDrawerToggle(this, findViewById(R.id.drawer_layout) as DrawerLayout, toolbar, R.string.app_name, R.string.app_name).syncState() } }
android/src/main/kotlin/y2k/joyreactor/MainActivity.kt
738454842
package com.siimkinks.sqlitemagic.task import com.siimkinks.sqlitemagic.annotation.internal.Invokes import javassist.CtClass import javassist.CtMethod import javassist.bytecode.annotation.Annotation import org.gradle.api.file.FileCollection import org.gradle.api.logging.Logging import java.io.File class InvokeTransformation( destinationDir: File, sources: FileCollection, classpath: FileCollection, debug: Boolean = false ) : BaseTransformation(destinationDir, sources, classpath, debug) { private val METHOD_ANNOTATIONS = setOf<String>(Invokes::class.java.canonicalName) override val LOG = Logging.getLogger(InvokeTransformation::class.java) override fun shouldTransform(candidateClass: CtClass): Boolean { return candidateClass.methods.any { it.hasAnyAnnotationFrom(METHOD_ANNOTATIONS) } } override fun applyTransform(clazz: CtClass) { logInfo("Transforming ${clazz.name}") clazz.methods.forEach { val invokes = it.findAnnotation(Invokes::class.java) if (invokes != null) { handleInvocation(clazz, it, invokes) } } } private fun handleInvocation(clazz: CtClass, method: CtMethod, invokesAnnotation: Annotation) { val value = invokesAnnotation.getAnnotationElementValue(ANNOTATION_VALUE_NAME) ?: return val pos = value.indexOf("#") val targetMethod = value.substring(pos + 1) val targetClass = value.substring(0, pos) logInfo("Invoker ${method.name} invokes targetMethod $targetMethod of class $targetClass") try { val body = StringBuilder() val returnType = method.returnType if (!returnType.name.equals("void", ignoreCase = true)) { body.append("return ") } body.append(targetClass) body.append('.') body.append(targetMethod) body.append('(') if (invokesAnnotation.getAnnotationElementValue("useThisAsOnlyParam")?.toBoolean() == true) { body.append("this") } else { body.append("$$") } body.append(");") method.setBody(body.toString()) } catch (e: Throwable) { val errMsg = e.message if (errMsg != null && errMsg.contains("class is frozen")) { logInfo("Not transforming frozen class ${clazz.name}; errMsg=$errMsg") } else { logError("Transformation failed for class ${clazz.name}", e) } } } }
gradle-plugin/src/main/kotlin/com/siimkinks/sqlitemagic/task/InvokeTransformation.kt
1003518958
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.newsfeed.dto import com.google.gson.annotations.SerializedName import kotlin.String import kotlin.collections.List /** * @param text - Question text, that appears under two posts. E.g. "Which one do you like better?" * @param nextButtonText * @param answers * @param entries * @param buttonText */ data class NewsfeedItemFeedbackPollQuestion( @SerializedName("text") val text: String, @SerializedName("next_button_text") val nextButtonText: String, @SerializedName("answers") val answers: List<NewsfeedItemFeedbackPollQuestionAnswer>, @SerializedName("entries") val entries: List<NewsfeedItemFeedbackPollQuestionEntry>, @SerializedName("button_text") val buttonText: String? = null )
api/src/main/java/com/vk/sdk/api/newsfeed/dto/NewsfeedItemFeedbackPollQuestion.kt
3573653013
package com.naosim.rpglib.model.value.field import com.naosim.rpglib.model.viewmodel.sound.bgm.HasBGM class Field( val fieldName: FieldName, val hasBGM: HasBGM? = null, private val backFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData, private val frontFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData? = null ) { constructor(fieldName: FieldName, backFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData, frontFieldDataAndFieldCollisionData: FieldDataAndFieldCollisionData? = null) : this(fieldName, null, backFieldDataAndFieldCollisionData, frontFieldDataAndFieldCollisionData) val backFieldLayer = FieldLayer(fieldName, FieldLayerNameType.back, backFieldDataAndFieldCollisionData) val frontFieldLayer: FieldLayer? = if(frontFieldDataAndFieldCollisionData != null) { FieldLayer(fieldName, FieldLayerNameType.front, frontFieldDataAndFieldCollisionData) } else { null } }
rpglib/src/main/kotlin/com/naosim/rpglib/model/value/field/Field.kt
985634983
package pl.shockah.godwit.test.desktop import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration import pl.shockah.godwit.GodwitApplication import pl.shockah.godwit.desktop.PlatformProviders class TestStarter { companion object { @Suppress("UNCHECKED_CAST") @JvmStatic fun main(args: Array<String>) { val config = Lwjgl3ApplicationConfiguration() val adapter = (Class.forName(args[0]) as Class<out GodwitApplication>).newInstance() PlatformProviders.register(adapter) Lwjgl3Application(adapter, config) } } }
test-desktop/src/pl/shockah/godwit/test/desktop/TestStarter.kt
2306086861
package com.andremion.counterfab.sample.helpers import android.os.Bundle import androidx.test.runner.AndroidJUnitRunner import com.facebook.testing.screenshot.ScreenshotRunner class ScreenshotTestRunner : AndroidJUnitRunner() { override fun onCreate(arguments: Bundle) { ScreenshotRunner.onCreate(this, arguments) super.onCreate(arguments) } override fun finish(resultCode: Int, results: Bundle) { ScreenshotRunner.onDestroy() super.finish(resultCode, results) } }
sample/src/androidTest/java/com/andremion/counterfab/sample/helpers/ScreenshotTestRunner.kt
2772297455
package com.intfocus.template.model import android.content.Context import android.database.sqlite.SQLiteDatabase import com.intfocus.template.model.gen.* /** * @author liuruilin * @data 2017/11/5 * @describe */ object DaoUtil { private var daoSession: DaoSession? = null private var database: SQLiteDatabase? = null /** * 初始化数据库 * 建议放在Application中执行 */ fun initDataBase(context: Context) { //通过DaoMaster的内部类DevOpenHelper,可得到一个SQLiteOpenHelper对象。 val devOpenHelper = DaoMaster.DevOpenHelper(context, "shengyiplus.db", null) //数据库名称 database = devOpenHelper.writableDatabase val daoMaster = DaoMaster(database) daoSession = daoMaster.newSession() } fun getDaoSession(): DaoSession? = daoSession fun getDatabase(): SQLiteDatabase? = database fun getSourceDao(): SourceDao = daoSession!!.sourceDao fun getCollectionDao(): CollectionDao = daoSession!!.collectionDao fun getReportDao(): ReportDao = daoSession!!.reportDao fun getPushMsgDao(): PushMsgBeanDao = daoSession!!.pushMsgBeanDao fun getAttentionItemDao(): AttentionItemDao = daoSession!!.attentionItemDao }
app/src/main/java/com/intfocus/template/model/DaoUtil.kt
3257790205
package com.intfocus.template.model.response.mine_page /** * Created by liuruilin on 2017/8/11. */ class UserInfo { var user_num: String? = null var user_name: String? = null var gravatar: String? = null var group_name: String? = null var role_name: String? = null var login_duration: String? = null var browse_report_count: String? = null var surpass_percentage: Double = 0.toDouble() var login_count: String? = null var browse_count: String? = null var coordinate_location: String? = null var browse_distinct_count: String? = null }
app/src/main/java/com/intfocus/template/model/response/mine_page/UserInfo.kt
784366976
package cz.richter.david.astroants.model import com.fasterxml.jackson.annotation.JsonProperty data class Astroants( @JsonProperty("x") val x: Int, @JsonProperty("y") val y: Int )
src/main/kotlin/cz/richter/david/astroants/model/Astroants.kt
1348757212
package de.gesellix.docker.compose.types data class ExtraHosts( val entries: HashMap<String, String> = hashMapOf() )
src/main/kotlin/de/gesellix/docker/compose/types/ExtraHosts.kt
1781196814
package com.reactnativenavigation.viewcontrollers.navigator import android.app.Activity import androidx.coordinatorlayout.widget.CoordinatorLayout import com.facebook.react.ReactInstanceManager import com.reactnativenavigation.BaseTest import com.reactnativenavigation.TestActivity import com.reactnativenavigation.hierarchy.root.RootAnimator import com.reactnativenavigation.mocks.SimpleViewController import com.reactnativenavigation.options.* import com.reactnativenavigation.options.params.Bool import com.reactnativenavigation.react.CommandListenerAdapter import com.reactnativenavigation.viewcontrollers.child.ChildControllersRegistry import com.reactnativenavigation.viewcontrollers.viewcontroller.LayoutDirectionApplier import com.reactnativenavigation.viewcontrollers.viewcontroller.RootPresenter import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController import com.reactnativenavigation.views.BehaviourDelegate import org.assertj.core.api.Java6Assertions import org.junit.Test import org.mockito.ArgumentCaptor import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.never import org.robolectric.android.controller.ActivityController class RootPresenterTest : BaseTest() { private lateinit var uut: RootPresenter private lateinit var rootContainer: CoordinatorLayout private lateinit var root: ViewController<*> private lateinit var root2: ViewController<*> private lateinit var animator: RootAnimator private lateinit var layoutDirectionApplier: LayoutDirectionApplier private lateinit var defaultOptions: Options private lateinit var reactInstanceManager: ReactInstanceManager private lateinit var activity: Activity private lateinit var activityController: ActivityController<TestActivity> private lateinit var root1View: SimpleViewController.SimpleView private lateinit var root2View: SimpleViewController.SimpleView override fun beforeEach() { activityController = newActivityController(TestActivity::class.java) activity = activityController.create().get() reactInstanceManager = Mockito.mock(ReactInstanceManager::class.java) rootContainer = CoordinatorLayout(activity) root1View = SimpleViewController.SimpleView(activity) root2View = SimpleViewController.SimpleView(activity) root = object : SimpleViewController(activity, ChildControllersRegistry(), "child1", Options()) { override fun createView(): SimpleView { return root1View } } root2 = object : SimpleViewController(activity, ChildControllersRegistry(), "child1", Options()) { override fun createView(): SimpleView { return root2View } } setupWithAnimator(Mockito.spy(createAnimator())) } @Test fun setRoot_viewIsAddedToContainer() { uut.setRoot(root, null, defaultOptions, CommandListenerAdapter(), reactInstanceManager) Java6Assertions.assertThat(root.view.parent).isEqualTo(rootContainer) Java6Assertions.assertThat((root.view.layoutParams as CoordinatorLayout.LayoutParams).behavior).isInstanceOf(BehaviourDelegate::class.java) } @Test fun setRoot_reportsOnSuccess() { val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(root, null, defaultOptions, listener, reactInstanceManager) Mockito.verify(listener).onSuccess(root.id) } @Test fun setRoot_doesNotAnimateByDefault() { val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(root, null, defaultOptions, listener, reactInstanceManager) Mockito.verifyNoInteractions(animator) Mockito.verify(listener).onSuccess(root.id) } @Test fun setRoot_playNoAnimationWhenOptionsHaveThemDisabled() { setupWithAnimator(RootAnimator()) val animatedSetRoot = Options() val enter = Mockito.spy(AnimationOptions()) val exit = Mockito.spy(AnimationOptions()) enter.enabled = Bool(false) exit.enabled = Bool(false) Mockito.`when`(enter.hasValue()).thenReturn(true) Mockito.`when`(enter.hasAnimation()).thenReturn(true) Mockito.`when`(exit.hasValue()).thenReturn(true) Mockito.`when`(exit.hasValue()).thenReturn(true) animatedSetRoot.animations.setRoot = createEnterExitTransitionAnim(enter, exit) val spy = Mockito.spy(root) val spy2 = Mockito.spy(root2) Mockito.`when`(spy.resolveCurrentOptions(defaultOptions)).thenReturn(animatedSetRoot) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, spy2, defaultOptions, listener, reactInstanceManager) Mockito.verify(enter, never()).getAnimation(spy.view) Mockito.verify(exit, never()).getAnimation(spy2.view) } @Test fun setRoot_playEnterAnimOnlyWhenNoDisappearingView() { setupWithAnimator(RootAnimator()) val animatedSetRoot = Options() val enter = Mockito.spy(AnimationOptions()) val exit = Mockito.spy(AnimationOptions()) Mockito.`when`(enter.hasValue()).thenReturn(true) Mockito.`when`(enter.hasAnimation()).thenReturn(true) Mockito.`when`(exit.hasValue()).thenReturn(false) animatedSetRoot.animations.setRoot = createEnterExitTransitionAnim(enter, exit) val spy = Mockito.spy(root) Mockito.`when`(spy.resolveCurrentOptions(defaultOptions)).thenReturn(animatedSetRoot) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, null, defaultOptions, listener, reactInstanceManager) Mockito.verify(enter).getAnimation(spy.view) Mockito.verify(exit, never()).getAnimation(spy.view) } @Test fun setRoot_playExitAnimOnlyWhenNoEnterAnimation() { setupWithAnimator(RootAnimator()) val animatedSetRoot = Options() val enter = Mockito.spy(AnimationOptions()) val exit = Mockito.spy(AnimationOptions()) Mockito.`when`(enter.hasValue()).thenReturn(false) Mockito.`when`(enter.hasAnimation()).thenReturn(false) Mockito.`when`(exit.hasValue()).thenReturn(true) Mockito.`when`(exit.hasAnimation()).thenReturn(true) animatedSetRoot.animations.setRoot = createEnterExitTransitionAnim(enter, exit) val spy = Mockito.spy(root) val spy2 = Mockito.spy(root2) Mockito.`when`(spy.resolveCurrentOptions(defaultOptions)).thenReturn(animatedSetRoot) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, spy2, defaultOptions, listener, reactInstanceManager) Mockito.verify(enter, never()).getAnimation(spy.view) Mockito.verify(exit).getAnimation(spy2.view) } @Test fun setRoot_playEnterExitAnimOnBothViews() { setupWithAnimator(RootAnimator()) val animatedSetRoot = Options() val enter = Mockito.spy(AnimationOptions()) val exit = Mockito.spy(AnimationOptions()) Mockito.`when`(enter.hasValue()).thenReturn(true) Mockito.`when`(enter.hasAnimation()).thenReturn(true) Mockito.`when`(exit.hasValue()).thenReturn(true) Mockito.`when`(exit.hasAnimation()).thenReturn(true) animatedSetRoot.animations.setRoot = createEnterExitTransitionAnim(enter, exit) val spy = Mockito.spy(root) val spy2 = Mockito.spy(root2) Mockito.`when`(spy.resolveCurrentOptions(defaultOptions)).thenReturn(animatedSetRoot) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, spy2, defaultOptions, listener, reactInstanceManager) Mockito.verify(enter).getAnimation(spy.view) Mockito.verify(exit).getAnimation(spy2.view) } @Test fun setRoot_animates() { val animatedSetRoot = Options() val enter = Mockito.spy(AnimationOptions()) Mockito.`when`(enter.hasValue()).thenReturn(true) Mockito.`when`(enter.hasAnimation()).thenReturn(true) animatedSetRoot.animations.setRoot = createEnterTransitionAnim(enter) val spy = Mockito.spy(root) Mockito.`when`(spy.resolveCurrentOptions(defaultOptions)).thenReturn(animatedSetRoot) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, null, defaultOptions, listener, reactInstanceManager) Mockito.verify(listener).onSuccess(spy.id) Mockito.verify(animator).setRoot(eq(spy), eq(null), eq(animatedSetRoot.animations.setRoot), any()) } @Test fun setRoot_waitForRenderIsSet() { root.options.animations.setRoot.enter.waitForRender = Bool(true) val spy = Mockito.spy(root) uut.setRoot(spy, null, defaultOptions, CommandListenerAdapter(), reactInstanceManager) val captor = ArgumentCaptor.forClass(Bool::class.java) Mockito.verify(spy).setWaitForRender(captor.capture()) Java6Assertions.assertThat(captor.value.get()).isTrue() } @Test fun setRoot_waitForRender() { root.options.animations.setRoot.enter.waitForRender = Bool(true) val spy = Mockito.spy(root) val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(spy, null, defaultOptions, listener, reactInstanceManager) Mockito.verify(spy).addOnAppearedListener(any()) Java6Assertions.assertThat(spy.view.alpha).isZero() Mockito.verifyNoInteractions(listener) spy.onViewWillAppear() idleMainLooper() Java6Assertions.assertThat(spy.view.alpha).isOne() Mockito.verify(listener).onSuccess(spy.id) } @Test fun setRoot_appliesLayoutDirection() { val listener = Mockito.spy(CommandListenerAdapter()) uut.setRoot(root, null, defaultOptions, listener, reactInstanceManager) Mockito.verify(layoutDirectionApplier).apply(root, defaultOptions, reactInstanceManager) } private fun createAnimator(): RootAnimator { return object : RootAnimator() { override fun setRoot(appearing: ViewController<*>, disappearing: ViewController<*>?, setRoot: TransitionAnimationOptions, onAnimationEnd: () -> Unit) { super.setRoot(appearing, disappearing, setRoot, onAnimationEnd) } } } private fun createEnterExitTransitionAnim(enter: AnimationOptions, exit: AnimationOptions): TransitionAnimationOptions { return TransitionAnimationOptions(enter, exit, SharedElements(), ElementTransitions()) } private fun createEnterTransitionAnim(enter: AnimationOptions): TransitionAnimationOptions { return createEnterExitTransitionAnim(enter, AnimationOptions()) } private fun createExitTransitionAnim(exit: AnimationOptions): TransitionAnimationOptions { return createEnterExitTransitionAnim(AnimationOptions(), exit) } private fun setupWithAnimator(rootAnimator: RootAnimator) { animator = rootAnimator layoutDirectionApplier = Mockito.mock(LayoutDirectionApplier::class.java) uut = RootPresenter(animator, layoutDirectionApplier) uut.setRootContainer(rootContainer) defaultOptions = Options() } }
lib/android/app/src/test/java/com/reactnativenavigation/viewcontrollers/navigator/RootPresenterTest.kt
2907581295
package chat.willow.hopper.auth import java.security.NoSuchAlgorithmException import java.security.spec.InvalidKeySpecException import java.util.* import javax.crypto.SecretKeyFactory import javax.crypto.spec.PBEKeySpec typealias EncodedEntry = String interface IPbdfk2HmacSha512PasswordStorage { fun deriveKey(plaintext: String, salt: String, iterations: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_ITERATIONS, keyLengthBits: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_KEY_LENGTH_BITS): ByteArray? fun encode(salt: String, computedHash: ByteArray, iterations: Int = Pbdfk2HmacSha512PasswordStorage.DEFAULT_ITERATIONS): EncodedEntry? fun decode(encodedEntry: EncodedEntry): Pbdfk2HmacSha512PasswordStorage.DecodedEntry? } object Pbdfk2HmacSha512PasswordStorage: IPbdfk2HmacSha512PasswordStorage { val DEFAULT_ITERATIONS = 64000 val DEFAULT_KEY_LENGTH_BITS = 256 private val BITS_IN_A_BYTE = 8 private val MIN_ITERATIONS = 10000 private val MAX_ITERATIONS = 1000000 private val MIN_SALT_LENGTH = 8 private val MAX_SALT_LENGTH = 256 private val MIN_PLAINTEXT_LENGTH = 8 private val MAX_PLAINTEXT_LENGTH = 256 private val MIN_ENCODED_HASH_SANITY = 8 override fun deriveKey(plaintext: String, salt: String, iterations: Int, keyLengthBits: Int): ByteArray? { if (plaintext.length < MIN_PLAINTEXT_LENGTH || plaintext.length > MAX_PLAINTEXT_LENGTH) { return null } if (salt.length < MIN_SALT_LENGTH || salt.length > MAX_SALT_LENGTH) { return null } if (iterations < MIN_ITERATIONS || iterations > MAX_ITERATIONS) { return null } try { // TODO: Extract and make testable by wrapping SKF stuff val skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") val spec = PBEKeySpec(plaintext.toCharArray(), salt.toByteArray(charset = Charsets.UTF_8), iterations, keyLengthBits) val key = skf.generateSecret(spec) if (key.encoded.isEmpty()) { return null } return key.encoded } catch (e: NoSuchAlgorithmException) { return null } catch (e: InvalidKeySpecException) { return null } } // algorithm:iterations:hashSize:salt:hash // 1:64000:hashsizebits:salt:hash override fun encode(salt: String, computedHash: ByteArray, iterations: Int): String? { if (computedHash.isEmpty()) { return null } if (salt.contains(':')) { return null } val encodedHash = Base64.getEncoder().encodeToString(computedHash) return "1:$iterations:${computedHash.size * BITS_IN_A_BYTE}:$salt:$encodedHash" } override fun decode(encodedEntry: String): DecodedEntry? { val parts = encodedEntry.split(':', limit = 5) if (parts.any { it.contains(":") } || parts.size != 5) { return null } val iterations = parts.getOrNull(1)?.toIntOrNull() ?: return null val hashSize = parts.getOrNull(2)?.toIntOrNull() ?: return null val salt = parts.getOrNull(3) ?: return null val encodedHash = parts.getOrNull(4) ?: return null if (salt.length < MIN_SALT_LENGTH || salt.length > MAX_SALT_LENGTH) { return null } if (iterations < MIN_ITERATIONS || iterations > MAX_ITERATIONS) { return null } if (encodedHash.length < MIN_ENCODED_HASH_SANITY) { return null } return DecodedEntry(encodedHash, iterations, hashSize, salt) } private fun extractFrom(parts: List<String>, index: Int): Int? { val part: String = parts.getOrNull(index) ?: return null return part.toIntOrNull() } data class DecodedEntry(val derivedKeyHash: String, val iterations: Int, val hashSize: Int, val salt: String) }
src/main/kotlin/chat/willow/hopper/auth/Pbdfk2HmacSha512PasswordStorage.kt
4038516742
/* * Copyright (C) 2018-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.existdb.query.rest import com.intellij.openapi.vfs.VirtualFile import org.jsoup.Jsoup import uk.co.reecedunn.intellij.plugin.core.xml.dom.XmlDocument import uk.co.reecedunn.intellij.plugin.processor.debug.frame.VirtualFileStackFrame import uk.co.reecedunn.intellij.plugin.processor.query.QueryError import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModuleUri @Suppress("RegExpAnonymousGroup") private val RE_EXISTDB_MESSAGE = "^(exerr:ERROR )?(org.exist.xquery.XPathException: )?([^ ]+) (.*)\n?$".toRegex() @Suppress("RegExpAnonymousGroup") private val RE_EXISTDB_LOCATION = "^line ([0-9]+), column ([0-9]+).*$".toRegex() fun String.toEXistDBQueryError(queryFile: VirtualFile): QueryError = when { this.startsWith("<html>") -> parseMessageHtml() else -> this.parseMessageXml(queryFile) } private fun String.parseMessageHtml(): QueryError { val html = Jsoup.parse(this) return QueryError( standardCode = "FOER0000", vendorCode = null, description = html.select("title").text(), value = listOf(), frames = listOf() ) } private fun String.parseMessageXml(queryFile: VirtualFile): QueryError { val xml = XmlDocument.parse(this, mapOf()) val messageText = xml.root.children("message").first().text()!!.split("\n")[0] val parts = RE_EXISTDB_MESSAGE.matchEntire(messageText)?.groupValues ?: throw RuntimeException("Cannot parse eXist-db error message: $messageText") val locationParts = RE_EXISTDB_LOCATION.matchEntire(parts[4].substringAfter(" [at "))?.groupValues val path = xml.root.children("path").first().text() val line = locationParts?.get(1)?.toIntOrNull() ?: 1 val col = locationParts?.get(2)?.toIntOrNull() ?: 1 val frame = when (path) { null, "/db" -> VirtualFileStackFrame(queryFile, line - 1, col - 1) else -> VirtualFileStackFrame(XpmModuleUri(queryFile, path), line - 1, col - 1) } return QueryError( standardCode = (parts[3].let { if (it == "Type:") null else it } ?: "FOER0000").replace("^err:".toRegex(), ""), vendorCode = null, description = parts[4].substringBefore(" [at "), value = listOf(), frames = listOf(frame) ) }
src/plugin-existdb/main/uk/co/reecedunn/intellij/plugin/existdb/query/rest/EXistDBQueryError.kt
537754745
/* * Copyright (C) 2016, 2018-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xdm.resources import com.intellij.AbstractBundle import org.jetbrains.annotations.PropertyKey object XdmBundle : AbstractBundle("messages.XdmBundle") { fun message(@PropertyKey(resourceBundle = "messages.XdmBundle") key: String, vararg params: Any): String { return getMessage(key, *params) } }
src/lang-xdm/main/uk/co/reecedunn/intellij/plugin/xdm/resources/XdmBundle.kt
3761565835
package org.dictat.wikistat.model import java.util.Date import com.fasterxml.jackson.annotation.JsonProperty /** * A nova is an exceptional (over-average) behavior of a page. */ public data class Nova { JsonProperty("s") var start: Date? = null JsonProperty("e") var end: Date? = null JsonProperty("n") var novaType: NovaType? = null JsonProperty("l") var lang: String? = null JsonProperty("p") var page: String? = null }
src/main/kotlin/org/dictat/wikistat/model/Nova.kt
3650452242
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.workspace.usecase class UnsupportedProjectVersionException(msg: String) : Throwable(msg)
workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/usecase/UnsupportedProjectVersionException.kt
2209881025
package burp import com.github.kittinunf.fuel.Fuel import javax.swing.JTextField import javax.swing.JToggleButton class FakeScannerMessage(val requestResponseTextField: JTextField, val requestResponseButton: JToggleButton, val callbacks: IBurpExtenderCallbacks) : IScannerCheck { override fun doActiveScan(baseRequestResponse: IHttpRequestResponse?, insertionPoint: IScannerInsertionPoint?): MutableList<IScanIssue>? { return null } override fun consolidateDuplicateIssues(existingIssue: IScanIssue?, newIssue: IScanIssue?): Int { return 0 } override fun doPassiveScan(baseRequestResponse: IHttpRequestResponse): MutableList<IScanIssue>? { if (requestResponseButton.isSelected) { return null } val hookURLs = requestResponseTextField.text.split(",") val b2b = BurpToBuddy(callbacks) val jsonHttpRequestResponse = b2b.httpRequestResponseToJsonObject(baseRequestResponse) hookURLs.forEach{ Fuel.Companion.post(it). body(jsonHttpRequestResponse.toString()).response() } return null } }
src/main/kotlin/burp/FakeScannerMessage.kt
2882990287
package exh.metadata.sql.queries import com.pushtorefresh.storio.sqlite.queries.DeleteQuery import com.pushtorefresh.storio.sqlite.queries.Query import eu.kanade.tachiyomi.data.database.DbProvider import eu.kanade.tachiyomi.data.database.inTransaction import exh.metadata.sql.models.SearchTag import exh.metadata.sql.tables.SearchTagTable interface SearchTagQueries : DbProvider { fun getSearchTagsForManga(mangaId: Long) = db.get() .listOfObjects(SearchTag::class.java) .withQuery(Query.builder() .table(SearchTagTable.TABLE) .where("${SearchTagTable.COL_MANGA_ID} = ?") .whereArgs(mangaId) .build()) .prepare() fun deleteSearchTagsForManga(mangaId: Long) = db.delete() .byQuery(DeleteQuery.builder() .table(SearchTagTable.TABLE) .where("${SearchTagTable.COL_MANGA_ID} = ?") .whereArgs(mangaId) .build()) .prepare() fun insertSearchTag(searchTag: SearchTag) = db.put().`object`(searchTag).prepare() fun insertSearchTags(searchTags: List<SearchTag>) = db.put().objects(searchTags).prepare() fun deleteSearchTag(searchTag: SearchTag) = db.delete().`object`(searchTag).prepare() fun deleteAllSearchTags() = db.delete().byQuery(DeleteQuery.builder() .table(SearchTagTable.TABLE) .build()) .prepare() fun setSearchTagsForManga(mangaId: Long, tags: List<SearchTag>) { db.inTransaction { deleteSearchTagsForManga(mangaId).executeAsBlocking() tags.chunked(100) { chunk -> insertSearchTags(chunk).executeAsBlocking() } } } }
app/src/main/java/exh/metadata/sql/queries/SearchTagQueries.kt
4071196637
package com.agrawalsuneet.dotsloader.loaders import android.content.Context import android.os.Handler import android.util.AttributeSet import android.view.ViewTreeObserver import android.view.animation.* import android.widget.LinearLayout import com.agrawalsuneet.dotsloader.R import com.agrawalsuneet.dotsloader.basicviews.CircleView import com.agrawalsuneet.dotsloader.basicviews.ThreeDotsBaseView /** * Created by suneet on 12/13/17. */ class SlidingLoader : ThreeDotsBaseView { override var animDuration: Int = 500 set(value) { field = value firstDelayDuration = value / 10 secondDelayDuration = value / 5 } override var interpolator: Interpolator = AnticipateOvershootInterpolator() set(value) { field = AnticipateOvershootInterpolator() } var distanceToMove: Int = 12 set(value) { field = value invalidate() } private var firstDelayDuration: Int = 0 private var secondDelayDuration: Int = 0 constructor(context: Context, dotsRadius: Int, dotsDist: Int, firstDotColor: Int, secondDotColor: Int, thirdDotColor: Int) : super(context, dotsRadius, dotsDist, firstDotColor, secondDotColor, thirdDotColor) { initView() } constructor(context: Context?) : super(context) { initView() } constructor(context: Context?, attrs: AttributeSet) : super(context, attrs) { initAttributes(attrs) initView() } constructor(context: Context?, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initAttributes(attrs) initView() } override fun initAttributes(attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SlidingLoader, 0, 0) this.dotsRadius = typedArray.getDimensionPixelSize(R.styleable.SlidingLoader_slidingloader_dotsRadius, 30) this.dotsDist = typedArray.getDimensionPixelSize(R.styleable.SlidingLoader_slidingloader_dotsDist, 15) this.firstDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_firstDotColor, resources.getColor(R.color.loader_selected)) this.secondDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_secondDotColor, resources.getColor(R.color.loader_selected)) this.thirdDotColor = typedArray.getColor(R.styleable.SlidingLoader_slidingloader_thirdDotColor, resources.getColor(R.color.loader_selected)) this.animDuration = typedArray.getInt(R.styleable.SlidingLoader_slidingloader_animDur, 500) this.distanceToMove = typedArray.getInteger(R.styleable.SlidingLoader_slidingloader_distanceToMove, 12) typedArray.recycle() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val calWidth = (10 * dotsRadius) + (distanceToMove * dotsRadius) + (2 * dotsDist) val calHeight = 2 * dotsRadius setMeasuredDimension(calWidth, calHeight) } override fun initView() { removeAllViews() removeAllViewsInLayout() firstCircle = CircleView(context, dotsRadius, firstDotColor) secondCircle = CircleView(context, dotsRadius, secondDotColor) thirdCircle = CircleView(context, dotsRadius, thirdDotColor) val paramsFirstCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsFirstCircle.leftMargin = (2 * dotsRadius) val paramsSecondCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsSecondCircle.leftMargin = dotsDist val paramsThirdCircle = LinearLayout.LayoutParams((2 * dotsRadius), 2 * dotsRadius) paramsThirdCircle.leftMargin = dotsDist paramsThirdCircle.rightMargin = (2 * dotsRadius) addView(firstCircle, paramsFirstCircle) addView(secondCircle, paramsSecondCircle) addView(thirdCircle, paramsThirdCircle) val loaderView = this viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { startLoading(true) val vto = loaderView.viewTreeObserver vto.removeOnGlobalLayoutListener(this) } }) } private fun startLoading(isForwardDir: Boolean) { val trans1Anim = getTranslateAnim(isForwardDir) if (isForwardDir) thirdCircle.startAnimation(trans1Anim) else firstCircle.startAnimation(trans1Anim) val trans2Anim = getTranslateAnim(isForwardDir) Handler().postDelayed({ secondCircle.startAnimation(trans2Anim) }, firstDelayDuration.toLong()) val trans3Anim = getTranslateAnim(isForwardDir) Handler().postDelayed({ if (isForwardDir) firstCircle.startAnimation(trans3Anim) else thirdCircle.startAnimation(trans3Anim) }, secondDelayDuration.toLong()) trans3Anim.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation?) { } override fun onAnimationEnd(animation: Animation?) { startLoading(!isForwardDir) } override fun onAnimationStart(animation: Animation) { } }) } private fun getTranslateAnim(isForwardDir: Boolean): TranslateAnimation { val transAnim = TranslateAnimation(if (isForwardDir) 0f else (distanceToMove * dotsRadius).toFloat(), if (isForwardDir) (distanceToMove * dotsRadius).toFloat() else 0f, 0f, 0f) transAnim.duration = animDuration.toLong() transAnim.fillAfter = true transAnim.interpolator = interpolator return transAnim } }
dotsloader/src/main/java/com/agrawalsuneet/dotsloader/loaders/SlidingLoader.kt
4045758191
package com.vmenon.mpo.my_library.presentation.di.dagger import android.content.Context import com.vmenon.mpo.common.framework.di.dagger.CommonFrameworkComponentProvider import com.vmenon.mpo.my_library.framework.di.dagger.DaggerLibraryFrameworkComponent import com.vmenon.mpo.player.framework.di.dagger.PlayerFrameworkComponentProvider fun Context.toLibraryComponent(): LibraryComponent { val commonFrameworkComponent = (applicationContext as CommonFrameworkComponentProvider).commonFrameworkComponent() val libraryFrameworkComponent = DaggerLibraryFrameworkComponent.builder() .commonFrameworkComponent(commonFrameworkComponent) .build() val playerFrameworkComponent = (applicationContext as PlayerFrameworkComponentProvider).playerFrameworkComponent() return DaggerLibraryComponent.builder() .commonFrameworkComponent(commonFrameworkComponent) .libraryFrameworkComponent(libraryFrameworkComponent) .playerFrameworkComponent(playerFrameworkComponent) .build() }
my_library_presentation/src/main/java/com/vmenon/mpo/my_library/presentation/di/dagger/Extensions.kt
3270060639
/* * Copyright (c) 2015 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.kwery.mappertest.example.test import com.github.andrewoma.kwery.fetcher.GraphFetcher import com.github.andrewoma.kwery.fetcher.Node import com.github.andrewoma.kwery.fetcher.node import com.github.andrewoma.kwery.mappertest.example.* import org.junit.Test import java.time.Duration import java.time.LocalDateTime import kotlin.comparisons.compareBy import kotlin.properties.Delegates import kotlin.test.* class FilmDaoTest : AbstractFilmDaoTest<Film, Int, FilmDao>() { var graphFetcher: GraphFetcher by Delegates.notNull() var filmActorDao: FilmActorDao by Delegates.notNull() override var dao: FilmDao by Delegates.notNull() override fun afterSessionSetup() { dao = FilmDao(session) filmActorDao = FilmActorDao(session) graphFetcher = createFilmFetcher(session) super.afterSessionSetup() } override val data by lazy { listOf( Film(-1, "Underworld", 2003, sd.languageEnglish, null, Duration.ofMinutes(121), FilmRating.NC_17, LocalDateTime.now(), listOf("Commentaries", "Behind the Scenes")), Film(-1, "Underworld: Evolution", 2006, sd.languageEnglish, null, Duration.ofMinutes(106), FilmRating.R, LocalDateTime.now(), listOf("Behind the Scenes")), Film(-1, "Underworld: Rise of the Lycans", 2006, sd.languageEnglish, sd.languageSpanish, Duration.ofMinutes(92), FilmRating.R, LocalDateTime.now(), listOf()) ) } override fun mutateContents(t: Film) = t.copy( title = "Resident Evil", language = sd.languageSpanish, originalLanguage = sd.languageEnglish, duration = Duration.ofMinutes(10), rating = FilmRating.G ) override fun contentsEqual(t1: Film, t2: Film) = t1.title == t2.title && t1.language.id == t2.language.id && t1.originalLanguage?.id == t2.originalLanguage?.id && t1.duration == t2.duration && t1.rating == t2.rating @Test fun `findWithActors should fetch actors via a join`() { val film = insertAll().first() val actors = listOf(sd.actorKate, sd.actorBrad) for (actor in actors) { filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actor.id), LocalDateTime.now())) } val found = dao.findWithActors(film.title, film.releaseYear)!! assertEquals(actors.toSet(), found.actors) } @Test fun `findWithLanguages should fetch actors via a join`() { val films = insertAll() dao.findWithLanguages(films[0].title, films[0].releaseYear)!!.let { film -> assertEquals(film.language, sd.languageEnglish) assertNull(film.originalLanguage) } dao.findWithLanguages(films[2].title, films[2].releaseYear)!!.let { film -> assertEquals(film.language, sd.languageEnglish) assertEquals(film.originalLanguage, sd.languageSpanish) } } @Test fun `findAllTitlesAndReleaseYears should return partial data`() { insertAll() val films = dao.findAllTitlesAndReleaseYears() assertTrue(films.map { it.title }.toSet().contains("Underworld")) assertTrue(films.map { it.releaseYear }.toSet().contains(2006)) assertFalse(films.map { it.rating }.toSet().contains(FilmRating.R)) } fun <T> Collection<T>.fetch(node: Node) = graphFetcher.fetch(this, node) @Test fun `find by graph fetcher`() { val films = insertAll() val ids = films.map { it.id } val actors = listOf(sd.actorKate, sd.actorBrad) for (film in films) { for (actor in actors) { filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actor.id), LocalDateTime.now())) } } // Check to see actors and language are populated var fetched = dao.findByIds(ids).values.fetch(Node(Node.all)) assertEquals(films.size, fetched.size) for (film in fetched) { assertEquals(2, film.actors.size) assertEquals(sd.languageEnglish.name, film.language.name) if (film.title == "Underworld: Rise of the Lycans") { assertEquals(sd.languageSpanish, film.originalLanguage) } else { assertNull(film.originalLanguage) } } // Check to see only the language is populate fetched = dao.findByIds(ids).values.fetch(Node(Film::language.node())) assertEquals(films.size, fetched.size) for (film in fetched) { assertEquals(0, film.actors.size) assertEquals(sd.languageEnglish.name, film.language.name) } } @Test fun `findByCriteria should filter films`() { val inserted = insertAll() for ((index, film) in inserted.withIndex()) { val actorId = if (index % 2 == 0) sd.actorBrad.id else sd.actorKate.id filmActorDao.insert(FilmActor(FilmActor.Id(film.id, actorId), LocalDateTime.now())) } val data = dao.findAll().sortedWith(compareBy(Film::title, Film::releaseYear)).fetch(Node(Node.all)) fun assert(criteria: FilmCriteria, expected: List<Film>) { if (criteria != FilmCriteria()) { assertNotEquals(data.size, expected.size, "Invalid filter - no values filtered") } assertNotEquals(0, expected.size, "Invalid filter - all values filtered") assertEquals(expected.map(Film::id), dao.findByCriteria(criteria).map(Film::id)) } fun assert(criteria: FilmCriteria, filter: (FilmCriteria, Film) -> Boolean) = assert(criteria, data.filter { filter(criteria, it) }) assert(FilmCriteria()) { _, _ -> true } // Default criteria should select everything // Individual criteria assert(FilmCriteria(releaseYear = 2003)) { c, f -> f.releaseYear == c.releaseYear } assert(FilmCriteria(title = "lycans")) { c, f -> f.title.toLowerCase().contains(c.title!!.toLowerCase()) } assert(FilmCriteria(maxDuration = Duration.ofHours(2))) { c, f -> f.duration == null || f.duration <= c.maxDuration } assert(FilmCriteria(limit = 2, offset = 1), data.drop(1).take(2)) assert(FilmCriteria(actor = sd.actorKate)) { c, f -> c.actor in f.actors} assert(FilmCriteria(ratings = setOf(FilmRating.R, FilmRating.G))) { c, f -> f.rating in c.ratings} // Combinations assert(FilmCriteria(ratings = setOf(FilmRating.R), maxDuration = Duration.ofHours(1).plusMinutes(32))) { c, f -> f.rating in c.ratings && f.duration != null && f.duration <= c.maxDuration } } }
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/FilmDaoTest.kt
1033577814
package info.hzvtc.hipixiv.inject.annotation import javax.inject.Qualifier @Qualifier @Retention annotation class ApplicationContext
app/src/main/java/info/hzvtc/hipixiv/inject/annotation/ApplicationContext.kt
1593229386
package eu.kanade.presentation.more.settings import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import eu.kanade.presentation.components.ScrollbarLazyColumn import eu.kanade.presentation.more.settings.screen.SearchableSettings import eu.kanade.presentation.more.settings.widget.PreferenceGroupHeader import kotlinx.coroutines.delay import kotlin.time.Duration.Companion.seconds /** * Preference Screen composable which contains a list of [Preference] items * @param items [Preference] items which should be displayed on the preference screen. An item can be a single [PreferenceItem] or a group ([Preference.PreferenceGroup]) * @param modifier [Modifier] to be applied to the preferenceScreen layout */ @Composable fun PreferenceScreen( items: List<Preference>, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { val state = rememberLazyListState() val highlightKey = SearchableSettings.highlightKey if (highlightKey != null) { LaunchedEffect(Unit) { val i = items.findHighlightedIndex(highlightKey) if (i >= 0) { delay(0.5.seconds) state.animateScrollToItem(i) } SearchableSettings.highlightKey = null } } ScrollbarLazyColumn( modifier = modifier, state = state, contentPadding = contentPadding, ) { items.fastForEachIndexed { i, preference -> when (preference) { // Create Preference Group is Preference.PreferenceGroup -> { if (!preference.enabled) return@fastForEachIndexed item { Column { PreferenceGroupHeader(title = preference.title) } } items(preference.preferenceItems) { item -> PreferenceItem( item = item, highlightKey = highlightKey, ) } item { if (i < items.lastIndex) { Spacer(modifier = Modifier.height(12.dp)) } } } // Create Preference Item is Preference.PreferenceItem<*> -> item { PreferenceItem( item = preference, highlightKey = highlightKey, ) } } } } } private fun List<Preference>.findHighlightedIndex(highlightKey: String): Int { return flatMap { if (it is Preference.PreferenceGroup) { mutableListOf<String?>() .apply { add(null) // Header addAll(it.preferenceItems.map { groupItem -> groupItem.title }) add(null) // Spacer } } else { listOf(it.title) } }.indexOfFirst { it == highlightKey } }
app/src/main/java/eu/kanade/presentation/more/settings/PreferenceScreen.kt
2474837087
package org.flightofstairs.redesignedPotato.parsers.json import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.Test import org.skyscreamer.jsonassert.JSONAssert import java.nio.charset.StandardCharsets.UTF_8 class ParsedMonsterInfoTest { @Test fun yeti() { val objectMapper = jacksonObjectMapper() val parsedMonster = objectMapper.readValue(javaClass.getResourceAsStream("/yeti-raw.json"), ParsedMonster::class.java) val modelledMonsterJson = objectMapper.writeValueAsString(parsedMonster.toModel()) val expectedYetiJson = javaClass.getResourceAsStream("/yeti-modelled.json").reader(UTF_8).readText() JSONAssert.assertEquals(expectedYetiJson, modelledMonsterJson, true) } }
core/test/org/flightofstairs/redesignedPotato/parsers/json/ParsedMonsterInfoTest.kt
1226842675
package com.hotpodata.common.view import android.annotation.TargetApi import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.os.Build import android.util.AttributeSet import android.view.View import android.widget.ImageView import com.hotpodata.common.R /** * Created by jdrotos on 7/30/14. */ class CircleImageView : ImageView { private var mCircleBgColor = Color.TRANSPARENT private var mCircleBorderColor = Color.TRANSPARENT private var mCircleBorderWidth = 2 private val mBgPaint = Paint() private val mBorderPaint = Paint() constructor(context: Context) : super(context) { init(context, null) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(context, attrs) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs) } private fun init(context: Context, attrs: AttributeSet?) { if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView) if (a != null) { if (a.hasValue(R.styleable.CircleImageView_circleBackgroundColor)) { mCircleBgColor = a.getColor(R.styleable.CircleImageView_circleBackgroundColor, mCircleBgColor) } if (a.hasValue(R.styleable.CircleImageView_circleBorderColor)) { mCircleBorderColor = a.getColor(R.styleable.CircleImageView_circleBorderColor, mCircleBorderColor) } if (a.hasValue(R.styleable.CircleImageView_circleBorderWidth)) { mCircleBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_circleBorderWidth, mCircleBorderWidth) } a.recycle() } } updatePaints() //clipPath does not work if we are working in the hardware layer if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setLayerType(View.LAYER_TYPE_NONE, null) } else { setLayerType(View.LAYER_TYPE_SOFTWARE, null) } } private fun updatePaints() { //the circle background mBgPaint.isAntiAlias = true mBgPaint.color = mCircleBgColor mBgPaint.style = Paint.Style.FILL //circle border mBorderPaint.isAntiAlias = true mBorderPaint.color = mCircleBorderColor mBorderPaint.strokeWidth = mCircleBorderWidth.toFloat() mBorderPaint.style = Paint.Style.STROKE } fun setCircleBgColor(color: Int) { mCircleBgColor = color updatePaints() } fun setCircleBorderColor(color: Int) { mCircleBorderColor = color updatePaints() } fun setCircleBorderWidth(width: Int) { mCircleBorderWidth = width updatePaints() } override fun onDraw(canvas: Canvas) { val w = width val h = height val circle = Path() circle.addCircle(w / 2f, h / 2f, Math.min(w, h) / 2f, Path.Direction.CW) if (mCircleBgColor != Color.TRANSPARENT) { canvas.drawPath(circle, mBgPaint) } if (mCircleBorderColor != Color.TRANSPARENT && mCircleBorderWidth > 0) { val borderCirclePath = Path() val hsw = mCircleBorderWidth / 2f borderCirclePath.addCircle(w / 2f, h / 2f, (Math.min(w, h) / 2f) - hsw, Path.Direction.CW) canvas.drawPath(borderCirclePath, mBorderPaint) } canvas.clipPath(circle) super.onDraw(canvas) } }
src/main/java/com/hotpodata/common/view/CircleImageView.kt
4194232860
package com.trevorhalvorson.ping.injection.module import com.trevorhalvorson.ping.builder.BuilderActivity import com.trevorhalvorson.ping.builder.BuilderModule import com.trevorhalvorson.ping.injection.scope.PerActivity import com.trevorhalvorson.ping.sendMessage.SendMessageActivity import com.trevorhalvorson.ping.sendMessage.SendMessageModule import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class ActivityBindingModule { @PerActivity @ContributesAndroidInjector(modules = arrayOf(SendMessageModule::class)) abstract fun sendMessageActivity(): SendMessageActivity @PerActivity @ContributesAndroidInjector(modules = arrayOf(BuilderModule::class)) abstract fun builderActivity(): BuilderActivity }
app/src/main/kotlin/com/trevorhalvorson/ping/injection/module/ActivityBindingModule.kt
2839739990
package abi43_0_0.expo.modules.medialibrary import android.content.Context import android.database.Cursor.FIELD_TYPE_NULL import android.os.AsyncTask import android.os.Bundle import android.provider.MediaStore import android.provider.MediaStore.Images.Media import abi43_0_0.expo.modules.core.Promise internal open class GetAlbums(private val mContext: Context, private val mPromise: Promise) : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg params: Void?): Void? { val projection = arrayOf(Media.BUCKET_ID, Media.BUCKET_DISPLAY_NAME) val selection = "${MediaStore.Files.FileColumns.MEDIA_TYPE} != ${MediaStore.Files.FileColumns.MEDIA_TYPE_NONE}" val albums = HashMap<String, Album>() try { mContext.contentResolver .query( MediaLibraryConstants.EXTERNAL_CONTENT, projection, selection, null, Media.BUCKET_DISPLAY_NAME ) .use { asset -> if (asset == null) { mPromise.reject( MediaLibraryConstants.ERROR_UNABLE_TO_LOAD, "Could not get albums. Query returns null." ) return@use } val bucketIdIndex = asset.getColumnIndex(Media.BUCKET_ID) val bucketDisplayNameIndex = asset.getColumnIndex(Media.BUCKET_DISPLAY_NAME) while (asset.moveToNext()) { val id = asset.getString(bucketIdIndex) if (asset.getType(bucketDisplayNameIndex) == FIELD_TYPE_NULL) { continue } val album = albums[id] ?: Album( id = id, title = asset.getString(bucketDisplayNameIndex) ).also { albums[id] = it } album.count++ } mPromise.resolve(albums.values.map { it.toBundle() }) } } catch (e: SecurityException) { mPromise.reject( MediaLibraryConstants.ERROR_UNABLE_TO_LOAD_PERMISSION, "Could not get albums: need READ_EXTERNAL_STORAGE permission.", e ) } catch (e: RuntimeException) { mPromise.reject(MediaLibraryConstants.ERROR_UNABLE_TO_LOAD, "Could not get albums.", e) } return null } private class Album(private val id: String, private val title: String, var count: Int = 0) { fun toBundle() = Bundle().apply { putString("id", id) putString("title", title) putParcelable("type", null) putInt("assetCount", count) } } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/medialibrary/GetAlbums.kt
3582210121
package io.github.feelfreelinux.wykopmobilny.ui.widgets.buttons.vote.base import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.widget.TextView import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.ui.dialogs.showExceptionDialog import io.github.feelfreelinux.wykopmobilny.utils.getActivityContext import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi import javax.inject.Inject @Suppress("LeakingThis") abstract class BaseVoteButton : TextView { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs, R.attr.MirkoButtonStyle) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @Inject lateinit var userManager : UserManagerApi abstract fun vote() abstract fun unvote() init { WykopApp.uiInjector.inject(this) val typedValue = TypedValue() getActivityContext()!!.theme?.resolveAttribute(R.attr.voteButtonStatelist, typedValue, true) setBackgroundResource(typedValue.resourceId) setOnClickListener { userManager.runIfLoggedIn(context) { if (isSelected) unvote() else vote() } } } var voteCount : Int get() = text.toString().toInt() set(value) { text = context.getString(R.string.votes_count, value) } var isButtonSelected: Boolean get() = isSelected set(value) { isSelected = value } fun showErrorDialog(e : Throwable) = context.showExceptionDialog(e) }
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/widgets/buttons/vote/base/BaseVoteButton.kt
3210386177
package expo.modules.imagepicker.fileproviders import android.net.Uri import java.io.File class CropFileProvider(private val croppedUri: Uri) : FileProvider { override fun generateFile() = File(croppedUri.path!!) }
packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/fileproviders/CropFileProvider.kt
1440747192
package info.nightscout.androidaps.plugins.general.automation.elements import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerTestBase import org.junit.Assert import org.junit.Test class InputTempTargetTest : TriggerTestBase() { @Test fun setValueTest() { val i = InputTempTarget(profileFunction) i.units = GlucoseUnit.MMOL i.value = 5.0 Assert.assertEquals(5.0, i.value, 0.01) i.units = GlucoseUnit.MGDL i.value = 100.0 Assert.assertEquals(100.0, i.value, 0.01) Assert.assertEquals(GlucoseUnit.MGDL, i.units) } }
automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.kt
3373904350
package net.ndrei.bushmaster.api object BushMasterApi { // TODO: add some kind of protection around this lateinit var harvestableFactory: IHarvestableFactory }
src/api/kotlin/net/ndrei/bushmaster/api/BushMasterApi.kt
508037421
package tech.jamescoggan.playground import android.support.v7.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
app/src/main/java/tech/jamescoggan/playground/MainActivity.kt
15827286
package org.sirix.cli.commands import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sirix.access.Databases import org.sirix.exception.SirixUsageException import org.slf4j.Logger import org.slf4j.LoggerFactory internal class DropTest : CliCommandTest() { companion object { @JvmField val LOGGER: Logger = LoggerFactory.getLogger(DropTest::class.java) } @BeforeEach fun setUp() { createXmlDatabase() } @AfterEach fun tearDown() { removeTestDatabase(CreateResourceTest.LOGGER) } @Test fun happyPath() { // GIVEN val dropCommand = Drop(giveACliOptions()) // WHEN dropCommand.execute() // THEN Assertions.assertThrows(SirixUsageException::class.java) { Databases.openXmlDatabase(path()) } } }
bundles/sirix-kotlin-cli/src/test/kotlin/org/sirix/cli/commands/DropTest.kt
3007200235
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.widgets.glance import android.content.Context import android.content.Intent import androidx.glance.appwidget.GlanceAppWidget import androidx.glance.appwidget.GlanceAppWidgetReceiver import androidx.glance.appwidget.updateAll import app.ss.widgets.BaseWidgetProvider import app.ss.widgets.WidgetDataProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import javax.inject.Inject abstract class BaseGlanceAppWidgetReceiver<T : BaseGlanceAppWidget<*>> : GlanceAppWidgetReceiver(), CoroutineScope by MainScope() { @Inject internal lateinit var widgetDataProvider: WidgetDataProvider override val glanceAppWidget: GlanceAppWidget get() = createWidget().also { it.initiateLoad() } abstract fun createWidget(): T override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) if (intent.action == BaseWidgetProvider.REFRESH_ACTION) { launch { glanceAppWidget.updateAll(context) } } } }
features/app-widgets/src/main/java/app/ss/widgets/glance/BaseGlanceAppWidgetReceiver.kt
1918035277
package net.dean.jraw.models /** A model is identifiable if it has a full name (like "t1_abc123") and an ID (like "abc123") */ interface Identifiable : UniquelyIdentifiable { val fullName: String /** The unique base 36 identifier given to this model by reddit */ val id: String }
lib/src/main/kotlin/net/dean/jraw/models/Identifiable.kt
1887664901
package xxx.jq.service import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component import org.springframework.web.context.WebApplicationContext import xxx.jq.ResultRepository import xxx.jq.entity.Result /** * @author rinp * @since 2015/10/08 */ @Component @Scope(WebApplicationContext.SCOPE_REQUEST) class ResultService { @Autowired lateinit private var repo: ResultRepository fun save(result: Result): Result { return repo.save(result) } fun save(result: Iterable<Result>): List<Result> { return repo.save(result) } fun findOne(id: Long): Result? { return repo.findOne(id) } }
src/main/kotlin/xxx/jq/service/ResultService.kt
2710255178
/* * Copyright (c) 2022. Adventech <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cryart.sabbathschool.lessons.ui.lessons.components.spec import app.ss.models.SSLesson import org.amshove.kluent.shouldBeEqualTo import org.joda.time.DateTime import org.junit.Test class QuarterlyInfoSpecTest { @Test fun `should find lesson index on Wednesday`() { val index = findIndex( lessons = buildLessons(), today = DateTime.parse("2022-08-17T13:30:05.000Z") ) // Wednesday 17th August 2022 would fall under the 8th lesson of the quarter index shouldBeEqualTo "lesson_8" } @Test fun `should use previous week lesson index on Sabbath morning`() { val index = findIndex( lessons = buildLessons(), today = DateTime.parse("2022-08-20T09:30:05.000Z") ) // Sabbath morning 20th August 2022 would fall back to the 8th lesson of the quarter index shouldBeEqualTo "lesson_8" } @Test fun `should use current week lesson index on Sabbath afternoon`() { val index = findIndex( lessons = buildLessons(), today = DateTime.parse("2022-08-20T15:40:05.000Z") ) // Sabbath afternoon 20th August 2022 would fall under the 9th lesson of the quarter index shouldBeEqualTo "lesson_9" } /** * Builds 13 [SSLesson]s starting from Sunday 25 June 2022. * 13 is the average number of lessons in a quarter. */ private fun buildLessons(): List<SSLesson> { val lessons = mutableListOf<SSLesson>() val weekStart = DateTime.parse("2022-06-25T13:30:05.000Z") var currentWeek = weekStart for (i in 1..13) { val firstDay = currentWeek val lastDay = currentWeek.plusDays(6) lessons.add( SSLesson( title = "Lesson $i", start_date = "${firstDay.dayOfMonth().get()}/${firstDay.monthOfYear().get()}/${firstDay.year().get()}", end_date = "${lastDay.dayOfMonth().get()}/${lastDay.monthOfYear().get()}/${lastDay.year().get()}", index = "lesson_$i" ) ) currentWeek = currentWeek.plusWeeks(1) } return lessons } }
app/src/test/java/com/cryart/sabbathschool/lessons/ui/lessons/components/spec/QuarterlyInfoSpecTest.kt
16637168
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage.keys import arcs.core.common.ArcId import arcs.core.common.toArcId import arcs.core.data.Capabilities import arcs.core.data.Capability import arcs.core.storage.StorageKey import arcs.core.storage.StorageKeyFactory import arcs.core.storage.StorageKeyProtocol import arcs.core.storage.StorageKeySpec /** Protocol to be used with the volatile driver. */ /** Storage key for a piece of data kept in the volatile driver. */ data class VolatileStorageKey( /** Id of the arc where this key was created. */ val arcId: ArcId, /** Unique identifier for this particular key. */ val unique: String ) : StorageKey(protocol) { override fun toKeyString(): String = "$arcId/$unique" override fun newKeyWithComponent(component: String): StorageKey { return VolatileStorageKey(arcId, component) } override fun toString(): String = super.toString() class VolatileStorageKeyFactory : StorageKeyFactory( protocol, Capabilities( listOf( Capability.Persistence.IN_MEMORY, Capability.Shareable(false) ) ) ) { override fun create(options: StorageKeyOptions): StorageKey { return VolatileStorageKey(options.arcId, options.unique) } } companion object : StorageKeySpec<VolatileStorageKey> { private val VOLATILE_STORAGE_KEY_PATTERN = "^([^/]+)/(.*)\$".toRegex() override val protocol = StorageKeyProtocol.Volatile override fun parse(rawKeyString: String): VolatileStorageKey { val match = requireNotNull(VOLATILE_STORAGE_KEY_PATTERN.matchEntire(rawKeyString)) { "Not a valid VolatileStorageKey" } return VolatileStorageKey(match.groupValues[1].toArcId(), match.groupValues[2]) } } }
java/arcs/core/storage/keys/VolatileStorageKey.kt
2593955545
package org.rust.lang.core.lexer import com.intellij.lexer.Lexer import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.LexerTestCase import java.io.File import java.io.IOException import java.nio.file.Paths public class RustLexingTestCase : LexerTestCase() { override fun getDirPath(): String { val home = Paths.get(PathManager.getHomePath()).toAbsolutePath() val testData = Paths.get("src", "test", "resources", "org", "rust", "lang", "core", "lexer", "fixtures").toAbsolutePath() // XXX: unfortunately doFileTest will look for the file relative to the home directory of // the test instance of IDEA, so let's cook a dirPath starting with several ../../ return home.relativize(testData).toString() } override fun createLexer(): Lexer? = RustLexer() // NOTE(matkad): this is basically a copy-paste of doFileTest. // The only difference is that encoding is set to utf-8 fun doTest() { val fileName = PathManager.getHomePath() + "/" + dirPath + "/" + getTestName(true) + ".rs" var text = "" try { val fileText = FileUtil.loadFile(File(fileName), CharsetToolkit.UTF8); text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText); } catch (e: IOException) { fail("can't load file " + fileName + ": " + e.message); } doTest(text); } fun testComments() = doTest() fun testShebang() = doTest() fun testFloat() = doTest() fun testIdentifiers() = doTest() fun testCharLiterals() = doTest() fun testStringLiterals() = doTest() fun testByteLiterals() = doTest() }
src/test/kotlin/org/rust/lang/core/lexer/RustLexingTestCase.kt
1070234964
package me.elsiff.morefish.fishing.catchhandler import me.elsiff.morefish.fishing.Fish import org.bukkit.Color import org.bukkit.FireworkEffect import org.bukkit.entity.Firework import org.bukkit.entity.Player /** * Created by elsiff on 2019-01-15. */ class CatchFireworkSpawner : CatchHandler { private val effect = FireworkEffect.builder() .with(FireworkEffect.Type.BALL_LARGE) .withColor(Color.AQUA) .withFade(Color.BLUE) .withTrail() .withFlicker() .build() override fun handle(catcher: Player, fish: Fish) { if (fish.type.hasCatchFirework) { val firework = catcher.world.spawn(catcher.location, Firework::class.java) val meta = firework.fireworkMeta meta.addEffect(effect) meta.power = 1 firework.fireworkMeta = meta } } }
src/main/kotlin/me/elsiff/morefish/fishing/catchhandler/CatchFireworkSpawner.kt
801569006
package nl.jstege.adventofcode.aoc2016.days import nl.jstege.adventofcode.aoccommon.utils.DayTester /** * Test for Day23 * @author Jelle Stege */ class Day23Test : DayTester(Day23())
aoc-2016/src/test/kotlin/nl/jstege/adventofcode/aoc2016/days/Day23Test.kt
4168959735
package org.hexworks.zircon.examples.fragments import org.hexworks.cobalt.databinding.api.binding.bindTransform import org.hexworks.cobalt.databinding.api.collection.ListProperty import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.value.ObservableValue import org.hexworks.zircon.api.ComponentDecorations.box import org.hexworks.zircon.api.component.HBox import org.hexworks.zircon.api.component.VBox import org.hexworks.zircon.api.component.renderer.ComponentRenderer import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.dsl.component.* import org.hexworks.zircon.api.dsl.fragment.buildTable import org.hexworks.zircon.api.fragment.Table import org.hexworks.zircon.examples.base.OneColumnComponentExampleKotlin import org.hexworks.zircon.examples.fragments.table.* import org.hexworks.zircon.examples.fragments.table.randomWage class TableWithSelectionExample : OneColumnComponentExampleKotlin() { companion object { @JvmStatic fun main(args: Array<String>) { TableWithSelectionExample().show("Table with selection") } } override fun build(box: VBox) { val persons = 15.randomPersons().toProperty() val tableWidth = box.width / 3 * 2 val panelWidth = box.width / 3 val tableFragment = buildTable<Person> { // TODO: Use an observable list and add UI elements to add/remove elements data = persons height = box.height selectedRowRenderer = ComponentRenderer { tileGraphics, context -> val style = context.currentStyle tileGraphics.fill(Tile.defaultTile()) tileGraphics.applyStyle(style.withBackgroundColor(context.theme.accentColor)) } textColumn { name = "First name" width = 14 valueProvider = Person::firstName } textColumn { name = "Last name" width = 14 valueProvider = Person::lastName } numberColumn { name = "Age" width = 3 valueProvider = Person::age } iconColumn { name = "Height" valueProvider = Person::heightIcon } observableTextColumn { name = "Wage" width = 8 valueProvider = Person::formattedWage } } val selectionPanel = buildSelectionPanel(persons, tableFragment, panelWidth) box.addComponent(buildHbox { preferredSize = box.contentSize withChildren(buildPanel { preferredSize = Size.create(tableWidth, box.height) withChildren(tableFragment.root) }, selectionPanel) }) } /** * Builds the right panel displaying the currently selected person. */ private fun buildSelectionPanel( persons: ListProperty<Person>, tableFragment: Table<Person>, width: Int ) = buildVbox { preferredSize = Size.create(width, tableFragment.size.height) spacing = 1 decoration = box() val panelContentSize = contentSize val personValue = tableFragment .selectedRowsValue .bindTransform { it.firstOrNull() ?: Person( "None", "Selected", 0, Height.SHORT, 50000.toProperty() ) } header { text = "Selected person:" } withChildren( personValue.asLabel(contentSize.width, Person::firstName), personValue.asLabel(contentSize.width, Person::lastName), heightPanel(contentSize.width, personValue), ) label { preferredSize = Size.create(contentSize.width, 1) textProperty.updateFrom(personValue.value.formattedWage) } button { +"shuffle" onActivated { val newWage = randomWage() personValue.value.wage.updateValue(newWage) } } horizontalNumberInput { preferredSize = Size.create(contentSize.width, 1) maxValue = Person.MAX_WAGE minValue = Person.MIN_WAGE }.apply { currentValue = personValue.value.wage.value currentValueProperty.bindTransform { personValue.value.wage.updateValue(it) } } button { preferredSize = contentSize.withHeight(1) textProperty.updateFrom(personValue.bindTransform { "Delete ${it.firstName} ${it.lastName}" }) onActivated { persons.remove(personValue.value) } } hbox { spacing = 1 preferredSize = panelContentSize.withHeight(1) button { +"+" onActivated { persons.add(randomPerson()) } } label { +"random Person" } button { +"-" onActivated { if (persons.isNotEmpty()) { persons.removeAt(persons.lastIndex) } } } } } private fun heightPanel(width: Int, person: ObservableValue<Person>): HBox = buildHbox { spacing = 1 preferredSize = Size.create(width, 1) icon { iconProperty.updateFrom(person.bindTransform { it.heightIcon }) } label { preferredSize = Size.create(width - 2, 1) textProperty.updateFrom(person.bindTransform { it.height.name }) } } private fun <T : Any> ObservableValue<T>.asLabel(width: Int, labelText: T.() -> String) = buildLabel { preferredSize = Size.create(width, 1) textProperty.updateFrom(bindTransform(labelText), true) } }
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/fragments/TableWithSelectionExample.kt
645353490
package org.hexworks.zircon.api.component import org.hexworks.cobalt.databinding.api.event.ObservableValueChanged import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.cobalt.events.api.Subscription import org.hexworks.zircon.api.Beta import org.hexworks.zircon.internal.component.impl.textedit.EditableTextBuffer @Beta interface NumberInput : Component { var text: String /** * Current value with respect to the maxValue */ var currentValue: Int /** * Bindable, current value */ val currentValueProperty: Property<Int> // TODO: do we need to expose this? fun textBuffer(): EditableTextBuffer fun incrementCurrentValue() fun decrementCurrentValue() /** * Callback called when value changes */ fun onChange(fn: (ObservableValueChanged<Int>) -> Unit): Subscription }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/NumberInput.kt
2467435856
package cc.femto.kommon.ui.recyclerview import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View open class MarginDecoration : RecyclerView.ItemDecoration { private var margin = -1 private var marginLeft: Int = 0 private var marginTop: Int = 0 private var marginRight: Int = 0 private var marginBottom: Int = 0 constructor(margin: Int) { this.margin = margin } constructor(marginLeft: Int, marginTop: Int, marginRight: Int, marginBottom: Int) { this.marginLeft = marginLeft this.marginTop = marginTop this.marginRight = marginRight this.marginBottom = marginBottom } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) { if (margin != -1) { outRect.set(margin, margin, margin, margin) } else { outRect.set(marginLeft, marginTop, marginRight, marginBottom) } } }
app/src/main/java/cc/femto/kommon/ui/recyclerview/MarginDecoration.kt
2845429692
package com.joe.zatuji.module.login import android.os.Bundle import com.joe.zatuji.R import com.joe.zatuji.base.BaseFragmentActivity import com.joe.zatuji.event.LoginSuccessEvent import com.joe.zatuji.module.login.login.LoginFragment import com.joe.zatuji.module.login.register.RegisterFragment import com.joey.cheetah.core.async.RxJavaManager /** * Description: * author:Joey * date:2018/11/20 */ class LoginActivity: BaseFragmentActivity() { private val tagLogin = "login" private val tagRegister = "register" private lateinit var loginFragment:LoginFragment private lateinit var registerFragment:RegisterFragment override fun createFragment() { loginFragment = LoginFragment() registerFragment = RegisterFragment() } override fun restoreFragment(p0: Bundle?) { loginFragment = fragmentManager.findFragmentByTag(tagLogin) as LoginFragment? ?: LoginFragment() registerFragment = fragmentManager.findFragmentByTag(tagRegister) as RegisterFragment? ?: RegisterFragment() } override fun attachFragment() { addFragment(loginFragment, R.id.fl_container_login,tagLogin) } fun toRegister() { addFragmentToStack(registerFragment, R.id.fl_container_login, tagRegister) } override fun initLayout(): Int { return R.layout.activity_login } override fun initView() {} override fun initPresenter() {} }
app/src/main/java/com/joe/zatuji/module/login/LoginActivity.kt
1053536793
package org.wordpress.android.ui.plans import android.os.Bundle import org.wordpress.android.databinding.PlansActivityBinding import org.wordpress.android.fluxc.model.plans.PlanOffersModel import org.wordpress.android.ui.FullScreenDialogFragment import org.wordpress.android.ui.LocaleAwareActivity import org.wordpress.android.ui.plans.PlansListFragment.PlansListInterface import org.wordpress.android.util.StringUtils class PlansActivity : LocaleAwareActivity(), PlansListInterface { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) with(PlansActivityBinding.inflate(layoutInflater)) { setContentView(root) setSupportActionBar(toolbarMain) } supportActionBar!!.setDisplayHomeAsUpEnabled(true) } override fun onPlanItemClicked(plan: PlanOffersModel) { val bundle = PlanDetailsFragment.newBundle(plan) val planDetailsDialog = FullScreenDialogFragment.Builder(this) .setTitle(StringUtils.notNullStr(plan.name)) .setContent(PlanDetailsFragment::class.java, bundle) .build() planDetailsDialog!!.show(this.supportFragmentManager, FullScreenDialogFragment.TAG) } override fun onPlansUpdating() { val planDetailsDialogFragment = supportFragmentManager.findFragmentByTag( FullScreenDialogFragment.TAG ) if (planDetailsDialogFragment != null && planDetailsDialogFragment is FullScreenDialogFragment) { planDetailsDialogFragment.dismissAllowingStateLoss() } } }
WordPress/src/main/java/org/wordpress/android/ui/plans/PlansActivity.kt
2830017561
package info.fox.messup.base import android.support.annotation.IdRes import android.view.View /** * Created by * snake on 2017/9/16. */ /** * Extension function for View's findViewById(). */ inline fun <reified T: View> View.findWidget(@IdRes id: Int): T = findViewById(id) as T
app/src/main/java/info/fox/messup/base/Extensions.kt
2542902810
package org.wordpress.android.ui.stories import android.app.Activity import android.content.Intent import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.ActivityLauncher import org.wordpress.android.ui.PagePostCreationSourcesDetail import org.wordpress.android.ui.media.MediaBrowserActivity import org.wordpress.android.ui.media.MediaBrowserType import org.wordpress.android.ui.mysite.SiteNavigationAction import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStory import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStoryWithMediaIds import org.wordpress.android.ui.mysite.SiteNavigationAction.AddNewStoryWithMediaUris import org.wordpress.android.ui.photopicker.MediaPickerConstants import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.UTILS import org.wordpress.android.viewmodel.Event import javax.inject.Inject class StoriesMediaPickerResultHandler @Inject constructor() { private val _onNavigation = MutableLiveData<Event<SiteNavigationAction>>() val onNavigation = _onNavigation as LiveData<Event<SiteNavigationAction>> @Deprecated("Use rather the other handle method and the live data navigation.") fun handleMediaPickerResultForStories( data: Intent, activity: Activity?, selectedSite: SiteModel?, source: PagePostCreationSourcesDetail ): Boolean { if (selectedSite == null) { return false } when (val navigationAction = buildNavigationAction(data, selectedSite, source)) { is AddNewStory -> ActivityLauncher.addNewStoryForResult( activity, navigationAction.site, navigationAction.source ) is AddNewStoryWithMediaIds -> ActivityLauncher.addNewStoryWithMediaIdsForResult( activity, navigationAction.site, navigationAction.source, navigationAction.mediaIds.toLongArray() ) is AddNewStoryWithMediaUris -> ActivityLauncher.addNewStoryWithMediaUrisForResult( activity, navigationAction.site, navigationAction.source, navigationAction.mediaUris.toTypedArray() ) else -> { return false } } return true } fun handleMediaPickerResultForStories( data: Intent, selectedSite: SiteModel, source: PagePostCreationSourcesDetail ): Boolean { val navigationAction = buildNavigationAction(data, selectedSite, source) return if (navigationAction != null) { _onNavigation.postValue(Event(navigationAction)) true } else { false } } private fun buildNavigationAction( data: Intent, selectedSite: SiteModel, source: PagePostCreationSourcesDetail ): SiteNavigationAction? { if (data.getBooleanExtra(MediaPickerConstants.EXTRA_LAUNCH_WPSTORIES_CAMERA_REQUESTED, false)) { return AddNewStory(selectedSite, source) } else if (isWPStoriesMediaBrowserTypeResult(data)) { if (data.hasExtra(MediaBrowserActivity.RESULT_IDS)) { val mediaIds = data.getLongArrayExtra(MediaBrowserActivity.RESULT_IDS)?.asList() ?: listOf() return AddNewStoryWithMediaIds(selectedSite, source, mediaIds) } else { val mediaUriStringsArray = data.getStringArrayExtra( MediaPickerConstants.EXTRA_MEDIA_URIS ) if (mediaUriStringsArray.isNullOrEmpty()) { AppLog.e( UTILS, "Can't resolve picked or captured image" ) return null } val mediaUris = mediaUriStringsArray.asList() return AddNewStoryWithMediaUris( selectedSite, source, mediaUris = mediaUris ) } } return null } private fun isWPStoriesMediaBrowserTypeResult(data: Intent): Boolean { if (data.hasExtra(MediaBrowserActivity.ARG_BROWSER_TYPE)) { val browserType = data.getSerializableExtra(MediaBrowserActivity.ARG_BROWSER_TYPE) return (browserType as MediaBrowserType).isWPStoriesPicker } return false } }
WordPress/src/main/java/org/wordpress/android/ui/stories/StoriesMediaPickerResultHandler.kt
808925752
open class Foo<T>() { /** * Doc for method xyzzy */ open fun xyzzy(): Int = 0 } open class Bar(): Foo<String>() { override fun xyzzy(): Int = 1 }
plugins/kotlin/idea/tests/testData/kdoc/finder/OverriddenWithSubstitutedType.kt
1390987282
package com.kelsos.mbrc.widgets import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import com.kelsos.mbrc.annotations.PlayerState.State import com.kelsos.mbrc.domain.TrackInfo object UpdateWidgets { const val COVER = "com.kelsos.mbrc.widgets.COVER" const val COVER_PATH = "com.kelsos.mbrc.widgets.COVER_PATH" const val STATE = "com.kelsos.mbrc.widgets.STATE" const val INFO = "com.kelsos.mbrc.widgets.INFO" const val TRACK_INFO = "com.kelsos.mbrc.widgets.TRACKINFO" const val PLAYER_STATE = "com.kelsos.mbrc.widgets.PLAYER_STATE" fun updateCover(context: Context, path: String = "") { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(COVER, true) .putExtra(COVER_PATH, path) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(COVER, true) .putExtra(COVER_PATH, path) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } fun updatePlaystate(context: Context, @State state: String) { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(STATE, true) .putExtra(PLAYER_STATE, state) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(STATE, true) .putExtra(PLAYER_STATE, state) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } fun updateTrackInfo(context: Context, info: TrackInfo) { val normalIntent = getIntent(WidgetNormal::class.java, context) .putExtra(INFO, true) .putExtra(TRACK_INFO, info) val smallIntent = getIntent(WidgetSmall::class.java, context) .putExtra(INFO, true) .putExtra(TRACK_INFO, info) context.sendBroadcast(smallIntent) context.sendBroadcast(normalIntent) } private fun getIntent(clazz: Class<*>, context: Context): Intent { val widgetUpdateIntent = Intent(context, clazz) widgetUpdateIntent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE return widgetUpdateIntent } }
app/src/main/kotlin/com/kelsos/mbrc/widgets/UpdateWidgets.kt
3783665935
package org.snakeskin.utility.value import kotlin.reflect.KProperty /** * @author Cameron Earle * @version 8/7/2019 * */ class SelectableInt(private vararg val values: Int) { operator fun getValue(thisRef: Any?, property: KProperty<*>): Int { if (SelectableValue.selected > values.lastIndex) { println("Warning: Selectable value '${property.name}' does not define a value for index $${SelectableValue.selected}! Returning first value.") return values.first() } return values[SelectableValue.selected] } }
SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/SelectableInt.kt
3396373370
package me.aberrantfox.hotbot.listeners import me.aberrantfox.hotbot.services.Configuration import me.aberrantfox.hotbot.services.UserID import net.dv8tion.jda.core.events.guild.GuildBanEvent import net.dv8tion.jda.core.hooks.ListenerAdapter import java.util.concurrent.ConcurrentHashMap typealias MessageID = String object WelcomeMessages { val map = ConcurrentHashMap<UserID, MessageID>() } class BanListener(val config: Configuration) : ListenerAdapter() { override fun onGuildBan(event: GuildBanEvent) { if(WelcomeMessages.map.containsKey(event.user.id)) { val messageID = WelcomeMessages.map[event.user.id] event.jda.getTextChannelById(config.messageChannels.welcomeChannel).getMessageById(messageID).queue { it.delete().queue() } } } }
src/main/kotlin/me/aberrantfox/hotbot/listeners/BanListener.kt
3742052733
/* * Copyright (C) 2019. Zac Sweers * * 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.sweers.catchup.base.ui.widget import android.annotation.SuppressLint import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.util.TypedValue import androidx.annotation.FontRes import androidx.appcompat.widget.AppCompatTextView import androidx.core.content.res.use import catchup.ui.core.R import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor /** * An extension to [AppCompatTextView] which aligns text to a 4dp baseline grid. * * To achieve this we expose a `lineHeightHint` allowing you to specify the desired line * height (alternatively a `lineHeightMultiplierHint` to use a multiplier of the text size). * This line height will be adjusted to be a multiple of 4dp to ensure that baselines sit on * the grid. * * We also adjust spacing above and below the text to ensure that the first line's baseline sits on * the grid (relative to the view's top) & that this view's height is a multiple of 4dp so that * subsequent views start on the grid. */ @SuppressLint("Recycle") // False positive class BaselineGridTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : AppCompatTextView( context, attrs, defStyleAttr ) { private val fourDip: Float var lineHeightMultiplierHint = 1f set(value) { field = value computeLineHeight() } var lineHeightHint = 0f set(value) { field = value computeLineHeight() } var maxLinesByHeight = false set(value) { field = value requestLayout() } private var extraTopPadding = 0 private var extraBottomPadding = 0 @FontRes var fontResId = 0 private set init { context.obtainStyledAttributes( attrs, R.styleable.BaselineGridTextView, defStyleAttr, 0 ).use { // first check TextAppearance for line height & font attributes if (it.hasValue(R.styleable.BaselineGridTextView_android_textAppearance)) { val textAppearanceId = it.getResourceId( R.styleable.BaselineGridTextView_android_textAppearance, android.R.style.TextAppearance ) context.obtainStyledAttributes( textAppearanceId, R.styleable.BaselineGridTextView ).use { parseTextAttrs(it) } } // then check view attrs parseTextAttrs(it) maxLinesByHeight = it.getBoolean(R.styleable.BaselineGridTextView_maxLinesByHeight, false) } fourDip = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 4f, resources.displayMetrics ) computeLineHeight() } override fun getCompoundPaddingTop(): Int { // include extra padding to place the first line's baseline on the grid return super.getCompoundPaddingTop() + extraTopPadding } override fun getCompoundPaddingBottom(): Int { // include extra padding to make the height a multiple of 4dp return super.getCompoundPaddingBottom() + extraBottomPadding } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { extraTopPadding = 0 extraBottomPadding = 0 super.onMeasure(widthMeasureSpec, heightMeasureSpec) var height = measuredHeight height += ensureBaselineOnGrid() height += ensureHeightGridAligned(height) setMeasuredDimension(measuredWidth, height) checkMaxLines(height, MeasureSpec.getMode(heightMeasureSpec)) } private fun parseTextAttrs(a: TypedArray) { if (a.hasValue(R.styleable.BaselineGridTextView_lineHeightMultiplierHint)) { lineHeightMultiplierHint = a.getFloat( R.styleable.BaselineGridTextView_lineHeightMultiplierHint, 1f ) } if (a.hasValue(R.styleable.BaselineGridTextView_lineHeightHint)) { lineHeightHint = a.getDimensionPixelSize( R.styleable.BaselineGridTextView_lineHeightHint, 0 ).toFloat() } if (a.hasValue(R.styleable.BaselineGridTextView_android_fontFamily)) { fontResId = a.getResourceId(R.styleable.BaselineGridTextView_android_fontFamily, 0) } } /** * Ensures line height is a multiple of 4dp. */ private fun computeLineHeight() { val fm = paint.fontMetrics val fontHeight = abs(fm.ascent - fm.descent) + fm.leading val desiredLineHeight = if (lineHeightHint > 0) lineHeightHint else lineHeightMultiplierHint * fontHeight val baselineAlignedLineHeight = (fourDip * ceil((desiredLineHeight / fourDip).toDouble()).toFloat() + 0.5f).toInt() setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f) } /** * Ensure that the first line of text sits on the 4dp grid. */ private fun ensureBaselineOnGrid(): Int { val baseline = baseline.toFloat() val gridAlign = baseline % fourDip if (gridAlign != 0f) { extraTopPadding = (fourDip - ceil(gridAlign.toDouble())).toInt() } return extraTopPadding } /** * Ensure that height is a multiple of 4dp. */ private fun ensureHeightGridAligned(height: Int): Int { val gridOverhang = height % fourDip if (gridOverhang != 0f) { extraBottomPadding = (fourDip - ceil(gridOverhang.toDouble())).toInt() } return extraBottomPadding } /** * When measured with an exact height, text can be vertically clipped mid-line. Prevent * this by setting the `maxLines` property based on the available space. */ private fun checkMaxLines(height: Int, heightMode: Int) { if (!maxLinesByHeight || heightMode != MeasureSpec.EXACTLY) return val textHeight = height - compoundPaddingTop - compoundPaddingBottom val completeLines = floor((textHeight / lineHeight).toDouble()).toInt() maxLines = completeLines } }
libraries/base-ui/src/main/kotlin/io/sweers/catchup/base/ui/widget/BaselineGridTextView.kt
876240527
fun main(args: Array<String>) { <caret> listOf(5, null).asSequence().lastIndexOf(null) }
plugins/kotlin/jvm-debugger/test/testData/sequence/psi/sequence/positive/types/NullableInt.kt
560773259
// "Remove useless cast" "true" fun foo(a: String) { val b = a <caret>as String }
plugins/kotlin/idea/tests/testData/quickfix/expressions/removeUselessCast.kt
735089050
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiUtilCore import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespace class KotlinValueArgumentListFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { if (element !is KtValueArgumentList || element.rightParenthesis != null) return val lPar = element.leftParenthesis ?: return val lastArgument = element.arguments.lastOrNull() if (lastArgument != null && PsiUtilCore.hasErrorElementChild(lastArgument)) { val prev = lastArgument.getPrevSiblingIgnoringWhitespace() ?: lPar val offset = prev.endOffset if (prev == lPar) { editor.document.insertString(offset, ")") editor.caretModel.moveToOffset(offset) } else { editor.document.insertString(offset, " )") editor.caretModel.moveToOffset(offset + 1) } } else { val offset = lastArgument?.endOffset ?: element.endOffset editor.document.insertString(offset, ")") editor.caretModel.moveToOffset(offset + 1) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinValueArgumentListFixer.kt
2679703686
package me.ycdev.android.lib.common.packets class PacketsException(message: String) : Exception(message)
baseLib/src/main/java/me/ycdev/android/lib/common/packets/PacketsException.kt
1228545836