content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
private const val VERSION_TESTFX = "4.0.16-alpha" fun Dependencies.testFx(module: String) = "org.testfx:testfx-$module:$VERSION_TESTFX"
buildSrc/src/dependencies/testfx.kt
655936387
package ben.upsilon.up.done import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import ben.upsilon.up.R /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [BlankFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [BlankFragment.newInstance] factory method to * create an instance of this fragment. */ class BlankFragment : Fragment() { // TODO: Rename and change types of parameters private var mParam1: String? = null private var mParam2: String? = null private var mListener: OnFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mParam1 = arguments?.getString(ARG_PARAM1) mParam2 = arguments?.getString(ARG_PARAM2) } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // wtf.text="$mParam1 +++ $mParam2" } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_blank, container, false) } // TODO: Rename method, update argument and hook method into UI event fun onButtonPressed(uri: Uri) { if (mListener != null) { mListener!!.onFragmentInteraction(uri) } } override fun onDetach() { super.onDetach() mListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { // TODO: Update argument type and name fun onFragmentInteraction(uri: Uri) } companion object { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private val ARG_PARAM1 = "param1" private val ARG_PARAM2 = "param2" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @param param1 Parameter 1. * * * @param param2 Parameter 2. * * * @return A new instance of fragment BlankFragment. */ // TODO: Rename and change types and number of parameters fun newInstance(param1: String, param2: String): BlankFragment { val fragment = BlankFragment() val args = Bundle() args.putString(ARG_PARAM1, param1) args.putString(ARG_PARAM2, param2) fragment.arguments = args return fragment } } }// Required empty public constructor
up/src/main/java/ben/upsilon/up/done/BlankFragment.kt
1304287095
package com.zzkun.util.date import com.zzkun.service.* import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.util.* import javax.annotation.PostConstruct /** * Created by Administrator on 2017/2/19 0019. */ @Component open class ScheduledManager( @Autowired private val ojContestService: OJContestService, @Autowired private val extOjService: ExtOjService, @Autowired private val ratingService: RatingService, @Autowired private val cfbcService: CFBCService, @Autowired private val systemService: SystemService) { companion object { private val logger: Logger = LoggerFactory.getLogger(ScheduledManager::class.java) } val timer = Timer() // 注册计划任务 @PostConstruct fun run() { timer.schedule(object : TimerTask() { override fun run() { try { logger.info("做题统计:6小时") extOjService.flushACDB() } catch(e: Exception) { e.printStackTrace() } } }, 3600 * 1000L, 6 * 3600 * 1000L) timer.schedule(object : TimerTask() { override fun run() { try { logger.info("近期比赛:1小时") ojContestService.flushOJContests() } catch(e: Exception) { e.printStackTrace() } } }, 3600 * 1000L, 1 * 3600 * 1000L) timer.schedule(object : TimerTask() { override fun run() { try { logger.info("全局比赛Rating:1天") ratingService.flushGlobalUserRating() } catch(e: Exception) { e.printStackTrace() } } }, 3600 * 1000L, 24 * 3600 * 1000L) timer.schedule(object : TimerTask() { override fun run() { try { logger.info("CF/BC Rating:12小时") cfbcService.flushBCUserInfos() cfbcService.flushCFUserInfos() } catch(e: Exception) { e.printStackTrace() } } }, 3600 * 1000L, 12 * 3600 * 1000L) timer.schedule(object : TimerTask() { override fun run() { try { logger.info("更新系统状态:1天") systemService.saveCurState() } catch(e: Exception) { e.printStackTrace() } } }, 60 * 1000L, 24 * 3600 * 1000L) logger.info("注册计划任务完毕...") } }
src/main/java/com/zzkun/util/date/ScheduledManager.kt
1164385106
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.text import org.lanternpowered.api.text.BlockDataText import org.lanternpowered.api.text.EntityDataText import org.lanternpowered.api.text.KeybindText import org.lanternpowered.api.text.ScoreText import org.lanternpowered.api.text.SelectorText import org.lanternpowered.api.text.StorageDataText import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.TranslatableText import org.lanternpowered.api.text.emptyText import org.lanternpowered.api.text.literalTextBuilderOf import org.lanternpowered.api.text.textOf import org.lanternpowered.api.text.translation.Translator import org.lanternpowered.api.util.optional.orNull import java.text.MessageFormat /** * A [LanternTextRenderer] that renders all the [Text] components in their literal form. */ class LiteralTextRenderer( private val translator: Translator ) : LanternTextRenderer<FormattedTextRenderContext>() { override fun renderKeybindIfNeeded(text: KeybindText, context: FormattedTextRenderContext): Text? = literalTextBuilderOf("[${text.keybind()}]") .applyStyleAndChildren(text, context).build() override fun renderSelectorIfNeeded(text: SelectorText, context: FormattedTextRenderContext): Text? = literalTextBuilderOf(text.pattern()) .applyStyleAndChildren(text, context).build() override fun renderScoreIfNeeded(text: ScoreText, context: FormattedTextRenderContext): Text? { val value = text.value() if (value != null) return literalTextBuilderOf(value).applyStyleAndChildren(text, context).build() val scoreboard = context.scoreboard ?: return emptyText() val objective = scoreboard.getObjective(text.objective()).orNull() ?: return emptyText() var name = text.name() // This shows the readers own score if (name == "*") { name = context.player?.name ?: "" if (name.isEmpty()) return emptyText() } val score = objective.getScore(textOf(name)).orNull() ?: return emptyText() return literalTextBuilderOf(score.score.toString()).applyStyleAndChildren(text, context).build() } // TODO: Lookup the actual data from the blocks, entities, etc. override fun renderBlockNbtIfNeeded(text: BlockDataText, context: FormattedTextRenderContext): Text? = literalTextBuilderOf("[${text.nbtPath()}] @ ${text.pos().asString()}") .applyStyleAndChildren(text, context).build() override fun renderEntityNbtIfNeeded(text: EntityDataText, context: FormattedTextRenderContext): Text? = literalTextBuilderOf("[${text.nbtPath()}] @ ${text.selector()}") .applyStyleAndChildren(text, context).build() override fun renderStorageNbtIfNeeded(text: StorageDataText, context: FormattedTextRenderContext): Text? = literalTextBuilderOf("[${text.nbtPath()}] @ ${text.storage()}") .applyStyleAndChildren(text, context).build() override fun renderTranslatableIfNeeded(text: TranslatableText, context: FormattedTextRenderContext): Text? { val format = this.translate(text.key(), context) if (format != null) return super.renderTranslatableIfNeeded(text, context) return literalTextBuilderOf(text.key()) .applyStyleAndChildren(text, context).build() } override fun translate(key: String, context: FormattedTextRenderContext): MessageFormat? = this.translator.translate(key, context.locale) }
src/main/kotlin/org/lanternpowered/server/text/LiteralTextRenderer.kt
722773350
package com.zzkun.service.extoj import com.zzkun.dao.UserRepo import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit4.SpringJUnit4ClassRunner /** * Created by kun on 2016/9/29. */ @RunWith(SpringJUnit4ClassRunner::class) @ContextConfiguration(locations = arrayOf("classpath*:springmvc-servlet.xml")) class VJudgeServiceTest { @Autowired lateinit var vjudgeService: VJudgeService @Autowired lateinit var userRepo: UserRepo @Test fun userACPbs() { // val user = userRepo.findByUsername("kun368") // val list = vjudgeService.getUserACPbsOnline(user) // for (acPb in list) { // println(acPb) // } // println(list.size) } }
src/test/java/com/zzkun/service/extoj/VJudgeServiceTest.kt
2270567576
package nos2jdbc.tutorial.kotlinspring.entity.nonauto import javax.persistence.Entity import javax.persistence.OneToOne import nos2jdbc.annotation.NoFk import nos2jdbc.annotation.NonAuto @Entity @NonAuto class YmItemMember { var memberId: Long? = null var memberName: String? = null @OneToOne @NoFk var ymItem: YmItem? = null }
nos2jdbc-tutorial-kotlin-spring/src/main/kotlin/nos2jdbc/tutorial/kotlinspring/entity/nonauto/YmItemMember.kt
2554366645
package io.rover.sdk.experiences.ui.blocks.concerns.text import android.graphics.Paint /** * A selected [Font] with a size, colour, and alignment to be drawn. */ internal data class FontAppearance( /** * Font size, in Android Scalable Pixels. */ val fontSize: Int, val font: Font, /** * An ARGB color value suitable for use with various Android APIs. */ val color: Int, val align: Paint.Align )
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/concerns/text/FontAppearance.kt
807672043
/* * Copyright (C) 2018 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.entitymapper import android.database.Cursor import net.simonvt.cathode.common.data.MappedCursorLiveData import net.simonvt.cathode.entity.Episode object EpisodeListMapper : MappedCursorLiveData.CursorMapper<List<Episode>> { override fun map(cursor: Cursor): List<Episode> { val episodes = mutableListOf<Episode>() cursor.moveToPosition(-1) while (cursor.moveToNext()) { episodes.add(EpisodeMapper.mapEpisode(cursor)) } return episodes } }
cathode/src/main/java/net/simonvt/cathode/entitymapper/EpisodeListMapper.kt
1049468359
package com.makeevapps.simpletodolist.viewmodel import android.arch.lifecycle.ViewModel import android.databinding.ObservableBoolean import android.databinding.ObservableField import android.os.Bundle import com.makeevapps.simpletodolist.App import com.makeevapps.simpletodolist.Keys.KEY_ALL_DAY import com.makeevapps.simpletodolist.Keys.KEY_DUE_DATE_IN_MILLIS import com.makeevapps.simpletodolist.datasource.preferences.PreferenceManager import com.makeevapps.simpletodolist.utils.DateUtils import com.makeevapps.simpletodolist.utils.extension.asString import com.makeevapps.simpletodolist.utils.extension.toEndDay import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import java.util.* import javax.inject.Inject class DateTimePickerViewModel : ViewModel() { @Inject lateinit var preferenceManager: PreferenceManager val timeText = ObservableField<String>() val allDay = ObservableBoolean() internal val calendar: BehaviorSubject<Calendar> = BehaviorSubject.create() private val compositeDisposable = CompositeDisposable() private val is24HoursFormat: Boolean init { App.component.inject(this) is24HoursFormat = preferenceManager.is24HourFormat() compositeDisposable.add(calendar.subscribe({ val timeString = calendar.value.time?.let { if (is24HoursFormat) { it.asString(DateUtils.TIME_24H_FORMAT) } else { it.asString(DateUtils.TIME_12H_FORMAT) } } timeText.set(timeString) })) } /** * Init logic * */ fun initData(arguments: Bundle) { val longDate = arguments.getLong(KEY_DUE_DATE_IN_MILLIS) val oldDate = if (longDate > 0) Date(longDate) else null val allDay = arguments.getBoolean(KEY_ALL_DAY, true) val tempCalendar = Calendar.getInstance() if (oldDate != null) { tempCalendar.time = oldDate this.allDay.set(allDay) } else { tempCalendar.time = DateUtils.endCurrentDayDate() this.allDay.set(true) } calendar.onNext(tempCalendar) } fun setDateToCalendar(year: Int, monthOfYear: Int, dayOfMonth: Int) { val tempCalendar = calendar.value tempCalendar.set(Calendar.YEAR, year) tempCalendar.set(Calendar.MONTH, monthOfYear) tempCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth) calendar.onNext(tempCalendar) } fun setTimeToCalendar(date: Date?) { if (date != null) { val tempCalendar = Calendar.getInstance() tempCalendar.time = date calendar.onNext(tempCalendar) allDay.set(false) } else { calendar.onNext(calendar.value.toEndDay()) allDay.set(true) } } override fun onCleared() { compositeDisposable.clear() } }
app/src/main/java/com/makeevapps/simpletodolist/viewmodel/DateTimePickerViewModel.kt
3290412393
package nl.hannahsten.texifyidea.psi import com.intellij.testFramework.ParsingTestCase import nl.hannahsten.texifyidea.LatexParserDefinition class LatexParserToPsiTest : ParsingTestCase("", "tex", LatexParserDefinition()) { override fun getTestDataPath(): String = "test/resources/psi/parser" override fun skipSpaces(): Boolean = false override fun includeRanges(): Boolean = true fun testParsingInlineVerbatim() { doTest(true) } fun testLatex3Syntax() { doTest(true) } }
test/nl/hannahsten/texifyidea/psi/LatexParserToPsiTest.kt
3629041435
package voice.playbackScreen import voice.playback.misc.Decibel import java.text.DecimalFormat import javax.inject.Inject class VolumeGainFormatter @Inject constructor() { private val dbFormat = DecimalFormat("0.0 dB") fun format(gain: Decibel): String { return dbFormat.format(gain.value) } }
playbackScreen/src/main/kotlin/voice/playbackScreen/VolumeGainFormatter.kt
3535110207
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.rules.Case import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class ComplexInterfaceSpec : SubjectSpek<ComplexInterface>({ subject { ComplexInterface(threshold = THRESHOLD) } given("several interface declarations") { val path = Case.ComplexInterfacePositive.path() it("reports interfaces which member size exceeds the threshold") { assertThat(subject.lint(path)).hasSize(2) } it("reports interfaces which member size exceeds the threshold including static declarations") { val config = TestConfig(mapOf(ComplexInterface.INCLUDE_STATIC_DECLARATIONS to "true")) val rule = ComplexInterface(config, threshold = THRESHOLD) assertThat(rule.lint(path)).hasSize(3) } it("does not report interfaces which member size is under the threshold") { assertThat(subject.lint(Case.ComplexInterfaceNegative.path())).hasSize(0) } } }) private const val THRESHOLD = 4
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/ComplexInterfaceSpec.kt
818097105
package com.habitrpg.android.habitica.ui.fragments.preferences import android.app.ProgressDialog import android.app.Service import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.DialogInterface import android.content.SharedPreferences import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.preference.EditTextPreference import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceCategory import android.view.LayoutInflater import android.widget.EditText import android.widget.LinearLayout import android.widget.Toast import com.habitrpg.android.habitica.HabiticaApplication import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.events.commands.OpenGemPurchaseFragmentCommand import com.habitrpg.android.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.helpers.QrCodeManager import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.views.subscriptions.SubscriptionDetailsView import org.greenrobot.eventbus.EventBus import rx.Observable import rx.functions.Action1 class AuthenticationPreferenceFragment: BasePreferencesFragment() { override var user: User? = null set(value) { field = value updateUserFields() } override fun onCreate(savedInstanceState: Bundle?) { HabiticaBaseApplication.getComponent().inject(this) super.onCreate(savedInstanceState) } private fun updateUserFields() { configurePreference(findPreference("login_name"), user?.authentication?.localAuthentication?.username) configurePreference(findPreference("email"), user?.authentication?.localAuthentication?.email) } private fun configurePreference(preference: Preference?, value: String?) { preference?.summary = value } override fun setupPreferences() { updateUserFields() } override fun onPreferenceTreeClick(preference: Preference): Boolean { when (preference.key) { "login_name" -> showLoginNameDialog() "email" -> showEmailDialog() "change_password" -> showChangePasswordDialog() "subscription_status" -> { if (user != null && user!!.purchased != null && user!!.purchased.plan != null) { val plan = user!!.purchased.plan if (plan.isActive) { showSubscriptionStatusDialog() return super.onPreferenceTreeClick(preference) } } EventBus.getDefault().post(OpenGemPurchaseFragmentCommand()) } "reset_account" -> showAccountResetConfirmation() "delete_account" -> showAccountDeleteConfirmation() else -> { val clipMan = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipMan.primaryClip = ClipData.newPlainText(preference.key, preference.summary) Toast.makeText(activity, "Copied " + preference.key + " to clipboard.", Toast.LENGTH_SHORT).show() } } return super.onPreferenceTreeClick(preference) } private fun showChangePasswordDialog() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } private fun showEmailDialog() { val inflater = context.layoutInflater val view = inflater.inflate(R.layout.dialog_edittext_confirm_pw, null) val emailEditText = view.findViewById<EditText>(R.id.editText) emailEditText.setText(user?.authentication?.localAuthentication?.email) val passwordEditText = view.findViewById<EditText>(R.id.passwordEditText) val dialog = AlertDialog.Builder(context) .setTitle(R.string.change_email) .setPositiveButton(R.string.change) { thisDialog, _ -> thisDialog.dismiss() userRepository.updateEmail(emailEditText.text.toString(), passwordEditText.text.toString()) .subscribe(Action1 { configurePreference(findPreference("email"), emailEditText.text.toString()) }, RxErrorHandler.handleEmptyError()) } .setNegativeButton(R.string.action_cancel) { thisDialog, _ -> thisDialog.dismiss() } .create() dialog.setView(view) dialog.show() } private fun showLoginNameDialog() { val inflater = context.layoutInflater val view = inflater.inflate(R.layout.dialog_edittext_confirm_pw, null) val loginNameEditText = view.findViewById<EditText>(R.id.editText) loginNameEditText.setText(user?.authentication?.localAuthentication?.username) val passwordEditText = view.findViewById<EditText>(R.id.passwordEditText) val dialog = AlertDialog.Builder(context) .setTitle(R.string.change_login_name) .setPositiveButton(R.string.change) { thisDialog, _ -> thisDialog.dismiss() userRepository.updateLoginName(loginNameEditText.text.toString(), passwordEditText.text.toString()) .subscribe(Action1 { configurePreference(findPreference("login_name"), loginNameEditText.text.toString()) }, RxErrorHandler.handleEmptyError()) } .setNegativeButton(R.string.action_cancel) { thisDialog, _ -> thisDialog.dismiss() } .create() dialog.setView(view) dialog.show() } private fun showAccountDeleteConfirmation() { val input = EditText(context) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT) input.layoutParams = lp val dialog = AlertDialog.Builder(context) .setTitle(R.string.delete_account) .setMessage(R.string.delete_account_description) .setPositiveButton(R.string.delete_account_confirmation) { thisDialog, _ -> thisDialog.dismiss() deleteAccount(input.text.toString()) } .setNegativeButton(R.string.nevermind) { thisDialog, _ -> thisDialog.dismiss() } .create() dialog.setOnShowListener { _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.red_10)) } dialog.setView(input) dialog.show() } private fun deleteAccount(password: String) { val dialog = ProgressDialog.show(context, context.getString(R.string.deleting_account), null, true) userRepository.deleteAccount(password).subscribe({ _ -> HabiticaApplication.logout(context) activity.finish() }) { throwable -> dialog.dismiss() RxErrorHandler.reportError(throwable) } } private fun showAccountResetConfirmation() { val dialog = AlertDialog.Builder(context) .setTitle(R.string.reset_account) .setMessage(R.string.reset_account_description) .setPositiveButton(R.string.reset_account_confirmation) { thisDialog, _ -> thisDialog.dismiss() resetAccount() } .setNegativeButton(R.string.nevermind) { thisDialog, _ -> thisDialog.dismiss() } .create() dialog.setOnShowListener { _ -> dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.red_10)) } dialog.show() } private fun resetAccount() { val dialog = ProgressDialog.show(context, context.getString(R.string.resetting_account), null, true) userRepository.resetAccount().subscribe({ _ -> dialog.dismiss() }) { throwable -> dialog.dismiss() RxErrorHandler.reportError(throwable) } } private fun showSubscriptionStatusDialog() { val view = SubscriptionDetailsView(context) view.setPlan(user?.purchased?.plan) val dialog = AlertDialog.Builder(context) .setView(view) .setTitle(R.string.subscription_status) .setPositiveButton(R.string.close) { dialogInterface, _ -> dialogInterface.dismiss() }.create() dialog.show() } }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/AuthenticationPreferenceFragment.kt
906933400
package eu.fizzystuff.krog.scenes import com.google.common.collect.ImmutableList import com.google.inject.Guice import com.google.inject.Inject import com.google.inject.Injector import com.googlecode.lanterna.input.KeyStroke import com.googlecode.lanterna.screen.AbstractScreen import com.googlecode.lanterna.terminal.Terminal import eu.fizzystuff.krog.main.KrogModule import eu.fizzystuff.krog.scenes.mainscreen.AddActionPoints import eu.fizzystuff.krog.scenes.mainscreen.NpcAI import eu.fizzystuff.krog.scenes.aspects.MainMapDrawingComponent import eu.fizzystuff.krog.scenes.mainscreen.input.ExitGame import eu.fizzystuff.krog.scenes.mainscreen.input.PlayerCharacterMovement import eu.fizzystuff.krog.scenes.visibility.RaycastingVisibilityStrategy import eu.fizzystuff.krog.model.PlayerCharacter import eu.fizzystuff.krog.model.WorldState import eu.fizzystuff.krog.scenes.aspects.MessageBufferDrawingComponent import eu.fizzystuff.krog.ui.MessageBuffer class MainScreenScene public @Inject constructor(val injector: Injector, val mainMapDrawingComponent: MainMapDrawingComponent, val messageBufferDrawingComponent: MessageBufferDrawingComponent, val terminal: Terminal, val messageBuffer: MessageBuffer, val screen: AbstractScreen) : Scene() { override fun run(): SceneTransition? { while(true) { draw() acceptInput(terminal.readInput()) val sceneTransition = tick() if (sceneTransition != null) { return sceneTransition } } } override fun destroy() { } var inputNodes: List<InputNode> = listOf() var logicNodes: List<LogicNode> = listOf() override fun init() { calculateVisibility() inputNodes = ImmutableList.of(injector.getInstance(PlayerCharacterMovement::class.java), injector.getInstance(ExitGame::class.java)) logicNodes = ImmutableList.of(injector.getInstance(AddActionPoints::class.java), injector.getInstance(NpcAI::class.java)) } fun draw() { messageBufferDrawingComponent.draw(0, 0, ImmutableList.of(messageBuffer.poll(80), messageBuffer.poll(80))) mainMapDrawingComponent.draw(0, 2) screen.refresh() } fun acceptInput(input: KeyStroke): SceneTransition? { inputNodes.map { x -> x.process(input) } calculateVisibility() return null } fun tick(): SceneTransition? { while (true) { logicNodes.map { x -> x.process() } if (PlayerCharacter.instance.actionPoints >= PlayerCharacter.instance.actionCost) { break } } if (messageBuffer.size() > 160) { return SceneTransition(MainScreenMessageBufferScene::class.java) } return null } private fun calculateVisibility() { val visibilityMap = RaycastingVisibilityStrategy().calculateVisibility(WorldState.instance.currentDungeonLevel, PlayerCharacter.instance.x, PlayerCharacter.instance.y, 4) for (x in 0..WorldState.instance.currentDungeonLevel.width - 1) { for (y in 0..WorldState.instance.currentDungeonLevel.height - 1) { WorldState.instance.currentDungeonLevel.setVisible(x, y, visibilityMap[x][y]) } } } }
src/main/kotlin/eu/fizzystuff/krog/scenes/MainScreenScene.kt
2232133566
package net.ndrei.teslapoweredthingies.common import com.mojang.authlib.GameProfile import net.minecraft.entity.Entity import net.minecraft.item.ItemStack import net.minecraft.util.EnumHand import net.minecraft.world.WorldServer import net.minecraftforge.common.util.FakePlayer import java.lang.ref.WeakReference import java.util.* class TeslaFakePlayer(world: WorldServer, name: GameProfile) : FakePlayer(world, name) { fun setItemInUse(stack: ItemStack) { this.setHeldItem(EnumHand.MAIN_HAND, stack) this.setHeldItem(EnumHand.OFF_HAND, ItemStack.EMPTY) this.activeHand = EnumHand.MAIN_HAND } fun resetTicksSinceLastSwing() { this.ticksSinceLastSwing = Int.MAX_VALUE } override fun attackTargetEntityWithCurrentItem(targetEntity: Entity?) { this.resetTicksSinceLastSwing() super.attackTargetEntityWithCurrentItem(targetEntity) } override fun getDistanceSq(x: Double, y: Double, z: Double) = 0.0 override fun getDistance(x: Double, y: Double, z: Double) = 0.0 // override fun getSoundVolume() = 0.0f companion object { private val PROFILE = GameProfile(UUID.fromString("225F6E4B-5BAE-4BDA-9B88-2397DEFD95EB"), "[TESLA_THINGIES]") private var PLAYER: WeakReference<TeslaFakePlayer>? = null fun getPlayer(world: WorldServer): TeslaFakePlayer { var ret: TeslaFakePlayer? = if (PLAYER != null) PLAYER!!.get() else null if (ret == null) { ret = TeslaFakePlayer(world, PROFILE) PLAYER = WeakReference(ret) } return ret } } }
src/main/kotlin/net/ndrei/teslapoweredthingies/common/TeslaFakePlayer.kt
2878253436
package net.ndrei.teslapoweredthingies.machines.animalfarm import com.google.common.collect.Lists import net.minecraft.entity.passive.EntityAnimal import net.minecraft.entity.passive.EntityCow import net.minecraft.entity.passive.EntityMooshroom import net.minecraft.entity.player.EntityPlayer import net.minecraft.init.Blocks import net.minecraft.init.Items import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraftforge.common.IShearable /** * Created by CF on 2017-07-07. */ open class VanillaGenericAnimal(override val animal: EntityAnimal) : IAnimalWrapper { override fun breedable(): Boolean { val animal = this.animal return !animal.isInLove && !animal.isChild && animal.growingAge == 0 } override fun isFood(stack: ItemStack): Boolean { return this.animal.isBreedingItem(stack) } override fun canMateWith(wrapper: IAnimalWrapper): Boolean { return this.breedable() && wrapper.breedable() && this.animal.javaClass == wrapper.animal.javaClass } override fun mate(player: EntityPlayer, stack: ItemStack, wrapper: IAnimalWrapper): Int { val consumedFood: Int val neededFood = 2 * this.getFoodNeededForMating(stack) consumedFood = if (stack.count < neededFood) { 0 } else if (!this.canMateWith(wrapper) || !this.isFood(stack)) { 0 } else { this.animal.setInLove(player) wrapper.animal.setInLove(player) neededFood } return consumedFood } protected open fun getFoodNeededForMating(stack: ItemStack): Int { return 1 } override fun shearable(): Boolean { return this.animal !is EntityMooshroom && this.animal is IShearable } override fun canBeShearedWith(stack: ItemStack): Boolean { if (stack.isEmpty || stack.item !== Items.SHEARS) { return false } var isShearable = false val animal = this.animal if (this.shearable() && animal is IShearable) { val shearable = animal as IShearable isShearable = shearable.isShearable(stack, animal.entityWorld, animal.position) } return isShearable } override fun shear(stack: ItemStack, fortune: Int): List<ItemStack> { var result: List<ItemStack> = Lists.newArrayList<ItemStack>() val animal = this.animal if (animal is IShearable) { val shearable = animal as IShearable if (shearable.isShearable(stack, animal.entityWorld, animal.position)) { result = shearable.onSheared(stack, animal.entityWorld, animal.position, fortune) } } return result } override fun canBeMilked(): Boolean { val animal = this.animal return animal is EntityCow && !animal.isChild } override fun milk(): ItemStack { return if (this.canBeMilked()) ItemStack(Items.MILK_BUCKET, 1) else ItemStack.EMPTY } override fun canBeBowled(): Boolean { val animal = this.animal return animal is EntityMooshroom && !animal.isChild } override fun bowl(): ItemStack { return if (this.canBeBowled()) ItemStack(Items.MUSHROOM_STEW, 1) else ItemStack.EMPTY } companion object { fun populateFoodItems(food: MutableList<Item>) { // cows / mooshrooms food.add(Items.WHEAT) // chicken food.add(Items.WHEAT_SEEDS) food.add(Items.BEETROOT_SEEDS) food.add(Items.PUMPKIN_SEEDS) food.add(Items.MELON_SEEDS) // pigs food.add(Items.CARROT) food.add(Items.POTATO) food.add(Items.BEETROOT) food.add(Items.GOLDEN_CARROT) food.add(Item.getItemFromBlock(Blocks.HAY_BLOCK)) food.add(Items.APPLE) } } }
src/main/kotlin/net/ndrei/teslapoweredthingies/machines/animalfarm/VanillaGenericAnimal.kt
162274750
/* Copyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.androidstudiopoet.generators import com.google.androidstudiopoet.testutils.mock import com.google.androidstudiopoet.utils.joinPath import com.google.androidstudiopoet.writers.FileWriter import com.nhaarman.mockitokotlin2.verify import org.junit.Test class DependencyGraphGeneratorTest: DependencyGraphBase() { private val fileWriter: FileWriter = mock() private val dependencyImageGenerator: DependencyImageGenerator = mock() private val dependencyGraphGenerator = DependencyGraphGenerator(fileWriter, dependencyImageGenerator) @Test fun `generator dot file is correct`() { val blueprint = getProjectBlueprint() dependencyGraphGenerator.generate(blueprint) val expectedPath = "projectRoot".joinPath("dependencies.dot") verify(fileWriter).writeToFile(expectedGraphText, expectedPath) } @Test fun `generator image is called`() { val blueprint = getProjectBlueprint() dependencyGraphGenerator.generate(blueprint) verify(dependencyImageGenerator).generate(blueprint) } }
aspoet/src/test/kotlin/com/google/androidstudiopoet/generators/DependencyGraphGeneratorTest.kt
147512855
package com.simplecity.amp_library.ui.screens.album.list import android.annotation.SuppressLint import com.simplecity.amp_library.data.AlbumsRepository import com.simplecity.amp_library.model.AlbumArtist import com.simplecity.amp_library.ui.common.Presenter import com.simplecity.amp_library.ui.screens.album.list.AlbumListContract.View import com.simplecity.amp_library.ui.screens.album.menu.AlbumMenuContract import com.simplecity.amp_library.ui.screens.album.menu.AlbumMenuPresenter import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.sorting.SortManager import io.reactivex.android.schedulers.AndroidSchedulers import javax.inject.Inject class AlbumsPresenter @Inject constructor( private val albumsRepository: AlbumsRepository, private val sortManager: SortManager, private val albumsMenuPresenter: AlbumMenuPresenter ) : Presenter<View>(), AlbumListContract.Presenter, AlbumMenuContract.Presenter by albumsMenuPresenter { private var albums = mutableListOf<AlbumArtist>() override fun bindView(view: View) { super.bindView(view) albumsMenuPresenter.bindView(view) } override fun unbindView(view: View) { super.unbindView(view) albumsMenuPresenter.unbindView(view) } @SuppressLint("CheckResult") override fun loadAlbums(scrollToTop: Boolean) { addDisposable(albumsRepository.getAlbums() .map { albumArtists -> val albumArtists = albumArtists.toMutableList() sortManager.sortAlbums(albumArtists) if (!sortManager.artistsAscending) { albumArtists.reverse() } albumArtists } .observeOn(AndroidSchedulers.mainThread()) .subscribe( { albumArtists -> this.albums - albumArtists view?.setData(albumArtists) }, { error -> LogUtils.logException(TAG, "refreshAdapterItems error", error) } )) } override fun setAlbumsSortOrder(order: Int) { sortManager.artistsSortOrder = order loadAlbums(true) view?.invalidateOptionsMenu() } override fun setAlbumsAscending(ascending: Boolean) { sortManager.artistsAscending = ascending loadAlbums(true) view?.invalidateOptionsMenu() } companion object { const val TAG = "AlbumPresenter" } }
app/src/main/java/com/simplecity/amp_library/ui/screens/album/list/AlbumListPresenter.kt
3684151957
/* * Copyright 2020-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.coroutines import io.lettuce.core.* import kotlinx.coroutines.flow.Flow /** * Coroutine executed commands for Sorted Sets. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 * @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesApi */ @ExperimentalLettuceCoroutinesApi interface RedisSortedSetCoroutinesCommands<K : Any, V : Any> { /** * Removes and returns a member with the lowest scores in the sorted set stored at one of the keys. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue<K, ScoredValue<V>> multi-bulk containing the name of the key, the score and the popped * member. * @since 5.1 */ suspend fun bzpopmin(timeout: Long, vararg keys: K): KeyValue<K, ScoredValue<V>>? /** * Removes and returns a member with the lowest scores in the sorted set stored at one of the keys. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue<K, ScoredValue<V>> multi-bulk containing the name of the key, the score and the popped * member. * @since 6.1.3 */ suspend fun bzpopmin(timeout: Double, vararg keys: K): KeyValue<K, ScoredValue<V>>? /** * Removes and returns a member with the highest scores in the sorted set stored at one of the keys. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue<K, ScoredValue<V>> multi-bulk containing the name of the key, the score and the popped * member. * @since 5.1 */ suspend fun bzpopmax(timeout: Long, vararg keys: K): KeyValue<K, ScoredValue<V>>? /** * Removes and returns a member with the highest scores in the sorted set stored at one of the keys. * * @param timeout the timeout in seconds. * @param keys the keys. * @return KeyValue<K, ScoredValue<V>> multi-bulk containing the name of the key, the score and the popped * member. * @since 6.1.3 */ suspend fun bzpopmax(timeout: Double, vararg keys: K): KeyValue<K, ScoredValue<V>>? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the key. * @param score the score. * @param member the member. * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, score: Double, member: V): Long? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the key. * @param scoresAndValues the scoresAndValue tuples (score,value,score,value,...). * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, vararg scoresAndValues: Any): Long? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the key. * @param scoredValues the scored values. * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, vararg scoredValues: ScoredValue<V>): Long? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the key. * @param zAddArgs arguments for zadd. * @param score the score. * @param member the member. * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, zAddArgs: ZAddArgs, score: Double, member: V): Long? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the key. * @param zAddArgs arguments for zadd. * @param scoresAndValues the scoresAndValue tuples (score,value,score,value,...). * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, zAddArgs: ZAddArgs, vararg scoresAndValues: Any): Long? /** * Add one or more members to a sorted set, or update its score if it already exists. * * @param key the ke. * @param zAddArgs arguments for zadd. * @param scoredValues the scored values. * @return Long integer-reply specifically: * * The number of elements added to the sorted sets, not including elements already existing for which the score was * updated. */ suspend fun zadd(key: K, zAddArgs: ZAddArgs, vararg scoredValues: ScoredValue<V>): Long? /** * Add one or more members to a sorted set, or update its score if it already exists applying the `INCR` option. ZADD * acts like ZINCRBY. * * @param key the key. * @param score the score. * @param member the member. * @return Long integer-reply specifically: The total number of elements changed. */ suspend fun zaddincr(key: K, score: Double, member: V): Double? /** * Add one or more members to a sorted set, or update its score if it already exists applying the `INCR` option. ZADD * acts like ZINCRBY. * * @param key the key. * @param zAddArgs arguments for zadd. * @param score the score. * @param member the member. * @return Long integer-reply specifically: The total number of elements changed. * @since 4.3 */ suspend fun zaddincr(key: K, zAddArgs: ZAddArgs, score: Double, member: V): Double? /** * Get the number of members in a sorted set. * * @param key the key. * @return Long integer-reply the cardinality (number of elements) of the sorted set, or `false` if `key` does * not exist. */ suspend fun zcard(key: K): Long? /** * Count the members in a sorted set with scores within the given [Range]. * * @param key the key. * @param range the range. * @return Long integer-reply the number of elements in the specified score range. * @since 4.3 */ suspend fun zcount(key: K, range: Range<out Number>): Long? /** * Computes the difference between the first and all successive input sorted sets. * * @param keys the keys. * @return List<V> array-reply list of elements. * @since 6.1 */ fun zdiff(vararg keys: K): Flow<V> /** * Computes the difference between the first and all successive input sorted sets and stores the result in destination. * * @param destKey the dest key. * @param srcKeys the src keys. * @return Long the number of elements in the resulting sorted set at destination. * @since 6.1 */ suspend fun zdiffstore(destKey: K, vararg srcKeys: K): Long? /** * Computes the difference between the first and all successive input sorted sets. * * @param keys the keys. * @return List<V> array-reply list of scored values. * @since 6.1 */ fun zdiffWithScores(vararg keys: K): Flow<ScoredValue<V>> /** * Increment the score of a member in a sorted set. * * @param key the key. * @param amount the increment type: long. * @param member the member type: value. * @return Double bulk-string-reply the new score of `member` (a Double precision floating point number), represented * as string. */ suspend fun zincrby(key: K, amount: Double, member: V): Double? /** * Intersect multiple sorted sets and returns the resulting sorted. * * @param keys the keys. * @return List<V> array-reply list of elements. * @since 6.1 */ fun zinter(vararg keys: K): Flow<V> /** * Intersect multiple sorted sets and returns the resulting sorted. * * @param aggregateArgs arguments to define aggregation and weights. * @param keys the keys. * @return List<V> array-reply list of elements. * @since 6.1 */ fun zinter(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<V> /** * This command is similar to {@link #zinter(Any[])}, but instead of returning the result set, it returns just * the cardinality of the result. * * @param keys the keys. * @return Long Integer reply the number of elements in the resulting intersection. * @since 6.2 */ suspend fun zintercard(vararg keys: K): Long? /** * This command is similar to {@link #zinter(Any[])}, but instead of returning the result set, it returns just * the cardinality of the result. * * @param limit If the intersection cardinality reaches limit partway through the computation, the algorithm will exit and * yield limit as the cardinality * @param keys the keys. * @return Long Integer reply the number of elements in the resulting intersection. * @since 6.2 */ suspend fun zintercard(limit: Long, vararg keys: K): Long? /** * Intersect multiple sorted sets and returns the resulting sorted. * * @param aggregateArgs arguments to define aggregation and weights. * @param keys the keys. * @return List<V> array-reply list of scored values. * @since 6.1 */ fun zinterWithScores( aggregateArgs: ZAggregateArgs, vararg keys: K ): Flow<ScoredValue<V>> /** * Intersect multiple sorted sets and returns the resulting sorted. * * @param keys the keys. * @return List<V> array-reply list of scored values. * @since 6.1 */ fun zinterWithScores(vararg keys: K): Flow<ScoredValue<V>> /** * Intersect multiple sorted sets and store the resulting sorted set in a new key. * * @param destination the destination. * @param keys the keys. * @return Long integer-reply the number of elements in the resulting sorted set at `destination`. */ suspend fun zinterstore(destination: K, vararg keys: K): Long? /** * Intersect multiple sorted sets and store the resulting sorted set in a new key. * * @param destination the destination. * @param storeArgs arguments to define aggregation and weights. * @param keys the keys. * @return Long integer-reply the number of elements in the resulting sorted set at `destination`. */ suspend fun zinterstore(destination: K, storeArgs: ZStoreArgs, vararg keys: K): Long? /** * Count the number of members in a sorted set between a given lexicographical range. * * @param key the key. * @param range the range. * @return Long integer-reply the number of elements in the specified score range. * @since 4.3 */ suspend fun zlexcount(key: K, range: Range<out V>): Long? /** * Returns the scores associated with the specified members in the sorted set stored at key. * * @param key the key. * @param members the member type: value. * @return List<Double> array-reply list of scores or nil associated with the specified member values. * @since 6.1 */ suspend fun zmscore(key: K, vararg members: V): List<Double?> /** * Removes and returns up to count members with the lowest scores in the sorted set stored at key. * * @param key the key. * @return ScoredValue<V> the removed element. * @since 5.1 */ suspend fun zpopmin(key: K): ScoredValue<V>? /** * Removes and returns up to count members with the lowest scores in the sorted set stored at key. * * @param key the key. * @param count the number of elements to return. * @return List<ScoredValue<V>> array-reply list of popped scores and elements. * @since 5.1 */ fun zpopmin(key: K, count: Long): Flow<ScoredValue<V>> /** * Removes and returns up to count members with the highest scores in the sorted set stored at key. * * @param key the key. * @return ScoredValue<V> the removed element. * @since 5.1 */ suspend fun zpopmax(key: K): ScoredValue<V>? /** * Removes and returns up to count members with the highest scores in the sorted set stored at key. * * @param key the key. * @param count the number of elements to return. * @return List<ScoredValue<V>> array-reply list of popped scores and elements. * @since 5.1 */ fun zpopmax(key: K, count: Long): Flow<ScoredValue<V>> /** * Return a random member from the sorted set stored at `key`. * * @param key the key. * @return element. * @since 6.1 */ suspend fun zrandmember(key: K): V? /** * Return `count` random members from the sorted set stored at `key`. * * @param key the key. * @param count the number of members to return. If the provided count argument is positive, return an array of distinct fields. * @return List<ScoredValue<V>> array-reply list of scores and elements. * @since 6.1 */ suspend fun zrandmember(key: K, count: Long): List<V> /** * Return a random member along its value from the sorted set stored at `key`. * * @param key the key. * @return the score and element. * @since 6.1 */ suspend fun zrandmemberWithScores(key: K): ScoredValue<V>? /** * Return `count` random members along their value from the sorted set stored at `key`. * * @param key the key. * @param count the number of members to return. If the provided count argument is positive, return an array of distinct fields. * @return List<ScoredValue<V>> array-reply list of scores and elements. * @since 6.1 */ suspend fun zrandmemberWithScores(key: K, count: Long): List<ScoredValue<V>> /** * Return a range of members in a sorted set, by index. * * @param key the key. * @param start the start. * @param stop the stop. * @return List<V> array-reply list of elements in the specified range. */ fun zrange(key: K, start: Long, stop: Long): Flow<V> /** * Return a range of members with scores in a sorted set, by index. * * @param key the key. * @param start the start. * @param stop the stop. * @return List<V> array-reply list of elements in the specified range. */ fun zrangeWithScores(key: K, start: Long, stop: Long): Flow<ScoredValue<V>> /** * Return a range of members in a sorted set, by lexicographical range. * * @param key the key. * @param range the range. * @return List<V> array-reply list of elements in the specified range. * @since 4.3 */ fun zrangebylex(key: K, range: Range<out V>): Flow<V> /** * Return a range of members in a sorted set, by lexicographical range. * * @param key the key. * @param range the range. * @param limit the limit. * @return List<V> array-reply list of elements in the specified range. * @since 4.3 */ fun zrangebylex(key: K, range: Range<out V>, limit: Limit): Flow<V> /** * Return a range of members in a sorted set, by score. * * @param key the key. * @param range the range. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrangebyscore(key: K, range: Range<out Number>): Flow<V> /** * Return a range of members in a sorted set, by score. * * @param key the key. * @param range the range. * @param limit the limit. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrangebyscore(key: K, range: Range<out Number>, limit: Limit): Flow<V> /** * Return a range of members with score in a sorted set, by score. * * @param key the key. * @param range the range. * @return List<ScoredValue<V>> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrangebyscoreWithScores(key: K, range: Range<out Number>): Flow<ScoredValue<V>> /** * Return a range of members with score in a sorted set, by score. * * @param key the key. * @param range the range. * @param limit the limit. * @return List<ScoredValue<V>> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrangebyscoreWithScores( key: K, range: Range<out Number>, limit: Limit ): Flow<ScoredValue<V>> /** * Get the specified range of elements in the sorted set stored at `srcKey` and stores the result in the `dstKey` destination key. * * @param dstKey the dst key. * @param srcKey the src key. * @param range the rank. * @return the number of elements in the resulting sorted set. * @since 6.2.1 */ suspend fun zrangestore(dstKey: K, srcKey: K, range: Range<Long>): Long? /** * Get the specified range of elements in the sorted set stored at `srcKey` and stores the result in the `dstKey` destination key. * * @param dstKey the dst key. * @param srcKey the src key. * @param range the lexicographical range. * @param limit the limit to apply. * @return the number of elements in the resulting sorted set. * @since 6.1 */ suspend fun zrangestorebylex(dstKey: K, srcKey: K, range: Range<out V>, limit: Limit): Long? /** * Get the specified range of elements in the sorted set stored at `srcKey` and stores the result in the `dstKey` destination key. * * @param dstKey the dst key. * @param srcKey the src key. * @param range the score range. * @param limit the limit to apply. * @return the number of elements in the resulting sorted set. * @since 6.1 */ suspend fun zrangestorebyscore(dstKey: K, srcKey: K, range: Range<out Number>, limit: Limit): Long? /** * Determine the index of a member in a sorted set. * * @param key the key. * @param member the member type: value. * @return Long integer-reply the rank of `member`. If `member` does not exist in the sorted set or `key` * does not exist,. */ suspend fun zrank(key: K, member: V): Long? /** * Remove one or more members from a sorted set. * * @param key the key. * @param members the member type: value. * @return Long integer-reply specifically: * * The number of members removed from the sorted set, not including non existing members. */ suspend fun zrem(key: K, vararg members: V): Long? /** * Remove all members in a sorted set between the given lexicographical range. * * @param key the key. * @param range the range. * @return Long integer-reply the number of elements removed. * @since 4.3 */ suspend fun zremrangebylex(key: K, range: Range<out V>): Long? /** * Remove all members in a sorted set within the given indexes. * * @param key the key. * @param start the start type: long. * @param stop the stop type: long. * @return Long integer-reply the number of elements removed. */ suspend fun zremrangebyrank(key: K, start: Long, stop: Long): Long? /** * Remove all members in a sorted set within the given scores. * * @param key the key. * @param range the range. * @return Long integer-reply the number of elements removed. * @since 4.3 */ suspend fun zremrangebyscore(key: K, range: Range<out Number>): Long? /** * Return a range of members in a sorted set, by index, with scores ordered from high to low. * * @param key the key. * @param start the start. * @param stop the stop. * @return List<V> array-reply list of elements in the specified range. */ fun zrevrange(key: K, start: Long, stop: Long): Flow<V> /** * Return a range of members with scores in a sorted set, by index, with scores ordered from high to low. * * @param key the key. * @param start the start. * @param stop the stop. * @return List<V> array-reply list of elements in the specified range. */ fun zrevrangeWithScores(key: K, start: Long, stop: Long): Flow<ScoredValue<V>> /** * Return a range of members in a sorted set, by lexicographical range ordered from high to low. * * @param key the key. * @param range the range. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebylex(key: K, range: Range<out V>): Flow<V> /** * Return a range of members in a sorted set, by lexicographical range ordered from high to low. * * @param key the key. * @param range the range. * @param limit the limit. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebylex(key: K, range: Range<out V>, limit: Limit): Flow<V> /** * Return a range of members in a sorted set, by score, with scores ordered from high to low. * * @param key the key. * @param range the range. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebyscore(key: K, range: Range<out Number>): Flow<V> /** * Return a range of members in a sorted set, by score, with scores ordered from high to low. * * @param key the key. * @param range the range. * @param limit the limit. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebyscore(key: K, range: Range<out Number>, limit: Limit): Flow<V> /** * Return a range of members with scores in a sorted set, by score, with scores ordered from high to low. * * @param key the key. * @param range the range. * @return List<ScoredValue<V>> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebyscoreWithScores(key: K, range: Range<out Number>): Flow<ScoredValue<V>> /** * Return a range of members with scores in a sorted set, by score, with scores ordered from high to low. * * @param key the key. * @param range the range. * @param limit limit. * @return List<V> array-reply list of elements in the specified score range. * @since 4.3 */ fun zrevrangebyscoreWithScores( key: K, range: Range<out Number>, limit: Limit ): Flow<ScoredValue<V>> /** * Get the specified range of elements ordered from high to low in the sorted set stored at `srcKey` and stores the result in the `dstKey` destination key. * * @param dstKey the dst key. * @param srcKey the src key. * @param range the rank. * @return the number of elements in the resulting sorted set. * @since 6.2.1 */ suspend fun zrevrangestore(dstKey: K, srcKey: K, range: Range<Long>): Long? /** * Get the lexicographical range ordered from high to low of elements in the sorted set stored at `srcKey` and stores the result in the `dstKey` destination key. * * @param dstKey the src key. * @param srcKey the dst key. * @param range the lexicographical range. * @param limit the limit to apply. * @return the number of elements in the resulting sorted set. * @since 6.1 */ suspend fun zrevrangestorebylex(dstKey: K, srcKey: K, range: Range<out V>, limit: Limit): Long? /** * Get the specified range of elements in the sorted set stored at {@code srcKey with scores ordered from high to low and stores the result in the `dstKey` destination key. * * @param dstKey the src key. * @param srcKey the dst key. * @param range the score range. * @param limit the limit to apply. * @return the number of elements in the resulting sorted set. * @since 6.1 */ suspend fun zrevrangestorebyscore(dstKey: K, srcKey: K, range: Range<out Number>, limit: Limit): Long? /** * Determine the index of a member in a sorted set, with scores ordered from high to low. * * @param key the key. * @param member the member type: value. * @return Long integer-reply the rank of `member`. If `member` does not exist in the sorted set or `key` * does not exist,. */ suspend fun zrevrank(key: K, member: V): Long? /** * Incrementally iterate sorted sets elements and associated scores. * * @param key the key. * @return ScoredValueScanCursor<V> scan cursor. */ suspend fun zscan(key: K): ScoredValueScanCursor<V>? /** * Incrementally iterate sorted sets elements and associated scores. * * @param key the key. * @param scanArgs scan arguments. * @return ScoredValueScanCursor<V> scan cursor. */ suspend fun zscan(key: K, scanArgs: ScanArgs): ScoredValueScanCursor<V>? /** * Incrementally iterate sorted sets elements and associated scores. * * @param key the key. * @param scanCursor cursor to resume from a previous scan, must not be `null`. * @param scanArgs scan arguments. * @return ScoredValueScanCursor<V> scan cursor. */ suspend fun zscan(key: K, scanCursor: ScanCursor, scanArgs: ScanArgs): ScoredValueScanCursor<V>? /** * Incrementally iterate sorted sets elements and associated scores. * * @param key the key. * @param scanCursor cursor to resume from a previous scan, must not be `null`. * @return ScoredValueScanCursor<V> scan cursor. */ suspend fun zscan(key: K, scanCursor: ScanCursor): ScoredValueScanCursor<V>? /** * Get the score associated with the given member in a sorted set. * * @param key the key. * @param member the member type: value. * @return Double bulk-string-reply the score of `member` (a Double precision floating point number), represented as * string. */ suspend fun zscore(key: K, member: V): Double? /** * Add multiple sorted sets and returns the resulting sorted set. * * @param keys the keys. * @return List<V> array-reply list of elements. * @since 6.1 */ fun zunion(vararg keys: K): Flow<V> /** * Add multiple sorted sets and returns the resulting sorted set. * * @param aggregateArgs arguments to define aggregation and weights. * @param keys the keys. * @return List<V> array-reply list of elements. * @since 6.1 */ fun zunion(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<V> /** * Add multiple sorted sets and returns the resulting sorted set. * * @param aggregateArgs arguments to define aggregation and weights. * @param keys the keys. * @return List<V> array-reply list of scored values. * @since 6.1 */ fun zunionWithScores( aggregateArgs: ZAggregateArgs, vararg keys: K ): Flow<ScoredValue<V>> /** * Add multiple sorted sets and returns the resulting sorted set. * * @param keys the keys. * @return List<V> array-reply list of scored values. * @since 6.1 */ fun zunionWithScores(vararg keys: K): Flow<ScoredValue<V>> /** * Add multiple sorted sets and store the resulting sorted set in a new key. * * @param destination destination key. * @param keys source keys. * @return Long integer-reply the number of elements in the resulting sorted set at `destination`. */ suspend fun zunionstore(destination: K, vararg keys: K): Long? /** * Add multiple sorted sets and store the resulting sorted set in a new key. * * @param destination the destination. * @param storeArgs arguments to define aggregation and weights. * @param keys the keys. * @return Long integer-reply the number of elements in the resulting sorted set at `destination`. */ suspend fun zunionstore(destination: K, storeArgs: ZStoreArgs, vararg keys: K): Long? }
src/main/kotlin/io/lettuce/core/api/coroutines/RedisSortedSetCoroutinesCommands.kt
1939108030
package com.bendaniel10.weatherlite.di import com.bendaniel10.weatherlite.WeatherLiteActivity import dagger.Component /** * Created by bendaniel on 22/06/2017. */ @Component(modules = arrayOf(WeatherLiteModule::class)) interface WeatherLiteComponent { fun inject(weatherLiteActivity: WeatherLiteActivity) }
app/src/main/java/com/bendaniel10/weatherlite/di/WeatherLiteComponent.kt
1936451125
package transaction import core.JustDB import groovy.util.GroovyTestCase import storage.Block import kotlin.concurrent.thread /** * Created by liufengkai on 2017/7/4. */ class TransactionTest : GroovyTestCase() { fun testGetNextTransactionNumber() { repeat(100) { thread { println("get-next-id ${Transaction.generateTransactionNumber()}") } } } fun testTransaction() { val justDB = JustDB("transaction-test-database") val transaction = Transaction(justDB) val block = Block("transaction-test", 0) transaction.pin(block) transaction.setString(block, 0, "lfkdsk lfkdsk") transaction.commit() val transaction1 = Transaction(justDB) transaction1.pin(block) transaction1.setString(block, 0, "lfkdsk ssss") transaction1.rollback() } fun testTransactionPinNew() { // val justDB = JustDB("transaction-test-database") // val transaction = Transaction(justDB) // // val block = Block("transaction-test", 1) // transaction.pin(block) // transaction.setString(block, 0, "lfkdsk lfkdsk") // transaction.commit() } }
tests/transaction/TransactionTest.kt
1114736923
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md import android.animation.AnimatorInflater import android.animation.AnimatorSet import android.app.Activity import android.content.Intent import android.content.res.Resources import android.graphics.Bitmap import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.annotation.MainThread import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.chip.Chip import com.google.common.collect.ImmutableList import com.google.mlkit.md.productsearch.BottomSheetScrimView import com.google.mlkit.md.objectdetection.DetectedObjectInfo import com.google.mlkit.md.objectdetection.StaticObjectDotView import com.google.mlkit.md.productsearch.PreviewCardAdapter import com.google.mlkit.md.productsearch.Product import com.google.mlkit.md.productsearch.ProductAdapter import com.google.mlkit.md.productsearch.SearchEngine import com.google.mlkit.md.productsearch.SearchedObject import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions import com.google.mlkit.vision.objects.DetectedObject import com.google.mlkit.vision.objects.ObjectDetection import com.google.mlkit.vision.objects.ObjectDetector import java.io.IOException import java.lang.NullPointerException import java.util.TreeMap /** Demonstrates the object detection and visual search workflow using static image. */ class StaticObjectDetectionActivity : AppCompatActivity(), View.OnClickListener { private val searchedObjectMap = TreeMap<Int, SearchedObject>() private var loadingView: View? = null private var bottomPromptChip: Chip? = null private var inputImageView: ImageView? = null private var previewCardCarousel: RecyclerView? = null private var dotViewContainer: ViewGroup? = null private var bottomSheetBehavior: BottomSheetBehavior<View>? = null private var bottomSheetScrimView: BottomSheetScrimView? = null private var bottomSheetTitleView: TextView? = null private var productRecyclerView: RecyclerView? = null private var inputBitmap: Bitmap? = null private var searchedObjectForBottomSheet: SearchedObject? = null private var dotViewSize: Int = 0 private var detectedObjectNum = 0 private var currentSelectedObjectIndex = 0 private var detector: ObjectDetector? = null private var searchEngine: SearchEngine? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) searchEngine = SearchEngine(applicationContext) setContentView(R.layout.activity_static_object) loadingView = findViewById<View>(R.id.loading_view).apply { setOnClickListener(this@StaticObjectDetectionActivity) } bottomPromptChip = findViewById(R.id.bottom_prompt_chip) inputImageView = findViewById(R.id.input_image_view) previewCardCarousel = findViewById<RecyclerView>(R.id.card_recycler_view).apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(this@StaticObjectDetectionActivity, RecyclerView.HORIZONTAL, false) addItemDecoration( CardItemDecoration( resources ) ) } dotViewContainer = findViewById(R.id.dot_view_container) dotViewSize = resources.getDimensionPixelOffset(R.dimen.static_image_dot_view_size) setUpBottomSheet() findViewById<View>(R.id.close_button).setOnClickListener(this) findViewById<View>(R.id.photo_library_button).setOnClickListener(this) detector = ObjectDetection.getClient( ObjectDetectorOptions.Builder() .setDetectorMode(ObjectDetectorOptions.SINGLE_IMAGE_MODE) .enableMultipleObjects() .build() ) intent.data?.let(::detectObjects) } override fun onDestroy() { super.onDestroy() try { detector?.close() } catch (e: IOException) { Log.e(TAG, "Failed to close the detector!", e) } searchEngine?.shutdown() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == Utils.REQUEST_CODE_PHOTO_LIBRARY && resultCode == Activity.RESULT_OK) { data?.data?.let(::detectObjects) } else { super.onActivityResult(requestCode, resultCode, data) } } override fun onBackPressed() { if (bottomSheetBehavior?.state != BottomSheetBehavior.STATE_HIDDEN) { bottomSheetBehavior?.setState(BottomSheetBehavior.STATE_HIDDEN) } else { super.onBackPressed() } } override fun onClick(view: View) { when (view.id) { R.id.close_button -> onBackPressed() R.id.photo_library_button -> Utils.openImagePicker(this) R.id.bottom_sheet_scrim_view -> bottomSheetBehavior?.state = BottomSheetBehavior.STATE_HIDDEN } } private fun showSearchResults(searchedObject: SearchedObject) { searchedObjectForBottomSheet = searchedObject val productList = searchedObject.productList bottomSheetTitleView?.text = resources .getQuantityString( R.plurals.bottom_sheet_title, productList.size, productList.size ) productRecyclerView?.adapter = ProductAdapter(productList) bottomSheetBehavior?.peekHeight = (inputImageView?.parent as View).height / 2 bottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED } private fun setUpBottomSheet() { bottomSheetBehavior = BottomSheetBehavior.from(findViewById<View>(R.id.bottom_sheet)).apply { setBottomSheetCallback( object : BottomSheetBehavior.BottomSheetCallback() { override fun onStateChanged(bottomSheet: View, newState: Int) { Log.d(TAG, "Bottom sheet new state: $newState") bottomSheetScrimView?.visibility = if (newState == BottomSheetBehavior.STATE_HIDDEN) View.GONE else View.VISIBLE } override fun onSlide(bottomSheet: View, slideOffset: Float) { if (java.lang.Float.isNaN(slideOffset)) { return } val collapsedStateHeight = bottomSheetBehavior!!.peekHeight.coerceAtMost(bottomSheet.height) val searchedObjectForBottomSheet = searchedObjectForBottomSheet ?: return bottomSheetScrimView?.updateWithThumbnailTranslate( searchedObjectForBottomSheet.getObjectThumbnail(), collapsedStateHeight, slideOffset, bottomSheet ) } } ) state = BottomSheetBehavior.STATE_HIDDEN } bottomSheetScrimView = findViewById<BottomSheetScrimView>(R.id.bottom_sheet_scrim_view).apply { setOnClickListener(this@StaticObjectDetectionActivity) } bottomSheetTitleView = findViewById(R.id.bottom_sheet_title) productRecyclerView = findViewById<RecyclerView>(R.id.product_recycler_view)?.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(this@StaticObjectDetectionActivity) adapter = ProductAdapter(ImmutableList.of()) } } private fun detectObjects(imageUri: Uri) { inputImageView?.setImageDrawable(null) bottomPromptChip?.visibility = View.GONE previewCardCarousel?.adapter = PreviewCardAdapter(ImmutableList.of()) { showSearchResults(it) } previewCardCarousel?.clearOnScrollListeners() dotViewContainer?.removeAllViews() currentSelectedObjectIndex = 0 try { inputBitmap = Utils.loadImage( this, imageUri, MAX_IMAGE_DIMENSION ) } catch (e: IOException) { Log.e(TAG, "Failed to load file: $imageUri", e) showBottomPromptChip("Failed to load file!") return } inputImageView?.setImageBitmap(inputBitmap) loadingView?.visibility = View.VISIBLE val image = InputImage.fromBitmap(inputBitmap!!, 0) detector?.process(image) ?.addOnSuccessListener { objects -> onObjectsDetected(BitmapInputInfo(inputBitmap!!), objects) } ?.addOnFailureListener { onObjectsDetected(BitmapInputInfo(inputBitmap!!), ImmutableList.of()) } } @MainThread private fun onObjectsDetected(image: InputInfo, objects: List<DetectedObject>) { detectedObjectNum = objects.size Log.d(TAG, "Detected objects num: $detectedObjectNum") if (detectedObjectNum == 0) { loadingView?.visibility = View.GONE showBottomPromptChip(getString(R.string.static_image_prompt_detected_no_results)) } else { searchedObjectMap.clear() for (i in objects.indices) { searchEngine?.search(DetectedObjectInfo(objects[i], i, image)) { detectedObject, products -> onSearchCompleted(detectedObject, products) } } } } private fun onSearchCompleted(detectedObject: DetectedObjectInfo, productList: List<Product>) { Log.d(TAG, "Search completed for object index: ${detectedObject.objectIndex}") searchedObjectMap[detectedObject.objectIndex] = SearchedObject(resources, detectedObject, productList) if (searchedObjectMap.size < detectedObjectNum) { // Hold off showing the result until the search of all detected objects completes. return } showBottomPromptChip(getString(R.string.static_image_prompt_detected_results)) loadingView?.visibility = View.GONE previewCardCarousel?.adapter = PreviewCardAdapter(ImmutableList.copyOf(searchedObjectMap.values)) { showSearchResults(it) } previewCardCarousel?.addOnScrollListener( object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { Log.d(TAG, "New card scroll state: $newState") if (newState == RecyclerView.SCROLL_STATE_IDLE) { for (i in 0 until recyclerView.childCount) { val childView = recyclerView.getChildAt(i) if (childView.x >= 0) { val cardIndex = recyclerView.getChildAdapterPosition(childView) if (cardIndex != currentSelectedObjectIndex) { selectNewObject(cardIndex) } break } } } } }) for (searchedObject in searchedObjectMap.values) { val dotView = createDotView(searchedObject) dotView.setOnClickListener { if (searchedObject.objectIndex == currentSelectedObjectIndex) { showSearchResults(searchedObject) } else { selectNewObject(searchedObject.objectIndex) showSearchResults(searchedObject) previewCardCarousel!!.smoothScrollToPosition(searchedObject.objectIndex) } } dotViewContainer?.addView(dotView) val animatorSet = AnimatorInflater.loadAnimator(this, R.animator.static_image_dot_enter) as AnimatorSet animatorSet.setTarget(dotView) animatorSet.start() } } private fun createDotView(searchedObject: SearchedObject): StaticObjectDotView { val viewCoordinateScale: Float val horizontalGap: Float val verticalGap: Float val inputImageView = inputImageView ?: throw NullPointerException() val inputBitmap = inputBitmap ?: throw NullPointerException() val inputImageViewRatio = inputImageView.width.toFloat() / inputImageView.height val inputBitmapRatio = inputBitmap.width.toFloat() / inputBitmap.height if (inputBitmapRatio <= inputImageViewRatio) { // Image content fills height viewCoordinateScale = inputImageView.height.toFloat() / inputBitmap.height horizontalGap = (inputImageView.width - inputBitmap.width * viewCoordinateScale) / 2 verticalGap = 0f } else { // Image content fills width viewCoordinateScale = inputImageView.width.toFloat() / inputBitmap.width horizontalGap = 0f verticalGap = (inputImageView.height - inputBitmap.height * viewCoordinateScale) / 2 } val boundingBox = searchedObject.boundingBox val boxInViewCoordinate = RectF( boundingBox.left * viewCoordinateScale + horizontalGap, boundingBox.top * viewCoordinateScale + verticalGap, boundingBox.right * viewCoordinateScale + horizontalGap, boundingBox.bottom * viewCoordinateScale + verticalGap ) val initialSelected = searchedObject.objectIndex == 0 val dotView = StaticObjectDotView(this, initialSelected) val layoutParams = FrameLayout.LayoutParams(dotViewSize, dotViewSize) val dotCenter = PointF( (boxInViewCoordinate.right + boxInViewCoordinate.left) / 2, (boxInViewCoordinate.bottom + boxInViewCoordinate.top) / 2 ) layoutParams.setMargins( (dotCenter.x - dotViewSize / 2f).toInt(), (dotCenter.y - dotViewSize / 2f).toInt(), 0, 0 ) dotView.layoutParams = layoutParams return dotView } private fun selectNewObject(objectIndex: Int) { val dotViewToDeselect = dotViewContainer!!.getChildAt(currentSelectedObjectIndex) as StaticObjectDotView dotViewToDeselect.playAnimationWithSelectedState(false) currentSelectedObjectIndex = objectIndex val selectedDotView = dotViewContainer!!.getChildAt(currentSelectedObjectIndex) as StaticObjectDotView selectedDotView.playAnimationWithSelectedState(true) } private fun showBottomPromptChip(message: String) { bottomPromptChip?.visibility = View.VISIBLE bottomPromptChip?.text = message } private class CardItemDecoration constructor(resources: Resources) : RecyclerView.ItemDecoration() { private val cardSpacing: Int = resources.getDimensionPixelOffset(R.dimen.preview_card_spacing) override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val adapterPosition = parent.getChildAdapterPosition(view) outRect.left = if (adapterPosition == 0) cardSpacing * 2 else cardSpacing val adapter = parent.adapter ?: return if (adapterPosition == adapter.itemCount - 1) { outRect.right = cardSpacing } } } companion object { private const val TAG = "StaticObjectActivity" private const val MAX_IMAGE_DIMENSION = 1024 } }
android/material-showcase/app/src/main/java/com/google/mlkit/md/StaticObjectDetectionActivity.kt
4132892032
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.text import com.intellij.openapi.util.text.StringUtil fun String?.nullize(nullizeSpaces: Boolean = false): String? = StringUtil.nullize(this, nullizeSpaces) fun String.trimMiddle(maxLength: Int, useEllipsisSymbol: Boolean = true): String { return StringUtil.shortenTextWithEllipsis(this, maxLength, maxLength shr 1, useEllipsisSymbol) } fun CharArray.nullize() = if (isEmpty()) null else this
platform/platform-api/src/com/intellij/util/text/string.kt
2577017630
object `$$Anko$Factories$Sdk15View` { val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) } val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) } val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) } val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) } val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) } val VIEW = { ctx: Context -> android.view.View(ctx) } val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) } val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) } val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) } val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) } val BUTTON = { ctx: Context -> android.widget.Button(ctx) } val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) } val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) } val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) } val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) } val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) } val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) } val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) } val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) } val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) } val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) } val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) } val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) } val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) } val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) } val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) } val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) } val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) } val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) } val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) } val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) } val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) } val SPACE = { ctx: Context -> android.widget.Space(ctx) } val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) } val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) } val SWITCH = { ctx: Context -> android.widget.Switch(ctx) } val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) } val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) } val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) } val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) } val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) } val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) } val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) } val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) } val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) } val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) } } inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun ViewManager.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun Context.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({}) inline fun Activity.gestureOverlayView(init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView { return ankoView(`$$Anko$Factories$Sdk15View`.GESTURE_OVERLAY_VIEW) { init() } } inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({}) inline fun ViewManager.extractEditText(init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText { return ankoView(`$$Anko$Factories$Sdk15View`.EXTRACT_EDIT_TEXT) { init() } } inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({}) inline fun ViewManager.gLSurfaceView(init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView { return ankoView(`$$Anko$Factories$Sdk15View`.G_L_SURFACE_VIEW) { init() } } inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({}) inline fun ViewManager.surfaceView(init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView { return ankoView(`$$Anko$Factories$Sdk15View`.SURFACE_VIEW) { init() } } inline fun ViewManager.textureView(): android.view.TextureView = textureView({}) inline fun ViewManager.textureView(init: android.view.TextureView.() -> Unit): android.view.TextureView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXTURE_VIEW) { init() } } inline fun ViewManager.view(): android.view.View = view({}) inline fun ViewManager.view(init: android.view.View.() -> Unit): android.view.View { return ankoView(`$$Anko$Factories$Sdk15View`.VIEW) { init() } } inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({}) inline fun ViewManager.viewStub(init: android.view.ViewStub.() -> Unit): android.view.ViewStub { return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_STUB) { init() } } inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun ViewManager.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun Context.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({}) inline fun Activity.adapterViewFlipper(init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.ADAPTER_VIEW_FLIPPER) { init() } } inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({}) inline fun ViewManager.analogClock(init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock { return ankoView(`$$Anko$Factories$Sdk15View`.ANALOG_CLOCK) { init() } } inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({}) inline fun ViewManager.autoCompleteTextView(init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk15View`.AUTO_COMPLETE_TEXT_VIEW) { init() } } inline fun ViewManager.button(): android.widget.Button = button({}) inline fun ViewManager.button(init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { init() } } inline fun ViewManager.button(text: CharSequence?): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { setText(text) } } inline fun ViewManager.button(text: CharSequence?, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { init() setText(text) } } inline fun ViewManager.button(text: Int): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { setText(text) } } inline fun ViewManager.button(text: Int, init: android.widget.Button.() -> Unit): android.widget.Button { return ankoView(`$$Anko$Factories$Sdk15View`.BUTTON) { init() setText(text) } } inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({}) inline fun ViewManager.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() } } inline fun Context.calendarView(): android.widget.CalendarView = calendarView({}) inline fun Context.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() } } inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({}) inline fun Activity.calendarView(init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView { return ankoView(`$$Anko$Factories$Sdk15View`.CALENDAR_VIEW) { init() } } inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({}) inline fun ViewManager.checkBox(init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() } } inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { setText(text) } } inline fun ViewManager.checkBox(text: CharSequence?, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() setText(text) } } inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { setText(text) } } inline fun ViewManager.checkBox(text: Int, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() setText(text) } } inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { setText(text) setChecked(checked) } } inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox { return ankoView(`$$Anko$Factories$Sdk15View`.CHECK_BOX) { init() setText(text) setChecked(checked) } } inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({}) inline fun ViewManager.checkedTextView(init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView { return ankoView(`$$Anko$Factories$Sdk15View`.CHECKED_TEXT_VIEW) { init() } } inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({}) inline fun ViewManager.chronometer(init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer { return ankoView(`$$Anko$Factories$Sdk15View`.CHRONOMETER) { init() } } inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({}) inline fun ViewManager.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() } } inline fun Context.datePicker(): android.widget.DatePicker = datePicker({}) inline fun Context.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() } } inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({}) inline fun Activity.datePicker(init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker { return ankoView(`$$Anko$Factories$Sdk15View`.DATE_PICKER) { init() } } inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun ViewManager.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() } } inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun Context.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() } } inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({}) inline fun Activity.dialerFilter(init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter { return ankoView(`$$Anko$Factories$Sdk15View`.DIALER_FILTER) { init() } } inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({}) inline fun ViewManager.digitalClock(init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock { return ankoView(`$$Anko$Factories$Sdk15View`.DIGITAL_CLOCK) { init() } } inline fun ViewManager.editText(): android.widget.EditText = editText({}) inline fun ViewManager.editText(init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { init() } } inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { setText(text) } } inline fun ViewManager.editText(text: CharSequence?, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { init() setText(text) } } inline fun ViewManager.editText(text: Int): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { setText(text) } } inline fun ViewManager.editText(text: Int, init: android.widget.EditText.() -> Unit): android.widget.EditText { return ankoView(`$$Anko$Factories$Sdk15View`.EDIT_TEXT) { init() setText(text) } } inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun ViewManager.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun Context.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({}) inline fun Activity.expandableListView(init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView { return ankoView(`$$Anko$Factories$Sdk15View`.EXPANDABLE_LIST_VIEW) { init() } } inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({}) inline fun ViewManager.imageButton(init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { init() } } inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { setImageDrawable(imageDrawable) } } inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { init() setImageDrawable(imageDrawable) } } inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { setImageResource(imageResource) } } inline fun ViewManager.imageButton(imageResource: Int, init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_BUTTON) { init() setImageResource(imageResource) } } inline fun ViewManager.imageView(): android.widget.ImageView = imageView({}) inline fun ViewManager.imageView(init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { init() } } inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { setImageDrawable(imageDrawable) } } inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { init() setImageDrawable(imageDrawable) } } inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { setImageResource(imageResource) } } inline fun ViewManager.imageView(imageResource: Int, init: android.widget.ImageView.() -> Unit): android.widget.ImageView { return ankoView(`$$Anko$Factories$Sdk15View`.IMAGE_VIEW) { init() setImageResource(imageResource) } } inline fun ViewManager.listView(): android.widget.ListView = listView({}) inline fun ViewManager.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() } } inline fun Context.listView(): android.widget.ListView = listView({}) inline fun Context.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() } } inline fun Activity.listView(): android.widget.ListView = listView({}) inline fun Activity.listView(init: android.widget.ListView.() -> Unit): android.widget.ListView { return ankoView(`$$Anko$Factories$Sdk15View`.LIST_VIEW) { init() } } inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({}) inline fun ViewManager.multiAutoCompleteTextView(init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView { return ankoView(`$$Anko$Factories$Sdk15View`.MULTI_AUTO_COMPLETE_TEXT_VIEW) { init() } } inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun ViewManager.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() } } inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun Context.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() } } inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({}) inline fun Activity.numberPicker(init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker { return ankoView(`$$Anko$Factories$Sdk15View`.NUMBER_PICKER) { init() } } inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({}) inline fun ViewManager.progressBar(init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar { return ankoView(`$$Anko$Factories$Sdk15View`.PROGRESS_BAR) { init() } } inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({}) inline fun ViewManager.quickContactBadge(init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge { return ankoView(`$$Anko$Factories$Sdk15View`.QUICK_CONTACT_BADGE) { init() } } inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({}) inline fun ViewManager.radioButton(init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton { return ankoView(`$$Anko$Factories$Sdk15View`.RADIO_BUTTON) { init() } } inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({}) inline fun ViewManager.ratingBar(init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar { return ankoView(`$$Anko$Factories$Sdk15View`.RATING_BAR) { init() } } inline fun ViewManager.searchView(): android.widget.SearchView = searchView({}) inline fun ViewManager.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() } } inline fun Context.searchView(): android.widget.SearchView = searchView({}) inline fun Context.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() } } inline fun Activity.searchView(): android.widget.SearchView = searchView({}) inline fun Activity.searchView(init: android.widget.SearchView.() -> Unit): android.widget.SearchView { return ankoView(`$$Anko$Factories$Sdk15View`.SEARCH_VIEW) { init() } } inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({}) inline fun ViewManager.seekBar(init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar { return ankoView(`$$Anko$Factories$Sdk15View`.SEEK_BAR) { init() } } inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun ViewManager.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() } } inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun Context.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() } } inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({}) inline fun Activity.slidingDrawer(init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer { return ankoView(`$$Anko$Factories$Sdk15View`.SLIDING_DRAWER) { init() } } inline fun ViewManager.space(): android.widget.Space = space({}) inline fun ViewManager.space(init: android.widget.Space.() -> Unit): android.widget.Space { return ankoView(`$$Anko$Factories$Sdk15View`.SPACE) { init() } } inline fun ViewManager.spinner(): android.widget.Spinner = spinner({}) inline fun ViewManager.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() } } inline fun Context.spinner(): android.widget.Spinner = spinner({}) inline fun Context.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() } } inline fun Activity.spinner(): android.widget.Spinner = spinner({}) inline fun Activity.spinner(init: android.widget.Spinner.() -> Unit): android.widget.Spinner { return ankoView(`$$Anko$Factories$Sdk15View`.SPINNER) { init() } } inline fun ViewManager.stackView(): android.widget.StackView = stackView({}) inline fun ViewManager.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() } } inline fun Context.stackView(): android.widget.StackView = stackView({}) inline fun Context.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() } } inline fun Activity.stackView(): android.widget.StackView = stackView({}) inline fun Activity.stackView(init: android.widget.StackView.() -> Unit): android.widget.StackView { return ankoView(`$$Anko$Factories$Sdk15View`.STACK_VIEW) { init() } } inline fun ViewManager.switch(): android.widget.Switch = switch({}) inline fun ViewManager.switch(init: android.widget.Switch.() -> Unit): android.widget.Switch { return ankoView(`$$Anko$Factories$Sdk15View`.SWITCH) { init() } } inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({}) inline fun ViewManager.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() } } inline fun Context.tabHost(): android.widget.TabHost = tabHost({}) inline fun Context.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() } } inline fun Activity.tabHost(): android.widget.TabHost = tabHost({}) inline fun Activity.tabHost(init: android.widget.TabHost.() -> Unit): android.widget.TabHost { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_HOST) { init() } } inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun ViewManager.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() } } inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun Context.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() } } inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({}) inline fun Activity.tabWidget(init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget { return ankoView(`$$Anko$Factories$Sdk15View`.TAB_WIDGET) { init() } } inline fun ViewManager.textView(): android.widget.TextView = textView({}) inline fun ViewManager.textView(init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { init() } } inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { setText(text) } } inline fun ViewManager.textView(text: CharSequence?, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { init() setText(text) } } inline fun ViewManager.textView(text: Int): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { setText(text) } } inline fun ViewManager.textView(text: Int, init: android.widget.TextView.() -> Unit): android.widget.TextView { return ankoView(`$$Anko$Factories$Sdk15View`.TEXT_VIEW) { init() setText(text) } } inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({}) inline fun ViewManager.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() } } inline fun Context.timePicker(): android.widget.TimePicker = timePicker({}) inline fun Context.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() } } inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({}) inline fun Activity.timePicker(init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker { return ankoView(`$$Anko$Factories$Sdk15View`.TIME_PICKER) { init() } } inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({}) inline fun ViewManager.toggleButton(init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton { return ankoView(`$$Anko$Factories$Sdk15View`.TOGGLE_BUTTON) { init() } } inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun ViewManager.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() } } inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun Context.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() } } inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({}) inline fun Activity.twoLineListItem(init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem { return ankoView(`$$Anko$Factories$Sdk15View`.TWO_LINE_LIST_ITEM) { init() } } inline fun ViewManager.videoView(): android.widget.VideoView = videoView({}) inline fun ViewManager.videoView(init: android.widget.VideoView.() -> Unit): android.widget.VideoView { return ankoView(`$$Anko$Factories$Sdk15View`.VIDEO_VIEW) { init() } } inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun ViewManager.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() } } inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun Context.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() } } inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({}) inline fun Activity.viewFlipper(init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper { return ankoView(`$$Anko$Factories$Sdk15View`.VIEW_FLIPPER) { init() } } inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({}) inline fun ViewManager.zoomButton(init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton { return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_BUTTON) { init() } } inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun ViewManager.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() } } inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun Context.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() } } inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({}) inline fun Activity.zoomControls(init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls { return ankoView(`$$Anko$Factories$Sdk15View`.ZOOM_CONTROLS) { init() } } object `$$Anko$Factories$Sdk15ViewGroup` { val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) } val WEB_VIEW = { ctx: Context -> _WebView(ctx) } val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) } val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) } val GALLERY = { ctx: Context -> _Gallery(ctx) } val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) } val GRID_VIEW = { ctx: Context -> _GridView(ctx) } val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) } val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) } val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) } val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) } val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) } val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) } val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) } val TABLE_ROW = { ctx: Context -> _TableRow(ctx) } val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) } val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) } val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) } } inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun ViewManager.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun Context.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({}) inline fun Activity.appWidgetHostView(init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.APP_WIDGET_HOST_VIEW) { init() } } inline fun ViewManager.webView(): android.webkit.WebView = webView({}) inline fun ViewManager.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() } } inline fun Context.webView(): android.webkit.WebView = webView({}) inline fun Context.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() } } inline fun Activity.webView(): android.webkit.WebView = webView({}) inline fun Activity.webView(init: _WebView.() -> Unit): android.webkit.WebView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.WEB_VIEW) { init() } } inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun ViewManager.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun Context.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({}) inline fun Activity.absoluteLayout(init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.ABSOLUTE_LAYOUT) { init() } } inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun ViewManager.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() } } inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun Context.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() } } inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({}) inline fun Activity.frameLayout(init: _FrameLayout.() -> Unit): android.widget.FrameLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.FRAME_LAYOUT) { init() } } inline fun ViewManager.gallery(): android.widget.Gallery = gallery({}) inline fun ViewManager.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() } } inline fun Context.gallery(): android.widget.Gallery = gallery({}) inline fun Context.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() } } inline fun Activity.gallery(): android.widget.Gallery = gallery({}) inline fun Activity.gallery(init: _Gallery.() -> Unit): android.widget.Gallery { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GALLERY) { init() } } inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun ViewManager.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() } } inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun Context.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() } } inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({}) inline fun Activity.gridLayout(init: _GridLayout.() -> Unit): android.widget.GridLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_LAYOUT) { init() } } inline fun ViewManager.gridView(): android.widget.GridView = gridView({}) inline fun ViewManager.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() } } inline fun Context.gridView(): android.widget.GridView = gridView({}) inline fun Context.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() } } inline fun Activity.gridView(): android.widget.GridView = gridView({}) inline fun Activity.gridView(init: _GridView.() -> Unit): android.widget.GridView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.GRID_VIEW) { init() } } inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun ViewManager.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun Context.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({}) inline fun Activity.horizontalScrollView(init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.HORIZONTAL_SCROLL_VIEW) { init() } } inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun ViewManager.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun Context.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({}) inline fun Activity.imageSwitcher(init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.IMAGE_SWITCHER) { init() } } inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun ViewManager.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun Context.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({}) inline fun Activity.linearLayout(init: _LinearLayout.() -> Unit): android.widget.LinearLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.LINEAR_LAYOUT) { init() } } inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun ViewManager.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() } } inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun Context.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() } } inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({}) inline fun Activity.radioGroup(init: _RadioGroup.() -> Unit): android.widget.RadioGroup { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RADIO_GROUP) { init() } } inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun ViewManager.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun Context.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({}) inline fun Activity.relativeLayout(init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.RELATIVE_LAYOUT) { init() } } inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({}) inline fun ViewManager.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() } } inline fun Context.scrollView(): android.widget.ScrollView = scrollView({}) inline fun Context.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() } } inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({}) inline fun Activity.scrollView(init: _ScrollView.() -> Unit): android.widget.ScrollView { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.SCROLL_VIEW) { init() } } inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun ViewManager.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() } } inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun Context.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() } } inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({}) inline fun Activity.tableLayout(init: _TableLayout.() -> Unit): android.widget.TableLayout { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_LAYOUT) { init() } } inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({}) inline fun ViewManager.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() } } inline fun Context.tableRow(): android.widget.TableRow = tableRow({}) inline fun Context.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() } } inline fun Activity.tableRow(): android.widget.TableRow = tableRow({}) inline fun Activity.tableRow(init: _TableRow.() -> Unit): android.widget.TableRow { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TABLE_ROW) { init() } } inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun ViewManager.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() } } inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun Context.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() } } inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({}) inline fun Activity.textSwitcher(init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.TEXT_SWITCHER) { init() } } inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun ViewManager.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun Context.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({}) inline fun Activity.viewAnimator(init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_ANIMATOR) { init() } } inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun ViewManager.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() } } inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun Context.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() } } inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({}) inline fun Activity.viewSwitcher(init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher { return ankoView(`$$Anko$Factories$Sdk15ViewGroup`.VIEW_SWITCHER) { init() } }
dsl/testData/functional/sdk15/ViewTest.kt
3136656637
package org.videolan.vlc.viewmodels import android.content.Context import android.net.Uri import androidx.databinding.Observable import androidx.databinding.ObservableBoolean import androidx.databinding.ObservableField import androidx.lifecycle.* import kotlinx.coroutines.Job import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.videolan.tools.FileUtils import org.videolan.resources.util.NoConnectivityException import org.videolan.tools.Settings import org.videolan.vlc.R import org.videolan.resources.opensubtitles.OpenSubtitle import org.videolan.vlc.gui.dialogs.State import org.videolan.vlc.gui.dialogs.SubtitleItem import org.videolan.vlc.repository.ExternalSubRepository import org.videolan.resources.opensubtitles.OpenSubtitleRepository import org.videolan.tools.CoroutineContextProvider import org.videolan.tools.putSingle import java.io.File import java.util.* private const val LAST_USED_LANGUAGES = "last_used_subtitles" class SubtitlesModel(private val context: Context, private val mediaUri: Uri, val coroutineContextProvider: CoroutineContextProvider = CoroutineContextProvider()): ViewModel() { val observableSearchName = ObservableField<String>() val observableSearchEpisode = ObservableField<String>() val observableSearchSeason = ObservableField<String>() val observableSearchLanguage = ObservableField<List<String>>() private var previousSearchLanguage: List<String>? = null val manualSearchEnabled = ObservableBoolean(false) val isApiLoading = ObservableBoolean(false) val observableMessage = ObservableField<String>() private val apiResultLiveData: MutableLiveData<List<OpenSubtitle>> = MutableLiveData() private val downloadedLiveData = Transformations.map(ExternalSubRepository.getInstance(context).getDownloadedSubtitles(mediaUri)) { it.map { SubtitleItem(it.idSubtitle, mediaUri, it.subLanguageID, it.movieReleaseName, State.Downloaded, "") } } private val downloadingLiveData = ExternalSubRepository.getInstance(context).downloadingSubtitles val result: MediatorLiveData<List<SubtitleItem>> = MediatorLiveData() val history: MediatorLiveData<List<SubtitleItem>> = MediatorLiveData() private var searchJob: Job? = null init { observableSearchLanguage.addOnPropertyChangedCallback(object: Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(sender: Observable?, propertyId: Int) { if (observableSearchLanguage.get() != previousSearchLanguage) { previousSearchLanguage = observableSearchLanguage.get() saveLastUsedLanguage(observableSearchLanguage.get() ?: listOf()) search(!manualSearchEnabled.get()) } } }) history.apply { addSource(downloadedLiveData) { viewModelScope.launch { value = merge(it, downloadingLiveData.value?.values?.filter { it.mediaUri == mediaUri }) } } addSource(downloadingLiveData) { viewModelScope.launch { value = merge(downloadedLiveData.value, it?.values?.filter { it.mediaUri == mediaUri }) } } } result.apply { addSource(apiResultLiveData) { viewModelScope.launch { value = updateListState(it, history.value) } } addSource(history) { viewModelScope.launch { value = updateListState(apiResultLiveData.value, it) } } } } private suspend fun merge(downloadedResult: List<SubtitleItem>?, downloadingResult: List<SubtitleItem>?): List<SubtitleItem> = withContext(coroutineContextProvider.Default) { downloadedResult.orEmpty() + downloadingResult?.toList().orEmpty() } private suspend fun updateListState(apiResultLiveData: List<OpenSubtitle>?, history: List<SubtitleItem>?): MutableList<SubtitleItem> = withContext(coroutineContextProvider.Default) { val list = mutableListOf<SubtitleItem>() apiResultLiveData?.forEach { openSubtitle -> val exist = history?.find { it.idSubtitle == openSubtitle.idSubtitle } val state = exist?.state ?: State.NotDownloaded list.add(SubtitleItem(openSubtitle.idSubtitle, mediaUri, openSubtitle.subLanguageID, openSubtitle.movieReleaseName, state, openSubtitle.zipDownloadLink)) } list } fun onCheckedChanged(isChecked: Boolean) { if (manualSearchEnabled.get() == isChecked) return manualSearchEnabled.set(isChecked) isApiLoading.set(false) apiResultLiveData.postValue(listOf()) searchJob?.cancel() observableMessage.set("") if (!isChecked) search(true) } private suspend fun getSubtitleByName(name: String, episode: Int?, season: Int?, languageIds: List<String>?): List<OpenSubtitle> { return OpenSubtitleRepository.getInstance().queryWithName(name ,episode, season, languageIds) } private suspend fun getSubtitleByHash(movieByteSize: Long, movieHash: String?, languageIds: List<String>?): List<OpenSubtitle> { return OpenSubtitleRepository.getInstance().queryWithHash(movieByteSize, movieHash, languageIds) } fun onRefresh() { if (manualSearchEnabled.get() && observableSearchName.get().isNullOrEmpty()) { isApiLoading.set(false) // As it's already false we need to notify it to // disable refreshing animation isApiLoading.notifyChange() return } search(!manualSearchEnabled.get()) } fun search(byHash: Boolean) { searchJob?.cancel() isApiLoading.set(true) observableMessage.set("") apiResultLiveData.postValue(listOf()) searchJob = viewModelScope.launch { try { val subs = if (byHash) { withContext(coroutineContextProvider.IO) { val videoFile = File(mediaUri.path) val hash = FileUtils.computeHash(videoFile) val fileLength = videoFile.length() getSubtitleByHash(fileLength, hash, observableSearchLanguage.get()) } } else { observableSearchName.get()?.let { getSubtitleByName(it, observableSearchEpisode.get()?.toInt(), observableSearchSeason.get()?.toInt(), observableSearchLanguage.get()) } ?: listOf() } if (isActive) apiResultLiveData.postValue(subs) if (subs.isEmpty()) observableMessage.set(context.getString(R.string.no_result)) } catch (e: Exception) { if (e is NoConnectivityException) observableMessage.set(context.getString(R.string.no_internet_connection)) else observableMessage.set(context.getString(R.string.some_error_occurred)) } finally { isApiLoading.set(false) } } } fun deleteSubtitle(mediaPath: String, idSubtitle: String) { ExternalSubRepository.getInstance(context).deleteSubtitle(mediaPath, idSubtitle) } fun getLastUsedLanguage() : List<String> { val language = try { Locale.getDefault().isO3Language } catch (e: MissingResourceException) { "eng" } return Settings.getInstance(context).getStringSet(LAST_USED_LANGUAGES, setOf(language))?.map { it.getCompliantLanguageID() } ?: emptyList() } fun saveLastUsedLanguage(lastUsedLanguages: List<String>) = Settings.getInstance(context).putSingle(LAST_USED_LANGUAGES, lastUsedLanguages) class Factory(private val context: Context, private val mediaUri: Uri): ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return SubtitlesModel(context.applicationContext, mediaUri) as T } } // Locale ID Control, because of OpenSubtitle support of ISO639-2 codes // e.g. French ID can be 'fra' or 'fre', OpenSubtitles considers 'fre' but Android Java Locale provides 'fra' private fun String.getCompliantLanguageID() = when(this) { "fra" -> "fre" "deu" -> "ger" "zho" -> "chi" "ces" -> "cze" "fas" -> "per" "nld" -> "dut" "ron" -> "rum" "slk" -> "slo" else -> this } }
application/vlc-android/src/org/videolan/vlc/viewmodels/SubtitlesModel.kt
3796159118
package com.cout970.magneticraft.misc.fluid import net.minecraftforge.fluids.FluidStack import net.minecraftforge.fluids.capability.IFluidHandler import net.minecraftforge.fluids.capability.IFluidTankProperties /** * Created by cout970 on 2017/08/29. */ object VoidFluidHandler : IFluidHandler { override fun drain(resource: FluidStack?, doDrain: Boolean): FluidStack? = null override fun drain(maxDrain: Int, doDrain: Boolean): FluidStack? = null override fun fill(resource: FluidStack?, doFill: Boolean): Int = resource?.amount ?: 0 override fun getTankProperties(): Array<IFluidTankProperties> = arrayOf(VoidFluidTankProperties) } object VoidFluidTankProperties : IFluidTankProperties { override fun canDrainFluidType(fluidStack: FluidStack?): Boolean = false override fun getContents(): FluidStack? = null override fun canFillFluidType(fluidStack: FluidStack?): Boolean = true override fun getCapacity(): Int = 16000 override fun canFill(): Boolean = true override fun canDrain(): Boolean = false } fun IFluidHandler.fillFromTank(max: Int, tank: IFluidHandler): Int { val canDrain = tank.drain(max, false) if (canDrain != null) { val result = fill(canDrain, false) if (result > 0) { val drained = tank.drain(result, true) return fill(drained, true) } } return 0 } fun IFluidHandler.isEmpty(): Boolean { return tankProperties.none { it.contents != null } }
src/main/kotlin/com/cout970/magneticraft/misc/fluid/Utilities.kt
560981724
package com.calintat.units.recycler import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.calintat.units.R import org.jetbrains.anko.find class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal val num = itemView.find<TextView>(R.id.list_item_num) internal val str = itemView.find<TextView>(R.id.list_item_str) internal val sym = itemView.find<TextView>(R.id.list_item_sym) }
app/src/main/java/com/calintat/units/recycler/ViewHolder.kt
520019660
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.searchsuggestions import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import mozilla.components.browser.search.SearchEngine import mozilla.components.browser.search.suggestions.SearchSuggestionClient import okhttp3.OkHttpClient import okhttp3.Request import org.mozilla.focus.utils.debounce import kotlin.coroutines.CoroutineContext class SearchSuggestionsFetcher(searchEngine: SearchEngine) : CoroutineScope { private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main data class SuggestionResult(val query: String, val suggestions: List<String>) private var client: SearchSuggestionClient? = null private var httpClient = OkHttpClient() private val fetchChannel = Channel<String>(capacity = Channel.UNLIMITED) private val _results = MutableLiveData<SuggestionResult>() val results: LiveData<SuggestionResult> = _results var canProvideSearchSuggestions = false private set init { updateSearchEngine(searchEngine) launch(IO) { debounce(THROTTLE_AMOUNT, fetchChannel) .consumeEach { getSuggestions(it) } } } fun requestSuggestions(query: String) { if (query.isBlank()) { _results.value = SuggestionResult(query, listOf()); return } fetchChannel.offer(query) } fun updateSearchEngine(searchEngine: SearchEngine) { canProvideSearchSuggestions = searchEngine.canProvideSearchSuggestions client = if (canProvideSearchSuggestions) SearchSuggestionClient(searchEngine, { fetch(it) }) else null } private suspend fun getSuggestions(query: String) = coroutineScope { val suggestions = try { client?.getSuggestions(query) ?: listOf() } catch (ex: SearchSuggestionClient.ResponseParserException) { listOf<String>() } catch (ex: SearchSuggestionClient.FetchException) { listOf<String>() } launch(Main) { _results.value = SuggestionResult(query, suggestions) } } private fun fetch(url: String): String? { httpClient.dispatcher().queuedCalls() .filter { it.request().tag() == REQUEST_TAG } .forEach { it.cancel() } val request = Request.Builder() .tag(REQUEST_TAG) .url(url) .build() return httpClient.newCall(request).execute().body()?.string() ?: "" } companion object { private const val REQUEST_TAG = "searchSuggestionFetch" private const val THROTTLE_AMOUNT: Long = 100 } }
app/src/main/java/org/mozilla/focus/searchsuggestions/SearchSuggestionsFetcher.kt
3215691831
package net.nemerosa.ontrack.extension.sonarqube.property import net.nemerosa.ontrack.extension.sonarqube.SonarQubeMeasuresList import net.nemerosa.ontrack.extension.sonarqube.configuration.SonarQubeConfiguration import net.nemerosa.ontrack.model.support.ConfigurationProperty import java.net.URLEncoder class SonarQubeProperty( override val configuration: SonarQubeConfiguration, val key: String, val validationStamp: String, override val measures: List<String>, val override: Boolean, val branchModel: Boolean, val branchPattern: String? ) : ConfigurationProperty<SonarQubeConfiguration>, SonarQubeMeasuresList { val projectUrl: String get() = "${configuration.url}/dashboard?id=${URLEncoder.encode(key, "UTF-8")}" companion object { const val DEFAULT_VALIDATION_STAMP = "sonarqube" } }
ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/property/SonarQubeProperty.kt
1183113505
package org.rust.ide.annotator.fixes import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.lang.refactoring.RsPromoteModuleToDirectoryAction import org.rust.lang.core.psi.RsModDeclItem import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.getOrCreateModuleFile /** * Creates module file by the given module declaration. */ class AddModuleFileFix( modDecl: RsModDeclItem, private val expandModuleFirst: Boolean ) : LocalQuickFixAndIntentionActionOnPsiElement(modDecl) { override fun getText(): String = "Create module file" override fun getFamilyName(): String = text override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val modDecl = startElement as RsModDeclItem if (expandModuleFirst) { val containingFile = modDecl.containingFile as RsFile RsPromoteModuleToDirectoryAction.expandModule(containingFile) } modDecl.getOrCreateModuleFile()?.navigate(true) } }
src/main/kotlin/org/rust/ide/annotator/fixes/AddModuleFileFix.kt
2872456856
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.Parcel import android.os.Parcelable import androidx.core.os.ParcelCompat.readBoolean import androidx.core.os.ParcelCompat.writeBoolean import java.util.* data class Project( var masterURL: String = "", var projectDir: String = "", var resourceShare: Float = 0f, var projectName: String = "", var userName: String = "", var teamName: String = "", var hostVenue: String = "", var hostId: Int = 0, val guiURLs: MutableList<GuiUrl?> = mutableListOf(), var userTotalCredit: Double = 0.0, var userExpAvgCredit: Double = 0.0, /** * As reported by server */ var hostTotalCredit: Double = 0.0, /** * As reported by server */ var hostExpAvgCredit: Double = 0.0, var diskUsage: Double = 0.0, var noOfRPCFailures: Int = 0, var masterFetchFailures: Int = 0, /** * Earliest time to contact any server */ var minRPCTime: Double = 0.0, var downloadBackoff: Double = 0.0, var uploadBackoff: Double = 0.0, var cpuShortTermDebt: Double = 0.0, var cpuLongTermDebt: Double = 0.0, var cpuBackoffTime: Double = 0.0, var cpuBackoffInterval: Double = 0.0, var cudaDebt: Double = 0.0, var cudaShortTermDebt: Double = 0.0, var cudaBackoffTime: Double = 0.0, var cudaBackoffInterval: Double = 0.0, var atiDebt: Double = 0.0, var atiShortTermDebt: Double = 0.0, var atiBackoffTime: Double = 0.0, var atiBackoffInterval: Double = 0.0, var durationCorrectionFactor: Double = 0.0, /** * Need to contact scheduling server. Encodes the reason for the request. */ var scheduledRPCPending: Int = 0, var projectFilesDownloadedTime: Double = 0.0, var lastRPCTime: Double = 0.0, /** * Need to fetch and parse the master URL */ var masterURLFetchPending: Boolean = false, var nonCPUIntensive: Boolean = false, var suspendedViaGUI: Boolean = false, var doNotRequestMoreWork: Boolean = false, var schedulerRPCInProgress: Boolean = false, var attachedViaAcctMgr: Boolean = false, var detachWhenDone: Boolean = false, var ended: Boolean = false, var trickleUpPending: Boolean = false, var noCPUPref: Boolean = false, var noCUDAPref: Boolean = false, var noATIPref: Boolean = false ) : Parcelable { val name: String? get() = if (projectName.isEmpty()) masterURL else projectName private constructor(parcel: Parcel) : this(masterURL = parcel.readString() ?: "", projectDir = parcel.readString() ?: "", resourceShare = parcel.readFloat(), projectName = parcel.readString() ?: "", userName = parcel.readString() ?: "", teamName = parcel.readString() ?: "", hostVenue = parcel.readString() ?: "", hostId = parcel.readInt(), userTotalCredit = parcel.readDouble(), userExpAvgCredit = parcel.readDouble(), hostTotalCredit = parcel.readDouble(), hostExpAvgCredit = parcel.readDouble(), diskUsage = parcel.readDouble(), noOfRPCFailures = parcel.readInt(), masterFetchFailures = parcel.readInt(), minRPCTime = parcel.readDouble(), downloadBackoff = parcel.readDouble(), uploadBackoff = parcel.readDouble(), cpuShortTermDebt = parcel.readDouble(), cpuBackoffTime = parcel.readDouble(), cpuBackoffInterval = parcel.readDouble(), cudaDebt = parcel.readDouble(), cudaShortTermDebt = parcel.readDouble(), cudaBackoffTime = parcel.readDouble(), cudaBackoffInterval = parcel.readDouble(), atiDebt = parcel.readDouble(), atiShortTermDebt = parcel.readDouble(), atiBackoffTime = parcel.readDouble(), atiBackoffInterval = parcel.readDouble(), durationCorrectionFactor = parcel.readDouble(), scheduledRPCPending = parcel.readInt(), projectFilesDownloadedTime = parcel.readDouble(), lastRPCTime = parcel.readDouble(), masterURLFetchPending = readBoolean(parcel), nonCPUIntensive = readBoolean(parcel), suspendedViaGUI = readBoolean(parcel), doNotRequestMoreWork = readBoolean(parcel), schedulerRPCInProgress = readBoolean(parcel), attachedViaAcctMgr = readBoolean(parcel), detachWhenDone = readBoolean(parcel), ended = readBoolean(parcel), trickleUpPending = readBoolean(parcel), noCPUPref = readBoolean(parcel), noCUDAPref = readBoolean(parcel), noATIPref = readBoolean(parcel), guiURLs = arrayListOf<GuiUrl?>().apply { if (VERSION.SDK_INT >= VERSION_CODES.TIRAMISU) { parcel.readList(this as MutableList<GuiUrl?>, GuiUrl::class.java.classLoader, GuiUrl::class.java) } else { @Suppress("DEPRECATION") parcel.readList(this as MutableList<*>, GuiUrl::class.java.classLoader) } }) override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is Project && other.resourceShare.compareTo(resourceShare) == 0 && hostId == other.hostId && other.userTotalCredit.compareTo(userTotalCredit) == 0 && other.userExpAvgCredit.compareTo(userExpAvgCredit) == 0 && other.hostTotalCredit.compareTo(hostTotalCredit) == 0 && other.hostExpAvgCredit.compareTo(hostExpAvgCredit) == 0 && other.diskUsage.compareTo(diskUsage) == 0 && noOfRPCFailures == other.noOfRPCFailures && masterFetchFailures == other.masterFetchFailures && other.minRPCTime.compareTo(minRPCTime) == 0 && other.downloadBackoff.compareTo(downloadBackoff) == 0 && other.uploadBackoff.compareTo(uploadBackoff) == 0 && other.cpuShortTermDebt.compareTo(cpuShortTermDebt) == 0 && other.cpuLongTermDebt.compareTo(cpuLongTermDebt) == 0 && other.cpuBackoffTime.compareTo(cpuBackoffTime) == 0 && other.cpuBackoffInterval.compareTo(cpuBackoffInterval) == 0 && other.cudaDebt.compareTo(cudaDebt) == 0 && other.cudaShortTermDebt.compareTo(cudaShortTermDebt) == 0 && other.cudaBackoffTime.compareTo(cudaBackoffTime) == 0 && other.cudaBackoffInterval.compareTo(cudaBackoffInterval) == 0 && other.atiDebt.compareTo(atiDebt) == 0 && other.atiShortTermDebt.compareTo(atiShortTermDebt) == 0 && other.atiBackoffTime.compareTo(atiBackoffTime) == 0 && other.atiBackoffInterval.compareTo(atiBackoffInterval) == 0 && other.durationCorrectionFactor.compareTo(durationCorrectionFactor) == 0 && masterURLFetchPending == other.masterURLFetchPending && scheduledRPCPending == other.scheduledRPCPending && nonCPUIntensive == other.nonCPUIntensive && suspendedViaGUI == other.suspendedViaGUI && doNotRequestMoreWork == other.doNotRequestMoreWork && schedulerRPCInProgress == other.schedulerRPCInProgress && attachedViaAcctMgr == other.attachedViaAcctMgr && detachWhenDone == other.detachWhenDone && ended == other.ended && trickleUpPending == other.trickleUpPending && other.projectFilesDownloadedTime.compareTo(projectFilesDownloadedTime) == 0 && other.lastRPCTime.compareTo(lastRPCTime) == 0 && noCPUPref == other.noCPUPref && noCUDAPref == other.noCUDAPref && noATIPref == other.noATIPref && masterURL.equals(other.masterURL, ignoreCase = true) && projectDir == other.projectDir && projectName == other.projectName && userName.equals(other.userName, ignoreCase = true) && teamName == other.teamName && hostVenue == other.hostVenue && guiURLs == other.guiURLs } override fun hashCode() = Objects.hash( masterURL.lowercase(Locale.ROOT), projectDir, resourceShare, projectName, userName.lowercase(Locale.ROOT), teamName, hostVenue, hostId, guiURLs, userTotalCredit, userExpAvgCredit, hostTotalCredit, hostExpAvgCredit, diskUsage, noOfRPCFailures, masterFetchFailures, minRPCTime, downloadBackoff, uploadBackoff, cpuShortTermDebt, cpuLongTermDebt, cpuBackoffTime, cpuBackoffInterval, cudaDebt, cudaShortTermDebt, cudaBackoffTime, cudaBackoffInterval, atiDebt, atiShortTermDebt, atiBackoffTime, atiBackoffInterval, durationCorrectionFactor, masterURLFetchPending, scheduledRPCPending, nonCPUIntensive, suspendedViaGUI, doNotRequestMoreWork, schedulerRPCInProgress, attachedViaAcctMgr, detachWhenDone, ended, trickleUpPending, projectFilesDownloadedTime, lastRPCTime, noCPUPref, noCUDAPref, noATIPref) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(masterURL) dest.writeString(projectDir) dest.writeFloat(resourceShare) dest.writeString(projectName) dest.writeString(userName) dest.writeString(teamName) dest.writeString(hostVenue) dest.writeInt(hostId) dest.writeDouble(userTotalCredit) dest.writeDouble(userExpAvgCredit) dest.writeDouble(hostTotalCredit) dest.writeDouble(hostExpAvgCredit) dest.writeDouble(diskUsage) dest.writeInt(noOfRPCFailures) dest.writeInt(masterFetchFailures) dest.writeDouble(minRPCTime) dest.writeDouble(downloadBackoff) dest.writeDouble(uploadBackoff) dest.writeDouble(cpuShortTermDebt) dest.writeDouble(cpuBackoffTime) dest.writeDouble(cpuBackoffInterval) dest.writeDouble(cudaDebt) dest.writeDouble(cudaShortTermDebt) dest.writeDouble(cudaBackoffTime) dest.writeDouble(cudaBackoffInterval) dest.writeDouble(atiDebt) dest.writeDouble(atiShortTermDebt) dest.writeDouble(atiBackoffTime) dest.writeDouble(atiBackoffInterval) dest.writeDouble(durationCorrectionFactor) dest.writeInt(scheduledRPCPending) dest.writeDouble(projectFilesDownloadedTime) dest.writeDouble(lastRPCTime) writeBoolean(dest, masterURLFetchPending) writeBoolean(dest, nonCPUIntensive) writeBoolean(dest, suspendedViaGUI) writeBoolean(dest, doNotRequestMoreWork) writeBoolean(dest, schedulerRPCInProgress) writeBoolean(dest, attachedViaAcctMgr) writeBoolean(dest, detachWhenDone) writeBoolean(dest, ended) writeBoolean(dest, trickleUpPending) writeBoolean(dest, noCPUPref) writeBoolean(dest, noCUDAPref) writeBoolean(dest, noATIPref) dest.writeList(guiURLs.toList()) } object Fields { const val PROJECT_DIR = "project_dir" const val RESOURCE_SHARE = "resource_share" const val USER_NAME = "user_name" const val TEAM_NAME = "team_name" const val HOST_VENUE = "host_venue" const val HOSTID = "hostid" const val USER_TOTAL_CREDIT = "user_total_credit" const val USER_EXPAVG_CREDIT = "user_expavg_credit" const val HOST_TOTAL_CREDIT = "host_total_credit" const val HOST_EXPAVG_CREDIT = "host_expavg_credit" const val NRPC_FAILURES = "nrpc_failures" const val MASTER_FETCH_FAILURES = "master_fetch_failures" const val MIN_RPC_TIME = "min_rpc_time" const val DOWNLOAD_BACKOFF = "download_backoff" const val UPLOAD_BACKOFF = "upload_backoff" const val CPU_BACKOFF_TIME = "cpu_backoff_time" const val CPU_BACKOFF_INTERVAL = "cpu_backoff_interval" const val CUDA_DEBT = "cuda_debt" const val CUDA_SHORT_TERM_DEBT = "cuda_short_term_debt" const val CUDA_BACKOFF_TIME = "cuda_backoff_time" const val CUDA_BACKOFF_INTERVAL = "cuda_backoff_interval" const val ATI_DEBT = "ati_debt" const val ATI_SHORT_TERM_DEBT = "ati_short_term_debt" const val ATI_BACKOFF_TIME = "ati_backoff_time" const val ATI_BACKOFF_INTERVAL = "ati_backoff_interval" const val DURATION_CORRECTION_FACTOR = "duration_correction_factor" const val MASTER_URL_FETCH_PENDING = "master_url_fetch_pending" const val SCHED_RPC_PENDING = "sched_rpc_pending" const val SUSPENDED_VIA_GUI = "suspended_via_gui" const val DONT_REQUEST_MORE_WORK = "dont_request_more_work" const val SCHEDULER_RPC_IN_PROGRESS = "scheduler_rpc_in_progress" const val ATTACHED_VIA_ACCT_MGR = "attached_via_acct_mgr" const val DETACH_WHEN_DONE = "detach_when_done" const val ENDED = "ended" const val TRICKLE_UP_PENDING = "trickle_up_pending" const val PROJECT_FILES_DOWNLOADED_TIME = "project_files_downloaded_time" const val LAST_RPC_TIME = "last_rpc_time" const val NO_CPU_PREF = "no_cpu_pref" const val NO_CUDA_PREF = "no_cuda_pref" const val NO_ATI_PREF = "no_ati_pref" const val DISK_USAGE = "disk_usage" } companion object { @JvmField val CREATOR: Parcelable.Creator<Project> = object : Parcelable.Creator<Project> { override fun createFromParcel(parcel: Parcel) = Project(parcel) override fun newArray(size: Int) = arrayOfNulls<Project>(size) } } }
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/Project.kt
1508962697
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.reply.ui.nav import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.ListAdapter import com.materialstudies.reply.databinding.NavDividerItemLayoutBinding import com.materialstudies.reply.databinding.NavEmailFolderItemLayoutBinding import com.materialstudies.reply.databinding.NavMenuItemLayoutBinding private const val VIEW_TYPE_NAV_MENU_ITEM = 4 private const val VIEW_TYPE_NAV_DIVIDER = 6 private const val VIEW_TYPE_NAV_EMAIL_FOLDER_ITEM = 5 class NavigationAdapter( private val listener: NavigationAdapterListener ) : ListAdapter<NavigationModelItem, NavigationViewHolder<NavigationModelItem>>( NavigationModelItem.NavModelItemDiff ) { interface NavigationAdapterListener { fun onNavMenuItemClicked(item: NavigationModelItem.NavMenuItem) fun onNavEmailFolderClicked(folder: NavigationModelItem.NavEmailFolder) } override fun getItemViewType(position: Int): Int { return when (getItem(position)) { is NavigationModelItem.NavMenuItem -> VIEW_TYPE_NAV_MENU_ITEM is NavigationModelItem.NavDivider -> VIEW_TYPE_NAV_DIVIDER is NavigationModelItem.NavEmailFolder -> VIEW_TYPE_NAV_EMAIL_FOLDER_ITEM else -> throw RuntimeException("Unsupported ItemViewType for obj ${getItem(position)}") } } @Suppress("unchecked_cast") override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): NavigationViewHolder<NavigationModelItem> { return when (viewType) { VIEW_TYPE_NAV_MENU_ITEM -> NavigationViewHolder.NavMenuItemViewHolder( NavMenuItemLayoutBinding.inflate( LayoutInflater.from(parent.context), parent, false ), listener ) VIEW_TYPE_NAV_DIVIDER -> NavigationViewHolder.NavDividerViewHolder( NavDividerItemLayoutBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) VIEW_TYPE_NAV_EMAIL_FOLDER_ITEM -> NavigationViewHolder.EmailFolderViewHolder( NavEmailFolderItemLayoutBinding.inflate( LayoutInflater.from(parent.context), parent, false ), listener ) else -> throw RuntimeException("Unsupported view holder type") } as NavigationViewHolder<NavigationModelItem> } override fun onBindViewHolder( holder: NavigationViewHolder<NavigationModelItem>, position: Int ) { holder.bind(getItem(position)) } }
Reply/app/src/main/java/com/materialstudies/reply/ui/nav/NavigationAdapter.kt
2849833818
package org.ojacquemart.eurobets.firebase.initdb.fixture import com.fasterxml.jackson.annotation.JsonUnwrapped import org.ojacquemart.eurobets.firebase.initdb.i18n.I18n data class TeamI18n( @JsonUnwrapped val i18n: I18n, val isoAlpha2Code: String, val goals: Int, val winner: Boolean = false)
src/main/kotlin/org/ojacquemart/eurobets/firebase/initdb/fixture/TeamI18n.kt
4020165045
/* * Copyright (c) 2018 Ollix. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * --- * Author: [email protected] (Olli Wang) */ package com.ollix.moui import android.content.Context import java.io.File class Path(context: Context) { private val context: Context init { this.context = context } fun getCacheDir(): String { val file = context.getCacheDir() return file.getAbsolutePath() } fun getDocumentDir(): String { val file = context.getDir("Document", 0) return file.getAbsolutePath() } fun getFilesDir(): String { val file = context.getFilesDir() return file.getAbsolutePath() } }
android/src/main/java/com/ollix/moui/Path.kt
3635329178
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.server.command import org.tmatesoft.svn.core.SVNErrorCode import org.tmatesoft.svn.core.SVNErrorMessage import org.tmatesoft.svn.core.SVNException import svnserver.parser.SvnServerWriter import svnserver.repository.VcsCopyFrom import svnserver.server.SessionContext import java.io.IOException import java.util.* /** * <pre> * get-locations * params: ( path:string peg-rev:number ( rev:number ... ) ) * Before sending response, server sends location entries, ending with "done". * location-entry: ( rev:number abs-path:number ) | done * response: ( ) </pre> * * * @author a.navrotskiy */ class GetLocationsCmd : BaseCmd<GetLocationsCmd.Params>() { override val arguments: Class<out Params> get() { return Params::class.java } @Throws(IOException::class, SVNException::class) override fun processCommand(context: SessionContext, args: Params) { val writer: SvnServerWriter = context.writer val sortedRevs: IntArray = args.revs.copyOf(args.revs.size) Arrays.sort(sortedRevs) var fullPath: String = context.getRepositoryPath(args.path) var lastChange: Int? = context.branch.getLastChange(fullPath, args.pegRev) if (lastChange == null) { writer.word("done") throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "File not found: " + fullPath + "@" + args.pegRev)) } for (i in sortedRevs.indices.reversed()) { val revision: Int = sortedRevs[i] if (revision > args.pegRev) { writer.word("done") throw SVNException(SVNErrorMessage.create(SVNErrorCode.FS_NOT_FOUND, "File not found: " + fullPath + "@" + args.pegRev + " at revision " + revision)) } while ((lastChange != null) && (revision < lastChange)) { val change: Int? = context.branch.getLastChange(fullPath, lastChange - 1) if (change != null) { lastChange = change continue } val copyFrom: VcsCopyFrom? = context.branch.getRevisionInfo(lastChange).getCopyFrom(fullPath) if (copyFrom == null || !context.canRead(copyFrom.path)) { lastChange = null break } lastChange = copyFrom.revision fullPath = copyFrom.path } if (lastChange == null) break if (revision >= lastChange) { writer .listBegin() .number(revision.toLong()) .string(fullPath) .listEnd() } } writer .word("done") writer .listBegin() .word("success") .listBegin() .listEnd() .listEnd() } @Throws(IOException::class, SVNException::class) override fun permissionCheck(context: SessionContext, args: Params) { context.checkRead(context.getRepositoryPath(args.path)) } class Params constructor(val path: String, val pegRev: Int, val revs: IntArray) }
src/main/kotlin/svnserver/server/command/GetLocationsCmd.kt
2646424717
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[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 dev.yuriel.mahjan.enums import dev.yuriel.kotmvp.LEFT_SIDE import dev.yuriel.kotmvp.RIGHT_SIDE /** * Created by yuriel on 8/6/16. */ enum class TileSide(val value: Int) { LEFT(LEFT_SIDE), RIGHT(RIGHT_SIDE) }
app/src/main/java/dev/yuriel/mahjan/enums/TileSide.kt
20336276
package com.soywiz.korge.input import com.soywiz.korge.view.* import com.soywiz.korma.geom.* import kotlin.math.* data class SwipeInfo( var dx: Double = 0.0, var dy: Double = 0.0, var direction: SwipeDirection ) { fun setTo(dx: Double, dy: Double, direction: SwipeDirection): SwipeInfo { this.dx = dx this.dy = dy this.direction = direction return this } } enum class SwipeDirection { LEFT, RIGHT, TOP, BOTTOM } /** * This methods lets you specify a [callback] to execute when swipe event is triggered. * @property threshold a threshold for dx or dy after which a swipe event should be triggered. * Negative [threshold] means a swipe event should be triggered only after [onUp] mouse event. * [threshold] is set to -1 by default. * @property direction a direction for which a swipe event should be triggered. * [direction] is set to null by default, which means a swipe event should be triggered for any direction. * @property callback a callback to execute */ fun <T : View> T.onSwipe( threshold: Double = -1.0, direction: SwipeDirection? = null, callback: suspend Views.(SwipeInfo) -> Unit ): T { var register = false var sx = 0.0 var sy = 0.0 var cx = 0.0 var cy = 0.0 var movedLeft = false var movedRight = false var movedTop = false var movedBottom = false val view = this val mousePos = Point() val swipeInfo = SwipeInfo(0.0, 0.0, SwipeDirection.TOP) fun views() = view.stage!!.views fun updateMouse() { val views = views() mousePos.setTo( views.nativeMouseX, views.nativeMouseY ) } fun updateCoordinates() { if (mousePos.x < cx) movedLeft = true if (mousePos.x > cx) movedRight = true if (mousePos.y < cy) movedTop = true if (mousePos.y > cy) movedBottom = true cx = mousePos.x cy = mousePos.y } suspend fun triggerEvent(direction: SwipeDirection) { register = false views().callback(swipeInfo.setTo(cx - sx, cy - sy, direction)) } suspend fun checkPositionOnMove() { if (threshold < 0) return val curDirection = when { sx - cx > threshold && !movedRight -> SwipeDirection.LEFT cx - sx > threshold && !movedLeft -> SwipeDirection.RIGHT sy - cy > threshold && !movedBottom -> SwipeDirection.TOP cy - sy > threshold && !movedTop -> SwipeDirection.BOTTOM else -> return } if (direction == null || direction == curDirection) { triggerEvent(curDirection) } } suspend fun checkPositionOnUp() { if (threshold >= 0) return val horDiff = abs(cx - sx) val verDiff = abs(cy - sy) val curDirection = when { horDiff >= verDiff && cx < sx && !movedRight -> SwipeDirection.LEFT horDiff >= verDiff && cx > sx && !movedLeft -> SwipeDirection.RIGHT horDiff <= verDiff && cy < sy && !movedBottom -> SwipeDirection.TOP horDiff <= verDiff && cy > sy && !movedTop -> SwipeDirection.BOTTOM else -> return } if (direction == null || direction == curDirection) { triggerEvent(curDirection) } } this.mouse { onDown { updateMouse() register = true sx = mousePos.x sy = mousePos.y cx = sx cy = sy movedLeft = false movedRight = false movedTop = false movedBottom = false } onMoveAnywhere { if (register) { updateMouse() updateCoordinates() checkPositionOnMove() } } onUpAnywhere { if (register) { updateMouse() updateCoordinates() register = false checkPositionOnUp() } } } return this }
korge/src/commonMain/kotlin/com/soywiz/korge/input/SwipeComponent.kt
242877726
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[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 dev.yuriel.kotmvp.bases import android.os.Bundle import com.badlogic.gdx.Gdx import com.badlogic.gdx.backends.android.AndroidFragmentApplication /** * Created by yuriel on 8/2/16. */ class BaseFragment: AndroidFragmentApplication() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } }
app/src/main/java/dev/yuriel/kotmvp/bases/BaseFragment.kt
2355601517
package com.protryon.jasm class Field(val parent: Klass, var type: JType, var name: String) { var isPublic = false var isPrivate = false var isProtected = false var isStatic = false var isFinal = false var isVolatile = false var isTransient = false var isSynthetic = false var isEnum = false var constantValue: Constant<*>? = null // set for created methods in things like stdlib or unincluded libs var isDummy = false }
src/main/java/com/protryon/jasm/Field.kt
2309385185
package com.tamsiree.rxkit.interfaces /** * @author Tamsiree * @date 2017/4/19 */ interface OnSuccessAndErrorListener { fun onSuccess(s: String?) fun onError(s: String?) }
RxKit/src/main/java/com/tamsiree/rxkit/interfaces/OnSuccessAndErrorListener.kt
2328784511
/* * Copyright 2020 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pasterino.settings import androidx.compose.runtime.Stable import com.pyamsoft.pydroid.arch.UiViewState @Stable data class SettingsViewState internal constructor( val delayTime: Long, val isDeepSearch: Boolean, ) : UiViewState
app/src/main/java/com/pyamsoft/pasterino/settings/SettingsFlow.kt
1091786271
package chat.rocket.android.chatdetails.domain data class ChatDetails( val name: String?, val fullName: String?, val type: String?, val topic: String?, val announcement: String?, val description: String? )
app/src/main/java/chat/rocket/android/chatdetails/domain/ChatDetails.kt
3417388409
package com.telenav.osv.utils import android.content.Context import android.util.TypedValue import androidx.lifecycle.MutableLiveData import androidx.recyclerview.widget.RecyclerView import com.google.android.gms.tasks.Task import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.PreferenceTypes import com.telenav.osv.jarvis.login.utils.LoginUtils import com.telenav.osv.map.model.MapModes import com.telenav.osv.recorder.camera.Camera import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine /** * Extension method for creating a [MutableLiveData] with a default value by calling internally with the [apply] function the setter. */ fun <T : Any?> MutableLiveData<T>.default(initialValue: T) = apply { setValue(initialValue) } /** * Transforms [Task] into a suspended function with respect to the type. */ suspend fun <T> Task<T>.await(): T? = suspendCoroutine { continuation -> addOnCompleteListener { task -> if (task.isSuccessful) { continuation.resume(task.result) } else { continuation.resumeWithException(task.exception ?: RuntimeException("Unknown task exception")) } } } fun <T : RecyclerView.ViewHolder> T.listen(event: (position: Int, type: Int) -> Unit): T { itemView.setOnClickListener { event.invoke(adapterPosition, itemViewType) } return this } fun <T> concatenate(vararg lists: List<T>): List<T> { return listOf(*lists).flatten() } /** * Extension method for [Camera] to return the resolution based on video format. * * If the camera API used is Camera1 and the recording mode is video the images for encoder have the same size as the preview. * The camera1 doesn't support to set a custom size for frames which is not depending on the preview available sizes, * therefore the maximum size for a frame will be of 1920x1080. * @return the resolution as [Size] for the [Camera] used in video/jpeg. */ fun Camera.getResolution(): Size { return if (isVideoMode && !isCamera2Api) { Log.d("Camera", "getResolution. Status: Return preview size since Camera API V1 and video mode is on. Preview size: $previewSize") previewSize } else { Log.d("Camera", "getResolution. Status: Return picture size. Picture size: $pictureSize") pictureSize } } /** * Extension method to close the camera */ fun Camera.close() { if (isCameraOpen) { closeCamera() } } fun Context.getDimension(value: Float): Int { return TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, value, this.resources.displayMetrics).toInt() } /** * Extension method for [ApplicationPreferences] which will return based on saved data the [MapModes] */ fun ApplicationPreferences.getMapMode(): MapModes { return if (this.getBooleanPreference(PreferenceTypes.K_MAP_ENABLED)) { if (LoginUtils.isLoginTypePartner(this)) MapModes.GRID else MapModes.IDLE } else MapModes.DISABLED } /** * Extension method for [ApplicationPreferences] which will return the status for enabling or not the map for Recording feature */ fun ApplicationPreferences.enableMapForRecording(): Boolean { return this.getBooleanPreference(PreferenceTypes.K_MAP_ENABLED) && this.getBooleanPreference(PreferenceTypes.K_RECORDING_MINI_MAP_ENABLED, true) }
app/src/main/java/com/telenav/osv/utils/Extensions.kt
2656298578
package com.telenav.osv.ui.fragment.settings import android.Manifest import android.content.Context import android.view.View import android.widget.RadioGroup import androidx.preference.PreferenceViewHolder import androidx.test.InstrumentationRegistry import androidx.test.annotation.UiThreadTest import androidx.test.rule.GrantPermissionRule import com.telenav.osv.R import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.KVApplication import com.telenav.osv.application.PreferenceTypes import com.telenav.osv.ui.fragment.settings.custom.RadioGroupPreference import com.telenav.osv.ui.fragment.settings.viewmodel.DistanceUnitViewModel import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.MockitoAnnotations class DistanceUnitViewModelTest { private lateinit var viewModel: DistanceUnitViewModel private lateinit var context: Context private lateinit var appPrefs: ApplicationPreferences @Before fun setUp() { GrantPermissionRule.grant(Manifest.permission.CAMERA) context = InstrumentationRegistry.getTargetContext() val app = InstrumentationRegistry.getTargetContext().applicationContext as KVApplication MockitoAnnotations.initMocks(this) appPrefs = ApplicationPreferences(app) viewModel = DistanceUnitViewModel(app, appPrefs) } @Test @UiThreadTest fun testDistanceUnitClick() { val preference = getGroupPreference() val checkedChangeListener = preference.onCheckedChangeListener var preferenceChanged = false preference.onCheckedChangeListener = (RadioGroup.OnCheckedChangeListener { radioGroup, i -> preferenceChanged = true checkedChangeListener.onCheckedChanged(radioGroup, i) }) preference.onBindViewHolder(PreferenceViewHolder.createInstanceForTests(View.inflate(context, R.layout.settings_item_radio_group, null))) preference.radioButtonList[0].isChecked = false preference.radioButtonList[0].isChecked = true Assert.assertTrue(preferenceChanged) val distanceUnitTag = preference.radioButtonList[0].tag as Int Assert.assertEquals(distanceUnitTag == DistanceUnitViewModel.TAG_METRIC, appPrefs.getBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC)) } @Test @UiThreadTest fun testStoredDistanceUnitCheckedWhenDisplayingTheList() { val preference = getGroupPreference() for (radioButton in preference.radioButtonList) { if (radioButton.isChecked) { val distanceUnitTag = radioButton.tag as Int Assert.assertEquals(distanceUnitTag == DistanceUnitViewModel.TAG_METRIC, appPrefs.getBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC)) return } } Assert.assertTrue(false) } private fun getGroupPreference(): RadioGroupPreference { viewModel.settingsDataObservable viewModel.start() val settingsGroups = viewModel.settingsDataObservable.value!! return settingsGroups[0].getPreference(context) as RadioGroupPreference } }
app/src/androidTest/java/com/telenav/osv/ui/fragment/settings/DistanceUnitViewModelTest.kt
2537746144
package api.event import io.luna.game.event.impl.ItemOnItemEvent import io.luna.game.event.impl.ItemOnObjectEvent /** * A model that intercepts [ItemOnItemEvent]s and [ItemOnObjectEvent]s. * * @author lare96 */ class InterceptUseItem(private val id: Int) { /** * Intercepts an [ItemOnItemEvent]. **Will match both ways!** */ fun onItem(itemId: Int, action: ItemOnItemEvent.() -> Unit) { val matcher = Matcher.get<ItemOnItemEvent, Pair<Int, Int>>() matcher[id to itemId] = { action(this) } matcher[itemId to id] = { action(this) } } /** * Intercepts an [ItemOnObjectEvent]. */ fun onObject(objectId: Int, action: ItemOnObjectEvent.() -> Unit) { val matcher = Matcher.get<ItemOnObjectEvent, Pair<Int, Int>>() matcher[id to objectId] = { action(this) } } }
plugins/api/event/InterceptUseItem.kt
3505340395
package com.cossacklabs.themis.android.example import android.os.Bundle import android.util.Base64 import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.cossacklabs.themis.PrivateKey import com.cossacklabs.themis.PublicKey import com.cossacklabs.themis.SecureMessage import java.nio.charset.StandardCharsets import java.util.* class MainActivitySecureMessage : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Check secure message try { secureMessageLocal() } catch (e: Exception) { e.printStackTrace() } } private fun secureMessageLocal() { val charset = StandardCharsets.UTF_8 val clientPrivateKey = "UkVDMgAAAC1EvnquAPUxxwJsoJxoMAkEF7c06Fo7dVwnWPnmNX5afyjEEGmG" val serverPublicKey = "VUVDMgAAAC1FJv/DAmg8/L1Pl5l6ypyRqXUU9xQQaAgzfRZ+/gsjqgEdwXhc" val message = "some weird message here" val privateKey = PrivateKey(Base64.decode(clientPrivateKey.toByteArray(charset(charset.name())), Base64.NO_WRAP)) val publicKey = PublicKey(Base64.decode(serverPublicKey.toByteArray(charset(charset.name())), Base64.NO_WRAP)) Log.d("SMC", "privateKey1 = " + Arrays.toString(privateKey.toByteArray())) Log.d("SMC", "publicKey1 = " + Arrays.toString(publicKey.toByteArray())) val sm = SecureMessage(privateKey, publicKey) val wrappedMessage = sm.wrap(message.toByteArray(charset(charset.name()))) val encodedMessage = Base64.encodeToString(wrappedMessage, Base64.NO_WRAP) Log.d("SMC", "EncodedMessage = $encodedMessage") val wrappedMessageFromB64 = Base64.decode(encodedMessage, Base64.NO_WRAP) val decodedMessage = String(sm.unwrap(wrappedMessageFromB64), charset) Log.d("SMC", "DecodedMessageFromOwnCode = $decodedMessage") val encodedMessageFromExternal = "ICcEJksAAAAAAQFADAAAABAAAAAXAAAAFi/vBAb2fiNBqf3a6wgyVoMAdPXpJ14ZYxk/oaUcwSmKnNgmRzaH7JkIQBvFChAVK9tF" val wrappedMessageFromB64External = Base64.decode(encodedMessageFromExternal, Base64.NO_WRAP) val decodedMessageExternal = String(sm.unwrap(wrappedMessageFromB64External), charset) Log.d("SMC", "DecodedMessageFromExternal = $decodedMessageExternal") } }
docs/examples/android/app/src/main/java/com/cossacklabs/themis/android/example/MainActivitySecureMessage.kt
3170418086
package net.semlang.transforms typealias RenamingStrategy = (name: String, allNamesPresent: Set<String>) -> String object RenamingStrategies { fun getKeywordAvoidingStrategy(keywords: Set<String>): RenamingStrategy { return fun(varName: String, allVarNamesPresent: Set<String>): String { if (!keywords.contains(varName)) { return varName } var suffix = 1 var newName = varName + suffix while (allVarNamesPresent.contains(newName)) { suffix += 1 newName = varName + suffix } return newName } } }
kotlin/semlang-transforms/src/main/kotlin/RenamingStrategy.kt
401633031
package cn.devifish.readme.view.adapter import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import cn.devifish.readme.R import cn.devifish.readme.entity.Book import cn.devifish.readme.provider.BookProvider import cn.devifish.readme.service.BookService import cn.devifish.readme.util.RxJavaUtil import cn.devifish.readme.view.base.BaseRecyclerAdapter import cn.devifish.readme.view.base.BaseViewHolder import kotlinx.android.synthetic.main.header_book_detail.view.* import kotlinx.android.synthetic.main.list_item_stack.view.* import java.text.SimpleDateFormat /** * Created by zhang on 2017/8/3. * 书籍详情列表适配器 */ class BookDetailRecyclerAdapter(val book: Book) : BaseRecyclerAdapter<Any, BaseViewHolder<Any>>() { private val bookProvider = BookProvider.getInstance().create(BookService::class.java) companion object { val TYPE_DETAIL = 0 val TYPE_BETTER = 1 val TYPE_NORMAL = 2 } override fun getItemViewType(position: Int): Int { when (position) { 0 -> return TYPE_DETAIL 1 -> return TYPE_BETTER else -> return TYPE_NORMAL } } override fun onCreateView(group: ViewGroup, viewType: Int): BaseViewHolder<Any> { val layoutInflater = LayoutInflater.from(group.context) when (viewType) { TYPE_DETAIL -> { val view = layoutInflater.inflate(R.layout.header_book_detail, group, false) return BookDetailHolder(view) } TYPE_BETTER -> { val view = layoutInflater.inflate(R.layout.list_item_stack, group, false) return BetterBookHolder(view) } TYPE_NORMAL -> { } } val view = layoutInflater.inflate(R.layout.header_book_detail, group, false) return BookDetailHolder(view) } override fun onBindView(holder: BaseViewHolder<Any>, position: Int) { when (getItemViewType(position)) { TYPE_DETAIL -> (holder as BookDetailHolder).bind(book) TYPE_BETTER -> (holder as BetterBookHolder).bind(book) TYPE_NORMAL -> { } } } override fun getItemCount(): Int = if (super.getItemCount() < 2) 2 else super.getItemCount() inner class BookDetailHolder(itemView: View) : BaseViewHolder<Any>(itemView) { @SuppressLint("SimpleDateFormat") override fun bind(m: Any) { val context = itemView.context RxJavaUtil.getObservable(bookProvider.getBookDetail((m as Book)._id!!)) .subscribe { bookDetail -> itemView.serial_info.text = context.getString(if (bookDetail.isSerial) R.string.book_serial else R.string.book_end) itemView.update.text = SimpleDateFormat("yyyy-MM-dd").format(bookDetail.updated) itemView.chapter_count.text = context.getString(R.string.book_chapterCount, bookDetail.chaptersCount.toString()) itemView.book_intro.text = bookDetail.longIntro } } } inner class BetterBookHolder(itemView: View) : BaseViewHolder<Any>(itemView) { override fun bind(m: Any) { itemView.name.text = "更多书籍" } } }
app/src/main/java/cn/devifish/readme/view/adapter/BookDetailRecyclerAdapter.kt
3503198281
package com.stripe.android.stripecardscan.framework.time import androidx.test.filters.SmallTest import com.stripe.android.camera.framework.time.Duration import com.stripe.android.camera.framework.time.days import com.stripe.android.camera.framework.time.hours import com.stripe.android.camera.framework.time.max import com.stripe.android.camera.framework.time.microseconds import com.stripe.android.camera.framework.time.milliseconds import com.stripe.android.camera.framework.time.min import com.stripe.android.camera.framework.time.minutes import com.stripe.android.camera.framework.time.months import com.stripe.android.camera.framework.time.nanoseconds import com.stripe.android.camera.framework.time.seconds import com.stripe.android.camera.framework.time.weeks import com.stripe.android.camera.framework.time.years import org.junit.Test import kotlin.math.pow import kotlin.math.roundToInt import kotlin.math.roundToLong import kotlin.random.Random import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue private fun Float.truncate(digits: Int) = ((this * 10.0.pow(digits)).roundToLong() / 10.0.pow(digits)).toFloat() private fun Double.truncate(digits: Int) = (this * 10.0.pow(digits)).roundToLong() / 10.0.pow(digits) class DurationTest { @Test @SmallTest fun reflective() { val randomInt = Random.nextInt(-10, 10) val randomLong = Random.nextLong(-10, 10) val randomFloat = Random.nextFloat() * 20 - 10 val randomDouble = Random.nextDouble() * 20 - 10 assertEquals(randomInt, randomInt.nanoseconds.inNanoseconds.toInt()) assertEquals(randomInt, randomInt.microseconds.inMicroseconds.roundToInt()) assertEquals(randomInt, randomInt.milliseconds.inMilliseconds.roundToInt()) assertEquals(randomInt, randomInt.seconds.inSeconds.roundToInt()) assertEquals(randomInt, randomInt.minutes.inMinutes.roundToInt()) assertEquals(randomInt, randomInt.hours.inHours.roundToInt()) assertEquals(randomInt, randomInt.days.inDays.roundToInt()) assertEquals(randomInt, randomInt.weeks.inWeeks.roundToInt()) assertEquals(randomInt, randomInt.months.inMonths.roundToInt()) assertEquals(randomInt, randomInt.years.inYears.roundToInt()) assertEquals(randomLong, randomLong.nanoseconds.inNanoseconds) assertEquals(randomLong, randomLong.microseconds.inMicroseconds.roundToLong()) assertEquals(randomLong, randomLong.milliseconds.inMilliseconds.roundToLong()) assertEquals(randomLong, randomLong.seconds.inSeconds.roundToLong()) assertEquals(randomLong, randomLong.minutes.inMinutes.roundToLong()) assertEquals(randomLong, randomLong.hours.inHours.roundToLong()) assertEquals(randomLong, randomLong.days.inDays.roundToLong()) assertEquals(randomLong, randomLong.weeks.inWeeks.roundToLong()) assertEquals(randomLong, randomLong.months.inMonths.roundToLong()) assertEquals(randomLong, randomLong.years.inYears.roundToLong()) // These have to be truncated since the limiting factor for accuracy is nanoseconds. assertEquals( randomFloat.roundToLong(), randomFloat.nanoseconds.inNanoseconds, randomFloat.toString() ) assertEquals( randomFloat.truncate(3), randomFloat.microseconds.inMicroseconds.toFloat(), randomFloat.toString() ) assertEquals( randomFloat.truncate(6), randomFloat.milliseconds.inMilliseconds.toFloat(), randomFloat.toString() ) assertEquals( randomFloat.truncate(9), randomFloat.seconds.inSeconds.toFloat(), randomFloat.toString() ) assertEquals(randomFloat, randomFloat.minutes.inMinutes.toFloat(), randomFloat.toString()) assertEquals(randomFloat, randomFloat.hours.inHours.toFloat(), randomFloat.toString()) assertEquals(randomFloat, randomFloat.days.inDays.toFloat(), randomFloat.toString()) assertEquals(randomFloat, randomFloat.weeks.inWeeks.toFloat(), randomFloat.toString()) assertEquals(randomFloat, randomFloat.months.inMonths.toFloat(), randomFloat.toString()) assertEquals(randomFloat, randomFloat.years.inYears.toFloat(), randomFloat.toString()) // These have to be truncated since the limiting factor for accuracy is nanoseconds. assertEquals( randomDouble.roundToLong(), randomDouble.nanoseconds.inNanoseconds, randomDouble.toString() ) assertEquals( randomDouble.truncate(3), randomDouble.microseconds.inMicroseconds, randomDouble.toString() ) assertEquals( randomDouble.truncate(6), randomDouble.milliseconds.inMilliseconds.truncate(6), randomDouble.toString() ) assertEquals( randomDouble.truncate(9), randomDouble.seconds.inSeconds.truncate(9), randomDouble.toString() ) assertEquals( randomDouble.truncate(8), randomDouble.minutes.inMinutes.truncate(8), randomDouble.toString() ) assertEquals( randomDouble.truncate(10), randomDouble.hours.inHours.truncate(10), randomDouble.toString() ) assertEquals( randomDouble.truncate(10), randomDouble.days.inDays.truncate(10), randomDouble.toString() ) assertEquals( randomDouble.truncate(11), randomDouble.weeks.inWeeks.truncate(11), randomDouble.toString() ) assertEquals( randomDouble.truncate(11), randomDouble.months.inMonths.truncate(11), randomDouble.toString() ) assertEquals( randomDouble.truncate(11), randomDouble.years.inYears.truncate(11), randomDouble.toString() ) } @Test @SmallTest fun minMax() { assertEquals(5.seconds, max(1.milliseconds, 5.seconds)) assertEquals(5.seconds, max(5.seconds, 1.milliseconds)) assertEquals(1.milliseconds, min(1.milliseconds, 5.seconds)) assertEquals(1.milliseconds, min(5.seconds, 1.milliseconds)) assertEquals(Duration.INFINITE, max(1.milliseconds, Duration.INFINITE)) assertEquals(Duration.INFINITE, max(Duration.INFINITE, 1.milliseconds)) assertEquals(Duration.INFINITE, max(Duration.INFINITE, Duration.INFINITE)) assertEquals(Duration.ZERO, max(Duration.NEGATIVE_INFINITE, Duration.ZERO)) assertEquals(Duration.ZERO, max(Duration.ZERO, Duration.NEGATIVE_INFINITE)) assertEquals( Duration.NEGATIVE_INFINITE, max(Duration.NEGATIVE_INFINITE, Duration.NEGATIVE_INFINITE) ) assertEquals( Duration.NEGATIVE_INFINITE, min(1.milliseconds, Duration.NEGATIVE_INFINITE) ) assertEquals( Duration.NEGATIVE_INFINITE, min(Duration.NEGATIVE_INFINITE, 1.milliseconds) ) assertEquals( Duration.NEGATIVE_INFINITE, min(Duration.NEGATIVE_INFINITE, Duration.NEGATIVE_INFINITE) ) assertEquals(Duration.ZERO, min(Duration.ZERO, Duration.INFINITE)) assertEquals(Duration.ZERO, min(Duration.INFINITE, Duration.ZERO)) assertEquals(Duration.INFINITE, min(Duration.INFINITE, Duration.INFINITE)) } @Test @SmallTest fun arithmetic() { assertEquals(5005.milliseconds, 5.milliseconds + 5.seconds) assertEquals(26.seconds, 6000.milliseconds + 20.seconds) assertEquals(4995.milliseconds, 5.seconds - 5.milliseconds) assertEquals(14.seconds, 20.seconds - 6000.milliseconds) assertEquals((-5).seconds, 55.seconds - 1.minutes) assertEquals(6.seconds, 2.seconds * 3) assertEquals(1.weeks, 3.5.days * 2) assertEquals(9.seconds, 6.seconds * 1.5F) assertEquals(9.seconds, 6.seconds * 1.5) assertEquals(2.days, (4.0 / 7).weeks / 2) assertEquals(6.seconds, 12.seconds / 2) assertEquals(4.minutes, 10.minutes / 2.5F) assertEquals(4.minutes, 10.minutes / 2.5) assertEquals((-5).years, -(5.years)) assertEquals(2.months, -((-2).months)) } @Test @SmallTest fun comparison() { assertTrue { 5.milliseconds > 5.microseconds } assertFalse { 5.milliseconds < 5.microseconds } assertTrue { 5.milliseconds >= 5.microseconds } assertTrue { 5.milliseconds < 6.milliseconds } assertFalse { 5.milliseconds > 6.milliseconds } assertTrue { 5.milliseconds <= 6.milliseconds } assertTrue { 2.hours == 120.minutes } assertTrue { 2.hours >= 120.minutes } assertTrue { 2.hours <= 120.minutes } } @Test @SmallTest fun absolutes() { val duration = 2.years assertEquals( (2 * 365.25 * 24 * 60 * 60 * 1000 * 1000 * 1000).toLong(), duration.inNanoseconds ) assertEquals(2 * 365.25 * 24 * 60 * 60 * 1000 * 1000, duration.inMicroseconds) assertEquals(2 * 365.25 * 24 * 60 * 60 * 1000, duration.inMilliseconds) assertEquals(2 * 365.25 * 24 * 60 * 60, duration.inSeconds) assertEquals(2 * 365.25 * 24 * 60, duration.inMinutes) assertEquals(2 * 365.25 * 24, duration.inHours) assertEquals(2 * 365.25, duration.inDays) assertEquals(2 * 365.25 / 7, duration.inWeeks) assertEquals(2 * 12.0, duration.inMonths) assertEquals(2.0, duration.inYears) } }
stripecardscan/src/test/java/com/stripe/android/stripecardscan/framework/time/DurationTest.kt
1397260383
package dwallet.core.bitcoin.script /** * Created by unsignedint8 on 8/22/17. * https://en.bitcoin.it/wiki/Script */ class Words { enum class Constants(val raw: Byte) { OP_0(0x00), OP_FALSE(OP_0.raw), NA_LOW(0x01), NA_HIGH(0x4b), OP_PUSHDATA1(0x4c), OP_PUSHDATA2(0x4d), OP_PUSHDATA4(0x4e), OP_1NEGATE(0x4f), OP_1(0x51), OP_TRUE(OP_1.raw), OP_2(0x52), OP_3(0x53), OP_4(0x54), OP_5(0x55), OP_6(0x56), OP_7(0x57), OP_8(0x58), OP_9(0x59), OP_10(0x5a), OP_11(0x5b), OP_12(0x5c), OP_13(0x5d), OP_14(0x5e), OP_15(0x5f), OP_16(0x60), } enum class Flow(val raw: Byte) { OP_NOP(0x61), OP_IF(0x63), OP_NOTIF(0x64), OP_ELSE(0x67), OP_ENDIF(0x68), OP_VERIFY(0x69), OP_RETURN(0x6a), } enum class Stack(val raw: Byte) { OP_TOALTSTACK(0x6b), OP_FROMALTSTACK(0x6c), OP_IFDUP(0x73), OP_DEPTH(0x74), OP_DROP(0x75), OP_DUP(0x76), OP_NIP(0x77), OP_OVER(0x78), OP_PICK(0x79), OP_ROLL(0x7a), OP_ROT(0x7b), OP_SWAP(0x7c), OP_TUCK(0x7d), OP_2DROP(0x6d), OP_2DUP(0x6e), OP_3DUP(0x6f), OP_2OVER(0x70), OP_2ROT(0x71), OP_2SWAP(0x72), } enum class Splice(val raw: Byte) { OP_SIZE(0x82.toByte()), } enum class Bitwise(val raw: Byte) { OP_EQUAL(0x87.toByte()), OP_EQUALVERIFY(0x88.toByte()), } enum class Arithmetic(val raw: Byte) { /** * Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output. * If any input value for any of these commands is longer than 4 bytes, the script must abort and fail. If any opcode marked as disabled is present in a script - it must also abort and fail. */ OP_1ADD(0x8b.toByte()), OP_1SUB(0x8c.toByte()), OP_NEGATE(0x8f.toByte()), OP_ABS(0x90.toByte()), OP_NOT(0x91.toByte()), OP_0NOTEQUAL(0x92.toByte()), OP_ADD(0x93.toByte()), OP_SUB(0x94.toByte()), OP_BOOLAND(0x9a.toByte()), OP_BOOLOR(0x9b.toByte()), OP_NUMEQUAL(0x9c.toByte()), OP_NUMEQUALVERIFY(0x9d.toByte()), OP_NUMNOTEQUAL(0x9e.toByte()), OP_LESSTHAN(0x9f.toByte()), OP_GREATERTHAN(0xa0.toByte()), OP_LESSTHANOREQUAL(0xa1.toByte()), OP_GREATERTHANOREQUAL(0xa2.toByte()), OP_MIN(0xa3.toByte()), OP_MAX(0xa4.toByte()), OP_WITHIN(0xa5.toByte()), } enum class Crypto(val raw: Byte) { OP_RIPEMD160(0xa6.toByte()), OP_SHA1(0xa7.toByte()), OP_SHA256(0xa8.toByte()), OP_HASH160(0xa9.toByte()), OP_HASH256(0xaa.toByte()), OP_CODESEPARATOR(0xab.toByte()), OP_CHECKSIG(0xac.toByte()), OP_CHECKSIGVERIFY(0xad.toByte()), OP_CHECKMULTISIG(0xae.toByte()), OP_CHECKMULTISIGVERIFY(0xaf.toByte()), } enum class Locktime(val raw: Byte) { OP_CHECKLOCKTIMEVERIFY(0xb1.toByte()), OP_CHECKSEQUENCEVERIFY(0xb2.toByte()), } class Disabled { enum class Splice(val raw: Byte) { OP_CAT(0x7e), OP_SUBSTR(0x7f), OP_LEFT(0x80.toByte()), OP_RIGHT(0x81.toByte()), } enum class Bitwise(val raw: Byte) { OP_INVERT(0x83.toByte()), OP_AND(0x84.toByte()), OP_OR(0x85.toByte()), OP_XOR(0x86.toByte()), } enum class Arithmetic(val raw: Byte) { OP_2MUL(0x8d.toByte()), OP_2DIV(0x8e.toByte()), OP_MUL(0x95.toByte()), OP_DIV(0x96.toByte()), OP_MOD(0x97.toByte()), OP_LSHIFT(0x98.toByte()), OP_RSHIFT(0x99.toByte()), } enum class Pseudo(val raw: Byte) { /** * These words are used internally for assisting with transaction matching. They are invalid if used in actual scripts. */ OP_PUBKEYHASH(0xfd.toByte()), OP_PUBKEY(0xfe.toByte()), OP_INVALIDOPCODE(0xff.toByte()), } enum class Reserved(val raw: Byte) { /** * Any opcode not assigned is also reserved. Using an unassigned opcode makes the transaction invalid. */ OP_RESERVED(0x50.toByte()), OP_VER(0x62.toByte()), OP_VERIF(0x65.toByte()), OP_VERNOTIF(0x66.toByte()), OP_RESERVED1(0x89.toByte()), OP_RESERVED2(0x8a.toByte()), OP_NOP1(0xb0.toByte()), OP_NOP4(0xb3.toByte()), OP_NOP5(0xb4.toByte()), OP_NOP6(0xb5.toByte()), OP_NOP7(0xb6.toByte()), OP_NOP8(0xb7.toByte()), OP_NOP9(0xb8.toByte()), OP_NOP10(0xb9.toByte()), } } }
android/lib/src/main/java/dWallet/core/bitcoin/script/Words.kt
1155896193
package org.softeg.slartus.forpdaplus.core.repositories import org.softeg.slartus.forpdaplus.core.entities.UserProfile interface UserProfileRepository { suspend fun getUserProfile(userId: String): UserProfile? }
core/src/main/java/org/softeg/slartus/forpdaplus/core/repositories/UserProfileRepository.kt
2841504084
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.wear.compose.foundation import android.os.Build import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class CurvedScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_PATH) @get:Rule val testName = TestName() @Test fun curved_row_and_column() = verify_screenshot { curvedColumn(CurvedModifier.background(Color.Red)) { basicCurvedText("A") basicCurvedText("B") basicCurvedText("C") } basicCurvedText("D", CurvedModifier.background(Color.Green)) curvedColumn(CurvedModifier.background(Color.Blue)) { basicCurvedText("E") curvedRow { basicCurvedText("F") basicCurvedText("G") basicCurvedText("H") } basicCurvedText("I") } } @Test fun curved_backgrounds() = verify_screenshot { val size = 0.15f val rgb = listOf(Color.Red, Color.Green, Color.Blue) curvedColumn( CurvedModifier.size(sweepDegrees = 20f, thickness = 30.dp) .radialGradientBackground(rgb) ) { } curvedColumn( CurvedModifier.size(sweepDegrees = 20f, thickness = 30.dp) .radialGradientBackground( (0.5f - size) to Color.Red, 0.5f to Color.Blue, (0.5f + size) to Color.Red, ) ) { } curvedColumn( CurvedModifier.size(sweepDegrees = 20f, thickness = 30.dp) .angularGradientBackground(rgb) ) { } curvedColumn( CurvedModifier.size(sweepDegrees = 20f, thickness = 30.dp) .angularGradientBackground( (0.5f - size) to Color.Red, 0.5f to Color.Blue, (0.5f + size) to Color.Red, ) ) { } } @Test fun curved_padding() = verify_screenshot { basicCurvedText( "Text", CurvedModifier.background(Color.Red).padding(3.dp) .background(Color.Green).padding(angular = 5.dp) .background(Color.Blue).padding(radial = 4.dp) ) } @Test fun curved_plus_composables() = verify_screenshot { curvedRow(CurvedModifier.background(Color.Green)) { curvedComposable { Column { Box(Modifier.size(15.dp).background(Color.Red)) BasicText("Text") Box(Modifier.size(15.dp).background(Color.Red)) } } curvedComposable { Box(Modifier.size(15.dp).background(Color.Blue)) } } } @Test fun curved_alignment() = verify_screenshot { listOf( CurvedAlignment.Angular.Start, CurvedAlignment.Angular.Center, CurvedAlignment.Angular.End ).forEachIndexed { ix, align -> curvedColumn( CurvedModifier.angularSize(45f) .angularGradientBackground(listOf(Color.Red, Color.Green)), angularAlignment = align ) { curvedComposable { Box(Modifier.size(15.dp).background(Color.Blue)) } basicCurvedText(listOf("Start", "Center", "End")[ix]) } } curvedColumn( CurvedModifier.angularSize(45f) ) { listOf( CurvedAlignment.Radial.Inner, CurvedAlignment.Radial.Center, CurvedAlignment.Radial.Outer, ).forEachIndexed { ix, align -> curvedRow( CurvedModifier.size(45f, 20.dp) .radialGradientBackground(listOf(Color.Red, Color.Green)), radialAlignment = align ) { curvedComposable { Box(Modifier.size(10.dp).background(Color.Blue)) } basicCurvedText( listOf("Inner", "Center", "Outer")[ix], style = CurvedTextStyle(fontSize = 10.sp) ) } } } } @Test public fun layout_direction_rtl() = layout_direction(LayoutDirection.Rtl) @Test public fun layout_direction_ltr() = layout_direction(LayoutDirection.Ltr) private fun layout_direction(layoutDirection: LayoutDirection) = verify_composable_screenshot { CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) { CurvedLayout( Modifier.fillMaxSize(), angularDirection = CurvedDirection.Angular.Clockwise ) { curvedRow( CurvedModifier.background(Color.Green), angularDirection = CurvedDirection.Angular.Normal ) { layout_direction_block() } curvedComposable { Spacer(Modifier.size(10.dp)) } curvedRow( CurvedModifier.background(Color.Red), angularDirection = CurvedDirection.Angular.Clockwise ) { layout_direction_block() } } CurvedLayout( Modifier.fillMaxSize(), anchor = 90f, angularDirection = CurvedDirection.Angular.CounterClockwise ) { curvedRow( CurvedModifier.background(Color.Green), angularDirection = CurvedDirection.Angular.Reversed ) { layout_direction_block() } curvedComposable { Spacer(Modifier.size(10.dp)) } curvedRow( CurvedModifier.background(Color.Red), angularDirection = CurvedDirection.Angular.CounterClockwise ) { layout_direction_block() } } } } private fun CurvedScope.layout_direction_block() { basicCurvedText("A") curvedColumn { basicCurvedText("B") basicCurvedText("C") } curvedColumn(radialDirection = CurvedDirection.Radial.OutsideIn) { basicCurvedText("D") basicCurvedText("E") } curvedColumn(radialDirection = CurvedDirection.Radial.InsideOut) { basicCurvedText("F") basicCurvedText("G") } basicCurvedText("H") } private fun verify_screenshot(contentBuilder: CurvedScope.() -> Unit) = verify_composable_screenshot(content = { CurvedLayout( modifier = Modifier.fillMaxSize(), contentBuilder = contentBuilder ) }) private fun verify_composable_screenshot(content: @Composable BoxScope.() -> Unit) { rule.setContent { Box( modifier = Modifier.size(200.dp).background(Color.White).testTag(TEST_TAG), content = content ) } rule.onNodeWithTag(TEST_TAG) .captureToImage() .assertAgainstGolden(screenshotRule, testName.methodName) } } internal const val SCREENSHOT_GOLDEN_PATH = "wear/compose/foundation"
wear/compose/compose-foundation/src/androidAndroidTest/kotlin/androidx/wear/compose/foundation/CurvedScreenshotTest.kt
2338203440
package abi43_0_0.expo.modules.splashscreen import android.annotation.SuppressLint import android.content.Context import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout // this needs to stay for versioning to work /* ktlint-disable no-unused-imports */ import expo.modules.splashscreen.SplashScreenImageResizeMode /* ktlint-enable no-unused-imports */ @SuppressLint("ViewConstructor") class SplashScreenView( context: Context ) : RelativeLayout(context) { val imageView: ImageView = ImageView(context).also { view -> view.layoutParams = LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) } init { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) isClickable = true addView(imageView) } fun configureImageViewResizeMode(resizeMode: SplashScreenImageResizeMode) { imageView.scaleType = resizeMode.scaleType when (resizeMode) { SplashScreenImageResizeMode.NATIVE -> {} SplashScreenImageResizeMode.CONTAIN -> { imageView.adjustViewBounds = true } SplashScreenImageResizeMode.COVER -> {} } } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/splashscreen/SplashScreenView.kt
961715513
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Entity import com.vimeo.networking2.enums.SurveyQuestionType import com.vimeo.networking2.enums.asEnum /** * A representation of a user-facing survey question. Questions are expected to be presented to a user with * a series of multiple-choice responses to select as an answer. * * @param analyticsId The id that should be used when logging this [SurveyQuestion]. * @param resourceKey A globally unique identifier. * @param titleEmoji A unicode emoji character in “surrogate pair” representation (e.g. \uD83D\uDC4B). * @param question The survey question that the user should be asked. This string will be localized. * @param rawType The type of the survey question. See [SurveyQuestion.type]. * @param responseChoices A list of [SurveyResponseChoices][SurveyResponseChoice] to present to a user as valid * answers to the question. The order of this list will be randomized by the Vimeo api. * */ @JsonClass(generateAdapter = true) data class SurveyQuestion( @Json(name = "analytics_id") val analyticsId: String? = null, @Json(name = "resource_key") val resourceKey: String? = null, @Json(name = "title_emoji") val titleEmoji: String? = null, @Json(name = "title") val question: String? = null, @Json(name = "type") val rawType: String? = null, @Json(name = "answers") val responseChoices: List<SurveyResponseChoice>? = null ) : Entity { override val identifier: String? = resourceKey } /** * @see SurveyQuestionType * @see SurveyQuestion.rawType */ val SurveyQuestion.type: SurveyQuestionType get() = rawType.asEnum(SurveyQuestionType.UNKNOWN)
models/src/main/java/com/vimeo/networking2/SurveyQuestion.kt
3678855573
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.journeytests import batect.journeytests.testutils.ApplicationRunner import batect.journeytests.testutils.itCleansUpAllContainersItCreates import batect.journeytests.testutils.itCleansUpAllNetworksItCreates import batect.testutils.createForGroup import batect.testutils.on import batect.testutils.runBeforeGroup import batect.testutils.withPlatformSpecificLineSeparator import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.containsSubstring import com.natpryce.hamkrest.equalTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object NonStandardConfigurationFileNameTest : Spek({ describe("a configuration file with a non-standard name") { on("listing available tasks") { val runner by createForGroup { ApplicationRunner("non-standard-name") } val result by runBeforeGroup { runner.runApplication(listOf("-f", "another-name.yml", "--list-tasks")) } it("prints a list of all available tasks") { assertThat(result.output, containsSubstring(""" |- task-1 |- task-2 |- task-3 """.trimMargin().withPlatformSpecificLineSeparator())) } it("returns a zero exit code") { assertThat(result.exitCode, equalTo(0)) } } on("running a task") { val runner by createForGroup { ApplicationRunner("non-standard-name") } val result by runBeforeGroup { runner.runApplication(listOf("-f", "another-name.yml", "task-1")) } it("prints the output of the task ") { assertThat(result.output, containsSubstring("This is some output from task 1\r\n")) } it("returns the exit code from the task") { assertThat(result.exitCode, equalTo(123)) } itCleansUpAllContainersItCreates { result } itCleansUpAllNetworksItCreates { result } } } })
app/src/journeyTest/kotlin/batect/journeytests/NonStandardConfigurationFileNameTest.kt
3794839716
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.benchmark import androidx.compose.testutils.benchmark.ComposeBenchmarkRule import androidx.compose.testutils.benchmark.benchmarkDrawPerf import androidx.compose.testutils.benchmark.benchmarkFirstCompose import androidx.compose.testutils.benchmark.benchmarkFirstDraw import androidx.compose.testutils.benchmark.benchmarkFirstLayout import androidx.compose.testutils.benchmark.benchmarkFirstMeasure import androidx.compose.testutils.benchmark.benchmarkLayoutPerf import androidx.compose.testutils.benchmark.toggleStateBenchmarkDraw import androidx.compose.testutils.benchmark.toggleStateBenchmarkLayout import androidx.compose.testutils.benchmark.toggleStateBenchmarkMeasure import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @LargeTest @RunWith(AndroidJUnit4::class) class ScrollerBenchmark { @get:Rule val benchmarkRule = ComposeBenchmarkRule() private val scrollerCaseFactory = { ScrollerTestCase() } @Test fun first_compose() { benchmarkRule.benchmarkFirstCompose(scrollerCaseFactory) } @Test fun first_measure() { benchmarkRule.benchmarkFirstMeasure(scrollerCaseFactory) } @Test fun first_layout() { benchmarkRule.benchmarkFirstLayout(scrollerCaseFactory) } @Test fun first_draw() { benchmarkRule.benchmarkFirstDraw(scrollerCaseFactory) } @Test fun changeScroll_measure() { benchmarkRule.toggleStateBenchmarkMeasure( scrollerCaseFactory, toggleCausesRecompose = false ) } @Test fun changeScroll_layout() { benchmarkRule.toggleStateBenchmarkLayout( scrollerCaseFactory, toggleCausesRecompose = false ) } @Test fun changeScroll_draw() { benchmarkRule.toggleStateBenchmarkDraw( scrollerCaseFactory, toggleCausesRecompose = false ) } @Test fun layout() { benchmarkRule.benchmarkLayoutPerf(scrollerCaseFactory) } @Test fun draw() { benchmarkRule.benchmarkDrawPerf(scrollerCaseFactory) } }
compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/ScrollerBenchmark.kt
3644345679
package com.simplemobiletools.commons.views import android.content.Context import android.content.res.ColorStateList import android.util.AttributeSet import com.google.android.material.textfield.TextInputLayout import com.simplemobiletools.commons.extensions.adjustAlpha import com.simplemobiletools.commons.extensions.value import com.simplemobiletools.commons.helpers.HIGHER_ALPHA import com.simplemobiletools.commons.helpers.MEDIUM_ALPHA class MyTextInputLayout : TextInputLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) // we need to use reflection to make some colors work well fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) { try { editText!!.setTextColor(textColor) editText!!.backgroundTintList = ColorStateList.valueOf(accentColor) val hintColor = if (editText!!.value.isEmpty()) textColor.adjustAlpha(HIGHER_ALPHA) else textColor val defaultTextColor = TextInputLayout::class.java.getDeclaredField("defaultHintTextColor") defaultTextColor.isAccessible = true defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(hintColor))) val focusedTextColor = TextInputLayout::class.java.getDeclaredField("focusedTextColor") focusedTextColor.isAccessible = true focusedTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(accentColor))) val defaultHintTextColor = textColor.adjustAlpha(MEDIUM_ALPHA) val boxColorState = ColorStateList( arrayOf( intArrayOf(android.R.attr.state_active), intArrayOf(android.R.attr.state_focused) ), intArrayOf( defaultHintTextColor, accentColor ) ) setBoxStrokeColorStateList(boxColorState) defaultTextColor.set(this, ColorStateList(arrayOf(intArrayOf(0)), intArrayOf(defaultHintTextColor))) } catch (e: Exception) { } } }
commons/src/main/kotlin/com/simplemobiletools/commons/views/MyTextInputLayout.kt
3798831488
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.samples import androidx.annotation.Sampled import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TransformedText @Sampled fun passwordFilter(text: AnnotatedString): TransformedText { return TransformedText( AnnotatedString("*".repeat(text.text.length)), /** * [OffsetMapping.Identity] is a predefined [OffsetMapping] that can be used for the * transformation that does not change the character count. */ OffsetMapping.Identity ) } @Sampled fun creditCardFilter(text: AnnotatedString): TransformedText { // Making XXXX-XXXX-XXXX-XXXX string. val trimmed = if (text.text.length >= 16) text.text.substring(0..15) else text.text var out = "" for (i in trimmed.indices) { out += trimmed[i] if (i % 4 == 3 && i != 15) out += "-" } /** * The offset translator should ignore the hyphen characters, so conversion from * original offset to transformed text works like * - The 4th char of the original text is 5th char in the transformed text. * - The 13th char of the original text is 15th char in the transformed text. * Similarly, the reverse conversion works like * - The 5th char of the transformed text is 4th char in the original text. * - The 12th char of the transformed text is 10th char in the original text. */ val creditCardOffsetTranslator = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int { if (offset <= 3) return offset if (offset <= 7) return offset + 1 if (offset <= 11) return offset + 2 if (offset <= 16) return offset + 3 return 19 } override fun transformedToOriginal(offset: Int): Int { if (offset <= 4) return offset if (offset <= 9) return offset - 1 if (offset <= 14) return offset - 2 if (offset <= 19) return offset - 3 return 16 } } return TransformedText(AnnotatedString(out), creditCardOffsetTranslator) }
compose/ui/ui-text/samples/src/main/java/androidx/compose/ui/text/samples/VisualTransformationSamples.kt
3993130900
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft.listeners import com.demonwav.statcraft.StatCraft import com.demonwav.statcraft.querydsl.QOnFire import org.bukkit.ChatColor import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.EventPriority import org.bukkit.event.Listener import org.bukkit.event.entity.EntityCombustByBlockEvent import org.bukkit.event.entity.EntityCombustByEntityEvent import org.bukkit.event.entity.EntityCombustEvent import org.bukkit.event.entity.EntityDamageEvent import org.bukkit.potion.PotionEffectType import java.util.HashMap import java.util.UUID class OnFireListener(private val plugin: StatCraft) : Listener { private val lastSource = HashMap<UUID, String>() @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onFire(event: EntityDamageEvent) { if (event.entity is Player) { val cause = event.cause if (cause == EntityDamageEvent.DamageCause.FIRE_TICK) { val uuid = event.entity.uniqueId val worldName = event.entity.world.name val source = lastSource[uuid] plugin.threadManager.schedule<QOnFire>( uuid, worldName, { o, clause, id, worldId -> clause.columns(o.id, o.worldId, o.source, o.time).values(id, worldId, source, 1).execute() }, { o, clause, id, worldId -> clause.where(o.id.eq(id), o.worldId.eq(worldId), o.source.eq(source)).set(o.time, o.time.add(1)).execute() } ) } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onCombust(event: EntityCombustEvent) { if (!plugin.config.stats.onFireAnnounce) { return } if (event.entity is Player) { val uuid = event.entity.uniqueId if (System.currentTimeMillis() / 1000 - plugin.getLastFireTime(uuid) > 60) { val giveWarning = (event.entity as Player).activePotionEffects.any { it.type == PotionEffectType.FIRE_RESISTANCE } if (giveWarning) { event.entity.server.broadcastMessage( ChatColor.RED.toString() + plugin.config.stats.onFireAnnounceMessage.replace( "~".toRegex(), (event.entity as Player).displayName + ChatColor.RED) ) plugin.setLastFireTime(uuid, (System.currentTimeMillis() / 1000).toInt()) } } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onCombustByBlock(event: EntityCombustByBlockEvent) { if (event.entity is Player) { val player = event.entity as Player lastSource[player.uniqueId] = "BLOCK" } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) fun onCombustByEntity(event: EntityCombustByEntityEvent) { if (event.entity is Player) { val player = event.entity as Player if (event.combuster is Player) { val id = plugin.databaseManager.getPlayerId(event.combuster.uniqueId) ?: return lastSource.put(player.uniqueId, id.toString()) } else { lastSource.put(player.uniqueId, event.combuster.name) } } } }
src/main/kotlin/com/demonwav/statcraft/listeners/OnFireListener.kt
3574921058
package li.klass.bezahl.scanner import org.joda.time.DateTime class DateTimeProvider { fun now(): DateTime { return DateTime() } }
app/src/main/java/li/klass/bezahl/scanner/DateTimeProvider.kt
2110957520
package one.codehz.container import android.app.Activity import android.app.ActivityManager import android.app.ActivityOptions import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Bundle import android.os.Handler import android.support.design.widget.CollapsingToolbarLayout import android.support.design.widget.TabLayout import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.graphics.Palette import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ImageView import com.lody.virtual.os.VUserHandle import one.codehz.container.base.BaseActivity import one.codehz.container.ext.get import one.codehz.container.ext.setBackground import one.codehz.container.ext.systemService import one.codehz.container.ext.virtualCore import one.codehz.container.fragment.BasicDetailFragment import one.codehz.container.fragment.ComponentDetailFragment import one.codehz.container.models.AppModel class DetailActivity : BaseActivity(R.layout.application_detail) { companion object { val RESULT_DELETE_APK = 1 val REQUEST_USER = 0 val REQUEST_USER_FOR_SHORTCUT = 1 fun launch(context: Activity, appModel: AppModel, iconView: View, startFn: (Intent, Bundle) -> Unit) { startFn(Intent(context, DetailActivity::class.java).apply { action = Intent.ACTION_VIEW data = Uri.Builder().scheme("container").authority("detail").appendPath(appModel.packageName).build() }, ActivityOptions.makeSceneTransitionAnimation(context, iconView, "app_icon").toBundle()) } } val package_name: String by lazy { intent.data.path.substring(1) } val model by lazy { AppModel(this, virtualCore.findApp(package_name)) } val iconView by lazy<ImageView> { this[R.id.icon] } val viewPager by lazy<ViewPager> { this[R.id.viewPager] } val tabLayout by lazy<TabLayout> { this[R.id.tabs] } val collapsingToolbar by lazy<CollapsingToolbarLayout> { this[R.id.collapsing_toolbar] } var bgcolor = 0 val handler = Handler() inner class DetailPagerAdapter : FragmentPagerAdapter(supportFragmentManager) { override fun getItem(position: Int) = when (position) { 0 -> BasicDetailFragment(model) { it.setBackground(bgcolor) it.show() } 1 -> ComponentDetailFragment(model) { it.setBackground(bgcolor) it.show() } else -> throw IllegalArgumentException() } override fun getPageTitle(position: Int) = when (position) { 0 -> getString(R.string.basic_info)!! 1 -> getString(R.string.component_filter)!! else -> throw IllegalArgumentException() } override fun getCount() = 2 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setResult(Activity.RESULT_CANCELED) postponeEnterTransition() supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) } iconView.setImageDrawable(model.icon) Palette.from(model.icon.bitmap).apply { maximumColorCount(1) }.generate { palette -> try { val (main_color) = palette.swatches val dark_color = Color.HSVToColor(floatArrayOf(0f, 0f, 0f).apply { Color.colorToHSV(main_color.rgb, this) }.apply { this[2] *= 0.8f }) window.statusBarColor = dark_color window.navigationBarColor = dark_color bgcolor = dark_color collapsingToolbar.background = ColorDrawable(main_color.rgb) setTaskDescription(ActivityManager.TaskDescription(getString(R.string.task_detail_prefix, model.name), model.icon.bitmap, dark_color)) } catch (e: Exception) { e.printStackTrace() } finally { startPostponedEnterTransition() } } tabLayout.setupWithViewPager(viewPager) with(viewPager) { adapter = DetailPagerAdapter() } collapsingToolbar.title = model.name } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.detail_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { finishAfterTransition() true } R.id.run -> { LoadingActivity.launch(this, model, VUserHandle.USER_OWNER, iconView) true } R.id.run_as -> { startActivityForResult(Intent(this, UserSelectorActivity::class.java), REQUEST_USER) true } R.id.uninstall -> { setResult(RESULT_DELETE_APK, intent) finishAfterTransition() true } R.id.send_to_desktop -> { startActivityForResult(Intent(this, UserSelectorActivity::class.java), REQUEST_USER_FOR_SHORTCUT) true } else -> false } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { REQUEST_USER -> if (resultCode == Activity.RESULT_OK) { data!! handler.post { LoadingActivity.launch(this, model, data.getIntExtra(UserSelectorActivity.KEY_USER_ID, 0), iconView) } } REQUEST_USER_FOR_SHORTCUT -> if (resultCode == Activity.RESULT_OK) { data!! sendBroadcast(Intent("com.android.launcher.action.INSTALL_SHORTCUT").apply { val size = systemService<ActivityManager>(Context.ACTIVITY_SERVICE).launcherLargeIconSize val scaledIcon = Bitmap.createScaledBitmap(model.icon.bitmap, size, size, false) putExtra(Intent.EXTRA_SHORTCUT_INTENT, Intent(this@DetailActivity, VLoadingActivity::class.java).apply { this.data = Uri.Builder().scheme("container").authority("launch").appendPath(model.packageName).fragment(data.getIntExtra(UserSelectorActivity.KEY_USER_ID, 0).toString()).build() }) putExtra(Intent.EXTRA_SHORTCUT_NAME, model.name) putExtra(Intent.EXTRA_SHORTCUT_ICON, scaledIcon) putExtra("duplicate", false) }) } } } }
app/src/main/java/one/codehz/container/DetailActivity.kt
3415461857
/* * Copyright (C) 2017-2019 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 import android.graphics.drawable.Drawable import io.vavr.control.Try import org.andstatus.app.graphics.CacheName import org.andstatus.app.graphics.CachedImage import org.andstatus.app.graphics.ImageCaches import org.andstatus.app.util.TryUtils class DrawableLoader(mediaFile: MediaFile, private val cacheName: CacheName) : AbstractImageLoader(mediaFile, "-asynd") { fun load(): Try<Drawable> { return TryUtils.ofNullable(ImageCaches.loadAndGetImage(cacheName, mediaFile)) .map { obj: CachedImage -> obj.getDrawable() } } }
app/src/main/kotlin/org/andstatus/app/data/DrawableLoader.kt
259373803
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config import com.demonwav.mcdev.asset.PlatformAssets import com.intellij.json.JsonLanguage import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.fileTypes.ex.FileTypeIdentifiableByVirtualFile import com.intellij.openapi.vfs.VirtualFile object MixinConfigFileType : LanguageFileType(JsonLanguage.INSTANCE), FileTypeIdentifiableByVirtualFile { private val filenameRegex = "(^|\\.)mixins?(\\.[^.]+)*\\.json\$".toRegex() // Dynamic file type detection is sadly needed as we're overriding the built-in json file type. // Simply using an extension pattern is not sufficient as there is no way to bump the version to tell // the cache that the pattern has changed, as it now has, without changing the file type name. // See https://www.plugin-dev.com/intellij/custom-language/file-type-detection/#guidelines override fun isMyFileType(file: VirtualFile) = file.name.contains(filenameRegex) override fun getName() = "Mixin Configuration" override fun getDescription() = "Mixin configuration" override fun getDefaultExtension() = "" override fun getIcon() = PlatformAssets.MIXIN_ICON }
src/main/kotlin/platform/mixin/config/MixinConfigFileType.kt
4076499178
package com.teo.ttasks import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty open class LateInit<T : Any>( private val getter: FieldHolder<T>.() -> T = { field }, private val setter: FieldHolder<T>.(T) -> Unit = { field = it } ) : ReadWriteProperty<Any?, T> { private val fieldHolder = FieldHolder<T>() override fun getValue(thisRef: Any?, property: KProperty<*>) = fieldHolder.getter() override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = fieldHolder.setter(value) class FieldHolder<T : Any> { lateinit var field: T /** Check if the backing field has been initialized. */ fun isInitialized() = ::field.isInitialized } }
t-tasks/src/main/java/com/teo/ttasks/LateInit.kt
3169939692
package org.jetbrains.haskell.debugger.config import com.intellij.openapi.options.Configurable import javax.swing.JComponent import com.intellij.openapi.ui.ComboBox import javax.swing.DefaultComboBoxModel import com.intellij.ui.DocumentAdapter import javax.swing.event.DocumentEvent import java.awt.event.ItemListener import java.awt.event.ItemEvent import javax.swing.JPanel import java.awt.GridBagLayout import org.jetbrains.haskell.util.gridBagConstraints import java.awt.Insets import javax.swing.JLabel import org.jetbrains.haskell.util.setConstraints import java.awt.GridBagConstraints import javax.swing.Box import javax.swing.JCheckBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import org.jetbrains.haskell.debugger.utils.UIUtils import javax.swing.JButton import javax.swing.AbstractAction import java.awt.event.ActionEvent /** * Manages debugger settings. Creates additional section in IDEA Settings and tracks changes appeared there to obtain * debugger settings. The settings are as follows: * 1) user can select what debugger he would like to use * 2) user can switch ':trace' command off * * @author Habibullin Marat */ public class DebuggerConfigurable() : Configurable { companion object { private val ITEM_GHCI = "GHCi" private val ITEM_REMOTE = "Remote" private val TRACE_CHECKBOX_LABEL = "Switch off ':trace' command" private val PRINT_DEBUG_OUTPUT_LABEL = "Print debugger output to stdout" } private val selectDebuggerComboBox: ComboBox = ComboBox(DefaultComboBoxModel(arrayOf(ITEM_GHCI, ITEM_REMOTE))) private val remoteDebuggerPathField: TextFieldWithBrowseButton = TextFieldWithBrowseButton() private val traceSwitchOffCheckBox: JCheckBox = JCheckBox(TRACE_CHECKBOX_LABEL, false) private val printDebugOutputCheckBox: JCheckBox = JCheckBox(PRINT_DEBUG_OUTPUT_LABEL, false) private var isModified = false override fun getDisplayName(): String? = "Haskell debugger" override fun getHelpTopic(): String? = null /** * Creates UI for settings page */ override fun createComponent(): JComponent? { remoteDebuggerPathField.addBrowseFolderListener( "Select remote debugger executable", null, null, FileChooserDescriptorFactory.createSingleLocalFileDescriptor()) val itemListener = object : ItemListener { override fun itemStateChanged(e: ItemEvent) { isModified = true } } val docListener : DocumentAdapter = object : DocumentAdapter() { override fun textChanged(e: DocumentEvent?) { isModified = true } }; selectDebuggerComboBox.addItemListener(itemListener) remoteDebuggerPathField.getTextField()!!.getDocument()!!.addDocumentListener(docListener) traceSwitchOffCheckBox.addItemListener(itemListener) printDebugOutputCheckBox.addItemListener(itemListener) val result = JPanel(GridBagLayout()) UIUtils.addLabeledControl(result, 0, "Prefered debugger:", selectDebuggerComboBox, false) UIUtils.addLabeledControl(result, 1, "Remote debugger path:", remoteDebuggerPathField) result.add(traceSwitchOffCheckBox, gridBagConstraints { anchor = GridBagConstraints.LINE_START gridx = 0; gridwidth = 2; gridy = 2; }) result.add(printDebugOutputCheckBox, gridBagConstraints { anchor = GridBagConstraints.LINE_START gridx = 0; gridwidth = 2; gridy = 3; }) result.add(JPanel(), gridBagConstraints { gridx = 0; gridy = 4; weighty = 10.0 }) return result } override fun isModified(): Boolean = isModified /** * Actions performed when user press "Apply" button. Here we obtain settings and need to set them in some global * debug settings object */ override fun apply() { val ghciSelected = selectDebuggerComboBox.getSelectedIndex() == 0 val remotePath = remoteDebuggerPathField.getTextField()!!.getText() val traceSwitchedOff = traceSwitchOffCheckBox.isSelected() val printDebugOutput = printDebugOutputCheckBox.isSelected() val state = HaskellDebugSettings.getInstance().getState() state.debuggerType = if (ghciSelected) HaskellDebugSettings.Companion.DebuggerType.GHCI else HaskellDebugSettings.Companion.DebuggerType.REMOTE state.remoteDebuggerPath = remotePath state.traceOff = traceSwitchedOff state.printDebugOutput = printDebugOutput isModified = false } /** * Actions performed when user press "Reset" button. Here we need to reset appropriate properties in global * debug settings object */ override fun reset() { val state = HaskellDebugSettings.getInstance().getState() selectDebuggerComboBox.setSelectedIndex(if (state.debuggerType == HaskellDebugSettings.Companion.DebuggerType.GHCI) 0 else 1) traceSwitchOffCheckBox.setSelected(state.traceOff) remoteDebuggerPathField.getTextField()!!.setText(state.remoteDebuggerPath) printDebugOutputCheckBox.setSelected(state.printDebugOutput) isModified = false } override fun disposeUIResources() {} }
plugin/src/org/jetbrains/haskell/debugger/config/DebuggerConfigurable.kt
338255303
// Copyright (c) 2017, Daniel Andersen ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Rest controller responsible for handling product labels. */ package dk.etiktak.backend.controller.rest import dk.etiktak.backend.controller.rest.json.add import dk.etiktak.backend.model.recommendation.RecommendationScore import dk.etiktak.backend.model.user.Client import dk.etiktak.backend.security.CurrentlyLoggedClient import dk.etiktak.backend.service.client.ClientService import dk.etiktak.backend.service.company.CompanyService import dk.etiktak.backend.service.infochannel.InfoChannelService import dk.etiktak.backend.service.product.ProductCategoryService import dk.etiktak.backend.service.product.ProductLabelService import dk.etiktak.backend.service.product.ProductService import dk.etiktak.backend.service.product.ProductTagService import dk.etiktak.backend.service.recommendation.RecommendationService import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* import java.util.* @RestController @RequestMapping("/service/recommendation") class RecommendationRestController @Autowired constructor( private val recommendationService: RecommendationService, private val productService: ProductService, private val productCategoryService: ProductCategoryService, private val productLabelService: ProductLabelService, private val productTagService: ProductTagService, private val companyService: CompanyService, private val infoChannelService: InfoChannelService, private val clientService: ClientService) : BaseRestController() { @RequestMapping(value = "/", method = arrayOf(RequestMethod.GET)) fun getRecommendation( @CurrentlyLoggedClient loggedClient: Client, @RequestParam productUuid: String): HashMap<String, Any> { val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client") val product = productService.getProductByUuid(productUuid) ?: return notFoundMap("Product") val recommendations = recommendationService.getRecommendations(client, product) return okMap().add(recommendations) } @RequestMapping(value = "/create/", method = arrayOf(RequestMethod.POST)) fun createRecommendation( @CurrentlyLoggedClient loggedClient: Client, @RequestParam infoChannelUuid: String, @RequestParam summary: String, @RequestParam score: String, @RequestParam(required = false) infoSourceReferenceUrlList: List<String>, @RequestParam(required = false) productUuid: String? = null, @RequestParam(required = false) productCategoryUuid: String? = null, @RequestParam(required = false) productLabelUuid: String? = null, @RequestParam(required = false) productTagUuid: String? = null, @RequestParam(required = false) companyUuid: String? = null): HashMap<String, Any> { val client = clientService.getByUuid(loggedClient.uuid) ?: return notFoundMap("Client") val infoChannel = infoChannelService.getInfoChannelByUuid(infoChannelUuid) ?: return notFoundMap("Info channel") val scoreType = RecommendationScore.valueOf(score) // Create product recommendation productUuid?.let { val product = productService.getProductByUuid(productUuid) ?: return notFoundMap("Product") val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, product, infoSourceReferenceUrlList) return okMap().add(recommendation) } // Create product category recommendation productCategoryUuid?.let { val productCategory = productCategoryService.getProductCategoryByUuid(productCategoryUuid) ?: return notFoundMap("Product category") val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productCategory, infoSourceReferenceUrlList) return okMap().add(recommendation) } // Create product label recommendation productLabelUuid?.let { val productLabel = productLabelService.getProductLabelByUuid(productLabelUuid) ?: return notFoundMap("Product label") val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productLabel, infoSourceReferenceUrlList) return okMap().add(recommendation) } // Create product tag recommendation productTagUuid?.let { val productTag = productTagService.getProductTagByUuid(productTagUuid) ?: return notFoundMap("Product tag") val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, productTag, infoSourceReferenceUrlList) return okMap().add(recommendation) } // Create company recommendation companyUuid?.let { val company = companyService.getCompanyByUuid(companyUuid) ?: return notFoundMap("Company") val recommendation = recommendationService.createRecommendation(client, infoChannel, summary, scoreType, company, infoSourceReferenceUrlList) return okMap().add(recommendation) } return illegalInvocationMap("None of the required parameters set") } }
src/main/kotlin/dk/etiktak/backend/controller/rest/RecommendationRestController.kt
1793981239
/** * 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.wall.dto import com.google.gson.annotations.SerializedName import kotlin.String enum class WallGetCommentsExtendedSort( val value: String ) { @SerializedName("asc") CHRONOLOGICAL("asc"), @SerializedName("desc") REVERSE_CHRONOLOGICAL("desc"); }
api/src/main/java/com/vk/sdk/api/wall/dto/WallGetCommentsExtendedSort.kt
3008443875
package commons import ch.qos.logback.classic.Level import ch.qos.logback.classic.Logger import ch.qos.logback.classic.PatternLayout import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.ConsoleAppender import ch.qos.logback.core.Context import ch.qos.logback.core.FileAppender import org.slf4j.LoggerFactory import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths object Configuration { val directory: Path = Paths.get(System.getProperty("user.home"), ".config", "nsync") init { if (!Files.exists(directory)) { Files.createDirectory(directory) } } } fun configureLog(confDir: Path, verbose: Boolean, logLevel: String) { val level: Level? = Level.valueOf(logLevel.toUpperCase()) val logCtx = LoggerFactory.getILoggerFactory() val log = logCtx.getLogger(Logger.ROOT_LOGGER_NAME) as Logger log.detachAndStopAllAppenders() log.isAdditive = false log.level = level ?: Level.ALL val layout = PatternLayout() layout.pattern = "%date{yyyy-MM-dd'T'HH:mm:ss.SSS'Z', UTC} | %level | %thread | %logger{15} | %msg %ex{3} %n" layout.context = logCtx as Context layout.start() if (verbose) { println("Log configured as verbose and level $logLevel") val logConsoleAppender = ConsoleAppender<ILoggingEvent>() logConsoleAppender.setLayout(layout) logConsoleAppender.context = logCtx logConsoleAppender.name = "console" logConsoleAppender.start() log.addAppender(logConsoleAppender) } else { val logFile = confDir.resolve("log").toString() println("Log configured as to file $logFile and level $logLevel") val fileConsoleAppender = FileAppender<ILoggingEvent>() fileConsoleAppender.setLayout(layout) fileConsoleAppender.isAppend = false fileConsoleAppender.context = logCtx fileConsoleAppender.name = "file" fileConsoleAppender.file = logFile fileConsoleAppender.start() log.addAppender(fileConsoleAppender) } }
src/main/kotlin/commons/Configuration.kt
714165001
package org.jetbrains.kotlinx.jupyter.libraries import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryDefinitionProducer import org.jetbrains.kotlinx.jupyter.api.libraries.LibraryResolutionRequest interface LibrariesProcessor { val requests: Collection<LibraryResolutionRequest> fun processNewLibraries(arg: String): List<LibraryDefinitionProducer> }
jupyter-lib/shared-compiler/src/main/kotlin/org/jetbrains/kotlinx/jupyter/libraries/LibrariesProcessor.kt
4033455234
package ktx.graphics import com.badlogic.gdx.Gdx import com.badlogic.gdx.backends.lwjgl.LwjglNativesLoader import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.glutils.FrameBuffer import com.badlogic.gdx.graphics.glutils.ShaderProgram import com.badlogic.gdx.math.Matrix4 import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.spy import com.nhaarman.mockitokotlin2.verify import org.junit.Assert.assertEquals import org.junit.Assert.assertSame import org.junit.Test import java.io.File /** * Tests general utilities related to libGDX graphics API. */ class GraphicsTest { @Test fun `should begin and end Batch`() { val batch = mock<Batch>() batch.use { verify(batch).begin() assertSame(batch, it) verify(batch, never()).end() } verify(batch).end() verify(batch, never()).projectionMatrix = any() } @Test fun `should set projection matrix`() { val batch = mock<Batch>() val matrix = Matrix4((0..15).map { it.toFloat() }.toFloatArray()) batch.use(matrix) { verify(batch).projectionMatrix = matrix verify(batch).begin() assertSame(batch, it) verify(batch, never()).end() } verify(batch).end() } @Test fun `should use Batch exactly once`() { val batch = mock<Batch>() val variable: Int batch.use { variable = 42 } assertEquals(42, variable) } @Test fun `should set projection matrix if a camera is passed`() { val batch = mock<Batch>() val camera = OrthographicCamera() batch.use(camera) { verify(batch).projectionMatrix = camera.combined verify(batch).begin() assertSame(batch, it) verify(batch, never()).end() } verify(batch).end() } @Test fun `should use Batch with camera exactly once`() { val batch = mock<Batch>() val variable: Int batch.use(OrthographicCamera()) { variable = 42 } assertEquals(42, variable) } @Test fun `should begin with provided projection matrix`() { val batch = mock<Batch>() val matrix = Matrix4(FloatArray(16) { it.toFloat() }) batch.begin(projectionMatrix = matrix) verify(batch).projectionMatrix = matrix verify(batch).begin() } @Test fun `should use Batch with projection matrix exactly once`() { val batch = mock<Batch>() val variable: Int batch.use(Matrix4()) { variable = 42 } assertEquals(42, variable) } @Test fun `should begin with provided camera combined matrix`() { val batch = mock<Batch>() val camera = OrthographicCamera() batch.begin(camera = camera) verify(batch).projectionMatrix = camera.combined verify(batch).begin() } @Test fun `should bind ShaderProgram`() { val shaderProgram = mock<ShaderProgram>() shaderProgram.use { verify(shaderProgram).bind() assertSame(shaderProgram, it) } } @Test fun `should use ShaderProgram exactly once`() { val shaderProgram = mock<ShaderProgram>() val variable: Int shaderProgram.use { variable = 42 } assertEquals(42, variable) } @Test fun `should begin and end FrameBuffer`() { val frameBuffer = mock<FrameBuffer>() frameBuffer.use { verify(frameBuffer).begin() assertSame(frameBuffer, it) verify(frameBuffer, never()).end() } verify(frameBuffer).end() } @Test fun `should use FrameBuffer exactly once`() { val frameBuffer = mock<FrameBuffer>() val variable: Int frameBuffer.use { variable = 42 } assertEquals(42, variable) } @Test fun `should take screenshot`() { LwjglNativesLoader.load() Gdx.gl = mock() Gdx.graphics = mock { on { backBufferHeight } doReturn 4 on { backBufferWidth } doReturn 4 } val fileHandle = spy(FileHandle(File.createTempFile("screenshot", ".png"))) takeScreenshot(fileHandle) verify(fileHandle).write(false) } }
graphics/src/test/kotlin/ktx/graphics/GraphicsTest.kt
1818434549
package com.google.firebase.quickstart.auth.kotlin import android.app.Activity import android.os.Bundle import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class MultiFactorActivity : Activity() { // [START declare_auth] private lateinit var auth: FirebaseAuth // [END declare_auth] public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // [START initialize_auth] // Initialize Firebase Auth auth = Firebase.auth // [END initialize_auth] } // [START on_start_check_user] public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) } // [END on_start_check_user] private fun sendEmailVerification() { // [START send_email_verification] val user = auth.currentUser!! user.sendEmailVerification() .addOnCompleteListener(this) { task -> // Email verification sent } // [END send_email_verification] } private fun reload() { } private fun updateUI(user: FirebaseUser?) { } }
auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MultiFactorActivity.kt
2999635646
package com.github.telegram_bots.channels_feed.tg.service import com.github.telegram_bots.channels_feed.tg.domain.Channel import io.reactivex.Completable import io.reactivex.Flowable import org.davidmoten.rx.jdbc.Database import org.springframework.stereotype.Repository @Repository class ChannelRepository(private val db: Database) { fun update(channel: Channel): Completable { return db .update( """ | UPDATE channels | SET telegram_id = ?, hash = ?, url = ?, name = ?, created_at = to_timestamp(?), | last_post_id = CASE WHEN ? > last_post_id OR last_post_id IS NULL THEN ? ELSE last_post_id END | WHERE id = ? """.trimMargin() ) .parameters( channel.telegramId, channel.hash, channel.url, channel.name, channel.createdAt.epochSecond, channel.lastPostId, channel.lastPostId, channel.id ) .complete() } fun list(): Flowable<Channel> { return db.select("""SELECT * FROM channels ORDER BY last_post_id DESC""").get(::Channel) } fun listNeedToUpdate(): Flowable<Channel> { return db .select( """ | SELECT * FROM channels | WHERE extract(DAY FROM created_at) = extract(DAY FROM now()) | AND extract(MONTH FROM created_at) != extract(MONTH FROM now()) """.trimMargin() ) .get(::Channel) } }
tg/src/main/kotlin/com/github/telegram_bots/channels_feed/tg/service/ChannelRepository.kt
2396166012
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.`as`.oss.policies.impl import android.content.Context import com.google.android.`as`.oss.policies.api.PolicyMap import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Suppress("EXPERIMENTAL_API_USAGE") @Module @InstallIn(SingletonComponent::class) internal object ProdPoliciesModule { @Provides @Singleton @JvmStatic fun providePolicies(@ApplicationContext context: Context): PolicyMap { return AssetLoader.loadPolicyMapFromAssets( context, "AmbientContextPolicy_FederatedCompute_ASI_PROD.binarypb", "AutofillPolicy_FederatedCompute_ASI_PROD.binarypb", "SafecommsPolicy_FederatedCompute_ASI_PROD.binarypb", "LiveTranslatePolicy_FederatedCompute_ASI_PROD.binarypb", "SmartSelectAnalyticsPolicy_FederatedCompute_ASI_PROD.binarypb", "SmartSelectLearningPolicy_FederatedCompute_ASI_PROD.binarypb", "ContentCapturePerformanceDataPolicy_FederatedCompute_ASI_PROD.binarypb", "GPPServicePolicy_FederatedCompute_GPPS_PROD.binarypb", "NowPlayingUsagePolicy_FederatedCompute_ASI_PROD.binarypb", "PecanUsageEventPolicy_FederatedCompute_ASI_PROD.binarypb", "PecanScrollingEventPolicy_FederatedCompute_ASI_PROD.binarypb", "PecanLatencyAnalyticsEventPolicy_FederatedCompute_ASI_PROD.binarypb", "AppLaunchPredictionMetricsPolicy_FederatedCompute_ASI_PROD.binarypb", "PecanConversationFragmentEventPolicy_FederatedCompute_ASI_PROD.binarypb", "PecanConversationThreadEventPolicy_FederatedCompute_ASI_PROD.binarypb", "PecanMessageEventPolicy_FederatedCompute_ASI_PROD.binarypb", "SearchPolicy_FederatedCompute_ASI_PROD.binarypb", ) } }
src/com/google/android/as/oss/policies/impl/ProdPoliciesModule.kt
3522367384
package de.westnordost.streetcomplete object ApplicationConstants { const val NAME = "StreetComplete" const val USER_AGENT = NAME + " " + BuildConfig.VERSION_NAME const val QUESTTYPE_TAG_KEY = NAME + ":quest_type" const val MAX_DOWNLOADABLE_AREA_IN_SQKM = 12.0 const val MIN_DOWNLOADABLE_AREA_IN_SQKM = 0.1 const val DATABASE_NAME = "streetcomplete.db" const val QUEST_TILE_ZOOM = 16 const val NOTE_MIN_ZOOM = 15 /** a "best before" duration for quests. Quests will not be downloaded again for any tile * before the time expired */ const val REFRESH_QUESTS_AFTER = 3L * 24 * 60 * 60 * 1000 // 3 days in ms /** the duration after which quests (and quest meta data) will be deleted from the database if * unsolved and not refreshed in the meantime */ const val DELETE_UNSOLVED_QUESTS_AFTER = 14L * 24 * 60 * 60 * 1000 // 14 days in ms /** the max age of the undo history - one cannot undo changes older than X */ const val MAX_QUEST_UNDO_HISTORY_AGE = 24L * 60 * 60 * 1000 // 1 day in ms const val AVATARS_CACHE_DIRECTORY = "osm_user_avatars" const val SC_PHOTO_SERVICE_URL = "https://westnordost.de/streetcomplete/photo-upload/" // must have trailing / const val ATTACH_PHOTO_QUALITY = 80 const val ATTACH_PHOTO_MAXWIDTH = 1280 // WXGA const val ATTACH_PHOTO_MAXHEIGHT = 1280 // WXGA const val NOTIFICATIONS_CHANNEL_DOWNLOAD = "downloading" }
app/src/main/java/de/westnordost/streetcomplete/ApplicationConstants.kt
2160264573
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.test import com.intellij.configurationStore.SchemeManagerImpl import com.intellij.configurationStore.TestScheme import com.intellij.configurationStore.TestSchemesProcessor import com.intellij.openapi.components.RoamingType import com.intellij.util.xmlb.serialize import com.intellij.util.xmlb.toByteArray import org.eclipse.jgit.lib.Repository import org.hamcrest.CoreMatchers.equalTo import org.jetbrains.settingsRepository.ReadonlySource import org.jetbrains.settingsRepository.git.cloneBare import org.jetbrains.settingsRepository.git.commit import org.junit.Assert.assertThat import org.junit.Test import java.io.File class LoadTest : TestCase() { private val dirPath = "\$ROOT_CONFIG$/keymaps" private fun createSchemeManager(dirPath: String) = SchemeManagerImpl<TestScheme, TestScheme>(dirPath, TestSchemesProcessor(), RoamingType.PER_USER, provider, tempDirManager.newDirectory("schemes")) public Test fun `load scheme`() { val localScheme = TestScheme("local") val data = localScheme.serialize().toByteArray() provider.save("$dirPath/local.xml", data) val schemesManager = createSchemeManager(dirPath) schemesManager.loadSchemes() assertThat(schemesManager.getAllSchemes(), equalTo(listOf(localScheme))) } public Test fun `load scheme with the same names`() { val localScheme = TestScheme("local") val data = localScheme.serialize().toByteArray() provider.save("$dirPath/local.xml", data) provider.save("$dirPath/local2.xml", data) val schemesManager = createSchemeManager(dirPath) schemesManager.loadSchemes() assertThat(schemesManager.getAllSchemes(), equalTo(listOf(localScheme))) } public Test fun `load scheme from repo and read-only repo`() { val localScheme = TestScheme("local") provider.save("$dirPath/local.xml", localScheme.serialize().toByteArray()) val remoteScheme = TestScheme("remote") val remoteRepository = tempDirManager.createRepository() remoteRepository .add(remoteScheme.serialize().toByteArray(), "$dirPath/Mac OS X from RubyMine.xml") .commit("") remoteRepository.useAsReadOnlySource { val schemesManager = createSchemeManager(dirPath) schemesManager.loadSchemes() assertThat(schemesManager.getAllSchemes(), equalTo(listOf(remoteScheme, localScheme))) assertThat(schemesManager.isMetadataEditable(localScheme), equalTo(true)) assertThat(schemesManager.isMetadataEditable(remoteScheme), equalTo(false)) } } public Test fun `scheme overrides read-only`() { val schemeName = "Emacs" val localScheme = TestScheme(schemeName, "local") provider.save("$dirPath/$schemeName.xml", localScheme.serialize().toByteArray()) val remoteScheme = TestScheme(schemeName, "remote") val remoteRepository = tempDirManager.createRepository("remote") remoteRepository .add(remoteScheme.serialize().toByteArray(), "$dirPath/$schemeName.xml") .commit("") remoteRepository.useAsReadOnlySource { val schemesManager = createSchemeManager(dirPath) schemesManager.loadSchemes() assertThat(schemesManager.getAllSchemes(), equalTo(listOf(localScheme))) assertThat(schemesManager.isMetadataEditable(localScheme), equalTo(false)) } } inline fun Repository.useAsReadOnlySource(runnable: () -> Unit) { createAndRegisterReadOnlySource() try { runnable() } finally { icsManager.readOnlySourcesManager.setSources(emptyList()) } } fun Repository.createAndRegisterReadOnlySource(): ReadonlySource { val source = ReadonlySource(getWorkTree().getAbsolutePath()) assertThat(cloneBare(source.url!!, File(icsManager.readOnlySourcesManager.rootDir, source.path!!)).getObjectDatabase().exists(), equalTo(true)) icsManager.readOnlySourcesManager.setSources(listOf(source)) return source } }
plugins/settings-repository/testSrc/LoadTest.kt
2903216943
class Outer(val s: String) { inner class Inner { constructor(x: Int) { this.x = x } constructor(z: String) { x = z.length } val x: Int fun foo() = s } } fun main(args: Array<String>) { println(Outer("OK").Inner(42).foo()) println(Outer("OK").Inner("zzz").foo()) }
backend.native/tests/codegen/innerClass/noPrimaryConstructor.kt
3776494141
open class A(val result: String) { constructor(x: Int = 11, y: Int = 22, z: Int = 33) : this("$x$y$z") } class B() : A(y = 44) fun box(): String { val result = B().result if (result != "114433") return "fail: $result" return "OK" }
backend.native/tests/external/codegen/box/secondaryConstructors/callFromPrimaryWithNamedArgs.kt
691063752
package nl.sugcube.dirtyarrows.util import org.bukkit.entity.Arrow import org.bukkit.entity.Entity import org.bukkit.entity.EntityType import kotlin.math.sqrt /** * The diameter of the entity based on width and height. */ val Entity.diameter: Double get() = sqrt(width * width + height * height) /** * Respawns an arrow in the same direction as this arrow. * * @return The spawned arrow. */ fun Arrow.respawnArrow(): Arrow { val landedArrow = this landedArrow.remove() return landedArrow.world.spawnEntity(landedArrow.location, EntityType.ARROW).apply { val createdArrow = this as Arrow createdArrow.velocity = landedArrow.velocity createdArrow.isCritical = landedArrow.isCritical createdArrow.pickupStatus = landedArrow.pickupStatus createdArrow.knockbackStrength = landedArrow.knockbackStrength createdArrow.fireTicks = landedArrow.fireTicks createdArrow.shooter = [email protected] } as Arrow }
src/main/kotlin/nl/sugcube/dirtyarrows/util/Entities.kt
556620161
package me.liuqingwen.android.projectviewpager import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v4.view.ViewPager import android.view.View import kotlinx.android.synthetic.main.layout_activity_main.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.* class MainActivity : AppCompatActivity(), AnkoLogger { companion object { const val PREFERENCE_NAME = "project_view_pager" private const val NO_PAGES_NEXT_TIME = "no_pages_next_time" } private val pages by lazy(LazyThreadSafetyMode.NONE) { arrayListOf(Page("4.1 Jelly Bean", this.getString(R.string.android_4), R.drawable.android4), Page("5.0 Lollipop", this.getString(R.string.android_5), R.drawable.android5), Page("6.0 Marshmallow", this.getString(R.string.android_6), R.drawable.android6), Page("7.0 Nougat", this.getString(R.string.android_7), R.drawable.android7), Page("8.0 Oreo", this.getString(R.string.android_8), R.drawable.android8)) } private val pagerAdapter by lazy(LazyThreadSafetyMode.NONE) { ViewPagerAdapter(this.supportFragmentManager, this.pages) } private val preference by lazy(LazyThreadSafetyMode.NONE) { this.getSharedPreferences(MainActivity.PREFERENCE_NAME, Context.MODE_PRIVATE) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.initUI() this.init() } private fun initUI() { this.checkBox.visibility = View.INVISIBLE this.imageButton.visibility = View.INVISIBLE } private fun init() { if (this.preference.getBoolean(MainActivity.NO_PAGES_NEXT_TIME, false)) { this.startActivity<AppActivity>() this.finish() return } this.viewPager.adapter = this.pagerAdapter this.layoutTabs.setupWithViewPager(this.viewPager) this.viewPager.addOnPageChangeListener(object:ViewPager.SimpleOnPageChangeListener(){ override fun onPageSelected(position: Int) { super.onPageSelected(position) if (position >= [email protected] - 1 && [email protected] != View.VISIBLE) { [email protected] = View.VISIBLE [email protected] = View.VISIBLE [email protected] { val noViewPager = [email protected] val editor = [email protected]() editor.putBoolean(MainActivity.NO_PAGES_NEXT_TIME, noViewPager) editor.apply() [email protected]<AppActivity>() [email protected]() } } } }) } }
ProjectViewPager/app/src/main/java/me/liuqingwen/android/projectviewpager/MainActivity.kt
3051050040
package com.msc.serverbrowser.data.insallationcandidates import com.msc.serverbrowser.constants.PathConstants import com.msc.serverbrowser.data.InstallationCandidateCache import com.msc.serverbrowser.data.properties.AllowCachingDownloadsProperty import com.msc.serverbrowser.data.properties.ClientPropertiesController import com.msc.serverbrowser.info import com.msc.serverbrowser.severe import com.msc.serverbrowser.util.basic.FileUtility import com.msc.serverbrowser.util.samp.GTAController import com.msc.serverbrowser.util.unix.WineUtility import com.msc.serverbrowser.util.windows.OSUtility import java.io.IOException import java.nio.file.Files import java.nio.file.Paths /** * Class for installing SA-MP Versions. * * @author Marcel * @since 22.01.2018 */ object Installer { /** * Installs an [InstallationCandidate]. * * @param candidate the candidate to be installed. */ fun installViaInstallationCandidate(candidate: InstallationCandidate) { // RetrievePath (includes isDownload if necessary, otherwise cache path) try { info("Installing $candidate.") val installer = getInstallerPathAndDownloadIfNecessary(candidate) val gtaPath = GTAController.gtaPath!! // Check whether its an installer or a zip if (candidate.url.endsWith(".exe")) { val windowsStyleGtaPath = GTAController.windowsStyleGtaPath runNullSoftInstaller(installer, windowsStyleGtaPath!!) info("Ran installer: $installer") } else { FileUtility.unzip(installer, gtaPath) info("Unzipped installation files: $installer") } // In case the cache wasn't use, we don't want to keep the temporary file. if (installer == PathConstants.TEMP_INSTALLER_EXE || installer == PathConstants.TEMP_INSTALLER_EXE) { Files.delete(Paths.get(installer)) info("Deleted temporary installation files: $installer") } } catch (exception: IOException) { severe("Error installing SA-MP.", exception) } } @Throws(IOException::class) private fun getInstallerPathAndDownloadIfNecessary(candidate: InstallationCandidate): String { if (InstallationCandidateCache.isVersionCached(candidate)) { val path = InstallationCandidateCache.getPathForCachedVersion(candidate) if (path.isPresent) { info("Using cached version for candidate '$candidate'.") return path.get() } } if (candidate.isDownload) { val isExecutable = candidate.url.endsWith(".exe") val outputPath = if (isExecutable) PathConstants.TEMP_INSTALLER_EXE else PathConstants.TEMP_INSTALLER_ZIP info("Downloading file for candidate '$candidate'.") FileUtility.downloadFile(candidate.url, outputPath) if (ClientPropertiesController.getProperty(AllowCachingDownloadsProperty)) { info("Adding file for candidate '$candidate' to cache.") InstallationCandidateCache.addCandidateToCache(candidate, outputPath) } return outputPath } return candidate.url } private fun runNullSoftInstaller(installerPath: String, gtaPath: String) { try { // cmd /c allows elevation of the command instead of retrieving an severe // /S starts a silent installation // /D specifies the installation target folder val installerProcess = if (OSUtility.isWindows.not()) { WineUtility.createWineRunner(listOf("cmd", "/c", installerPath, "/S", "/D=$gtaPath")).start() } else { Runtime.getRuntime().exec("cmd /c $installerPath /S /D=$gtaPath") } // Waiting until the installer has finished, in order to be able to give proper GUI responses. installerProcess.waitFor() } catch (exception: IOException) { severe("Error using installer: $installerPath", exception) } catch (exception: InterruptedException) { severe("Error using installer: $installerPath", exception) } } }
src/main/kotlin/com/msc/serverbrowser/data/insallationcandidates/Installer.kt
3844223770
package com.mindera.skeletoid.kt.extensions.utils fun String.removeSpaces() = this.replace(" ", "") fun String.digits() = this.map(Character::getNumericValue) fun String?.removeCharacters(charactersToRemove: String): String? { return this?.replace("[$charactersToRemove]".toRegex(), "") ?: this } fun String.matchesEntireRegex(regex: Regex): Boolean { return regex.matchEntire(this)?.value?.isNotEmpty() == true } fun String.isEmailValid(): Boolean { return this.isNotBlank() && android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches() } fun String?.nullIfBlank(): String? = if (isNullOrBlank()) null else this fun String?.nullIfEmpty(): String? = if (isNullOrEmpty()) null else this
kt-extensions/src/main/java/com/mindera/skeletoid/kt/extensions/utils/String.kt
3438357239
/* * Copyright (C) 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 com.example.android.people.ui.main import android.os.Bundle import android.transition.TransitionInflater import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.people.R import com.example.android.people.databinding.MainFragmentBinding import com.example.android.people.getNavigationController import com.example.android.people.ui.viewBindings /** * The main chat list screen. */ class MainFragment : Fragment(R.layout.main_fragment) { private val binding by viewBindings(MainFragmentBinding::bind) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) exitTransition = TransitionInflater.from(context).inflateTransition(R.transition.slide_top) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val navigationController = getNavigationController() navigationController.updateAppBar(false) val viewModel: MainViewModel by viewModels() val contactAdapter = ContactAdapter { id -> navigationController.openChat(id, null) } viewModel.contacts.observe(viewLifecycleOwner, Observer { contacts -> contactAdapter.submitList(contacts) }) binding.contacts.run { layoutManager = LinearLayoutManager(view.context) setHasFixedSize(true) adapter = contactAdapter } } }
app/src/main/java/com/example/android/people/ui/main/MainFragment.kt
2113664570
package co.garmax.materialflashlight.di import co.garmax.materialflashlight.ui.main.MainViewModel import co.garmax.materialflashlight.ui.root.RootViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val presentationModule = module { viewModel { RootViewModel(get(), get(), get()) } viewModel { MainViewModel(get(), get(), get(), get(), get()) } }
app/src/main/java/co/garmax/materialflashlight/di/PresentationModule.kt
3731445965
package expo.modules.updates import android.content.Context import expo.modules.core.interfaces.InternalModule import expo.modules.updates.db.DatabaseHolder import expo.modules.updates.db.entity.AssetEntity import expo.modules.updates.db.entity.UpdateEntity import expo.modules.updates.launcher.Launcher.LauncherCallback import expo.modules.updates.loader.FileDownloader import expo.modules.updates.selectionpolicy.SelectionPolicy import java.io.File // these unused imports must stay because of versioning /* ktlint-disable no-unused-imports */ import expo.modules.updates.UpdatesConfiguration import expo.modules.updates.UpdatesController /* ktlint-enable no-unused-imports */ open class UpdatesService(protected var context: Context) : InternalModule, UpdatesInterface { override fun getExportedInterfaces(): List<Class<*>> { return listOf(UpdatesInterface::class.java as Class<*>) } override val configuration: UpdatesConfiguration get() = UpdatesController.instance.updatesConfiguration override val selectionPolicy: SelectionPolicy get() = UpdatesController.instance.selectionPolicy override val directory: File? get() = UpdatesController.instance.updatesDirectory override val fileDownloader: FileDownloader get() = UpdatesController.instance.fileDownloader override val databaseHolder: DatabaseHolder get() = UpdatesController.instance.databaseHolder override val isEmergencyLaunch: Boolean get() = UpdatesController.instance.isEmergencyLaunch override val isUsingEmbeddedAssets: Boolean get() = UpdatesController.instance.isUsingEmbeddedAssets override fun canRelaunch(): Boolean { return configuration.isEnabled && launchedUpdate != null } override val launchedUpdate: UpdateEntity? get() = UpdatesController.instance.launchedUpdate override val localAssetFiles: Map<AssetEntity, String>? get() = UpdatesController.instance.localAssetFiles override fun relaunchReactApplication(callback: LauncherCallback) { UpdatesController.instance.relaunchReactApplication(context, callback) } override fun resetSelectionPolicy() { UpdatesController.instance.resetSelectionPolicyToDefault() } companion object { private val TAG = UpdatesService::class.java.simpleName } }
packages/expo-updates/android/src/main/java/expo/modules/updates/UpdatesService.kt
1872605522
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks import android.content.Context import dagger.android.HasAndroidInjector import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.utils.Round.isSame import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import kotlin.math.roundToLong /** * This class is intended to be run by the Service, for the Service. Not intended for clients to run. */ class InitializePumpManagerTask(injector: HasAndroidInjector, private val context: Context) : ServiceTask(injector) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @Inject lateinit var rileyLinkUtil: RileyLinkUtil override fun run() { if (!isRileyLinkDevice) return var lastGoodFrequency: Double if (rileyLinkServiceData.lastGoodFrequency == null) { lastGoodFrequency = sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0) lastGoodFrequency = (lastGoodFrequency * 1000.0).roundToLong() / 1000.0 rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency } else lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency ?: 0.0 val rileyLinkCommunicationManager = pumpDevice?.rileyLinkService?.deviceCommunicationManager if (activePlugin.activePump.manufacturer() === ManufacturerType.Medtronic) { if (lastGoodFrequency > 0.0 && rileyLinkCommunicationManager?.isValidFrequency(lastGoodFrequency) == true) { rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkReady) aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to $lastGoodFrequency MHz") rileyLinkCommunicationManager.setRadioFrequencyForPump(lastGoodFrequency) if (rileyLinkCommunicationManager.tryToConnectToDevice()) rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorReady) else { rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.NoContactWithDevice) rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context) } } else rileyLinkUtil.sendBroadcastMessage(RileyLinkConst.IPC.MSG_PUMP_tunePump, context) } else { if (!isSame(lastGoodFrequency, RileyLinkTargetFrequency.Omnipod.scanFrequencies[0])) { lastGoodFrequency = RileyLinkTargetFrequency.Omnipod.scanFrequencies[0] lastGoodFrequency = (lastGoodFrequency * 1000.0).roundToLong() / 1000.0 rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency } rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkReady) rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod // TODO shouldn't be needed aapsLogger.info(LTag.PUMPBTCOMM, "Setting radio frequency to $lastGoodFrequency MHz") rileyLinkCommunicationManager?.setRadioFrequencyForPump(lastGoodFrequency) rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorReady) } } }
rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.kt
3132245296
package info.nightscout.androidaps.setupwizard.elements import android.os.Bundle import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.activities.MyPreferenceFragment import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.setupwizard.SWDefinition import javax.inject.Inject class SWPreference(injector: HasAndroidInjector, private val definition: SWDefinition) : SWItem(injector, Type.PREFERENCE) { @Inject lateinit var pluginStore: PluginStore @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin private var xml: Int = -1 fun option(xml: Int): SWPreference { this.xml = xml return this } override fun generateDialog(layout: LinearLayout) { addConfiguration(layout, xml) super.generateDialog(layout) } private fun addConfiguration(layout: LinearLayout, xml: Int) { MyPreferenceFragment().also { fragment -> fragment.arguments = Bundle().also { it.putInt("id", xml) } definition.activity.supportFragmentManager.beginTransaction().run { replace(layout.id, fragment) commit() } } } }
app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPreference.kt
3335582842
package br.com.maiconhellmann.pomodoro.ui.base import android.os.Bundle import android.support.annotation.CallSuper import android.support.v4.app.Fragment import br.com.maiconhellmann.pomodoro.PomodoroApplication import br.com.maiconhellmann.pomodoro.injection.component.ConfigPersistentComponent import br.com.maiconhellmann.pomodoro.injection.module.PresenterModule import timber.log.Timber import java.util.concurrent.atomic.AtomicLong open class BaseFragment: Fragment(){ lateinit var baseActivity: BaseActivity companion object { @JvmStatic private val KEY_FRAGMENT_ID = "KEY_FRAGMENT_ID" @JvmStatic private val NEXT_ID = AtomicLong(0) @JvmStatic private val componentsMap = HashMap<Long, ConfigPersistentComponent>() } private var fragmentId: Long = 0 lateinit var component: ConfigPersistentComponent get @Suppress("UsePropertyAccessSyntax") @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Create the ActivityComponent and reuses cached ConfigPersistentComponent if this is // being called after a configuration change. fragmentId = savedInstanceState?.getLong(KEY_FRAGMENT_ID) ?: NEXT_ID.getAndIncrement() if (componentsMap[fragmentId] != null) Timber.i("Reusing ConfigPersistentComponent id = $fragmentId") component = componentsMap.getOrPut(fragmentId, { Timber.i("Creating new ConfigPersistentComponent id=$fragmentId") (context.applicationContext as PomodoroApplication).applicationComponent.plus(PresenterModule()) }) } @CallSuper override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putLong(KEY_FRAGMENT_ID, fragmentId) } @CallSuper override fun onDestroy() { if (!activity.isChangingConfigurations) { Timber.i("Clearing ConfigPersistentComponent id=$fragmentId") componentsMap.remove(fragmentId) } super.onDestroy() } @CallSuper override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) if(activity is BaseActivity){ baseActivity = activity as BaseActivity }else{ throw Throwable("Fragment doesn't implements ${BaseActivity::class.java.simpleName}") } } open fun showProgressIndicator(){ baseActivity.showProgressIndicator() } open fun hideProgressIndicator(){ baseActivity.hideProgressIndicator() } }
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/ui/base/BaseFragment.kt
979717754
package pl.droidsonroids.gradle.ci import org.assertj.core.api.Assertions.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Rule import org.junit.Test import pl.droidsonroids.gradle.ci.Constants.CONNECTED_SETUP_REVERT_UI_TEST_TASK_NAME import pl.droidsonroids.gradle.ci.Constants.CONNECTED_SETUP_UI_TEST_TASK_NAME import pl.droidsonroids.gradle.ci.Constants.CONNECTED_UI_TEST_TASK_NAME import pl.droidsonroids.gradle.ci.Constants.SPOON_TASK_NAME class SetupFunctionalTest { @get:Rule val temporaryFolder = TemporaryProjectFolder() @Test fun `setup fails when there is no connected devices`() { temporaryFolder.copyResource("base.gradle", "base.gradle") temporaryFolder.copyResource("buildType.gradle", "build.gradle") val result = GradleRunner .create() .withProjectDir(temporaryFolder.root) .withTestKitDir(temporaryFolder.newFolder()) .withArguments(CONNECTED_SETUP_UI_TEST_TASK_NAME) .withPluginClasspath() .withJaCoCo() .buildAndFail() assertThat(result.output).contains("No connected devices") } @Test fun `setup invoked as dependent task`() { temporaryFolder.copyResource("base.gradle", "base.gradle") temporaryFolder.copyResource("buildType.gradle", "build.gradle") val result = GradleRunner .create() .withProjectDir(temporaryFolder.root) .withTestKitDir(temporaryFolder.newFolder()) .withArguments(CONNECTED_UI_TEST_TASK_NAME, "-m") .withPluginClasspath() .withJaCoCo() .build() assertThat(result.task(":$CONNECTED_SETUP_UI_TEST_TASK_NAME")).isNotNull() assertThat(result.task(":$SPOON_TASK_NAME")).isNotNull() assertThat(result.task(":$CONNECTED_SETUP_REVERT_UI_TEST_TASK_NAME")).isNotNull() } }
plugin/src/test/kotlin/pl/droidsonroids/gradle/ci/SetupFunctionalTest.kt
1452137568
package venus.riscv.insts.dsl.relocators import venus.riscv.InstructionField import venus.riscv.MachineCode private object PCRelLoStoreRelocator32 : Relocator32 { override operator fun invoke(mcode: MachineCode, pc: Int, target: Int) { val offset = target - (pc - 4) mcode[InstructionField.IMM_4_0] = offset mcode[InstructionField.IMM_11_5] = offset shr 5 } } val PCRelLoStoreRelocator = Relocator(PCRelLoStoreRelocator32, NoRelocator64)
src/main/kotlin/venus/riscv/insts/dsl/relocators/PCRelLoStoreRelocator.kt
2781189991
package com.prt2121.everywhere.meetup.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Created by pt2121 on 1/18/16. */ data class NextEvent( @SerializedName("id") @Expose var id: String, @SerializedName("name") @Expose var name: String, @SerializedName("yes_rsvp_count") @Expose var yesRsvpCount: Int, @SerializedName("time") @Expose var time: Long, @SerializedName("utc_offset") @Expose var utcOffset: Int )
Everywhere/app/src/main/kotlin/com/prt2121/everywhere/meetup/model/NextEvent.kt
2490691322
package com.prateekj.snooper.rules import android.os.Looper import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class RunUsingLooper : TestRule { override fun apply(base: Statement, description: Description): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { try { if (Looper.myLooper() == null) { Looper.prepare() } base.evaluate() } finally { Looper.myLooper()!!.quit() } } } } }
Snooper/src/androidTest/java/com/prateekj/snooper/rules/RunUsingLooper.kt
1397636970
package net.treelzebub.zinepress.auth import android.net.Uri import de.rheinfabrik.heimdall.OAuth2AccessToken import de.rheinfabrik.heimdall.grants.OAuth2AuthorizationCodeGrant import net.treelzebub.zinepress.Constants import net.treelzebub.zinepress.auth.model.AccessTokenRequestBody import net.treelzebub.zinepress.auth.model.PocketAccessToken import net.treelzebub.zinepress.net.api.PocketApiFactory import net.treelzebub.zinepress.util.UserUtils import rx.Observable /** * Created by Tre Murillo on 1/2/16 */ class PocketAuthCodeGrant : OAuth2AuthorizationCodeGrant<PocketAccessToken>() { override fun buildAuthorizationUri(): Uri { return Uri.parse(Constants.AUTHORIZE_URL) .buildUpon() .appendQueryParameter("consumer_key", clientId) .appendQueryParameter("redirect_uri", redirectUri) .appendQueryParameter("X-Accept", "application/json") .build() } override fun exchangeTokenUsingCode(code: String): Observable<PocketAccessToken> { val body = AccessTokenRequestBody(code, Constants.CONSUMER_KEY, redirectUri) return PocketApiFactory.newApiService().newAccessToken(body) } }
app/src/main/java/net/treelzebub/zinepress/auth/PocketAuthCodeGrant.kt
1963889562
package net.treelzebub.zinepress /** * Created by Tre Murillo on 1/2/16 */ object Constants { const val CONSUMER_KEY = "49756-f2c439a8fa6256da0bc3710a" const val BASE_URL = "https://getpocket.com" const val AUTHORIZE_URL = "$BASE_URL/auth/authorize" const val REDIRECT_URI = "oauth://zinepress.treelzebub.net" const val CONTENT_TYPE_ARTICLE = "article" }
app/src/main/java/net/treelzebub/zinepress/Constants.kt
1452052078
/* * Copyright 2021 Realm 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 io.realm.entities import io.realm.RealmAny import io.realm.RealmList import io.realm.RealmObject import io.realm.RealmSet import io.realm.annotations.PrimaryKey import org.bson.types.Decimal128 import org.bson.types.ObjectId import java.util.* open class SetContainerClass : RealmObject() { val myRealmModelNoPkSet = RealmSet<Owner>() val myRealmModelSet = RealmSet<DogPrimaryKey>() val myBooleanSet = RealmSet<Boolean>() val myStringSet = RealmSet<String>() val myIntSet = RealmSet<Int>() val myFloatSet = RealmSet<Float>() val myLongSet = RealmSet<Long>() val myShortSet = RealmSet<Short>() val myDoubleSet = RealmSet<Double>() val myByteSet = RealmSet<Byte>() val myBinarySet = RealmSet<ByteArray>() val myDateSet = RealmSet<Date>() val myObjectIdSet = RealmSet<ObjectId>() val myUUIDSet = RealmSet<UUID>() val myDecimal128Set = RealmSet<Decimal128>() val myRealmAnySet = RealmSet<RealmAny>() val myRealmModelNoPkList = RealmList<Owner>() val myRealmModelList = RealmList<DogPrimaryKey>() val myBooleanList = RealmList<Boolean>() val myStringList = RealmList<String>() val myIntList = RealmList<Int>() val myFloatList = RealmList<Float>() val myLongList = RealmList<Long>() val myShortList = RealmList<Short>() val myDoubleList = RealmList<Double>() val myByteList = RealmList<Byte>() val myBinaryList = RealmList<ByteArray>() val myDateList = RealmList<Date>() val myObjectIdList = RealmList<ObjectId>() val myUUIDList = RealmList<UUID>() val myDecimal128List = RealmList<Decimal128>() val myRealmAnyList = RealmList<RealmAny>() companion object { const val CLASS_NAME = "SetContainerClass" } } open class SetContainerMigrationClass : RealmObject() { @PrimaryKey var id: String? = "" val myRealmModelSet = RealmSet<StringOnly>() val myBooleanSet = RealmSet<Boolean>() val myStringSet = RealmSet<String>() val myIntSet = RealmSet<Int>() val myFloatSet = RealmSet<Float>() val myLongSet = RealmSet<Long>() val myShortSet = RealmSet<Short>() val myDoubleSet = RealmSet<Double>() val myByteSet = RealmSet<Byte>() val myBinarySet = RealmSet<ByteArray>() val myDateSet = RealmSet<Date>() val myObjectIdSet = RealmSet<ObjectId>() val myUUIDSet = RealmSet<UUID>() val myDecimal128Set = RealmSet<Decimal128>() val myRealmAnySet = RealmSet<RealmAny>() companion object { const val CLASS_NAME = "SetContainerMigrationClass" } } open class SetContainerAfterMigrationClass : RealmObject() { @PrimaryKey var id: String? = "" companion object { const val CLASS_NAME = "SetContainerAfterMigrationClass" } }
realm/realm-library/src/androidTest/kotlin/io/realm/entities/SetContainerClass.kt
351307714
/* * Copyright (c) 2017 Dmitry Zhuravlev, Sergei Stepanov * * 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.hotswap.agent.plugin.configuration.patcher import com.hotswap.agent.plugin.services.HotSwapAgentPluginNotification import com.hotswap.agent.plugin.settings.HotSwapAgentPluginSettingsProvider import com.hotswap.agent.plugin.util.DCEVMUtil import com.intellij.execution.Executor import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.configurations.RunProfile import com.intellij.execution.runners.JavaProgramPatcher import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import java.io.File /** * @author Dmitry Zhuravlev * Date: 10.03.2017 */ class HotSwapAgentPluginConfigurationPatcher : JavaProgramPatcher() { companion object { internal val log = Logger.getInstance(HotSwapAgentPluginConfigurationPatcher::class.java) } override fun patchJavaParameters(executor: Executor?, configuration: RunProfile?, javaParameters: JavaParameters?) { val project = (configuration as? RunConfiguration)?.project ?: return val stateProvider = HotSwapAgentPluginSettingsProvider.getInstance(project) val agentPath = stateProvider.currentState.agentPath val disablePluginsParam = stateProvider.currentState.disabledPlugins.toDisabledPluginsParam() if (!File(agentPath).exists()) return if (stateProvider.currentState.enableAgentForAllConfiguration) { applyForConfiguration(agentPath, disablePluginsParam, configuration, javaParameters, project) } else if (stateProvider.currentState.selectedRunConfigurations.contains(configuration.name ?: "")) { applyForConfiguration(agentPath, disablePluginsParam, configuration, javaParameters, project) } } private fun applyForConfiguration(agentPath: String, disablePluginsParam: String, configuration: RunProfile?, javaParameters: JavaParameters?, project: Project) { log.debug("Applying HotSwapAgent to configuration ${configuration?.name ?: ""}") ProjectRootManager.getInstance(project).projectSdk?.let { sdk -> if (DCEVMUtil.isDCEVMInstalledLikeAltJvm(sdk)) { javaParameters?.vmParametersList?.add("-XXaltjvm=dcevm") } if (!DCEVMUtil.isDCEVMPresent(sdk)) { HotSwapAgentPluginNotification.getInstance(project).showNotificationAboutMissingDCEVM() } } javaParameters?.vmParametersList?.add("-javaagent:$agentPath$disablePluginsParam") } private fun Set<String>.toDisabledPluginsParam() = if (this.isEmpty()) "" else "=" + this.joinToString(",") { "disablePlugin=$it" } }
src/com/hotswap/agent/plugin/configuration/patcher/HotSwapAgentPluginConfigurationPatcher.kt
3318563245
package arcs.core.data.proto import arcs.core.data.AccessPath import arcs.core.data.Check import arcs.core.data.HandleConnectionSpec import arcs.core.data.HandleMode import arcs.core.data.InformationFlowLabel import arcs.core.data.TypeVariable import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class CheckProtoTest { @Test fun roundTrip_assert() { val connectionSpec = HandleConnectionSpec( name = "connectionSpec", direction = HandleMode.Read, type = TypeVariable("a") ) val check = Check( accessPath = AccessPath("particleSpec", connectionSpec), predicate = InformationFlowLabel.Predicate.Label( InformationFlowLabel.SemanticTag("label") ) ) val encoded = check.encode() val decoded = encoded.decode(mapOf("connectionSpec" to connectionSpec)) assertThat(decoded).isEqualTo(check) } }
javatests/arcs/core/data/proto/CheckProtoTest.kt
3561270202
package com.fsck.k9.ui.messagelist import android.content.ContentResolver import com.fsck.k9.Preferences import kotlinx.coroutines.CoroutineScope class MessageListLiveDataFactory( private val messageListLoader: MessageListLoader, private val preferences: Preferences, private val contentResolver: ContentResolver ) { fun create(coroutineScope: CoroutineScope, config: MessageListConfig): MessageListLiveData { return MessageListLiveData(messageListLoader, preferences, contentResolver, coroutineScope, config) } }
app/ui/legacy/src/main/java/com/fsck/k9/ui/messagelist/MessageListLiveDataFactory.kt
45204956
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.kotlin.generator.protoc.util.graph import com.google.common.annotations.Beta import com.google.common.base.Preconditions.checkArgument import com.google.common.graph.Graph import io.grpc.kotlin.generator.protoc.util.sort.PartialOrdering import io.grpc.kotlin.generator.protoc.util.sort.TopologicalSort.sortLexicographicallyLeast @Beta object TopologicalSortGraph { fun <N> topologicalOrdering(graph: Graph<N>): List<N> { checkArgument(graph.isDirected, "Cannot get topological ordering of an undirected graph.") val partialOrdering: PartialOrdering<N> = object : PartialOrdering<N> { override fun getPredecessors(element: N): Set<N> = element?.let { graph.predecessors(it) } ?: emptySet() } return sortLexicographicallyLeast(graph.nodes(), partialOrdering) } }
compiler/src/main/java/io/grpc/kotlin/generator/protoc/util/graph/TopologicalSortGraph.kt
79820506
package bz.stewart.bracken.shared.data /** * Created by stew on 5/18/17. */ interface PublicRelatedBill
shared/src/main/kotlin/bz/stewart/bracken/shared/data/PublicRelatedBill.kt
3182037757
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.toExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType import org.jetbrains.kotlin.nj2k.types.isArrayType import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.nj2k.types.updateNullabilityRecursively class AnnotationClassConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind != JKClass.ClassKind.ANNOTATION) return recurse(element) val javaAnnotationMethods = element.classBody.declarations .filterIsInstance<JKJavaAnnotationMethod>() val constructor = JKKtPrimaryConstructor( JKNameIdentifier(""), javaAnnotationMethods.map { it.asKotlinAnnotationParameter() }, JKStubExpression(), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) element.modality = Modality.FINAL element.classBody.declarations += constructor element.classBody.declarations -= javaAnnotationMethods return recurse(element) } private fun JKJavaAnnotationMethod.asKotlinAnnotationParameter(): JKParameter { val type = returnType.type .updateNullabilityRecursively(Nullability.NotNull) .replaceJavaClassWithKotlinClassType(symbolProvider) val initializer = this::defaultValue.detached().toExpression(symbolProvider) val isVarArgs = type is JKJavaArrayType && name.value == "value" return JKParameter( JKTypeElement( if (!isVarArgs) type else (type as JKJavaArrayType).type, returnType::annotationList.detached() ), JKNameIdentifier(name.value), isVarArgs = isVarArgs, initializer = if (type.isArrayType() && initializer !is JKKtAnnotationArrayInitializerExpression && initializer !is JKStubExpression ) { JKKtAnnotationArrayInitializerExpression(initializer) } else initializer, annotationList = this::annotationList.detached(), ).also { parameter -> parameter.trailingComments += trailingComments parameter.leadingComments += leadingComments } } }
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnnotationClassConversion.kt
2727117193