content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.debug import com.intellij.debugger.PositionManager import com.intellij.debugger.PositionManagerFactory import com.intellij.debugger.engine.DebugProcess class MixinPositionManagerFactory : PositionManagerFactory() { override fun createPositionManager(process: DebugProcess): PositionManager? = MixinPositionManager(process) }
src/main/kotlin/platform/mixin/debug/MixinPositionManagerFactory.kt
1338439448
package request import constant.Constant import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import util.LogUtil /** * 作用 网络请求工具类,单例 * Created by 司马林 on 2017/10/10. */ class RetrofitUtil private constructor() { private object getInstance { val INSTANCE = RetrofitUtil() } companion object { val instance: RetrofitUtil by lazy { getInstance.INSTANCE } private var client: OkHttpClient? = null init { val interceptor = Interceptor { chain -> val request = chain.request().newBuilder().build() LogUtil.e(request.toString()) chain.proceed(request) } client = OkHttpClient.Builder().addInterceptor(interceptor).build() } } fun<S> getApi(server:Class<S>): S { val retrofit: Retrofit = Retrofit.Builder().baseUrl(Constant.BASE_URL) .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(server) } }
base/src/main/java/request/RetrofitUtil.kt
64050341
package com.omega.discord.bot.audio.loader import com.omega.discord.bot.audio.GuildAudioPlayerManager import com.omega.discord.bot.util.MessageSender import com.sedmelluq.discord.lavaplayer.tools.FriendlyException import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist import com.sedmelluq.discord.lavaplayer.track.AudioTrack import org.slf4j.Logger import org.slf4j.LoggerFactory import sx.blah.discord.handle.obj.IChannel class QueueUrlResultLoadHandler(private val manager: GuildAudioPlayerManager, val channel: IChannel) : AudioLoadHandler() { private val LOGGER: Logger = LoggerFactory.getLogger(this.javaClass) override fun trackLoaded(track: AudioTrack) { super.trackLoaded(track) MessageSender.sendMessage(channel, "Added track ${track.info.title} to queue") manager.scheduler.queue(track) } override fun playlistLoaded(playlist: AudioPlaylist) { super.playlistLoaded(playlist) MessageSender.sendMessage(channel, "Added playlist ${playlist.name} (${playlist.tracks.size} tracks) to queue") manager.scheduler.queue(playlist.tracks) } override fun noMatches() { super.noMatches() MessageSender.sendMessage(channel, "No track(s) found") } override fun loadFailed(exception: FriendlyException?) { super.loadFailed(exception) MessageSender.sendMessage(channel, "Failed to load track(s)") LOGGER.error("Failed to load track(s)", exception) } }
src/main/kotlin/com/omega/discord/bot/audio/loader/QueueUrlResultLoadHandler.kt
2179525600
/* * Copyright (c) 2020. André Mion * * 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.andremion.louvre.data import android.database.Cursor import android.database.MatrixCursor import android.database.MergeCursor import android.os.Build import android.os.Bundle import android.provider.MediaStore import androidx.annotation.IntRange import androidx.fragment.app.FragmentActivity import androidx.loader.app.LoaderManager import androidx.loader.content.CursorLoader import androidx.loader.content.Loader import com.andremion.louvre.R private const val TIME_LOADER = 0 private const val BUCKET_LOADER = 1 private const val MEDIA_LOADER = 2 private const val ARG_BUCKET_ID = MediaStore.Images.Media.BUCKET_ID /** * [Loader] for media and bucket data */ class MediaLoader : LoaderManager.LoaderCallbacks<Cursor?> { interface Callbacks { fun onBucketLoadFinished(data: Cursor?) fun onMediaLoadFinished(data: Cursor?) } private var activity: FragmentActivity? = null private var callbacks: Callbacks? = null private var typeFilter = "1" // Means all media type. override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor?> = ensureActivityAttached().let { activity -> when (id) { TIME_LOADER -> CursorLoader( activity, GALLERY_URI, IMAGE_PROJECTION, typeFilter, null, MEDIA_SORT_ORDER ) BUCKET_LOADER -> CursorLoader( activity, GALLERY_URI, BUCKET_PROJECTION, "$typeFilter AND $BUCKET_SELECTION", null, BUCKET_SORT_ORDER ) // id == MEDIA_LOADER else -> CursorLoader( activity, GALLERY_URI, IMAGE_PROJECTION, "${MediaStore.Images.Media.BUCKET_ID}=${args?.getLong(ARG_BUCKET_ID) ?: 0} AND $typeFilter", null, MEDIA_SORT_ORDER ) } } override fun onLoadFinished(loader: Loader<Cursor?>, data: Cursor?) { callbacks?.let { callbacks -> if (loader.id == BUCKET_LOADER) { callbacks.onBucketLoadFinished(finishUpBuckets(data)) } else { callbacks.onMediaLoadFinished(data) } } } override fun onLoaderReset(loader: Loader<Cursor?>) { // no-op } fun onAttach(activity: FragmentActivity, callbacks: Callbacks) { this.activity = activity this.callbacks = callbacks } fun onDetach() { activity = null callbacks = null } fun setMediaTypes(mediaTypes: Array<String>) { val filter = mediaTypes.joinToString { "'$it'" } if (filter.isNotEmpty()) { typeFilter = "${MediaStore.Images.Media.MIME_TYPE} IN ($filter)" } } fun loadBuckets() { LoaderManager.getInstance(ensureActivityAttached()) .restartLoader(BUCKET_LOADER, null, this) } fun loadByBucket(@IntRange(from = 0) bucketId: Long) { ensureActivityAttached().let { activity -> if (ALL_MEDIA_BUCKET_ID == bucketId) { LoaderManager.getInstance(activity).restartLoader(TIME_LOADER, null, this) } else { val args = Bundle() args.putLong(ARG_BUCKET_ID, bucketId) LoaderManager.getInstance(activity).restartLoader(MEDIA_LOADER, args, this) } } } /** * Ensure that a FragmentActivity is attached to this loader. */ private fun ensureActivityAttached(): FragmentActivity = requireNotNull(activity) { "The FragmentActivity was not attached!" } private fun finishUpBuckets(cursor: Cursor?): Cursor? = MergeCursor( arrayOf( addAllMediaBucketItem(cursor), if (isAllowedAggregatedFunctions) cursor else aggregateBuckets(cursor) ) ) /** * Add "All Media" item as the first row of bucket items. * * @param cursor The original data of all bucket items * @return The data with "All Media" item added */ private fun addAllMediaBucketItem(cursor: Cursor?): Cursor? = cursor?.run { if (!moveToPosition(0)) return null val id = ALL_MEDIA_BUCKET_ID val label = ensureActivityAttached().getString(R.string.activity_gallery_bucket_all_media) val data = getString(getColumnIndex(MediaStore.Images.Media.DATA)) MatrixCursor(BUCKET_PROJECTION).apply { newRow() .add(id) .add(label) .add(data) } } /** * Since we are not allowed to use SQL aggregation functions we need to do that on code * * @param cursor The original data of all bucket items * @return The data aggregated by buckets */ private fun aggregateBuckets(cursor: Cursor?): Cursor? = cursor?.run { val idIndex = getColumnIndex(MediaStore.Images.Media.BUCKET_ID) val labelIndex = getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME) val dataIndex = getColumnIndex(MediaStore.Images.Media.DATA) val aggregatedBucket = MatrixCursor(BUCKET_PROJECTION) var previousId = 0L for (position in 0 until cursor.count) { moveToPosition(position) val id = getLong(idIndex) val label = getString(labelIndex) val data = getString(dataIndex) if (id != previousId) { aggregatedBucket.newRow() .add(id) .add(label) .add(data) } previousId = id } aggregatedBucket } } internal val isAllowedAggregatedFunctions = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
louvre/src/main/java/com/andremion/louvre/data/MediaLoader.kt
206711619
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmMultifileClass @file:JvmName("MenuItemsSequencesKt") package org.jetbrains.anko import android.view.Menu import android.view.MenuItem import java.util.* fun Menu.itemsSequence(): Sequence<MenuItem> = MenuItemsSequence(this) private class MenuItemsSequence(private val menu: Menu) : Sequence<MenuItem> { override fun iterator(): Iterator<MenuItem> { return MenuItemIterator(menu) } private class MenuItemIterator(private val menu: Menu) : Iterator<MenuItem> { private var index = 0 private val count = menu.size() override fun next(): MenuItem { if (!hasNext()) { throw NoSuchElementException() } return menu.getItem(index++) } override fun hasNext(): Boolean { if (count != menu.size()) { throw ConcurrentModificationException() } return index < count } } }
dsl/static/src/common/menuItemsSequences.kt
261641384
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.domain.actions.actionexecutors.webview import android.content.Context import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import com.gigigo.orchextra.core.R import kotlinx.android.synthetic.main.ox_activity_web_view.oxWebView import java.net.URI import java.net.URISyntaxException class WebViewActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.ox_activity_web_view) initToolbar() oxWebView.loadUrl(getUrl()) } private fun initToolbar() { val toolbar = findViewById<Toolbar>(R.id.ox_toolbar) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) toolbar.setNavigationOnClickListener { onBackPressed() } title = getDomainName(getUrl()) } private fun getUrl(): String = intent.getStringExtra(EXTRA_URL) ?: "" @Throws(URISyntaxException::class) private fun getDomainName(url: String): String { val uri = URI(url) val domain = uri.host return if (domain.startsWith("www.")) domain.substring(4) else domain } companion object Navigator { val EXTRA_URL = "extra_url" fun open(context: Context, url: String) { val intent = Intent(context, WebViewActivity::class.java) intent.putExtra(EXTRA_URL, url) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(intent) } } }
core/src/main/java/com/gigigo/orchextra/core/domain/actions/actionexecutors/webview/WebViewActivity.kt
686048610
/* * Copyright (c) 2017 Michał Bączkowski * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.mibac138.argparser.exception /** * Indicates a exception inside a [Parser] */ open class ParserException : RuntimeException { constructor() : super() constructor(message: String?) : super(message) constructor(message: String?, cause: Throwable?) : super(message, cause) constructor(cause: Throwable?) : super(cause) }
core/src/main/kotlin/com/github/mibac138/argparser/exception/ParserException.kt
1718678159
package io.gitlab.arturbosch.tinbo.finance import io.gitlab.arturbosch.tinbo.api.config.ModeManager import io.gitlab.arturbosch.tinbo.api.config.TinboMode import io.gitlab.arturbosch.tinbo.api.marker.Command import io.gitlab.arturbosch.tinbo.api.utils.printlnInfo import org.springframework.shell.core.annotation.CliAvailabilityIndicator import org.springframework.shell.core.annotation.CliCommand import org.springframework.stereotype.Component /** * @author Artur Bosch */ @Component class StartFinanceModeCommand : Command { override val id: String = "start" @CliAvailabilityIndicator("finance") fun onlyModeCommands(): Boolean { return ModeManager.isCurrentMode(TinboMode.START) } @CliCommand("finance", help = "Switch to finance mode where you can manage your finances.") fun financeMode() { ModeManager.current = FinanceMode printlnInfo("Entering finance mode...") } }
tinbo-finance/src/main/kotlin/io/gitlab/arturbosch/tinbo/finance/StartFinanceModeCommand.kt
3679641275
/* * 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.context import javax.annotation.concurrent.ThreadSafe /** * Interface for objects in LocalContext. * * @author Artem V. Navrotskiy <[email protected]> */ @ThreadSafe interface Local : AutoCloseable { @Throws(Exception::class) override fun close() { } }
src/main/kotlin/svnserver/context/Local.kt
3537283607
/* Copyright (c) 2020 David Allison <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.dialogs import android.app.Activity import android.app.Dialog import android.content.Context import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.Filter import android.widget.Filterable import android.widget.TextView import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.ichi2.anki.R import com.ichi2.anki.analytics.AnalyticsDialogFragment import com.ichi2.anki.dialogs.LocaleSelectionDialog.LocaleListAdapter.TextViewHolder import com.ichi2.ui.RecyclerSingleTouchAdapter import com.ichi2.utils.DisplayUtils.resizeWhenSoftInputShown import java.util.* /** Locale selection dialog. Note: this must be dismissed onDestroy if not called from an activity implementing LocaleSelectionDialogHandler */ class LocaleSelectionDialog : AnalyticsDialogFragment() { private var mDialogHandler: LocaleSelectionDialogHandler? = null interface LocaleSelectionDialogHandler { fun onSelectedLocale(selectedLocale: Locale) fun onLocaleSelectionCancelled() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isCancelable = true } override fun onAttach(context: Context) { super.onAttach(context) if (context is Activity) { if (mDialogHandler == null) { require(context is LocaleSelectionDialogHandler) { "Calling activity must implement LocaleSelectionDialogHandler" } mDialogHandler = context } resizeWhenSoftInputShown(context.window) } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity: Activity = requireActivity() val tagsDialogView = LayoutInflater.from(activity) .inflate(R.layout.locale_selection_dialog, activity.findViewById(R.id.root_layout), false) val adapter = LocaleListAdapter(Locale.getAvailableLocales()) setupRecyclerView(activity, tagsDialogView, adapter) inflateMenu(tagsDialogView, adapter) // Only show a negative button, use the RecyclerView for positive actions val builder = MaterialDialog.Builder(activity) .negativeText(getString(R.string.dialog_cancel)) .customView(tagsDialogView, false) .onNegative { _: MaterialDialog?, _: DialogAction? -> mDialogHandler!!.onLocaleSelectionCancelled() } val dialog: Dialog = builder.build() val window = dialog.window if (window != null) { resizeWhenSoftInputShown(window) } return dialog } private fun setupRecyclerView(activity: Activity, tagsDialogView: View, adapter: LocaleListAdapter) { val recyclerView: RecyclerView = tagsDialogView.findViewById(R.id.locale_dialog_selection_list) recyclerView.requestFocus() val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(activity) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.addOnItemTouchListener( RecyclerSingleTouchAdapter(activity) { _: View?, position: Int -> val l = adapter.getLocaleAtPosition(position) mDialogHandler!!.onSelectedLocale(l) } ) } private fun inflateMenu(tagsDialogView: View, adapter: LocaleListAdapter) { val toolbar: Toolbar = tagsDialogView.findViewById(R.id.locale_dialog_selection_toolbar) toolbar.setTitle(R.string.locale_selection_dialog_title) toolbar.inflateMenu(R.menu.locale_dialog_search_bar) val searchItem = toolbar.menu.findItem(R.id.locale_dialog_action_search) val searchView = searchItem.actionView as SearchView searchView.imeOptions = EditorInfo.IME_ACTION_DONE searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { return false } override fun onQueryTextChange(newText: String): Boolean { adapter.filter.filter(newText) return false } }) } class LocaleListAdapter(locales: Array<Locale?>) : RecyclerView.Adapter<TextViewHolder>(), Filterable { private val mCurrentlyVisibleLocales: MutableList<Locale> private val mSelectableLocales: List<Locale> = Collections.unmodifiableList(ArrayList(mutableListOf(*locales))) class TextViewHolder(private val textView: TextView) : RecyclerView.ViewHolder(textView) { fun setText(text: String) { textView.text = text } fun setLocale(locale: Locale) { val displayValue = locale.displayName textView.text = displayValue } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): TextViewHolder { val v = LayoutInflater.from(parent.context) .inflate(R.layout.locale_dialog_fragment_textview, parent, false) as TextView return TextViewHolder(v) } override fun onBindViewHolder(holder: TextViewHolder, position: Int) { holder.setLocale(mCurrentlyVisibleLocales[position]) } override fun getItemCount(): Int { return mCurrentlyVisibleLocales.size } fun getLocaleAtPosition(position: Int): Locale { return mCurrentlyVisibleLocales[position] } override fun getFilter(): Filter { val selectableLocales = mSelectableLocales val visibleLocales = mCurrentlyVisibleLocales return object : Filter() { override fun performFiltering(constraint: CharSequence): FilterResults { if (TextUtils.isEmpty(constraint)) { val filterResults = FilterResults() filterResults.values = selectableLocales return filterResults } val normalisedConstraint = constraint.toString().lowercase(Locale.getDefault()) val locales = ArrayList<Locale>(selectableLocales.size) for (l in selectableLocales) { if (l.displayName.lowercase(Locale.getDefault()).contains(normalisedConstraint)) { locales.add(l) } } val filterResults = FilterResults() filterResults.values = locales return filterResults } @Suppress("UNCHECKED_CAST") override fun publishResults(constraint: CharSequence, results: FilterResults) { visibleLocales.clear() val values = results.values as Collection<Locale> visibleLocales.addAll(values) notifyDataSetChanged() } } } init { mCurrentlyVisibleLocales = ArrayList(mutableListOf(*locales)) } } companion object { /** * @param handler Marker interface to enforce the convention the caller implementing LocaleSelectionDialogHandler */ @JvmStatic fun newInstance(handler: LocaleSelectionDialogHandler): LocaleSelectionDialog { val t = LocaleSelectionDialog() t.mDialogHandler = handler val args = Bundle() t.arguments = args return t } } }
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/LocaleSelectionDialog.kt
1391237141
package com.sksamuel.rxhive import com.sksamuel.rxhive.formats.ParquetFormat import io.kotlintest.specs.FunSpec import io.kotlintest.shouldBe class ParquetFormatTest : FunSpec() { init { test("should set correct serde information") { ParquetFormat.serde().inputFormat shouldBe "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat" ParquetFormat.serde().outputFormat shouldBe "org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat" ParquetFormat.serde().serializationLib shouldBe "org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe" } } }
rxhive-core/src/test/kotlin/com/sksamuel/rxhive/ParquetFormatTest.kt
660790401
package teamcity.crowd.plugin import com.atlassian.crowd.exception.* import com.atlassian.crowd.integration.rest.entity.GroupEntity import com.atlassian.crowd.model.group.GroupType import com.atlassian.crowd.model.user.User import com.atlassian.crowd.service.client.CrowdClient import com.intellij.openapi.diagnostic.Logger import org.junit.Assert.* import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.mock import org.mockito.Mockito.verify import teamcity.crowd.plugin.utils.LoggerFactory class TeamCityPluginCrowdClientTest { private val username = "username" private val password = "pass" private val loggerFactory = mock(LoggerFactory::class.java) private val logger = mock(Logger::class.java) @Test fun shouldAutheticateUser() { // Given val crowdClient = mock(CrowdClient::class.java) val user = mock(User::class.java) val loggerFactory = FakeLogger() val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) Mockito.`when`(tcCrowdClient.loginUserWithPassword(username, password)).thenReturn(user) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Assert assertEquals(user, theUser) } @Test fun shouldLogWarningAndReturnNullIfUserNotFound() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val userNotFoundException = UserNotFoundException("User not found") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(userNotFoundException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).warn("User with name [username] doesn't exists.", userNotFoundException) } @Test fun shouldLogInfoWhenUserAccountIsInactiveAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val inactiveAccountException = InactiveAccountException("Account inactive") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(inactiveAccountException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).info("User account [username] is inactive", inactiveAccountException) } @Test fun shouldLogInfoWhenUserCredentialsExpiredAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val expiredCredentialException = ExpiredCredentialException("Creds expired") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(expiredCredentialException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).info("User [username] credentials expired", expiredCredentialException) } @Test fun shouldLogErrorWhenCrowdClientApplicationPermissionsAreWrongAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val appPermissionsException = ApplicationPermissionException("App has no permissions") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(appPermissionsException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).error(PluginCrowdClient.APPLICATION_PERMISSIONS_MESSAGE, appPermissionsException) } @Test fun shouldLogErrorWhenCrowdClientAuthenticationFailsAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val invalidAuthException = InvalidAuthenticationException("Application authentication issue") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(invalidAuthException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).error(PluginCrowdClient.INVALID_AUTHENTICATION_MESSAGE, invalidAuthException) } @Test fun shouldLogErrorWhenCrowdOperationFailsAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val operationFailed = OperationFailedException("Bonkers!") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(operationFailed) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).error(PluginCrowdClient.OPERATION_FAILED_MESSAGE, operationFailed) } @Test fun shouldLogErrorWhenFailsWithUnknownReasonAndReturnNull() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val unknownException = RuntimeException("Bonkers!") Mockito.`when`(crowdClient.authenticateUser(username, password)).thenThrow(unknownException) // When val theUser = tcCrowdClient.loginUserWithPassword(username, password) // Then assertNull(theUser) verify(logger).error(PluginCrowdClient.UNKNOWN_ERROR_MESSAGE, unknownException) } @Test fun shouldReturnUsersGroups() { // Given val crowdClient = mock(CrowdClient::class.java) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, FakeLogger()) val theGroup = GroupEntity(username, "", GroupType.GROUP, true) Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenReturn(listOf(theGroup)) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertEquals(1, userGroups.size) assertEquals(theGroup, userGroups.first()) } @Test fun shouldLogWarningAndReturnEmptyListWhenRetrievingGroupsForUserThatIsNotInCrowd() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val userNotFoundException = UserNotFoundException("User not in crowd") Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenThrow(userNotFoundException) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertTrue(userGroups.isEmpty()) verify(logger).warn("User with name [$username] doesn't exists.", userNotFoundException) } @Test fun shouldLogErrorAndReturnEmptyListWhenOperationInCrowdFailed() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val operationFailedException = OperationFailedException("FooBar") Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenThrow(operationFailedException) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertTrue(userGroups.isEmpty()) verify(logger).error(PluginCrowdClient.OPERATION_FAILED_MESSAGE, operationFailedException) } @Test fun shouldLogErrorAndReturnEmptyListWhenCrowdApplicationAuthenticationFailed() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val invalidAuthException = InvalidAuthenticationException("Bonkers") Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenThrow(invalidAuthException) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertTrue(userGroups.isEmpty()) verify(logger).error(PluginCrowdClient.INVALID_AUTHENTICATION_MESSAGE, invalidAuthException) } @Test fun shouldLogErrorAndReturnEmptyListWhenCrowdApplicationHasInvalidPermissions() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val appPermissionsException = ApplicationPermissionException("Permissions are wrond") Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenThrow(appPermissionsException) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertTrue(userGroups.isEmpty()) verify(logger).error(PluginCrowdClient.APPLICATION_PERMISSIONS_MESSAGE, appPermissionsException) } @Test fun shouldLogErrorAndReturnEmptyListWhenUnknownErrorHappens() { // Given val crowdClient = mock(CrowdClient::class.java) Mockito.`when`(loggerFactory.getServerLogger()).thenReturn(logger) val tcCrowdClient = TeamCityPluginCrowdClient(crowdClient, loggerFactory) val unknownError = RuntimeException("Permissions are wrond") Mockito.`when`(crowdClient.getGroupsForUser(username, 0, Int.MAX_VALUE)).thenThrow(unknownError) // When val userGroups = tcCrowdClient.getUserGroups(username) // Then assertTrue(userGroups.isEmpty()) verify(logger).error(PluginCrowdClient.UNKNOWN_ERROR_MESSAGE, unknownError) } }
teamcity-crowd-plugin-server/src/test/kotlin/teamcity/crowd/plugin/TeamCityPluginCrowdClientTest.kt
3679638102
package com.bennyhuo.github.utils import android.support.v4.view.PagerAdapter /** * Created by benny on 7/9/17. */ class ViewPagerAdapterList<T>(val adapter: PagerAdapter): ArrayList<T>(){ override fun removeAt(index: Int): T { return super.removeAt(index).apply { adapter.notifyDataSetChanged() } } override fun remove(element: T): Boolean { val index = indexOf(element) return super.remove(element).apply { adapter.notifyDataSetChanged() } } override fun removeRange(fromIndex: Int, toIndex: Int) { super.removeRange(fromIndex, toIndex).apply { adapter.notifyDataSetChanged() } } override fun removeAll(elements: Collection<T>): Boolean { return super.removeAll(elements).apply { adapter.notifyDataSetChanged() } } override fun add(index: Int, element: T) { super.add(index, element) adapter.notifyDataSetChanged() } override fun add(element: T): Boolean { return super.add(element).apply { adapter.notifyDataSetChanged() } } override fun addAll(elements: Collection<T>): Boolean { return super.addAll(elements).apply { adapter.notifyDataSetChanged() } } override fun addAll(index: Int, elements: Collection<T>): Boolean { return super.addAll(index, elements).apply { adapter.notifyDataSetChanged() } } fun update(elements: Collection<T>){ super.clear() super.addAll(elements) adapter.notifyDataSetChanged() } }
Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/utils/ViewPagerAdapterList.kt
2309429015
package com.austinv11.planner.core.json.responses data class CreateAccountResponse(var token: String, var session_id: Long)
Core/src/main/kotlin/com/austinv11/planner/core/json/responses/CreateAccountResponse.kt
2230702496
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.databinding.twowaysample.ui import android.annotation.SuppressLint import androidx.lifecycle.ViewModelProviders import android.content.Context import androidx.databinding.DataBindingUtil import androidx.databinding.Observable import androidx.databinding.ObservableInt import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.util.Log import com.example.android.databinding.twowaysample.BR import com.example.android.databinding.twowaysample.R import com.example.android.databinding.twowaysample.data.IntervalTimerViewModel import com.example.android.databinding.twowaysample.data.IntervalTimerViewModelFactory import com.example.android.databinding.twowaysample.databinding.IntervalTimerBinding const val SHARED_PREFS_KEY = "timer" /** * This activity only takes care of binding a ViewModel to the layout. All UI calls are delegated * to the Data Binding library or Binding Adapters ([BindingAdapters]). * * Note that not all calls to the framework are removed, activities are still responsible for non-UI * interactions with the framework, like Shared Preferences or Navigation. */ class MainActivity : AppCompatActivity() { private val intervalTimerViewModel: IntervalTimerViewModel by lazy { ViewModelProviders.of(this, IntervalTimerViewModelFactory) .get(IntervalTimerViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: IntervalTimerBinding = DataBindingUtil.setContentView( this, R.layout.interval_timer) val viewmodel = intervalTimerViewModel binding.viewmodel = viewmodel /* Save the user settings whenever they change */ observeAndSaveTimePerSet( viewmodel.timePerWorkSet, R.string.prefs_timePerWorkSet) observeAndSaveTimePerSet( viewmodel.timePerRestSet, R.string.prefs_timePerRestSet) /* Number of sets needs a different */ observeAndSaveNumberOfSets(viewmodel) if (savedInstanceState == null) { /* If this is the first run, restore shared settings */ restorePreferences(viewmodel) observeAndSaveNumberOfSets(viewmodel) } } private fun observeAndSaveTimePerSet(timePerWorkSet: ObservableInt, prefsKey: Int) { timePerWorkSet.addOnPropertyChangedCallback( object : Observable.OnPropertyChangedCallback() { @SuppressLint("CommitPrefEdits") override fun onPropertyChanged(observable: Observable?, p1: Int) { Log.d("saveTimePerWorkSet", "Saving time-per-set preference") val sharedPref = getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return sharedPref.edit().apply { putInt(getString(prefsKey), (observable as ObservableInt).get()) commit() } } }) } private fun restorePreferences(viewModel: IntervalTimerViewModel) { val sharedPref = getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return val timePerWorkSetKey = getString(R.string.prefs_timePerWorkSet) var wasAnythingRestored = false if (sharedPref.contains(timePerWorkSetKey)) { viewModel.timePerWorkSet.set(sharedPref.getInt(timePerWorkSetKey, 100)) wasAnythingRestored = true } val timePerRestSetKey = getString(R.string.prefs_timePerRestSet) if (sharedPref.contains(timePerRestSetKey)) { viewModel.timePerRestSet.set(sharedPref.getInt(timePerRestSetKey, 50)) wasAnythingRestored = true } val numberOfSetsKey = getString(R.string.prefs_numberOfSets) if (sharedPref.contains(numberOfSetsKey)) { viewModel.numberOfSets = arrayOf(0, sharedPref.getInt(numberOfSetsKey, 5)) wasAnythingRestored = true } if (wasAnythingRestored) Log.d("saveTimePerWorkSet", "Preferences restored") viewModel.stopButtonClicked() } private fun observeAndSaveNumberOfSets(viewModel: IntervalTimerViewModel) { viewModel.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() { @SuppressLint("CommitPrefEdits") override fun onPropertyChanged(observable: Observable?, p1: Int) { if (p1 == BR.numberOfSets) { Log.d("saveTimePerWorkSet", "Saving number of sets preference") val sharedPref = getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE) ?: return sharedPref.edit().apply { putInt(getString(R.string.prefs_numberOfSets), viewModel.numberOfSets[1]) commit() } } } }) } }
TwoWaySample/app/src/main/java/com/example/android/databinding/twowaysample/ui/MainActivity.kt
3901408639
package com.chilangolabs.mdb.services import com.chilangolabs.mdb.utils.logd import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceIdService /** * @author Gorro. */ class FirebaseInstanceIDService : FirebaseInstanceIdService() { override fun onTokenRefresh() { super.onTokenRefresh() val refreshedToken = FirebaseInstanceId.getInstance().token logd("Refreshed Token $refreshedToken") //SendToken to Server //todo } }
app/src/main/java/com/chilangolabs/mdb/services/FirebaseInstanceIDService.kt
2282426931
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter import android.support.v7.widget.RecyclerView import android.text.TextUtils import android.text.method.LinkMovementMethod import android.util.SparseBooleanArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Space import android.widget.TextView import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.contains import de.vanita5.microblog.library.twitter.model.TranslationResult import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.iface.IGapSupportedAdapter import de.vanita5.twittnuker.adapter.iface.IItemCountsAdapter import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter import de.vanita5.twittnuker.constant.* import de.vanita5.twittnuker.extension.model.originalId import de.vanita5.twittnuker.extension.model.retweet_sort_id import de.vanita5.twittnuker.fragment.status.StatusFragment import de.vanita5.twittnuker.model.* import de.vanita5.twittnuker.util.StatusAdapterLinkClickHandler import de.vanita5.twittnuker.util.ThemeUtils import de.vanita5.twittnuker.util.TwidereLinkify import de.vanita5.twittnuker.view.holder.EmptyViewHolder import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder import de.vanita5.twittnuker.view.holder.status.DetailStatusViewHolder class StatusDetailsAdapter( val fragment: StatusFragment ) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(fragment.context, fragment.requestManager), IStatusesAdapter<List<ParcelableStatus>>, IItemCountsAdapter { override val twidereLinkify: TwidereLinkify override var statusClickListener: IStatusViewHolder.StatusClickListener? = null override val itemCounts = ItemCounts(ITEM_TYPES_SUM) override val nameFirst = preferences[nameFirstKey] override val mediaPreviewStyle = preferences[mediaPreviewStyleKey] override val linkHighlightingStyle = preferences[linkHighlightOptionKey] override val lightFont = preferences[lightFontKey] override val mediaPreviewEnabled = preferences[mediaPreviewKey] override val sensitiveContentEnabled = preferences[displaySensitiveContentsKey] override val useStarsForLikes = preferences[iWantMyStarsBackKey] private val inflater: LayoutInflater private val cardBackgroundColor: Int private val showCardActions = !preferences[hideCardActionsKey] private var recyclerView: RecyclerView? = null private var detailMediaExpanded: Boolean = false var status: ParcelableStatus? = null internal set var translationResult: TranslationResult? = null internal set(translation) { if (translation == null || status?.originalId != translation.id) { field = null } else { field = translation } notifyDataSetChanged() } var statusActivity: StatusFragment.StatusActivity? = null internal set(value) { val status = status ?: return if (value != null && !value.isStatus(status)) { return } field = value val statusIndex = getIndexStart(ITEM_IDX_STATUS) notifyItemChanged(statusIndex, value) } var statusAccount: AccountDetails? = null internal set private var data: List<ParcelableStatus>? = null private var replyError: CharSequence? = null private var conversationError: CharSequence? = null private var replyStart: Int = 0 private var showingActionCardPosition = RecyclerView.NO_POSITION private val showingFullTextStates = SparseBooleanArray() init { setHasStableIds(true) val context = fragment.activity // There's always a space at the end of the list itemCounts[ITEM_IDX_SPACE] = 1 itemCounts[ITEM_IDX_STATUS] = 1 itemCounts[ITEM_IDX_CONVERSATION_LOAD_MORE] = 1 itemCounts[ITEM_IDX_REPLY_LOAD_MORE] = 1 inflater = LayoutInflater.from(context) cardBackgroundColor = ThemeUtils.getCardBackgroundColor(context, preferences[themeBackgroundOptionKey], preferences[themeBackgroundAlphaKey]) val listener = StatusAdapterLinkClickHandler<List<ParcelableStatus>>(context, preferences) listener.setAdapter(this) twidereLinkify = TwidereLinkify(listener) } override fun getStatus(position: Int, raw: Boolean): ParcelableStatus { when (getItemCountIndex(position, raw)) { ITEM_IDX_CONVERSATION -> { var idx = position - getIndexStart(ITEM_IDX_CONVERSATION) if (data!![idx].is_filtered) idx++ return data!![idx] } ITEM_IDX_REPLY -> { var idx = position - getIndexStart(ITEM_IDX_CONVERSATION) - getTypeCount(ITEM_IDX_CONVERSATION) - getTypeCount(ITEM_IDX_STATUS) + replyStart if (data!![idx].is_filtered) idx++ return data!![idx] } ITEM_IDX_STATUS -> { return status!! } } throw IndexOutOfBoundsException("index: $position") } fun getIndexStart(index: Int): Int { if (index == 0) return 0 return itemCounts.getItemStartPosition(index) } override fun getStatusId(position: Int, raw: Boolean): String { return getStatus(position, raw).id } override fun getStatusTimestamp(position: Int, raw: Boolean): Long { return getStatus(position, raw).timestamp } override fun getStatusPositionKey(position: Int, raw: Boolean): Long { val status = getStatus(position, raw) return if (status.position_key > 0) status.timestamp else getStatusTimestamp(position, raw) } override fun getAccountKey(position: Int, raw: Boolean) = getStatus(position, raw).account_key override fun findStatusById(accountKey: UserKey, statusId: String): ParcelableStatus? { if (status != null && accountKey == status!!.account_key && TextUtils.equals(statusId, status!!.id)) { return status } return data?.firstOrNull { accountKey == it.account_key && TextUtils.equals(it.id, statusId) } } override fun getStatusCount(raw: Boolean): Int { return getTypeCount(ITEM_IDX_CONVERSATION) + getTypeCount(ITEM_IDX_STATUS) + getTypeCount(ITEM_IDX_REPLY) } override fun isCardActionsShown(position: Int): Boolean { if (position == RecyclerView.NO_POSITION) return showCardActions return showCardActions || showingActionCardPosition == position } override fun showCardActions(position: Int) { if (showingActionCardPosition != RecyclerView.NO_POSITION) { notifyItemChanged(showingActionCardPosition) } showingActionCardPosition = position if (position != RecyclerView.NO_POSITION) { notifyItemChanged(position) } } override fun isFullTextVisible(position: Int): Boolean { return showingFullTextStates.get(position) } override fun setFullTextVisible(position: Int, visible: Boolean) { showingFullTextStates.put(position, visible) if (position != RecyclerView.NO_POSITION) { notifyItemChanged(position) } } override fun setData(data: List<ParcelableStatus>?): Boolean { val status = this.status ?: return false val changed = this.data != data this.data = data if (data == null || data.isEmpty()) { setTypeCount(ITEM_IDX_CONVERSATION, 0) setTypeCount(ITEM_IDX_REPLY, 0) replyStart = -1 } else { val sortId = if (status.is_retweet) { status.retweet_sort_id } else { status.sort_id } var conversationCount = 0 var replyCount = 0 var replyStart = -1 data.forEachIndexed { i, item -> if (item.sort_id < sortId) { if (!item.is_filtered) { conversationCount++ } } else if (status.id == item.id) { this.status = item } else if (item.sort_id > sortId) { if (replyStart < 0) { replyStart = i } if (!item.is_filtered) { replyCount++ } } } setTypeCount(ITEM_IDX_CONVERSATION, conversationCount) setTypeCount(ITEM_IDX_REPLY, replyCount) this.replyStart = replyStart } notifyDataSetChanged() updateItemDecoration() return changed } override val showAccountsColor: Boolean get() = false var isDetailMediaExpanded: Boolean get() { if (detailMediaExpanded) return true if (mediaPreviewEnabled) { val status = this.status return status != null && (sensitiveContentEnabled || !status.is_possibly_sensitive) } return false } set(expanded) { detailMediaExpanded = expanded notifyDataSetChanged() updateItemDecoration() } override fun isGapItem(position: Int): Boolean { return false } override val gapClickListener: IGapSupportedAdapter.GapClickListener? get() = statusClickListener override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { when (viewType) { VIEW_TYPE_DETAIL_STATUS -> { val view = inflater.inflate(R.layout.header_status, parent, false) view.setBackgroundColor(cardBackgroundColor) return DetailStatusViewHolder(this, view) } VIEW_TYPE_LIST_STATUS -> { return ListParcelableStatusesAdapter.createStatusViewHolder(this, inflater, parent) } VIEW_TYPE_CONVERSATION_LOAD_INDICATOR, VIEW_TYPE_REPLIES_LOAD_INDICATOR -> { val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false) return LoadIndicatorViewHolder(view) } VIEW_TYPE_SPACE -> { return EmptyViewHolder(Space(context)) } VIEW_TYPE_REPLY_ERROR -> { val view = inflater.inflate(R.layout.adapter_item_status_error, parent, false) return StatusErrorItemViewHolder(view) } } return null } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: List<Any>) { var handled = false when (holder.itemViewType) { VIEW_TYPE_DETAIL_STATUS -> { holder as DetailStatusViewHolder payloads.forEach { it -> when (it) { is StatusFragment.StatusActivity -> { holder.updateStatusActivity(it) } is ParcelableStatus -> { holder.displayStatus(statusAccount, status, statusActivity, translationResult) } } handled = true } } } if (handled) return super.onBindViewHolder(holder, position, payloads) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder.itemViewType) { VIEW_TYPE_DETAIL_STATUS -> { val status = getStatus(position) val detailHolder = holder as DetailStatusViewHolder detailHolder.displayStatus(statusAccount, status, statusActivity, translationResult) } VIEW_TYPE_LIST_STATUS -> { val status = getStatus(position) val statusHolder = holder as IStatusViewHolder // Display 'in reply to' for first item // useful to indicate whether first tweet has reply or not // We only display that indicator for first conversation item val itemType = getItemType(position) val displayInReplyTo = itemType == ITEM_IDX_CONVERSATION && position - getItemTypeStart(position) == 0 statusHolder.display(status = status, displayInReplyTo = displayInReplyTo) } VIEW_TYPE_REPLY_ERROR -> { val errorHolder = holder as StatusErrorItemViewHolder errorHolder.showError(replyError!!) } VIEW_TYPE_CONVERSATION_ERROR -> { val errorHolder = holder as StatusErrorItemViewHolder errorHolder.showError(conversationError!!) } VIEW_TYPE_CONVERSATION_LOAD_INDICATOR -> { val indicatorHolder = holder as LoadIndicatorViewHolder indicatorHolder.setLoadProgressVisible(isConversationsLoading) } VIEW_TYPE_REPLIES_LOAD_INDICATOR -> { val indicatorHolder = holder as LoadIndicatorViewHolder indicatorHolder.setLoadProgressVisible(isRepliesLoading) } } } override fun getItemViewType(position: Int): Int { return getItemViewTypeByItemType(getItemType(position)) } override fun addGapLoadingId(id: ObjectId) { } override fun removeGapLoadingId(id: ObjectId) { } private fun getItemViewTypeByItemType(type: Int): Int { when (type) { ITEM_IDX_CONVERSATION, ITEM_IDX_REPLY -> return VIEW_TYPE_LIST_STATUS ITEM_IDX_CONVERSATION_LOAD_MORE -> return VIEW_TYPE_CONVERSATION_LOAD_INDICATOR ITEM_IDX_REPLY_LOAD_MORE -> return VIEW_TYPE_REPLIES_LOAD_INDICATOR ITEM_IDX_STATUS -> return VIEW_TYPE_DETAIL_STATUS ITEM_IDX_SPACE -> return VIEW_TYPE_SPACE ITEM_IDX_REPLY_ERROR -> return VIEW_TYPE_REPLY_ERROR ITEM_IDX_CONVERSATION_ERROR -> return VIEW_TYPE_CONVERSATION_ERROR } throw IllegalStateException() } private fun getItemCountIndex(position: Int, raw: Boolean): Int { return itemCounts.getItemCountIndex(position) } fun getItemType(position: Int): Int { var typeStart = 0 for (type in 0 until ITEM_TYPES_SUM) { val typeCount = getTypeCount(type) val typeEnd = typeStart + typeCount if (position in typeStart until typeEnd) return type typeStart = typeEnd } throw IllegalStateException("Unknown position " + position) } fun getItemTypeStart(position: Int): Int { var typeStart = 0 for (type in 0 until ITEM_TYPES_SUM) { val typeCount = getTypeCount(type) val typeEnd = typeStart + typeCount if (position in typeStart until typeEnd) return typeStart typeStart = typeEnd } throw IllegalStateException() } override fun getItemId(position: Int): Long { val countIndex = getItemCountIndex(position) when (countIndex) { ITEM_IDX_CONVERSATION, ITEM_IDX_STATUS, ITEM_IDX_REPLY -> { val status = getStatus(position) val hashCode = ParcelableStatus.calculateHashCode(status.account_key, status.id) return (countIndex.toLong() shl 32) or hashCode.toLong() } } val countPos = (position - getItemStartPosition(countIndex)).toLong() return (countIndex.toLong() shl 32) or countPos } override fun getItemCount(): Int { if (status == null) return 0 return itemCounts.itemCount } override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) { super.onAttachedToRecyclerView(recyclerView) this.recyclerView = recyclerView } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView?) { super.onDetachedFromRecyclerView(recyclerView) this.recyclerView = null } private fun setTypeCount(idx: Int, size: Int) { itemCounts[idx] = size notifyDataSetChanged() } fun getTypeCount(idx: Int): Int { return itemCounts[idx] } fun setReplyError(error: CharSequence?) { replyError = error setTypeCount(ITEM_IDX_REPLY_ERROR, if (error != null) 1 else 0) updateItemDecoration() } fun setConversationError(error: CharSequence?) { conversationError = error setTypeCount(ITEM_IDX_CONVERSATION_ERROR, if (error != null) 1 else 0) updateItemDecoration() } fun setStatus(status: ParcelableStatus, account: AccountDetails?): Boolean { val oldStatus = this.status val oldAccount = this.statusAccount val changed = oldStatus != status && oldAccount != account this.status = status this.statusAccount = account if (changed) { notifyDataSetChanged() updateItemDecoration() } else { val statusIndex = getIndexStart(ITEM_IDX_STATUS) notifyItemChanged(statusIndex, status) } return changed } fun updateItemDecoration() { if (recyclerView == null) return } fun getFirstPositionOfItem(itemIdx: Int): Int { var position = 0 for (i in 0 until ITEM_TYPES_SUM) { if (itemIdx == i) return position position += getTypeCount(i) } return RecyclerView.NO_POSITION } fun getData(): List<ParcelableStatus>? { return data } var isConversationsLoading: Boolean get() = ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition set(loading) { if (loading) { loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.START } else { loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.START.inv() } updateItemDecoration() } var isRepliesLoading: Boolean get() = ILoadMoreSupportAdapter.END in loadMoreIndicatorPosition set(loading) { if (loading) { loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.END } else { loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.END.inv() } updateItemDecoration() } class StatusErrorItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textView = itemView.findViewById<TextView>(android.R.id.text1) init { textView.movementMethod = LinkMovementMethod.getInstance() textView.linksClickable = true } fun showError(text: CharSequence) { textView.text = text } } companion object { const val VIEW_TYPE_LIST_STATUS = 0 const val VIEW_TYPE_DETAIL_STATUS = 1 const val VIEW_TYPE_CONVERSATION_LOAD_INDICATOR = 2 const val VIEW_TYPE_REPLIES_LOAD_INDICATOR = 3 const val VIEW_TYPE_REPLY_ERROR = 4 const val VIEW_TYPE_CONVERSATION_ERROR = 5 const val VIEW_TYPE_SPACE = 6 const val VIEW_TYPE_EMPTY = 7 const val ITEM_IDX_CONVERSATION_LOAD_MORE = 0 const val ITEM_IDX_CONVERSATION_ERROR = 1 const val ITEM_IDX_CONVERSATION = 2 const val ITEM_IDX_STATUS = 3 const val ITEM_IDX_REPLY = 4 const val ITEM_IDX_REPLY_ERROR = 5 const val ITEM_IDX_REPLY_LOAD_MORE = 6 const val ITEM_IDX_SPACE = 7 const val ITEM_TYPES_SUM = 8 } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/StatusDetailsAdapter.kt
1970625402
package com.bl_lia.kirakiratter.presentation.transform import android.content.Context import android.graphics.* import android.os.Build import android.support.annotation.ColorRes import android.support.v4.content.ContextCompat import com.squareup.picasso.Transformation class AvatarTransformation(val context: Context, @ColorRes val borderColor: Int) : Transformation { override fun key(): String = "avatar" override fun transform(source: Bitmap?): Bitmap? { if (source == null) return source if (Build.VERSION.SDK_INT < 21) return source val size = Math.min(source.width, source.height) val x = (source.width - size) / 2 val y = (source.height - size) / 2 val squareBitmap = Bitmap.createBitmap(source, x, y, size, size) if (squareBitmap != source) { source.recycle() } val config = source.config ?: Bitmap.Config.ARGB_8888 val bitmap = Bitmap.createBitmap(size, size, config) val canvas = Canvas(bitmap) val paint = Paint() val shader = BitmapShader(squareBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true val borader: Int = 5 val r: Float = 10F val paintBg = Paint().apply { color = ContextCompat.getColor(context, borderColor) isAntiAlias = true } canvas.drawRoundRect(x.toFloat(), y.toFloat(), size.toFloat(), size.toFloat(), r, r, paintBg) canvas.drawRoundRect((x + borader).toFloat(), (y + borader).toFloat(), (size - borader).toFloat(), (size - borader).toFloat(), r, r, paint) squareBitmap.recycle() return bitmap } }
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/transform/AvatarTransformation.kt
2110256141
package com.robohorse.gpversionchecker.utils import java.text.ParseException import java.text.SimpleDateFormat import java.util.* class DateFormatUtils { private val formatter = SimpleDateFormat(DATE_FORMAT, Locale.UK) fun formatTodayDate(): Date? { val today = Date(System.currentTimeMillis()) try { return formatter.parse(formatter.format(today)) } catch (e: ParseException) { e.printStackTrace() } return today } } private const val DATE_FORMAT = "dd/MM/yyyy"
gpversionchecker/src/main/kotlin/com/robohorse/gpversionchecker/utils/DateFormatUtils.kt
335381865
/* * 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.compose.foundation.text import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.util.fastAny import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch internal interface TextDragObserver { /** * Called as soon as a down event is received. If the pointer eventually moves while remaining * down, a drag gesture may be started. After this method: * - [onUp] will always be called eventually, once the pointer is released. * - [onStart] _may_ be called, if there is a drag that exceeds touch slop. * * This method will not be called before [onStart] in the case when a down event happens that * may not result in a drag, e.g. on the down before a long-press that starts a selection. */ fun onDown(point: Offset) /** * Called after [onDown] if an up event is received without dragging. */ fun onUp() /** * Called once a drag gesture has started, which means touch slop has been exceeded. * [onDown] _may_ be called before this method if the down event could not have * started a different gesture. */ fun onStart(startPoint: Offset) fun onDrag(delta: Offset) fun onStop() fun onCancel() } internal suspend fun PointerInputScope.detectDragGesturesAfterLongPressWithObserver( observer: TextDragObserver ) = detectDragGesturesAfterLongPress( onDragEnd = { observer.onStop() }, onDrag = { _, offset -> observer.onDrag(offset) }, onDragStart = { observer.onStart(it) }, onDragCancel = { observer.onCancel() } ) /** * Detects gesture events for a [TextDragObserver], including both initial down events and drag * events. */ internal suspend fun PointerInputScope.detectDownAndDragGesturesWithObserver( observer: TextDragObserver ) { coroutineScope { launch { detectPreDragGesturesWithObserver(observer) } launch { detectDragGesturesWithObserver(observer) } } } /** * Detects initial down events and calls [TextDragObserver.onDown] and * [TextDragObserver.onUp]. */ private suspend fun PointerInputScope.detectPreDragGesturesWithObserver( observer: TextDragObserver ) { awaitEachGesture { val down = awaitFirstDown() observer.onDown(down.position) // Wait for that pointer to come up. do { val event = awaitPointerEvent() } while (event.changes.fastAny { it.id == down.id && it.pressed }) observer.onUp() } } /** * Detects drag gestures for a [TextDragObserver]. */ private suspend fun PointerInputScope.detectDragGesturesWithObserver( observer: TextDragObserver ) { detectDragGestures( onDragEnd = { observer.onStop() }, onDrag = { _, offset -> observer.onDrag(offset) }, onDragStart = { observer.onStart(it) }, onDragCancel = { observer.onCancel() } ) }
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/LongPressTextDragObserver.kt
3650523742
package au.com.codeka.warworlds.common.sim import au.com.codeka.warworlds.common.proto.* import com.google.common.collect.Lists import java.util.ArrayList /** * Helper for making a star proto with default options if we don't care about all the required * fields. Only the ID is required here. */ fun makeStar( id: Long, name: String = "Test star", classification: Star.Classification = Star.Classification.BLUE, size: Int = 1, offset_x: Int = 0, offset_y: Int = 0, sector_x: Long = 0L, sector_y: Long = 0L, planets: List<Planet> = ArrayList<Planet>(), fleets: List<Fleet> = ArrayList<Fleet>(), empire_stores: List<EmpireStorage> = ArrayList<EmpireStorage>() ): Star { return Star( id, name = name, classification = classification, size = size, offset_x = offset_x, offset_y = offset_y, sector_x = sector_x, sector_y = sector_y, planets = planets, fleets = fleets, empire_stores = empire_stores) } /** * Initializes some designs. */ fun initDesign() { DesignDefinitions.init( Designs( designs = Lists.newArrayList( Design( type = Design.DesignType.COLONY_SHIP, design_kind = Design.DesignKind.SHIP, display_name = "Colony ship", description = "A colony ship", image_url = "", fuel_size = 800, build_cost = Design.BuildCost( minerals = 100f, population = 120f)), Design( type = Design.DesignType.SCOUT, design_kind = Design.DesignKind.SHIP, display_name = "Scout ship", description = "A scout ship", image_url = "", fuel_size = 100, build_cost = Design.BuildCost( minerals = 10f, population = 12f)) )) ) }
common/src/test/kotlin/au/com/codeka/warworlds/common/sim/Helpers.kt
1301153086
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model /** * This interface is implemented by all model classes, that can be observed. * In case of a change they will notify all registered listeners. * * @param T type of the object that is passed in case of a change */ interface ObservableModel<T> { /** * Notifies all listeners. * * @param obj The object that has changed. */ fun notifyListeners(obj: T) /** * Registers a listeners to be notified about all future changes. * * @param listener the listener to register */ fun registerListener(listener: ModelChangeListener<T>) /** * Removes an listner. If listener is not found nothing happens. * * @param listener the listener to remove */ fun removeListener(listener: ModelChangeListener<T>) }
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/ObservableModel.kt
1962286162
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.surroundWith.expression import org.rust.ide.surroundWith.RsSurrounderTestBase class RsWithWhileExpSurrounderTest : RsSurrounderTestBase(RsWithWhileExpSurrounder()) { fun `test simple`() = doTest(""" fn main() { <selection>true</selection> } """, """ fn main() { while true {<caret>} } """) fun `test call`() = doTest(""" fn func() -> bool { false } fn main() { <selection>func()</selection> } """, """ fn func() -> bool { false } fn main() { while func() {<caret>} } """) fun `test correct post process`() = doTest(""" fn main() { <selection>true</selection> 1; } """, """ fn main() { while true {<caret>} 1; } """) fun `test number`() = doTestNotApplicable(""" fn main() { <selection>1234</selection> } """) fun `test number call`() = doTestNotApplicable(""" fn func() -> i32 { 1234 } fn main() { <selection>func()</selection> } """) }
src/test/kotlin/org/rust/ide/surroundWith/expression/RsWithWhileExpSurrounderTest.kt
1246076527
package com.teamwizardry.librarianlib.foundation.recipe.kotlin import com.teamwizardry.librarianlib.core.util.loc import net.minecraft.data.IFinishedRecipe import net.minecraft.data.ShapelessRecipeBuilder import net.minecraft.util.IItemProvider import java.util.function.Consumer @DslMarker internal annotation class RecipeDslMarker @RecipeDslMarker public class RecipeDslContext(private val consumer: Consumer<IFinishedRecipe>, private val modid: String) { public fun shapeless( id: String, result: IItemProvider, count: Int = 1, config: ShapelessRecipeDsl.() -> Unit ) { val dsl = ShapelessRecipeDsl(result, count) dsl.config() dsl.buildRecipe(consumer, loc(modid, id)) } public fun shaped( id: String, result: IItemProvider, count: Int = 1, config: ShapedRecipeDsl.() -> Unit ) { val dsl = ShapedRecipeDsl(result, count) dsl.config() dsl.buildRecipe(consumer, loc(modid, id)) } }
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/recipe/kotlin/RecipeDsl.kt
657956154
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.util.InspectionMessage import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.rust.ide.annotator.fixes.AddTypeFix import org.rust.ide.inspections.fixes.SubstituteTextFix import org.rust.lang.core.CompilerFeature.Companion.C_VARIADIC import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.types.type import org.rust.lang.utils.RsDiagnostic import org.rust.lang.utils.addToHolder import org.rust.openapiext.forEachChild import org.rust.stdext.capitalized import org.rust.stdext.pluralize import java.lang.Integer.max class RsSyntaxErrorsAnnotator : AnnotatorBase() { override fun annotateInternal(element: PsiElement, holder: AnnotationHolder) { when (element) { is RsExternAbi -> checkExternAbi(holder, element) is RsItemElement -> { checkItem(holder, element) when (element) { is RsFunction -> checkFunction(holder, element) is RsStructItem -> checkStructItem(holder, element) is RsTypeAlias -> checkTypeAlias(holder, element) is RsConstant -> checkConstant(holder, element) is RsModItem -> checkModItem(holder, element) is RsModDeclItem -> checkModDeclItem(holder, element) is RsForeignModItem -> checkForeignModItem(holder, element) } } is RsMacro -> checkMacro(holder, element) is RsMacroCall -> checkMacroCall(holder, element) is RsValueParameterList -> checkValueParameterList(holder, element) is RsValueParameter -> checkValueParameter(holder, element) is RsTypeParameterList -> checkTypeParameterList(holder, element) is RsTypeArgumentList -> checkTypeArgumentList(holder, element) is RsLetExpr -> checkLetExpr(holder, element) } } } private fun checkItem(holder: AnnotationHolder, item: RsItemElement) { checkItemOrMacro(item, item.itemKindName.pluralize().capitalized(), item.itemDefKeyword, holder) } private fun checkMacro(holder: AnnotationHolder, element: RsMacro) = checkItemOrMacro(element, "Macros", element.macroRules, holder) private fun checkItemOrMacro(item: RsElement, itemName: String, highlightElement: PsiElement, holder: AnnotationHolder) { if (item !is RsAbstractable) { val parent = item.context val owner = if (parent is RsMembers) parent.context else parent if (owner is RsItemElement && (owner is RsForeignModItem || owner is RsTraitOrImpl)) { holder.newAnnotation(HighlightSeverity.ERROR, "$itemName are not allowed inside ${owner.article} ${owner.itemKindName}") .range(highlightElement).create() } } if (item !is RsAbstractable && item !is RsTraitOrImpl) { denyDefaultKeyword(item, holder, itemName) } } private fun denyDefaultKeyword(item: RsElement, holder: AnnotationHolder, itemName: String) { deny( item.node.findChildByType(RsElementTypes.DEFAULT)?.psi, holder, "$itemName cannot have the `default` qualifier" ) } private fun checkMacroCall(holder: AnnotationHolder, element: RsMacroCall) { denyDefaultKeyword(element, holder, "Macro invocations") } private fun checkFunction(holder: AnnotationHolder, fn: RsFunction) { when (fn.owner) { is RsAbstractableOwner.Free -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") } is RsAbstractableOwner.Trait -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.vis, holder, "${fn.title} cannot have the `pub` qualifier") fn.const?.let { RsDiagnostic.ConstTraitFnError(it).addToHolder(holder) } } is RsAbstractableOwner.Impl -> { require(fn.block, holder, "${fn.title} must have a body", fn.lastChild) if (fn.default != null) { deny(fn.vis, holder, "Default ${fn.title.firstLower} cannot have the `pub` qualifier") } } is RsAbstractableOwner.Foreign -> { deny(fn.default, holder, "${fn.title} cannot have the `default` qualifier") deny(fn.block, holder, "${fn.title} cannot have a body") deny(fn.const, holder, "${fn.title} cannot have the `const` qualifier") deny(fn.unsafe, holder, "${fn.title} cannot have the `unsafe` qualifier") deny(fn.externAbi, holder, "${fn.title} cannot have an extern ABI") } } } private fun checkStructItem(holder: AnnotationHolder, struct: RsStructItem) { if (struct.kind == RsStructKind.UNION && struct.tupleFields != null) { deny(struct.tupleFields, holder, "Union cannot be tuple-like") } } private fun checkTypeAlias(holder: AnnotationHolder, ta: RsTypeAlias) { val title = "Type `${ta.identifier.text}`" when (val owner = ta.owner) { is RsAbstractableOwner.Free -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") require(ta.typeReference, holder, "$title should have a body`", ta) } is RsAbstractableOwner.Trait -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") } is RsAbstractableOwner.Impl -> { if (owner.isInherent) { deny(ta.default, holder, "$title cannot have the `default` qualifier") } deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") require(ta.typeReference, holder, "$title should have a body", ta) } RsAbstractableOwner.Foreign -> { deny(ta.default, holder, "$title cannot have the `default` qualifier") deny(ta.typeParameterList, holder, "$title cannot have generic parameters") deny(ta.whereClause, holder, "$title cannot have `where` clause") deny(ta.typeParamBounds, holder, "Bounds on $title have no effect") deny(ta.typeReference, holder, "$title cannot have a body", ta) } } } private fun checkConstant(holder: AnnotationHolder, const: RsConstant) { val name = const.nameLikeElement.text val title = if (const.static != null) "Static constant `$name`" else "Constant `$name`" when (const.owner) { is RsAbstractableOwner.Free -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.expr, holder, "$title must have a value", const) } is RsAbstractableOwner.Foreign -> { deny(const.default, holder, "$title cannot have the `default` qualifier") require(const.static, holder, "Only static constants are allowed in extern blocks", const.const) deny(const.expr, holder, "Static constants in extern blocks cannot have values", const.eq, const.expr) } is RsAbstractableOwner.Trait -> { deny(const.vis, holder, "$title cannot have the `pub` qualifier") deny(const.default, holder, "$title cannot have the `default` qualifier") deny(const.static, holder, "Static constants are not allowed in traits") } is RsAbstractableOwner.Impl -> { deny(const.static, holder, "Static constants are not allowed in impl blocks") require(const.expr, holder, "$title must have a value", const) } } checkConstantType(holder, const) } private fun checkConstantType(holder: AnnotationHolder, element: RsConstant) { if (element.colon == null && element.typeReference == null) { val typeText = if (element.isConst) { "const" } else { "static" } val message = "Missing type for `$typeText` item" val annotation = holder.newAnnotation(HighlightSeverity.ERROR, message) .range(element.textRange) val expr = element.expr if (expr != null) { annotation.withFix(AddTypeFix(element.nameLikeElement, expr.type)) } annotation.create() } } private fun checkValueParameterList(holder: AnnotationHolder, params: RsValueParameterList) { val fn = params.parent as? RsFunction ?: return when (fn.owner) { is RsAbstractableOwner.Free -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") checkVariadic(holder, fn, params.variadic?.dotdotdot) } is RsAbstractableOwner.Trait, is RsAbstractableOwner.Impl -> { deny(params.variadic?.dotdotdot, holder, "${fn.title} cannot be variadic") } RsAbstractableOwner.Foreign -> { deny(params.selfParameter, holder, "${fn.title} cannot have `self` parameter") checkDot3Parameter(holder, params.variadic?.dotdotdot) } } } private fun checkVariadic(holder: AnnotationHolder, fn: RsFunction, dot3: PsiElement?) { if (dot3 == null) return if (fn.isUnsafe && fn.abiName == "C") { C_VARIADIC.check(holder, dot3, "C-variadic functions") } else { deny(dot3, holder, "${fn.title} cannot be variadic") } } private fun checkDot3Parameter(holder: AnnotationHolder, dot3: PsiElement?) { if (dot3 == null) return dot3.rightVisibleLeaves .first { if (it.text != ")") { holder.newAnnotation(HighlightSeverity.ERROR, "`...` must be last in argument list for variadic function") .range(it).create() } return } } private fun checkValueParameter(holder: AnnotationHolder, param: RsValueParameter) { val fn = param.parent.parent as? RsFunction ?: return when (fn.owner) { is RsAbstractableOwner.Free, is RsAbstractableOwner.Impl, is RsAbstractableOwner.Foreign -> { require(param.pat, holder, "${fn.title} cannot have anonymous parameters", param) } is RsAbstractableOwner.Trait -> { denyType<RsPatTup>(param.pat, holder, "${fn.title} cannot have tuple parameters", param) if (param.pat == null) { val message = "Anonymous functions parameters are deprecated (RFC 1685)" val annotation = holder.newAnnotation(HighlightSeverity.WARNING, message) val fix = SubstituteTextFix.replace( "Add dummy parameter name", param.containingFile, param.textRange, "_: ${param.text}" ) val descriptor = InspectionManager.getInstance(param.project) .createProblemDescriptor(param, message, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true) annotation.newLocalQuickFix(fix, descriptor).registerFix().create() } } } } private fun checkTypeParameterList(holder: AnnotationHolder, element: RsTypeParameterList) { if (element.parent is RsImplItem || element.parent is RsFunction) { element.typeParameterList .mapNotNull { it.typeReference } .forEach { holder.newAnnotation( HighlightSeverity.ERROR, "Defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions" ).range(it).create() } } else { val lastNotDefaultIndex = max(element.typeParameterList.indexOfLast { it.typeReference == null }, 0) element.typeParameterList .take(lastNotDefaultIndex) .filter { it.typeReference != null } .forEach { holder.newAnnotation(HighlightSeverity.ERROR, "Type parameters with a default must be trailing") .range(it).create() } } checkTypeList(element, "parameters", holder) } private fun checkTypeArgumentList(holder: AnnotationHolder, args: RsTypeArgumentList) { checkTypeList(args, "arguments", holder) val startOfAssocTypeBindings = args.assocTypeBindingList.firstOrNull()?.textOffset ?: return for (generic in args.lifetimeList + args.typeReferenceList + args.exprList) { if (generic.textOffset > startOfAssocTypeBindings) { holder.newAnnotation(HighlightSeverity.ERROR, "Generic arguments must come before the first constraint") .range(generic).create() } } } private fun checkTypeList(typeList: PsiElement, elementsName: String, holder: AnnotationHolder) { var kind = TypeKind.LIFETIME typeList.forEachChild { child -> val newKind = TypeKind.forType(child) ?: return@forEachChild if (newKind.canStandAfter(kind)) { kind = newKind } else { val newStateName = newKind.presentableName.capitalized() holder.newAnnotation( HighlightSeverity.ERROR, "$newStateName $elementsName must be declared prior to ${kind.presentableName} $elementsName" ).range(child).create() } } } private fun checkExternAbi(holder: AnnotationHolder, element: RsExternAbi) { val litExpr = element.litExpr ?: return val abyLiteralKind = litExpr.kind ?: return if (abyLiteralKind !is RsLiteralKind.String) { holder.newAnnotation(HighlightSeverity.ERROR, "Non-string ABI literal").range(litExpr).create() } } private fun checkModDeclItem(holder: AnnotationHolder, element: RsModDeclItem) { checkInvalidUnsafe(holder, element.unsafe, "Module") } private fun checkModItem(holder: AnnotationHolder, element: RsModItem) { checkInvalidUnsafe(holder, element.unsafe, "Module") } private fun checkForeignModItem(holder: AnnotationHolder, element: RsForeignModItem) { checkInvalidUnsafe(holder, element.unsafe, "Extern block") } private fun checkInvalidUnsafe(holder: AnnotationHolder, unsafe: PsiElement?, itemName: String) { if (unsafe != null) { holder.newAnnotation(HighlightSeverity.ERROR, "$itemName cannot be declared unsafe").range(unsafe).create() } } private fun checkLetExpr(holder: AnnotationHolder, element: RsLetExpr) { var ancestor = element.parent while (when (ancestor) { is RsCondition, is RsMatchArmGuard -> return is RsBinaryExpr -> ancestor.binaryOp.andand != null else -> false }) { ancestor = ancestor.parent } deny(element, holder, "`let` expressions are not supported here") } private enum class TypeKind { LIFETIME, TYPE, CONST; val presentableName: String get() = name.lowercase() fun canStandAfter(prev: TypeKind): Boolean = this !== LIFETIME || prev === LIFETIME companion object { fun forType(seekingElement: PsiElement): TypeKind? = when (seekingElement) { is RsLifetimeParameter, is RsLifetime -> LIFETIME is RsTypeParameter, is RsTypeReference -> TYPE is RsConstParameter, is RsExpr -> CONST else -> null } } } private fun require(el: PsiElement?, holder: AnnotationHolder, message: String, vararg highlightElements: PsiElement?): Unit? = if (el != null || highlightElements.combinedRange == null) null else { holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange!!).create() } private fun deny( el: PsiElement?, holder: AnnotationHolder, @InspectionMessage message: String, vararg highlightElements: PsiElement? ) { if (el == null) return holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange ?: el.textRange).create() } private inline fun <reified T : RsElement> denyType( el: PsiElement?, holder: AnnotationHolder, @InspectionMessage message: String, vararg highlightElements: PsiElement? ) { if (el !is T) return holder.newAnnotation(HighlightSeverity.ERROR, message) .range(highlightElements.combinedRange ?: el.textRange).create() } private val Array<out PsiElement?>.combinedRange: TextRange? get() = if (isEmpty()) null else filterNotNull() .map { it.textRange } .reduce(TextRange::union) private val PsiElement.rightVisibleLeaves: Sequence<PsiElement> get() = generateSequence(PsiTreeUtil.nextVisibleLeaf(this)) { el -> PsiTreeUtil.nextVisibleLeaf(el) } private val String.firstLower: String get() = if (isEmpty()) this else this[0].lowercaseChar() + substring(1)
src/main/kotlin/org/rust/ide/annotator/RsSyntaxErrorsAnnotator.kt
2112699507
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions.visibility import org.rust.ide.intentions.RsIntentionTestBase class MakePubCrateIntentionTest : RsIntentionTestBase(MakePubCrateIntention::class) { fun `test available on function keyword`() = checkAvailableInSelectionOnly(""" <selection>fn</selection> foo() {} """) fun `test available on function modifier`() = checkAvailableInSelectionOnly(""" <selection>unsafe fn</selection> foo() {} """) fun `test unavailable on pub(crate) item`() = doUnavailableTest(""" pub(crate) /*caret*/fn foo() {} """) fun `test make restricted visibility pub(crate)`() = doAvailableTest(""" mod bar { pub(in crate::bar) /*caret*/fn foo() {} } """, """ mod bar { pub(crate) /*caret*/fn foo() {} } """) fun `test make function pub(crate)`() = doAvailableTest(""" /*caret*/fn foo() {} """, """ /*caret*/pub(crate) fn foo() {} """) fun `test make async function pub(crate)`() = doAvailableTest(""" async /*caret*/fn foo() {} """, """ pub(crate) async /*caret*/fn foo() {} """) fun `test make unsafe function pub(crate)`() = doAvailableTest(""" unsafe /*caret*/fn foo() {} """, """ pub(crate) unsafe /*caret*/fn foo() {} """) fun `test make extern function pub(crate)`() = doAvailableTest(""" extern "C" /*caret*/fn foo() {} """, """ pub(crate) extern "C" /*caret*/fn foo() {} """) fun `test make struct pub(crate)`() = doAvailableTest(""" /*caret*/struct Foo {} """, """ /*caret*/pub(crate) struct Foo {} """) fun `test make struct named field pub(crate)`() = doAvailableTest(""" struct Foo { /*caret*/a: u32 } """, """ struct Foo { /*caret*/pub(crate) a: u32 } """) fun `test make struct tuple field pub(crate)`() = doAvailableTest(""" struct Foo(/*caret*/a: u32); """, """ struct Foo(/*caret*/pub(crate) a: u32); """) fun `test make type alias pub(crate)`() = doAvailableTest(""" /*caret*/type Foo = u32; """, """ /*caret*/pub(crate) type Foo = u32; """) fun `test make constant pub(crate)`() = doAvailableTest(""" /*caret*/const FOO: u32 = u32; """, """ /*caret*/pub(crate) const FOO: u32 = u32; """) fun `test make use pub(crate)`() = doAvailableTest(""" use/*caret*/ foo::bar; """, """ pub(crate) use/*caret*/ foo::bar; """) }
src/test/kotlin/org/rust/ide/intentions/visibility/MakePubCrateIntentionTest.kt
932105298
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain.tools import com.intellij.execution.configurations.PtyCommandLine import org.rust.cargo.toolchain.RsToolchainBase import java.io.File fun RsToolchainBase.evcxr(): Evcxr? = if (hasCargoExecutable(Evcxr.NAME)) Evcxr(this) else null class Evcxr(toolchain: RsToolchainBase) : CargoBinary(NAME, toolchain) { fun createCommandLine(workingDirectory: File): PtyCommandLine { val commandLine = createBaseCommandLine( "--ide-mode", "--disable-readline", "--opt", "0", workingDirectory = workingDirectory.toPath() ) return PtyCommandLine(commandLine).withInitialColumns(PtyCommandLine.MAX_COLUMNS) } companion object { const val NAME: String = "evcxr" } }
src/main/kotlin/org/rust/cargo/toolchain/tools/Evcxr.kt
1261819597
package com.github.jk1.ytplugin.issues import com.github.jk1.ytplugin.ComponentAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity class IssuesUpdaterInitExtension: StartupActivity.Background { override fun runActivity(project: Project) { // force init on project open ComponentAware.of(project).issueUpdaterComponent } }
src/main/kotlin/com/github/jk1/ytplugin/issues/IssuesUpdaterInitExtension.kt
2883676358
package com.example.octodroid.views.holders import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.octodroid.R class ProgressViewHolder(view: View) : RecyclerView.ViewHolder(view) { companion object { fun create(parent: ViewGroup): ProgressViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_progress, parent, false) return ProgressViewHolder(view) } } }
app/src/main/kotlin/com/example/octodroid/views/holders/ProgressViewHolder.kt
4249706
package org.jetbrains.dokka.gradle import org.junit.BeforeClass import java.io.File abstract class AbstractDokkaAndroidGradleTest : AbstractDokkaGradleTest() { override val pluginClasspath: List<File> = androidPluginClasspathData.toFile().readLines().map { File(it) } companion object { @JvmStatic @BeforeClass fun acceptAndroidSdkLicenses() { val sdkDir = androidLocalProperties?.toFile()?.let { val lines = it.readLines().map { it.trim() } val sdkDirLine = lines.firstOrNull { "sdk.dir" in it } sdkDirLine?.substringAfter("=")?.trim() } ?: System.getenv("ANDROID_HOME") if (sdkDir == null || sdkDir.isEmpty()) { error("Android SDK home not set, " + "try setting \$ANDROID_HOME " + "or sdk.dir in runners/gradle-integration-tests/testData/android.local.properties") } val sdkDirFile = File(sdkDir) if (!sdkDirFile.exists()) error("\$ANDROID_HOME and android.local.properties points to non-existing location") val sdkLicensesDir = sdkDirFile.resolve("licenses") val acceptedLicenses = File("android-licenses") acceptedLicenses.listFiles().forEach { licenseFile -> val target = sdkLicensesDir.resolve(licenseFile.name) if(!target.exists() || target.readText() != licenseFile.readText()) { val overwrite = System.getProperty("android.licenses.overwrite", "false").toBoolean() if (!target.exists() || overwrite) { licenseFile.copyTo(target, true) println("Accepted ${licenseFile.name}, by copying $licenseFile to $target") } } } } } }
runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AbstractDokkaAndroidGradleTest.kt
2917119001
package com.physphil.android.unitconverterultimate.data import com.physphil.android.unitconverterultimate.models.Temperature import java.math.BigDecimal import java.math.RoundingMode object TemperatureConverter : Converter<Temperature> { override fun convert(value: BigDecimal, initial: Temperature, final: Temperature): BigDecimal = when (final) { Temperature.Celsius -> value.toCelsius(initial) Temperature.Fahrenheit -> value.toFahrenheit(initial) Temperature.Kelvin -> value.toKelvin(initial) Temperature.Rankine -> value.toRankine(initial) Temperature.Delisle -> value.toDelisle(initial) Temperature.Newton -> value.toNewton(initial) Temperature.Reaumur -> value.toReaumur(initial) Temperature.Romer -> value.toRomer(initial) } private fun BigDecimal.toCelsius(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this Temperature.Fahrenheit -> (this - 32) * 5 / 9 Temperature.Kelvin -> this - 273.15 Temperature.Rankine -> (this - 491.67) * 5 / 9 Temperature.Delisle -> 100 - this * 2 / 3 Temperature.Newton -> this * 100 / 33 Temperature.Reaumur -> this * 5 / 4 Temperature.Romer -> (this - 7.5) * 40 / 21 } private fun BigDecimal.toFahrenheit(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 9 / 5 + 32 Temperature.Fahrenheit -> this Temperature.Kelvin -> this * 9 / 5 - 459.67 Temperature.Rankine -> this - 459.67 Temperature.Delisle -> 212 - this * 6 / 5 Temperature.Newton -> this * 60 / 11 + 32 Temperature.Reaumur -> this * 9 / 4 + 32 Temperature.Romer -> (this - 7.5) * 24 / 7 + 32 } private fun BigDecimal.toKelvin(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this + 273.15 Temperature.Fahrenheit -> (this + 459.67) * 5 / 9 Temperature.Kelvin -> this Temperature.Rankine -> this * 5 / 9 Temperature.Delisle -> 373.15 - this * 2 / 3 Temperature.Newton -> this * 100 / 33 + 273.15 Temperature.Reaumur -> this * 5 / 4 + 273.15 Temperature.Romer -> (this - 7.5) * 40 / 21 + 273.15 } private fun BigDecimal.toRankine(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> (this + 273.15) * 9 / 5 Temperature.Fahrenheit -> this + 459.67 Temperature.Kelvin -> this * 9 / 5 Temperature.Rankine -> this Temperature.Delisle -> 671.67 - this * 6 / 5 Temperature.Newton -> this * 60 / 11 + 491.67 Temperature.Reaumur -> this * 9 / 4 + 491.67 Temperature.Romer -> (this - 7.5) * 24 / 7 + 491.67 } private fun BigDecimal.toDelisle(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> (100 - this) * 1.5 Temperature.Fahrenheit -> (212 - this) * 5 / 6 Temperature.Kelvin -> (373.15 - this) * 1.5 Temperature.Rankine -> (671.67 - this) * 5 / 6 Temperature.Delisle -> this Temperature.Newton -> (33 - this) * 50 / 11 Temperature.Reaumur -> (80 - this) * 1.875 Temperature.Romer -> (60 - this) * 20 / 7 } private fun BigDecimal.toNewton(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 33 / 100 Temperature.Fahrenheit -> (this - 32) * 11 / 60 Temperature.Kelvin -> (this - 273.15) * 33 / 100 Temperature.Rankine -> (this - 491.67) * 11 / 60 Temperature.Delisle -> 33 - this * 11 / 50 Temperature.Newton -> this Temperature.Reaumur -> this * 33 / 80 Temperature.Romer -> (this - 7.5) * 22 / 35 } private fun BigDecimal.toReaumur(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 4 / 5 Temperature.Fahrenheit -> (this - 32) * 4 / 9 Temperature.Kelvin -> (this - 273.15) * 4 / 5 Temperature.Rankine -> (this - 491.67) * 4 / 9 Temperature.Delisle -> 80 - this * 8 / 15 Temperature.Newton -> this * 80 / 33 Temperature.Reaumur -> this Temperature.Romer -> (this - 7.5) * 32 / 21 } private fun BigDecimal.toRomer(from: Temperature): BigDecimal = when (from) { Temperature.Celsius -> this * 21 / 40 + 7.5 Temperature.Fahrenheit -> (this - 32) * 7 / 24 + 7.5 Temperature.Kelvin -> (this - 273.15) * 21 / 40 + 7.5 Temperature.Rankine -> (this - 491.67) * 7 / 24 + 7.5 Temperature.Delisle -> 60 - this * 7 / 20 Temperature.Newton -> this * 35 / 22 + 7.5 Temperature.Reaumur -> this * 21 / 32 + 7.5 Temperature.Romer -> this } private operator fun BigDecimal.plus(i: Int): BigDecimal = this + i.toBigDecimal() private operator fun BigDecimal.plus(d: Double): BigDecimal = this + d.toBigDecimal() private operator fun BigDecimal.minus(i: Int): BigDecimal = this - i.toBigDecimal() private operator fun BigDecimal.minus(d: Double): BigDecimal = this - d.toBigDecimal() private operator fun BigDecimal.times(i: Int): BigDecimal = this * i.toBigDecimal() private operator fun BigDecimal.times(d: Double): BigDecimal = this * d.toBigDecimal() private operator fun BigDecimal.div(i: Int): BigDecimal = this.divide(i.toBigDecimal(), SCALE_RESULT, RoundingMode.HALF_UP) private operator fun Int.minus(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() - bigDecimal private operator fun Int.times(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() * bigDecimal private operator fun Double.minus(bigDecimal: BigDecimal): BigDecimal = this.toBigDecimal() - bigDecimal }
v6000/src/main/java/com/physphil/android/unitconverterultimate/data/TemperatureConverter.kt
1734249171
/* * Copyright 2021 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.identity.sample.fido2 import android.app.Application import android.os.Build import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import com.google.android.gms.identity.sample.fido2.api.AddHeaderInterceptor import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.HiltAndroidApp import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import okhttp3.OkHttpClient import java.util.concurrent.TimeUnit import javax.inject.Singleton @HiltAndroidApp class Fido2App : Application() @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideOkHttpClient() : OkHttpClient { val userAgent = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME} " + "(Android ${Build.VERSION.RELEASE}; ${Build.MODEL}; ${Build.BRAND})" return OkHttpClient.Builder() .addInterceptor(AddHeaderInterceptor(userAgent)) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(40, TimeUnit.SECONDS) .connectTimeout(40, TimeUnit.SECONDS) .build() } @Singleton @Provides fun provideAppCoroutineScope() : CoroutineScope = CoroutineScope(SupervisorJob()) @Singleton @Provides fun provideDataStore(application: Application): DataStore<Preferences> { return PreferenceDataStoreFactory.create { application.preferencesDataStoreFile("auth") } } }
Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/Fido2App.kt
3304809220
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.internal import androidx.compose.runtime.ComposeCompilerApi /** * This annotation is applied to the FunctionKeyMeta classes created by the Compose * Compiler. These classes will have multiple of these annotations, each one corresponding to a * single composable function. The annotation holds some metadata about the function itself and is * intended to be used to provide information useful to tooling. * * @param key The key used for the function's group. * @param startOffset The startOffset of the function in the source file at the time of compilation. * @param endOffset The startOffset of the function in the source file at the time of compilation. */ @ComposeCompilerApi @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) @Repeatable annotation class FunctionKeyMeta( val key: Int, val startOffset: Int, val endOffset: Int ) /** * This annotation is applied to the FunctionKeyMeta classes created by the Compose * Compiler. This is intended to be used to provide information useful to tooling. * * @param file The file path of the file the associated class was produced for */ @ComposeCompilerApi @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) annotation class FunctionKeyMetaClass( val file: String )
compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/internal/FunctionKeyMeta.kt
3745139359
/* * 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.window.core import android.graphics.Rect import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test public class BoundsTest { @Test public fun testConstructor_matchesRect() { val rect = Rect(1, 2, 3, 4) val actual = Bounds(rect) assertEquals(rect.left, actual.left) assertEquals(rect.top, actual.top) assertEquals(rect.right, actual.right) assertEquals(rect.bottom, actual.bottom) } // equals and hashCode do not seem to be implemented on API 15 so need to check properties @Test public fun testToRect_matchesBounds() { val rect = Rect(1, 2, 3, 4) val bounds = Bounds(rect) val actual = bounds.toRect() assertEquals(rect.left, actual.left) assertEquals(rect.top, actual.top) assertEquals(rect.right, actual.right) assertEquals(rect.bottom, actual.bottom) } @Test public fun testWidth_matchesRect() { val rect = Rect(1, 2, 3, 4) val actual = Bounds(rect).width assertEquals(rect.width(), actual) } @Test public fun testHeight_matchesRect() { val rect = Rect(1, 2, 3, 4) val actual = Bounds(rect).height assertEquals(rect.height(), actual) } @Test public fun testIsEmpty_matchesRect() { val emptyRect = Rect(0, 0, 111, 0) val isRectEmpty = Bounds(emptyRect).isEmpty val nonEmptyRect = Rect(0, 0, 100, 100) val isRectNotEmpty = Bounds(nonEmptyRect).isEmpty assertTrue(isRectEmpty) assertFalse(isRectNotEmpty) } @Test public fun testIsZero() { val zeroBounds = Bounds(Rect(0, 0, 0, 0)) assertTrue(zeroBounds.isZero) } }
window/window/src/androidTest/java/androidx/window/core/BoundsTest.kt
1682646686
package com.github.willjgriff.ethereumwallet.ui.screens.nodedetails import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.github.willjgriff.ethereumwallet.R import com.github.willjgriff.ethereumwallet.di.AppInjector import com.github.willjgriff.ethereumwallet.mvp.BaseMvpControllerKotlin import com.github.willjgriff.ethereumwallet.ui.navigation.NavigationToolbarListener import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.di.DaggerNodeDetailsComponent import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsHeadersAdapter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsHeadersAdapter.NodeStatusHeadersAdapterListener import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.list.NodeDetailsPeersAdapter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.mvp.NodeDetailsPresenter import com.github.willjgriff.ethereumwallet.ui.screens.nodedetails.mvp.NodeDetailsView import com.github.willjgriff.ethereumwallet.ui.utils.inflate import kotlinx.android.synthetic.main.controller_node_status.view.* import javax.inject.Inject /** * Created by Will on 20/03/2017. */ class NodeDetailsController : BaseMvpControllerKotlin<NodeDetailsView, NodeDetailsPresenter>(), NodeDetailsView, NodeStatusHeadersAdapterListener { override val mvpView: NodeDetailsView get() = this @Inject lateinit override var presenter: NodeDetailsPresenter private lateinit var nodeDetails: TextView private lateinit var syncProgress: TextView private lateinit var peers: TextView private lateinit var peersInfo: RecyclerView private lateinit var headers: RecyclerView private val mPeersAdapter: NodeDetailsPeersAdapter = NodeDetailsPeersAdapter() private val mHeadersAdapter: NodeDetailsHeadersAdapter = NodeDetailsHeadersAdapter(this) init { DaggerNodeDetailsComponent.builder() .appComponent(AppInjector.appComponent) .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { val view = container.inflate(R.layout.controller_node_status) setupToolbarTitle() bindViews(view) setupRecyclerViews() return view } private fun setupToolbarTitle() { if (targetController is NavigationToolbarListener) { (targetController as NavigationToolbarListener) .setToolbarTitle(applicationContext!!.getString(R.string.controller_node_details_title)) } } private fun bindViews(view: View) { peers = view.controller_node_status_peers peersInfo = view.controller_node_status_peers_list headers = view.controller_node_status_headers_list nodeDetails = view.controller_node_status_node_details syncProgress = view.controller_node_status_sync_progress } private fun setupRecyclerViews() { headers.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = mHeadersAdapter } peersInfo.apply { layoutManager = LinearLayoutManager(applicationContext) adapter = mPeersAdapter } } override fun headerInserted(position: Int) { headers.scrollToPosition(position) } override fun newHeaderHash(headerHash: String) { mHeadersAdapter.addHeaderHash(headerHash) } override fun updateNumberOfPeers(numberOfPeers: Long) { peers.text = "Peers: $numberOfPeers" } override fun setNodeDetails(nodeInfoString: String) { nodeDetails.text = nodeInfoString } override fun setSyncProgress(syncProgressString: String) { syncProgress.text = syncProgressString } override fun setPeerStrings(peers: List<String>) { mPeersAdapter.peers = peers } }
app/src/main/kotlin/com/github/willjgriff/ethereumwallet/ui/screens/nodedetails/NodeDetailsController.kt
4273837843
package diff.equality.strategies import diff.equality.EqualityStrategy import diff.patch.coords.RootCoordinate import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test /** * Created by sebasjm on 14/07/17. */ class LCSCollectionEqualityStrategyTest { @Test fun emptyListShouldBeEquals() { assertEquals( LCSCollectionEqualityStrategy().compare( emptyList(), emptyList() ), EqualityStrategy.CompareResult.EQUALS ) } @Test fun equalListShoudBeEquals() { assertEquals( LCSCollectionEqualityStrategy().compare( listOf(1,2,3), listOf(1,2,3) ), EqualityStrategy.CompareResult.EQUALS ) } @Test fun shouldReduceTheComparisonToARange1() { val before = listOf(1, 4, 3) val after = listOf(1, 2, 3) val compare = LCSCollectionEqualityStrategy().compare(before, after) as EqualityStrategy.UndecidibleMoreToCompare<List<Any>> assertEquals(compare.result.size , 1) assertEquals(compare.result.first()(RootCoordinate()).getter(true, before).get(), listOf(4)) assertEquals(compare.result.first()(RootCoordinate()).getter(false, after).get(), listOf(2)) } @Test fun shouldReduceTheComparisonToARange2() { val before = listOf(1, 4, 5, 6, 3) val after = listOf(1, 2, 3) val compare = LCSCollectionEqualityStrategy().compare(before, after) as EqualityStrategy.UndecidibleMoreToCompare<List<Any>> assertEquals(compare.result.size , 1) assertEquals(compare.result.first()(RootCoordinate()).getter(true, before).get(), listOf(4,5,6)) assertEquals(compare.result.first()(RootCoordinate()).getter(false, after).get(), listOf(2)) } @Test fun shouldReduceTheComparisonToARange3() { val before = listOf(1, 4, 5, 6, 3) val after = listOf(1, 2, 7, 3) val compare = LCSCollectionEqualityStrategy().compare(before, after) as EqualityStrategy.UndecidibleMoreToCompare<List<Any>> assertEquals(compare.result.size , 1) assertEquals(compare.result.first()(RootCoordinate()).getter(true, before).get(), listOf(4,5,6)) assertEquals(compare.result.first()(RootCoordinate()).getter(false, after).get(), listOf(2,7)) } @Test fun shouldReduceTheComparisonToARange4() { val before = listOf(1, 3) val after = listOf(1, 2, 7, 3) val compare = LCSCollectionEqualityStrategy().compare(before, after) as EqualityStrategy.UndecidibleMoreToCompare<List<Any>> assertEquals(compare.result.size , 1) assertEquals(compare.result.first()(RootCoordinate()).getter(true, before).get(), emptyList<Int>()) assertEquals(compare.result.first()(RootCoordinate()).getter(false, after).get(), listOf(2,7)) } @Test fun shouldReduceTheComparisonToMultipleRange1() { val before = listOf(1, 3, 4, 5, 6, 8,9) val after = listOf(1, 2, 7, 3, 4 , 8,9) val compare = LCSCollectionEqualityStrategy().compare(before, after) as EqualityStrategy.UndecidibleMoreToCompare<List<Any>> assertEquals(compare.result.size , 2) assertEquals(compare.result[0](RootCoordinate()).getter(true, before).get(), listOf(5,6)) assertEquals(compare.result[0](RootCoordinate()).getter(false, after).get(), emptyList<Int>()) assertEquals(compare.result[1](RootCoordinate()).getter(true, before).get(), emptyList<Int>()) assertEquals(compare.result[1](RootCoordinate()).getter(false, after).get(), listOf(2,7)) } }
src/test/java/diff/equality/strategies/LCSCollectionEqualityStrategyTest.kt
2270810170
package org.elm.ide.inspections class QuickFixInvocationTracker { @Volatile var invoked: Boolean = false private set fun invoke() { invoked = true } }
src/main/kotlin/org/elm/ide/inspections/QuickFixInvocationTracker.kt
4123794927
package diff.patch.accessors import diff.patch.Setter import java.lang.reflect.Array /** * @author sebasjm <smarchano></smarchano>@primary.com.ar> */ class ArraySetter<ArrayType: Any, ComponentType: Any>(internal val target: ArrayType, internal val index: Int) : Setter<ComponentType> { override fun set(value: ComponentType) { if (index < Array.getLength(target)) { Array.set(target, index, value) } } }
src/main/kotlin/diff/patch/accessors/ArraySetter.kt
781123248
package diff.equality.strategies import diff.equality.EqualityStrategy import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import java.util.* /** * Created by sebasjm on 07/07/17. */ class OrderedMapEqualityStrategyTest { @Test fun shouldReturnEqualsWhenComparingTwoEmptyTreeMaps() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> val compare = OrderedMapEqualityStrategy().compare(before, after) assert( compare == EqualityStrategy.CompareResult.EQUALS ) } @Test fun shouldReturnUndecidibleWhenMapsHasContents() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> before.put("1","something") before.put("2","something") val compare = OrderedMapEqualityStrategy().compare(before, after) as? EqualityStrategy.UndecidibleMoreToCompare<*> ?: throw AssertionError("Assertion failed") assertEquals( compare.result.size, before.size * 2 ) } @Test fun shouldQueueOrderComparisonAndKeyComparisonForOrderedMaps() { val before = TreeMap<String,String>() as TreeMap<Any,Any> val after = TreeMap<String,String>() as TreeMap<Any,Any> before.put("1","something") before.put("2","something") val compare = OrderedMapEqualityStrategy().compare(before, after) as? EqualityStrategy.UndecidibleMoreToCompare<*> ?: throw AssertionError("Assertion failed") assertEquals( compare.result.size, before.size * 2 ) } @Test fun shouldCompareTreeMap() { val map = TreeMap<String,String>() as SortedMap<Any,Any> assertTrue( OrderedMapEqualityStrategy().shouldUseThisStrategy(map.javaClass) ) } }
src/test/java/diff/equality/strategies/OrderedMapEqualityStrategyTest.kt
576552672
package org.edx.mobile.exception /** * Error handling model class for ViewModel * handle exceptions/error based on errorCode */ data class ErrorMessage( val errorCode: Int, val throwable: Throwable ) { companion object { // Custom error codes const val BANNER_INFO_CODE = 101 const val COURSE_RESET_DATES_CODE = 102 const val COURSE_DATES_CODE = 103 } }
OpenEdXMobile/src/main/java/org/edx/mobile/exception/ErrorMessage.kt
2347841914
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.launcher import org.wfanet.measurement.api.v2alpha.ExchangeStep import org.wfanet.measurement.api.v2alpha.ExchangeStepAttemptKey import org.wfanet.panelmatch.client.launcher.ExchangeStepValidator.ValidatedExchangeStep /** Executes an [ExchangeStep]. This may be locally or remotely. */ interface JobLauncher { /** * Initiates work on [step]. * * This may return before the work is complete. * * This could run [step] in-process or enqueue/start work remotely, e.g. via an RPC call. */ suspend fun execute(step: ValidatedExchangeStep, attemptKey: ExchangeStepAttemptKey) }
src/main/kotlin/org/wfanet/panelmatch/client/launcher/JobLauncher.kt
333796159
package ru.fantlab.android.data.dao.model import android.os.Parcelable import androidx.annotation.Keep import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Keep @Parcelize data class Work( val authors: ArrayList<Author>, val image: String?, @SerializedName("image_preview") val preview: String?, @SerializedName("lang") val lang: String?, @SerializedName("lang_code") val lang_code: String?, @SerializedName("publish_statuses") val publishStatuses: ArrayList<String>, val rating: Rating, val title: String, @SerializedName("val_responsecount") val responseCount: Int, @SerializedName("work_description") val description: String?, @SerializedName("work_description_author") val descriptionAuthor: String?, @SerializedName("work_id") val id: Int, @SerializedName("work_lp") val hasLinguaProfile: Int?, @SerializedName("work_name") val name: String, @SerializedName("work_name_alts") val nameAlts: ArrayList<String>, @SerializedName("work_name_bonus") val nameBonus: String?, @SerializedName("work_name_orig") val nameOrig: String, @SerializedName("work_notes") val notes: String, @SerializedName("work_notfinished") val notFinished: Int, @SerializedName("work_parent") val parentId: Int, @SerializedName("work_preparing") val preparing: Int, @SerializedName("work_published") val published: Int, @SerializedName("work_type") val type: String, @SerializedName("work_type_id") val typeId: Int, @SerializedName("work_type_name") val typeName: String, @SerializedName("work_year") val year: Int?, @SerializedName("work_year_of_write") val yearOfWrite: Int? ) : Parcelable { @Keep @Parcelize data class Author( val id: Int, @SerializedName("is_opened") val isOpened: Int, val name: String, @SerializedName("name_orig") val nameOrig: String, val type: String ) : Parcelable { override fun toString() = name } @Keep @Parcelize data class Rating( val rating: String, @SerializedName("voters") val votersCount: String ) : Parcelable }
app/src/main/kotlin/ru/fantlab/android/data/dao/model/Work.kt
2563519083
package at.ac.tuwien.caa.docscan.logic enum class ExportFormat(val id: String) { ZIP("ZIP"), PDF("PDF"), PDF_WITH_OCR("PDF_WITH_OCR"); fun getFileType(): PageFileType { return when (this) { ZIP -> PageFileType.ZIP PDF, PDF_WITH_OCR -> PageFileType.PDF } } companion object { fun getExportFormatById(id: String?): ExportFormat { values().forEach { format -> if (format.id == id) { return format } } return PDF } } }
app/src/main/java/at/ac/tuwien/caa/docscan/logic/ExportFormat.kt
519162034
package org.jetbrains.haskell.run.haskell import com.intellij.execution.configuration.ConfigurationFactoryEx import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationType import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.project.Project import org.jetbrains.haskell.icons.HaskellIcons import javax.swing.* public class HaskellRunConfigurationType() : ConfigurationType { private val myFactory: ConfigurationFactory override fun getDisplayName(): String { return "Haskell" } override fun getConfigurationTypeDescription(): String { return "Haskell application" } override fun getIcon(): Icon { return HaskellIcons.APPLICATION } override fun getId(): String { return "CabalRunConfiguration" } override fun getConfigurationFactories(): Array<ConfigurationFactory> { return arrayOf(myFactory) } init { this.myFactory = object : ConfigurationFactoryEx(this) { override fun createTemplateConfiguration(project: Project?): RunConfiguration { return CabalRunConfiguration(project, this) } } } companion object { public val INSTANCE: HaskellRunConfigurationType = HaskellRunConfigurationType() } }
plugin/src/org/jetbrains/haskell/run/haskell/HaskellRunConfigurationType.kt
1742484141
/* * Copyright 2016 Pedro Rodrigues * * 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.hpedrorodrigues.gzmd.adapter import android.view.LayoutInflater import android.view.ViewGroup import com.hpedrorodrigues.gzmd.R import com.hpedrorodrigues.gzmd.entity.Preview import com.hpedrorodrigues.gzmd.adapter.holder.PreviewHolder import com.squareup.picasso.Picasso import javax.inject.Inject class PreviewAdapter : BaseAdapter<Preview, PreviewHolder> { @Inject lateinit var inflater: LayoutInflater @Inject constructor() : super() var onPreviewClick: OnPreviewClick? = null override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PreviewHolder? { return PreviewHolder(inflater.inflate(R.layout.preview, parent, false)) } override fun onBindViewHolder(holder: PreviewHolder, position: Int) { val preview = content[position] holder.title.text = preview.title holder.authorName.text = preview.authorName holder.postedAt.text = preview.postedAt holder.sharesCount.text = preview.sharesCount.toString() holder.commentsCount.text = preview.commentsCount.toString() holder.image.labelText = preview.tagName.toUpperCase() holder.view.setOnClickListener { onPreviewClick?.onClick(preview) } Picasso.with(holder.image.context) .load(preview.imageUrl) .placeholder(R.drawable.preview_background) .into(holder.image) } interface OnPreviewClick { fun onClick(preview: Preview) } }
app/src/main/kotlin/com/hpedrorodrigues/gzmd/adapter/PreviewAdapter.kt
1436400083
package com.tasomaniac.openwith.redirect import android.app.Activity import android.content.ComponentName import android.content.Intent import android.net.Uri import android.os.Bundle import com.tasomaniac.android.widget.DelayedProgressBar import com.tasomaniac.openwith.resolver.ResolverActivity import com.tasomaniac.openwith.rx.SchedulingStrategy import dagger.android.support.DaggerAppCompatActivity import io.reactivex.Maybe import io.reactivex.MaybeTransformer import io.reactivex.Single import io.reactivex.disposables.Disposable import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import javax.inject.Inject class RedirectFixActivity : DaggerAppCompatActivity() { @Inject lateinit var browserIntentChecker: BrowserIntentChecker @Inject lateinit var redirectFixer: RedirectFixer @Inject lateinit var urlFix: UrlFix @Inject lateinit var schedulingStrategy: SchedulingStrategy private var disposable: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.redirect_activity) val progress = findViewById<DelayedProgressBar>(R.id.resolver_progress) progress.show(true) val source = Intent(intent).apply { component = null } disposable = Single.just(source) .filter { browserIntentChecker.hasOnlyBrowsers(it) } .map { urlFix.fixUrls(it.dataString!!) } .flatMap { Maybe.fromCallable<HttpUrl> { it.toHttpUrlOrNull() } } .compose(redirectTransformer) .map(HttpUrl::toString) .toSingle(source.dataString!!) // fall-back to original data if anything goes wrong .map(urlFix::fixUrls) // fix again after potential redirect .map { source.withUrl(it) } .compose(schedulingStrategy.forSingle()) .subscribe { intent -> intent.component = ComponentName(this, ResolverActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT) startActivity(intent) finish() } } private val redirectTransformer = MaybeTransformer<HttpUrl, HttpUrl> { source -> source.flatMap { httpUrl -> redirectFixer .followRedirects(httpUrl) .toMaybe() } } override fun onDestroy() { disposable?.dispose() super.onDestroy() } companion object { @JvmStatic fun createIntent(activity: Activity, foundUrl: String): Intent { return Intent(activity, RedirectFixActivity::class.java) .putExtras(activity.intent) .setAction(Intent.ACTION_VIEW) .setData(Uri.parse(foundUrl)) } private fun Intent.withUrl(url: String): Intent = setData(Uri.parse(url)) } }
redirect/src/main/kotlin/com/tasomaniac/openwith/redirect/RedirectFixActivity.kt
1140277012
package com.mxt.anitrend.worker import android.content.Context import android.net.Uri import android.text.TextUtils import androidx.work.Data import androidx.work.ListenableWorker import androidx.work.Worker import androidx.work.WorkerParameters import com.mxt.anitrend.BuildConfig import com.mxt.anitrend.base.custom.async.WebTokenRequest import com.mxt.anitrend.presenter.base.BasePresenter import com.mxt.anitrend.util.KeyUtil import org.koin.core.KoinComponent import org.koin.core.inject import timber.log.Timber import java.util.concurrent.ExecutionException class AuthenticatorWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams), KoinComponent { private val presenter by inject<BasePresenter>() private val authenticatorUri: Uri by lazy(LazyThreadSafetyMode.NONE) { Uri.parse(workerParams.inputData .getString(KeyUtil.arg_model)) } /** * Override this method to do your actual background processing. This method is called on a * background thread - you are required to **synchronously** do your work and return the * [Result] from this method. Once you return from this * method, the Worker is considered to have finished what its doing and will be destroyed. If * you need to do your work asynchronously on a thread of your own choice, see * [ListenableWorker]. * * * A Worker is given a maximum of ten minutes to finish its execution and return a * [Result]. After this time has expired, the Worker will * be signalled to stop. * * @return The [Result] of the computation; note that * dependent work will not execute if you use * [Result.failure] or * [Result.failure] */ override fun doWork(): Result { val errorDataBuilder = Data.Builder() try { val authorizationCode = authenticatorUri.getQueryParameter(BuildConfig.RESPONSE_TYPE) if (!TextUtils.isEmpty(authorizationCode)) { val isSuccess = WebTokenRequest.getToken(authorizationCode) presenter.settings.isAuthenticated = isSuccess val outputData = Data.Builder() .putBoolean(KeyUtil.arg_model, isSuccess) .build() return Result.success(outputData) } else Timber.tag(TAG).e("Authorization authenticatorUri was empty or null, cannot authenticate with the current state") } catch (e: ExecutionException) { e.printStackTrace() errorDataBuilder.putString(KeyUtil.arg_exception_error, e.message) } catch (e: InterruptedException) { e.printStackTrace() errorDataBuilder.putString(KeyUtil.arg_exception_error, e.message) } val workerErrorOutputData = errorDataBuilder .putString(KeyUtil.arg_uri_error, authenticatorUri .getQueryParameter(KeyUtil.arg_uri_error)) .putString(KeyUtil.arg_uri_error_description, authenticatorUri .getQueryParameter(KeyUtil.arg_uri_error_description)) .build() return Result.failure(workerErrorOutputData) } companion object { private val TAG = AuthenticatorWorker::class.java.simpleName } }
app/src/main/java/com/mxt/anitrend/worker/AuthenticatorWorker.kt
3888635259
package com.sebastian.sokolowski.auctionhunter.rest.request /** * Created by Sebastian Sokołowski on 22.09.20. */ enum class SortType(val id: String) { RELEVANCE_DESC("-relevance"), PRICE_ASC("+price"), PRICE_DESC("-price"), PRICE_WITH_DELIVERY_ASC("+withDeliveryPrice"), PRICE_WITH_DELIVERY_DESC("-withDeliveryPrice"), POPULARITY_DESC("-popularity"), END_TIME_ASC("+endTime"), START_TIME_DESC("-startTime") }
android-app/app/src/main/java/com/sebastian/sokolowski/auctionhunter/rest/request/SortType.kt
1759169255
package com.sebastiansokolowski.auctionhunter.allegro_api.response data class RefreshTokenResponse( val access_token: String, val token_type: String, val refresh_token: String, val expires_in: Long, val allegro_api: Boolean, val jti: String )
server/src/main/kotlin/com/sebastiansokolowski/auctionhunter/allegro_api/response/RefreshTokenResponse.kt
3173849346
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.sslr import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.PlSqlGrammar class IfStatementTest : TreeTest<IfStatement>(PlSqlGrammar.IF_STATEMENT) { @Test fun matchesSimpleIf() { val tree = parse( "if true then " + "null; " + "end if;") assertThat(tree.condition.allTokensToString).isEqualTo("true") assertThat(tree.statements).hasSize(1) assertThat(tree.statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elsifClauses).hasSize(0) assertThat(tree.elseClause).isNull() } @Test fun matchesIfWithElsif() { val tree = parse( "if true then " + "null; " + "elsif x = 1 then " + "null; " + "end if;") assertThat(tree.condition.allTokensToString).isEqualTo("true") assertThat(tree.statements).hasSize(1) assertThat(tree.statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elsifClauses).hasSize(1) assertThat(tree.elsifClauses[0].condition.allTokensToString).isEqualTo("x = 1") assertThat(tree.elsifClauses[0].statements).hasSize(1) assertThat(tree.elsifClauses[0].statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elseClause).isNull() } @Test fun matchesIfWithElsifAndElse() { val tree = parse( "if true then " + "null; " + "elsif x = 1 then " + "null; " + "elsif x = 2 then " + "null; " + "else " + "null; " + "end if;") assertThat(tree.condition.allTokensToString).isEqualTo("true") assertThat(tree.statements).hasSize(1) assertThat(tree.statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elsifClauses).hasSize(2) assertThat(tree.elsifClauses[0].condition.allTokensToString).isEqualTo("x = 1") assertThat(tree.elsifClauses[0].statements).hasSize(1) assertThat(tree.elsifClauses[0].statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elsifClauses[1].condition.allTokensToString).isEqualTo("x = 2") assertThat(tree.elsifClauses[1].statements).hasSize(1) assertThat(tree.elsifClauses[1].statements[0].tree).isInstanceOf(NullStatement::class.java) assertThat(tree.elseClause).isNotNull assertThat(tree.elseClause!!.statements).hasSize(1) assertThat(tree.elseClause!!.statements[0].tree).isInstanceOf(NullStatement::class.java) } }
zpa-core/src/test/kotlin/org/sonar/plsqlopen/sslr/IfStatementTest.kt
3086234376
package klogging import org.slf4j.LoggerFactory import kotlin.reflect.KClass actual object KLoggers { actual fun logger(owner: Any): KLogger = when (owner) { is String -> KLogger(JVMLogger(LoggerFactory.getLogger(owner))) is KClass<*> -> logger(owner.java) is Class<*> -> KLogger(JVMLogger(LoggerFactory.getLogger(owner))) else -> logger(owner.javaClass) } }
klogging.jvm/src/klogging/KLoggers.kt
1540478631
/* * Copyright (C) 2019 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.basex.query.session.binding interface Session { fun execute(command: String): String? fun query(query: String): Query fun close() }
src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/query/session/binding/Session.kt
24276291
package info.nightscout.androidaps.plugins.constraints.objectives.events import info.nightscout.androidaps.events.EventUpdateGui class EventObjectivesUpdateGui : EventUpdateGui()
app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/events/EventObjectivesUpdateGui.kt
1922439702
package com.habitrpg.android.habitica.utils import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.habitrpg.android.habitica.extensions.getAsString import com.habitrpg.android.habitica.models.WorldState import com.habitrpg.android.habitica.models.WorldStateEvent import com.habitrpg.android.habitica.models.inventory.QuestProgress import com.habitrpg.android.habitica.models.inventory.QuestRageStrike import io.realm.RealmList import java.lang.reflect.Type class WorldStateSerialization : JsonDeserializer<WorldState> { override fun deserialize( json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext? ): WorldState { val state = WorldState() val obj = json?.asJsonObject ?: return state val worldBossObject = obj.get("worldBoss")?.asJsonObject if (worldBossObject != null) { if (worldBossObject.has("active") && !worldBossObject["active"].isJsonNull) { state.worldBossActive = worldBossObject["active"].asBoolean } if (worldBossObject.has("key") && !worldBossObject["key"].isJsonNull) { state.worldBossKey = worldBossObject["key"].asString } if (worldBossObject.has("progress")) { val progress = QuestProgress() val progressObj = worldBossObject.getAsJsonObject("progress") if (progressObj.has("hp")) { progress.hp = progressObj["hp"].asDouble } if (progressObj.has("rage")) { progress.rage = progressObj["rage"].asDouble } state.progress = progress } if (worldBossObject.has("extra")) { val extra = worldBossObject["extra"].asJsonObject if (extra.has("worldDmg")) { val worldDmg = extra["worldDmg"].asJsonObject state.rageStrikes = RealmList() worldDmg.entrySet().forEach { (key, value) -> val strike = QuestRageStrike(key, value.asBoolean) state.rageStrikes?.add(strike) } } } } state.npcImageSuffix = obj.getAsString("npcImageSuffix") try { if (obj.has("currentEvent") && obj.get("currentEvent")?.isJsonObject == true) { val event = obj.getAsJsonObject("currentEvent") if (event != null) { state.currentEvent = context?.deserialize(event, WorldStateEvent::class.java) } if (obj.has("currentEventList")) { val events = RealmList<WorldStateEvent>() for (element in obj.getAsJsonArray("currentEventList")) { context?.deserialize<WorldStateEvent>(element, WorldStateEvent::class.java)?.let { events.add(it) } } state.events = events } } } catch (e: Exception) { } return state } }
Habitica/src/main/java/com/habitrpg/android/habitica/utils/WorldStateSerialization.kt
2321116119
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.gistlist import giuliolodi.gitnav.data.DataManager import giuliolodi.gitnav.ui.base.BasePresenter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.eclipse.egit.github.core.Gist import timber.log.Timber import javax.inject.Inject /** * Created by giulio on 23/05/2017. */ class GistListPresenter<V: GistListContract.View> : BasePresenter<V>, GistListContract.Presenter<V> { private val TAG = "GistListPresenter" private var mGistList: MutableList<Gist> = mutableListOf() private var PAGE_N = 1 private var ITEMS_PER_PAGE = 20 private var LOADING: Boolean = false private var LOADING_LIST: Boolean = false private var MINE_STARRED: String = "mine" private var NO_SHOWING: Boolean = false @Inject constructor(mCompositeDisposable: CompositeDisposable, mDataManager: DataManager) : super(mCompositeDisposable, mDataManager) override fun subscribe(isNetworkAvailable: Boolean) { if (!mGistList.isEmpty()) getView().showGists(mGistList) else if (LOADING) getView().showLoading() else if (NO_SHOWING) getView().showNoGists(MINE_STARRED) else { if (isNetworkAvailable) { LOADING = true getView().showLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else { getView().showNoConnectionError() getView().hideLoading() LOADING = false } } } override fun getMineGists() { getCompositeDisposable().add(getDataManager().pageGists(null, PAGE_N, ITEMS_PER_PAGE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { gistList -> getView().hideLoading() getView().hideListLoading() mGistList.addAll(gistList) getView().showGists(gistList) if (PAGE_N == 1 && gistList.isEmpty()) { getView().showNoGists(MINE_STARRED) NO_SHOWING = true } PAGE_N += 1 LOADING = false LOADING_LIST = false }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() getView().hideListLoading() Timber.e(throwable) LOADING = false LOADING_LIST = false } )) } override fun getStarredGists() { getCompositeDisposable().add(getDataManager().pageStarredGists(PAGE_N, ITEMS_PER_PAGE) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { gistList -> mGistList.addAll(gistList) getView().showGists(gistList) getView().hideLoading() getView().hideListLoading() if (PAGE_N == 1 && gistList.isEmpty()) { getView().showNoGists(MINE_STARRED) NO_SHOWING = true } PAGE_N += 1 LOADING = false LOADING_LIST = false }, { throwable -> throwable?.localizedMessage?.let { getView().showError(it) } getView().hideLoading() getView().hideListLoading() Timber.e(throwable) LOADING = false LOADING_LIST = false } )) } override fun onSwipeToRefresh(isNetworkAvailable: Boolean) { if (isNetworkAvailable) { getView().hideNoGists() NO_SHOWING = false PAGE_N = 1 getView().clearAdapter() mGistList.clear() LOADING = true getView().showLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else { getView().showNoConnectionError() getView().hideLoading() } } override fun onLastItemVisible(isNetworkAvailable: Boolean, dy: Int) { if (LOADING_LIST) return if (isNetworkAvailable) { LOADING_LIST = true getView().showListLoading() when (MINE_STARRED) { "mine" -> getMineGists() "starred" -> getStarredGists() } } else if (dy > 0) { getView().showNoConnectionError() getView().hideLoading() } } override fun onBottomViewMineGistClick(isNetworkAvailable: Boolean) { getView().showLoading() getView().hideNoGists() NO_SHOWING = false getView().clearAdapter() mGistList.clear() getView().setAdapterAndClickListener() PAGE_N = 1 MINE_STARRED = "mine" getMineGists() } override fun onBottomViewStarredGistClick(isNetworkAvailable: Boolean) { getView().showLoading() getView().hideNoGists() NO_SHOWING = false getView().clearAdapter() mGistList.clear() getView().setAdapterAndClickListener() PAGE_N = 1 MINE_STARRED = "starred" getStarredGists() } override fun onGistClick(gistId: String) { getView().intentToGistActivitiy(gistId) } override fun unsubscribe() { if (getCompositeDisposable().size() != 0) getCompositeDisposable().clear() } }
app/src/main/java/giuliolodi/gitnav/ui/gistlist/GistListPresenter.kt
3233797773
package org.stepik.android.view.course_list.ui.fragment import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.item_course_list.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.util.CoursesSnapHelper import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_list.model.CourseListQuery import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper import org.stepik.android.domain.filter.model.CourseListFilterQuery import org.stepik.android.domain.last_step.model.LastStep import org.stepik.android.model.Course import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource import org.stepik.android.presentation.course_list.CourseListQueryPresenter import org.stepik.android.presentation.course_list.CourseListQueryView import org.stepik.android.presentation.course_list.CourseListView import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager import org.stepik.android.view.course.mapper.DisplayPriceMapper import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate import org.stepik.android.view.course_list.delegate.CourseListViewDelegate import org.stepik.android.view.course_list.resolver.TableLayoutHorizontalSpanCountResolver import org.stepik.android.view.ui.delegate.ViewStateDelegate import ru.nobird.android.core.model.PaginationDirection import ru.nobird.android.view.base.ui.extension.setOnPaginationListener import javax.inject.Inject class CourseListPopularFragment : Fragment(R.layout.item_course_list), CourseListQueryView { companion object { fun newInstance(): Fragment = CourseListPopularFragment() } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper @Inject internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper @Inject internal lateinit var displayPriceMapper: DisplayPriceMapper @Inject internal lateinit var tableLayoutHorizontalSpanCountResolver: TableLayoutHorizontalSpanCountResolver private lateinit var courseListViewDelegate: CourseListViewDelegate private val courseListQueryPresenter: CourseListQueryPresenter by viewModels { viewModelFactory } private lateinit var tableLayoutManager: TableLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) containerCarouselCount.isVisible = false containerTitle.text = resources.getString(R.string.course_list_popular_toolbar_title) val rowCount = resources.getInteger(R.integer.course_list_rows) val columnsCount = resources.getInteger(R.integer.course_list_columns) tableLayoutManager = TableLayoutManager(requireContext(), columnsCount, rowCount, RecyclerView.HORIZONTAL, false) with(courseListCoursesRecycler) { layoutManager = tableLayoutManager itemAnimator?.changeDuration = 0 val snapHelper = CoursesSnapHelper(rowCount) snapHelper.attachToRecyclerView(this) setOnPaginationListener { pageDirection -> if (pageDirection == PaginationDirection.NEXT) { courseListQueryPresenter.fetchNextPage() } } } val courseListQuery = CourseListQuery( page = 1, order = CourseListQuery.Order.ACTIVITY_DESC, isCataloged = true, filterQuery = CourseListFilterQuery(language = sharedPreferenceHelper.languageForFeatured) ) catalogBlockContainer.setOnClickListener { screenManager.showCoursesByQuery( requireContext(), resources.getString(R.string.course_list_popular_toolbar_title), courseListQuery ) } courseListPlaceholderEmpty.setOnClickListener { screenManager.showCatalog(requireContext()) } courseListPlaceholderEmpty.setPlaceholderText(R.string.empty_courses_popular) courseListPlaceholderNoConnection.setOnClickListener { courseListQueryPresenter.fetchCourses(courseListQuery = courseListQuery, forceUpdate = true) } courseListPlaceholderNoConnection.setText(R.string.internet_problem) val viewStateDelegate = ViewStateDelegate<CourseListView.State>() viewStateDelegate.addState<CourseListView.State.Idle>(catalogBlockContainer) viewStateDelegate.addState<CourseListView.State.Loading>(catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Content>(catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Empty>(courseListPlaceholderEmpty) viewStateDelegate.addState<CourseListView.State.NetworkError>(courseListPlaceholderNoConnection) courseListViewDelegate = CourseListViewDelegate( analytic = analytic, courseContinueViewDelegate = CourseContinueViewDelegate( activity = requireActivity(), analytic = analytic, screenManager = screenManager ), courseListTitleContainer = catalogBlockContainer, courseItemsRecyclerView = courseListCoursesRecycler, courseListViewStateDelegate = viewStateDelegate, onContinueCourseClicked = { courseListItem -> courseListQueryPresenter .continueCourse( course = courseListItem.course, viewSource = CourseViewSource.Query(courseListQuery), interactionSource = CourseContinueInteractionSource.COURSE_WIDGET ) }, defaultPromoCodeMapper = defaultPromoCodeMapper, displayPriceMapper = displayPriceMapper ) courseListQueryPresenter.fetchCourses(courseListQuery) } private fun injectComponent() { App.component() .courseListQueryComponentBuilder() .build() .inject(this) } override fun setState(state: CourseListQueryView.State) { val courseListState = (state as? CourseListQueryView.State.Data)?.courseListViewState ?: CourseListView.State.Idle if (courseListState == CourseListView.State.Empty) { analytic.reportEvent(Analytic.Error.FEATURED_EMPTY) } if (courseListState is CourseListView.State.Content) { tableLayoutHorizontalSpanCountResolver.resolveSpanCount(courseListState.courseListDataItems.size).let { resolvedSpanCount -> if (tableLayoutManager.spanCount != resolvedSpanCount) { tableLayoutManager.spanCount = resolvedSpanCount } } } courseListViewDelegate.setState(courseListState) } override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) { courseListViewDelegate.showCourse(course, source, isAdaptive) } override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) { courseListViewDelegate.showSteps(course, source, lastStep) } override fun setBlockingLoading(isLoading: Boolean) { courseListViewDelegate.setBlockingLoading(isLoading) } override fun showNetworkError() { courseListViewDelegate.showNetworkError() } override fun onStart() { super.onStart() courseListQueryPresenter.attachView(this) } override fun onStop() { courseListQueryPresenter.detachView(this) super.onStop() } }
app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListPopularFragment.kt
1390030592
import java.util.* fun main(args: Array<String>) { val vowels = listOf('a', 'e', 'i', 'o', 'u') val digits = "1234567890".toList() val s = Scanner(System.`in`) with(s) { var total = 0 nextLine() .forEach { when (it) { in vowels -> { total++ } in digits -> { if (it.toInt() % 2 == 1) { total++ } } } } println(total) } }
CodeForces/908A.kt
2195825938
package me.liuqingwen.android.projectsimpleanimation import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.animation.DecelerateInterpolator import kotlinx.android.synthetic.main.layout_activity_main.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.displayMetrics class MainActivity : AppCompatActivity(), AnkoLogger { private var sunYStart = 0f private var sunYEnd = 0f private var duration = 10000L private var sunSetDelay = 2000L override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.init() } private fun init() { //this.skyView.translationY = - this.skyView.height.toFloat() this.sunYStart = this.sunView.top.toFloat() this.sunYEnd = this.displayMetrics.heightPixels.toFloat() this.skyView.alpha = 0.0f this.sunSet() } private fun sunSet() { val animSun = ObjectAnimator.ofFloat(this.sunView, "y", this.sunYStart, this.sunYEnd).setDuration(this.duration) animSun.interpolator = DecelerateInterpolator() val animSky = ObjectAnimator.ofFloat(this.skyView, "alpha", 0.0f, 1.0f).setDuration(this.duration - 2000) val animSet = AnimatorSet() animSet.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { [email protected]() } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) animSet.play(animSun).with(animSky) animSet.startDelay = this.sunSetDelay animSet.start() } private fun sunRise() { val animSun = ObjectAnimator.ofFloat(this.sunView, "y", this.sunYEnd, this.sunYStart).setDuration(this.duration) //anim.interpolator = DecelerateInterpolator() val animSky = ObjectAnimator.ofFloat(this.skyView, "alpha", 1.0f, 0.0f).setDuration(this.duration - 2000) val animSet = AnimatorSet() animSet.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) {} override fun onAnimationEnd(animation: Animator?) { [email protected]() } override fun onAnimationCancel(animation: Animator?) {} override fun onAnimationStart(animation: Animator?) {} }) animSet.play(animSun).with(animSky) animSet.start() } }
ProjectSimpleAnimation/app/src/main/java/me/liuqingwen/android/projectsimpleanimation/MainActivity.kt
2803827714
package com.marknjunge.core.data.network.interceptors import android.content.Context import android.net.ConnectivityManager import com.marknjunge.core.utils.NoInternetException import okhttp3.Interceptor import okhttp3.Response internal class NetworkConnectionInterceptor(private val context: Context) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { if (!isInternetAvailable()) { throw NoInternetException() } return chain.proceed(chain.request()) } private fun isInternetAvailable(): Boolean { val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager connectivityManager.activeNetworkInfo.also { return it != null } } }
core/src/main/java/com/marknjunge/core/data/network/interceptors/NetworkConnectionInterceptor.kt
1006420778
package com.gkzxhn.mygithub.bean.info /** * Created by Xuezhi on 2017/10/26. */ data class Stargazers( val login: String, //octocat val id: Int, //1 val avatar_url: String, //https://github.com/images/error/octocat_happy.gif val gravatar_id: String, val url: String, //https://api.github.com/users/octocat val html_url: String, //https://github.com/octocat val followers_url: String, //https://api.github.com/users/octocat/followers val following_url: String, //https://api.github.com/users/octocat/following{/other_user} val gists_url: String, //https://api.github.com/users/octocat/gists{/gist_id} val starred_url: String, //https://api.github.com/users/octocat/starred{/owner}{/repo} val subscriptions_url: String, //https://api.github.com/users/octocat/subscriptions val organizations_url: String, //https://api.github.com/users/octocat/orgs val repos_url: String, //https://api.github.com/users/octocat/repos val events_url: String, //https://api.github.com/users/octocat/events{/privacy} val received_events_url: String, //https://api.github.com/users/octocat/received_events val type: String, //User val site_admin: Boolean //false ) data class Starred( val id: Int, //1296269 val owner: Owner, val name: String, //Hello-World val full_name: String, //octocat/Hello-World val description: String, //This your first repo! val private: Boolean, //false val fork: Boolean, //false val url: String, //https://api.github.com/repos/octocat/Hello-World val html_url: String, //https://github.com/octocat/Hello-World val archive_url: String, //http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref} val assignees_url: String, //http://api.github.com/repos/octocat/Hello-World/assignees{/user} val blobs_url: String, //http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha} val branches_url: String, //http://api.github.com/repos/octocat/Hello-World/branches{/branch} val clone_url: String, //https://github.com/octocat/Hello-World.git val collaborators_url: String, //http://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator} val comments_url: String, //http://api.github.com/repos/octocat/Hello-World/comments{/number} val commits_url: String, //http://api.github.com/repos/octocat/Hello-World/commits{/sha} val compare_url: String, //http://api.github.com/repos/octocat/Hello-World/compare/{base}...{head} val contents_url: String, //http://api.github.com/repos/octocat/Hello-World/contents/{+path} val contributors_url: String, //http://api.github.com/repos/octocat/Hello-World/contributors val deployments_url: String, //http://api.github.com/repos/octocat/Hello-World/deployments val downloads_url: String, //http://api.github.com/repos/octocat/Hello-World/downloads val events_url: String, //http://api.github.com/repos/octocat/Hello-World/events val forks_url: String, //http://api.github.com/repos/octocat/Hello-World/forks val git_commits_url: String, //http://api.github.com/repos/octocat/Hello-World/git/commits{/sha} val git_refs_url: String, //http://api.github.com/repos/octocat/Hello-World/git/refs{/sha} val git_tags_url: String, //http://api.github.com/repos/octocat/Hello-World/git/tags{/sha} val git_url: String, //git:github.com/octocat/Hello-World.git val hooks_url: String, //http://api.github.com/repos/octocat/Hello-World/hooks val issue_comment_url: String, //http://api.github.com/repos/octocat/Hello-World/issues/comments{/number} val issue_events_url: String, //http://api.github.com/repos/octocat/Hello-World/issues/events{/number} val issues_url: String, //http://api.github.com/repos/octocat/Hello-World/issues{/number} val keys_url: String, //http://api.github.com/repos/octocat/Hello-World/keys{/key_id} val labels_url: String, //http://api.github.com/repos/octocat/Hello-World/labels{/name} val languages_url: String, //http://api.github.com/repos/octocat/Hello-World/languages val merges_url: String, //http://api.github.com/repos/octocat/Hello-World/merges val milestones_url: String, //http://api.github.com/repos/octocat/Hello-World/milestones{/number} val mirror_url: String, //git:git.example.com/octocat/Hello-World val notifications_url: String, //http://api.github.com/repos/octocat/Hello-World/notifications{?since, all, participating} val pulls_url: String, //http://api.github.com/repos/octocat/Hello-World/pulls{/number} val releases_url: String, //http://api.github.com/repos/octocat/Hello-World/releases{/id} val ssh_url: String, //[email protected]:octocat/Hello-World.git val stargazers_url: String, //http://api.github.com/repos/octocat/Hello-World/stargazers val statuses_url: String, //http://api.github.com/repos/octocat/Hello-World/statuses/{sha} val subscribers_url: String, //http://api.github.com/repos/octocat/Hello-World/subscribers val subscription_url: String, //http://api.github.com/repos/octocat/Hello-World/subscription val svn_url: String, //https://svn.github.com/octocat/Hello-World val tags_url: String, //http://api.github.com/repos/octocat/Hello-World/tags val teams_url: String, //http://api.github.com/repos/octocat/Hello-World/teams val trees_url: String, //http://api.github.com/repos/octocat/Hello-World/git/trees{/sha} val homepage: String, //https://github.com val language: Any, //null val forks_count: Int, //9 val stargazers_count: Int, //80 val watchers_count: Int, //80 val size: Int, //108 val default_branch: String, //master val open_issues_count: Int, //0 val topics: List<String>, val has_issues: Boolean, //true val has_wiki: Boolean, //true val has_pages: Boolean, //false val has_downloads: Boolean, //true val pushed_at: String, //2011-01-26T19:06:43Z val created_at: String, //2011-01-26T19:01:12Z val updated_at: String, //2011-01-26T19:14:43Z val permissions: Permissions, val allow_rebase_merge: Boolean, //true val allow_squash_merge: Boolean, //true val allow_merge_commit: Boolean, //true val subscribers_count: Int, //42 val network_count: Int //0 )
app/src/main/java/com/gkzxhn/mygithub/bean/info/Stars.kt
229513973
package abi42_0_0.host.exp.exponent.modules.api.components.webview.events import abi42_0_0.com.facebook.react.bridge.WritableMap import abi42_0_0.com.facebook.react.uimanager.events.Event import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when shouldOverrideUrlLoading is called */ class TopShouldStartLoadWithRequestEvent(viewId: Int, private val mData: WritableMap) : Event<TopShouldStartLoadWithRequestEvent>(viewId) { companion object { const val EVENT_NAME = "topShouldStartLoadWithRequest" } init { mData.putString("navigationType", "other") // Android does not raise shouldOverrideUrlLoading for inner frames mData.putBoolean("isTopFrame", true) } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, mData) }
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopShouldStartLoadWithRequestEvent.kt
1365678220
/* * Copyright 2017 DevJake * * 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 me.salt.entities.config.entities internal class SaltLanguageConfig : Config internal class GuildLanguageConfig : Config internal class TextChannelLanguageConfig : Config internal class UserLanguageConfig : Config
src/main/kotlin/me/salt/entities/config/entities/LanguageConfigs.kt
3996202977
/* * Copyright © 2014 Stefan Niederhauser ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package guru.nidi.jenkins.remote import org.apache.http.util.EntityUtils import org.junit.Assert.assertTrue import org.junit.Ignore import org.junit.Test import javax.net.ssl.SSLHandshakeException class JenkinsConnectTest { @Test fun simpleConnect() { val connect = JenkinsConnect(Server.APACHE) connect.get("") { res -> assertTrue(EntityUtils.toString(res.entity).length > 1000) } } @Ignore("different key stores locally and on travis?") @Test(expected = JenkinsException::class) fun unknownCertNok() { val connect = JenkinsConnect(Server.JENKINS) connect.get("") {} } @Test fun unknownCertOk() { val connect = JenkinsConnect(Server.JENKINS, verifyCertificate = false) connect.get("") {} } }
jenkins-remote-client/src/test/kotlin/guru/nidi/jenkins/remote/JenkinsConnectTest.kt
1474317349
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire actual typealias GrpcResponseBody = okhttp3.ResponseBody
wire-library/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponseBody.kt
3793532454
package com.intellij.workspaceModel.storage.entities.unknowntypes.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import java.util.Date import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class UnknownFieldEntityImpl: UnknownFieldEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: Date? = null override val data: Date get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: UnknownFieldEntityData?): ModifiableWorkspaceEntityBase<UnknownFieldEntity>(), UnknownFieldEntity.Builder { constructor(): this(UnknownFieldEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity UnknownFieldEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isDataInitialized()) { error("Field UnknownFieldEntity#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field UnknownFieldEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: Date get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): UnknownFieldEntityData = result ?: super.getEntityData() as UnknownFieldEntityData override fun getEntityClass(): Class<UnknownFieldEntity> = UnknownFieldEntity::class.java } } class UnknownFieldEntityData : WorkspaceEntityData<UnknownFieldEntity>() { lateinit var data: Date fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<UnknownFieldEntity> { val modifiable = UnknownFieldEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): UnknownFieldEntity { val entity = UnknownFieldEntityImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return UnknownFieldEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as UnknownFieldEntityData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as UnknownFieldEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/unknowntypes/test/api/UnknownFieldEntityImpl.kt
1523723033
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExternalLibraryDescriptor import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinJvmBundle import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.configuration.findApplicableConfigurator import org.jetbrains.kotlin.idea.facet.getRuntimeLibraryVersion import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtImportDirective class AddReflectionQuickFix(element: KtElement) : AddKotlinLibQuickFix(element, LibraryJarDescriptor.REFLECT_JAR, DependencyScope.COMPILE) { override fun getText() = KotlinJvmBundle.message("classpath.add.reflection") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-reflect", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType(::AddReflectionQuickFix) } } class AddScriptRuntimeQuickFix(element: KtElement) : AddKotlinLibQuickFix( element, LibraryJarDescriptor.SCRIPT_RUNTIME_JAR, DependencyScope.COMPILE ) { override fun getText() = KotlinJvmBundle.message("classpath.add.script.runtime") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-script-runtime", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtElement>? = diagnostic.createIntentionForFirstParentOfType(::AddScriptRuntimeQuickFix) } } class AddTestLibQuickFix(element: KtElement) : AddKotlinLibQuickFix(element, LibraryJarDescriptor.TEST_JAR, DependencyScope.TEST) { override fun getText() = KotlinJvmBundle.message("classpath.add.kotlin.test") override fun getFamilyName() = text override fun getLibraryDescriptor(module: Module) = MavenExternalLibraryDescriptor.create( "org.jetbrains.kotlin", "kotlin-test", getRuntimeLibraryVersion(module) ?: KotlinPluginLayout.standaloneCompilerVersion ) companion object : KotlinSingleIntentionActionFactory() { val KOTLIN_TEST_UNRESOLVED = setOf( "Asserter", "assertFailsWith", "currentStackTrace", "failsWith", "todo", "assertEquals", "assertFails", "assertNot", "assertNotEquals", "assertNotNull", "assertNull", "assertTrue", "expect", "fail", "fails" ) override fun createAction(diagnostic: Diagnostic): IntentionAction? { val unresolvedReference = Errors.UNRESOLVED_REFERENCE.cast(diagnostic) if (PsiTreeUtil.getParentOfType(diagnostic.psiElement, KtImportDirective::class.java) != null) return null val unresolvedText = unresolvedReference.a.text if (unresolvedText in KOTLIN_TEST_UNRESOLVED) { val ktFile = (diagnostic.psiElement.containingFile as? KtFile) ?: return null val exactImportFqName = FqName("kotlin.test.$unresolvedText") val kotlinTestAllUnder = FqName("kotlin.test") var hasExactImport = false var hasKotlinTestAllUnder = false for (importDirective in ktFile.importDirectives.filter { it.text.contains("kotlin.test.") }) { if (importDirective.importedFqName == exactImportFqName) { hasExactImport = true break } if (importDirective.importedFqName == kotlinTestAllUnder && importDirective.isAllUnder) { hasKotlinTestAllUnder = true break } } if (hasExactImport || hasKotlinTestAllUnder) { return diagnostic.createIntentionForFirstParentOfType(::AddTestLibQuickFix) } } return null } } } abstract class AddKotlinLibQuickFix( element: KtElement, private val libraryJarDescriptor: LibraryJarDescriptor, private val scope: DependencyScope ) : KotlinQuickFixAction<KtElement>(element) { protected abstract fun getLibraryDescriptor(module: Module): MavenExternalLibraryDescriptor class MavenExternalLibraryDescriptor private constructor( groupId: String, artifactId: String, version: String ): ExternalLibraryDescriptor(groupId, artifactId, version, version) { companion object { fun create(groupId: String, artifactId: String, version: IdeKotlinVersion): MavenExternalLibraryDescriptor { val artifactVersion = version.artifactVersion return MavenExternalLibraryDescriptor(groupId, artifactId, artifactVersion) } } override fun getLibraryClassesRoots(): List<String> = emptyList() } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val module = ProjectRootManager.getInstance(project).fileIndex.getModuleForFile(element.containingFile.virtualFile) ?: return val configurator = findApplicableConfigurator(module) configurator.addLibraryDependency(module, element, getLibraryDescriptor(module), libraryJarDescriptor, scope) } override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/inspections/AddKotlinLibQuickFix.kt
2345182556
package me.elsiff.morefish.configuration.loader import me.elsiff.morefish.configuration.Config import me.elsiff.morefish.configuration.ConfigurationValueAccessor import me.elsiff.morefish.configuration.translated import me.elsiff.morefish.fishing.FishRarity import me.elsiff.morefish.fishing.catchhandler.CatchCommandExecutor import me.elsiff.morefish.fishing.catchhandler.CatchHandler /** * Created by elsiff on 2019-01-09. */ class FishRaritySetLoader( private val chatColorLoader: ChatColorLoader, private val playerAnnouncementLoader: PlayerAnnouncementLoader ) : CustomLoader<Set<FishRarity>> { override fun loadFrom(section: ConfigurationValueAccessor, path: String): Set<FishRarity> { return section[path].children.map { val catchHandlers = mutableListOf<CatchHandler>() if (it.contains("commands")) { val handler = CatchCommandExecutor(it.strings("commands").translated()) catchHandlers.add(handler) } FishRarity( name = it.name, displayName = it.string("display-name").translated(), default = it.boolean("default", false), probability = it.double("chance", 0.0) / 100.0, color = chatColorLoader.loadFrom(it, "color"), catchHandlers = catchHandlers, catchAnnouncement = playerAnnouncementLoader.loadIfExists(it, "catch-announce") ?: Config.defaultCatchAnnouncement, hasNotFishItemFormat = it.boolean("skip-item-format", false), noDisplay = it.boolean("no-display", false), hasCatchFirework = it.boolean("firework", false), additionalPrice = it.double("additional-price", 0.0) ) }.toSet() } }
src/main/kotlin/me/elsiff/morefish/configuration/loader/FishRaritySetLoader.kt
2972330193
package forpdateam.ru.forpda.entity.remote.qms /** * Created by radiationx on 03.08.16. */ interface IQmsContact { var nick: String? var id: Int var count: Int var avatar: String? }
app/src/main/java/forpdateam/ru/forpda/entity/remote/qms/IQmsContact.kt
2810219801
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.recurrent.simple import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.layers.helpers.BackwardHelper import com.kotlinnlp.simplednn.core.arrays.getInputErrors import com.kotlinnlp.simplednn.simplemath.ndarray.NDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * The helper which executes the backward on a [layer]. * * @property layer the [SimpleRecurrentLayer] in which the backward is executed */ internal class SimpleRecurrentBackwardHelper<InputNDArrayType : NDArray<InputNDArrayType>>( override val layer: SimpleRecurrentLayer<InputNDArrayType> ) : BackwardHelper<InputNDArrayType>(layer) { /** * Executes the backward calculating the errors of the parameters and eventually of the input through the SGD * algorithm, starting from the preset errors of the output array. * * @param propagateToInput whether to propagate the errors to the input array */ override fun execBackward(propagateToInput: Boolean) { val prevStateLayer = this.layer.layersWindow.getPrevState() val nextStateLayer = this.layer.layersWindow.getNextState() if (nextStateLayer != null) { this.addLayerRecurrentGradients(nextStateLayer as SimpleRecurrentLayer<*>) } this.layer.applyOutputActivationDeriv() // must be applied AFTER having added the recurrent contribution this.assignParamsGradients(prevStateLayer?.outputArray) if (propagateToInput) { this.assignLayerGradients() } } /** * gb = gy * 1 * gw = gb (dot) x * gwRec = gy (dot) yPrev * * @param prevStateOutput the output array in the previous state */ private fun assignParamsGradients(prevStateOutput: AugmentedArray<DenseNDArray>?) { this.layer.outputArray.assignParamsGradients( gw = this.layer.params.unit.weights.errors.values, gb = this.layer.params.unit.biases.errors.values, gwRec = this.layer.params.unit.recurrentWeights.errors.values, x = this.layer.inputArray.values, yPrev = prevStateOutput?.values) } /** * gx = gb (dot) w */ private fun assignLayerGradients() { this.layer.inputArray.assignErrors(this.layer.outputArray.getInputErrors(w = this.layer.params.unit.weights.values)) } /** * gy += gyNext (dot) wRec */ private fun addLayerRecurrentGradients(nextStateLayer: SimpleRecurrentLayer<*>) { val gy: DenseNDArray = this.layer.outputArray.errors val gRec: DenseNDArray = nextStateLayer.outputArray.getRecurrentErrors(parameters = this.layer.params.unit) gy.assignSum(gRec) } }
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/recurrent/simple/SimpleRecurrentBackwardHelper.kt
3383069259
package org.wordpress.android.ui.main.jetpack.migration.compose.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.unit.dp import org.wordpress.android.R @Composable fun SecondaryButton( text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true ) { Button( onClick = onClick, enabled = enabled, elevation = ButtonDefaults.elevation( defaultElevation = 0.dp, pressedElevation = 0.dp, ), colors = ButtonDefaults.buttonColors( backgroundColor = Color.Transparent, contentColor = MaterialTheme.colors.primary, disabledBackgroundColor = Color.Transparent, disabledContentColor = MaterialTheme.colors.primary, ), modifier = modifier .padding(bottom = 10.dp) .padding(horizontal = dimensionResource(R.dimen.jp_migration_buttons_padding_horizontal)) .fillMaxWidth() ) { Text(text = text) } }
WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/compose/components/SecondaryButton.kt
1148879748
package com.rohitsuratekar.NCBSinfo.database import androidx.room.* /** * Created by Rohit Suratekar on 20-06-17 for NCBSinfo. * All code is released under MIT License. */ @Dao interface TripsDao { @Insert fun insertTrips(tripData: TripData): Long // Will return 0 id not found @Query( "SELECT tripID FROM trips " + "WHERE routeID LIKE :routeID AND " + "day LIKE :day " ) fun getTripID(routeID: Int, day: Int): Int @Update fun updateTrips(tripData: TripData) @Query("SELECT * FROM trips " + "WHERE routeID LIKE :routeID ") fun getTripsByRoute(routeID: Int): List<TripData> @Query("SELECT * FROM trips WHERE tripID LIKE :tripID") fun getTrip(tripID: Int): TripData @Delete fun deleteTrip(tripData: TripData) @Query("DELETE FROM trips " + "WHERE routeID LIKE :routeID ") fun deleteTripsByRoute(routeID: Int) @Query("DELETE FROM trips " + "WHERE tripID LIKE :tripID ") fun deleteTripsByTrip(tripID: Int) @Query("DELETE FROM trips") fun deleteAll() }
app/src/main/java/com/rohitsuratekar/NCBSinfo/database/TripsDao.kt
2081376733
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.grazie import com.intellij.grazie.GrazieTestBase class PythonGrazieSupportTest : GrazieTestBase() { override fun getBasePath() = "python/testData/grazie/" override fun isCommunity() = true fun `test grammar check in constructs`() { runHighlightTestForFile("Constructs.py") } fun `test grammar check in docs`() { runHighlightTestForFile("Docs.py") } fun `test grammar check in comments`() { runHighlightTestForFile("Comments.py") } fun `test grammar check in string literals`() { runHighlightTestForFile("StringLiterals.py") } }
python/testSrc/com/jetbrains/python/grazie/PythonGrazieSupportTest.kt
1932562488
// 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.idea.fir import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.impl.search.AllClassesSearchExecutor import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StringStubIndexExtension import org.jetbrains.kotlin.analysis.project.structure.allDirectDependencies import org.jetbrains.kotlin.analysis.project.structure.getKtModule import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.base.utils.fqname.isJavaClassNotToBeUsedInKotlin import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.idea.util.isSyntheticKotlinClass import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration /* * Move to another module */ class HLIndexHelper(val project: Project, private val scope: GlobalSearchScope) { fun getTopLevelCallables(nameFilter: (Name) -> Boolean): Collection<KtCallableDeclaration> { fun sequenceOfElements(index: StringStubIndexExtension<out KtCallableDeclaration>): Sequence<KtCallableDeclaration> = index.getAllKeys(project).asSequence() .onEach { ProgressManager.checkCanceled() } .filter { fqName -> nameFilter(getShortName(fqName)) } .flatMap { fqName -> index[fqName, project, scope] } .filter { it.receiverTypeReference == null } val functions = sequenceOfElements(KotlinTopLevelFunctionFqnNameIndex) val properties = sequenceOfElements(KotlinTopLevelPropertyFqnNameIndex) return (functions + properties).toList() } fun getTopLevelExtensions(nameFilter: (Name) -> Boolean, receiverTypeNames: Set<String>): Collection<KtCallableDeclaration> { val index = KotlinTopLevelExtensionsByReceiverTypeIndex return index.getAllKeys(project).asSequence() .onEach { ProgressManager.checkCanceled() } .filter { KotlinTopLevelExtensionsByReceiverTypeIndex.receiverTypeNameFromKey(it) in receiverTypeNames } .filter { nameFilter(Name.identifier(KotlinTopLevelExtensionsByReceiverTypeIndex.callableNameFromKey(it))) } .flatMap { key -> index[key, project, scope] } .toList() } fun getPossibleTypeAliasExpansionNames(originalTypeName: String): Set<String> { val index = KotlinTypeAliasByExpansionShortNameIndex val out = mutableSetOf<String>() fun searchRecursively(typeName: String) { ProgressManager.checkCanceled() index[typeName, project, scope].asSequence() .mapNotNull { it.name } .filter { out.add(it) } .forEach(::searchRecursively) } searchRecursively(originalTypeName) return out } companion object { private fun FqName.asStringForIndexes(): String = asString().replace('/', '.') private fun ClassId.asStringForIndexes(): String = asSingleFqName().asStringForIndexes() private fun getShortName(fqName: String) = Name.identifier(fqName.substringAfterLast('.')) @OptIn(ExperimentalStdlibApi::class) fun createForPosition(position: PsiElement): HLIndexHelper { val module = position.getKtModule() val allScopes = module.allDirectDependencies().mapTo(mutableSetOf()) { it.contentScope } allScopes.add(module.contentScope) return HLIndexHelper(position.project, GlobalSearchScope.union(allScopes)) } } }
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/IndexHelper.kt
3546755066
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class LibraryExternalSystemIdEntityImpl : LibraryExternalSystemIdEntity, WorkspaceEntityBase() { companion object { internal val LIBRARY_CONNECTION_ID: ConnectionId = ConnectionId.create(LibraryEntity::class.java, LibraryExternalSystemIdEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( LIBRARY_CONNECTION_ID, ) } @JvmField var _externalSystemId: String? = null override val externalSystemId: String get() = _externalSystemId!! override val library: LibraryEntity get() = snapshot.extractOneToOneParent(LIBRARY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: LibraryExternalSystemIdEntityData?) : ModifiableWorkspaceEntityBase<LibraryExternalSystemIdEntity>(), LibraryExternalSystemIdEntity.Builder { constructor() : this(LibraryExternalSystemIdEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity LibraryExternalSystemIdEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isExternalSystemIdInitialized()) { error("Field LibraryExternalSystemIdEntity#externalSystemId should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(LIBRARY_CONNECTION_ID, this) == null) { error("Field LibraryExternalSystemIdEntity#library should be initialized") } } else { if (this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] == null) { error("Field LibraryExternalSystemIdEntity#library should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as LibraryExternalSystemIdEntity this.entitySource = dataSource.entitySource this.externalSystemId = dataSource.externalSystemId if (parents != null) { this.library = parents.filterIsInstance<LibraryEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var externalSystemId: String get() = getEntityData().externalSystemId set(value) { checkModificationAllowed() getEntityData().externalSystemId = value changedProperty.add("externalSystemId") } override var library: LibraryEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(LIBRARY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity } else { this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)]!! as LibraryEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToOneParentOfChild(LIBRARY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*>) { value.entityLinks[EntityLink(true, LIBRARY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, LIBRARY_CONNECTION_ID)] = value } changedProperty.add("library") } override fun getEntityData(): LibraryExternalSystemIdEntityData = result ?: super.getEntityData() as LibraryExternalSystemIdEntityData override fun getEntityClass(): Class<LibraryExternalSystemIdEntity> = LibraryExternalSystemIdEntity::class.java } } class LibraryExternalSystemIdEntityData : WorkspaceEntityData<LibraryExternalSystemIdEntity>() { lateinit var externalSystemId: String fun isExternalSystemIdInitialized(): Boolean = ::externalSystemId.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<LibraryExternalSystemIdEntity> { val modifiable = LibraryExternalSystemIdEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): LibraryExternalSystemIdEntity { val entity = LibraryExternalSystemIdEntityImpl() entity._externalSystemId = externalSystemId entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return LibraryExternalSystemIdEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return LibraryExternalSystemIdEntity(externalSystemId, entitySource) { this.library = parents.filterIsInstance<LibraryEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(LibraryEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryExternalSystemIdEntityData if (this.entitySource != other.entitySource) return false if (this.externalSystemId != other.externalSystemId) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as LibraryExternalSystemIdEntityData if (this.externalSystemId != other.externalSystemId) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + externalSystemId.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + externalSystemId.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/LibraryExternalSystemIdEntityImpl.kt
4088148077
/* * Thrifty * * Copyright (c) Microsoft Corporation * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import java.util.Collections import java.util.concurrent.atomic.AtomicInteger class ThriftTypeTest { @Test fun byteAndI8AreSynonyms() { val ctr = AtomicInteger(0) val v = object : ThriftType.Visitor<Unit> { override fun visitVoid(voidType: BuiltinType) { } override fun visitBool(boolType: BuiltinType) { } override fun visitByte(byteType: BuiltinType) { ctr.incrementAndGet() } override fun visitI16(i16Type: BuiltinType) { } override fun visitI32(i32Type: BuiltinType) { } override fun visitI64(i64Type: BuiltinType) { } override fun visitDouble(doubleType: BuiltinType) { } override fun visitString(stringType: BuiltinType) { } override fun visitBinary(binaryType: BuiltinType) { } override fun visitEnum(enumType: EnumType) { } override fun visitList(listType: ListType) { } override fun visitSet(setType: SetType) { } override fun visitMap(mapType: MapType) { } override fun visitStruct(structType: StructType) { } override fun visitTypedef(typedefType: TypedefType) { } override fun visitService(serviceType: ServiceType) { } } BuiltinType.I8.accept(v) BuiltinType.BYTE.accept(v) BuiltinType.I8.isBuiltin shouldBe true ctr.get() shouldBe 2 } @Test fun typesWithSameNameAreEqual() { val one = BuiltinType.get("i32") val two = BuiltinType.get("i32") one shouldBe two } @Test fun annotationsDoNotAffectEquality() { val one = BuiltinType.get("i32")!!.withAnnotations(Collections.singletonMap("test", "one")) val two = BuiltinType.get("i32")!!.withAnnotations(Collections.singletonMap("test", "two")) one shouldBe two } @Test fun withAnnotationsMergesAnnotations() { val one = BuiltinType.get("i32")!!.withAnnotations(Collections.singletonMap("i32", "bar")) val two = one.withAnnotations(Collections.singletonMap("baz", "quux")) two.annotations["i32"] shouldBe "bar" two.annotations["baz"] shouldBe "quux" } }
thrifty-schema/src/test/kotlin/com/microsoft/thrifty/schema/ThriftTypeTest.kt
256280812
package c import a.A as AA import a.foo as foofoo import a.x as xx fun bar() { val t: AA = AA() foofoo() println(xx) xx = "" }
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/movePackage/movePackage/before/c/specificImportsWithAliases.kt
1663873884
// MOVE: up fun test() { for (i in 1..10) { run { } } <caret>println() }
plugins/kotlin/idea/tests/testData/codeInsight/moveUpDown/expressions/lambdaInFor2.kt
3622207502
package test interface A class <caret>B(val bar: A = object: A {}, val withError = object: A {}, notProperty = object: A {})
plugins/kotlin/idea/tests/testData/javaFacade/ClassWithObjectLiteralInConstructorProperty.kt
3979902122
package edu.byu.suite.features.cougarCash.model /** * Created by poolguy on 12/22/16 */ data class StartPaymentPost(var amount: Double, var paymentTypeId: String?)
app/src/main/java/edu/byu/suite/features/cougarCash/model/StartPaymentPost.kt
3549807550
/** * Copyright 2016 Stealth2800 <http://stealthyone.com/> * Copyright 2016 Contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexlib.command import me.st28.flexseries.flexlib.logging.LogHelper import me.st28.flexseries.flexlib.plugin.FlexPlugin import org.bukkit.Bukkit import org.bukkit.command.CommandMap import org.bukkit.command.CommandSender import org.bukkit.entity.Player import java.util.* import kotlin.reflect.KFunction import kotlin.reflect.declaredMemberFunctions import kotlin.reflect.defaultType /** * Handles command registration for a [FlexPlugin]. */ class FlexCommandMap(val plugin: FlexPlugin) { internal companion object { val bukkit_commandMap: CommandMap //val bukkit_registerMethod: Method init { val pluginManager = Bukkit.getPluginManager() val commandMap = pluginManager.javaClass.getDeclaredField("commandMap") commandMap.isAccessible = true bukkit_commandMap = commandMap.get(pluginManager) as CommandMap //bukkit_registerMethod = bukkit_commandMap.javaClass.getDeclaredMethod("register", String::class.java, Command::class.java) } /** * Registers a FlexCommand's Bukkit command with Bukkit's plugin manager via reflection. */ private fun registerBukkitCommand(plugin: FlexPlugin, command: FlexCommand) { try { //bukkit_registerMethod.invoke(bukkit_commandMap, plugin.name.toLowerCase(), command.bukkitCommand) bukkit_commandMap.register(plugin.name.toLowerCase(), command.bukkitCommand) } catch (ex: Exception) { LogHelper.severe(plugin, "An exception occurred while registering command with Bukkit", ex) } } } /** * Registers an object containing methods annotated with [CommandHandler] that represent * command handlers. */ fun register(obj: Any) { val commandModule = FlexPlugin.getGlobalModule(CommandModule::class)!! outer@ for (f in obj.javaClass.kotlin.declaredMemberFunctions) { val meta: CommandHandler = f.annotations.find { it is CommandHandler } as CommandHandler? ?: continue // Parameter 0 of the function is the instance of the class (object in this case) // 1) Determine if function is player only based on the first parameter. // 2) Determine if function is player only based on the first parameter. Otherwise, it // must be a CommandSender. val playerOnly: Boolean = when (f.parameters[1].type) { Player::class.defaultType -> true CommandSender::class.defaultType -> false else -> { LogHelper.severe(plugin, "Invalid command handler '${f.name}': first parameter is not a CommandSender or Player") continue@outer } } // 3) Get base command (or create and register it if it doesn't exist) val commandPath: Stack<String> = Stack() commandPath.addAll(meta.command.split(" ").reversed()) if (commandPath.peek() == "%") { LogHelper.severe(plugin, "Base command can not have reversed arguments") continue@outer } val baseLabel = commandPath.pop() var base = commandModule.getBaseCommand(plugin.javaClass.kotlin, baseLabel) if (base == null) { // Base doesn't exist, create and register it with the command module. base = FlexCommand(plugin, baseLabel) commandModule.registerCommand(base) registerBukkitCommand(plugin, base) } // 2) Iterate through labels until subcommand is found (creating along the way) var subcmd: BasicCommand = base var offset = 0 while (commandPath.isNotEmpty()) { val curLabel = commandPath.pop() // Check for reverse subcommands if (curLabel == "%") { // Find offset while (commandPath.peek() == "%") { ++offset commandPath.pop() } val newLabel = commandPath.pop() // Look for reverse subcommand var temp: BasicCommand? = null for (entry in subcmd.reverseSubcommands) { if (entry.first == offset && entry.second == newLabel) { // Found existing //subcmd = entry.third temp = entry.third break } } if (temp == null) { // Command not found, create it temp = BasicCommand(plugin, newLabel) subcmd.reverseSubcommands.add(Triple(offset, newLabel, BasicCommand(plugin, newLabel))) } subcmd = temp continue } /* No reverse subcommand, look for normal subcommands */ offset = 0 var temp: BasicCommand? = subcmd.subcommands[curLabel] if (temp == null) { // Subcommand doesn't exist, create it now temp = BasicCommand(plugin, curLabel) subcmd.registerSubcommand(temp) } subcmd = temp } // 3) Set command executor //subcmd.setMeta(meta, playerOnly, obj, f as KFunction<Any>) subcmd.executors.add(CommandExecutor(meta, playerOnly, subcmd, obj, f as KFunction<Any>, offset)) // 4) Set default if (meta.isDefault) { subcmd.parent?.defaultSubcommand = subcmd.label } } } fun getCommand(path: String): BasicCommand? { val split = ("${plugin.name.toLowerCase()}:$path").split(" ") var found: BasicCommand = (bukkit_commandMap.getCommand(split[0]) as? FlexCommand.WrappedBukkitCommand)?.flexCommand ?: return null for ((index, name) in split.withIndex()) { if (index == 0) { continue } found = found.subcommands[name] ?: return null } return found } }
src/main/kotlin/me/st28/flexseries/flexlib/command/FlexCommandMap.kt
3418221353
package com.kiwiandroiddev.sc2buildassistant.feature.settings.data import android.content.Context import com.kiwiandroiddev.sc2buildassistant.di.qualifiers.ApplicationContext import com.kiwiandroiddev.sc2buildassistant.feature.settings.domain.LoadStandardBuildsIntoDatabaseUseCase import com.kiwiandroiddev.sc2buildassistant.service.JsonBuildService import com.kiwiandroiddev.sc2buildassistant.service.StandardBuildsService import io.reactivex.Observable class LoadStandardBuildsIntoDatabaseUseCaseImpl(@ApplicationContext val appContext: Context) : LoadStandardBuildsIntoDatabaseUseCase { override fun loadBuilds(): Observable<Int> = StandardBuildsService.getLoadStandardBuildsIntoDBObservable(appContext, true) .doOnComplete { JsonBuildService.notifyBuildProviderObservers(appContext) } }
app/src/main/java/com/kiwiandroiddev/sc2buildassistant/feature/settings/data/LoadStandardBuildsIntoDatabaseUseCaseImpl.kt
3803273763
package com.austinv11.d4j.bot.command.impl import com.austinv11.d4j.bot.CONFIG import com.austinv11.d4j.bot.command.CommandExecutor import com.austinv11.d4j.bot.command.Executor import com.austinv11.d4j.bot.extensions.isIgnored import sx.blah.discord.handle.obj.IUser class IgnoreCommand : CommandExecutor() { override val name: String = "ignore" override val aliases: Array<String> = arrayOf() @Executor("Makes this bot ignore the specified user.", requiresOwner = true) fun execute(user: IUser): Boolean { user.isIgnored = true return true } }
src/main/kotlin/com/austinv11/d4j/bot/command/impl/IgnoreCommand.kt
2717646132
// Copyright © 2017 Laurence Gonsalves // // This file is part of xenocom, a library which can be found at // http://github.com/xenomachina/xenocom // // This library 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 2.1 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License // for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, see http://www.gnu.org/licenses/ package com.xenomachina.text import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.FunSpec // TODO does kotlintest have a matcher for this? internal fun <T> Sequence<T>.shouldContain(vararg expected: T) { toList() shouldBe expected.toList() } class CodepointSequenceTest : FunSpec() { init { test("empty") { "".codePointSequence().shouldContain() } test("ASCII characters") { "foo".codePointSequence().shouldContain(0x66, 0x6f, 0x6f) } test("non-ASCII, BMP characters") { "你好吗".codePointSequence().shouldContain(0x4f60, 0x597d, 0x5417) } test("non-BMP characters") { "\ud83c\udc1c\ud83d\ude4f".codePointSequence().shouldContain(0x1f01c, 0x1f64f) } } } class StringBuilderClearTest : FunSpec() { init { test("empty") { val sb = StringBuilder() sb.clear() sb.toString() shouldBe "" } test("non-empty") { val sb = StringBuilder() sb.append("hello") sb.clear() sb.toString() shouldBe "" } } } class TrimNewlineTest : FunSpec() { init { test("empty") { "".trimNewline() shouldBe "" } test("just newline") { "\n".trimNewline() shouldBe "" } test("no newline") { "hello world".trimNewline() shouldBe "hello world" } test("text + newline") { "goodbye earth\n".trimNewline() shouldBe "goodbye earth" } test("only last newline is removed") { "what's up moon\n\n\n".trimNewline() shouldBe "what's up moon\n\n" } test("only newline at end is removed") { "so long\nsaturn".trimNewline() shouldBe "so long\nsaturn" } } }
src/test/kotlin/TextTest.kt
1846349013
package com.eden.orchid.swiftdoc.swift.members import com.eden.orchid.api.OrchidContext import com.eden.orchid.swiftdoc.swift.SwiftAttributes import com.eden.orchid.swiftdoc.swift.SwiftMember import com.eden.orchid.swiftdoc.swift.SwiftStatement import org.json.JSONObject class SwiftInstanceVar(context: OrchidContext, data: JSONObject, origin: SwiftStatement) : SwiftMember(context, data, "instanceVar", origin), SwiftAttributes { override lateinit var attributes: List<String> var name: String? = null var type: String? = null override fun init() { super.init() initAttributes(data) name = data.optString("key.name") type = data.optString("key.typename") } }
plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/swift/members/SwiftInstanceVar.kt
2969097923
package com.eden.orchid.swiftdoc.swift.members import com.eden.orchid.api.OrchidContext import com.eden.orchid.swiftdoc.swift.SwiftAttributes import com.eden.orchid.swiftdoc.swift.SwiftMember import com.eden.orchid.swiftdoc.swift.SwiftStatement import org.json.JSONObject class SwiftCommentMark(context: OrchidContext, data: JSONObject, origin: SwiftStatement) : SwiftMember(context, data, "commentMark", origin), SwiftAttributes { override lateinit var attributes: List<String> override fun init() { super.init() initAttributes(data) } }
plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/swift/members/SwiftCommentMark.kt
1764474755
// WITH_STDLIB // FIX: Replace with 'mutableListOf' function import java.util.Arrays fun test() { val a = Arrays.<caret>asList(1, 3, null) }
plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceJavaStaticMethodWithKotlinAnalog/collections/mutableListOf.kt
2044256900
// "Replace with 'c1.newFun(this, c2)'" "true" // WITH_STDLIB class X { @Deprecated("", ReplaceWith("c1.newFun(this, c2)")) fun oldFun(c1: Char, c2: Char): Char = c1.newFun(this, c2) val c: Char = 'a' } fun Char.newFun(x: X, c: Char): Char = this fun foo(s: String, x: X) { val chars = s.filter { O.x?.<caret>oldFun(it, x.c) != 'a' } } object O { var x: X? = null }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/safeCall/changeThisSafeCallWithValue3Runtime.kt
3949478064
package org.kethereum.erc681 import org.kethereum.erc831.ERC831 import org.kethereum.erc831.toERC831 import org.kethereum.model.EthereumURI fun ERC831.isERC681() = scheme == "ethereum" && (prefix == null || prefix == "pay") fun EthereumURI.isERC681() = toERC831().isERC681()
erc681/src/main/kotlin/org/kethereum/erc681/ERC681Detector.kt
2400146736
package org.dvbviewer.controller.data.timer.retrofit import com.google.gson.reflect.TypeToken import okhttp3.RequestBody import okhttp3.ResponseBody import org.dvbviewer.controller.data.entities.Timer import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type /** * A [converter][Converter.Factory] for the ffmpegprefs.ini files. * * * This converter only applies for class FFMpegPresetList. * */ class TimerConverterFactory private constructor() : Converter.Factory() { private val timerList: Type init { val typeToken = TypeToken.getParameterized(List::class.java, Timer::class.java) timerList = typeToken.type } override fun responseBodyConverter(type: Type, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, List<Timer>>? { return if (type == timerList) { TimerPresetResponseBodyConverter() } else null } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>?, methodAnnotations: Array<Annotation>?, retrofit: Retrofit?): Converter<List<Timer>, RequestBody>? { return if (type == timerList) { TimerRequestBodyConverter() } else null } companion object { /** Create an instance conversion. */ fun create(): TimerConverterFactory { return TimerConverterFactory() } } }
dvbViewerController/src/main/java/org/dvbviewer/controller/data/timer/retrofit/TimerConverterFactory.kt
2734493438
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package test.server import io.ktor.http.* import io.ktor.http.content.* import io.ktor.util.* import io.ktor.utils.io.charsets.* import io.ktor.utils.io.core.* fun makeArray(size: Int): ByteArray = ByteArray(size) { it.toByte() } fun makeString(size: Int): String = CharArray(size) { it.toChar() }.concatToString().encodeBase64().take(size) fun List<PartData>.makeString(): String = buildString { val list = this@makeString list.forEach { append("${it.name!!}\n") val content = when (it) { is PartData.FileItem -> filenameContentTypeAndContentString(it.provider, it.headers) is PartData.FormItem -> it.value is PartData.BinaryItem -> filenameContentTypeAndContentString(it.provider, it.headers) is PartData.BinaryChannelItem -> error("Not implemented") } append(content) } } private fun filenameContentTypeAndContentString(provider: () -> Input, headers: Headers): String { val dispositionHeader: String = headers.getAll(HttpHeaders.ContentDisposition)!!.joinToString(";") val disposition: ContentDisposition = ContentDisposition.parse(dispositionHeader) val filename: String = disposition.parameter("filename") ?: "" val contentType = headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } ?: "" val content: String = provider().readText(Charsets.ISO_8859_1) return "$filename$contentType$content" }
buildSrc/src/main/kotlin/test/server/ServerUtils.kt
3669277032
package de.tarent.axon.ports.rest data class MoveRequest(val row: Int, val column: Int) { // Just for JPA @Suppress("unused") private constructor(): this(0, 0) }
src/main/kotlin/de/tarent/axon/ports/rest/MoveRequest.kt
220343621
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.permissions import android.content.Intent import android.os.Build import androidx.activity.ComponentActivity import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.dp import androidx.test.filters.FlakyTest import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiDevice import com.google.accompanist.permissions.test.PermissionsTestActivity import org.junit.Rule import org.junit.Test @OptIn(ExperimentalPermissionsApi::class) @FlakyTest(detail = "https://github.com/google/accompanist/issues/490") @SdkSuppress(minSdkVersion = 23) class MultipleAndSinglePermissionsTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private val instrumentation by lazy { InstrumentationRegistry.getInstrumentation() } private val uiDevice by lazy { UiDevice.getInstance(instrumentation) } @Test fun singlePermission_granted() { composeTestRule.setContent { ComposableUnderTest(listOf(android.Manifest.permission.CAMERA)) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Test fun singlePermission_deniedAndGrantedInSecondActivity() { composeTestRule.setContent { ComposableUnderTest(listOf(android.Manifest.permission.CAMERA)) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() denyPermissionInDialog() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() uiDevice.pressBack() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Test fun singlePermission_deniedAndGrantedInFirstActivity() { composeTestRule.setContent { ComposableUnderTest(listOf(android.Manifest.permission.CAMERA)) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() denyPermissionInDialog() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() uiDevice.pressBack() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Test fun singlePermission_deniedAndGrantedInFirstActivity_singlePermission() { composeTestRule.setContent { ComposableUnderTest( listOf(android.Manifest.permission.CAMERA), requestSinglePermission = true ) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() denyPermissionInDialog() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() uiDevice.pressBack() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Test fun multiplePermissions_granted() { composeTestRule.setContent { ComposableUnderTest( listOf( android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA ) ) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() // Grant first permission grantPermissionInDialog() // Grant second permission composeTestRule.onNodeWithText("Granted").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Test fun multiplePermissions_denied() { composeTestRule.setContent { ComposableUnderTest( listOf( android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA ) ) } composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("No permission").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() denyPermissionInDialog() // Deny first permission denyPermissionInDialog() // Deny second permission composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Navigate").performClick() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("PermissionsTestActivity").assertIsDisplayed() composeTestRule.onNodeWithText("ShowRationale").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() // Grant the permission composeTestRule.onNodeWithText("Granted").assertIsDisplayed() uiDevice.pressBack() instrumentation.waitForIdleSync() composeTestRule.onNodeWithText("MultipleAndSinglePermissionsTest").assertIsDisplayed() composeTestRule.onNodeWithText("Request").performClick() grantPermissionInDialog() // only one permission to grant now if (Build.VERSION.SDK_INT == 23) { // API 23 shows all permissions again grantPermissionInDialog() } composeTestRule.onNodeWithText("Granted").assertIsDisplayed() } @Composable private fun ComposableUnderTest( permissions: List<String>, requestSinglePermission: Boolean = false ) { val state = rememberMultiplePermissionsState(permissions) Column { Text("MultipleAndSinglePermissionsTest") Spacer(Modifier.height(16.dp)) if (state.allPermissionsGranted) { Text("Granted") } else { Column { val textToShow = if (state.shouldShowRationale) { "ShowRationale" } else { "No permission" } Text(textToShow) Button( onClick = { if (requestSinglePermission && state.revokedPermissions.size == 1) { state.revokedPermissions[0].launchPermissionRequest() } else { state.launchMultiplePermissionRequest() } } ) { Text("Request") } } } Spacer(Modifier.height(16.dp)) Button( onClick = { composeTestRule.activity.startActivity( Intent(composeTestRule.activity, PermissionsTestActivity::class.java) ) } ) { Text("Navigate") } } } }
permissions/src/androidTest/java/com/google/accompanist/permissions/MultipleAndSinglePermissionsTest.kt
4047578592
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("KDocMissingDocumentation") package io.ktor.content public typealias TextContent = io.ktor.http.content.TextContent public typealias ByteArrayContent = io.ktor.http.content.ByteArrayContent
ktor-http/common/src/io/ktor/content/Compatibility.kt
3968563922
package io.armcha.ribble.domain.fetcher.result_listener /** * Created by Chatikyan on 23.09.2017. */ enum class RequestType { AUTH, POPULAR_SHOTS, RECENT_SHOTS, FOLLOWINGS_SHOTS, LIKED_SHOTS, COMMENTS, LIKE, TYPE_NONE }
app/src/main/kotlin/io/armcha/ribble/domain/fetcher/result_listener/RequestType.kt
1457773645
package io.armcha.ribble.data.response import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Created by Chatikyan on 28.08.2017. */ class ImageResponse{ @SerializedName("hidpi") @Expose val big: String? = null @SerializedName("normal") @Expose val normal: String? = null @SerializedName("teaser") @Expose val small: String? = null }
app/src/main/kotlin/io/armcha/ribble/data/response/ImageResponse.kt
836566678
package com.example.demo import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.web.reactive.function.client.WebClient import reactor.kotlin.test.test class ApplicationTests { lateinit var client: WebClient lateinit var app: Application @BeforeEach fun setup() { app = Application() app.start() Thread.sleep(5000) client = WebClient.create("http://localhost:8080") } @AfterEach fun tearDown() { app.stop() } @Test fun getPostsShouldBeOK() { client .get() .uri("/api/posts") .accept(MediaType.APPLICATION_JSON) .exchangeToFlux { assertThat(it.statusCode()).isEqualTo(HttpStatus.OK) it.bodyToFlux(Post::class.java) } .test() .expectNextCount(2) .verifyComplete() } }
kotlin-dsl/src/test/kotlin/com/example/demo/ApplicationTests.kt
3873512200
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.reference import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.AT import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.METHOD_INJECTORS import com.demonwav.mcdev.util.insideAnnotationAttribute import com.intellij.patterns.PsiJavaPatterns import com.intellij.patterns.StandardPatterns import com.intellij.psi.PsiReferenceContributor import com.intellij.psi.PsiReferenceRegistrar class MixinReferenceContributor : PsiReferenceContributor() { override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { // Method references registrar.registerReferenceProvider(PsiJavaPatterns.psiLiteral(StandardPatterns.string()).insideAnnotationAttribute( StandardPatterns.string().oneOf(METHOD_INJECTORS), "method"), MethodReference) // Injection point types registrar.registerReferenceProvider(PsiJavaPatterns.psiLiteral(StandardPatterns.string()) .insideAnnotationAttribute(AT), InjectionPointType) // Target references registrar.registerReferenceProvider(PsiJavaPatterns.psiLiteral(StandardPatterns.string()) .insideAnnotationAttribute(AT, "target"), TargetReference) } }
src/main/kotlin/com/demonwav/mcdev/platform/mixin/reference/MixinReferenceContributor.kt
1550267636
package com.example.kotlin.robsmall.kotlinexampleapp import android.app.Application import butterknife.ButterKnife class ExampleApplication : Application() { override fun onCreate() { super.onCreate() ButterKnife.setDebug(BuildConfig.DEBUG) } }
app/src/main/java/com/example/kotlin/robsmall/kotlinexampleapp/ExampleApplication.kt
3685984680
/* * 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.fhir.datacapture.views import android.view.View import com.google.android.fhir.datacapture.R import com.google.android.fhir.datacapture.validation.ValidationResult internal object QuestionnaireItemDisplayViewHolderFactory : QuestionnaireItemViewHolderFactory(R.layout.questionnaire_item_display_view) { override fun getQuestionnaireItemViewHolderDelegate() = object : QuestionnaireItemViewHolderDelegate { private lateinit var header: QuestionnaireItemHeaderView override lateinit var questionnaireItemViewItem: QuestionnaireItemViewItem override fun init(itemView: View) { header = itemView.findViewById(R.id.header) } override fun bind(questionnaireItemViewItem: QuestionnaireItemViewItem) { header.bind(questionnaireItemViewItem.questionnaireItem) } override fun displayValidationResult(validationResult: ValidationResult) { // Display type questions have no user input to be validated } override fun setReadOnly(isReadOnly: Boolean) { // Display type questions have no user input } } }
datacapture/src/main/java/com/google/android/fhir/datacapture/views/QuestionnaireItemDisplayViewHolderFactory.kt
4245703602
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.test.common import com.intellij.psi.PsiNamedElement import org.jetbrains.uast.UFile import org.jetbrains.uast.UResolvable import org.jetbrains.uast.test.env.findElementByText import org.junit.Assert.assertEquals interface ResolveTestBase { fun check(testName: String, file: UFile) { val refComment = file.allCommentsInFile.find { it.text.startsWith("// REF:") } ?: throw IllegalArgumentException( "No // REF tag in file") val resultComment = file.allCommentsInFile.find { it.text.startsWith("// RESULT:") } ?: throw IllegalArgumentException( "No // RESULT tag in file") val refText = refComment.text.substringAfter("REF:") val parent = refComment.uastParent val matchingElement = parent.findElementByText<UResolvable>(refText) val resolveResult = matchingElement.resolve() ?: throw IllegalArgumentException("Unresolved reference") val resultText = resolveResult.javaClass.simpleName + (if (resolveResult is PsiNamedElement) ":${resolveResult.name}" else "") assertEquals(resultComment.text.substringAfter("RESULT:"), resultText) } }
uast/uast-tests/src/org/jetbrains/uast/test/common/ResolveTestBase.kt
1739064454