content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package app.cash.sqldelight.intellij.gotodeclaration
import app.cash.sqldelight.intellij.SqlDelightGotoDeclarationHandler
import app.cash.sqldelight.intellij.SqlDelightProjectTestCase
import com.alecstrong.sql.psi.core.psi.SqlIdentifier
import com.google.common.truth.Truth.assertThat
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class GoToDeclarationHandlerTest : SqlDelightProjectTestCase() {
private val goToDeclarationHandler = SqlDelightGotoDeclarationHandler()
fun testMethodGoesToIdentifier() {
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/java/com/example/SampleClass.java")!!,
)
val sourceElement = searchForElement<PsiElement>("someQuery").single()
val elements = goToDeclarationHandler.getGotoDeclarationTargets(sourceElement, 0, editor)
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/sqldelight/com/example/Main.sq")!!,
)
val offset = file.text.indexOf("someQuery")
assertThat(elements).asList().containsExactly(
file.findElementAt(offset)!!.getStrictParentOfType<SqlIdentifier>(),
)
}
fun testMethodGoesToIdentifierFromKotlin() {
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/kotlin/com/example/KotlinClass.kt")!!,
)
val sourceElement = searchForElement<PsiElement>("someQuery").single()
val elements = goToDeclarationHandler.getGotoDeclarationTargets(sourceElement, 0, editor)
myFixture.openFileInEditor(
tempRoot.findFileByRelativePath("src/main/sqldelight/com/example/Main.sq")!!,
)
val offset = file.text.indexOf("someQuery")
assertThat(elements).asList().containsExactly(
file.findElementAt(offset)!!.getStrictParentOfType<SqlIdentifier>(),
)
}
}
| sqldelight-idea-plugin/src/test/kotlin/app/cash/sqldelight/intellij/gotodeclaration/GoToDeclarationHandlerTest.kt | 1364736296 |
package edu.cs4730.drawdemo1_kt
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import com.google.android.material.navigation.NavigationView
/**
* while there is alot of code here, the example is actually all in the fragments.
* this is just to get the drawer layout working.
*/
class MainActivity : AppCompatActivity() {
private lateinit var mDrawerToggle: ActionBarDrawerToggle
private lateinit var mDrawerlayout: DrawerLayout
private lateinit var mNavigationView: NavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
// enable ActionBar app icon to behave as action to toggle nav drawer
// enable ActionBar app icon to behave as action to toggle nav drawer
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setHomeButtonEnabled(true)
//standard navigation drawer setup.
//standard navigation drawer setup.
mDrawerlayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout
mDrawerToggle = object : ActionBarDrawerToggle(
this, // host activity
mDrawerlayout, //drawerlayout object
toolbar, //toolbar
R.string.drawer_open, //open drawer description required!
R.string.drawer_close
) {
//closed drawer description
//called once the drawer has closed.
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
supportActionBar!!.title = "Categories"
invalidateOptionsMenu() // creates call to onPrepareOptionsMenu()
}
//called when the drawer is now open.
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
supportActionBar!!.setTitle(R.string.app_name)
invalidateOptionsMenu() // creates call to onPrepareOptionsMenu()
}
}
//To disable the icon for the drawer, change this to false
//mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerlayout.addDrawerListener(mDrawerToggle)
//this ia the support Navigation view.
mNavigationView = findViewById<View>(R.id.navview) as NavigationView
//setup a listener, which acts very similar to how menus are handled.
mNavigationView.setNavigationItemSelectedListener(NavigationView.OnNavigationItemSelectedListener { menuItem -> //we could just as easily call onOptionsItemSelected(menuItem) and how it deal with it.
val id = menuItem.itemId
if (id == R.id.drawing) {
//load fragment
// if (!menuItem.isChecked()) { //only need to do this if fragment is already loaded.
// menuItem.isChecked = true //make sure to check/highlight the item.
supportFragmentManager.beginTransaction().replace(R.id.container, MainFragment())
.commit()
// }
mDrawerlayout.closeDrawers() //close the drawer, since the user has selected it.
return@OnNavigationItemSelectedListener true
} else if (id == R.id.drawing1) {
//load fragment
// if (!menuItem.isChecked()) { //only need to do this if fragment is already loaded.
// menuItem.isChecked = true //make sure the item is checked/highlighted
supportFragmentManager.beginTransaction().replace(R.id.container, Draw1Fragment())
.commit()
// }
//now close the nav drawer.
mDrawerlayout.closeDrawers()
return@OnNavigationItemSelectedListener true
} else if (id == R.id.andraw) {
//load fragment
// menuItem.isChecked = true //make sure the item is checked/highlighted
supportFragmentManager.beginTransaction().replace(R.id.container, AnDrawFragment())
.commit()
//now close the nav drawer.
mDrawerlayout.closeDrawers()
return@OnNavigationItemSelectedListener true
} else if (id == R.id.asdraw) {
//load fragment
// menuItem.isChecked = true //make sure the item is checked/highlighted
supportFragmentManager.beginTransaction()
.replace(R.id.container, AsycDrawFragment()).commit()
//now close the nav drawer.
mDrawerlayout.closeDrawers()
return@OnNavigationItemSelectedListener true
}
false
})
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.container, MainFragment()).commit()
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig)
}
} | DrawDemo1_kt/app/src/main/java/edu/cs4730/drawdemo1_kt/MainActivity.kt | 267280966 |
/*
* Copyright (C) 2017 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.xml
import org.w3c.dom.Node
import org.w3c.dom.NodeList
private class NodeListIterator(val nodes: NodeList): Iterator<Node> {
private var current: Int = 0
override fun hasNext(): Boolean =
current != nodes.length
override fun next(): Node =
nodes.item(current++)
}
fun NodeList.asSequence(): Sequence<Node> =
NodeListIterator(this).asSequence()
| src/main/java/uk/co/reecedunn/intellij/plugin/core/xml/NodeList.kt | 3462163320 |
/*
* Copyright (c) 2021 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.servicelayer
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.servicelayer.SchedulerService.NextCard
import com.ichi2.async.CollectionTask
import com.ichi2.utils.Computation
import timber.log.Timber
class UndoService {
class Undo : ActionAndNextCard() {
override fun execute(): ComputeResult {
try {
val card = col.db.executeInTransactionReturn {
return@executeInTransactionReturn CollectionTask.nonTaskUndo(col)
}
return Computation.ok(NextCard.withNoResult(card))
} catch (e: RuntimeException) {
Timber.e(e, "doInBackgroundUndo - RuntimeException on undoing")
AnkiDroidApp.sendExceptionReport(e, "doInBackgroundUndo")
return Computation.err()
}
}
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/UndoService.kt | 1221365486 |
/*
* Copyright 2017 Ali Moghnieh
*
* 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.blurengine.blur.modules.maploading
interface MapChoiceStrategy {
fun getAvailableMaps(): List<BlurMap>
fun getMap(): BlurMap
}
| src/main/java/com/blurengine/blur/modules/maploading/MapChoiceStrategy.kt | 1175243859 |
package com.tamsiree.rxkit
import android.app.Activity
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import java.util.*
/**
*
* @author Tamsiree
* @date 2017/8/18
*/
object RxPermissionsTool {
@JvmStatic
fun with(activity: Activity?): Builder {
return Builder(activity)
}
class Builder(private val mActivity: Activity?) {
private val permissionList: MutableList<String>
/**
* Determine whether *you* have been granted a particular permission.
*
* @param permission The name of the permission being checked.
* @return [PackageManager.PERMISSION_GRANTED] if you have the
* permission, or [PackageManager.PERMISSION_DENIED] if not.
* @see PackageManager.checkPermission
*/
fun addPermission(permission: String): Builder {
if (!permissionList.contains(permission)) {
permissionList.add(permission)
}
return this
}
fun initPermission(): List<String> {
val list: MutableList<String> = ArrayList()
for (permission in permissionList) {
if (ActivityCompat.checkSelfPermission(mActivity!!.baseContext, permission) != PackageManager.PERMISSION_GRANTED) {
list.add(permission)
}
}
if (list.size > 0) {
ActivityCompat.requestPermissions(mActivity!!, list.toTypedArray(), 1)
}
return list
}
init {
permissionList = ArrayList()
}
}
} | RxKit/src/main/java/com/tamsiree/rxkit/RxPermissionsTool.kt | 1932601930 |
package com.uchuhimo.konf.source.toml
import com.uchuhimo.konf.source.Source
import com.uchuhimo.konf.source.base.MapSource
class TomlMapSource(
map: Map<String, Any>,
context: Map<String, String> = mapOf()
) : MapSource(map, "TOML", context) {
override fun Any.castToSource(context: Map<String, String>): Source = asTomlSource(context)
}
| konf/src/main/kotlin/com/uchuhimo/konf/source/toml/TomlMapSource.kt | 1346048067 |
package me.xbh.lib.core.cxx
/**
* <p>
* 描述:MD5本地接口
* </p>
* 创建日期:2017年11月02日.
* @author [email protected]
* @version 1.0
*/
internal class Md5 constructor(){
external fun digest(plainText: String): String
}
| CryptLibrary/src/main/kotlin/me/xbh/lib/core/cxx/Md5.kt | 2997645155 |
package com.tamsiree.rxui.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.tamsiree.rxui.model.ModelFVP
class AdapterFVP(fm: FragmentManager?, var modelFVP: List<ModelFVP>) : FragmentPagerAdapter(fm!!) {
override fun getCount(): Int {
return modelFVP.size
}
override fun getPageTitle(position: Int): CharSequence? {
return modelFVP[position].name
}
override fun getItem(position: Int): Fragment {
return modelFVP[position].fragment
}
} | RxUI/src/main/java/com/tamsiree/rxui/adapter/AdapterFVP.kt | 2522103599 |
/**
* 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 net.cleverdesk.cleverdesk.listener
/**
* A pair of the [event_type] and the for the eventtype registered [listener]. Is used to handle listener registrations without using reflection.
*/
data class ListenerRegistration<T : Event>(val listener: Listener<T>, val event_type: Class<T>); | src/main/java/net/cleverdesk/cleverdesk/listener/ListenerRegistration.kt | 390039315 |
package org.mcxa.vortaro
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// tag for log methods
val TAG = "Main_Activity"
var dbHelper: DatabaseHelper? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// set up the action bar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
dbHelper = DatabaseHelper(this)
word_view.apply{
adapter = WordAdapter()
layoutManager = LinearLayoutManager(this@MainActivity)
}
search_text.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val w = word_view.adapter as WordAdapter
if (!s.isNullOrEmpty()) {
dbHelper?.search(s.toString().toLowerCase(), w)
} else {
w.words.beginBatchedUpdates()
// remove items at end, to avoid unnecessary array shifting
while (w.words.size() > 0) {
w.words.removeItemAt(w.words.size() - 1)
}
w.words.endBatchedUpdates()
}
}
override fun afterTextChanged(s: Editable?) {}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.option_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.about -> {
val i = Intent(this, AboutActivity::class.java)
startActivity(i) // brings up the second activity
return true
}
}
return false
}
override fun onDestroy() {
dbHelper?.close()
super.onDestroy()
}
} | app/src/main/java/org/mcxa/vortaro/MainActivity.kt | 1413598942 |
package org.softeg.slartus.forpdaplus.fragments.qms
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import org.softeg.slartus.forpdaplus.MainActivity
import org.softeg.slartus.forpdaplus.R
import org.softeg.slartus.forpdaplus.fragments.BaseBrickContainerFragment
import org.softeg.slartus.forpdaplus.tabs.TabsManager
import org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment as FeatureFragment
class QmsNewThreadFragment : BaseBrickContainerFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTitleByNick(null)
childFragmentManager.setFragmentResultListener(
org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_NICK,
this
) { _, bundle ->
val nick = bundle.getString(org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_NICK)
setTitleByNick(nick)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setArrow()
supportActionBar.setDisplayHomeAsUpEnabled(true)
supportActionBar.setHomeButtonEnabled(true)
}
private fun setTitleByNick(contactNick: String?) {
val title = if (contactNick == null) {
getString(R.string.qms_title_new_thread, "QMS")
} else {
getString(R.string.qms_title_new_thread, contactNick)
}
setTitle(title)
TabsManager.instance.getTabByTag(tag)?.title = title
mainActivity.notifyTabAdapter()
}
override fun closeTab(): Boolean {
return false
}
override fun getFragmentInstance(): Fragment {
val args = arguments
return FeatureFragment().apply {
this.arguments = args
}
}
override fun onResume() {
super.onResume()
setArrow()
// if (mPopupPanelView != null)
// mPopupPanelView.resume();
}
companion object {
// @Override
// public void hidePopupWindows() {
// super.hidePopupWindows();
// mPopupPanelView.hidePopupWindow();
// }
fun showUserNewThread(userId: String?, userNick: String?) {
val args = bundleOf(org.softeg.slartus.forpdaplus.qms.impl.screens.newthread.QmsNewThreadFragment.ARG_CONTACT_ID to userId)
val fragment = QmsNewThreadFragment().apply {
arguments = args
}
MainActivity.addTab(userNick, fragment)
}
// private val mPopupPanelView: PopupPanelView? = null
// override fun onPause() {
// super.onPause()
// mPopupPanelView?.pause()
// }
//
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// if (mPopupPanelView == null)
// mPopupPanelView = new PopupPanelView(PopupPanelView.VIEW_FLAG_EMOTICS | PopupPanelView.VIEW_FLAG_BBCODES);
// mPopupPanelView.createView(LayoutInflater.from(getContext()), (ImageButton) findViewById(R.id.advanced_button), message);
// mPopupPanelView.activityCreated(getMainActivity(), view);
// return view;
// }
//
// @Override
// public void onDestroy() {
// if (mPopupPanelView != null) {
// mPopupPanelView.destroy();
// mPopupPanelView = null;
// }
// super.onDestroy();
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// }
//
// return true;
// }
//
}
} | app/src/main/java/org/softeg/slartus/forpdaplus/fragments/qms/QmsNewThreadFragment.kt | 2033863025 |
/*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.reflect
import io.github.classgraph.ClassGraph
import org.nd4j.common.config.ND4JSystemProperties.INIT_IMPORT_REFLECTION_CACHE
import org.nd4j.samediff.frameworkimport.hooks.NodePreProcessorHook
import org.nd4j.samediff.frameworkimport.hooks.PostImportHook
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.NodePreProcessor
import org.nd4j.samediff.frameworkimport.hooks.annotations.PostHookRule
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.shade.guava.collect.Table
import org.nd4j.shade.guava.collect.TreeBasedTable
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
object ImportReflectionCache {
//all relevant node names relevant for
val preProcessRuleImplementationsByNode: Table<String,String,MutableList<PreImportHook>> = TreeBasedTable.create()
val postProcessRuleImplementationsByNode: Table<String,String,MutableList<PostImportHook>> = TreeBasedTable.create()
//all relevant op names hook should be useful for
val preProcessRuleImplementationsByOp: Table<String,String,MutableList<PreImportHook>> = TreeBasedTable.create()
val postProcessRuleImplementationsByOp: Table<String,String,MutableList<PostImportHook>> = TreeBasedTable.create()
val nodePreProcessorRuleImplementationByOp: Table<String,String,MutableList<NodePreProcessorHook<GeneratedMessageV3,
GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,ProtocolMessageEnum>>> = TreeBasedTable.create()
init {
if(java.lang.Boolean.parseBoolean(System.getProperty(INIT_IMPORT_REFLECTION_CACHE,"true"))) {
load()
}
}
@JvmStatic
fun load() {
val scannedClasses = ClassGraphHolder.scannedClasses
scannedClasses.getClassesImplementing(PreImportHook::class.java.name).filter { input -> input.hasAnnotation(PreHookRule::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as PreImportHook
val rule = it.annotationInfo.first { input -> input.name == PreHookRule::class.java.name }
val nodeNames = rule.parameterValues["nodeNames"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeNames.forEach { nodeName ->
if(!preProcessRuleImplementationsByNode.contains(frameworkName,nodeName)) {
preProcessRuleImplementationsByNode.put(frameworkName,nodeName,ArrayList())
}
preProcessRuleImplementationsByNode.get(frameworkName,nodeName)!!.add(instance)
}
val opNames = rule.parameterValues["opNames"].value as Array<String>
opNames.forEach { opName ->
if(!preProcessRuleImplementationsByOp.contains(frameworkName,opName)) {
preProcessRuleImplementationsByOp.put(frameworkName,opName,ArrayList())
}
preProcessRuleImplementationsByOp.get(frameworkName,opName)!!.add(instance)
}
}
scannedClasses.getClassesImplementing(PostImportHook::class.java.name).filter { input -> input.hasAnnotation(PostHookRule::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as PostImportHook
val rule = it.annotationInfo.first { input -> input.name == PostHookRule::class.java.name }
val nodeNames = rule.parameterValues["nodeNames"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeNames.forEach { nodeName ->
if(!postProcessRuleImplementationsByNode.contains(frameworkName,nodeName)) {
postProcessRuleImplementationsByNode.put(frameworkName,nodeName,ArrayList())
}
postProcessRuleImplementationsByNode.get(frameworkName,nodeName)!!.add(instance)
}
val opNames = rule.parameterValues["opNames"].value as Array<String>
opNames.forEach { opName ->
if(!postProcessRuleImplementationsByOp.contains(frameworkName,opName)) {
postProcessRuleImplementationsByOp.put(frameworkName,opName,ArrayList())
}
postProcessRuleImplementationsByOp.get(frameworkName,opName)!!.add(instance)
}
}
scannedClasses.getClassesImplementing(NodePreProcessorHook::class.java.name).filter { input -> input.hasAnnotation(NodePreProcessor::class.java.name) }.forEach {
val instance = Class.forName(it.name).getDeclaredConstructor().newInstance() as NodePreProcessorHook<GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,GeneratedMessageV3,ProtocolMessageEnum>
val rule = it.annotationInfo.first { input -> input.name == NodePreProcessor::class.java.name }
val nodeTypes = rule.parameterValues["nodeTypes"].value as Array<String>
val frameworkName = rule.parameterValues["frameworkName"].value as String
nodeTypes.forEach { nodeType ->
if(!nodePreProcessorRuleImplementationByOp.contains(frameworkName,nodeType)) {
nodePreProcessorRuleImplementationByOp.put(frameworkName,nodeType,ArrayList())
}
nodePreProcessorRuleImplementationByOp.get(frameworkName,nodeType)!!.add(instance)
}
}
}
}
| nd4j/samediff-import/samediff-import-api/src/main/kotlin/org/nd4j/samediff/frameworkimport/reflect/ImportReflectionCache.kt | 852671319 |
/*
* 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.animation.samples
import androidx.annotation.Sampled
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Sampled
@Composable
fun AnimateContent() {
val shortText = "Hi"
val longText = "Very long text\nthat spans across\nmultiple lines"
var short by remember { mutableStateOf(true) }
Box(
modifier = Modifier
.background(
Color.Blue,
RoundedCornerShape(15.dp)
)
.clickable { short = !short }
.padding(20.dp)
.wrapContentSize()
.animateContentSize()
) {
Text(
if (short) {
shortText
} else {
longText
},
style = LocalTextStyle.current.copy(color = Color.White)
)
}
}
| compose/animation/animation/samples/src/main/java/androidx/compose/animation/samples/AnimationModifierSample.kt | 561952178 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.api.weight
interface Weighted {
val weight: Double
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/weight/Weighted.kt | 3366109981 |
package abi42_0_0.expo.modules.notifications.service
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.os.ResultReceiver
import android.util.Log
import androidx.core.app.RemoteInput
import expo.modules.notifications.notifications.model.Notification
import expo.modules.notifications.notifications.model.NotificationAction
import expo.modules.notifications.notifications.model.NotificationBehavior
import expo.modules.notifications.notifications.model.NotificationCategory
import expo.modules.notifications.notifications.model.NotificationRequest
import expo.modules.notifications.notifications.model.NotificationResponse
import expo.modules.notifications.notifications.model.TextInputNotificationAction
import expo.modules.notifications.notifications.model.TextInputNotificationResponse
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoCategoriesDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoHandlingDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoPresentationDelegate
import abi42_0_0.expo.modules.notifications.service.delegates.ExpoSchedulingDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.CategoriesDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.HandlingDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.PresentationDelegate
import abi42_0_0.expo.modules.notifications.service.interfaces.SchedulingDelegate
import kotlin.concurrent.thread
/**
* Subclass of FirebaseMessagingService, central dispatcher for all the notifications-related actions.
*/
open class NotificationsService : BroadcastReceiver() {
companion object {
const val NOTIFICATION_EVENT_ACTION = "expo.modules.notifications.NOTIFICATION_EVENT"
val SETUP_ACTIONS = listOf(
Intent.ACTION_BOOT_COMPLETED,
Intent.ACTION_REBOOT,
Intent.ACTION_MY_PACKAGE_REPLACED,
"android.intent.action.QUICKBOOT_POWERON",
"com.htc.intent.action.QUICKBOOT_POWERON"
)
const val USER_TEXT_RESPONSE_KEY = "userTextResponse"
// Event types
private const val GET_ALL_DISPLAYED_TYPE = "getAllDisplayed"
private const val PRESENT_TYPE = "present"
private const val DISMISS_SELECTED_TYPE = "dismissSelected"
private const val DISMISS_ALL_TYPE = "dismissAll"
private const val RECEIVE_TYPE = "receive"
private const val RECEIVE_RESPONSE_TYPE = "receiveResponse"
private const val DROPPED_TYPE = "dropped"
private const val GET_CATEGORIES_TYPE = "getCategories"
private const val SET_CATEGORY_TYPE = "setCategory"
private const val DELETE_CATEGORY_TYPE = "deleteCategory"
private const val SCHEDULE_TYPE = "schedule"
private const val TRIGGER_TYPE = "trigger"
private const val GET_ALL_SCHEDULED_TYPE = "getAllScheduled"
private const val GET_SCHEDULED_TYPE = "getScheduled"
private const val REMOVE_SELECTED_TYPE = "removeSelected"
private const val REMOVE_ALL_TYPE = "removeAll"
// Messages parts
const val SUCCESS_CODE = 0
const val ERROR_CODE = 1
const val EVENT_TYPE_KEY = "type"
const val EXCEPTION_KEY = "exception"
const val RECEIVER_KEY = "receiver"
// Specific messages parts
const val NOTIFICATION_KEY = "notification"
const val NOTIFICATION_RESPONSE_KEY = "notificationResponse"
const val TEXT_INPUT_NOTIFICATION_RESPONSE_KEY = "textInputNotificationResponse"
const val SUCCEEDED_KEY = "succeeded"
const val IDENTIFIERS_KEY = "identifiers"
const val IDENTIFIER_KEY = "identifier"
const val NOTIFICATION_BEHAVIOR_KEY = "notificationBehavior"
const val NOTIFICATIONS_KEY = "notifications"
const val NOTIFICATION_CATEGORY_KEY = "notificationCategory"
const val NOTIFICATION_CATEGORIES_KEY = "notificationCategories"
const val NOTIFICATION_REQUEST_KEY = "notificationRequest"
const val NOTIFICATION_REQUESTS_KEY = "notificationRequests"
const val NOTIFICATION_ACTION_KEY = "notificationAction"
/**
* A helper function for dispatching a "fetch all displayed notifications" command to the service.
*
* @param context Context where to start the service.
* @param receiver A receiver to which send the notifications
*/
fun getAllPresented(context: Context, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, getUriBuilder().build()).also {
it.putExtra(EVENT_TYPE_KEY, GET_ALL_DISPLAYED_TYPE)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "present notification" command to the service.
*
* @param context Context where to start the service.
* @param notification Notification to present
* @param behavior Allowed notification behavior
* @param receiver A receiver to which send the result of presenting the notification
*/
fun present(context: Context, notification: Notification, behavior: NotificationBehavior? = null, receiver: ResultReceiver? = null) {
val data = getUriBuilderForIdentifier(notification.notificationRequest.identifier).appendPath("present").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, PRESENT_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(NOTIFICATION_BEHAVIOR_KEY, behavior)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "notification received" command to the service.
*
* @param context Context where to start the service.
* @param notification Notification received
* @param receiver Result receiver
*/
fun receive(context: Context, notification: Notification, receiver: ResultReceiver? = null) {
val data = getUriBuilderForIdentifier(notification.notificationRequest.identifier).appendPath("receive").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, RECEIVE_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "dismiss notification" command to the service.
*
* @param context Context where to start the service.
* @param identifier Notification identifier
* @param receiver A receiver to which send the result of the action
*/
fun dismiss(context: Context, identifiers: Array<String>, receiver: ResultReceiver? = null) {
val data = getUriBuilder().appendPath("dismiss").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DISMISS_SELECTED_TYPE)
intent.putExtra(IDENTIFIERS_KEY, identifiers)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "dismiss notification" command to the service.
*
* @param context Context where to start the service.
* @param receiver A receiver to which send the result of the action
*/
fun dismissAll(context: Context, receiver: ResultReceiver? = null) {
val data = getUriBuilder().appendPath("dismiss").build()
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION, data).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DISMISS_ALL_TYPE)
intent.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "notifications dropped" command to the service.
*
* @param context Context where to start the service.
*/
fun handleDropped(context: Context) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, DROPPED_TYPE)
}
)
}
/**
* A helper function for dispatching a "get notification categories" command to the service.
*
* @param context Context where to start the service.
*/
fun getCategories(context: Context, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, GET_CATEGORIES_TYPE)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "set notification category" command to the service.
*
* @param context Context where to start the service.
* @param category Notification category to be set
*/
fun setCategory(context: Context, category: NotificationCategory, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.appendPath(category.identifier)
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, SET_CATEGORY_TYPE)
it.putExtra(NOTIFICATION_CATEGORY_KEY, category as Parcelable)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* A helper function for dispatching a "delete notification category" command to the service.
*
* @param context Context where to start the service.
* @param identifier Category Identifier
*/
fun deleteCategory(context: Context, identifier: String, receiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("categories")
.appendPath(identifier)
.build()
).also {
it.putExtra(EVENT_TYPE_KEY, DELETE_CATEGORY_TYPE)
it.putExtra(IDENTIFIER_KEY, identifier)
it.putExtra(RECEIVER_KEY, receiver)
}
)
}
/**
* Fetches all scheduled notifications asynchronously.
*
* @param context Context this is being called from
* @param resultReceiver Receiver to be called with the results
*/
fun getAllScheduledNotifications(context: Context, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, GET_ALL_SCHEDULED_TYPE)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Fetches scheduled notification asynchronously.
*
* @param context Context this is being called from
* @param identifier Identifier of the notification to be fetched
* @param resultReceiver Receiver to be called with the results
*/
fun getScheduledNotification(context: Context, identifier: String, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(identifier)
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, GET_SCHEDULED_TYPE)
intent.putExtra(IDENTIFIER_KEY, identifier)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Schedule notification asynchronously.
*
* @param context Context this is being called from
* @param notificationRequest Notification request to schedule
* @param resultReceiver Receiver to be called with the result
*/
fun schedule(context: Context, notificationRequest: NotificationRequest, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(notificationRequest.identifier)
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, SCHEDULE_TYPE)
intent.putExtra(NOTIFICATION_REQUEST_KEY, notificationRequest as Parcelable)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Cancel selected scheduled notification and remove it from the storage asynchronously.
*
* @param context Context this is being called from
* @param identifier Identifier of the notification to be removed
* @param resultReceiver Receiver to be called with the result
*/
fun removeScheduledNotification(context: Context, identifier: String, resultReceiver: ResultReceiver? = null) =
removeScheduledNotifications(context, listOf(identifier), resultReceiver)
/**
* Cancel selected scheduled notifications and remove them from the storage asynchronously.
*
* @param context Context this is being called from
* @param identifiers Identifiers of selected notifications to be removed
* @param resultReceiver Receiver to be called with the result
*/
fun removeScheduledNotifications(context: Context, identifiers: Collection<String>, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.build()
).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, REMOVE_SELECTED_TYPE)
intent.putExtra(IDENTIFIERS_KEY, identifiers.toTypedArray())
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Cancel all scheduled notifications and remove them from the storage asynchronously.
*
* @param context Context this is being called from
* @param resultReceiver Receiver to be called with the result
*/
fun removeAllScheduledNotifications(context: Context, resultReceiver: ResultReceiver? = null) {
doWork(
context,
Intent(NOTIFICATION_EVENT_ACTION).also { intent ->
intent.putExtra(EVENT_TYPE_KEY, REMOVE_ALL_TYPE)
intent.putExtra(RECEIVER_KEY, resultReceiver)
}
)
}
/**
* Sends the intent to the best service to handle the {@link #NOTIFICATION_EVENT_ACTION} intent
* or handles the intent immediately if the service is already up.
*
* @param context Context where to start the service
* @param intent Intent to dispatch
*/
fun doWork(context: Context, intent: Intent) {
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
context.sendBroadcast(intent)
return
}
Log.e("expo-notifications", "No service capable of handling notifications found (intent = ${intent.action}). Ensure that you have configured your AndroidManifest.xml properly.")
}
protected fun getUriBuilder(): Uri.Builder {
return Uri.parse("expo-notifications://notifications/").buildUpon()
}
protected fun getUriBuilderForIdentifier(identifier: String): Uri.Builder {
return getUriBuilder().appendPath(identifier)
}
fun findDesignatedBroadcastReceiver(context: Context, intent: Intent): ActivityInfo? {
val searchIntent = Intent(intent.action).setPackage(context.packageName)
return context.packageManager.queryBroadcastReceivers(searchIntent, 0).firstOrNull()?.activityInfo
}
/**
* Creates and returns a pending intent that will trigger [NotificationsService],
* which hands off the work to this class. The intent triggers notification of the given identifier.
*
* @param context Context this is being called from
* @param identifier Notification identifier
* @return [PendingIntent] triggering [NotificationsService], triggering notification of given ID.
*/
fun createNotificationTrigger(context: Context, identifier: String): PendingIntent {
val intent = Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath("scheduled")
.appendPath(identifier)
.appendPath("trigger")
.build()
).also { intent ->
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
}
intent.putExtra(EVENT_TYPE_KEY, TRIGGER_TYPE)
intent.putExtra(IDENTIFIER_KEY, identifier)
}
return PendingIntent.getBroadcast(
context,
intent.component?.className?.hashCode() ?: NotificationsService::class.java.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
/**
* Creates and returns a pending intent that will trigger [NotificationsService]'s "response received"
* event.
*
* @param context Context this is being called from
* @param notification Notification being responded to
* @param action Notification action being undertaken
* @return [PendingIntent] triggering [NotificationsService], triggering "response received" event
*/
fun createNotificationResponseIntent(context: Context, notification: Notification, action: NotificationAction): PendingIntent {
val intent = Intent(
NOTIFICATION_EVENT_ACTION,
getUriBuilder()
.appendPath(notification.notificationRequest.identifier)
.appendPath("actions")
.appendPath(action.identifier)
.build()
).also { intent ->
findDesignatedBroadcastReceiver(context, intent)?.let {
intent.component = ComponentName(it.packageName, it.name)
}
intent.putExtra(EVENT_TYPE_KEY, RECEIVE_RESPONSE_TYPE)
intent.putExtra(NOTIFICATION_KEY, notification)
intent.putExtra(NOTIFICATION_ACTION_KEY, action as Parcelable)
}
return PendingIntent.getBroadcast(
context,
intent.component?.className?.hashCode() ?: NotificationsService::class.java.hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
fun getNotificationResponseFromIntent(intent: Intent): NotificationResponse? {
intent.getByteArrayExtra(NOTIFICATION_RESPONSE_KEY)?.let { return unmarshalObject(NotificationResponse.CREATOR, it) }
intent.getByteArrayExtra(TEXT_INPUT_NOTIFICATION_RESPONSE_KEY)?.let { return unmarshalObject(TextInputNotificationResponse.CREATOR, it) }
return null
}
// Class loader used in BaseBundle when unmarshalling notification extras
// cannot handle abi42_0_0.expo.modules.notifications.….NotificationResponse
// so we go around it by marshalling and unmarshalling the object ourselves.
fun setNotificationResponseToIntent(intent: Intent, notificationResponse: NotificationResponse) {
try {
val keyToPutResponseUnder = if (notificationResponse is TextInputNotificationResponse) {
TEXT_INPUT_NOTIFICATION_RESPONSE_KEY
} else {
NOTIFICATION_RESPONSE_KEY
}
intent.putExtra(keyToPutResponseUnder, marshalObject(notificationResponse))
} catch (e: Exception) {
// If we couldn't marshal the request, let's not fail the whole build process.
Log.e("expo-notifications", "Could not marshal notification response: ${notificationResponse.actionIdentifier}.")
e.printStackTrace()
}
}
/**
* Marshals [Parcelable] into to a byte array.
*
* @param notificationResponse Notification response to marshall
* @return Given request marshalled to a byte array or null if the process failed.
*/
private fun marshalObject(objectToMarshal: Parcelable): ByteArray? {
val parcel: Parcel = Parcel.obtain()
objectToMarshal.writeToParcel(parcel, 0)
val bytes: ByteArray = parcel.marshall()
parcel.recycle()
return bytes
}
/**
* UNmarshals [Parcelable] object from a byte array given a [Parcelable.Creator].
* @return Object instance or null if the process failed.
*/
private fun <T> unmarshalObject(creator: Parcelable.Creator<T>, byteArray: ByteArray?): T? {
byteArray?.let {
try {
val parcel = Parcel.obtain()
parcel.unmarshall(it, 0, it.size)
parcel.setDataPosition(0)
val unmarshaledObject = creator.createFromParcel(parcel)
parcel.recycle()
return unmarshaledObject
} catch (e: Exception) {
Log.e("expo-notifications", "Could not unmarshall NotificationResponse from Intent.extra.", e)
}
}
return null
}
}
protected open fun getPresentationDelegate(context: Context): PresentationDelegate =
ExpoPresentationDelegate(context)
protected open fun getHandlingDelegate(context: Context): HandlingDelegate =
ExpoHandlingDelegate(context)
protected open fun getCategoriesDelegate(context: Context): CategoriesDelegate =
ExpoCategoriesDelegate(context)
protected open fun getSchedulingDelegate(context: Context): SchedulingDelegate =
ExpoSchedulingDelegate(context)
override fun onReceive(context: Context, intent: Intent?) {
val pendingIntent = goAsync()
thread {
try {
handleIntent(context, intent)
} finally {
pendingIntent.finish()
}
}
}
open fun handleIntent(context: Context, intent: Intent?) {
if (intent != null && SETUP_ACTIONS.contains(intent.action)) {
onSetupScheduledNotifications(context, intent)
} else if (intent?.action === NOTIFICATION_EVENT_ACTION) {
val receiver: ResultReceiver? = intent.extras?.get(RECEIVER_KEY) as? ResultReceiver
try {
var resultData: Bundle? = null
when (val eventType = intent.getStringExtra(EVENT_TYPE_KEY)) {
GET_ALL_DISPLAYED_TYPE ->
resultData = onGetAllPresentedNotifications(context, intent)
RECEIVE_TYPE -> onReceiveNotification(context, intent)
RECEIVE_RESPONSE_TYPE -> onReceiveNotificationResponse(context, intent)
DROPPED_TYPE -> onNotificationsDropped(context, intent)
PRESENT_TYPE -> onPresentNotification(context, intent)
DISMISS_SELECTED_TYPE -> onDismissNotifications(context, intent)
DISMISS_ALL_TYPE -> onDismissAllNotifications(context, intent)
GET_CATEGORIES_TYPE ->
resultData = onGetCategories(context, intent)
SET_CATEGORY_TYPE ->
resultData = onSetCategory(context, intent)
DELETE_CATEGORY_TYPE ->
resultData = onDeleteCategory(context, intent)
GET_ALL_SCHEDULED_TYPE ->
resultData = onGetAllScheduledNotifications(context, intent)
GET_SCHEDULED_TYPE ->
resultData = onGetScheduledNotification(context, intent)
SCHEDULE_TYPE -> onScheduleNotification(context, intent)
REMOVE_SELECTED_TYPE -> onRemoveScheduledNotifications(context, intent)
REMOVE_ALL_TYPE -> onRemoveAllScheduledNotifications(context, intent)
TRIGGER_TYPE -> onNotificationTriggered(context, intent)
else -> throw IllegalArgumentException("Received event of unrecognized type: $eventType. Ignoring.")
}
// If we ended up here, the callbacks must have completed successfully
receiver?.send(SUCCESS_CODE, resultData)
} catch (e: Exception) {
Log.e("expo-notifications", "Action ${intent.action} failed: ${e.message}")
e.printStackTrace()
receiver?.send(ERROR_CODE, Bundle().also { it.putSerializable(EXCEPTION_KEY, e) })
}
} else {
throw IllegalArgumentException("Received intent of unrecognized action: ${intent?.action}. Ignoring.")
}
}
//region Presenting notifications
open fun onPresentNotification(context: Context, intent: Intent) =
getPresentationDelegate(context).presentNotification(
intent.extras?.getParcelable(NOTIFICATION_KEY)!!,
intent.extras?.getParcelable(NOTIFICATION_BEHAVIOR_KEY)
)
open fun onGetAllPresentedNotifications(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATIONS_KEY,
ArrayList(
getPresentationDelegate(context).getAllPresentedNotifications()
)
)
}
open fun onDismissNotifications(context: Context, intent: Intent) =
getPresentationDelegate(context).dismissNotifications(
intent.extras?.getStringArray(IDENTIFIERS_KEY)!!.asList()
)
open fun onDismissAllNotifications(context: Context, intent: Intent) =
getPresentationDelegate(context).dismissAllNotifications()
//endregion
//region Handling notifications
open fun onReceiveNotification(context: Context, intent: Intent) =
getHandlingDelegate(context).handleNotification(
intent.getParcelableExtra(NOTIFICATION_KEY)!!
)
open fun onReceiveNotificationResponse(context: Context, intent: Intent) {
val notification = intent.getParcelableExtra<Notification>(NOTIFICATION_KEY)!!
val action = intent.getParcelableExtra<NotificationAction>(NOTIFICATION_ACTION_KEY)!!
val response = if (action is TextInputNotificationAction) {
TextInputNotificationResponse(action, notification, RemoteInput.getResultsFromIntent(intent).getString(USER_TEXT_RESPONSE_KEY))
} else {
NotificationResponse(action, notification)
}
getHandlingDelegate(context).handleNotificationResponse(response)
}
open fun onNotificationsDropped(context: Context, intent: Intent) =
getHandlingDelegate(context).handleNotificationsDropped()
//endregion
//region Category handling
open fun onGetCategories(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATION_CATEGORIES_KEY,
ArrayList(
getCategoriesDelegate(context).getCategories()
)
)
}
open fun onSetCategory(context: Context, intent: Intent) =
Bundle().also {
it.putParcelable(
NOTIFICATION_CATEGORY_KEY,
getCategoriesDelegate(context).setCategory(
intent.getParcelableExtra(NOTIFICATION_CATEGORY_KEY)!!
)
)
}
open fun onDeleteCategory(context: Context, intent: Intent) =
Bundle().also {
it.putBoolean(
SUCCEEDED_KEY,
getCategoriesDelegate(context).deleteCategory(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
)
}
//endregion
//region Scheduling notifications
open fun onGetAllScheduledNotifications(context: Context, intent: Intent) =
Bundle().also {
it.putParcelableArrayList(
NOTIFICATION_REQUESTS_KEY,
ArrayList(
getSchedulingDelegate(context).getAllScheduledNotifications()
)
)
}
open fun onGetScheduledNotification(context: Context, intent: Intent) =
Bundle().also {
it.putParcelable(
NOTIFICATION_REQUEST_KEY,
getSchedulingDelegate(context).getScheduledNotification(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
)
}
open fun onScheduleNotification(context: Context, intent: Intent) =
getSchedulingDelegate(context).scheduleNotification(
intent.extras?.getParcelable(NOTIFICATION_REQUEST_KEY)!!
)
open fun onNotificationTriggered(context: Context, intent: Intent) =
getSchedulingDelegate(context).triggerNotification(
intent.extras?.getString(IDENTIFIER_KEY)!!
)
open fun onRemoveScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).removeScheduledNotifications(
intent.extras?.getStringArray(IDENTIFIERS_KEY)!!.asList()
)
open fun onRemoveAllScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).removeAllScheduledNotifications()
open fun onSetupScheduledNotifications(context: Context, intent: Intent) =
getSchedulingDelegate(context).setupScheduledNotifications()
//endregion
}
| android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/notifications/service/NotificationsService.kt | 1719960043 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/* ktlint-disable max-line-length */
@RunWith(RobolectricTestRunner::class)
@Config(
manifest = Config.NONE,
minSdk = 23,
maxSdk = 23
)
class ComposerParamSignatureTests : AbstractCodegenSignatureTest() {
@Test
fun testParameterlessChildrenLambdasReused(): Unit = checkApi(
"""
@Composable fun Foo(content: @Composable () -> Unit) {
}
@Composable fun Bar() {
Foo {}
}
""",
// We expect 3 lambda classes. One for Foo's restart group. One for Bar's restart group.
// and one for the content lambda passed into Foo. Importantly, there is no lambda for
// the content lambda's restart group because we are using the lambda itself.
"""
public final class ComposableSingletons%TestKt {
public <init>()V
public final getLambda-1%test_module()Lkotlin/jvm/functions/Function2;
static <clinit>()V
public final static LComposableSingletons%TestKt; INSTANCE
public static Lkotlin/jvm/functions/Function2; lambda-1
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
final class ComposableSingletons%TestKt%lambda-1%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>()V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
static <clinit>()V
public final static LComposableSingletons%TestKt%lambda-1%1; INSTANCE
OUTERCLASS ComposableSingletons%TestKt null
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
public final class TestKt {
public final static Foo(Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;I)V
public final static Bar(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
final static INNERCLASS TestKt%Bar%1 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(Lkotlin/jvm/functions/Function2;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic Lkotlin/jvm/functions/Function2; %content
final synthetic I %%changed
OUTERCLASS TestKt Foo (Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%Bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Bar (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
"""
)
@Test
fun testNoComposerNullCheck(): Unit = validateBytecode(
"""
@Composable fun Foo() {}
"""
) {
assert(!it.contains("INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull"))
}
@Test
fun testStrangeReceiverIssue(): Unit = codegen(
"""
import androidx.compose.runtime.ExplicitGroupsComposable
import androidx.compose.runtime.NonRestartableComposable
class Foo
@Composable
@ExplicitGroupsComposable
fun A(foo: Foo) {
foo.b()
}
@Composable
@ExplicitGroupsComposable
inline fun Foo.b(label: String = "") {
c(this, label)
}
@Composable
@ExplicitGroupsComposable
inline fun c(foo: Foo, label: String) {
used(label)
}
"""
)
@Test
fun testArrayListSizeOverride(): Unit = validateBytecode(
"""
class CustomList : ArrayList<Any>() {
override val size: Int
get() = super.size
}
"""
) {
assertTrue(it.contains("INVOKESPECIAL java/util/ArrayList.size ()I"))
assertFalse(it.contains("INVOKESPECIAL java/util/ArrayList.getSize ()I"))
}
@Test
fun testForLoopIssue1(): Unit = codegen(
"""
@Composable
fun Test(text: String, callback: @Composable () -> Unit) {
for (char in text) {
if (char == '}') {
callback()
continue
}
}
}
"""
)
@Test
fun testForLoopIssue2(): Unit = codegen(
"""
@Composable
fun Test(text: List<String>, callback: @Composable () -> Unit) {
for ((i, value) in text.withIndex()) {
if (value == "" || i == 0) {
callback()
continue
}
}
}
"""
)
@Test
fun testCaptureIssue23(): Unit = codegen(
"""
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.runtime.Composable
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun SimpleAnimatedContentSample() {
@Composable fun Foo() {}
AnimatedContent(1f) {
Foo()
}
}
"""
)
@Test
fun test32Params(): Unit = codegen(
"""
@Composable
fun <T> TooVerbose(
v00: T, v01: T, v02: T, v03: T, v04: T, v05: T, v06: T, v07: T, v08: T, v09: T,
v10: T, v11: T, v12: T, v13: T, v14: T, v15: T, v16: T, v17: T, v18: T, v19: T,
v20: T, v21: T, v22: T, v23: T, v24: T, v25: T, v26: T, v27: T, v28: T, v29: T,
v30: T, v31: T,
) {
}
@Composable
fun Test() {
TooVerbose(
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1,
)
}
"""
)
@Test
fun testInterfaceMethodWithComposableParameter(): Unit = validateBytecode(
"""
@Composable
fun test1(cc: ControlledComposition) {
cc.setContent {}
}
fun test2(cc: ControlledComposition) {
cc.setContent {}
}
"""
) {
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/ControlledComposition.setContent (Lkotlin/jvm/functions/Function0;)V"))
}
@Test
fun testFakeOverrideFromSameModuleButLaterTraversal(): Unit = validateBytecode(
"""
class B : A() {
fun test() {
show {}
}
}
open class A {
fun show(content: @Composable () -> Unit) {}
}
"""
) {
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/ControlledComposition.setContent (Lkotlin/jvm/functions/Function0;)V"))
}
@Test
fun testPrimitiveChangedCalls(): Unit = validateBytecode(
"""
@Composable fun Foo(
a: Boolean,
b: Char,
c: Byte,
d: Short,
e: Int,
f: Float,
g: Long,
h: Double
) {
used(a)
used(b)
used(c)
used(d)
used(e)
used(f)
used(g)
used(h)
}
"""
) {
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Z)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (C)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (B)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (S)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (I)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (F)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (J)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (D)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Ljava/lang/Object;)Z"))
}
@Test
fun testNonPrimitiveChangedCalls(): Unit = validateBytecode(
"""
import androidx.compose.runtime.Stable
@Stable class Bar
@Composable fun Foo(a: Bar) {
used(a)
}
"""
) {
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Z)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (C)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (B)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (S)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (I)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (F)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (J)Z"))
assert(!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (D)Z"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Ljava/lang/Object;)Z"))
}
@Test
fun testInlineClassChangedCalls(): Unit = validateBytecode(
"""
inline class Bar(val value: Int)
@Composable fun Foo(a: Bar) {
used(a)
}
"""
) {
assert(!it.contains("INVOKESTATIC Bar.box-impl (I)LBar;"))
assert(it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (I)Z"))
assert(
!it.contains("INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Ljava/lang/Object;)Z")
)
}
@Test
fun testNullableInlineClassChangedCalls(): Unit = validateBytecode(
"""
inline class Bar(val value: Int)
@Composable fun Foo(a: Bar?) {
used(a)
}
"""
) {
val testClass = it.split("public final class ").single { it.startsWith("test/TestKt") }
assert(
!testClass.contains(
"INVOKEVIRTUAL Bar.unbox-impl ()I"
)
)
assert(
!testClass.contains(
"INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;"
)
)
assert(
testClass.contains(
"INVOKEINTERFACE androidx/compose/runtime/Composer.changed (Ljava/lang/Object;)Z"
)
)
}
@Test
fun testNoNullCheckForPassedParameters(): Unit = validateBytecode(
"""
inline class Bar(val value: Int)
fun nonNull(bar: Bar) {}
@NonRestartableComposable @Composable fun Foo(bar: Bar = Bar(123)) {
nonNull(bar)
}
"""
) {
assert(it.contains("public final static Foo-9N9I_pQ(ILandroidx/compose/runtime/Composer;II)V"))
}
@Test
fun testNoComposerNullCheck2(): Unit = validateBytecode(
"""
val foo = @Composable {}
val bar = @Composable { x: Int -> }
"""
) {
assert(!it.contains("INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull"))
}
@Test
fun testComposableLambdaInvoke(): Unit = validateBytecode(
"""
@Composable fun NonNull(content: @Composable() () -> Unit) {
content.invoke()
}
@Composable fun Nullable(content: (@Composable() () -> Unit)?) {
content?.invoke()
}
"""
) {
assert(
!it.contains(
"INVOKEINTERFACE kotlin/jvm/functions/Function0.invoke ()Ljava/lang/Object; (itf)"
)
)
}
@Test
fun testAnonymousParamNaming(): Unit = validateBytecode(
"""
@Composable
fun Foo(content: @Composable (a: Int, b: Int) -> Unit) {}
@Composable
fun test() {
Foo { _, _ -> }
}
"""
) {
assert(!it.contains("%anonymous parameter 0%"))
}
@Test
fun testBasicClassStaticTransform(): Unit = checkApi(
"""
class Foo
""",
"""
public final class Foo {
public <init>()V
static <clinit>()V
public final static I %stable
}
"""
)
@Test
fun testLambdaReorderedParameter(): Unit = checkApi(
"""
@Composable fun Foo(a: String, b: () -> Unit) { }
@Composable fun Example() {
Foo(b={}, a="Hello, world!")
}
""",
"""
public final class TestKt {
public final static Foo(Ljava/lang/String;Lkotlin/jvm/functions/Function0;Landroidx/compose/runtime/Composer;I)V
public final static Example(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
final static INNERCLASS TestKt%Example%1 null null
final static INNERCLASS TestKt%Example%2 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(Ljava/lang/String;Lkotlin/jvm/functions/Function0;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic Ljava/lang/String; %a
final synthetic Lkotlin/jvm/functions/Function0; %b
final synthetic I %%changed
OUTERCLASS TestKt Foo (Ljava/lang/String;Lkotlin/jvm/functions/Function0;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%Example%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0 {
<init>()V
public final invoke()V
public synthetic bridge invoke()Ljava/lang/Object;
static <clinit>()V
public final static LTestKt%Example%1; INSTANCE
OUTERCLASS TestKt Example (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%2 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Example (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%2 null null
}
"""
)
@Test
fun testCompositionLocalCurrent(): Unit = checkApi(
"""
val a = compositionLocalOf { 123 }
@Composable fun Foo() {
val b = a.current
print(b)
}
""",
"""
public final class TestKt {
public final static getA()Landroidx/compose/runtime/ProvidableCompositionLocal;
public final static Foo(Landroidx/compose/runtime/Composer;I)V
static <clinit>()V
private final static Landroidx/compose/runtime/ProvidableCompositionLocal; a
final static INNERCLASS TestKt%Foo%1 null null
final static INNERCLASS TestKt%a%1 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Foo (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%a%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0 {
<init>()V
public final invoke()Ljava/lang/Integer;
public synthetic bridge invoke()Ljava/lang/Object;
static <clinit>()V
public final static LTestKt%a%1; INSTANCE
OUTERCLASS TestKt null
final static INNERCLASS TestKt%a%1 null null
}
"""
)
@Test
fun testRemappedTypes(): Unit = checkApi(
"""
class A {
fun makeA(): A { return A() }
fun makeB(): B { return B() }
class B() {
}
}
class C {
fun useAB() {
val a = A()
a.makeA()
a.makeB()
val b = A.B()
}
}
""",
"""
public final class A {
public <init>()V
public final makeA()LA;
public final makeB()LA%B;
static <clinit>()V
public final static I %stable
public final static INNERCLASS A%B A B
}
public final class A%B {
public <init>()V
static <clinit>()V
public final static I %stable
public final static INNERCLASS A%B A B
}
public final class C {
public <init>()V
public final useAB()V
static <clinit>()V
public final static I %stable
}
"""
)
@Test
fun testDataClassHashCode(): Unit = validateBytecode(
"""
data class Foo(
val bar: @Composable () -> Unit
)
"""
) {
assert(!it.contains("CHECKCAST kotlin/jvm/functions/Function0"))
}
@Test
@Ignore("b/179279455")
fun testCorrectComposerPassed1(): Unit = checkComposerParam(
"""
var a: Composer? = null
fun run() {
a = makeComposer()
invokeComposable(a) {
assertComposer(a)
}
}
"""
)
@Test
@Ignore("b/179279455")
fun testCorrectComposerPassed2(): Unit = checkComposerParam(
"""
var a: Composer? = null
@Composable fun Foo() {
assertComposer(a)
}
fun run() {
a = makeComposer()
invokeComposable(a) {
Foo()
}
}
"""
)
@Test
@Ignore("b/179279455")
fun testCorrectComposerPassed3(): Unit = checkComposerParam(
"""
var a: Composer? = null
var b: Composer? = null
@Composable fun Callback(fn: () -> Unit) {
fn()
}
fun run() {
a = makeComposer()
b = makeComposer()
invokeComposable(a) {
assertComposer(a)
Callback {
invokeComposable(b) {
assertComposer(b)
}
}
}
}
"""
)
@Test
@Ignore("b/179279455")
fun testCorrectComposerPassed4(): Unit = checkComposerParam(
"""
var a: Composer? = null
var b: Composer? = null
@Composable fun makeInt(): Int {
assertComposer(a)
return 10
}
@Composable fun WithDefault(x: Int = makeInt()) {}
fun run() {
a = makeComposer()
b = makeComposer()
invokeComposable(a) {
assertComposer(a)
WithDefault()
WithDefault(10)
}
invokeComposable(b) {
assertComposer(b)
WithDefault(10)
}
}
"""
)
@Test
@Ignore("b/179279455")
fun testCorrectComposerPassed5(): Unit = checkComposerParam(
"""
var a: Composer? = null
@Composable fun Wrap(content: @Composable () -> Unit) {
content()
}
fun run() {
a = makeComposer()
invokeComposable(a) {
assertComposer(a)
Wrap {
assertComposer(a)
Wrap {
assertComposer(a)
Wrap {
assertComposer(a)
}
}
}
}
}
"""
)
@Test
fun testDefaultParameters(): Unit = checkApi(
"""
@Composable fun Foo(x: Int = 0) {
}
""",
"""
public final class TestKt {
public final static Foo(ILandroidx/compose/runtime/Composer;II)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(III)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
final synthetic I %%changed
final synthetic I %%default
OUTERCLASS TestKt Foo (ILandroidx/compose/runtime/Composer;II)V
final static INNERCLASS TestKt%Foo%1 null null
}
"""
)
@Test
fun testDefaultExpressionsWithComposableCall(): Unit = checkApi(
"""
@Composable fun <T> identity(value: T): T = value
@Composable fun Foo(x: Int = identity(20)) {
}
@Composable fun test() {
Foo()
Foo(10)
}
""",
"""
public final class TestKt {
public final static identity(Ljava/lang/Object;Landroidx/compose/runtime/Composer;I)Ljava/lang/Object;
public final static Foo(ILandroidx/compose/runtime/Composer;II)V
public final static test(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
final static INNERCLASS TestKt%test%1 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(III)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
final synthetic I %%changed
final synthetic I %%default
OUTERCLASS TestKt Foo (ILandroidx/compose/runtime/Composer;II)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%test%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt test (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%test%1 null null
}
"""
)
@Test
fun testBasicCallAndParameterUsage(): Unit = checkApi(
"""
@Composable fun Foo(a: Int, b: String) {
print(a)
print(b)
Bar(a, b)
}
@Composable fun Bar(a: Int, b: String) {
print(a)
print(b)
}
""",
"""
public final class TestKt {
public final static Foo(ILjava/lang/String;Landroidx/compose/runtime/Composer;I)V
public final static Bar(ILjava/lang/String;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
final static INNERCLASS TestKt%Bar%1 null null
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(ILjava/lang/String;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %a
final synthetic Ljava/lang/String; %b
final synthetic I %%changed
OUTERCLASS TestKt Foo (ILjava/lang/String;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%Bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(ILjava/lang/String;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %a
final synthetic Ljava/lang/String; %b
final synthetic I %%changed
OUTERCLASS TestKt Bar (ILjava/lang/String;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
"""
)
@Test
fun testCallFromInlinedLambda(): Unit = checkApi(
"""
@Composable fun Foo() {
listOf(1, 2, 3).forEach { Bar(it) }
}
@Composable fun Bar(a: Int) {}
""",
"""
public final class TestKt {
public final static Foo(Landroidx/compose/runtime/Composer;I)V
public final static Bar(ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%2 null null
final static INNERCLASS TestKt%Bar%1 null null
}
final class TestKt%Foo%2 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Foo (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%2 null null
}
final class TestKt%Bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(II)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %a
final synthetic I %%changed
OUTERCLASS TestKt Bar (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
"""
)
@Test
fun testBasicLambda(): Unit = checkApi(
"""
val foo = @Composable { x: Int -> print(x) }
@Composable fun Bar() {
foo(123)
}
""",
"""
public final class ComposableSingletons%TestKt {
public <init>()V
public final getLambda-1%test_module()Lkotlin/jvm/functions/Function3;
static <clinit>()V
public final static LComposableSingletons%TestKt; INSTANCE
public static Lkotlin/jvm/functions/Function3; lambda-1
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
final class ComposableSingletons%TestKt%lambda-1%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function3 {
<init>()V
public final invoke(ILandroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
static <clinit>()V
public final static LComposableSingletons%TestKt%lambda-1%1; INSTANCE
OUTERCLASS ComposableSingletons%TestKt null
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
public final class TestKt {
public final static getFoo()Lkotlin/jvm/functions/Function3;
public final static Bar(Landroidx/compose/runtime/Composer;I)V
static <clinit>()V
private final static Lkotlin/jvm/functions/Function3; foo
final static INNERCLASS TestKt%Bar%1 null null
}
final class TestKt%Bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Bar (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
"""
)
@Test
fun testLocalLambda(): Unit = checkApi(
"""
@Composable fun Bar(content: @Composable () -> Unit) {
val foo = @Composable { x: Int -> print(x) }
foo(123)
content()
}
""",
"""
public final class ComposableSingletons%TestKt {
public <init>()V
public final getLambda-1%test_module()Lkotlin/jvm/functions/Function3;
static <clinit>()V
public final static LComposableSingletons%TestKt; INSTANCE
public static Lkotlin/jvm/functions/Function3; lambda-1
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
final class ComposableSingletons%TestKt%lambda-1%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function3 {
<init>()V
public final invoke(ILandroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
static <clinit>()V
public final static LComposableSingletons%TestKt%lambda-1%1; INSTANCE
OUTERCLASS ComposableSingletons%TestKt null
final static INNERCLASS ComposableSingletons%TestKt%lambda-1%1 null null
}
public final class TestKt {
public final static Bar(Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
final class TestKt%Bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(Lkotlin/jvm/functions/Function2;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic Lkotlin/jvm/functions/Function2; %content
final synthetic I %%changed
OUTERCLASS TestKt Bar (Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Bar%1 null null
}
"""
)
@Test
fun testNesting(): Unit = checkApi(
"""
@Composable fun Wrap(content: @Composable (x: Int) -> Unit) {
content(123)
}
@Composable fun App(x: Int) {
print(x)
Wrap { a ->
print(a)
print(x)
Wrap { b ->
print(x)
print(a)
print(b)
}
}
}
""",
"""
public final class TestKt {
public final static Wrap(Lkotlin/jvm/functions/Function3;Landroidx/compose/runtime/Composer;I)V
public final static App(ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Wrap%1 null null
final static INNERCLASS TestKt%App%1 null null
final static INNERCLASS TestKt%App%2 null null
}
final class TestKt%Wrap%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(Lkotlin/jvm/functions/Function3;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic Lkotlin/jvm/functions/Function3; %content
final synthetic I %%changed
OUTERCLASS TestKt Wrap (Lkotlin/jvm/functions/Function3;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Wrap%1 null null
}
final class TestKt%App%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function3 {
<init>(I)V
public final invoke(ILandroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
OUTERCLASS TestKt App (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%App%1%1 null null
final static INNERCLASS TestKt%App%1 null null
}
final class TestKt%App%1%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function3 {
<init>(II)V
public final invoke(ILandroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
final synthetic I %a
OUTERCLASS TestKt%App%1 invoke (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%App%1%1 null null
final static INNERCLASS TestKt%App%1 null null
}
final class TestKt%App%2 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(II)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
final synthetic I %%changed
OUTERCLASS TestKt App (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%App%2 null null
}
"""
)
@Test
fun testComposableInterface(): Unit = checkApi(
"""
interface Foo {
@Composable fun bar()
}
class FooImpl : Foo {
@Composable override fun bar() {}
}
""",
"""
public abstract interface Foo {
public abstract bar(Landroidx/compose/runtime/Composer;I)V
}
public final class FooImpl implements Foo {
public <init>()V
public bar(Landroidx/compose/runtime/Composer;I)V
static <clinit>()V
public final static I %stable
final static INNERCLASS FooImpl%bar%1 null null
}
final class FooImpl%bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(LFooImpl;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic LFooImpl; %tmp0_rcvr
final synthetic I %%changed
OUTERCLASS FooImpl bar (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS FooImpl%bar%1 null null
}
"""
)
@Test
fun testSealedClassEtc(): Unit = checkApi(
"""
sealed class CompositionLocal2<T> {
inline val current: T
@Composable
get() = error("")
@Composable fun foo() {}
}
abstract class ProvidableCompositionLocal2<T> : CompositionLocal2<T>() {}
class DynamicProvidableCompositionLocal2<T> : ProvidableCompositionLocal2<T>() {}
class StaticProvidableCompositionLocal2<T> : ProvidableCompositionLocal2<T>() {}
""",
"""
public abstract class CompositionLocal2 {
private <init>()V
public final getCurrent(Landroidx/compose/runtime/Composer;I)Ljava/lang/Object;
public final foo(Landroidx/compose/runtime/Composer;I)V
public synthetic <init>(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
static <clinit>()V
public final static I %stable
final static INNERCLASS CompositionLocal2%foo%1 null null
}
final class CompositionLocal2%foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(LCompositionLocal2;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic LCompositionLocal2; %tmp0_rcvr
final synthetic I %%changed
OUTERCLASS CompositionLocal2 foo (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS CompositionLocal2%foo%1 null null
}
public abstract class ProvidableCompositionLocal2 extends CompositionLocal2 {
public <init>()V
static <clinit>()V
public final static I %stable
}
public final class DynamicProvidableCompositionLocal2 extends ProvidableCompositionLocal2 {
public <init>()V
static <clinit>()V
public final static I %stable
}
public final class StaticProvidableCompositionLocal2 extends ProvidableCompositionLocal2 {
public <init>()V
static <clinit>()V
public final static I %stable
}
"""
)
@Test
fun testComposableTopLevelProperty(): Unit = checkApi(
"""
val foo: Int @Composable get() { return 123 }
""",
"""
public final class TestKt {
public final static getFoo(Landroidx/compose/runtime/Composer;I)I
}
"""
)
@Test
fun testComposableProperty(): Unit = checkApi(
"""
class Foo {
val foo: Int @Composable get() { return 123 }
}
""",
"""
public final class Foo {
public <init>()V
public final getFoo(Landroidx/compose/runtime/Composer;I)I
static <clinit>()V
public final static I %stable
}
"""
)
@Test
fun testTableLambdaThing(): Unit = validateBytecode(
"""
@Composable
fun Foo() {
val c: @Composable () -> Unit = with(123) {
val x = @Composable {}
x
}
}
"""
) {
// TODO(lmr): test
}
@Test
fun testDefaultArgs(): Unit = validateBytecode(
"""
@Composable
fun Scaffold(
topAppBar: @Composable (() -> Unit)? = null
) {}
"""
) {
// TODO(lmr): test
}
@Test
fun testSyntheticAccessFunctions(): Unit = validateBytecode(
"""
class Foo {
@Composable private fun Bar() {}
}
"""
) {
// TODO(lmr): test
}
@Test
fun testLambdaMemoization(): Unit = validateBytecode(
"""
fun subcompose(block: @Composable () -> Unit) {}
private class Foo {
var content: @Composable (Double) -> Unit = {}
fun subcompose() {
val constraints = Math.random()
subcompose {
content(constraints)
}
}
}
"""
) {
// TODO(lmr): test
}
@Test
fun testCallingProperties(): Unit = checkApi(
"""
val bar: Int @Composable get() { return 123 }
@Composable fun Example() {
bar
}
""",
"""
public final class TestKt {
public final static getBar(Landroidx/compose/runtime/Composer;I)I
public final static Example(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Example (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1 null null
}
"""
)
@Test
fun testAbstractComposable(): Unit = checkApi(
"""
abstract class BaseFoo {
@Composable abstract fun bar()
}
class FooImpl : BaseFoo() {
@Composable override fun bar() {}
}
""",
"""
public abstract class BaseFoo {
public <init>()V
public abstract bar(Landroidx/compose/runtime/Composer;I)V
static <clinit>()V
public final static I %stable
}
public final class FooImpl extends BaseFoo {
public <init>()V
public bar(Landroidx/compose/runtime/Composer;I)V
static <clinit>()V
public final static I %stable
final static INNERCLASS FooImpl%bar%1 null null
}
final class FooImpl%bar%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(LFooImpl;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic LFooImpl; %tmp0_rcvr
final synthetic I %%changed
OUTERCLASS FooImpl bar (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS FooImpl%bar%1 null null
}
"""
)
@Test
fun testLocalClassAndObjectLiterals(): Unit = checkApi(
"""
@Composable
fun Wat() {}
@Composable
fun Foo(x: Int) {
Wat()
@Composable fun goo() { Wat() }
class Bar {
@Composable fun baz() { Wat() }
}
goo()
Bar().baz()
}
""",
"""
public final class TestKt {
public final static Wat(Landroidx/compose/runtime/Composer;I)V
public final static Foo(ILandroidx/compose/runtime/Composer;I)V
private final static Foo%goo(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Wat%1 null null
public final static INNERCLASS TestKt%Foo%Bar null Bar
final static INNERCLASS TestKt%Foo%1 null null
}
final class TestKt%Wat%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Wat (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Wat%1 null null
}
public final class TestKt%Foo%Bar {
public <init>()V
public final baz(Landroidx/compose/runtime/Composer;I)V
OUTERCLASS TestKt Foo (ILandroidx/compose/runtime/Composer;I)V
public final static INNERCLASS TestKt%Foo%Bar null Bar
}
final class TestKt%Foo%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(II)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %x
final synthetic I %%changed
OUTERCLASS TestKt Foo (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Foo%1 null null
}
"""
)
@Test
fun testNonComposableCode(): Unit = checkApi(
"""
fun A() {}
val b: Int get() = 123
fun C(x: Int) {
var x = 0
x++
class D {
fun E() { A() }
val F: Int get() = 123
}
val g = object { fun H() {} }
}
fun I(block: () -> Unit) { block() }
fun J() {
I {
I {
A()
}
}
}
""",
"""
public final class TestKt {
public final static A()V
public final static getB()I
public final static C(I)V
public final static I(Lkotlin/jvm/functions/Function0;)V
public final static J()V
public final static INNERCLASS TestKt%C%D null D
public final static INNERCLASS TestKt%C%g%1 null null
final static INNERCLASS TestKt%J%1 null null
}
public final class TestKt%C%D {
public <init>()V
public final E()V
public final getF()I
OUTERCLASS TestKt C (I)V
public final static INNERCLASS TestKt%C%D null D
}
public final class TestKt%C%g%1 {
<init>()V
public final H()V
OUTERCLASS TestKt C (I)V
public final static INNERCLASS TestKt%C%g%1 null null
}
final class TestKt%J%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0 {
<init>()V
public final invoke()V
public synthetic bridge invoke()Ljava/lang/Object;
static <clinit>()V
public final static LTestKt%J%1; INSTANCE
OUTERCLASS TestKt J ()V
final static INNERCLASS TestKt%J%1%1 null null
final static INNERCLASS TestKt%J%1 null null
}
final class TestKt%J%1%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0 {
<init>()V
public final invoke()V
public synthetic bridge invoke()Ljava/lang/Object;
static <clinit>()V
public final static LTestKt%J%1%1; INSTANCE
OUTERCLASS TestKt%J%1 invoke ()V
final static INNERCLASS TestKt%J%1%1 null null
final static INNERCLASS TestKt%J%1 null null
}
"""
)
@Test
fun testCircularCall(): Unit = checkApi(
"""
@Composable fun Example() {
Example()
}
""",
"""
public final class TestKt {
public final static Example(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Example (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1 null null
}
"""
)
@Test
fun testInlineCall(): Unit = checkApi(
"""
@Composable inline fun Example(content: @Composable () -> Unit) {
content()
}
@Composable fun Test() {
Example {}
}
""",
"""
public final class TestKt {
public final static Example(Lkotlin/jvm/functions/Function2;Landroidx/compose/runtime/Composer;I)V
public final static Test(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Test%2 null null
}
final class TestKt%Test%2 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Test (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Test%2 null null
}
"""
)
@Test
fun testDexNaming(): Unit = checkApi(
"""
val myProperty: () -> Unit @Composable get() {
return { }
}
""",
"""
public final class TestKt {
public final static getMyProperty(Landroidx/compose/runtime/Composer;I)Lkotlin/jvm/functions/Function0;
final static INNERCLASS TestKt%myProperty%1 null null
}
final class TestKt%myProperty%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function0 {
<init>()V
public final invoke()V
public synthetic bridge invoke()Ljava/lang/Object;
static <clinit>()V
public final static LTestKt%myProperty%1; INSTANCE
OUTERCLASS TestKt getMyProperty (Landroidx/compose/runtime/Composer;I)Lkotlin/jvm/functions/Function0;
final static INNERCLASS TestKt%myProperty%1 null null
}
"""
)
@Test
fun testInnerClass(): Unit = checkApi(
"""
interface A {
fun b() {}
}
class C {
val foo = 1
inner class D : A {
override fun b() {
print(foo)
}
}
}
""",
"""
public abstract interface A {
public abstract b()V
public final static INNERCLASS A%DefaultImpls A DefaultImpls
}
public final class A%DefaultImpls {
public static b(LA;)V
public final static INNERCLASS A%DefaultImpls A DefaultImpls
}
public final class C {
public <init>()V
public final getFoo()I
static <clinit>()V
private final I foo
public final static I %stable
public final INNERCLASS C%D C D
}
public final class C%D implements A {
public <init>(LC;)V
public b()V
final synthetic LC; this%0
public final INNERCLASS C%D C D
}
"""
)
@Test
fun testFunInterfaces(): Unit = checkApi(
"""
fun interface A {
fun compute(value: Int): Unit
}
fun Example(a: A) {
a.compute(123)
}
fun Usage() {
Example { it -> it + 1 }
}
""",
"""
public abstract interface A {
public abstract compute(I)V
}
public final class TestKt {
public final static Example(LA;)V
public final static Usage()V
final static INNERCLASS TestKt%Usage%1 null null
}
final class TestKt%Usage%1 implements A {
<init>()V
public final compute(I)V
static <clinit>()V
public final static LTestKt%Usage%1; INSTANCE
OUTERCLASS TestKt Usage ()V
final static INNERCLASS TestKt%Usage%1 null null
}
"""
)
@Test
fun testComposableFunInterfaces(): Unit = checkApi(
"""
fun interface A {
@Composable fun compute(value: Int): Unit
}
fun Example(a: A) {
Example { it -> a.compute(it) }
}
""",
"""
public abstract interface A {
public abstract compute(ILandroidx/compose/runtime/Composer;I)V
}
public final class TestKt {
public final static Example(LA;)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1 implements A {
<init>(LA;)V
public final compute(ILandroidx/compose/runtime/Composer;I)V
final synthetic LA; %a
OUTERCLASS TestKt Example (LA;)V
final static INNERCLASS TestKt%Example%1%compute%1 null null
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1%compute%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(LTestKt%Example%1;II)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic LTestKt%Example%1; %tmp0_rcvr
final synthetic I %it
final synthetic I %%changed
OUTERCLASS TestKt%Example%1 compute (ILandroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Example%1%compute%1 null null
final static INNERCLASS TestKt%Example%1 null null
}
"""
)
@Test
fun testFunInterfaceWithInlineReturnType(): Unit = checkApi(
"""
inline class Color(val value: Int)
fun interface A {
fun compute(value: Int): Color
}
fun Example(a: A) {
Example { it -> Color(it) }
}
""",
"""
public final class Color {
public final getValue()I
public static toString-impl(I)Ljava/lang/String;
public toString()Ljava/lang/String;
public static hashCode-impl(I)I
public hashCode()I
public static equals-impl(ILjava/lang/Object;)Z
public equals(Ljava/lang/Object;)Z
private synthetic <init>(I)V
public static constructor-impl(I)I
public final static synthetic box-impl(I)LColor;
public final synthetic unbox-impl()I
public final static equals-impl0(II)Z
private final I value
}
public abstract interface A {
public abstract compute-dZQu5ag(I)I
}
public final class TestKt {
public final static Example(LA;)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1 implements A {
<init>()V
public final compute-dZQu5ag(I)I
static <clinit>()V
public final static LTestKt%Example%1; INSTANCE
OUTERCLASS TestKt Example (LA;)V
final static INNERCLASS TestKt%Example%1 null null
}
"""
)
@Test
fun testComposableFunInterfaceWithInlineReturnType(): Unit = checkApi(
"""
inline class Color(val value: Int)
fun interface A {
@Composable fun compute(value: Int): Color
}
fun Example(a: A) {
Example { it -> Color(it) }
}
""",
"""
public final class Color {
public final getValue()I
public static toString-impl(I)Ljava/lang/String;
public toString()Ljava/lang/String;
public static hashCode-impl(I)I
public hashCode()I
public static equals-impl(ILjava/lang/Object;)Z
public equals(Ljava/lang/Object;)Z
private synthetic <init>(I)V
public static constructor-impl(I)I
public final static synthetic box-impl(I)LColor;
public final synthetic unbox-impl()I
public final static equals-impl0(II)Z
private final I value
}
public abstract interface A {
public abstract compute-WWBqCfo(ILandroidx/compose/runtime/Composer;I)I
}
public final class TestKt {
public final static Example(LA;)V
final static INNERCLASS TestKt%Example%1 null null
}
final class TestKt%Example%1 implements A {
<init>()V
public final compute-WWBqCfo(ILandroidx/compose/runtime/Composer;I)I
static <clinit>()V
public final static LTestKt%Example%1; INSTANCE
OUTERCLASS TestKt Example (LA;)V
final static INNERCLASS TestKt%Example%1 null null
}
"""
)
@Test
fun testComposableMap(): Unit = codegen(
"""
class Repro {
private val composables = linkedMapOf<String, @Composable () -> Unit>()
fun doSomething() {
composables[""]
}
}
"""
)
@Test
fun testComposableColorFunInterfaceExample(): Unit = checkApi(
"""
import androidx.compose.material.Text
import androidx.compose.ui.graphics.Color
@Composable fun condition(): Boolean = true
fun interface ButtonColors {
@Composable fun getColor(): Color
}
@Composable
fun Button(colors: ButtonColors) {
Text("hello world", color = colors.getColor())
}
@Composable
fun Test() {
Button {
if (condition()) Color.Red else Color.Blue
}
}
""",
"""
public abstract interface ButtonColors {
public abstract getColor-WaAFU9c(Landroidx/compose/runtime/Composer;I)J
}
public final class TestKt {
public final static condition(Landroidx/compose/runtime/Composer;I)Z
public final static Button(LButtonColors;Landroidx/compose/runtime/Composer;I)V
public final static Test(Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Button%1 null null
final static INNERCLASS TestKt%Test%1 null null
final static INNERCLASS TestKt%Test%2 null null
}
final class TestKt%Button%1 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(LButtonColors;I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic LButtonColors; %colors
final synthetic I %%changed
OUTERCLASS TestKt Button (LButtonColors;Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Button%1 null null
}
final class TestKt%Test%1 implements ButtonColors {
<init>()V
public final getColor-WaAFU9c(Landroidx/compose/runtime/Composer;I)J
static <clinit>()V
public final static LTestKt%Test%1; INSTANCE
OUTERCLASS TestKt Test (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Test%1 null null
}
final class TestKt%Test%2 extends kotlin/jvm/internal/Lambda implements kotlin/jvm/functions/Function2 {
<init>(I)V
public final invoke(Landroidx/compose/runtime/Composer;I)V
public synthetic bridge invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
final synthetic I %%changed
OUTERCLASS TestKt Test (Landroidx/compose/runtime/Composer;I)V
final static INNERCLASS TestKt%Test%2 null null
}
"""
)
} | compose/compiler/compiler-hosted/integration-tests/src/test/java/androidx/compose/compiler/plugins/kotlin/ComposerParamSignatureTests.kt | 1016322042 |
package com.peterlaurence.trekme.ui.maplist.events
sealed class ZipEvent
data class ZipProgressEvent(val p: Int, val mapName: String, val mapId: Int): ZipEvent()
data class ZipFinishedEvent(val mapId: Int): ZipEvent()
object ZipError : ZipEvent()
object ZipCloseEvent: ZipEvent() // sent after a ZipFinishedEvent to mark as fully completed | app/src/main/java/com/peterlaurence/trekme/ui/maplist/events/ZipEvent.kt | 431980542 |
package com.gh0u1l5.wechatmagician.backend.plugins
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.widget.ListAdapter
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_DELETE
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_EXECUTE
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_INSERT
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_QUERY
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_DATABASE_UPDATE
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_TRACE_FILES
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_TRACE_LOGCAT
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_DUMP_POPUP_MENU
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_TOUCH_EVENT
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_UI_TRACE_ACTIVITIES
import com.gh0u1l5.wechatmagician.Global.DEVELOPER_XML_PARSER
import com.gh0u1l5.wechatmagician.backend.WechatHook
import com.gh0u1l5.wechatmagician.spellbook.C
import com.gh0u1l5.wechatmagician.spellbook.base.Hooker
import com.gh0u1l5.wechatmagician.spellbook.base.HookerProvider
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.sdk.platformtools.Classes.Logcat
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.sdk.platformtools.Methods.XmlParser_parse
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.ui.base.Classes.MMListPopupWindow
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.database.Classes.SQLiteCursorFactory
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.database.Classes.SQLiteDatabase
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.wcdb.support.Classes.SQLiteCancellationSignal
import com.gh0u1l5.wechatmagician.util.MessageUtil.argsToString
import com.gh0u1l5.wechatmagician.util.MessageUtil.bundleToString
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge.*
import de.robv.android.xposed.XposedHelpers.findAndHookConstructor
import de.robv.android.xposed.XposedHelpers.findAndHookMethod
import java.io.File
object Developer : HookerProvider {
private val pref = WechatHook.developer
override fun provideStaticHookers(): List<Hooker>? {
return listOf (
traceTouchEventsHooker,
traceActivitiesHooker,
dumpPopupMenuHooker,
traceDatabaseHooker,
traceLogcatHooker,
traceFilesHooker,
traceXMLParseHooker
)
}
// Hook View.onTouchEvent to trace touch events.
private val traceTouchEventsHooker = Hooker {
if (pref.getBoolean(DEVELOPER_UI_TOUCH_EVENT, false)) {
findAndHookMethod(C.View, "onTouchEvent", C.MotionEvent, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
log("View.onTouchEvent => obj.class = ${param.thisObject::class.java}")
}
})
}
}
// Hook Activity.startActivity and Activity.onCreate to trace activities.
private val traceActivitiesHooker = Hooker {
if (pref.getBoolean(DEVELOPER_UI_TRACE_ACTIVITIES, false)) {
findAndHookMethod(C.Activity, "startActivity", C.Intent, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val intent = param.args[0] as Intent?
log("Activity.startActivity => " +
"${param.thisObject::class.java}, " +
"intent => ${bundleToString(intent?.extras)}")
}
})
findAndHookMethod(C.Activity, "onCreate", C.Bundle, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(param: MethodHookParam) {
val bundle = param.args[0] as Bundle?
val intent = (param.thisObject as Activity).intent
log("Activity.onCreate => " +
"${param.thisObject::class.java}, " +
"intent => ${bundleToString(intent?.extras)}, " +
"bundle => ${bundleToString(bundle)}")
}
})
}
}
// Hook MMListPopupWindow to trace every popup menu.
private val dumpPopupMenuHooker = Hooker {
if (pref.getBoolean(DEVELOPER_UI_DUMP_POPUP_MENU, false)) {
hookAllConstructors(MMListPopupWindow, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(param: MethodHookParam) {
val menu = param.thisObject
val context = param.args[0]
log("POPUP => menu.class = ${menu::class.java}")
log("POPUP => context.class = ${context::class.java}")
}
})
findAndHookMethod(MMListPopupWindow, "setAdapter", C.ListAdapter, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val adapter = param.args[0] as ListAdapter? ?: return
log("POPUP => adapter.count = ${adapter.count}")
(0 until adapter.count).forEach { index ->
log("POPUP => adapter.item[$index] = ${adapter.getItem(index)}")
log("POPUP => adapter.item[$index].class = ${adapter.getItem(index)::class.java}")
}
}
})
}
}
// Hook SQLiteDatabase to trace all the database operations.
private val traceDatabaseHooker = Hooker {
if (pref.getBoolean(DEVELOPER_DATABASE_QUERY, false)) {
findAndHookMethod(
SQLiteDatabase, "rawQueryWithFactory",
SQLiteCursorFactory, C.String, C.StringArray, C.String, SQLiteCancellationSignal, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val sql = param.args[1] as String?
val selectionArgs = param.args[2] as Array<*>?
log("DB => query sql = $sql, selectionArgs = ${argsToString(selectionArgs)}, db = ${param.thisObject}")
}
})
}
if (pref.getBoolean(DEVELOPER_DATABASE_INSERT, false)) {
findAndHookMethod(
SQLiteDatabase, "insertWithOnConflict",
C.String, C.String, C.ContentValues, C.Int, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val table = param.args[0] as String?
val values = param.args[2] as ContentValues?
log("DB => insert table = $table, values = $values, db = ${param.thisObject}")
}
})
}
if (pref.getBoolean(DEVELOPER_DATABASE_UPDATE, false)) {
findAndHookMethod(
SQLiteDatabase, "updateWithOnConflict",
C.String, C.ContentValues, C.String, C.StringArray, C.Int, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val table = param.args[0] as String?
val values = param.args[1] as ContentValues?
val whereClause = param.args[2] as String?
val whereArgs = param.args[3] as Array<*>?
log("DB => update " +
"table = $table, " +
"values = $values, " +
"whereClause = $whereClause, " +
"whereArgs = ${argsToString(whereArgs)}, " +
"db = ${param.thisObject}")
}
})
}
if (pref.getBoolean(DEVELOPER_DATABASE_DELETE, false)) {
findAndHookMethod(
SQLiteDatabase, "delete",
C.String, C.String, C.StringArray, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val table = param.args[0] as String?
val whereClause = param.args[1] as String?
val whereArgs = param.args[2] as Array<*>?
log("DB => delete " +
"table = $table, " +
"whereClause = $whereClause, " +
"whereArgs = ${argsToString(whereArgs)}, " +
"db = ${param.thisObject}")
}
})
}
if (pref.getBoolean(DEVELOPER_DATABASE_EXECUTE, false)) {
findAndHookMethod(
SQLiteDatabase, "executeSql",
C.String, C.ObjectArray, SQLiteCancellationSignal, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val sql = param.args[0] as String?
val bindArgs = param.args[1] as Array<*>?
log("DB => executeSql sql = $sql, bindArgs = ${argsToString(bindArgs)}, db = ${param.thisObject}")
}
})
}
}
// Hook Log to trace hidden logcat output.
private val traceLogcatHooker = Hooker {
if (pref.getBoolean(DEVELOPER_TRACE_LOGCAT, false)) {
val functions = listOf("d", "e", "f", "i", "v", "w")
functions.forEach { func ->
findAndHookMethod(Logcat, func, C.String, C.String, C.ObjectArray, object : XC_MethodHook() {
override fun afterHookedMethod(param: MethodHookParam) {
val tag = param.args[0] as String?
val msg = param.args[1] as String?
val args = param.args[2] as Array<*>?
if (args == null) {
log("LOG.${func.toUpperCase()} => [$tag] $msg")
} else {
log("LOG.${func.toUpperCase()} => [$tag] ${msg?.format(*args)}")
}
}
})
}
}
}
// Hook FileInputStream / FileOutputStream to trace file operations.
private val traceFilesHooker = Hooker {
if (pref.getBoolean(DEVELOPER_TRACE_FILES, false)) {
findAndHookConstructor(C.FileInputStream, C.File, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val path = (param.args[0] as File?)?.absolutePath ?: return
log("FILE => Read $path")
}
})
findAndHookConstructor(C.FileOutputStream, C.File, C.Boolean, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun beforeHookedMethod(param: MethodHookParam) {
val path = (param.args[0] as File?)?.absolutePath ?: return
log("FILE => Write $path")
}
})
findAndHookMethod(C.File, "delete", object : XC_MethodHook() {
override fun beforeHookedMethod(param: MethodHookParam) {
val file = param.thisObject as File
log("FILE => Delete ${file.absolutePath}")
}
})
}
}
// Hook XML Parser to trace the XML files used in Wechat.
private val traceXMLParseHooker = Hooker {
if (pref.getBoolean(DEVELOPER_XML_PARSER, false)) {
hookMethod(XmlParser_parse, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(param: MethodHookParam) {
val xml = param.args[0] as String?
val root = param.args[1] as String?
log("XML => root = $root, xml = $xml")
}
})
}
}
} | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/Developer.kt | 3776833619 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.search
import com.intellij.find.findUsages.FindUsagesHandler
import com.intellij.psi.PsiElement
class RsFindUsagesHandler(
psiElement: PsiElement,
private val secondaryElements: List<PsiElement>
) : FindUsagesHandler(psiElement) {
override fun getSecondaryElements(): Array<PsiElement> = secondaryElements.toTypedArray()
}
| src/main/kotlin/org/rust/ide/search/RsFindUsagesHandler.kt | 164659837 |
/*
* Copyright 2019 Kunal Sheth
*
* 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 info.kunalsheth.units.data
import info.kunalsheth.units.data.RelationType.Divide
import info.kunalsheth.units.data.RelationType.Multiply
import java.io.Serializable
/**
* Created by kunal on 8/5/17.
*/
data class Relation(val a: Dimension, val f: RelationType, val b: Dimension) : Serializable {
val result = f(a, b)
companion object {
private fun Set<Dimension>.permuteRelations() =
flatMap { x ->
flatMap { y ->
listOf(
Relation(x, Divide, x),
Relation(x, Divide, y),
Relation(x, Multiply, x),
Relation(x, Multiply, y),
Relation(y, Divide, x),
Relation(y, Divide, y),
Relation(y, Multiply, x),
Relation(y, Multiply, y)
)
}
}
fun closedPermute(inputDimensions: Set<Dimension>) = inputDimensions.permuteRelations()
.filter { arrayOf(it.a, it.b, it.result).all { it in inputDimensions } }
.toSet()
fun openPermute(inputDimensions: Set<Dimension>): Set<Relation> {
val newDimensions = inputDimensions +
inputDimensions.permuteRelations().map(Relation::result)
return newDimensions
.permuteRelations()
.filter { arrayOf(it.a, it.b, it.result).all { it in newDimensions } }
.toSet()
}
}
}
enum class RelationType : (Dimension, Dimension) -> Dimension {
Divide {
override fun invoke(a: Dimension, b: Dimension) = Dimension(
L = a.L - b.L,
A = a.A - b.A,
M = a.M - b.M,
T = a.T - b.T,
I = a.I - b.I,
Theta = a.Theta - b.Theta,
N = a.N - b.N,
J = a.J - b.J
)
},
Multiply {
override fun invoke(a: Dimension, b: Dimension) = Dimension(
L = a.L + b.L,
A = a.A + b.A,
M = a.M + b.M,
T = a.T + b.T,
I = a.I + b.I,
Theta = a.Theta + b.Theta,
N = a.N + b.N,
J = a.J + b.J
)
}
} | plugin/src/main/kotlin/info/kunalsheth/units/data/Relation.kt | 333555511 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.infer
import org.rust.lang.utils.snapshot.Snapshot
import org.rust.lang.utils.snapshot.UndoLog
import org.rust.lang.utils.snapshot.Undoable
interface NodeOrValue
interface Node: NodeOrValue {
var parent: NodeOrValue
}
data class VarValue<out V>(val value: V?, val rank: Int): NodeOrValue
/**
* [UnificationTable] is map from [K] to [V] with additional ability
* to redirect certain K's to a single V en-masse with the help of
* disjoint set union.
*
* We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* [Disjoint-set data structure](https://en.wikipedia.org/wiki/Disjoint-set_data_structure).
*/
@Suppress("UNCHECKED_CAST")
class UnificationTable<K : Node, V> {
private val undoLog: UndoLog = UndoLog()
@Suppress("UNCHECKED_CAST")
private data class Root<out K: Node, out V>(val key: K) {
private val varValue: VarValue<V> = key.parent as VarValue<V>
val rank: Int get() = varValue.rank
val value: V? get() = varValue.value
}
private fun get(key: Node): Root<K, V> {
val parent = key.parent
return if (parent is Node) {
val root = get(parent)
if (key.parent != root.key) {
logNodeState(key)
key.parent = root.key // Path compression
}
root
} else {
Root(key as K)
}
}
private fun setValue(root: Root<K, V>, value: V) {
logNodeState(root.key)
root.key.parent = VarValue(value, root.rank)
}
private fun unify(rootA: Root<K, V>, rootB: Root<K, V>, newValue: V?): K {
return when {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
rootA.rank > rootB.rank -> redirectRoot(rootA.rank, rootB, rootA, newValue)
// b has greater rank, so a should redirect to b.
rootA.rank < rootB.rank -> redirectRoot(rootB.rank, rootA, rootB, newValue)
// If equal, redirect one to the other and increment the
// other's rank.
else -> redirectRoot(rootA.rank + 1, rootA, rootB, newValue)
}
}
private fun redirectRoot(newRank: Int, oldRoot: Root<K, V>, newRoot: Root<K, V>, newValue: V?): K {
val oldRootKey = oldRoot.key
val newRootKey = newRoot.key
logNodeState(newRootKey)
logNodeState(oldRootKey)
oldRootKey.parent = newRootKey
newRootKey.parent = VarValue(newValue, newRank)
return newRootKey
}
fun findRoot(key: K): K = get(key).key
fun findValue(key: K): V? = get(key).value
fun unifyVarVar(key1: K, key2: K): K {
val node1 = get(key1)
val node2 = get(key2)
if (node1.key == node2.key) return node1.key // already unified
val val1 = node1.value
val val2 = node2.value
val newVal = if (val1 != null && val2 != null) {
if (val1 != val2) error("unification error") // must be solved on the upper level
val1
} else {
val1 ?: val2
}
return unify(node1, node2, newVal)
}
fun unifyVarValue(key: K, value: V) {
val node = get(key)
if (node.value != null && node.value != value) error("unification error") // must be solved on the upper level
setValue(node, value)
}
private fun logNodeState(node: Node) {
undoLog.logChange(SetParent(node, node.parent))
}
fun startSnapshot(): Snapshot = undoLog.startSnapshot()
private data class SetParent(private val node: Node, private val oldParent: NodeOrValue) : Undoable {
override fun undo() {
node.parent = oldParent
}
}
}
| src/main/kotlin/org/rust/lang/core/types/infer/Unify.kt | 534884541 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve.ref
import org.rust.lang.core.psi.RsBinaryOp
import org.rust.lang.core.psi.ext.OverloadableBinaryOperator
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.operatorType
import org.rust.lang.core.resolve.collectResolveVariants
import org.rust.lang.core.resolve.processBinaryOpVariants
class RsBinaryOpReferenceImpl(
element: RsBinaryOp
) : RsReferenceCached<RsBinaryOp>(element) {
override val cacheDependency: ResolveCacheDependency get() = ResolveCacheDependency.LOCAL_AND_RUST_STRUCTURE
override fun resolveInner(): List<RsElement> {
val operator = element.operatorType as? OverloadableBinaryOperator ?: return emptyList()
return collectResolveVariants(operator.fnName) { processBinaryOpVariants(element, operator, it) }
}
}
| src/main/kotlin/org/rust/lang/core/resolve/ref/RsBinaryOpReferenceImpl.kt | 3961421711 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.autocomplete
import android.content.Context
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class CustomAutocompleteTest {
@Before
fun setUp() {
RuntimeEnvironment.application
.getSharedPreferences("custom_autocomplete", Context.MODE_PRIVATE)
.edit()
.clear()
.apply()
}
@Test
fun testCustomListIsEmptyByDefault() {
val domains = runBlocking {
CustomAutocomplete.loadCustomAutoCompleteDomains(RuntimeEnvironment.application)
}
assertEquals(0, domains.size)
}
@Test
fun testSavingAndLoadingDomains() = runBlocking {
CustomAutocomplete.saveDomains(RuntimeEnvironment.application, listOf(
"mozilla.org",
"example.org",
"example.com"
))
val domains = CustomAutocomplete.loadCustomAutoCompleteDomains(RuntimeEnvironment.application)
assertEquals(3, domains.size)
assertEquals("mozilla.org", domains.elementAt(0))
assertEquals("example.org", domains.elementAt(1))
assertEquals("example.com", domains.elementAt(2))
}
} | app/src/test/java/org/mozilla/focus/autocomplete/CustomAutocompleteTest.kt | 492991306 |
// Copyright 2022 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.maps.android.compose
import androidx.compose.runtime.Immutable
import com.google.maps.android.compose.CameraMoveStartedReason.Companion.fromInt
import com.google.maps.android.compose.CameraMoveStartedReason.NO_MOVEMENT_YET
import com.google.maps.android.compose.CameraMoveStartedReason.UNKNOWN
/**
* Enumerates the different reasons why the map camera started to move.
*
* Based on enum values from https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnCameraMoveStartedListener#constants.
*
* [NO_MOVEMENT_YET] is used as the initial state before any map movement has been observed.
*
* [UNKNOWN] is used to represent when an unsupported integer value is provided to [fromInt] - this
* may be a new constant value from the Maps SDK that isn't supported by maps-compose yet, in which
* case this library should be updated to include a new enum value for that constant.
*/
@Immutable
public enum class CameraMoveStartedReason(public val value: Int) {
UNKNOWN(-2),
NO_MOVEMENT_YET(-1),
GESTURE(com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE),
API_ANIMATION(com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener.REASON_API_ANIMATION),
DEVELOPER_ANIMATION(com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION);
public companion object {
/**
* Converts from the Maps SDK [com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener]
* constants to [CameraMoveStartedReason], or returns [UNKNOWN] if there is no such
* [CameraMoveStartedReason] for the given [value].
*
* See https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnCameraMoveStartedListener#constants.
*/
public fun fromInt(value: Int): CameraMoveStartedReason {
return values().firstOrNull { it.value == value } ?: return UNKNOWN
}
}
} | maps-compose/src/main/java/com/google/maps/android/compose/CameraMoveStartedReason.kt | 504612536 |
package com.cauchymop.goblob.viewmodel
import com.cauchymop.goblob.proto.PlayGameData
data class PlayerViewModel(val playerName: String,
val playerColor: PlayGameData.Color)
| goblobBase/src/main/java/com/cauchymop/goblob/viewmodel/PlayerViewModel.kt | 3424488588 |
package de.holisticon.ranked.properties.test
import de.holisticon.ranked.extension.runApplicationExpr
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class PropertiesSpecApplication
fun main(args: Array<String>) = runApplicationExpr<PropertiesSpecApplication>(*args)
| backend/properties/src/test/kotlin/test/TestApplication.kt | 90572351 |
<comment>/**</comment>
<comment>*</comment>
<comment>* </comment>@see NotComent <comment>text</comment>
<comment>*/</comment> | kotlin-eclipse-ui-test/testData/highlighting/basic/kdocWithSee.kt | 536727267 |
/*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.launch
import org.eclipse.core.resources.IFile
import org.eclipse.core.resources.ResourcesPlugin
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.core.runtime.Path
import org.eclipse.debug.core.ILaunch
import org.eclipse.debug.core.ILaunchConfiguration
import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate
import org.eclipse.jdt.launching.ExecutionArguments
import org.eclipse.jdt.launching.VMRunnerConfiguration
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.core.model.KOTLIN_COMPILER_PATH
import org.jetbrains.kotlin.core.utils.ProjectUtils
import java.io.File
class KotlinScriptLaunchConfigurationDelegate : AbstractJavaLaunchConfigurationDelegate() {
companion object {
private val compilerMainClass = K2JVMCompiler::class.java.name
private val classpathForCompiler = arrayOf(File(KOTLIN_COMPILER_PATH).absolutePath)
}
override fun launch(configuration: ILaunchConfiguration, mode: String, launch: ILaunch, monitor: IProgressMonitor) {
monitor.beginTask("${configuration.name}...", 2)
try {
monitor.subTask("Verifying launch attributes...")
val runConfig = verifyAndCreateRunnerConfiguration(configuration) ?: return
if (monitor.isCanceled()) {
return;
}
monitor.worked(1)
val runner = getVMRunner(configuration, mode)
runner.run(runConfig, launch, monitor)
if (monitor.isCanceled()) {
return;
}
} finally {
monitor.done()
}
}
private fun verifyAndCreateRunnerConfiguration(configuration: ILaunchConfiguration): VMRunnerConfiguration? {
val scriptFile = getScriptFile(configuration) ?: return null
if (!scriptFile.exists()) return null
val workingDir = verifyWorkingDirectory(configuration)?.absolutePath
val programArgs = getProgramArguments(configuration)
val vmArgs = getVMArguments(configuration)
val executionArgs = ExecutionArguments(vmArgs, programArgs)
val environmentVars = getEnvironment(configuration)
val vmAttributesMap: MutableMap<String, Any>? = getVMSpecificAttributesMap(configuration)
return VMRunnerConfiguration(compilerMainClass, classpathForCompiler).apply {
setProgramArguments(buildCompilerArguments(
scriptFile,
executionArgs.programArgumentsArray).toTypedArray())
setEnvironment(environmentVars)
setVMArguments(executionArgs.vmArgumentsArray)
setWorkingDirectory(workingDir);
setVMSpecificAttributesMap(vmAttributesMap)
setBootClassPath(getBootpath(configuration))
}
}
private fun getScriptFile(configuration: ILaunchConfiguration): IFile? {
return configuration.getAttribute(SCRIPT_FILE_PATH, null as String?)?.let { scriptFilePath ->
ResourcesPlugin.getWorkspace().root.getFile(Path(scriptFilePath))
}
}
private fun buildCompilerArguments(scriptFile: IFile, programArguments: Array<String>): List<String> {
return arrayListOf<String>().apply {
add("-kotlin-home")
add(ProjectUtils.KT_HOME)
add("-script")
add(scriptFile.getLocation().toOSString())
addAll(programArguments)
}
}
} | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/launch/KotlinScriptLaunchConfigurationDelegate.kt | 2496775946 |
package com.baeldung.constructor
open class Person(
val name: String,
val age: Int? = null
) {
val upperCaseName: String = name.toUpperCase()
init {
println("Hello, I'm $name")
if (age != null && age < 0) {
throw IllegalArgumentException("Age cannot be less than zero!")
}
}
init {
println("upperCaseName is $upperCaseName")
}
}
fun main(args: Array<String>) {
val person = Person("John")
val personWithAge = Person("John", 22)
} | projects/tutorials-master/tutorials-master/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt | 3524847951 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val EXT_bindable_uniform = "EXTBindableUniform".nativeClassGL("EXT_bindable_uniform", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension introduces the concept of bindable uniforms to the OpenGL Shading Language. A uniform variable can be declared bindable, which means that
the storage for the uniform is not allocated by the compiler/linker anymore, but is backed by a buffer object. This buffer object is bound to the
bindable uniform through the new command UniformBufferEXT(). Binding needs to happen after linking a program object.
Binding different buffer objects to a bindable uniform allows an application to easily use different "uniform data sets", without having to re-specify
the data every time.
A buffer object can be bound to bindable uniforms in different program objects. If those bindable uniforms are all of the same type, accessing a
bindable uniform in program object A will result in the same data if the same access is made in program object B. This provides a mechanism for
'environment uniforms', uniform values that can be shared among multiple program objects.
"""
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"MAX_VERTEX_BINDABLE_UNIFORMS_EXT"..0x8DE2,
"MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT"..0x8DE3,
"MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT"..0x8DE4,
"MAX_BINDABLE_UNIFORM_SIZE_EXT"..0x8DED,
"UNIFORM_BUFFER_BINDING_EXT"..0x8DEF
)
IntConstant(
"Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and GetBufferPointerv.",
"UNIFORM_BUFFER_EXT"..0x8DEE
)
void(
"UniformBufferEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", ""),
GLuint.IN("buffer", "")
)
GLint(
"GetUniformBufferSizeEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", "")
)
GLintptr(
"GetUniformOffsetEXT",
"",
GLuint.IN("program", ""),
GLint.IN("location", "")
)
} | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/EXT_bindable_uniform.kt | 2996786488 |
package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import org.elm.lang.core.psi.*
/**
* A function call expression.
*
* e.g.
* - `toString 1`
* - `(+) 1 2`
* - `List.map toString [1, 2]`
* - `record.functionInField ()`
* - `(\x -> x) 1`
* - `(a << b) c
*/
class ElmFunctionCallExpr(node: ASTNode) : ElmPsiElementImpl(node), ElmExpressionTag, ElmOperandTag {
/**
* The function being called.
*
* In a well-formed program, the target must also be a [ElmFunctionCallTargetTag].
* (the parse rule was relaxed to allow any atom as a performance optimization)
*/
val target: ElmAtomTag
get() =
findNotNullChildByClass(ElmAtomTag::class.java)
/** The arguments to the function. This will always have at least one element */
val arguments: Sequence<ElmAtomTag>
get() =
directChildren.filterIsInstance<ElmAtomTag>().drop(1)
}
| src/main/kotlin/org/elm/lang/core/psi/elements/ElmFunctionCallExpr.kt | 992138121 |
/*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.states
import com.pyamsoft.powermanager.model.StateObserver
import com.pyamsoft.powermanager.model.States
import timber.log.Timber
import javax.inject.Inject
internal class DataSaverStateObserver @Inject internal constructor(
private val wrapper: DeviceFunctionWrapper) : StateObserver {
init {
Timber.d("New StateObserver for Data Saver")
}
override fun enabled(): Boolean {
val enabled = wrapper.state === States.ENABLED
Timber.d("Enabled: %s", enabled)
return enabled
}
override fun unknown(): Boolean {
val unknown = wrapper.state === States.UNKNOWN
Timber.d("Unknown: %s", unknown)
return unknown
}
}
| powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/DataSaverStateObserver.kt | 1975896893 |
/*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.service
import android.content.SyncResult
import org.andstatus.app.account.MyAccount
import org.andstatus.app.context.MyContext
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.util.MyLog
class MyServiceCommandsRunner(private val myContext: MyContext) {
private var ignoreServiceAvailability = false
fun autoSyncAccount(ma: MyAccount, syncResult: SyncResult) {
val method = "syncAccount " + ma.getAccountName()
if (!myContext.isReady) {
MyLog.d(this, "$method; Context is not ready")
return
}
if (ma.nonValid) {
MyLog.d(this, "$method; The account was not loaded")
return
} else if (!ma.isValidAndSucceeded()) {
syncResult.stats.numAuthExceptions++
MyLog.d(this, "$method; Credentials failed, skipping")
return
}
val timelines = myContext.timelines.toAutoSyncForAccount(ma)
if (timelines.isEmpty()) {
MyLog.d(this, "$method; No timelines to sync")
return
}
MyLog.v(this) { method + " started, " + timelines.size + " timelines" }
timelines.stream()
.map { t: Timeline -> CommandData.newTimelineCommand(CommandEnum.GET_TIMELINE, t) }
.forEach { commandData: CommandData -> sendCommand(commandData) }
MyLog.v(this) { method + " ended, " + timelines.size + " timelines requested: " + timelines }
}
private fun sendCommand(commandData: CommandData) {
// we don't wait for completion anymore.
// TODO: Implement Synchronous background sync ?!
if (ignoreServiceAvailability) {
MyServiceManager.sendCommandIgnoringServiceAvailability(commandData)
} else {
MyServiceManager.sendCommand(commandData)
}
}
fun setIgnoreServiceAvailability(ignoreServiceAvailability: Boolean) {
this.ignoreServiceAvailability = ignoreServiceAvailability
}
}
| app/src/main/kotlin/org/andstatus/app/service/MyServiceCommandsRunner.kt | 3380955103 |
package com.makingiants.caty.screens.settings
import com.makingiants.caty.model.cache.Settings
import com.makingiants.caty.model.notifications.Notifier
open class SettingsPresenter(val settings: Settings, val notifier: Notifier) {
private var view: SettingsView? = null
fun attach(view: SettingsView) {
this.view = view
if (settings.notificationPermissionGranted) {
view.setupViews()
view.setHeadphonesToggleCheck(settings.playJustWithHeadphones)
view.setReadNotificationsCheck(settings.readNotificationEnabled)
view.setReadOnlyMessageNotificationsCheck(settings.readJustMessages)
setOtherViewsEnabled(settings.readNotificationEnabled)
} else {
view.startWelcomeView()
view.close()
}
}
fun unAttach() {
view = null
}
fun onSwitchPlayJustWithHeadphonesClick(checked: Boolean) {
settings.playJustWithHeadphones = checked
}
fun onButtonTryClick(text: String) {
notifier.notify("Test", text)
}
fun onSwitchReadNotificationEnabledClick(checked: Boolean) {
settings.readNotificationEnabled = checked
setOtherViewsEnabled(checked)
}
open fun setOtherViewsEnabled(enabled: Boolean) {
view?.apply {
setEnabledSwitchPlayJustWithHeadphones(enabled)
setEnabledSwitchPlayJustMessageNotifications(enabled)
}
}
} | app/src/main/java/com/makingiants/caty/screens/settings/SettingsPresenter.kt | 2917221718 |
package com.commonsense.android.kotlin.views.extensions
import com.commonsense.android.kotlin.test.*
import org.junit.*
/**
* Created by Kasper Tvede on 1/29/2018.
* Purpose:
*/
class ListViewExtensionsKtTest : BaseRoboElectricTest() {
@Test
fun scrollToTop() {
}
@Test
fun scrollToBottom() {
}
} | widgets/src/test/kotlin/com/commonsense/android/kotlin/views/extensions/ListViewExtensionsKtTest.kt | 3776807586 |
package ru.fantlab.android.ui.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
import ru.fantlab.android.helper.TypeFaceHelper
/**
* Created by Kosh on 8/18/2015. copyrights are reserved
*/
class FontAutoCompleteEditText : AppCompatAutoCompleteTextView {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
if (isInEditMode) return
inputType = inputType or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_FULLSCREEN
imeOptions = imeOptions or EditorInfo.IME_FLAG_NO_FULLSCREEN
TypeFaceHelper.applyTypeface(this)
}
}
| app/src/main/kotlin/ru/fantlab/android/ui/widgets/FontAutoCompleteEditText.kt | 2538108301 |
package org.jetbrains.cabal.psi
import com.intellij.lang.ASTNode
import org.jetbrains.cabal.parser.*
import org.jetbrains.cabal.psi.Name
import java.util.ArrayList
import org.jetbrains.cabal.highlight.ErrorMessage
import java.lang.IllegalStateException
public class Benchmark(node: ASTNode) : BuildSection(node) {
public override fun getAvailableFieldNames(): List<String> {
var res = ArrayList<String>()
res.addAll(BENCHMARK_FIELDS.keySet())
res.addAll(IF_ELSE)
return res
}
public override fun check(): List<ErrorMessage> {
val res = ArrayList<ErrorMessage>()
val typeField = getField(javaClass<TypeField>())
val mainIsField = getField(javaClass<MainFileField>())
if (typeField == null) {
res.add(ErrorMessage(getSectTypeNode(), "type field is required", "error"))
}
if ((typeField?.getValue()?.getText() == "exitcode-stdio-1.0") && (mainIsField == null)) {
res.add(ErrorMessage(getSectTypeNode(), "main-is field is required", "error"))
}
return res
}
public fun getBenchmarkName(): String {
val res = getSectName()
if (res == null) throw IllegalStateException()
return res
}
}
| plugin/src/org/jetbrains/cabal/psi/Benchmark.kt | 3301827983 |
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Represents a product tag recommendation. Extends Recommendation.
*/
package dk.etiktak.backend.model.recommendation
import dk.etiktak.backend.model.product.ProductTag
import javax.persistence.*
@Entity
@DiscriminatorValue("ProductTag")
class ProductTagRecommendation : Recommendation() {
@ManyToOne(optional = true)
@JoinColumn(name = "product_tag_id")
var productTag = ProductTag()
} | src/main/kotlin/dk/etiktak/backend/model/recommendation/ProductTagRecommendation.kt | 1158246998 |
/**
* 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.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.typeIs
import org.sonar.plugins.plsqlopen.api.DmlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlPunctuator
import org.sonar.plugins.plsqlopen.api.annotations.*
import org.sonar.plugins.plsqlopen.api.symbols.PlSqlType
@Rule(priority = Priority.MAJOR, tags = [Tags.PERFORMANCE])
@ConstantRemediation("30min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class SelectAllColumnsCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(DmlGrammar.SELECT_COLUMN)
}
override fun visitNode(node: AstNode) {
val topParent = node.parent.parent.parent
if (topParent.typeIs(PlSqlGrammar.EXISTS_EXPRESSION)) {
return
}
if (topParent.typeIs(PlSqlGrammar.CURSOR_DECLARATION)) {
// TODO this is very complex and it probably can be simplified in the future
val fetchDestination = semantic(topParent.getFirstChild(PlSqlGrammar.IDENTIFIER_NAME))
.symbol?.usages().orEmpty()
.map { it.parent.parent }
.filter { it.typeIs(PlSqlGrammar.FETCH_STATEMENT) }
.map { it.getFirstChild(DmlGrammar.INTO_CLAUSE).getFirstChildOrNull(PlSqlGrammar.VARIABLE_NAME) }
.firstOrNull()
if (fetchDestination != null && semantic(fetchDestination).plSqlType == PlSqlType.ROWTYPE) {
return
}
}
var candidate = node.firstChild
if (candidate.typeIs(PlSqlGrammar.OBJECT_REFERENCE)) {
candidate = candidate.lastChild
}
if (candidate.typeIs(PlSqlPunctuator.MULTIPLICATION)) {
val intoClause = node.parent.getFirstChildOrNull(DmlGrammar.INTO_CLAUSE)
if (intoClause != null) {
val variablesInInto = intoClause.getChildren(PlSqlGrammar.VARIABLE_NAME, PlSqlGrammar.MEMBER_EXPRESSION, PlSqlGrammar.METHOD_CALL)
val type = semantic(variablesInInto[0]).plSqlType
if (variablesInInto.size == 1 && (type == PlSqlType.ROWTYPE || type == PlSqlType.ASSOCIATIVE_ARRAY)) {
return
}
}
addIssue(node, getLocalizedMessage())
}
}
}
| zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/SelectAllColumnsCheck.kt | 3354429826 |
package com.eden.orchid.impl.assets
import com.eden.orchid.impl.generators.HomepageGenerator
import com.eden.orchid.strikt.htmlBodyMatches
import com.eden.orchid.strikt.nothingElseRendered
import com.eden.orchid.strikt.pageWasRendered
import com.eden.orchid.testhelpers.OrchidIntegrationTest
import com.eden.orchid.testhelpers.withGenerator
import kotlinx.html.img
import kotlinx.html.p
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import strikt.api.expectThat
@DisplayName("Tests behavior of asset functions.")
class AssetFunctionsTest : OrchidIntegrationTest(withGenerator<HomepageGenerator>()) {
@Test
@DisplayName("Test asset function works properly")
fun test01() {
resource(
"homepage.md",
"""
|---
|---
|
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test rename function works properly")
fun test02() {
resource(
"homepage.md",
"""
|---
|---
| }})
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/some/other/directory.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/some/other/directory.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test rotate function works properly")
fun test03() {
resource(
"homepage.md",
"""
|---
|---
| }})
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image_rotate-90.0.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image_rotate-90.0.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test resize function works properly")
fun test04() {
resource(
"homepage.md",
"""
|---
|---
| }})
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image_800x600_exact.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image_800x600_exact.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test scale function works properly")
fun test05() {
resource(
"homepage.md",
"""
|---
|---
| }})
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image_scale-0.85.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image_scale-0.85.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test image function works properly")
fun test06() {
resource(
"homepage.md",
"""
|---
|---
|{{ "assets/media/image.jpg"|img('image') }}
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
@Test
@DisplayName("Test scale function works properly when rendered using img function")
fun test07() {
resource(
"homepage.md",
"""
|---
|---
|{{ "assets/media/image.jpg"|asset|scale(0.85)|img('image') }}
""".trimMargin()
)
classpathResource("assets/media/image.jpg")
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
p {
img(src = "http://orchid.test/assets/media/image_scale-0.85.jpg") {
alt = "image"
}
}
}
}
.pageWasRendered("/assets/media/image_scale-0.85.jpg") {}
.pageWasRendered("/favicon.ico") {}
.pageWasRendered("/404.html") {}
.nothingElseRendered()
}
}
| OrchidTest/src/test/kotlin/com/eden/orchid/impl/assets/AssetFunctionsTest.kt | 523649518 |
package com.google.firebase.dynamicinvites.kotlin.presenter
import android.content.Context
import android.widget.Toast
import com.google.firebase.dynamicinvites.R
import com.google.firebase.dynamicinvites.kotlin.model.InviteContent
class CopyPresenter(isAvailable: Boolean, content: InviteContent) :
InvitePresenter("Copy Link", R.drawable.ic_content_copy, isAvailable, content) {
override fun sendInvite(context: Context) {
super.sendInvite(context)
Toast.makeText(context, "TODO: Implement link copying", Toast.LENGTH_SHORT).show()
}
}
| dl-invites/app/src/main/java/com/google/firebase/dynamicinvites/kotlin/presenter/CopyPresenter.kt | 2385530786 |
package com.vimeo.stag.processor.utils
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import com.vimeo.stag.processor.Utils
import com.vimeo.stag.processor.utils.logging.DebugLog
import com.vimeo.stag.processor.utils.logging.Logger
import org.junit.Before
import org.junit.Test
/**
* Unit tests for [DebugLog].
*
* Created by restainoa on 6/15/18.
*/
class DebugLogTest {
@Before
fun setUp() {
DebugLog.initialize(null)
}
@Test
fun `DebugLog is not instantiable`() {
Utils.testZeroArgumentConstructorFinalClass(DebugLog::class.java)
}
@Test(expected = IllegalStateException::class)
fun `log without initialization crashes`() {
DebugLog.log("test")
}
@Test(expected = IllegalStateException::class)
fun `log with tag without initialization crashes`() {
DebugLog.log("test", "test")
}
@Test
fun `log message works`() {
val logger = mock<Logger>()
DebugLog.initialize(logger)
DebugLog.log("test message")
verify(logger).log("Stag: test message")
verifyNoMoreInteractions(logger)
}
@Test
fun `log with tag and message works`() {
val logger = mock<Logger>()
DebugLog.initialize(logger)
DebugLog.log("test tag", "test message")
verify(logger).log("Stag:test tag: test message")
verifyNoMoreInteractions(logger)
}
}
| stag-library-compiler/src/test/java/com/vimeo/stag/processor/utils/DebugLogTest.kt | 4109269528 |
/**
* 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.plugins.plsqlopen.api.statements
import com.felipebz.flr.tests.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.RuleTest
class CommitStatementTest : RuleTest() {
@BeforeEach
fun init() {
setRootRule(PlSqlGrammar.COMMIT_STATEMENT)
}
@Test
fun matchesSimpleCommit() {
assertThat(p).matches("commit;")
}
@Test
fun matchesCommitWork() {
assertThat(p).matches("commit work;")
}
@Test
fun matchesCommitForce() {
assertThat(p).matches("commit force 'test';")
}
@Test
fun matchesCommitForceWithScn() {
assertThat(p).matches("commit force 'test',1;")
}
@Test
fun matchesCommitWithComment() {
assertThat(p).matches("commit comment 'test';")
}
@Test
fun matchesCommitWrite() {
assertThat(p).matches("commit write;")
}
@Test
fun matchesCommitWriteImmediate() {
assertThat(p).matches("commit write immediate;")
}
@Test
fun matchesCommitWriteBatch() {
assertThat(p).matches("commit write batch;")
}
@Test
fun matchesCommitWriteWait() {
assertThat(p).matches("commit write wait;")
}
@Test
fun matchesCommitWriteNoWait() {
assertThat(p).matches("commit write nowait;")
}
@Test
fun matchesLongCommitStatement() {
assertThat(p).matches("commit work comment 'teste' write immediate wait;")
}
@Test
fun matchesLabeledCommit() {
assertThat(p).matches("<<foo>> commit;")
}
}
| zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/statements/CommitStatementTest.kt | 3943755160 |
/*
* Copyright 2015-2019 Julien Guerinet
*
* 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.guerinet.morf.base
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import androidx.annotation.StringRes
import com.google.android.material.textfield.TextInputLayout
import com.guerinet.morf.Morf
import com.guerinet.morf.util.Layout
/**
* Based form item for a [TextInputLayout]
* @author Julien Guerinet
* @since 3.0.0
*
* @param morf [Morf] instance
* @param view Item [View]
*/
open class BaseTextInputItem<T : BaseTextInputItem<T, V>, V : EditText>(morf: Morf, view: V)
: BaseEditTextItem<T, V>(morf, view, false) {
private val inputLayout = TextInputLayout(morf.context)
init {
inputLayout.layoutParams = LinearLayout.LayoutParams(Layout.MATCH_PARENT,
Layout.WRAP_CONTENT)
// Add the view to the input layout
inputLayout.addView(view)
}
var isPasswordVisibilityToggleEnabled: Boolean
get() = error("Setter only")
set(value) {
inputLayout.isPasswordVisibilityToggleEnabled = value
}
/**
* @return Item with the password visibility toggle shown or not depending on [isEnabled]
*/
fun showPasswordVisibilityToggle(isEnabled: Boolean): T = setAndReturn {
this.isPasswordVisibilityToggleEnabled = isEnabled
}
override var hint: String?
get() = super.hint
set(value) {
inputLayout.hint = value
}
override fun hint(hint: String?): T = setAndReturn { this.hint = hint }
override var hintId: Int
get() = super.hintId
set(@StringRes value) {
hint(view.resources.getString(value))
}
override fun hint(stringId: Int): T = setAndReturn { this.hintId = stringId }
override var backgroundId: Int
get() = super.backgroundId
set(value) = inputLayout.setBackgroundResource(value)
override fun backgroundId(backgroundId: Int): T =
setAndReturn { this.backgroundId = backgroundId }
override fun build(): T {
// Add the input layout to the container, not the view
if (inputLayout.parent == null) {
morf.addView(inputLayout)
}
return super.build()
}
}
| library/src/main/java/base/BaseTextInputItem.kt | 3929819178 |
package com.intfocus.template.subject.templateone.curvechart
import com.intfocus.template.base.BasePresenter
import com.intfocus.template.base.BaseView
import com.intfocus.template.subject.one.entity.Chart
/**
* ****************************************************
* @author jameswong
* created on: 17/10/24 下午3:03
* e-mail: [email protected]
* name:
* desc:
* ****************************************************
*/
interface ChartContract {
interface View : BaseView<Presenter> {
// 展示数据
fun showData(entity: Chart)
}
interface Presenter : BasePresenter {
// 加载数据
fun loadData(rootId: Int, index: Int)
}
}
| app/src/main/java/com/intfocus/template/subject/one/module/chart/ChartContract.kt | 2034511432 |
/**
* 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.squid
import org.sonar.api.batch.fs.InputFile
import org.sonar.plugins.plsqlopen.api.PlSqlFile
import java.io.IOException
class SonarQubePlSqlFile(val inputFile: InputFile) : PlSqlFile {
override fun fileName(): String = inputFile.filename()
override fun contents(): String =
try {
inputFile.contents()
} catch (e: IOException) {
throw IllegalStateException("Could not read contents of input file $inputFile", e)
}
override fun type(): PlSqlFile.Type =
when (inputFile.type()) {
InputFile.Type.MAIN -> PlSqlFile.Type.MAIN
InputFile.Type.TEST -> PlSqlFile.Type.TEST
else -> PlSqlFile.Type.MAIN
}
override fun toString(): String = inputFile.toString()
}
| sonar-zpa-plugin/src/main/kotlin/org/sonar/plsqlopen/squid/SonarQubePlSqlFile.kt | 3139507131 |
package de.westnordost.streetcomplete.data.osm.elementgeometry
/** Knows which vertices connect which ways. T is the identifier of a vertex */
class NodeWayMap<T>(ways: List<List<T>>) {
private val wayEndpoints = LinkedHashMap<T, MutableList<List<T>>>()
init {
for (way in ways) {
val firstNode = way.first()
val lastNode = way.last()
wayEndpoints.getOrPut(firstNode, { ArrayList() }).add(way)
wayEndpoints.getOrPut(lastNode, { ArrayList() }).add(way)
}
}
fun hasNextNode(): Boolean = wayEndpoints.isNotEmpty()
fun getNextNode(): T = wayEndpoints.keys.iterator().next()
fun getWaysAtNode(node: T): List<List<T>>? = wayEndpoints[node]
fun removeWay(way: List<T>) {
val it = wayEndpoints.values.iterator()
while (it.hasNext()) {
val waysPerNode = it.next()
val waysIt = waysPerNode.iterator()
while (waysIt.hasNext()) {
if (waysIt.next() === way) {
waysIt.remove()
}
}
if (waysPerNode.isEmpty()) {
it.remove()
}
}
}
}
| app/src/main/java/de/westnordost/streetcomplete/data/osm/elementgeometry/NodeWayMap.kt | 3605078399 |
package com.habitrpg.shared.habitica.extensions
import kotlin.math.pow
import kotlin.math.roundToInt
fun Double.round(decimals: Int): Double {
return (this * 10.0.pow(decimals.toDouble())).roundToInt() / 10.0.pow(decimals.toDouble())
}
| shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/extensions/Double-Extensions.kt | 1994017642 |
package com.habitrpg.android.habitica.helpers
import android.util.Log
import com.habitrpg.android.habitica.BuildConfig
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import io.reactivex.rxjava3.functions.Consumer
import kotlinx.coroutines.CoroutineExceptionHandler
import okhttp3.internal.http2.ConnectionShutdownException
import retrofit2.HttpException
import java.io.EOFException
import java.io.IOException
class ExceptionHandler {
private var analyticsManager: AnalyticsManager? = null
companion object {
private var instance = ExceptionHandler()
fun init(analyticsManager: AnalyticsManager) {
instance.analyticsManager = analyticsManager
}
fun coroutine(handler: ((Throwable) -> Unit)? = null): CoroutineExceptionHandler {
return CoroutineExceptionHandler { _, throwable ->
reportError(throwable)
handler?.invoke(throwable)
}
}
fun rx(): Consumer<Throwable> {
// Can't be turned into a lambda, because it then doesn't work for some reason.
return Consumer { reportError(it) }
}
fun reportError(throwable: Throwable) {
if (BuildConfig.DEBUG) {
try {
Log.e("ObservableError", Log.getStackTraceString(throwable))
} catch (ignored: Exception) {
}
} else {
if (!IOException::class.java.isAssignableFrom(throwable.javaClass) &&
!HttpException::class.java.isAssignableFrom(throwable.javaClass) &&
!retrofit2.HttpException::class.java.isAssignableFrom(throwable.javaClass) &&
!EOFException::class.java.isAssignableFrom(throwable.javaClass) &&
!retrofit2.adapter.rxjava3.HttpException::class.java.isAssignableFrom(throwable.javaClass) &&
throwable !is ConnectionShutdownException
) {
instance.analyticsManager?.logException(throwable)
}
}
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/helpers/ExceptionHandler.kt | 3588755617 |
package com.habitrpg.wearos.habitica.ui.viewmodels
import androidx.lifecycle.SavedStateHandle
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.MessageEvent
import com.habitrpg.wearos.habitica.data.repositories.TaskRepository
import com.habitrpg.wearos.habitica.data.repositories.UserRepository
import com.habitrpg.wearos.habitica.managers.AppStateManager
import com.habitrpg.wearos.habitica.util.ExceptionHandlerBuilder
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class ContinuePhoneViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
userRepository: UserRepository,
taskRepository: TaskRepository,
exceptionBuilder: ExceptionHandlerBuilder,
appStateManager: AppStateManager
) : BaseViewModel(userRepository, taskRepository, exceptionBuilder, appStateManager), MessageClient.OnMessageReceivedListener {
val keepActive = savedStateHandle.get<Boolean>("keep_active") ?: false
var onActionCompleted: (() -> Unit)? = null
override fun onMessageReceived(event: MessageEvent) {
when (event.path) {
"/action_completed" -> onActionCompleted?.invoke()
}
}
}
| wearos/src/main/java/com/habitrpg/wearos/habitica/ui/viewmodels/ContinuePhoneViewModel.kt | 2761762373 |
package com.habitrpg.android.habitica.data.implementation
import com.habitrpg.android.habitica.data.ApiClient
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.data.local.TaskLocalRepository
import com.habitrpg.android.habitica.models.BaseObject
import com.habitrpg.shared.habitica.models.responses.TaskDirectionData
import com.habitrpg.shared.habitica.models.responses.TaskScoringResult
import com.habitrpg.android.habitica.models.tasks.Task
import com.habitrpg.android.habitica.models.tasks.TaskList
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.habitrpg.shared.habitica.models.tasks.TasksOrder
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.android.habitica.models.user.User
import io.kotest.common.ExperimentalKotest
import io.kotest.core.spec.style.WordSpec
import io.kotest.framework.concurrency.eventually
import io.kotest.matchers.shouldBe
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.spyk
import io.mockk.verify
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.subscribers.TestSubscriber
import io.realm.Realm
import java.util.UUID
@OptIn(ExperimentalKotest::class)
class TaskRepositoryImplTest : WordSpec({
lateinit var repository: TaskRepository
val localRepository = mockk<TaskLocalRepository>()
val apiClient = mockk<ApiClient>()
beforeEach {
val slot = slot<((Realm) -> Unit)>()
every { localRepository.executeTransaction(transaction = capture(slot)) } answers {
slot.captured(mockk(relaxed = true))
}
repository = TaskRepositoryImpl(
localRepository,
apiClient,
"",
mockk(relaxed = true),
mockk(relaxed = true)
)
val liveObjectSlot = slot<BaseObject>()
every { localRepository.getLiveObject(capture(liveObjectSlot)) } answers {
liveObjectSlot.captured
}
}
"retrieveTasks" should {
"save tasks locally" {
val list = TaskList()
every { apiClient.tasks } returns Flowable.just(list)
every { localRepository.saveTasks("", any(), any()) } returns Unit
val order = TasksOrder()
val subscriber = TestSubscriber<TaskList>()
repository.retrieveTasks("", order).subscribe(subscriber)
subscriber.assertComplete()
verify { localRepository.saveTasks("", order, list) }
}
}
"taskChecked" should {
val task = Task()
task.id = UUID.randomUUID().toString()
lateinit var user: User
beforeEach {
user = spyk(User())
user.stats = Stats()
}
"debounce" {
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(
TaskDirectionData()
)
repository.taskChecked(user, task, true, false, null).subscribe()
repository.taskChecked(user, task, true, false, null).subscribe()
verify(exactly = 1) { apiClient.postTaskDirection(any(), any()) }
}
"get user if not passed" {
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(
TaskDirectionData()
)
every { localRepository.getUser("") } returns Flowable.just(user)
repository.taskChecked(null, task, true, false, null)
eventually(5000) {
localRepository.getUser("")
}
}
"does not update user for team tasks" {
val data = TaskDirectionData()
data.lvl = 0
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
val subscriber = TestSubscriber<TaskScoringResult>()
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
verify(exactly = 0) { user.stats }
subscriber.values().first().level shouldBe null
}
"builds task result correctly" {
val data = TaskDirectionData()
data.lvl = 10
data.hp = 20.0
data.mp = 30.0
data.gp = 40.0
user.stats?.lvl = 10
user.stats?.hp = 8.0
user.stats?.mp = 4.0
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
val subscriber = TestSubscriber<TaskScoringResult>()
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
subscriber.values().first().level shouldBe 10
subscriber.values().first().healthDelta shouldBe 12.0
subscriber.values().first().manaDelta shouldBe 26.0
subscriber.values().first().hasLeveledUp shouldBe false
}
"set hasLeveledUp correctly" {
val subscriber = TestSubscriber<TaskScoringResult>()
val data = TaskDirectionData()
data.lvl = 11
user.stats?.lvl = 10
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
subscriber.values().first().level shouldBe 11
subscriber.values().first().hasLeveledUp shouldBe true
}
"handle stats not being there" {
val subscriber = TestSubscriber<TaskScoringResult>()
val data = TaskDirectionData()
data.lvl = 1
user.stats = null
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
}
"update daily streak" {
val subscriber = TestSubscriber<TaskScoringResult>()
val data = TaskDirectionData()
data.delta = 1.0f
data.lvl = 1
task.type = TaskType.DAILY
task.value = 0.0
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
task.streak shouldBe 1
task.completed shouldBe true
}
"update habit counter" {
val subscriber = TestSubscriber<TaskScoringResult>()
val data = TaskDirectionData()
data.delta = 1.0f
data.lvl = 1
task.type = TaskType.HABIT
task.value = 0.0
every { apiClient.postTaskDirection(any(), "up") } returns Flowable.just(data)
repository.taskChecked(user, task, true, false, null).subscribe(subscriber)
subscriber.assertComplete()
task.counterUp shouldBe 1
data.delta = -10.0f
every { apiClient.postTaskDirection(any(), "down") } returns Flowable.just(data)
val downSubscriber = TestSubscriber<TaskScoringResult>()
repository.taskChecked(user, task, false, true, null).subscribe(downSubscriber)
downSubscriber.assertComplete()
task.counterUp shouldBe 1
task.counterDown shouldBe 1
}
}
afterEach { clearAllMocks() }
})
| Habitica/src/test/java/com/habitrpg/android/habitica/data/implementation/TaskRepositoryImplTest.kt | 78102757 |
package com.schneppd.myopenglapp
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import android.view.Menu
import android.view.MenuItem
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.content_main.*
import org.jetbrains.anko.imageBitmap
import java.io.File
import android.os.Environment.DIRECTORY_PICTURES
import android.support.v4.content.FileProvider
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
companion object Static {
val REQUEST_IMAGE_CAPTURE = 1
val REQUEST_TAKE_PHOTO = 1
}
var currentPhotoPath = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
/*
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view -> onClickTestButton(view) }
*/
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when(item.itemId){
R.id.action_photo -> onTakePhoto()
R.id.action_import_model -> onChangeModel()
}
return super.onOptionsItemSelected(item)
}
fun onChangeModel() {
//Snackbar.make(v, "Change model", Snackbar.LENGTH_LONG).setAction("Action", null).show()
if(svUserModel.visibility == View.VISIBLE)
svUserModel.visibility = View.INVISIBLE
else
svUserModel.visibility = View.VISIBLE
}
fun onTakePhoto() {
//Snackbar.make(v, "Taking photo for background", Snackbar.LENGTH_LONG).setAction("Action", null).show()
val takePictureIntent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val serviceProvider = takePictureIntent.resolveActivity(packageManager)
serviceProvider?.let {
var photoFile:File? = createImageSaveFile()
photoFile?: return
val photoURI = FileProvider.getUriForFile(this, "com.schneppd.myopenglapp.fileprovider", photoFile)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
//startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO)
}?: Snackbar.make(ivUserPicture, "No photo app installed", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
/*
val extras = data!!.extras
val rawImageBitmap = extras.get("data") as Bitmap
val imageBitmap = Bitmap.createScaledBitmap(rawImageBitmap, ivUserPicture.width, ivUserPicture.height, true)
ivUserPicture.imageBitmap = imageBitmap
*/
val fileUri = "file://" + currentPhotoPath
Picasso.with(this).load(fileUri).resize(ivUserPicture.width, ivUserPicture.height).centerCrop().into(ivUserPicture)
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun createImageSaveFile() : File{
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
currentPhotoPath = image.absolutePath
return image
}
}
| MyApplication/app/src/main/java/com/schneppd/myopenglapp/MainActivity.kt | 3075197409 |
package org.stepic.droid.services
import io.reactivex.Scheduler
import org.stepic.droid.di.AppSingleton
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.model.ViewedNotification
import org.stepic.droid.storage.operations.DatabaseFacade
import org.stepik.android.domain.notification.repository.NotificationRepository
import javax.inject.Inject
@AppSingleton
class NotificationsViewPusher
@Inject
constructor(
private val notificationRepository: NotificationRepository,
private val databaseFacade: DatabaseFacade,
@BackgroundScheduler
private val scheduler: Scheduler
) {
fun pushToViewedNotificationsQueue(notificationId: Long) {
if (notificationId == 0L) return
notificationRepository.putNotifications(notificationId, isRead = true)
.subscribeOn(scheduler)
.subscribe({}) {
databaseFacade.addToViewedNotificationsQueue(ViewedNotification(notificationId))
}
}
} | app/src/main/java/org/stepic/droid/services/NotificationsViewPusher.kt | 2635147277 |
package org.stepik.android.view.profile.ui.activity
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutManager
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatDelegate
import androidx.fragment.app.Fragment
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.SingleFragmentActivity
import org.stepic.droid.ui.activities.contracts.CloseButtonInToolbar
import org.stepic.droid.util.AppConstants
import org.stepik.android.view.profile.ui.fragment.ProfileFragment
class ProfileActivity : SingleFragmentActivity(), CloseButtonInToolbar {
companion object {
private const val EXTRA_USER_ID = "user_id"
init {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
}
fun createIntent(context: Context, userId: Long): Intent =
Intent(context, ProfileActivity::class.java)
.putExtra(EXTRA_USER_ID, userId)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null && intent.action == AppConstants.OPEN_SHORTCUT_PROFILE) {
analytic.reportEvent(Analytic.Shortcut.OPEN_PROFILE)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
getSystemService(ShortcutManager::class.java)?.reportShortcutUsed(AppConstants.PROFILE_SHORTCUT_ID)
}
}
}
override fun createFragment(): Fragment {
val userId = intent
.getLongExtra(EXTRA_USER_ID, 0)
.takeIf { it > 0 }
?: getUserId(intent.data)
return ProfileFragment.newInstance(userId)
}
private fun getUserId(dataUri: Uri?): Long {
if (dataUri == null) return 0
analytic.reportEvent(Analytic.Profile.OPEN_BY_LINK)
return try {
dataUri.pathSegments[1].toLong()
} catch (exception: NumberFormatException) {
-1
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean =
when (item?.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else ->
super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
override fun finish() {
super.finish()
overridePendingTransition(R.anim.no_transition, R.anim.push_down)
}
}
| app/src/main/java/org/stepik/android/view/profile/ui/activity/ProfileActivity.kt | 1110561512 |
/*
* Copyright 2010-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.kotlin.backend.konan.util
import kotlin.system.measureTimeMillis
fun printMillisec(message: String, body: () -> Unit) {
val msec = measureTimeMillis{
body()
}
println("$message: $msec msec")
}
fun profile(message: String, body: () -> Unit) = profileIf(
System.getProperty("konan.profile")?.equals("true") ?: false,
message, body)
fun profileIf(condition: Boolean, message: String, body: () -> Unit) =
if (condition) printMillisec(message, body) else body()
fun nTabs(amount: Int): String {
return String.format("%1$-${(amount+1)*4}s", "")
}
fun String.suffixIfNot(suffix: String) =
if (this.endsWith(suffix)) this else "$this$suffix"
fun String.removeSuffixIfPresent(suffix: String) =
if (this.endsWith(suffix)) this.dropLast(suffix.length) else this
| backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/util/util.kt | 3741741331 |
package org.example.ankodemo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import android.view.Gravity
import android.widget.Button
import android.widget.EditText
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MainActivityUi().setContentView(this)
}
fun tryLogin(ui: AnkoContext<MainActivity>, name: CharSequence?, password: CharSequence?) {
ui.doAsync {
Thread.sleep(500)
activityUiThreadWithContext {
if (checkCredentials(name.toString(), password.toString())) {
toast("Logged in! :)")
startActivity<CountriesActivity>()
} else {
toast("Wrong password :( Enter user:password")
}
}
}
}
private fun checkCredentials(name: String, password: String) = name == "user" && password == "password"
}
class MainActivityUi : AnkoComponent<MainActivity> {
private val customStyle = { v: Any ->
when (v) {
is Button -> v.textSize = 26f
is EditText -> v.textSize = 24f
}
}
override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
verticalLayout {
padding = dip(32)
imageView(android.R.drawable.ic_menu_manage).lparams {
margin = dip(16)
gravity = Gravity.CENTER
}
val name = editText {
hintResource = R.string.name
}
val password = editText {
hintResource = R.string.password
inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
}
button("Log in") {
onClick {
ui.owner.tryLogin(ui, name.text, password.text)
}
}
myRichView()
}.applyRecursively(customStyle)
}
} | anko-example-master/app/src/main/java/org/example/ankodemo/MainActivity.kt | 984563995 |
package com.agrawalsuneet.dotsloader.loaders
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.*
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.agrawalsuneet.dotsloader.R
import com.agrawalsuneet.dotsloader.basicviews.CircleView
import com.agrawalsuneet.dotsloader.contracts.LoaderContract
/**
* Created by agrawalsuneet on 4/13/19.
*/
class BounceLoader : LinearLayout, LoaderContract {
var ballRadius: Int = 60
var ballColor: Int = resources.getColor(android.R.color.holo_red_dark)
var showShadow: Boolean = true
var shadowColor: Int = resources.getColor(android.R.color.black)
var animDuration: Int = 1500
set(value) {
field = if (value <= 0) 1000 else value
}
private var relativeLayout: RelativeLayout? = null
private var ballCircleView: CircleView? = null
private var ballShadowView: CircleView? = null
private var calWidth: Int = 0
private var calHeight: Int = 0
private val STATE_GOINGDOWN: Int = 0
private val STATE_SQUEEZING: Int = 1
private val STATE_RESIZING: Int = 2
private val STATE_COMINGUP: Int = 3
private var state: Int = STATE_GOINGDOWN
constructor(context: Context?) : super(context) {
initView()
}
constructor(context: Context?, attrs: AttributeSet) : super(context, attrs) {
initAttributes(attrs)
initView()
}
constructor(context: Context?, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initAttributes(attrs)
initView()
}
constructor(context: Context?, ballRadius: Int, ballColor: Int, showShadow: Boolean, shadowColor: Int = 0) : super(context) {
this.ballRadius = ballRadius
this.ballColor = ballColor
this.shadowColor = shadowColor
initView()
}
override fun initAttributes(attrs: AttributeSet) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BounceLoader, 0, 0)
this.ballRadius = typedArray.getDimensionPixelSize(R.styleable.BounceLoader_bounce_ballRadius, 60)
this.ballColor = typedArray.getColor(R.styleable.BounceLoader_bounce_ballColor,
resources.getColor(android.R.color.holo_red_dark))
this.shadowColor = typedArray.getColor(R.styleable.BounceLoader_bounce_shadowColor,
resources.getColor(android.R.color.black))
this.showShadow = typedArray.getBoolean(R.styleable.BounceLoader_bounce_showShadow, true)
this.animDuration = typedArray.getInt(R.styleable.BounceLoader_bounce_animDuration, 1500)
typedArray.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (calWidth == 0 || calHeight == 0) {
calWidth = 5 * ballRadius
calHeight = 8 * ballRadius
}
setMeasuredDimension(calWidth, calHeight)
}
private fun initView() {
removeAllViews()
removeAllViewsInLayout()
if (calWidth == 0 || calHeight == 0) {
calWidth = 5 * ballRadius
calHeight = 8 * ballRadius
}
relativeLayout = RelativeLayout(context)
if (showShadow) {
ballShadowView = CircleView(context = context,
circleRadius = ballRadius,
circleColor = shadowColor,
isAntiAlias = false)
val shadowParam = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
shadowParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
shadowParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
relativeLayout?.addView(ballShadowView, shadowParam)
}
ballCircleView = CircleView(context = context,
circleRadius = ballRadius,
circleColor = ballColor)
val ballParam = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
ballParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
ballParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
relativeLayout?.addView(ballCircleView, ballParam)
val relParam = RelativeLayout.LayoutParams(calWidth, calHeight)
this.addView(relativeLayout, relParam)
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
startLoading()
[email protected](this)
}
})
}
private fun startLoading() {
val ballAnim = getBallAnimation()
ballAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationEnd(anim: Animation?) {
state = (state + 1) % 4
startLoading()
}
override fun onAnimationRepeat(p0: Animation?) {
}
override fun onAnimationStart(p0: Animation?) {
}
})
if (showShadow) {
if (state == STATE_SQUEEZING || state == STATE_RESIZING) {
ballShadowView?.clearAnimation()
ballShadowView?.visibility = View.GONE
} else {
ballShadowView?.visibility = View.VISIBLE
val shadowAnim = getShadowAnimation()
ballShadowView?.startAnimation(shadowAnim)
}
}
ballCircleView?.startAnimation(ballAnim)
}
private fun getBallAnimation(): Animation {
return when (state) {
STATE_GOINGDOWN -> {
TranslateAnimation(0.0f, 0.0f,
(-6 * ballRadius).toFloat(), 0.0f)
.apply {
duration = animDuration.toLong()
interpolator = AccelerateInterpolator()
}
}
STATE_SQUEEZING -> {
ScaleAnimation(1.0f, 1.0f, 1.0f, 0.85f
, ballRadius.toFloat(), (2 * ballRadius).toFloat())
.apply {
duration = (animDuration / 20).toLong()
interpolator = AccelerateInterpolator()
}
}
STATE_RESIZING -> {
ScaleAnimation(1.0f, 1.0f, 0.85f, 1.0f
, ballRadius.toFloat(), (2 * ballRadius).toFloat())
.apply {
duration = (animDuration / 20).toLong()
interpolator = DecelerateInterpolator()
}
}
else -> {
TranslateAnimation(0.0f, 0.0f,
0.0f, (-6 * ballRadius).toFloat())
.apply {
duration = animDuration.toLong()
interpolator = DecelerateInterpolator()
}
}
}.apply {
fillAfter = true
repeatCount = 0
}
}
private fun getShadowAnimation(): AnimationSet {
val transAnim: Animation
val scaleAnim: Animation
val alphaAnim: AlphaAnimation
val set = AnimationSet(true)
when (state) {
STATE_COMINGUP -> {
transAnim = TranslateAnimation(0.0f, (-4 * ballRadius).toFloat(),
0.0f, (-3 * ballRadius).toFloat())
scaleAnim = ScaleAnimation(0.9f, 0.5f, 0.9f, 0.5f,
ballRadius.toFloat(), ballRadius.toFloat())
alphaAnim = AlphaAnimation(0.6f, 0.2f)
set.interpolator = DecelerateInterpolator()
}
else -> {
transAnim = TranslateAnimation((-4 * ballRadius).toFloat(), 0.0f,
(-3 * ballRadius).toFloat(), 0.0f)
scaleAnim = ScaleAnimation(0.5f, 0.9f, 0.5f, 0.9f,
ballRadius.toFloat(), ballRadius.toFloat())
alphaAnim = AlphaAnimation(0.2f, 0.6f)
set.interpolator = AccelerateInterpolator()
}
}
set.addAnimation(transAnim)
set.addAnimation(scaleAnim)
set.addAnimation(alphaAnim)
set.apply {
duration = animDuration.toLong()
fillAfter = true
repeatCount = 0
}
return set
}
} | dotsloader/src/main/java/com/agrawalsuneet/dotsloader/loaders/BounceLoader.kt | 3471331463 |
package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.*
import org.bukkit.Location
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.*
import org.bukkit.event.entity.ProjectileHitEvent
import org.bukkit.inventory.ItemStack
import kotlin.random.Random
/**
* Breaks and drops all shearable blocks.
* Shears sheep in range on impact.
* Shears mooshrooms in range on impact.
* Shears snow golems in range on impact.
*
* @author SugarCaney
*/
open class ShearBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.SHEAR,
handleEveryNTicks = 1,
canShootInProtectedRegions = false,
removeArrow = true,
description = "Breaks all shearable blocks."
) {
/**
* The range around the location of impact where special blocks/entities (sheep, pumpkins, ...), in blocks.
*/
val impactRange = config.getDouble("$node.impact-range")
/**
* How much the range increases per power level on the bow, in blocks.
*/
val rangeIncrease = config.getDouble("$node.range-increase")
init {
require(impactRange >= 0) { "$node.impact-range must not be negative, got <$impactRange>" }
}
override fun land(arrow: Arrow, player: Player, event: ProjectileHitEvent) {
// When an entity is hit, don't bounce.
if (event.hitEntity != null) {
arrow.location.impactEffects(player)
arrow.remove()
return
}
val hitBlockType = event.hitBlock?.type ?: return
if (hitBlockType != Material.AIR && hitBlockType.isShearable.not()) {
arrow.location.impactEffects(player)
return
}
event.hitBlock?.shearBlocks()
registerArrow(arrow.respawnArrow())
}
override fun effect() {
arrows.forEach {
if (it.location.isInProtectedRegion(it.shooter as? LivingEntity, showError = false).not()) {
it.location.block.shearBlocks()
}
}
}
/**
* Shears all blocks around this block.
*/
@Suppress("DEPRECATION")
private fun Block.shearBlocks() {
forXYZ(-1..1, -1..1, -1..1) { dx, dy, dz ->
val block = getRelative(dx, dy, dz)
val originalType = block.type
if (originalType.isShearable) {
val itemDrop = ItemStack(originalType, 1, block.itemDataValue().toShort())
block.centreLocation.dropItem(itemDrop)
block.type = Material.AIR
}
}
}
/**
* Get the data value for the item that is dropped by this block.
*/
@Suppress("DEPRECATION")
private fun Block.itemDataValue(): Byte = when (type) {
// TODO: Shear Bow Leave block data
// Material.LEAVES -> (state.data as Leaves).species.data
// Material.LEAVES_2 -> ((state.data as Leaves).species.data - 4).toByte()
// Material.LONG_GRASS -> (state.data as LongGrass).species.data
// Material.DOUBLE_PLANT -> state.data.data
else -> 0
}
/**
* Processes all effects that happen when the arrow lands.
*/
private fun Location.impactEffects(player: Player) {
val bowItem = player.bowItem() ?: return
val lootingLevel = bowItem.getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS)
val powerLevel = bowItem.getEnchantmentLevel(Enchantment.ARROW_DAMAGE)
val range = impactRange + powerLevel * rangeIncrease
shearSheep(range, lootingLevel)
shearMooshrooms(range, lootingLevel)
shearSnowGolems(range)
}
/**
* Shears all sheep around this location.
*
* @param range
* How far from this location to check for sheep.
* @param lootingLevel
* The level of the looting enchantment (0 if not applicable).
*/
@Suppress("DEPRECATION")
private fun Location.shearSheep(range: Double, lootingLevel: Int = 0) = nearbyLivingEntities(range).asSequence()
.mapNotNull { it as? Sheep }
.filter { it.isSheared.not() }
.forEach {
// val woolBlocks = Random.nextInt(1, 4) + lootingLevel
// val itemDrops = ItemStack(Material.WOOL, woolBlocks, it.color.woolData.toShort())
// it.world.dropItem(it.location, itemDrops)
// it.isSheared = true
// TODO: Shear Bow Sheep wool drop
}
/**
* Shears all mooshrooms around this location.
*
* @param range
* How far from this location to check for mooshrooms.
* @param lootingLevel
* The level of the looting enchantment (0 if not applicable).
*/
private fun Location.shearMooshrooms(range: Double, lootingLevel: Int = 0) = nearbyLivingEntities(range).asSequence()
.mapNotNull { it as? MushroomCow }
.forEach {
val mushrooms = 5 + lootingLevel
val mushroomType = if (Random.nextBoolean()) Material.RED_MUSHROOM else Material.BROWN_MUSHROOM
val itemDrops = ItemStack(mushroomType, mushrooms)
it.world.dropItem(it.location, itemDrops)
it.location.spawn(Cow::class)
it.remove()
}
/**
* Shears all mooshrooms around this location.
*
* @param range
* How far from this location to check for snow golems.
*/
private fun Location.shearSnowGolems(range: Double) = nearbyLivingEntities(range).asSequence()
.mapNotNull { it as? Snowman }
.filter { it.isDerp }
.forEach {
val itemDrops = ItemStack(Material.PUMPKIN, 1)
it.world.dropItem(it.location, itemDrops)
it.isDerp = false
}
/**
* Shears all pumpkins around this location.
*
* @param range
* How far from this location to check for pumpkins.
* @param lootingLevel
* The level of the looting enchantment (0 if not applicable).
*/
@Suppress("UNUSED_PARAMETER")
private fun Location.carvePumpkins(range: Double, lootingLevel: Int = 0) {
// TODO: carving pumpkins has been introduced in 1.13
}
companion object {
/**
* The shears item used to break blocks.
*/
private val SHEARS = ItemStack(Material.SHEARS, 1)
}
} | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/ShearBow.kt | 3484403119 |
package br.com.battista.bgscore.robot
import android.content.Context
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.*
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.*
import br.com.battista.bgscore.R
import br.com.battista.bgscore.helper.NestedScrollViewScrollToAction
class NewGameRobot(private val context: Context) : BaseRobot() {
private fun checkStateCheckedView(checked: Boolean, idRes: Int) {
if (checked) {
onView(withId(idRes))
.check(matches(isChecked()))
} else {
onView(withId(idRes))
.check(matches(isNotChecked()))
}
}
fun fillTextName(name: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_name))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_name))
.perform(replaceText(name), closeSoftKeyboard())
return this
}
fun checkMyGame(checked: Boolean): NewGameRobot {
onView(withId(R.id.card_view_new_game_my_game))
.perform(NestedScrollViewScrollToAction.scrollTo())
checkStateCheckedView(checked, R.id.card_view_new_game_my_game)
return this
}
fun checkFavorite(checked: Boolean): NewGameRobot {
onView(withId(R.id.card_view_new_game_favorite))
.perform(NestedScrollViewScrollToAction.scrollTo())
checkStateCheckedView(checked, R.id.card_view_new_game_favorite)
return this
}
fun checkWantGame(checked: Boolean): NewGameRobot {
onView(withId(R.id.card_view_new_game_want_game))
.perform(NestedScrollViewScrollToAction.scrollTo())
checkStateCheckedView(checked, R.id.card_view_new_game_want_game)
return this
}
fun fillTextYearPublished(yearPublished: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_year_published))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_year_published))
.perform(replaceText(yearPublished), closeSoftKeyboard())
return this
}
fun fillTextAge(age: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_age))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_age))
.perform(replaceText(age), closeSoftKeyboard())
return this
}
fun fillTextMinPlayers(minPlayers: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_min_players))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_min_players))
.perform(replaceText(minPlayers), closeSoftKeyboard())
return this
}
fun fillTextMaxPlayers(maxPlayers: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_max_players))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_max_players))
.perform(replaceText(maxPlayers), closeSoftKeyboard())
return this
}
fun fillTextMinPlayTime(minPlayTime: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_min_play_time))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_min_play_time))
.perform(replaceText(minPlayTime), closeSoftKeyboard())
return this
}
fun fillTextMaxPlayTime(maxPlayTime: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_max_play_time))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_max_play_time))
.perform(replaceText(maxPlayTime), closeSoftKeyboard())
return this
}
fun fillTextGameBadge(gameBadge: String): NewGameRobot {
onView(withId(R.id.card_view_new_game_badge_game))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.card_view_new_game_badge_game))
.perform(replaceText(gameBadge), closeSoftKeyboard())
return this
}
fun saveGame(): GameRobot {
onView(withId(R.id.fab_next_done_game))
.perform(NestedScrollViewScrollToAction.scrollTo())
onView(withId(R.id.fab_next_done_game))
.perform(click())
return GameRobot(context)
}
}
| app/src/androidTest/java/br/com/battista/bgscore/robot/NewGameRobot.kt | 2469636952 |
package com.marknkamau.justjava.ui.productDetails
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.marknkamau.justjava.R
import com.marknkamau.justjava.data.models.AppProductChoiceOption
import com.marknkamau.justjava.databinding.ItemProductChoiceOptionBinding
import com.marknkamau.justjava.utils.CurrencyFormatter
class OptionsAdapter(private val context: Context) : RecyclerView.Adapter<OptionsAdapter.ViewHolder>() {
private val items by lazy { mutableListOf<AppProductChoiceOption>() }
var onSelected: ((option: AppProductChoiceOption, checked: Boolean) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ItemProductChoiceOptionBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position], context)
}
fun setItems(newItems: List<AppProductChoiceOption>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
inner class ViewHolder(
private val binding: ItemProductChoiceOptionBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(option: AppProductChoiceOption, context: Context) {
val formattedPrice = CurrencyFormatter.format(option.price)
binding.tvOptionPrice.text = context.getString(R.string.price_listing_w_add, formattedPrice)
binding.cbOptionTitle.text = option.name
binding.cbOptionTitle.isChecked = option.isChecked
binding.cbOptionTitle.setOnClickListener {
onSelected?.invoke(option, binding.cbOptionTitle.isChecked)
}
}
}
}
| app/src/main/java/com/marknkamau/justjava/ui/productDetails/OptionsAdapter.kt | 3226140760 |
package com.mindera.skeletoid.utils.tuples
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class QuadrupleTest {
@Test
fun testQuadruple() {
val quadruple = Quadruple(1, "Mindera", 123456L, 3.14F)
assertEquals(1, quadruple.first)
assertEquals("Mindera", quadruple.second)
assertEquals(123456L, quadruple.third)
assertEquals(3.14F, quadruple.fourth)
}
@Test
fun testNullableQuadruple() {
val quadruple = Quadruple<Int?, String?, Long?, Float?>(null, null, null, null)
assertEquals(null, quadruple.first)
assertEquals(null, quadruple.second)
assertEquals(null, quadruple.third)
assertEquals(null, quadruple.fourth)
}
@Test
fun testQuintuple() {
val quintuple = Quintuple(1, "Mindera", 123456L, 3.14F, arrayOf("hi", "there", "Skeletoid"))
assertEquals(1, quintuple.first)
assertEquals("Mindera", quintuple.second)
assertEquals(123456L, quintuple.third)
assertEquals(3.14F, quintuple.fourth)
assertTrue(arrayOf("hi", "there", "Skeletoid").contentEquals(quintuple.fifth))
}
@Test
fun testNullableQuintuple() {
val quintuple = Quintuple<Int?, String?, Long?, Float?, Array<String>?>(null, null, null, null, null)
assertEquals(null, quintuple.first)
assertEquals(null, quintuple.second)
assertEquals(null, quintuple.third)
assertEquals(null, quintuple.fourth)
assertEquals(null, quintuple.fourth)
}
}
| base/src/test/java/com/mindera/skeletoid/utils/tuples/QuadrupleTest.kt | 3051144533 |
package ca.gabrielcastro.openotp.ui.list
import ca.gabrielcastro.openotp.R
import ca.gabrielcastro.openotp.db.Database
import ca.gabrielcastro.openotp.rx.ioAndMain
import rx.Subscription
import timber.log.Timber
import javax.inject.Inject
internal class ListPresenterImpl @Inject constructor(
val database: Database
) : ListContract.Presenter {
lateinit var view: ListContract.View
var listSub: Subscription? = null
override fun init(view: ListContract.View) {
this.view = view
this.view.showEmptyView(false)
}
override fun pause() {
listSub?.unsubscribe()
}
override fun resume() {
listSub = database.list()
.ioAndMain()
.map {
it.map {
val iconRes = iconForIssuer(it.userIssuer)
?: iconForIssuer(it.issuer)
?: R.drawable.issuer_default_36
ListContract.ListItem(it.uuid, it.userIssuer, it.userAccountName, iconRes)
}
}
.subscribe {
view.showItems(it)
this.view.showEmptyView(it.size == 0)
}
}
override fun itemSelected(item: ListContract.ListItem) {
Timber.i("selected totp: $item")
view.showDetailForId(item.id)
}
override fun addNewTotp() {
Timber.i("add new totp clicked")
view.startScanning()
}
override fun invalidCodeScanned() {
Timber.i("invalid code scanned")
view.showTemporaryMessage("Invalid Code Scanned")
}
}
val iconMap = listOf(
Regex(".*Google.*", RegexOption.IGNORE_CASE) to R.drawable.issuer_google_36,
Regex(".*Slack.*", RegexOption.IGNORE_CASE) to R.drawable.issuer_slack_36
)
fun iconForIssuer(issuerName: String) : Int? {
return iconMap.find { it.first.matches(issuerName) }?.second
}
| app/src/main/kotlin/ca/gabrielcastro/openotp/ui/list/ListPresenterImpl.kt | 4060037864 |
package slak.gitforandroid
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ArrayAdapter
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
const val INTENT_REPO_NAME = "slak.gitforandroid.REPO_NAME"
}
private var repoNames: ArrayList<String> = ArrayList()
private var listElements: ArrayAdapter<String>? = null
private fun addRepoNames() {
repoNames.clear()
repoNames.addAll(Arrays.asList(*Repository.getRootDirectory(this).list()))
repoNames.sort()
}
override fun onResume() {
addRepoNames()
listElements!!.notifyDataSetChanged()
super.onResume()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
Thread.setDefaultUncaughtExceptionHandler {
thread, throwable -> Log.e("UNCAUGHT DEFAULT", thread.toString(), throwable)
}
// Force the user to quit if there isn't access to the filesystem
if (!Repository.isFilesystemAvailable) {
val fatalError = AlertDialog.Builder(this@MainActivity)
fatalError
.setTitle(R.string.error_storage_unavailable)
.setNegativeButton(R.string.app_quit) { _, _ ->
// It is impossible to have more than one Activity on the stack at this point
// This means the following call terminates the app
System.exit(1)
}
.create()
.show()
return
}
addRepoNames()
listElements = ArrayAdapter(this, R.layout.list_element_main, repoNames)
repoList.adapter = listElements
repoList.setOnItemClickListener { _, view: View, _, _ ->
val repoViewIntent = Intent(this@MainActivity, RepoViewActivity::class.java)
repoViewIntent.putExtra(INTENT_REPO_NAME, (view as TextView).text.toString())
startActivity(repoViewIntent)
}
fab.setOnClickListener {
createRepoDialog(this, fab, { newRepoName ->
repoNames.add(newRepoName)
listElements!!.notifyDataSetChanged()
})
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.settings) {
val settingsIntent = Intent(this@MainActivity, SettingsActivity::class.java)
startActivity(settingsIntent)
return true
}
return super.onOptionsItemSelected(item)
}
}
| app/src/main/java/slak/gitforandroid/MainActivity.kt | 3767980274 |
/*
* 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.utilities.rest
import io.javalin.Context
object StatsController {
fun getBotUptime(ctx: Context): () -> (Context) {
TODO()
}
fun getBotSessionId(ctx: Context): () -> (Context) {
TODO()
}
} | src/main/kotlin/me/salt/utilities/rest/StatsController.kt | 319273583 |
package info.nightscout.androidaps.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
@Module
abstract class CoreReceiversModule {
@ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver
} | core/src/main/java/info/nightscout/androidaps/di/CoreReceiversModule.kt | 488975126 |
package com.bluelinelabs.conductor.viewpager2
import android.app.Activity
import android.os.Looper.getMainLooper
import android.widget.FrameLayout
import androidx.core.view.ViewCompat
import androidx.viewpager2.widget.ViewPager2
import com.bluelinelabs.conductor.Conductor
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction.Companion.with
import com.bluelinelabs.conductor.viewpager2.util.TestController
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE)
class StateSaveTests {
private val pager: ViewPager2
private val adapter: RouterStateAdapter
private val destroyedItems = mutableListOf<Int>()
init {
val activityController = Robolectric.buildActivity(Activity::class.java).setup()
val layout = FrameLayout(activityController.get())
activityController.get().setContentView(layout)
val router = Conductor.attachRouter(activityController.get(), FrameLayout(activityController.get()), null)
val controller = TestController()
router.setRoot(with(controller))
pager = ViewPager2(activityController.get()).also {
it.id = ViewCompat.generateViewId()
}
layout.addView(pager)
pager.offscreenPageLimit = 1
adapter = object : RouterStateAdapter(controller) {
override fun configureRouter(router: Router, position: Int) {
if (!router.hasRootController()) {
router.setRoot(with(TestController()))
}
}
override fun getItemCount(): Int {
return 20
}
override fun onViewDetachedFromWindow(holder: RouterViewHolder) {
super.onViewDetachedFromWindow(holder)
destroyedItems.add(holder.currentItemPosition)
}
}
pager.adapter = adapter
shadowOf(getMainLooper()).idle()
}
@Test
fun testNoMaxSaves() {
// Load all pages
for (i in 0 until adapter.itemCount) {
pager.setCurrentItem(i, false)
shadowOf(getMainLooper()).idle()
}
// Ensure all non-visible pages are saved
assertEquals(
destroyedItems.size,
adapter.savedPageHistory.size
)
}
@Test
fun testMaxSavedSet() {
val maxPages = 3
adapter.setMaxPagesToStateSave(maxPages)
// Load all pages
for (i in 0 until adapter.itemCount) {
pager.setCurrentItem(i, false)
shadowOf(getMainLooper()).idle()
}
val firstSelectedItem = adapter.itemCount / 2
for (i in adapter.itemCount downTo firstSelectedItem) {
pager.setCurrentItem(i, false)
shadowOf(getMainLooper()).idle()
}
var savedPages = adapter.savedPageHistory
// Ensure correct number of pages are saved
assertEquals(maxPages, savedPages.size)
// Ensure correct pages are saved
assertEquals(destroyedItems[destroyedItems.lastIndex], savedPages[savedPages.lastIndex].toInt())
assertEquals(destroyedItems[destroyedItems.lastIndex - 1], savedPages[savedPages.lastIndex - 1].toInt())
assertEquals(destroyedItems[destroyedItems.lastIndex - 2], savedPages[savedPages.lastIndex - 2].toInt())
val secondSelectedItem = 1
for (i in adapter.itemCount downTo secondSelectedItem) {
pager.setCurrentItem(i, false)
shadowOf(getMainLooper()).idle()
}
savedPages = adapter.savedPageHistory
// Ensure correct number of pages are saved
assertEquals(maxPages, savedPages.size)
// Ensure correct pages are saved
assertEquals(destroyedItems[destroyedItems.lastIndex], savedPages[savedPages.lastIndex].toInt())
assertEquals(destroyedItems[destroyedItems.lastIndex - 1], savedPages[savedPages.lastIndex - 1].toInt())
assertEquals(destroyedItems[destroyedItems.lastIndex - 2], savedPages[savedPages.lastIndex - 2].toInt())
}
} | conductor-modules/viewpager2/src/test/java/com/bluelinelabs/conductor/viewpager2/StateSaveTests.kt | 673417711 |
package io.chesslave.mouth
data class Utterance(val text: String) | backend/src/main/java/io/chesslave/mouth/Utterance.kt | 3146114908 |
package jp.co.qoncept.kaja
import jp.co.qoncept.kotres.Result
import jp.co.qoncept.kotres.flatMap
operator fun Result<Json, JsonException>.get(index: Int): Result<Json, JsonException> {
return flatMap { it[index] }
}
operator fun Result<Json, JsonException>.get(key: String): Result<Json, JsonException> {
return flatMap { it[key] }
}
val Result<Json, JsonException>.boolean: Result<Boolean, JsonException>
get() = flatMap { it.boolean }
val Result<Json, JsonException>.int: Result<Int, JsonException>
get() = flatMap { it.int }
val Result<Json, JsonException>.long: Result<Long, JsonException>
get() = flatMap { it.long }
val Result<Json, JsonException>.double: Result<Double, JsonException>
get() = flatMap { it. double}
val Result<Json, JsonException>.string: Result<String, JsonException>
get() = flatMap { it. string}
val Result<Json, JsonException>.list: Result<List<Json>, JsonException>
get() = flatMap { it.list }
val Result<Json, JsonException>.map: Result<Map<String, Json>, JsonException>
get() = flatMap { it.map }
fun <T> Result<Json, JsonException>.list(decode: (Json) -> Result<T, JsonException>): Result<List<T>, JsonException> {
return flatMap { it.list(decode) }
}
fun <T> Result<Json, JsonException>.map(decode: (Json) -> Result<T, JsonException>): Result<Map<kotlin.String, T>, JsonException> {
return flatMap { it.map(decode) }
}
fun <T> Result<T, JsonException>.optional(defaultValue: T): Result<T, JsonException> {
return when (this) {
is Result.Success -> this
is Result.Failure -> when (exception) {
is MissingKeyException -> Result.Success(defaultValue)
else -> this
}
}
}
val <T> Result<T, JsonException>.optional: Result<T?, JsonException>
get() = when (this) {
is Result.Success -> Result.Success(value)
is Result.Failure -> when (exception) {
is MissingKeyException -> Result.Success(null)
else -> Result.Failure(exception)
}
}
| src/jp/co/qoncept/kaja/Result.kt | 2274509276 |
package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
/**
* Rewrite theme setting to use `FOLLOW_SYSTEM` when it's currently set to `LIGHT`.
*/
class StorageMigrationTo8(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
fun rewriteTheme() {
val theme = migrationsHelper.readValue(db, "theme")
if (theme == THEME_LIGHT) {
migrationsHelper.writeValue(db, "theme", THEME_FOLLOW_SYSTEM)
}
}
companion object {
private const val THEME_LIGHT = "LIGHT"
private const val THEME_FOLLOW_SYSTEM = "FOLLOW_SYSTEM"
}
}
| app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo8.kt | 4163206501 |
package com.github.shiraji.breakpointsmanager.model
data class BreakpointsSetNode(var breakpointsSetInfo: BreakpointsSetInfo,
var isShared: Boolean = false) {
override fun toString(): String {
if (isShared) {
return "[Shared] ${breakpointsSetInfo.name}"
} else {
return breakpointsSetInfo.name
}
}
} | src/main/java/com/github/shiraji/breakpointsmanager/model/BreakpointsSetNode.kt | 2339663902 |
package com.fsck.k9.ui.permissions
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import timber.log.Timber
interface PermissionUiHelper {
fun hasPermission(permission: Permission): Boolean
fun requestPermissionOrShowRationale(permission: Permission)
fun requestPermission(permission: Permission)
}
class K9PermissionUiHelper(private val activity: AppCompatActivity) : PermissionUiHelper {
override fun hasPermission(permission: Permission): Boolean {
return ContextCompat.checkSelfPermission(activity, permission.permission) == PackageManager.PERMISSION_GRANTED
}
override fun requestPermissionOrShowRationale(permission: Permission) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission.permission)) {
val dialogFragment = PermissionRationaleDialogFragment.newInstance(permission)
dialogFragment.show(activity.supportFragmentManager, FRAGMENT_TAG_RATIONALE)
} else {
requestPermission(permission)
}
}
override fun requestPermission(permission: Permission) {
Timber.i("Requesting permission: " + permission.permission)
ActivityCompat.requestPermissions(activity, arrayOf(permission.permission), permission.requestCode)
}
companion object {
private const val FRAGMENT_TAG_RATIONALE = "rationale"
}
}
| app/ui/legacy/src/main/java/com/fsck/k9/ui/permissions/PermissionUiHelper.kt | 1666401319 |
// 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.test
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.test.KotlinRoot
import java.io.File
abstract class KotlinLightPlatformCodeInsightFixtureTestCase : LightPlatformCodeInsightFixtureTestCase() {
protected open fun isFirPlugin(): Boolean = false
override fun setUp() {
super.setUp()
enableKotlinOfficialCodeStyle(project)
VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path)
if (!isFirPlugin()) {
invalidateLibraryCache(project)
}
}
override fun tearDown() {
runAll(
ThrowableRunnable { disableKotlinOfficialCodeStyle(project) },
ThrowableRunnable { super.tearDown() },
)
}
protected fun dataFile(fileName: String): File = File(testDataPath, fileName)
protected fun dataFile(): File = dataFile(fileName())
protected fun dataPath(fileName: String = fileName()): String = dataFile(fileName).toString()
protected fun dataPath(): String = dataPath(fileName())
protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt")
override fun getTestDataPath() = TestMetadataUtil.getTestDataPath(this::class.java)
}
| plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt | 1398453370 |
// 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
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText
import org.jetbrains.kotlin.idea.refactoring.getSmartSelectSuggestions
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.kotlin.psi.KtFile
abstract class AbstractSmartSelectionTest : KotlinLightCodeInsightFixtureTestCase() {
fun doTestSmartSelection(path: String) {
myFixture.configureByFile(path)
val expectedResultText = KotlinTestUtils.getLastCommentInFile(getFile() as KtFile)
val elements = getSmartSelectSuggestions(getFile(), getEditor().caretModel.offset, CodeInsightUtils.ElementKind.EXPRESSION)
assertEquals(expectedResultText, elements.joinToString(separator = "\n", transform = ::getExpressionShortText))
}
}
| plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/AbstractSmartSelectionTest.kt | 1847416430 |
/*
* 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.android.example.github.testing
/**
* This annotation allows us to open some classes for mocking purposes while they are final in
* release builds.
*/
@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class OpenClass
/**
* Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds.
*/
@OpenClass
@Target(AnnotationTarget.CLASS)
annotation class OpenForTesting | GithubBrowserSample/app/src/debug/java/com/android/example/github/testing/OpenForTesting.kt | 909679076 |
package org.wordpress.android.ui.posts.prepublishing
import android.os.Bundle
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.never
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.BaseUnitTest
import org.wordpress.android.R
import org.wordpress.android.TEST_DISPATCHER
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.TermModel
import org.wordpress.android.fluxc.store.TaxonomyStore
import org.wordpress.android.fluxc.store.TaxonomyStore.TaxonomyError
import org.wordpress.android.fluxc.store.TaxonomyStore.TaxonomyErrorType.GENERIC_ERROR
import org.wordpress.android.models.CategoryNode
import org.wordpress.android.test
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.posts.AddCategoryUseCase
import org.wordpress.android.ui.posts.EditPostRepository
import org.wordpress.android.ui.posts.GetCategoriesUseCase
import org.wordpress.android.ui.posts.PrepublishingAddCategoryRequest
import org.wordpress.android.ui.posts.PrepublishingCategoriesViewModel
import org.wordpress.android.ui.posts.PrepublishingCategoriesViewModel.UiState
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.Event
@InternalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class PrepublishingCategoriesViewModelTest : BaseUnitTest() {
private lateinit var viewModel: PrepublishingCategoriesViewModel
@Mock lateinit var getCategoriesUseCase: GetCategoriesUseCase
@Mock lateinit var addCategoryUseCase: AddCategoryUseCase
@Mock lateinit var networkUtilsWrapper: NetworkUtilsWrapper
@Mock lateinit var analyticsTrackerWrapper: AnalyticsTrackerWrapper
@Mock lateinit var editPostRepository: EditPostRepository
@Mock lateinit var siteModel: SiteModel
@Before
fun setup() = test {
viewModel = PrepublishingCategoriesViewModel(
getCategoriesUseCase,
addCategoryUseCase,
analyticsTrackerWrapper,
networkUtilsWrapper,
TEST_DISPATCHER
)
whenever(getCategoriesUseCase.getPostCategories(anyOrNull()))
.thenReturn(postCategoriesList())
whenever(getCategoriesUseCase.getSiteCategories(any()))
.thenReturn(siteCategoriesList())
whenever(addCategoryUseCase.addCategory(anyString(), anyLong(), any())).doAnswer { }
}
@Test
fun `when viewModel is started updateToolbarTitle is called with the categories title`() {
val toolbarTitleUiState = init().toolbarTitleUiState
viewModel.start(editPostRepository, siteModel, null, listOf())
val title: UiStringRes? = toolbarTitleUiState[0] as UiStringRes
assertThat(title?.stringRes)
.isEqualTo(R.string.prepublishing_nudges_toolbar_title_categories)
}
@Test
fun `when viewModel is started add category button is visible on the titlebar`() {
val uiStates = init().uiStates
viewModel.start(editPostRepository, siteModel, null, listOf())
val addCategoryButtonVisibility: Boolean = uiStates[0].addCategoryActionButtonVisibility
Assertions.assertThat(addCategoryButtonVisibility)
.isEqualTo(true)
}
@Test
fun `when viewModel is started progress views is not visible when not an addCategoryRequest`() {
val uiStates = init().uiStates
viewModel.start(editPostRepository, siteModel, null, listOf())
val progressVisibility: Boolean = uiStates[0].progressVisibility
Assertions.assertThat(progressVisibility)
.isEqualTo(false)
}
@Test
fun `when viewModel is started progress views is visible when this is an addCategoryRequest`() {
val uiStates = init().uiStates
viewModel.start(editPostRepository, siteModel, addCategoryRequest, listOf())
val progressVisibility: Boolean = uiStates[0].progressVisibility
Assertions.assertThat(progressVisibility)
.isEqualTo(true)
}
@Test
fun `when onBackClicked is triggered navigateToHomeScreen is called`() {
val navigateToHome = init().navigateToHome
viewModel.start(editPostRepository, siteModel, null, listOf())
viewModel.onBackButtonClick()
assertThat(navigateToHome[0]).isNotNull
}
@Test
fun `when onAddCategoryClick is triggered navigateToAddCategoryScreen is called`() {
val navigateToAddCategoryScreen = init().navigateToAddCategoryScreen
viewModel.start(editPostRepository, siteModel, null, listOf())
viewModel.onAddCategoryClick()
Assertions.assertThat(navigateToAddCategoryScreen[0]).isNotNull
}
@Test
fun `getSiteCategories is invoked on start`() {
viewModel.start(editPostRepository, siteModel, null, listOf())
verify(getCategoriesUseCase, times(1)).getSiteCategories(siteModel)
}
@Test
fun `getPostCategories is invoked on start`() {
viewModel.start(editPostRepository, siteModel, null, listOf())
verify(getCategoriesUseCase, times(1)).getPostCategories(editPostRepository)
}
@Test
fun `fetchSiteCategories is invoked on start when not an addCategoryRequest`() {
viewModel.start(editPostRepository, siteModel, null, listOf())
verify(getCategoriesUseCase, times(1)).fetchSiteCategories(siteModel)
}
@Test
fun `fetchSiteCategories is not invoked on start when there is an addCategoryRequest`() {
viewModel.start(editPostRepository, siteModel, addCategoryRequest, listOf())
verify(getCategoriesUseCase, never()).fetchSiteCategories(siteModel)
}
@Test
fun `selected categories are correctly shown on successful start`() {
val uiStates = init().uiStates
viewModel.start(editPostRepository, siteModel, null, listOf())
val siteCategories = siteCategoriesList()
val postCategories = postCategoriesList()
assertThat(viewModel.uiState.value).isNotNull
assertThat(viewModel.uiState.value).isInstanceOf(UiState::class.java)
assertThat(uiStates[0].categoriesListItemUiState.size).isEqualTo(siteCategories.size)
val categoriesListItems =
uiStates[0].categoriesListItemUiState
assertThat(categoriesListItems.count { item ->
item.checked
}).isEqualTo(postCategories.size)
}
@Test
fun `selected categories are correctly shown on successful start upon return from add `() {
val uiStates = init().uiStates
val postCategories = postCategoriesList()
val siteCategories = siteCategoriesList()
viewModel.start(editPostRepository, siteModel, null, postCategories)
assertThat(viewModel.uiState.value).isNotNull
assertThat(viewModel.uiState.value).isInstanceOf(UiState::class.java)
assertThat(uiStates[0].categoriesListItemUiState.size).isEqualTo(siteCategories.size)
val categoriesListItems =
uiStates[0].categoriesListItemUiState
assertThat(categoriesListItems.count { item ->
item.checked
}).isEqualTo(postCategories.size)
}
@Test
fun `when AddCategory success response toast is shown`() {
val msgs = init().snackbarMsgs
viewModel.start(editPostRepository, siteModel, null, listOf())
val termModel = getTermModel()
val onTermUploaded = TaxonomyStore.OnTermUploaded(termModel)
viewModel.onTermUploadedComplete(onTermUploaded)
assertThat(msgs[0].peekContent().message).isEqualTo(UiStringRes(R.string.adding_cat_success))
}
@Test
fun `when AddCategory success new item is checked in list`() {
val uiStates = init().uiStates
val siteCategories = updatedSiteCategoriesList()
val selectedCategoriesCount = postCategoriesList().size + 1
whenever(getCategoriesUseCase.getSiteCategories(any()))
.thenReturn(siteCategoriesList())
viewModel.start(editPostRepository, siteModel, null, listOf())
val termModel = getTermModel()
val onTermUploaded = TaxonomyStore.OnTermUploaded(termModel)
whenever(getCategoriesUseCase.getSiteCategories(any()))
.thenReturn(updatedSiteCategoriesList())
viewModel.onTermUploadedComplete(onTermUploaded)
assertThat(uiStates[1].categoriesListItemUiState.size).isEqualTo(siteCategories.size)
val categoriesListItems =
uiStates[1].categoriesListItemUiState
assertThat(categoriesListItems.count { item ->
item.checked
}).isEqualTo(selectedCategoriesCount)
}
@Test
fun `when addCategory fails response toast is shown`() {
val msgs = init().snackbarMsgs
viewModel.start(editPostRepository, siteModel, null, listOf())
val onTermUploaded = TaxonomyStore.OnTermUploaded(getTermModel())
onTermUploaded.error = TaxonomyError(GENERIC_ERROR, "This is an error")
viewModel.onTermUploadedComplete(onTermUploaded)
assertThat(msgs[0].peekContent().message).isEqualTo(UiStringRes(R.string.adding_cat_failed))
}
@Test
fun `when no changes exist navigateToHomeScreen is called`() {
val navigateToHome = init().navigateToHome
viewModel.start(editPostRepository, siteModel, null, listOf())
viewModel.onBackButtonClick()
assertThat(navigateToHome[0]).isNotNull
}
@Test
fun `when changes exist progress view is visible`() {
val uiStates = init().uiStates
viewModel.start(editPostRepository, siteModel, null, listOf())
viewModel.start(editPostRepository, siteModel, null, listOf())
val onTermUploaded = TaxonomyStore.OnTermUploaded(getTermModel())
whenever(getCategoriesUseCase.getSiteCategories(any()))
.thenReturn(updatedSiteCategoriesList())
viewModel.onTermUploadedComplete(onTermUploaded)
viewModel.onBackButtonClick()
assertThat(uiStates[2].progressVisibility).isEqualTo(true)
}
private fun postCategoriesList() = listOf<Long>(1, 2, 3, 4, 5)
private fun siteCategoriesList(): ArrayList<CategoryNode> {
return arrayListOf(
CategoryNode(1, 0, "Animals"),
CategoryNode(2, 0, "Colors"),
CategoryNode(3, 0, "Flavors"),
CategoryNode(4, 0, "Articles"),
CategoryNode(14, 4, "New"),
CategoryNode(5, 0, "Fruit"),
CategoryNode(6, 0, "Recipes"),
CategoryNode(16, 6, "New")
)
}
private fun updatedSiteCategoriesList(): ArrayList<CategoryNode> {
val termModel = getTermModel()
val categoryNode = CategoryNode(termModel.remoteTermId, 0, termModel.name)
val newList = arrayListOf<CategoryNode>()
newList.addAll(siteCategoriesList())
newList.add(categoryNode)
return newList
}
private fun init(): Observers {
val uiStates = mutableListOf<UiState>()
viewModel.uiState.observeForever { uiStates.add(it) }
val navigateToHome = mutableListOf<Event<Unit>>()
viewModel.navigateToHomeScreen.observeForever { navigateToHome.add(it) }
val navigateToAddCategoryScreen = mutableListOf<Bundle>()
viewModel.navigateToAddCategoryScreen.observeForever { navigateToAddCategoryScreen.add(it) }
val toolbarTitleUiState = mutableListOf<UiString>()
viewModel.toolbarTitleUiState.observeForever { toolbarTitleUiState.add(it) }
val msgs = mutableListOf<Event<SnackbarMessageHolder>>()
viewModel.snackbarEvents.observeForever { msgs.add(it) }
return Observers(
uiStates,
navigateToHome,
navigateToAddCategoryScreen,
toolbarTitleUiState,
msgs
)
}
// set up observers
private data class Observers(
val uiStates: List<UiState>,
val navigateToHome: List<Event<Unit>>,
val navigateToAddCategoryScreen: List<Bundle>,
val toolbarTitleUiState: List<UiString>,
val snackbarMsgs: List<Event<SnackbarMessageHolder>>
)
private val addCategoryRequest =
PrepublishingAddCategoryRequest(
categoryText = "Flowers",
categoryParentId = 0
)
private fun getTermModel(): TermModel {
val termModel = TermModel()
termModel.name = "Cars"
termModel.remoteTermId = 20
termModel.slug = "Cars"
return termModel
}
}
| WordPress/src/test/java/org/wordpress/android/ui/posts/prepublishing/PrepublishingCategoriesViewModelTest.kt | 1270622456 |
// 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
class AddEqEqTrueFix(expression: KtExpression) : KotlinQuickFixAction<KtExpression>(expression) {
override fun getText() = KotlinBundle.message("fix.add.eq.eq.true")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expression = element ?: return
expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0 == true", expression))
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddEqEqTrueFix.kt | 4043965418 |
abstract class Base {
abstract fun foo(oher: Int)
abstract val smalVal: Int
abstract fun smalFun()
}
class Other : Base() {
override fun foo(oher: Int) {
}
override val smalVal: Int get() = 1
override fun smalFun() {}
}
| plugins/kotlin/idea/tests/testData/checker/infos/TyposInOverrideParams.fir.kt | 966806062 |
fun test(some: (Int) -> Int) {
}
fun foo() = test() { it }
val function = test { a: Int -> a }
val function1 = test { a: Int -> a }
val function2 = test { }
val function3 = test {}
val function4 = test { }
val function5 = test {
}
// SET_TRUE: INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD | plugins/kotlin/idea/tests/testData/formatter/SingleLineFunctionLiteral.after.kt | 3720367463 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Experimental
package com.intellij.openapi.progress
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts.ProgressTitle
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import org.jetbrains.annotations.ApiStatus.Experimental
suspend fun <T> withBackgroundProgressIndicator(
project: Project,
title: @ProgressTitle String,
action: suspend CoroutineScope.() -> T
): T {
return withBackgroundProgressIndicator(project, title, cancellable = true, action)
}
suspend fun <T> withBackgroundProgressIndicator(
project: Project,
title: @ProgressTitle String,
cancellable: Boolean,
action: suspend CoroutineScope.() -> T
): T {
val cancellation = if (cancellable) TaskCancellation.cancellable() else TaskCancellation.nonCancellable()
return withBackgroundProgressIndicator(project, title, cancellation, action)
}
/**
* Shows a background progress indicator, and runs the specified [action].
* The action receives [ProgressSink] in the coroutine context, progress sink updates are reflected in the UI during the action.
* The indicator is not shown immediately to avoid flickering,
* i.e. the user won't see anything if the [action] completes within the given timeout.
*
* @param project in which frame the progress should be shown
* @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable]
* @throws CancellationException if the calling coroutine was cancelled,
* or if the indicator was cancelled by the user in the UI
*/
suspend fun <T> withBackgroundProgressIndicator(
project: Project,
title: @ProgressTitle String,
cancellation: TaskCancellation,
action: suspend CoroutineScope.() -> T
): T {
val service = ApplicationManager.getApplication().getService(TaskSupport::class.java)
return service.withBackgroundProgressIndicatorInternal(
project, title, cancellation, action
)
}
suspend fun <T> withModalProgressIndicator(
project: Project,
title: @ProgressTitle String,
action: suspend CoroutineScope.() -> T,
): T {
return withModalProgressIndicator(owner = ModalTaskOwner.project(project), title = title, action = action)
}
/**
* Shows a modal progress indicator, and runs the specified [action].
* The action receives [ProgressSink] in the coroutine context, progress sink updates are reflected in the UI during the action.
* The indicator is not shown immediately to avoid flickering,
* i.e. the user won't see anything if the [action] completes within the given timeout.
* Switches to [com.intellij.openapi.application.EDT] are allowed inside the action,
* as they are automatically scheduled with the correct modality, which is the newly entered one.
*
* @param owner in which frame the progress should be shown
* @param cancellation controls the UI appearance, e.g. [TaskCancellation.nonCancellable] or [TaskCancellation.cancellable]
* @throws CancellationException if the calling coroutine was cancelled,
* or if the indicator was cancelled by the user in the UI
*/
suspend fun <T> withModalProgressIndicator(
owner: ModalTaskOwner,
title: @ProgressTitle String,
cancellation: TaskCancellation = TaskCancellation.cancellable(),
action: suspend CoroutineScope.() -> T,
): T {
val service = ApplicationManager.getApplication().getService(TaskSupport::class.java)
return service.withModalProgressIndicatorInternal(owner, title, cancellation, action)
}
| platform/platform-api/src/com/intellij/openapi/progress/tasks.kt | 898169552 |
// 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.k2.fe10bindings.inspections
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.fir.highlighter.KotlinHighLevelDiagnosticHighlightingPass
import org.jetbrains.kotlin.idea.fir.invalidateCaches
import org.jetbrains.kotlin.idea.inspections.AbstractLocalInspectionTest
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.test.utils.IgnoreTests
import java.io.File
abstract class AbstractFe10BindingLocalInspectionTest : AbstractLocalInspectionTest() {
override fun isFirPlugin() = true
override fun checkForUnexpectedErrors(fileText: String) {}
override fun collectHighlightInfos(): List<HighlightInfo> {
return KotlinHighLevelDiagnosticHighlightingPass.ignoreThisPassInTests { super.collectHighlightInfos() }
}
override fun tearDown() {
runAll(
ThrowableRunnable { project.invalidateCaches() },
ThrowableRunnable { super.tearDown() }
)
}
override fun doTestFor(mainFile: File, inspection: AbstractKotlinInspection, fileText: String) {
IgnoreTests.runTestIfNotDisabledByFileDirective(mainFile.toPath(), IgnoreTests.DIRECTIVES.IGNORE_FE10_BINDING_BY_FIR, "after") {
super.doTestFor(mainFile, inspection, fileText)
}
}
} | plugins/kotlin/k2-fe10-bindings/test/org/jetbrains/kotlin/idea/k2/fe10bindings/inspections/AbstractFe10BindingLocalInspectionTest.kt | 3968799238 |
package net.nextpulse.jacumulus.requests
import net.nextpulse.jacumulus.requests.models.Supplier
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.XmlRootElement
/**
* Request to add both (if it does not exist yet) a supplier and invoice from this supplier. The supplier will be
* de-duplicated using the customerId or email address.
*
* @see [https://apidoc.sielsystems.nl/content/expense-add-expense]
*/
@XmlRootElement(name = "myxml")
data class AddExpenseRequest(
/**
* Supplier object to add
*/
@get:XmlElement(name = "supplier")
var supplier: Supplier? = null
) : AcumulusRequest() | src/main/java/net/nextpulse/jacumulus/requests/AddExpenseRequest.kt | 2348150674 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.niacatalog.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.add
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.google.accompanist.flowlayout.FlowRow
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaDropdownMenuButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilterChip
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBar
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaNavigationBarItem
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOutlinedButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTab
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTabRow
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTextButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaViewToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
/**
* Now in Android component catalog.
*/
@Composable
fun NiaCatalog() {
NiaTheme {
Surface {
val contentPadding = WindowInsets
.systemBars
.add(WindowInsets(left = 16.dp, top = 16.dp, right = 16.dp, bottom = 16.dp))
.asPaddingValues()
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = contentPadding,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
item {
Text(
text = "NiA Catalog",
style = MaterialTheme.typography.headlineSmall,
)
}
item { Text("Buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(onClick = {}) {
Text(text = "Enabled")
}
NiaOutlinedButton(onClick = {}) {
Text(text = "Enabled")
}
NiaTextButton(onClick = {}) {
Text(text = "Enabled")
}
}
}
item { Text("Disabled buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false
) {
Text(text = "Disabled")
}
NiaOutlinedButton(
onClick = {},
enabled = false
) {
Text(text = "Disabled")
}
NiaTextButton(
onClick = {},
enabled = false
) {
Text(text = "Disabled")
}
}
}
item { Text("Buttons with leading icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Disabled buttons with leading icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Buttons with trailing icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Disabled buttons with trailing icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Small buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
NiaOutlinedButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
NiaTextButton(
onClick = {},
small = true
) {
Text(text = "Enabled")
}
}
}
item { Text("Disabled small buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
NiaTextButton(
onClick = {},
enabled = false,
small = true
) {
Text(text = "Disabled")
}
}
}
item { Text("Small buttons with leading icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item {
Text(
"Disabled small buttons with leading icons",
Modifier.padding(top = 16.dp)
)
}
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
leadingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Small buttons with trailing icons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
small = true,
text = { Text(text = "Enabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item {
Text(
"Disabled small buttons with trailing icons",
Modifier.padding(top = 16.dp)
)
}
item {
FlowRow(mainAxisSpacing = 16.dp) {
NiaFilledButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaOutlinedButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
NiaTextButton(
onClick = {},
enabled = false,
small = true,
text = { Text(text = "Disabled") },
trailingIcon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
}
)
}
}
item { Text("Dropdown menu", Modifier.padding(top = 16.dp)) }
item {
NiaDropdownMenuButton(
text = { Text("Newest first") },
items = listOf("Item 1", "Item 2", "Item 3"),
onItemClick = {},
itemText = { item -> Text(item) }
)
}
item { Text("Chips", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
var firstChecked by remember { mutableStateOf(false) }
NiaFilterChip(
selected = firstChecked,
onSelectedChange = { checked -> firstChecked = checked },
label = { Text(text = "Enabled".uppercase()) }
)
var secondChecked by remember { mutableStateOf(true) }
NiaFilterChip(
selected = secondChecked,
onSelectedChange = { checked -> secondChecked = checked },
label = { Text(text = "Enabled".uppercase()) }
)
var thirdChecked by remember { mutableStateOf(true) }
NiaFilterChip(
selected = thirdChecked,
onSelectedChange = { checked -> thirdChecked = checked },
enabled = false,
label = { Text(text = "Disabled".uppercase()) }
)
}
}
item { Text("Toggle buttons", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
var firstChecked by remember { mutableStateOf(false) }
NiaToggleButton(
checked = firstChecked,
onCheckedChange = { checked -> firstChecked = checked },
icon = {
Icon(
painter = painterResource(id = NiaIcons.BookmarkBorder),
contentDescription = null
)
},
checkedIcon = {
Icon(
painter = painterResource(id = NiaIcons.Bookmark),
contentDescription = null
)
}
)
var secondChecked by remember { mutableStateOf(true) }
NiaToggleButton(
checked = secondChecked,
onCheckedChange = { checked -> secondChecked = checked },
icon = {
Icon(
painter = painterResource(id = NiaIcons.BookmarkBorder),
contentDescription = null
)
},
checkedIcon = {
Icon(
painter = painterResource(id = NiaIcons.Bookmark),
contentDescription = null
)
}
)
var thirdChecked by remember { mutableStateOf(false) }
NiaToggleButton(
checked = thirdChecked,
onCheckedChange = { checked -> thirdChecked = checked },
icon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
},
checkedIcon = {
Icon(imageVector = NiaIcons.Check, contentDescription = null)
}
)
var fourthChecked by remember { mutableStateOf(true) }
NiaToggleButton(
checked = fourthChecked,
onCheckedChange = { checked -> fourthChecked = checked },
icon = {
Icon(imageVector = NiaIcons.Add, contentDescription = null)
},
checkedIcon = {
Icon(imageVector = NiaIcons.Check, contentDescription = null)
}
)
}
}
item { Text("View toggle", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
var firstExpanded by remember { mutableStateOf(false) }
NiaViewToggleButton(
expanded = firstExpanded,
onExpandedChange = { expanded -> firstExpanded = expanded },
compactText = { Text(text = "Compact view") },
expandedText = { Text(text = "Expanded view") }
)
var secondExpanded by remember { mutableStateOf(true) }
NiaViewToggleButton(
expanded = secondExpanded,
onExpandedChange = { expanded -> secondExpanded = expanded },
compactText = { Text(text = "Compact view") },
expandedText = { Text(text = "Expanded view") }
)
}
}
item { Text("Tags", Modifier.padding(top = 16.dp)) }
item {
FlowRow(mainAxisSpacing = 16.dp) {
var expandedTopicId by remember { mutableStateOf<String?>(null) }
var firstFollowed by remember { mutableStateOf(false) }
NiaTopicTag(
expanded = expandedTopicId == "Topic 1",
followed = firstFollowed,
onDropMenuToggle = { show ->
expandedTopicId = if (show) "Topic 1" else null
},
onFollowClick = { firstFollowed = true },
onUnfollowClick = { firstFollowed = false },
onBrowseClick = {},
text = { Text(text = "Topic 1".uppercase()) },
followText = { Text(text = "Follow") },
unFollowText = { Text(text = "Unfollow") },
browseText = { Text(text = "Browse topic") }
)
var secondFollowed by remember { mutableStateOf(true) }
NiaTopicTag(
expanded = expandedTopicId == "Topic 2",
followed = secondFollowed,
onDropMenuToggle = { show ->
expandedTopicId = if (show) "Topic 2" else null
},
onFollowClick = { secondFollowed = true },
onUnfollowClick = { secondFollowed = false },
onBrowseClick = {},
text = { Text(text = "Topic 2".uppercase()) },
followText = { Text(text = "Follow") },
unFollowText = { Text(text = "Unfollow") },
browseText = { Text(text = "Browse topic") }
)
}
}
item { Text("Tabs", Modifier.padding(top = 16.dp)) }
item {
var selectedTabIndex by remember { mutableStateOf(0) }
val titles = listOf("Topics", "People")
NiaTabRow(selectedTabIndex = selectedTabIndex) {
titles.forEachIndexed { index, title ->
NiaTab(
selected = selectedTabIndex == index,
onClick = { selectedTabIndex = index },
text = { Text(text = title) }
)
}
}
}
item { Text("Navigation", Modifier.padding(top = 16.dp)) }
item {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf("For you", "Episodes", "Saved", "Interests")
val icons = listOf(
NiaIcons.UpcomingBorder,
NiaIcons.MenuBookBorder,
NiaIcons.BookmarksBorder
)
val selectedIcons = listOf(
NiaIcons.Upcoming,
NiaIcons.MenuBook,
NiaIcons.Bookmarks
)
val tagIcon = NiaIcons.Tag
NiaNavigationBar {
items.forEachIndexed { index, item ->
NiaNavigationBarItem(
icon = {
if (index == 3) {
Icon(imageVector = tagIcon, contentDescription = null)
} else {
Icon(
painter = painterResource(id = icons[index]),
contentDescription = item
)
}
},
selectedIcon = {
if (index == 3) {
Icon(imageVector = tagIcon, contentDescription = null)
} else {
Icon(
painter = painterResource(id = selectedIcons[index]),
contentDescription = item
)
}
},
label = { Text(item) },
selected = selectedItem == index,
onClick = { selectedItem = index }
)
}
}
}
}
}
}
}
| app-nia-catalog/src/main/java/com/google/samples/apps/niacatalog/ui/Catalog.kt | 3234650960 |
package org.snakeskin.component
import org.snakeskin.component.provider.ICurrentProvider
import org.snakeskin.component.provider.IOutputVoltageProvider
/**
* Marker interface for a current and voltage sensor combo
*/
interface ICurrentVoltageSensorComponent : ICurrentProvider, IOutputVoltageProvider | SnakeSkin-Core/src/main/kotlin/org/snakeskin/component/ICurrentVoltageSensorComponent.kt | 868081822 |
/*
* Copyright (C) 2013 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.picasso3
import android.content.ContentResolver
import android.content.Context
import android.content.UriMatcher
import android.net.Uri
import android.provider.ContactsContract
import android.provider.ContactsContract.Contacts
import com.squareup.picasso3.BitmapUtils.decodeStream
import com.squareup.picasso3.Picasso.LoadedFrom.DISK
import okio.Source
import okio.source
import java.io.FileNotFoundException
import java.io.IOException
internal class ContactsPhotoRequestHandler(private val context: Context) : RequestHandler() {
companion object {
/** A lookup uri (e.g. content://com.android.contacts/contacts/lookup/3570i61d948d30808e537) */
private const val ID_LOOKUP = 1
/** A contact thumbnail uri (e.g. content://com.android.contacts/contacts/38/photo) */
private const val ID_THUMBNAIL = 2
/** A contact uri (e.g. content://com.android.contacts/contacts/38) */
private const val ID_CONTACT = 3
/**
* A contact display photo (high resolution) uri
* (e.g. content://com.android.contacts/display_photo/5)
*/
private const val ID_DISPLAY_PHOTO = 4
private val matcher: UriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {
addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", ID_LOOKUP)
addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", ID_LOOKUP)
addURI(ContactsContract.AUTHORITY, "contacts/#/photo", ID_THUMBNAIL)
addURI(ContactsContract.AUTHORITY, "contacts/#", ID_CONTACT)
addURI(ContactsContract.AUTHORITY, "display_photo/#", ID_DISPLAY_PHOTO)
}
}
override fun canHandleRequest(data: Request): Boolean {
val uri = data.uri
return uri != null &&
ContentResolver.SCHEME_CONTENT == uri.scheme &&
Contacts.CONTENT_URI.host == uri.host &&
matcher.match(data.uri) != UriMatcher.NO_MATCH
}
override fun load(
picasso: Picasso,
request: Request,
callback: Callback
) {
var signaledCallback = false
try {
val requestUri = checkNotNull(request.uri)
val source = getSource(requestUri)
val bitmap = decodeStream(source, request)
signaledCallback = true
callback.onSuccess(Result.Bitmap(bitmap, DISK))
} catch (e: Exception) {
if (!signaledCallback) {
callback.onError(e)
}
}
}
private fun getSource(uri: Uri): Source {
val contentResolver = context.contentResolver
val input = when (matcher.match(uri)) {
ID_LOOKUP -> {
val contactUri =
Contacts.lookupContact(contentResolver, uri) ?: throw IOException("no contact found")
Contacts.openContactPhotoInputStream(contentResolver, contactUri, true)
}
ID_CONTACT -> Contacts.openContactPhotoInputStream(contentResolver, uri, true)
ID_THUMBNAIL, ID_DISPLAY_PHOTO -> contentResolver.openInputStream(uri)
else -> throw IllegalStateException("Invalid uri: $uri")
} ?: throw FileNotFoundException("can't open input stream, uri: $uri")
return input.source()
}
}
| picasso/src/main/java/com/squareup/picasso3/ContactsPhotoRequestHandler.kt | 1378271984 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.liveTemplates.macro
import com.intellij.codeInsight.template.JavaPsiElementResult
import com.intellij.psi.PsiNamedElement
class KotlinPsiElementResult(element: PsiNamedElement) : JavaPsiElementResult(element) {
override fun toString() = (element as PsiNamedElement).name ?: ""
}
| plugins/kotlin/code-insight/live-templates-shared/src/org/jetbrains/kotlin/idea/liveTemplates/macro/KotlinPsiElementResult.kt | 1156227560 |
// 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.vcs.log.ui.table.column
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vcs.FilePath
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.text.DateFormatUtil
import com.intellij.util.text.DateTimeFormatManager
import com.intellij.util.text.JBDateFormat
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.graph.DefaultColorGenerator
import com.intellij.vcs.log.history.FileHistoryPaths.filePathOrDefault
import com.intellij.vcs.log.history.FileHistoryPaths.hasPathsInformation
import com.intellij.vcs.log.impl.CommonUiProperties
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.paint.GraphCellPainter
import com.intellij.vcs.log.paint.SimpleGraphCellPainter
import com.intellij.vcs.log.ui.frame.CommitPresentationUtil
import com.intellij.vcs.log.ui.render.GraphCommitCell
import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.ui.table.RootCellRenderer
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import com.intellij.vcs.log.ui.table.VcsLogStringCellRenderer
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.visible.VisiblePack
import com.intellij.vcsUtil.VcsUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.util.*
import javax.swing.table.TableCellRenderer
internal fun getDefaultDynamicColumns() = listOf<VcsLogDefaultColumn<*>>(Author, Hash, Date)
internal sealed class VcsLogDefaultColumn<T>(
@NonNls override val id: String,
override val localizedName: @Nls String,
override val isDynamic: Boolean = true
) : VcsLogColumn<T> {
/**
* @return stable name (to identify column in statistics)
*/
val stableName: String
get() = id.toLowerCase(Locale.ROOT)
}
internal object Root : VcsLogDefaultColumn<FilePath>("Default.Root", "", false) {
override val isResizable = false
override fun getValue(model: GraphTableModel, row: Int): FilePath {
val visiblePack = model.visiblePack
if (visiblePack.hasPathsInformation()) {
val path = visiblePack.filePathOrDefault(visiblePack.visibleGraph.getRowInfo(row).commit)
if (path != null) {
return path
}
}
return VcsUtil.getFilePath(visiblePack.getRoot(row))
}
override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer {
doOnPropertyChange(table) { property ->
if (CommonUiProperties.SHOW_ROOT_NAMES == property) {
table.rootColumnUpdated()
}
}
return RootCellRenderer(table.properties, table.colorManager)
}
override fun getStubValue(model: GraphTableModel): FilePath = VcsUtil.getFilePath(ContainerUtil.getFirstItem(model.logData.roots))
}
internal object Commit : VcsLogDefaultColumn<GraphCommitCell>("Default.Subject", VcsLogBundle.message("vcs.log.column.subject"), false),
VcsLogMetadataColumn {
override fun getValue(model: GraphTableModel, row: Int): GraphCommitCell {
val printElements = if (VisiblePack.NO_GRAPH_INFORMATION.get(model.visiblePack, false)) emptyList()
else model.visiblePack.visibleGraph.getRowInfo(row).printElements
return GraphCommitCell(
getValue(model, model.getCommitMetadata(row, true)),
model.getRefsAtRow(row),
printElements
)
}
override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): String = commit.subject
override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer {
val graphCellPainter: GraphCellPainter = object : SimpleGraphCellPainter(DefaultColorGenerator()) {
override fun getRowHeight(): Int {
return table.rowHeight
}
}
val commitCellRenderer = GraphCommitCellRenderer(table.logData, graphCellPainter, table)
commitCellRenderer.setCompactReferencesView(table.properties[CommonUiProperties.COMPACT_REFERENCES_VIEW])
commitCellRenderer.setShowTagsNames(table.properties[CommonUiProperties.SHOW_TAG_NAMES])
commitCellRenderer.setLeftAligned(table.properties[CommonUiProperties.LABELS_LEFT_ALIGNED])
doOnPropertyChange(table) { property ->
if (CommonUiProperties.COMPACT_REFERENCES_VIEW == property) {
commitCellRenderer.setCompactReferencesView(table.properties[CommonUiProperties.COMPACT_REFERENCES_VIEW])
table.repaint()
}
else if (CommonUiProperties.SHOW_TAG_NAMES == property) {
commitCellRenderer.setShowTagsNames(table.properties[CommonUiProperties.SHOW_TAG_NAMES])
table.repaint()
}
else if (CommonUiProperties.LABELS_LEFT_ALIGNED == property) {
commitCellRenderer.setLeftAligned(table.properties[CommonUiProperties.LABELS_LEFT_ALIGNED])
table.repaint()
}
}
updateTableOnCommitDetailsLoaded(this, table)
return commitCellRenderer
}
override fun getStubValue(model: GraphTableModel): GraphCommitCell = GraphCommitCell("", emptyList(), emptyList())
}
internal object Author : VcsLogDefaultColumn<String>("Default.Author", VcsLogBundle.message("vcs.log.column.author")),
VcsLogMetadataColumn {
override fun getValue(model: GraphTableModel, row: Int) = getValue(model, model.getCommitMetadata(row, true))
override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata) = CommitPresentationUtil.getAuthorPresentation(commit)
override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer {
updateTableOnCommitDetailsLoaded(this, table)
return VcsLogStringCellRenderer(true)
}
override fun getStubValue(model: GraphTableModel) = ""
}
internal object Date : VcsLogDefaultColumn<String>("Default.Date", VcsLogBundle.message("vcs.log.column.date")), VcsLogMetadataColumn {
override fun getValue(model: GraphTableModel, row: Int): String {
return getValue(model, model.getCommitMetadata(row, true))
}
override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): String {
val properties = model.properties
val preferCommitDate = properties.exists(CommonUiProperties.PREFER_COMMIT_DATE) && properties.get(CommonUiProperties.PREFER_COMMIT_DATE)
val timeStamp = if (preferCommitDate) commit.commitTime else commit.authorTime
return if (timeStamp < 0) "" else JBDateFormat.getFormatter().formatPrettyDateTime(timeStamp)
}
override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer {
doOnPropertyChange(table) { property ->
if (property == CommonUiProperties.PREFER_COMMIT_DATE && table.getTableColumn(this@Date) != null) {
table.repaint()
}
}
updateTableOnCommitDetailsLoaded(this, table)
return VcsLogStringCellRenderer(
withSpeedSearchHighlighting = true,
contentSampleProvider = {
if (DateTimeFormatManager.getInstance().isPrettyFormattingAllowed) {
null
}
else {
JBDateFormat.getFormatter().formatDateTime(DateFormatUtil.getSampleDateTime())
}
}
)
}
override fun getStubValue(model: GraphTableModel): String = ""
}
internal object Hash : VcsLogDefaultColumn<String>("Default.Hash", VcsLogBundle.message("vcs.log.column.hash")), VcsLogMetadataColumn {
override fun getValue(model: GraphTableModel, row: Int): String = getValue(model, model.getCommitMetadata(row, true))
override fun getValue(model: GraphTableModel, commit: VcsCommitMetadata) = commit.id.toShortString()
override fun createTableCellRenderer(table: VcsLogGraphTable): TableCellRenderer {
updateTableOnCommitDetailsLoaded(this, table)
return VcsLogStringCellRenderer(
withSpeedSearchHighlighting = true,
contentSampleProvider = { "e".repeat(VcsLogUtil.SHORT_HASH_LENGTH) }
)
}
override fun getStubValue(model: GraphTableModel): String = ""
}
private fun updateTableOnCommitDetailsLoaded(column: VcsLogColumn<*>, graphTable: VcsLogGraphTable) {
val miniDetailsLoadedListener = Runnable { graphTable.onColumnDataChanged(column) }
graphTable.logData.miniDetailsGetter.addDetailsLoadedListener(miniDetailsLoadedListener)
Disposer.register(graphTable) {
graphTable.logData.miniDetailsGetter.removeDetailsLoadedListener(miniDetailsLoadedListener)
}
}
private fun doOnPropertyChange(graphTable: VcsLogGraphTable, listener: (VcsLogUiProperties.VcsLogUiProperty<*>) -> Unit) {
val propertiesChangeListener = object : VcsLogUiProperties.PropertiesChangeListener {
override fun <T : Any?> onPropertyChanged(property: VcsLogUiProperties.VcsLogUiProperty<T>) {
listener(property)
}
}
graphTable.properties.addChangeListener(propertiesChangeListener)
Disposer.register(graphTable) {
graphTable.properties.removeChangeListener(propertiesChangeListener)
}
}
@ApiStatus.Internal
interface VcsLogMetadataColumn {
@ApiStatus.Internal
fun getValue(model: GraphTableModel, commit: VcsCommitMetadata): @NlsSafe String
} | platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/column/VcsLogDefaultColumn.kt | 3869482390 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.impl
import com.intellij.diff.util.Side
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.*
import com.intellij.openapi.vcs.changes.conflicts.ChangelistConflictTracker
import com.intellij.openapi.vcs.ex.ExclusionState
import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PairFunction
import com.intellij.util.containers.MultiMap
import com.intellij.util.ui.ThreeStateCheckBox
object PartialChangesUtil {
private val LOG = Logger.getInstance(PartialChangesUtil::class.java)
@JvmStatic
fun getPartialTracker(project: Project, change: Change): PartialLocalLineStatusTracker? {
val file = getVirtualFile(change) ?: return null
return getPartialTracker(project, file)
}
@JvmStatic
fun getPartialTracker(project: Project, file: VirtualFile): PartialLocalLineStatusTracker? {
val tracker = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(file)
return tracker as? PartialLocalLineStatusTracker
}
@JvmStatic
fun getVirtualFile(change: Change): VirtualFile? {
val revision = change.afterRevision as? CurrentContentRevision
return revision?.virtualFile
}
@JvmStatic
fun processPartialChanges(project: Project,
changes: Collection<Change>,
executeOnEDT: Boolean,
partialProcessor: PairFunction<in List<ChangeListChange>, in PartialLocalLineStatusTracker, Boolean>): List<Change> {
if (!LineStatusTrackerManager.getInstance(project).arePartialChangelistsEnabled() ||
changes.none { it is ChangeListChange }) {
return changes.toMutableList()
}
val otherChanges = mutableListOf<Change>()
val task = Runnable {
val partialChangesMap = MultiMap<VirtualFile, ChangeListChange>()
for (change in changes) {
if (change is ChangeListChange) {
val virtualFile = getVirtualFile(change)
if (virtualFile != null) {
partialChangesMap.putValue(virtualFile, change)
}
else {
otherChanges.add(change.change)
}
}
else {
otherChanges.add(change)
}
}
val lstManager = LineStatusTrackerManager.getInstance(project)
for ((virtualFile, value) in partialChangesMap.entrySet()) {
@Suppress("UNCHECKED_CAST") val partialChanges = value as List<ChangeListChange>
val actualChange = partialChanges[0].change
val tracker = lstManager.getLineStatusTracker(virtualFile) as? PartialLocalLineStatusTracker
if (tracker == null ||
!partialProcessor.`fun`(partialChanges, tracker)) {
otherChanges.add(actualChange)
}
}
}
if (executeOnEDT && !ApplicationManager.getApplication().isDispatchThread) {
ApplicationManager.getApplication().invokeAndWait(task)
}
else {
task.run()
}
return otherChanges
}
@JvmStatic
fun runUnderChangeList(project: Project,
targetChangeList: LocalChangeList?,
task: Runnable) {
computeUnderChangeList(project, targetChangeList) {
task.run()
null
}
}
@JvmStatic
fun <T> computeUnderChangeList(project: Project,
targetChangeList: LocalChangeList?,
task: Computable<T>): T {
val changeListManager = ChangeListManagerEx.getInstanceEx(project)
val oldDefaultList = changeListManager.defaultChangeList
if (targetChangeList == null ||
targetChangeList == oldDefaultList ||
!changeListManager.areChangeListsEnabled()) {
return task.compute()
}
switchChangeList(changeListManager, targetChangeList, oldDefaultList)
val clmConflictTracker = ChangelistConflictTracker.getInstance(project)
try {
clmConflictTracker.setIgnoreModifications(true)
return task.compute()
}
finally {
clmConflictTracker.setIgnoreModifications(false)
restoreChangeList(changeListManager, targetChangeList, oldDefaultList)
}
}
suspend fun <T> underChangeList(project: Project,
targetChangeList: LocalChangeList?,
task: suspend () -> T): T {
val changeListManager = ChangeListManagerEx.getInstanceEx(project)
val oldDefaultList = changeListManager.defaultChangeList
if (targetChangeList == null ||
targetChangeList == oldDefaultList ||
!changeListManager.areChangeListsEnabled()) {
return task()
}
switchChangeList(changeListManager, targetChangeList, oldDefaultList)
val clmConflictTracker = ChangelistConflictTracker.getInstance(project)
try {
clmConflictTracker.setIgnoreModifications(true)
return task()
}
finally {
clmConflictTracker.setIgnoreModifications(false)
restoreChangeList(changeListManager, targetChangeList, oldDefaultList)
}
}
@JvmStatic
fun <T> computeUnderChangeListSync(project: Project,
targetChangeList: LocalChangeList?,
task: Computable<T>): T {
val changeListManager = ChangeListManagerEx.getInstanceEx(project)
val oldDefaultList = changeListManager.defaultChangeList
if (targetChangeList == null ||
!changeListManager.areChangeListsEnabled()) {
return task.compute()
}
switchChangeList(changeListManager, targetChangeList, oldDefaultList)
val clmConflictTracker = ChangelistConflictTracker.getInstance(project)
try {
clmConflictTracker.setIgnoreModifications(true)
return task.compute()
}
finally {
clmConflictTracker.setIgnoreModifications(false)
if (ApplicationManager.getApplication().isReadAccessAllowed) {
LOG.warn("Can't wait till changes are applied while holding read lock", Throwable())
}
else {
ChangeListManagerEx.getInstanceEx(project).waitForUpdate()
}
restoreChangeList(changeListManager, targetChangeList, oldDefaultList)
}
}
private fun switchChangeList(clm: ChangeListManagerEx,
targetChangeList: LocalChangeList,
oldDefaultList: LocalChangeList) {
clm.setDefaultChangeList(targetChangeList, true)
LOG.debug("Active changelist changed: ${oldDefaultList.name} -> ${targetChangeList.name}")
}
private fun restoreChangeList(clm: ChangeListManagerEx,
targetChangeList: LocalChangeList,
oldDefaultList: LocalChangeList) {
val defaultChangeList = clm.defaultChangeList
if (defaultChangeList.id == targetChangeList.id) {
clm.setDefaultChangeList(oldDefaultList, true)
LOG.debug("Active changelist restored: ${targetChangeList.name} -> ${oldDefaultList.name}")
}
else {
LOG.warn(Throwable("Active changelist was changed during the operation. " +
"Expected: ${targetChangeList.name} -> ${oldDefaultList.name}, " +
"actual default: ${defaultChangeList.name}"))
}
}
@JvmStatic
fun convertExclusionState(exclusionState: ExclusionState): ThreeStateCheckBox.State {
return when (exclusionState) {
ExclusionState.ALL_INCLUDED -> ThreeStateCheckBox.State.SELECTED
ExclusionState.ALL_EXCLUDED -> ThreeStateCheckBox.State.NOT_SELECTED
else -> ThreeStateCheckBox.State.DONT_CARE
}
}
@JvmStatic
fun wrapPartialChanges(project: Project, changes: List<Change>): List<Change> {
return changes.map { change -> wrapPartialChangeIfNeeded(project, change) ?: change }
}
private fun wrapPartialChangeIfNeeded(project: Project, change: Change): Change? {
if (change !is ChangeListChange) return null
val afterRevision = change.afterRevision
if (afterRevision !is CurrentContentRevision) return null
val tracker = getPartialTracker(project, change)
if (tracker == null || !tracker.isOperational() || !tracker.hasPartialChangesToCommit()) return null
val partialAfterRevision = PartialContentRevision(project, tracker.virtualFile, change.changeListId, afterRevision)
return ChangeListChange.replaceChangeContents(change, change.beforeRevision, partialAfterRevision)
}
private class PartialContentRevision(val project: Project,
val virtualFile: VirtualFile,
val changeListId: String,
val delegate: ContentRevision) : ContentRevision {
override fun getFile(): FilePath = delegate.file
override fun getRevisionNumber(): VcsRevisionNumber = delegate.revisionNumber
override fun getContent(): String? {
val tracker = getPartialTracker(project, virtualFile)
if (tracker != null && tracker.isOperational() && tracker.hasPartialChangesToCommit()) {
val partialContent = tracker.getChangesToBeCommitted(Side.LEFT, listOf(changeListId), true)
if (partialContent != null) return partialContent
LOG.warn("PartialContentRevision - missing partial content for $tracker")
}
return delegate.content
}
}
} | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/PartialChangesUtil.kt | 53189803 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.training.ifs
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.descendantsOfType
import com.intellij.psi.util.parentsOfType
import org.jetbrains.kotlin.psi.*
import training.featuresSuggester.SuggesterSupport
import training.featuresSuggester.getParentByPredicate
import training.featuresSuggester.getParentOfType
class KotlinSuggesterSupport : SuggesterSupport {
override fun isLoadedSourceFile(file: PsiFile): Boolean {
return file is KtFile && !file.isCompiled && file.isContentsLoaded
}
override fun isIfStatement(element: PsiElement): Boolean {
return element is KtIfExpression
}
override fun isForStatement(element: PsiElement): Boolean {
return element is KtForExpression
}
override fun isWhileStatement(element: PsiElement): Boolean {
return element is KtWhileExpression
}
override fun isCodeBlock(element: PsiElement): Boolean {
return element is KtBlockExpression
}
override fun getCodeBlock(element: PsiElement): PsiElement? {
return element.descendantsOfType<KtBlockExpression>().firstOrNull()
}
override fun getContainingCodeBlock(element: PsiElement): PsiElement? {
return element.getParentOfType<KtBlockExpression>()
}
override fun getParentStatementOfBlock(element: PsiElement): PsiElement? {
return element.parent?.parent
}
override fun getStatements(element: PsiElement): List<PsiElement> {
return if (element is KtBlockExpression) {
element.statements
} else {
emptyList()
}
}
override fun getTopmostStatementWithText(psiElement: PsiElement, text: String): PsiElement? {
val statement = psiElement.getParentByPredicate {
isSupportedStatementToIntroduceVariable(it) && it.text.contains(text) && it.text != text
}
return if (statement is KtCallExpression) {
return statement.parentsOfType<KtDotQualifiedExpression>().lastOrNull() ?: statement
} else {
statement
}
}
override fun isSupportedStatementToIntroduceVariable(element: PsiElement): Boolean {
return element is KtProperty || element is KtIfExpression ||
element is KtCallExpression || element is KtQualifiedExpression ||
element is KtReturnExpression
}
override fun isPartOfExpression(element: PsiElement): Boolean {
return element.getParentOfType<KtExpression>() != null
}
override fun isExpressionStatement(element: PsiElement): Boolean {
return element is KtExpression
}
override fun isVariableDeclaration(element: PsiElement): Boolean {
return element is KtProperty
}
override fun getVariableName(element: PsiElement): String? {
return if (element is KtProperty) {
element.name
} else {
null
}
}
override fun isFileStructureElement(element: PsiElement): Boolean {
return (element is KtProperty && !element.isLocal) || element is KtNamedFunction || element is KtClass
}
override fun isIdentifier(element: PsiElement): Boolean {
return element is LeafPsiElement && element.elementType.toString() == "IDENTIFIER"
}
override fun isLiteralExpression(element: PsiElement): Boolean {
return element is KtStringTemplateExpression
}
}
| plugins/kotlin/features-trainer/src/org/jetbrains/kotlin/training/ifs/KotlinSuggesterSupport.kt | 3422267086 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.completion.feature.impl
class CompletionFactors(proximity: Set<String>, relevance: Set<String>) {
private val knownFactors: Set<String> = HashSet<String>().apply {
addAll(proximity.map { "prox_$it" })
addAll(relevance)
}
fun unknownFactors(factors: Set<String>): List<String> {
var result: MutableList<String>? = null
for (factor in factors) {
val normalized = factor.substringBefore('@')
if (normalized !in knownFactors) {
result = (result ?: mutableListOf()).apply { add(normalized) }
}
}
return if (result != null) result else emptyList()
}
}
| plugins/stats-collector/features/src/com/jetbrains/completion/feature/impl/CompletionFactors.kt | 3160872319 |
package org.thoughtcrime.securesms.stories
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.annotation.Px
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.ColorUtils
import androidx.core.view.doOnNextLayout
import androidx.core.view.isVisible
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost
import org.thoughtcrime.securesms.fonts.TextFont
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.linkpreview.LinkPreviewViewModel
import org.thoughtcrime.securesms.mediasend.v2.text.TextAlignment
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationState
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryScale
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryTextWatcher
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture
import org.thoughtcrime.securesms.util.visible
import java.util.Locale
class StoryTextPostView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
inflate(context, R.layout.stories_text_post_view, this)
}
private var textAlignment: TextAlignment? = null
private val backgroundView: ImageView = findViewById(R.id.text_story_post_background)
private val textView: StoryTextView = findViewById(R.id.text_story_post_text)
private val linkPreviewView: StoryLinkPreviewView = findViewById(R.id.text_story_post_link_preview)
private var isPlaceholder: Boolean = true
init {
TextStoryTextWatcher.install(textView)
}
fun showCloseButton() {
linkPreviewView.setCanClose(true)
}
fun hideCloseButton() {
linkPreviewView.setCanClose(false)
}
fun setTypeface(typeface: Typeface) {
textView.typeface = typeface
}
private fun setPostBackground(drawable: Drawable) {
backgroundView.setImageDrawable(drawable)
}
private fun setTextColor(@ColorInt color: Int, isPlaceholder: Boolean) {
if (isPlaceholder) {
textView.setTextColor(ColorUtils.setAlphaComponent(color, 0x99))
} else {
textView.setTextColor(color)
}
}
private fun setText(text: CharSequence, isPlaceholder: Boolean) {
this.isPlaceholder = isPlaceholder
textView.text = text
}
private fun setTextSize(@Px textSize: Float) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
}
private fun setTextGravity(textAlignment: TextAlignment) {
textView.gravity = textAlignment.gravity
}
private fun setTextScale(scalePercent: Int) {
val scale = TextStoryScale.convertToScale(scalePercent)
textView.scaleX = scale
textView.scaleY = scale
}
private fun setTextVisible(visible: Boolean) {
textView.visible = visible
}
private fun setTextBackgroundColor(@ColorInt color: Int) {
textView.setWrappedBackgroundColor(color)
}
fun bindFromCreationState(state: TextStoryPostCreationState) {
textAlignment = state.textAlignment
setPostBackground(state.backgroundColor.chatBubbleMask)
setText(
state.body.ifEmpty {
context.getString(R.string.TextStoryPostCreationFragment__tap_to_add_text)
}.let {
if (state.textFont.isAllCaps) {
it.toString().uppercase(Locale.getDefault())
} else {
it
}
},
state.body.isEmpty()
)
setTextColor(state.textForegroundColor, state.body.isEmpty())
setTextBackgroundColor(state.textBackgroundColor)
setTextGravity(state.textAlignment)
setTextScale(state.textScale)
postAdjustLinkPreviewTranslationY()
}
fun bindFromStoryTextPost(storyTextPost: StoryTextPost) {
visible = true
linkPreviewView.visible = false
textAlignment = TextAlignment.CENTER
val font = TextFont.fromStyle(storyTextPost.style)
setPostBackground(ChatColors.forChatColor(ChatColors.Id.NotSet, storyTextPost.background).chatBubbleMask)
if (font.isAllCaps) {
setText(storyTextPost.body.uppercase(Locale.getDefault()), false)
} else {
setText(storyTextPost.body, false)
}
setTextColor(storyTextPost.textForegroundColor, false)
setTextBackgroundColor(storyTextPost.textBackgroundColor)
setTextGravity(TextAlignment.CENTER)
hideCloseButton()
postAdjustLinkPreviewTranslationY()
}
fun bindLinkPreview(linkPreview: LinkPreview?): ListenableFuture<Boolean> {
return linkPreviewView.bind(linkPreview, View.GONE)
}
fun bindLinkPreviewState(linkPreviewState: LinkPreviewViewModel.LinkPreviewState, hiddenVisibility: Int) {
linkPreviewView.bind(linkPreviewState, hiddenVisibility)
}
fun postAdjustLinkPreviewTranslationY() {
setTextVisible(canDisplayText())
doOnNextLayout {
adjustLinkPreviewTranslationY()
}
}
fun setTextViewClickListener(onClickListener: OnClickListener) {
setOnClickListener(onClickListener)
}
fun setLinkPreviewCloseListener(onClickListener: OnClickListener) {
linkPreviewView.setOnCloseClickListener(onClickListener)
}
fun setLinkPreviewClickListener(onClickListener: OnClickListener?) {
linkPreviewView.setOnClickListener(onClickListener)
}
fun showPostContent() {
textView.alpha = 1f
linkPreviewView.alpha = 1f
}
fun hidePostContent() {
textView.alpha = 0f
linkPreviewView.alpha = 0f
}
private fun canDisplayText(): Boolean {
return !(linkPreviewView.isVisible && isPlaceholder)
}
private fun adjustLinkPreviewTranslationY() {
val backgroundHeight = backgroundView.measuredHeight
val textHeight = if (canDisplayText()) textView.measuredHeight * textView.scaleY else 0f
val previewHeight = if (linkPreviewView.visible) linkPreviewView.measuredHeight else 0
val availableHeight = backgroundHeight - textHeight
if (availableHeight >= previewHeight) {
val totalContentHeight = textHeight + previewHeight
val topAndBottomMargin = backgroundHeight - totalContentHeight
val margin = topAndBottomMargin / 2f
linkPreviewView.translationY = -margin
val originPoint = textView.measuredHeight / 2f
val desiredPoint = (textHeight / 2f) + margin
textView.translationY = desiredPoint - originPoint
} else {
linkPreviewView.translationY = 0f
val originPoint = textView.measuredHeight / 2f
val desiredPoint = backgroundHeight / 2f
textView.translationY = desiredPoint - originPoint
}
}
}
| app/src/main/java/org/thoughtcrime/securesms/stories/StoryTextPostView.kt | 3370443170 |
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.java
import io.ktor.client.call.*
import io.ktor.client.engine.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.http.HttpHeaders
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import java.net.http.HttpRequest
import java.time.*
import java.util.*
import kotlin.coroutines.*
internal val DISALLOWED_HEADERS = TreeSet(String.CASE_INSENSITIVE_ORDER).apply {
addAll(
setOf(
HttpHeaders.Connection,
HttpHeaders.ContentLength,
HttpHeaders.Date,
HttpHeaders.Expect,
HttpHeaders.From,
HttpHeaders.Host,
HttpHeaders.Upgrade,
HttpHeaders.Via,
HttpHeaders.Warning
)
)
}
@OptIn(InternalAPI::class)
internal fun HttpRequestData.convertToHttpRequest(callContext: CoroutineContext): HttpRequest {
val builder = HttpRequest.newBuilder(url.toURI())
with(builder) {
getCapabilityOrNull(HttpTimeout)?.let { timeoutAttributes ->
timeoutAttributes.requestTimeoutMillis?.let {
if (!isTimeoutInfinite(it)) timeout(Duration.ofMillis(it))
}
}
mergeHeaders(headers, body) { key, value ->
if (!DISALLOWED_HEADERS.contains(key)) {
header(key, value)
}
}
method(method.value, body.convertToHttpRequestBody(callContext))
}
return builder.build()
}
@OptIn(DelicateCoroutinesApi::class)
internal fun OutgoingContent.convertToHttpRequestBody(
callContext: CoroutineContext
): HttpRequest.BodyPublisher = when (this) {
is OutgoingContent.ByteArrayContent -> HttpRequest.BodyPublishers.ofByteArray(bytes())
is OutgoingContent.ReadChannelContent -> JavaHttpRequestBodyPublisher(
coroutineContext = callContext,
contentLength = contentLength ?: -1
) { readFrom() }
is OutgoingContent.WriteChannelContent -> JavaHttpRequestBodyPublisher(
coroutineContext = callContext,
contentLength = contentLength ?: -1
) { GlobalScope.writer(callContext) { writeTo(channel) }.channel }
is OutgoingContent.NoContent -> HttpRequest.BodyPublishers.noBody()
else -> throw UnsupportedContentTypeException(this)
}
| ktor-client/ktor-client-java/jvm/src/io/ktor/client/engine/java/JavaHttpRequest.kt | 2511483036 |
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.cio.backend
import io.ktor.network.sockets.*
import io.ktor.util.network.*
internal actual fun SocketAddress.toNetworkAddress(): NetworkAddress {
// Do not read the hostname here because that may trigger a name service reverse lookup.
return toJavaAddress() as? java.net.InetSocketAddress ?: error("Expected inet socket address")
}
| ktor-server/ktor-server-cio/jvm/src/io/ktor/server/cio/backend/SocketAddressUtilsJvm.kt | 272394810 |
/*
* Copyright 2021 LinkedIn Corporation
* All Rights Reserved.
*
* Licensed under the BSD 2-Clause License (the "License"). See License in the project root for
* license information.
*/
package com.linkedin.android.litr.frameextract.behaviors
import android.graphics.Bitmap
import com.linkedin.android.litr.ExperimentalFrameExtractorApi
import com.linkedin.android.litr.frameextract.FrameExtractParameters
/**
* An interface used by [FrameExtractBehavior] to notify the job of the status of individual frame extraction.
*/
interface FrameExtractBehaviorFrameListener {
fun onFrameExtracted(bitmap: Bitmap)
fun onFrameFailed()
}
/**
* Provides a way to customize frame extraction behavior.
*
* All methods are guaranteed to be called on the same thread, but the thread will not be the main thread.
*/
@ExperimentalFrameExtractorApi
interface FrameExtractBehavior {
/**
* Perform frame extraction work here, and notify [listener] for each frame extracted. This method is called only once.
*
* For long-running operations, [Thread.isInterrupted] should be checked periodically. If interrupted, implementation should return false from this method.
*
* @return Return true if extraction is completed/scheduled, false if it was canceled.
*/
fun extract(params: FrameExtractParameters, listener: FrameExtractBehaviorFrameListener): Boolean
/**
* Called when this behavior should clean up any associated resources.
*/
fun release()
}
| litr/src/main/java/com/linkedin/android/litr/frameextract/behaviors/FrameExtractBehavior.kt | 1778125284 |
package com.squareup.wire
import com.squareup.wire.protos.kotlin.person.Person
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class KotlinEnumTest {
@Test fun getValue() {
assertThat(Person.PhoneType.HOME.value).isEqualTo(1)
}
@Test fun fromValue() {
assertThat(Person.PhoneType.fromValue(1)).isEqualTo(Person.PhoneType.HOME)
}
}
| wire-tests/src/test/java/com/squareup/wire/KotlinEnumTest.kt | 569530013 |
package fredboat.testutil.config
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import com.fredboat.sentinel.SentinelExchanges
import com.fredboat.sentinel.entities.SentinelHello
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.amqp.core.Binding
import org.springframework.amqp.core.BindingBuilder
import org.springframework.amqp.core.DirectExchange
import org.springframework.amqp.core.Queue
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter
import org.springframework.amqp.support.converter.MessageConverter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
import java.net.InetAddress
import java.util.*
@TestConfiguration
class RabbitConfig {
companion object {
private val log: Logger = LoggerFactory.getLogger(RabbitConfig::class.java)
}
@Bean
fun sentinelId(): String {
val rand = UUID.randomUUID().toString().replace("-", "").substring(0, 8)
val id = "${InetAddress.getLocalHost().hostName}-$rand"
log.info("Unique identifier for this session: $id")
return id
}
@Bean
fun jsonMessageConverter(): MessageConverter {
// We must register this Kotlin module to get deserialization to work with data classes
return Jackson2JsonMessageConverter(ObjectMapper().registerKotlinModule())
}
@Bean
fun eventQueue() = Queue(SentinelExchanges.EVENTS, false)
@Bean
fun requestExchange() = DirectExchange(SentinelExchanges.REQUESTS)
@Bean
fun requestQueue() = Queue(SentinelExchanges.REQUESTS, false)
@Bean
fun requestBinding(
@Qualifier("requestExchange") requestExchange: DirectExchange,
@Qualifier("requestQueue") requestQueue: Queue,
@Qualifier("sentinelId") key: String
): Binding {
log.info("BINDING")
return BindingBuilder.bind(requestQueue).to(requestExchange).with(key)
}
@Component
class HelloSender(
private val rabbitTemplate: RabbitTemplate,
@Qualifier("sentinelId")
private val key: String) {
fun send() {
rabbitTemplate.convertAndSend(SentinelExchanges.EVENTS, SentinelHello(
0,
1,
1,
key
))
}
}
} | FredBoat/src/test/java/fredboat/testutil/config/RabbitConfig.kt | 2147100305 |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gradle.replicator.codegen
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.random.Random
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.KVisibility
import kotlin.reflect.full.declaredFunctions
import kotlin.reflect.jvm.jvmErasure
/**
* Utility class to randomly pick a class from a list of imported modules and a classloader.
*
* The class picker will use and environment which is defined by a class loader capable of loading classes and
* a list of modules each with a list of class names that can be loaded by the previously mentioned class loader.
*
* The picked class is constrained by a few factors to be able to be used in code generation. In particular, the class
* must have the following attributes :
* <ul>
* <li> must be public
* <li> must be a class, non abstract
* <li> must have a valid constructor that takes arguments that are themselves following the same constraints.
* <li> must not be deprecated.
* <li> must have at least one function that can be called from generated code (with parameters all following the
* same constraints).
* </ul>
*/
open class ImportClassPicker(
private val classLoader: ClassLoader,
private val modules: List<GeneratorDriver.ModuleImport>,
private val verifyClasses: Boolean = true) {
/**
* set to true if we cannot pick any class in this environment, to avoid rescanning needlessly
*/
private val emptyPicker = AtomicBoolean(false)
/**
* pick a class using the [random] randomizer.
*
* @param random the randomizer to use to pick up the class.
* @return a picked class that can be used to generate code with or null if none can be found.
*/
open fun pickClass(random: Random): ClassModel<*>? {
if (emptyPicker.get() || modules.isEmpty()) return null
var moduleIndex = random.nextInt(modules.size)
val startModuleIndex = moduleIndex
var selectedModule = modules[moduleIndex]
var classIndex = random.nextInt(selectedModule.classes.size)
var startClassIndexInModule = classIndex
var className = selectedModule.classes[classIndex]
var loadedClass= loadClass(className)
var classModel = if (loadedClass != null) {
if (verifyClasses) isClassEligible(loadedClass) else loadModel(loadedClass)
} else null
while (classModel == null) {
classIndex = (classIndex + 1) % selectedModule.classes.size
if (classIndex == startClassIndexInModule) {
moduleIndex = (moduleIndex + 1) % modules.size
if (moduleIndex == startModuleIndex) {
emptyPicker.set(true)
return null
}
selectedModule = modules[moduleIndex]
classIndex = random.nextInt(selectedModule.classes.size)
startClassIndexInModule = classIndex
}
className = selectedModule.classes[classIndex]
loadedClass= loadClass(className)
if (loadedClass != null) {
classModel = isClassEligible(loadedClass)
}
}
return classModel
}
/**
* Loads a class from the classloader.
*
* @param name the class name to load.
* @return the loaded class or null if the class cannot be loaded.
*/
private fun loadClass(name: String): Class<*>? = try {
classLoader.loadClass(name)
// some imported modules are not packaged correctly and have references to classes not present.
// this is usually not a problem as those references are probably dead code but the randomizer can pick them
// nonetheless so we should handle these class loading failures graciously.
} catch (e: ClassNotFoundException) {
null
} catch (e: NoClassDefFoundError) {
null
}
/**
* creates a [ClassModel] without verify if the classes are suitable for use in code generation.
*/
private fun loadModel(kClass: Class<*>): ClassModel<*>? {
val selectedType = kClass.kotlin
try {
return ClassModel<Any>(selectedType,
selectedType.constructors.first(),
selectedType.declaredFunctions)
} catch (e: Exception) {
println("Caught !")
return null
} catch (e: Error) {
println("Caught !")
return null
}
}
/**
* Returns true if the class is eligible to used for code generation. It must follows all the constraints
* described in the class comments.
*/
private fun isClassEligible(kClass: Class<*>?): ClassModel<*>? {
try {
// if the class loader that actually loaded the class is a parent class loader like the boot
// classpath, do not use the class as it is probably a base JDK class version rather than
// android specific one.
if (kClass?.classLoader != classLoader) return null
// avoid picking up kotlin.* as it is problematic when using java code generation.
if (kClass.packageName.startsWith("kotlin")) return null
if (!kClass.isInterface
&& !kClass.isAnnotation) {
val selectedType = kClass.kotlin
val declaredFunctions = selectedType.declaredFunctions
if (!selectedType.isAbstract
&& isClassHierarchySafe(selectedType.java)
&& selectedType.visibility == KVisibility.PUBLIC
&& declaredFunctions.isNotEmpty()
&& selectedType.isNotDeprecated()
&& selectedType.isNotOptInType()) {
val constructor = selectedType.findSuitableConstructor(mutableListOf())
?: return null
val suitableMethodsToCall = findSuitableMethodsToCall(declaredFunctions)
if (suitableMethodsToCall.isEmpty()) return null
return ClassModel<Any>(selectedType, constructor, suitableMethodsToCall)
}
}
return null
// A number of exceptions can be thrown by kotlin reflection.
// Some of these exceptions are warranted like ClassNotFoundException which is due to faulty packaging
// of dependencies. However, some like the java.lang.reflect.* ones are linked to features not implemented
// in the kotlin reflection part or bugs in its implementation.
} catch (e: Exception) {
return null
} catch (e: Error) {
return null
}
}
private fun isClassHierarchySafe(type: Class<*>): Boolean {
if (!type.interfaces.all { intf -> isClassHierarchySafe(intf)}) return false
return isTypeSafe(type) && (type.superclass == null || isClassHierarchySafe(type.superclass))
}
private fun findSuitableMethodsToCall(methods: Collection<KFunction<*>>): List<KFunction<*>> =
methods.filter {
(it.isNotDeprecated()
&& it.isPublic()
&& it.allParametersCanBeInstantiated(mutableListOf())
&& it.parameters.all { parameter -> isTypeSafe(parameter.type.jvmErasure.java) }
&& isTypeSafe(it.returnType.jvmErasure.java)
&& !it.isSuspend
&& (it.parameters.any { parameter -> parameter.kind == KParameter.Kind.INSTANCE }))
}
private fun isTypeSafe(type: Class<*>): Boolean =
type.classLoader == classLoader
|| type.isPrimitive
|| type.packageName == "java.lang"
|| type.packageName == "java.util"
} | code/codegen/src/main/kotlin/com/android/gradle/replicator/codegen/ImportClassPicker.kt | 1420274216 |
package com.phapps.elitedangerous.companion.ui
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import com.phapps.elitedangerous.companion.R
import com.phapps.elitedangerous.companion.ui.galnet.GalNetFeedFragment
import com.phapps.elitedangerous.companion.ui.settings.SettingsActivity
import com.phapps.elitedangerous.companion.util.SharedPrefsHelper
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import javax.inject.Inject
/**
* An [AppCompatActivity] that contains a [NavigationView] and a content
* [android.widget.FrameLayout] to hold different [android.app.Fragment]s.
*
* Provides a `Settings` [Menu] option that starts the [SettingsActivity] when selected.
*/
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener,
HasSupportFragmentInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
lateinit var navigationController: NavigationController
@Inject
lateinit var sharedPrefsHelper: SharedPrefsHelper
override fun supportFragmentInjector(): AndroidInjector<Fragment> {
return dispatchingAndroidInjector
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
toggle.isDrawerIndicatorEnabled = false
toggle.setToolbarNavigationClickListener {
drawer_layout.openDrawer(GravityCompat.START)
toggle.syncState()
}
toggle.syncState()
drawer_layout.addDrawerListener(toggle)
nav_view.setNavigationItemSelectedListener(this)
if (savedInstanceState == null) {
nav_view.menu?.getItem(0)?.isChecked = true
var fragment = supportFragmentManager.findFragmentByTag(GalNetFeedFragment.TAG)
if (fragment == null) {
fragment = GalNetFeedFragment.newInstance()
}
supportFragmentManager.beginTransaction().replace(R.id.frame_content, fragment,
GalNetFeedFragment.TAG).commit()
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
startActivity(Intent(this@MainActivity, SettingsActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var handled = false
when (item.itemId) {
R.id.nav_galnet -> {
handled = true
navigationController.navigateToGalNet()
}
R.id.nav_item_profile -> {
handled = onProfileClicked()
}
R.id.nav_settings -> {
handled = true
onSettingsClicked()
}
R.id.nav_item_edsm_system_search -> {
handled = true
navigationController.navigateToSystemSearch()
}
R.id.nav_item_edsm_calculate_route -> {
handled = true
navigationController.navigateToRouteCalculation()
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return handled
}
private fun onProfileClicked(): Boolean {
var handled = false
if (sharedPrefsHelper.isEdcEnabled()) {
handled = true
navigationController.navigateToProfile()
} else {
val snackbar: Snackbar = Snackbar.make(nav_view, R.string.snack_edsm_not_configured,
Snackbar.LENGTH_LONG)
snackbar.setAction(R.string.snack_action_settings, {
startActivity(Intent(this@MainActivity, SettingsActivity::class.java))
})
snackbar.show()
}
return handled
}
private fun onSettingsClicked() {
startActivity(Intent(this, SettingsActivity::class.java))
}
}
| app/src/main/java/com/phapps/elitedangerous/companion/ui/MainActivity.kt | 3169601442 |
fun main(args: Array<String>) {
println(<selection>a1</selection>)
println(a2)
} | plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/NoExplicitReceiversUnresolved.kt | 3008597750 |
// FIR_COMPARISON
package first
import second.testFun
fun test() {
testFun().<caret>
}
// EXIST: testMethod | plugins/kotlin/completion/tests/testData/basic/multifile/CompletionOnImportedFunction/CompletionOnImportedFunction.kt | 108804046 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.