content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
expect class <!LINE_MARKER("descr='Has actuals in JVM'")!>WithConstructor<!>(x: Int, s: String) {
val <!LINE_MARKER("descr='Has actuals in JVM'")!>x<!>: Int
val <!LINE_MARKER("descr='Has actuals in JVM'")!>s<!>: String
} | plugins/kotlin/idea/tests/testData/multiModuleLineMarker/expectConstructorWithProperties/common/common.kt | 3003440680 |
/*
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.container.tools.core.analytics
import com.google.common.truth.Truth.assertThat
import com.google.container.tools.core.properties.PluginPropertiesFileReader
import com.google.container.tools.test.ContainerToolsRule
import com.google.container.tools.test.TestService
import com.intellij.ide.util.PropertiesComponent
import io.mockk.every
import io.mockk.impl.annotations.MockK
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* Tests for [UsageTrackerManagerService].
*/
class UsageTrackerManagerServiceTest {
@get:Rule
val containerToolsRule = ContainerToolsRule(this)
@TestService
@MockK
private lateinit var propertyReader: PluginPropertiesFileReader
@MockK
private lateinit var trackingPreferenceProperty: PropertiesComponent
private lateinit var usageTrackerManagerService: UsageTrackerManagerService
@Before
fun setUp() {
usageTrackerManagerService = UsageTrackerManagerService(trackingPreferenceProperty)
}
@Test
fun `usage tracking is not available and not enabled in unit test mode`() {
// Set the analytics ID to a proper value
val analyticsId = "UA-12345"
mockAnalyticsId(analyticsId)
assertThat(usageTrackerManagerService.isUsageTrackingAvailable()).isFalse()
assertThat(usageTrackerManagerService.isUsageTrackingEnabled()).isFalse()
}
@Test
fun `when user data tracking preference is stored true then tracking is opted in`() {
every {
trackingPreferenceProperty.getBoolean(
"GOOGLE_CLOUD_TOOLS_USAGE_TRACKER_OPT_IN",
false
)
} answers { true }
assertThat(usageTrackerManagerService.isTrackingOptedIn()).isTrue()
}
@Test
fun `when user data tracking preference is stored false then tracking is not opted in`() {
every {
trackingPreferenceProperty.getBoolean(
"GOOGLE_CLOUD_TOOLS_USAGE_TRACKER_OPT_IN",
false
)
} answers { false }
assertThat(usageTrackerManagerService.isTrackingOptedIn()).isFalse()
}
@Test
fun `get analytics ID when ID has been substituted returns analytics ID`() {
val analyticsId = "UA-12345"
mockAnalyticsId(analyticsId)
assertThat(usageTrackerManagerService.getAnalyticsId()).isEqualTo(analyticsId)
}
@Test
fun `get analytics ID when property placeholder has not been substituted returns null`() {
val analyticsIdPlaceholder = "\${analyticsId}"
every { propertyReader.getPropertyValue("analytics.id") } answers { analyticsIdPlaceholder }
assertThat(usageTrackerManagerService.getAnalyticsId()).isNull()
}
private fun mockAnalyticsId(analyticsId: String) {
every { propertyReader.getPropertyValue("analytics.id") } answers { analyticsId }
}
}
| core/src/test/kotlin/com/google/container/tools/core/analytics/UsageTrackerManagerServiceTest.kt | 2204414940 |
/*
* Copyright (C) 2017 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.room.integration.kotlintestapp.test
import android.support.test.InstrumentationRegistry
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.room.integration.kotlintestapp.TestDatabase
import androidx.room.integration.kotlintestapp.dao.BooksDao
import org.junit.After
import org.junit.Before
import org.junit.Rule
abstract class TestDatabaseTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
protected lateinit var database: TestDatabase
protected lateinit var booksDao: BooksDao
@Before
@Throws(Exception::class)
fun setUp() {
database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
TestDatabase::class.java)
// allowing main thread queries, just for testing
.allowMainThreadQueries()
.build()
booksDao = database.booksDao()
}
@After
@Throws(Exception::class)
fun tearDown() {
database.close()
}
}
| room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/test/TestDatabaseTest.kt | 364994214 |
package de.markusfisch.android.binaryeye.database
import android.app.Activity
import android.os.Environment
import de.markusfisch.android.binaryeye.io.writeExternalFile
import java.io.File
import java.io.FileInputStream
fun Activity.exportDatabase(fileName: String): Boolean {
val dbFile = File(
Environment.getDataDirectory(),
"//data//${packageName}//databases//${Database.FILE_NAME}"
)
if (!dbFile.exists()) {
return false
}
return writeExternalFile(
fileName,
"application/vnd.sqlite3"
) {
FileInputStream(dbFile).copyTo(it)
}
}
| app/src/main/kotlin/de/markusfisch/android/binaryeye/database/Export.kt | 1418136848 |
package org.jetbrains.protocolModelGenerator
import org.jetbrains.jsonProtocol.ItemDescriptor
import org.jetbrains.jsonProtocol.ProtocolMetaModel
interface ResolveAndGenerateScope {
fun getDomainName(): String
fun getTypeDirection(): TypeData.Direction
fun <T : ItemDescriptor> resolveType(typedObject: T): TypeDescriptor = throw UnsupportedOperationException()
open fun generateNestedObject(description: String?, properties: List<ProtocolMetaModel.ObjectProperty>?): BoxableType = throw UnsupportedOperationException()
}
| platform/script-debugger/protocol/protocol-model-generator/src/ResolveAndGenerateScope.kt | 2740698275 |
package com.malcolmcrum.spacetrader.states
import com.malcolmcrum.spacetrader.model.*
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.RepeatedTest
internal class OpponentGeneratorTest {
private lateinit var opponentGenerator: OpponentGenerator
@BeforeEach
fun setUp() {
opponentGenerator = OpponentGenerator(Difficulty.BEGINNER, 1000, PoliceRecord(),
SolarSystem("system", 0, 0, TechLevel.HI_TECH, Politics.TECHNOCRACY, SystemSize.HUGE, null, null))
}
@RepeatedTest(100)
fun `verify Morgan's Laser never generated`() {
val weapon = opponentGenerator.randomWeapon()
assertFalse(weapon == Weapon.MORGANS)
}
} | src/test/kotlin/com/malcolmcrum/spacetrader/states/OpponentGeneratorTest.kt | 2419633502 |
package com.piticlistudio.playednext.data.repository.datasource.room.genre
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.persistence.room.Room
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.piticlistudio.playednext.data.AppDatabase
import com.piticlistudio.playednext.data.entity.room.RoomGameGenre
import com.piticlistudio.playednext.factory.DomainFactory
import junit.framework.Assert
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
internal class RoomGenreServiceTest {
@JvmField
@Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private var database: AppDatabase? = null
@Before
fun setUp() {
database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDatabase::class.java)
.allowMainThreadQueries()
.build()
}
@Test
fun insertShouldStoreData() {
val data = DomainFactory.makeRoomGenre()
val result = database?.genreRoom()?.insert(data)
Assert.assertNotNull(result)
Assert.assertEquals(data.id, result!!.toInt())
}
fun insertShouldIgnoreIfAlreadyStored() {
val data = DomainFactory.makeRoomGenre()
val id = database?.genreRoom()?.insert(data)
val id2 = database?.genreRoom()?.insert(data)
Assert.assertTrue(id!! > 0L)
Assert.assertEquals(0L, id2)
}
@Test
fun insertGameGenreShouldStoreData() {
val genre = DomainFactory.makeRoomGenre()
val game = DomainFactory.makeGameCache()
val data = RoomGameGenre(game.id, genre.id)
database?.gamesDao()?.insert(game)
database?.genreRoom()?.insert(genre)
val result = database?.genreRoom()?.insertGameGenre(data)
Assert.assertNotNull(result)
Assert.assertTrue(result!! > 0)
}
@Test
fun insertGameDeveloperShouldReplaceDataOnConflict() {
val genre = DomainFactory.makeRoomGenre()
val game = DomainFactory.makeGameCache()
val data = RoomGameGenre(game.id, genre.id)
database?.gamesDao()?.insert(game)
database?.genreRoom()?.insert(genre)
database?.genreRoom()?.insertGameGenre(data)
val result = database?.genreRoom()?.insertGameGenre(data)
Assert.assertNotNull(result)
Assert.assertTrue(result!! > 0)
}
@Test
fun findForGameShouldReturnData() {
val game = DomainFactory.makeGameCache()
val game2 = DomainFactory.makeGameCache()
val genre1 = DomainFactory.makeRoomGenre()
val genre2 = DomainFactory.makeRoomGenre()
val data = RoomGameGenre(game.id, genre1.id)
val data2 = RoomGameGenre(game.id, genre2.id)
val data3 = RoomGameGenre(game2.id, genre1.id)
database?.gamesDao()?.insert(game)
database?.gamesDao()?.insert(game2)
database?.genreRoom()?.insert(genre1)
database?.genreRoom()?.insert(genre2)
database?.genreRoom()?.insertGameGenre(data)
database?.genreRoom()?.insertGameGenre(data2)
database?.genreRoom()?.insertGameGenre(data3)
// Act
val observer = database?.genreRoom()?.findForGame(game.id)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertNotComplete()
assertValue {
it.size == 2 && it.contains(genre1) && it.contains(genre2)
}
}
}
@Test
fun findForGameShouldReturnEmptyListWhenNoMatches() {
val game = DomainFactory.makeGameCache()
database?.gamesDao()?.insert(game)
// Act
// Act
val observer = database?.genreRoom()?.findForGame(game.id)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertNotComplete()
assertValue { it.isEmpty() }
}
}
@After
fun tearDown() {
database?.close()
}
} | app/src/androidTest/java/com/piticlistudio/playednext/data/repository/datasource/room/genre/RoomGenreServiceTest.kt | 2441135604 |
package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MTBadServerSalt @JvmOverloads constructor(badMsgId: Long = 0, badMsqSeqno: Int = 0, errorCode: Int = 0, var newSalt: Long = 0) : MTBadMessage(badMsgId, badMsqSeqno, errorCode) {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeLong(badMsgId, stream)
writeInt(badMsqSeqno, stream)
writeInt(errorCode, stream)
writeLong(newSalt, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
badMsgId = readLong(stream)
badMsqSeqno = readInt(stream)
errorCode = readInt(stream)
newSalt = readLong(stream)
}
override fun toString(): String {
return "bad_server_salt#edab447b"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = -307542917
}
}
| mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTBadServerSalt.kt | 2092865609 |
package com.tekinarslan.kotlinrxjavasample.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.tekinarslan.kotlinrxjavasample.R
import com.tekinarslan.kotlinrxjavasample.model.PhotosDataModel
import kotlinx.android.synthetic.main.item_recycler_view.view.*
import java.util.*
/**
* Created by selimtekinarslan on 6/29/2017.
*/
class RecyclerAdapter(var items: ArrayList<PhotosDataModel>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
override fun getItemCount(): Int {
return items.size
}
fun setItems(items: List<PhotosDataModel>) {
this.items = items as ArrayList<PhotosDataModel>
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_recycler_view, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
items[position].let {
holder?.title?.text = it.title
holder?.subtitle?.text = it.subTitle
Glide.with(holder?.image?.context)
.load(it.thumbnailUrl)
.placeholder(R.mipmap.ic_launcher)
.into(holder?.image)
}
}
class ViewHolder(rootView: View) : RecyclerView.ViewHolder(rootView) {
val card = rootView.card
val title = rootView.title
val subtitle = rootView.subtitle
val image = rootView.image
}
} | app/src/main/java/com/tekinarslan/kotlinrxjavasample/adapter/RecyclerAdapter.kt | 4158619505 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.JavaErrorMessages
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiredModuleFix
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.jrt.JrtFileSystem
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.util.PsiUtil
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName() = "Java Platform Module System"
override fun isAccessible(target: PsiPackage, place: PsiElement) = checkAccess(target, place, true) == null
override fun isAccessible(target: PsiClass, place: PsiElement) = checkAccess(target, place, true) == null
override fun checkAccess(target: PsiPackage, place: PsiElement) = checkAccess(target, place, false)
override fun checkAccess(target: PsiClass, place: PsiElement) = checkAccess(target, place, false)
private fun checkAccess(target: PsiClass, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val targetFile = target.containingFile
if (targetFile is PsiClassOwner) {
return checkAccess(targetFile, useFile, targetFile.packageName, quick)
}
}
return null
}
private fun checkAccess(target: PsiPackage, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
if (useVFile != null) {
val index = ProjectFileIndex.getInstance(useFile.project)
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
if (dirs.isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("package.not.found", target.qualifiedName))
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return if (error == null ||
dirs.size > 1 && dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null }) null
else error
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place)
if (targetModule != null) {
if (targetModule.originalElement == useModule?.originalElement) {
return null
}
if (useModule == null && targetModule.containingFile?.virtualFile?.fileSystem !is JrtFileSystem) {
return null // a target is not on the mandatory module path
}
if (!(targetModule is LightJavaModule || JavaModuleGraphUtil.exports(targetModule, packageName, useModule))) {
return if (quick) ERR
else if (useModule == null) ErrorWithFixes(JavaErrorMessages.message("module.access.from.unnamed", packageName, targetModule.name))
else ErrorWithFixes(JavaErrorMessages.message("module.access.from.named", packageName, targetModule.name, useModule.name))
}
if (useModule == null) {
return null
}
if (!(targetModule.name == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return if (quick) ERR else ErrorWithFixes(
JavaErrorMessages.message("module.access.does.not.read", packageName, targetModule.name, useModule.name),
listOf(AddRequiredModuleFix(useModule, targetModule.name)))
}
}
else if (useModule != null) {
return if (quick) ERR else ErrorWithFixes(JavaErrorMessages.message("module.access.to.unnamed", packageName, useModule.name))
}
return null
}
} | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 3971371055 |
/*
* Copyright 2016 Blue Box Ware
*
* 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.gmail.blueboxware.libgdxplugin.inspections.java
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.utils.isProfilingCall
import com.gmail.blueboxware.libgdxplugin.utils.resolveCall
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiMethodCallExpression
class JavaProfilingCodeInspection : LibGDXJavaBaseInspection() {
override fun getStaticDescription() = message("profiling.code.html.description")
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : JavaElementVisitor() {
override fun visitMethodCallExpression(expression: PsiMethodCallExpression?) {
super.visitMethodCallExpression(expression)
if (expression == null) return
val (receiverClass, method) = expression.resolveCall() ?: return
val className = receiverClass.qualifiedName ?: return
if (isProfilingCall(className, method.name)) {
holder.registerProblem(expression, message("profiling.code.problem.descriptor"))
}
}
}
}
| src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/java/JavaProfilingCodeInspection.kt | 2191969521 |
package me.proxer.library.api.ucp
import me.proxer.library.ProxerTest
import me.proxer.library.entity.user.UserMediaListEntry
import me.proxer.library.enums.Category
import me.proxer.library.enums.MediaState
import me.proxer.library.enums.Medium
import me.proxer.library.enums.UserMediaListFilterType
import me.proxer.library.enums.UserMediaListSortCriteria
import me.proxer.library.enums.UserMediaProgress
import me.proxer.library.runRequest
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
/**
* @author Ruben Gees
*/
class UcpMediaListEndpointTest : ProxerTest() {
private val expectedEntry = UserMediaListEntry(
id = "16257", name = "91 Days", episodeAmount = 12, medium = Medium.ANIMESERIES, state = MediaState.FINISHED,
commentId = "18301850", commentContent = "", mediaProgress = UserMediaProgress.WATCHED, episode = 12,
rating = 0
)
@Test
fun testDefault() {
val (result, _) = server.runRequest("user_media_list.json") {
api.ucp
.mediaList()
.build()
.safeExecute()
}
result.first() shouldBeEqualTo expectedEntry
}
@Test
fun testPath() {
val (_, request) = server.runRequest("user_media_list.json") {
api.ucp.mediaList()
.category(Category.ANIME)
.page(0)
.limit(5)
.search("test")
.searchStart("startTest")
.filter(UserMediaListFilterType.WATCHING)
.sort(UserMediaListSortCriteria.STATE_CHANGE_DATE_ASCENDING)
.includeHentai(true)
.build()
.execute()
}
request.path shouldBeEqualTo """
/api/v1/ucp/list?kat=anime&p=0&limit=5&search=test&search_start=startTest&filter=stateFilter1
&sort=stateChangeDateASC&isH=true
""".trimIndent().replace("\n", "")
}
}
| library/src/test/kotlin/me/proxer/library/api/ucp/UcpMediaListEndpointTest.kt | 3894522770 |
package vn.tiki.architecture.redux
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.processors.BehaviorProcessor
import io.reactivex.subjects.PublishSubject
interface Store<State> {
fun getState(): Flowable<State>
fun dispatch(action: Any)
fun destroy()
}
internal class StoreImpl<State>(initialState: State, epics: List<Epic<State>>, debug: Boolean) : Store<State> {
private val actions: PublishSubject<Any> = PublishSubject.create()
private val states: BehaviorProcessor<State> = BehaviorProcessor.createDefault(initialState)
private var disposables: CompositeDisposable = CompositeDisposable()
init {
val getState = { states.value }
val stateTransformer: ObservableTransformer<Any, State> = ObservableTransformer {
it.concatMap { action ->
Observable.concat(epics.map { epic -> epic.involve(Observable.just(action), getState) })
}
}
disposables.add(actions.compose(stateTransformer)
.subscribe(
states::onNext,
Throwable::printStackTrace))
if (debug) {
disposables.add(actions.map { "action = [$it]" }
.subscribe(::println))
disposables.add(states.map { "state = [$it]" }
.subscribe(::println))
}
}
override fun getState(): Flowable<State> {
return states
}
override fun dispatch(action: Any) {
actions.onNext(action)
}
override fun destroy() {
disposables.clear()
}
}
fun <State> createStore(initialState: State,
epics: List<Epic<State>>,
debug: Boolean = false): Store<State> {
return StoreImpl(initialState, epics, debug)
}
| redux/src/main/java/vn/tiki/architecture/redux/Redux.kt | 2496954616 |
package org.klips.engine.rete.builder.optimizer
import org.klips.engine.Binding
import org.klips.engine.rete.*
import org.klips.engine.rete.builder.StrategyOne
import org.klips.engine.util.Log
import java.util.*
class Optimizer(val engine: StrategyOne) {
fun optimize(nodes: Set<Node>): Set<Node> {
val roots = ArrayList(detectRoots(nodes))
val replaced = mutableSetOf<Node>()
fun step():Boolean {
val index = sortedMapOf<Signature, MutableSet<Tree>>()
roots.forEach {
nodeToTree(it).addToIndex(index)
}
findMaxMatch(index)?.let {
val (t1, t2, b) = it
replace(t1.reteNode, t2.reteNode, b)
roots.remove(t2.reteNode)
replaced.add(t2.reteNode)
return true
}
return false
}
while (step()){}
return replaced
}
// fun optimize1(nodes: Set<Node>): Set<Node> {
//
// val roots = detectRoots(nodes)
//
// val replaced = mutableSetOf<Node>()
//
// roots.forEach { root ->
//
// fun step():Boolean {
// nodeToTree(root).findMaxMatch()?.let {
// val (t1, t2, b) = it
// replace(t1.reteNode, t2.reteNode, b)
// replaced.add(t2.reteNode)
// return true
// }
// return false
// }
//
// while (step()){}
// }
//
// return replaced
// }
private fun nodeToTree(it: Node): Tree {
return when (it) {
is BetaNode -> Fork(it)
is AlphaNode -> Leafs(it)
is ProxyNode -> Rename(it)
else -> throw IllegalArgumentException()
}
}
private fun detectRoots(nodes: Set<Node>): List<Node> {
// Detect non root nodes
val nonRoots = mutableSetOf<Node>().apply {
nodes.forEach { node ->
if (node is BetaNode) {
add(node.left)
add(node.right)
} else add(node)
}
}
// Detect root nodes
val roots = nodes.filter { it !in nonRoots }
return roots
}
fun replace(with: Node, which: Node, binding: Binding) {
// 1. create proxy node ProxyNode
val pnode = engine.createProxyNode(with, binding)
// 2. attach proxy node to 'with'
val consumersRemove = mutableListOf<Consumer>()
which.consumers.forEach { consumer ->
when (consumer) {
is BetaNode -> {
// ASSERT
if (consumer.left != which && consumer.right != which)
throw IllegalArgumentException()
if (consumer.left == which) {
consumer.left = pnode
consumersRemove.add(consumer)
}
if (consumer.right == which) {
consumer.right = pnode
consumersRemove.add(consumer)
}
}
is ProxyNode ->
{
if (consumer.node == which) {
consumer.node = pnode
consumersRemove.add(consumer)
}
}
else ->
throw IllegalArgumentException()
}
}
// Clean consumers
consumersRemove.forEach { which.removeConsumer(it) }
}
fun Tree.addToIndex(index:MutableMap<Signature, MutableSet<Tree>>) {
deepTraverse {
index.getOrPut(signature){
mutableSetOf()
}.add(this)
false
}
}
fun findMaxMatch(index:Map<Signature, MutableSet<Tree>>): Triple<Tree, Tree, Binding>? {
index.values.filter { it.size > 1 }.reversed().forEach { group0 ->
val group = group0.toList()
for(i in 0..group.size-1)
for(j in i+1..group.size-1){
if (group[i].reteNode !== group[j].reteNode) {
group[i].bind(group[j])?.let {
return Triple(group[i], group[j], it)
}
}
}
}
return null
}
} | src/main/java/org/klips/engine/rete/builder/optimizer/Optimizer.kt | 507726688 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.media
import jp.nephy.penicillin.core.request.EndpointHost
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.request.formBody
import jp.nephy.penicillin.core.session.post
import jp.nephy.penicillin.endpoints.Media
import jp.nephy.penicillin.endpoints.Option
/**
* The FINALIZE command should be called after the entire media file is uploaded using APPEND commands. If and (only if) the response of the FINALIZE command contains a processing_info field, it may also be necessary to use a [STATUS command](https://developer.twitter.com/en/docs/media/upload-media/api-reference/get-media-upload-status) and wait for it to return success before proceeding to Tweet creation.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload-finalize)
*
* @param mediaId The media_id returned from the INIT command.
* @param options Optional. Custom parameters of this request.
* @receiver [Media] endpoint instance.
* @return [JsonObjectApiAction] for [jp.nephy.penicillin.models.Media] model.
*/
fun Media.uploadFinalize(
mediaId: Long,
mediaKey: String? = null,
vararg options: Option
) = client.session.post("/1.1/media/upload.json", EndpointHost.MediaUpload) {
formBody(
"command" to "FINALIZE",
"media_id" to mediaId,
"media_key" to mediaKey,
*options
)
}.jsonObject<jp.nephy.penicillin.models.Media>()
| src/main/kotlin/jp/nephy/penicillin/endpoints/media/UploadFinalize.kt | 2194141031 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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 jp.nephy.penicillin.core.request.action
import jp.nephy.penicillin.core.request.ApiRequest
import jp.nephy.penicillin.core.response.StreamResponse
import jp.nephy.penicillin.core.session.ApiClient
import jp.nephy.penicillin.core.streaming.handler.StreamHandler
import jp.nephy.penicillin.core.streaming.listener.StreamListener
/**
* The [ApiAction] that provides stream-able response.
*/
class StreamApiAction<L: StreamListener, H: StreamHandler<L>>(override val client: ApiClient, override val request: ApiRequest): ApiAction<StreamResponse<L, H>> {
override suspend operator fun invoke(): StreamResponse<L, H> {
val (request, response) = execute()
checkError(request, response)
return StreamResponse(client, request, response, this)
}
}
| src/main/kotlin/jp/nephy/penicillin/core/request/action/StreamApiAction.kt | 2365342851 |
package com.example.autofittextviewsample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import kotlinx.android.synthetic.main.activity_main2.*
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = object : Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return object : ViewHolder(LayoutInflater.from(this@Main2Activity).inflate(R.layout.item, parent, false)) {
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val sb = StringBuilder("item:")
for (i in 0..position)
sb.append(Integer.toString(position))
holder.textView.text = sb
}
override fun getItemCount(): Int {
return 50
}
}
}
private open class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val textView: TextView
init {
textView = itemView.findViewById<View>(android.R.id.text1) as TextView
}
}
}
| AutoFitTextViewSample/src/com/example/autofittextviewsample/Main2Activity.kt | 2333174171 |
package com.github.rubensousa.recyclerviewsnap
import android.os.Bundle
import android.view.Gravity
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper
import com.github.rubensousa.recyclerviewsnap.adapter.AppAdapter
import com.github.rubensousa.recyclerviewsnap.model.App
class GridActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_grid)
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val adapter = AppAdapter(R.layout.adapter_vertical)
val apps = arrayListOf<App>()
repeat(5) {
apps.addAll(MainActivity.getApps())
}
adapter.setItems(apps)
recyclerView.layoutManager = GridLayoutManager(this, 2, RecyclerView.VERTICAL, false)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
}
}
| app/src/main/java/com/github/rubensousa/recyclerviewsnap/GridActivity.kt | 2377959829 |
package io.github.benoitduffez.cupsprint
import android.app.Application
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.core.CrashlyticsCore
import io.fabric.sdk.android.Fabric
import org.koin.android.ext.android.startKoin
import org.koin.dsl.module.module
import timber.log.Timber
val applicationModule = module {
single { AppExecutors() }
}
class CupsPrintApp : Application() {
override fun onCreate() {
super.onCreate()
val core = CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()
Fabric.with(this, Crashlytics.Builder().core(core).build())
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
} else {
Timber.plant(CrashReportingTree())
}
startKoin(this, listOf(applicationModule))
}
/** A tree which logs important information for crash reporting. */
private class CrashReportingTree : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
Crashlytics.log(priority, tag, message)
t.let { Crashlytics.logException(it) }
}
}
}
| app/src/playstore/java/io/github/benoitduffez/cupsprint/CupsPrintApp.kt | 1163835759 |
package edu.kit.iti.formal.automation.st.util
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
/**
* Created by weigl on 13.06.14.
*
* @author weigl
* @version $Id: $Id
*/
data class Tuple<S, T>(val a: S, val b: T) {
companion object {
fun <T, S> make(a: T, b: S): Tuple<T, S> {
return Tuple(a, b)
}
}
}
sealed class Either<L, R> {
data class Left<L, R>(val l: L) : Either<L, R>()
data class Right<L, R>(val r: R) : Either<L, R>()
infix fun <Rp> bind(f: (R) -> (Either<L, Rp>)): Either<L, Rp> {
return when (this) {
is Either.Left<L, R> -> Left<L, Rp>(this.l)
is Either.Right<L, R> -> f(this.r)
}
}
infix fun <Rp> seq(e: Either<L, Rp>): Either<L, Rp> = e
companion object {
fun <L, R> ret(a: R) = Either.Right<L, R>(a)
fun <L, R> fail(msg: String): Either.Right<L, R> = throw Exception(msg)
}
}
| lang/src/main/kotlin/edu/kit/iti/formal/automation/st/util/Tuple.kt | 279903342 |
package tech.summerly.quiet.data.netease.result
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/24
* desc :
*/
data class RecommendSongResultBean(
@SerializedName("code")
@Expose
val code: Int,
@SerializedName("recommend")
@Expose
val recommend: List<Recommend>? = null
) {
data class Recommend(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
// @SerializedName("alias")
// @Expose
// val alias: List<String>? = null,
@SerializedName("artists")
@Expose
val artists: List<Artist>? = null,
@SerializedName("album")
@Expose
val album: Album,
@SerializedName("duration")
@Expose
val duration: Int,
@SerializedName("commentThreadId")
@Expose
val commentThreadId: String? = null,
@SerializedName("hMusic")
@Expose
val hMusic: MusicQuality? = null,
@SerializedName("mMusic")
@Expose
val mMusic: MusicQuality? = null,
@SerializedName("lMusic")
@Expose
val lMusic: MusicQuality? = null,
@SerializedName("bMusic")
@Expose
val bMusic: MusicQuality? = null,
@SerializedName("mvid")
@Expose
val mvid: Long? = null,
@SerializedName("reason")
@Expose
val reason: String? = null
// @SerializedName("position")
// @Expose
// val position: Long? = null,
// @SerializedName("status")
// @Expose
// val status: Long? = null,
// @SerializedName("fee")
// @Expose
// val fee: Long? = null,
// @SerializedName("copyrightId")
// @Expose
// val copyrightId: Long? = null,
// @SerializedName("disc")
// @Expose
// val disc: String? = null,
// @SerializedName("no")
// @Expose
// val no: Long? = null,
// @SerializedName("starred")
// @Expose
// val starred: Boolean? = null,
// @SerializedName("popularity")
// @Expose
// val popularity: Double? = null,
// @SerializedName("score")
// @Expose
// val score: Long? = null,
// @SerializedName("starredNum")
// @Expose
// val starredNum: Long? = null,
// @SerializedName("playedNum")
// @Expose
// val playedNum: Long? = null,
// @SerializedName("dayPlays")
// @Expose
// val dayPlays: Long? = null,
// @SerializedName("hearTime")
// @Expose
// val hearTime: Long? = null,
// @SerializedName("ringtone")
// @Expose
// val ringtone: Any? = null,
// @SerializedName("crbt")
// @Expose
// val crbt: Any? = null,
// @SerializedName("audition")
// @Expose
// val audition: Any? = null,
// @SerializedName("copyFrom")
// @Expose
// val copyFrom: String? = null,
// @SerializedName("rtUrl")
// @Expose
// val rtUrl: Any? = null,
// @SerializedName("ftype")
// @Expose
// val ftype: Long? = null,
// @SerializedName("rtUrls")
// @Expose
// val rtUrls: List<Any>? = null,
// @SerializedName("copyright")
// @Expose
// val copyright: Long? = null,
// @SerializedName("rtype")
// @Expose
// val rtype: Long? = null,
// @SerializedName("mp3Url")
// @Expose
// val mp3Url: Any? = null,
// @SerializedName("rurl")
// @Expose
// val rurl: Any? = null,
// @SerializedName("privilege")
// @Expose
// val privilege: Privilege? = null,
// @SerializedName("alg")
// @Expose
// val alg: String? = null
)
data class Album(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("type")
@Expose
val type: String,
@SerializedName("size")
@Expose
val size: Long,
@SerializedName("picId")
@Expose
val picId: Long? = null,
@SerializedName("blurPicUrl")
@Expose
val blurPicUrl: String? = null,
// @SerializedName("companyId")
// @Expose
// val companyId: Long? = null,
// @SerializedName("pic")
// @Expose
// val pic: Long? = null,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("publishTime")
@Expose
val publishTime: Long? = null,
// @SerializedName("description")
// @Expose
// val description: String? = null,
// @SerializedName("tags")
// @Expose
// val tags: String? = null,
// @SerializedName("company")
// @Expose
// val company: Any? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("artist")
// @Expose
// val artist: Artist_? = null,
// @SerializedName("songs")
// @Expose
// val songs: List<Any>? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("status")
// @Expose
// val status: Long? = null,
// @SerializedName("copyrightId")
// @Expose
// val copyrightId: Long? = null,
// @SerializedName("commentThreadId")
// @Expose
// val commentThreadId: String? = null,
@SerializedName("artists")
@Expose
val artists: List<Artist__>? = null
// @SerializedName("picId_str")
// @Expose
// val picIdStr: String? = null
)
data class Artist(
@SerializedName("title")
@Expose
val name: String,
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("img1v1Url")
@Expose
val img1v1Url: String? = null
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
)
data class Artist__(
@SerializedName("title")
@Expose
val name: String? = null,
@SerializedName("id")
@Expose
val id: Long? = null,
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
@SerializedName("picUrl")
@Expose
val picUrl: String? = null,
@SerializedName("img1v1Url")
@Expose
val img1v1Url: String? = null
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
)
data class MusicQuality(
@SerializedName("id")
@Expose
val id: Long,
@SerializedName("size")
@Expose
val size: Long? = null,
@SerializedName("extension")
@Expose
val extension: String? = null,
@SerializedName("sr")
@Expose
val sr: Long? = null,
@SerializedName("bitrate")
@Expose
val bitrate: Long? = null,
@SerializedName("playTime")
@Expose
val playTime: Long? = null,
@SerializedName("volumeDelta")
@Expose
val volumeDelta: Double? = null,
@SerializedName("dfsId_str")
@Expose
val dfsIdStr: Any? = null
// @SerializedName("title")
// @Expose
// val title: String? = null,
// @SerializedName("dfsId")
// @Expose
// val dfsId: Long? = null,
)
// data class Artist_(
//
// @SerializedName("title")
// @Expose
// val title: String? = null,
// @SerializedName("id")
// @Expose
// val id: Long? = null,
// @SerializedName("picId")
// @Expose
// val picId: Long? = null,
// @SerializedName("img1v1Id")
// @Expose
// val img1v1Id: Long? = null,
// @SerializedName("briefDesc")
// @Expose
// val briefDesc: String? = null,
// @SerializedName("picUrl")
// @Expose
// val picUrl: String? = null,
// @SerializedName("img1v1Url")
// @Expose
// val img1v1Url: String? = null,
// @SerializedName("albumSize")
// @Expose
// val albumSize: Long? = null,
// @SerializedName("alias")
// @Expose
// val alias: List<Any>? = null,
// @SerializedName("trans")
// @Expose
// val trans: String? = null,
// @SerializedName("musicSize")
// @Expose
// val musicSize: Long? = null
//
// )
//data class Privilege (
//
// @SerializedName("id")
// @Expose
// val id: Long? = null,
// @SerializedName("fee")
// @Expose
// val fee: Long? = null,
// @SerializedName("payed")
// @Expose
// val payed: Long? = null,
// @SerializedName("st")
// @Expose
// val st: Long? = null,
// @SerializedName("pl")
// @Expose
// val pl: Long? = null,
// @SerializedName("dl")
// @Expose
// val dl: Long? = null,
// @SerializedName("sp")
// @Expose
// val sp: Long? = null,
// @SerializedName("cp")
// @Expose
// val cp: Long? = null,
// @SerializedName("subp")
// @Expose
// val subp: Long? = null,
// @SerializedName("cs")
// @Expose
// val cs: Boolean? = null,
// @SerializedName("maxbr")
// @Expose
// val maxbr: Long? = null,
// @SerializedName("fl")
// @Expose
// val fl: Long? = null,
// @SerializedName("toast")
// @Expose
// val toast: Boolean? = null,
// @SerializedName("flag")
// @Expose
// val flag: Long? = null,
//
//)
}
| app/src/main/java/tech/summerly/quiet/data/netease/result/RecommendSongResultBean.kt | 3566805205 |
package fr.free.nrw.commons.explore.depictions.child
import android.os.Bundle
import android.view.View
import fr.free.nrw.commons.R
import fr.free.nrw.commons.explore.depictions.PageableDepictionsFragment
import javax.inject.Inject
class ChildDepictionsFragment: PageableDepictionsFragment() {
@Inject
lateinit var presenter: ChildDepictionsPresenter
override val injectedPresenter
get() = presenter
override fun getEmptyText(query: String) =
getString(R.string.no_child_classes, arguments!!.getString("wikidataItemName")!!)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
onQueryUpdated(arguments!!.getString("entityId")!!)
}
}
| app/src/main/java/fr/free/nrw/commons/explore/depictions/child/ChildDepictionsFragment.kt | 138001506 |
@file:JvmName("-Bitmaps")
@file:Suppress("NOTHING_TO_INLINE")
package coil.util
import android.content.Context
import android.graphics.Bitmap
import android.os.Build.VERSION.SDK_INT
import androidx.core.graphics.drawable.toDrawable
@Suppress("DEPRECATION")
internal val Bitmap.Config?.bytesPerPixel: Int
get() = when {
this == Bitmap.Config.ALPHA_8 -> 1
this == Bitmap.Config.RGB_565 -> 2
this == Bitmap.Config.ARGB_4444 -> 2
SDK_INT >= 26 && this == Bitmap.Config.RGBA_F16 -> 8
else -> 4
}
/**
* Returns the in memory size of this [Bitmap] in bytes.
* This value will not change over the lifetime of a bitmap.
*/
internal val Bitmap.allocationByteCountCompat: Int
get() {
check(!isRecycled) {
"Cannot obtain size for recycled bitmap: $this [$width x $height] + $config"
}
return try {
allocationByteCount
} catch (_: Exception) {
width * height * config.bytesPerPixel
}
}
internal val Bitmap.Config.isHardware: Boolean
get() = SDK_INT >= 26 && this == Bitmap.Config.HARDWARE
/** Guard against null bitmap configs. */
internal val Bitmap.safeConfig: Bitmap.Config
get() = config ?: Bitmap.Config.ARGB_8888
internal inline fun Bitmap.toDrawable(context: Context) = toDrawable(context.resources)
/** Convert null and [Bitmap.Config.HARDWARE] configs to [Bitmap.Config.ARGB_8888]. */
internal fun Bitmap.Config?.toSoftware(): Bitmap.Config {
return if (this == null || isHardware) Bitmap.Config.ARGB_8888 else this
}
| coil-base/src/main/java/coil/util/Bitmaps.kt | 1695594197 |
package org.rust.lang.core.psi
interface RustItemElement : RustVisibilityOwner, RustOuterAttributeOwner
| src/main/kotlin/org/rust/lang/core/psi/RustItemElement.kt | 3612787789 |
package tutorial.coroutine.scheduler
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main(): Unit = runBlocking {
launch(Dispatchers.Default + CoroutineName("test")) {
println("I'm working in thread ${Thread.currentThread().name}")
}
}
| src/kotlin/src/tutorial/coroutine/scheduler/MultipleContextElement.kt | 265100896 |
package app.opass.ccip.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isGone
import androidx.recyclerview.widget.RecyclerView
import app.opass.ccip.R
import app.opass.ccip.model.WifiNetworkInfo
class WifiNetworkAdapter(
private val items: List<WifiNetworkInfo>,
private val onItemClick: (WifiNetworkInfo) -> Unit
) : RecyclerView.Adapter<WifiNetworkViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WifiNetworkViewHolder =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_wifi_network, parent, false)
.let(::WifiNetworkViewHolder)
.apply {
itemView.setOnClickListener {
val pos = adapterPosition
if (pos != RecyclerView.NO_POSITION) onItemClick(items[pos])
}
}
override fun getItemCount() = items.size
override fun onBindViewHolder(holder: WifiNetworkViewHolder, position: Int) {
val item = items[position]
holder.name.text = item.ssid
val hasPassword = !item.password.isNullOrEmpty()
if (!hasPassword) {
holder.password.isGone = true
return
}
holder.password.text = item.password
holder.password.isGone = false
}
}
class WifiNetworkViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val name: TextView = view.findViewById(R.id.network_name)
val password: TextView = view.findViewById(R.id.network_password)
}
| app/src/main/java/app/opass/ccip/ui/WifiNetworkAdapter.kt | 2814586955 |
package com.etesync.syncadapter.ui.etebase
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.fragment.app.ListFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.commit
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.observe
import com.etebase.client.FetchOptions
import com.etesync.syncadapter.CachedCollection
import com.etesync.syncadapter.CachedItem
import com.etesync.syncadapter.R
import com.etesync.syncadapter.ui.etebase.ListEntriesFragment.Companion.setItemView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.util.*
import java.util.concurrent.Future
class ItemRevisionsListFragment : ListFragment(), AdapterView.OnItemClickListener {
private val model: AccountViewModel by activityViewModels()
private val revisionsModel: RevisionsViewModel by viewModels()
private var state: Parcelable? = null
private lateinit var cachedCollection: CachedCollection
private lateinit var cachedItem: CachedItem
private var emptyTextView: TextView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.journal_viewer_list, container, false)
//This is instead of setEmptyText() function because of Google bug
//See: https://code.google.com/p/android/issues/detail?id=21742
emptyTextView = view.findViewById<View>(android.R.id.empty) as TextView
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var restored = false
revisionsModel.loadRevisions(model.value!!, cachedCollection, cachedItem)
revisionsModel.observe(this) {
val entries = it.sortedByDescending { item ->
item.meta.mtime ?: 0
}
val listAdapter = EntriesListAdapter(requireContext(), cachedCollection)
setListAdapter(listAdapter)
listAdapter.addAll(entries)
if(!restored && (state != null)) {
listView.onRestoreInstanceState(state)
restored = true
}
emptyTextView!!.text = getString(R.string.journal_entries_list_empty)
}
listView.onItemClickListener = this
}
override fun onPause() {
state = listView.onSaveInstanceState()
super.onPause()
}
override fun onDestroyView() {
super.onDestroyView()
revisionsModel.cancelLoad()
}
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val item = listAdapter?.getItem(position) as CachedItem
activity?.supportFragmentManager?.commit {
replace(R.id.fragment_container, CollectionItemFragment.newInstance(item))
addToBackStack(null)
}
}
internal inner class EntriesListAdapter(context: Context, val cachedCollection: CachedCollection) : ArrayAdapter<CachedItem>(context, R.layout.journal_viewer_list_item) {
override fun getView(position: Int, _v: View?, parent: ViewGroup): View {
var v = _v
if (v == null)
v = LayoutInflater.from(context).inflate(R.layout.journal_viewer_list_item, parent, false)!!
val item = getItem(position)!!
setItemView(v, cachedCollection.collectionType, item)
/* FIXME: handle entry error:
val entryError = data.select(EntryErrorEntity::class.java).where(EntryErrorEntity.ENTRY.eq(entryEntity)).limit(1).get().firstOrNull()
if (entryError != null) {
val errorIcon = v.findViewById<View>(R.id.error) as ImageView
errorIcon.visibility = View.VISIBLE
}
*/
return v
}
}
companion object {
fun newInstance(cachedCollection: CachedCollection, cachedItem: CachedItem): ItemRevisionsListFragment {
val ret = ItemRevisionsListFragment()
ret.cachedCollection = cachedCollection
ret.cachedItem = cachedItem
return ret
}
}
}
class RevisionsViewModel : ViewModel() {
private val revisions = MutableLiveData<List<CachedItem>>()
private var asyncTask: Future<Unit>? = null
fun loadRevisions(accountCollectionHolder: AccountHolder, cachedCollection: CachedCollection, cachedItem: CachedItem) {
asyncTask = doAsync {
val ret = LinkedList<CachedItem>()
val col = cachedCollection.col
val itemManager = accountCollectionHolder.colMgr.getItemManager(col)
var iterator: String? = null
var done = false
while (!done) {
val chunk = itemManager.itemRevisions(cachedItem.item, FetchOptions().iterator(iterator).limit(30))
iterator = chunk.iterator
done = chunk.isDone
ret.addAll(chunk.data.map { CachedItem(it, it.meta, it.contentString) })
}
uiThread {
revisions.value = ret
}
}
}
fun cancelLoad() {
asyncTask?.cancel(true)
}
fun observe(owner: LifecycleOwner, observer: (List<CachedItem>) -> Unit) =
revisions.observe(owner, observer)
} | app/src/main/java/com/etesync/syncadapter/ui/etebase/ItemRevisionsListFragment.kt | 3254760719 |
package net.perfectdreams.loritta.embededitor.editors
import kotlinx.html.*
import kotlinx.html.dom.create
import kotlinx.html.js.onClickFunction
import net.perfectdreams.loritta.embededitor.EmbedEditor
import net.perfectdreams.loritta.embededitor.data.DiscordEmbed
import net.perfectdreams.loritta.embededitor.data.FieldRenderInfo
import net.perfectdreams.loritta.embededitor.generator.EmbedFieldsGenerator
import net.perfectdreams.loritta.embededitor.select
import net.perfectdreams.loritta.embededitor.utils.*
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLTextAreaElement
import kotlinx.browser.document
object EmbedFieldEditor : EditorBase {
val changeField: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
currentElement.classes += "clickable"
renderInfo as FieldRenderInfo
currentElement.onClickFunction = {
fieldPopup(
discordMessage.embed!!,
renderInfo.field,
false,
m
)
}
}
val addMoreFields: ELEMENT_CONFIGURATION = { m, discordMessage, currentElement, renderInfo ->
val embed = discordMessage.embed!!
if (DiscordEmbed.MAX_FIELD_OBJECTS > embed.fields.size) {
lovelyButton(
"fas fa-grip-lines",
"Adicionar Campo"
) {
fieldPopup(
embed,
DiscordEmbed.Field("owo", "uwu"),
true,
m
)
}
}
}
fun fieldPopup(embed: DiscordEmbed, field: DiscordEmbed.Field, isNew: Boolean, m: EmbedEditor) {
val modal = TingleModal(
TingleOptions(
footer = true
)
)
modal.setContent(
document.create.div {
div {
discordTextArea(m, field.name, "field-name", DiscordEmbed.MAX_FIELD_NAME_LENGTH)
}
div {
discordTextArea(m, field.value, "field-value", DiscordEmbed.MAX_FIELD_VALUE_LENGTH)
}
label {
+ "Inline? "
}
input(InputType.checkBox) {
name = "field-inline"
checked = field.inline
}
}
)
modal.closeMessageButton(
m
) {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
remove(field)
}
)
)
}
modal.addLovelyFooterButton(
"fas fa-save",
"Salvar"
) {
m.generateMessageAndUpdateJson(
if (isNew) {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
add(
DiscordEmbed.Field(
visibleModal.select<HTMLTextAreaElement>("[name='field-name']")
.value,
visibleModal.select<HTMLTextAreaElement>("[name='field-value']")
.value,
visibleModal.select<HTMLInputElement>("[name='field-inline']")
.checked
)
)
}
)
)
} else {
m.activeMessage!!.copy(
embed = m.activeMessage!!.embed!!
.copy(
fields = m.activeMessage!!.embed!!.fields.toMutableList().apply {
val indexOf = embed.fields.indexOf(field)
remove(field)
add(
indexOf,
DiscordEmbed.Field(
visibleModal.select<HTMLTextAreaElement>("[name='field-name']")
.value,
visibleModal.select<HTMLTextAreaElement>("[name='field-value']")
.value,
visibleModal.select<HTMLInputElement>("[name='field-inline']")
.checked
)
)
}
)
)
}
)
modal.close()
}
modal.open()
// visibleModal.select<HTMLTextAreaElement>(".text-input").autoResize()
}
} | web/embed-editor/embed-editor/src/main/kotlin/net/perfectdreams/loritta/embededitor/editors/EmbedFieldEditor.kt | 1333910998 |
package com.intellij.configurationStore
import com.intellij.codeInsight.template.impl.TemplateSettings
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.readText
import com.intellij.util.io.write
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class TemplateSchemeTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
// https://youtrack.jetbrains.com/issue/IDEA-155623#comment=27-1721029
@Test fun `do not remove unknown context`() {
val schemeFile = fsRule.fs.getPath("templates/Groovy.xml")
val schemeManagerFactory = SchemeManagerFactoryBase.TestSchemeManagerFactory(fsRule.fs.getPath(""))
val schemeData = """
<templateSet group="Groovy">
<template name="serr" value="System.err.println("$\END$")dwed" description="Prints a string to System.errwefwe" toReformat="true" toShortenFQNames="true" deactivated="true">
<context>
<option name="GROOVY_STATEMENT" value="false" />
<option name="__DO_NOT_DELETE_ME__" value="true" />
</context>
</template>
</templateSet>""".trimIndent()
schemeFile.write(schemeData)
TemplateSettings(schemeManagerFactory)
schemeManagerFactory.save()
assertThat(schemeFile.readText()).isEqualTo(schemeData)
}
} | platform/configuration-store-impl/testSrc/TemplateSchemeTest.kt | 2140156282 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.terraform.config.formatter
import org.intellij.plugins.hcl.formatter.HCLFormattingBuilderModel
import org.intellij.plugins.hcl.terraform.config.TerraformLanguage
class TerraformFormattingBuilderModel : HCLFormattingBuilderModel(TerraformLanguage)
| src/kotlin/org/intellij/plugins/hcl/terraform/config/formatter/TerraformFormattingBuilderModel.kt | 1497724011 |
package com.github.christophpickl.kpotpourri.http4k_fuel
import com.github.christophpickl.kpotpourri.http4k.internal.HttpClientType
import com.github.christophpickl.kpotpourri.http4k.non_test.AbstractHttpClientFactoryDetectorTest
import kotlin.reflect.KClass
class FuelHttpClientFactoryDetectorTest : AbstractHttpClientFactoryDetectorTest<FuelHttpClient>() {
override val expectedType: KClass<FuelHttpClient> get() = FuelHttpClient::class
override val httpClientEnum get() = HttpClientType.FuelClient
}
//class FuelHttpClientTest : WiremockTest() { }
| http4k-fuel/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k_fuel/FuelHttpClientTest.kt | 734359591 |
package library.service.api.books
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL
import library.service.business.books.domain.BookRecord
import org.springframework.hateoas.RepresentationModel
import org.springframework.hateoas.server.core.Relation
/** Representation of a [BookRecord] as a REST resource. */
@JsonInclude(NON_NULL)
@Relation(value = "book", collectionRelation = "books")
data class BookResource(
val isbn: String,
val title: String,
val authors: List<String>?,
val numberOfPages: Int?,
val borrowed: Borrowed?
) : RepresentationModel<BookResource>()
data class Borrowed(
val by: String,
val on: String
) | library-service/src/main/kotlin/library/service/api/books/BookResource.kt | 4236210998 |
import java.util.Random
import kotlin.system.measureTimeMillis
fun quickSort(a: IntArray, rnd: Random = Random(), low: Int = 0, high: Int = a.size - 1) {
if (low >= high)
return
val separator = a[low + rnd.nextInt(high - low + 1)]
var i = low
var j = high
while (i <= j) {
while (a[i] < separator)
++i
while (a[j] > separator)
--j
if (i <= j) {
a[i] = a[j].also { a[j] = a[i] }
++i
--j
}
}
quickSort(a, rnd, low, j)
quickSort(a, rnd, i, high)
}
// test
fun main() {
val n = 10_000_000L
val rnd = Random()
val a = rnd.ints(n).toArray()
val b = a.sortedArray()
println(measureTimeMillis { quickSort(a, rnd) })
if (!a.contentEquals(b))
throw RuntimeException()
}
| kotlin/QuickSort.kt | 1265007199 |
package servingclient.servingclient.GUI
import android.widget.ArrayAdapter
import android.widget.TextView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.app.Activity
import android.graphics.Color
import android.util.Log
import android.view.View
import android.widget.ImageView
import servingclient.servingclient.R
class CustomAdapter(private val context: Activity, private val itemname: ArrayList<String>?, private val imgid: Array<Int>)
: ArrayAdapter<String>(context, R.layout.mylist, itemname) {
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
val inflater = context.layoutInflater as LayoutInflater
val rowView = inflater.inflate(R.layout.mylist, null) as View
val txtTitle = rowView.findViewById(R.id.item) as TextView
val imageView = rowView.findViewById(R.id.icon) as ImageView
//imageView.setBackgroundColor(parent.solidColor)
txtTitle.text = itemname?.get(position)
txtTitle.setTextColor(Color.BLACK)
txtTitle.setTextSize(20.0f)
if (itemname != null)
imageView.setImageResource(when (true) {
itemname.get(position).contains("HOT_DOG") -> imgid[0]
itemname.get(position).contains("CHEESEBURGER") -> imgid[1]
itemname.get(position).contains("HAMBURGER") -> imgid[2]
itemname.get(position).contains("HOT_CORN") -> imgid[3]
itemname.get(position).contains("CHIPS") -> imgid[4]
itemname.get(position).contains("COLD_BEER") -> imgid[5]
itemname.get(position).contains("COCA_COLA") -> imgid[6]
itemname.get(position).contains("WATER") -> imgid[7]
itemname.get(position).contains("STEEL_WATER") -> imgid[8]
itemname.get(position).contains("TEA") -> imgid[9]
itemname.get(position).contains("COFFEE") -> imgid[10]
itemname.get(position).contains("JUICE") -> imgid[11]
itemname.get(position).contains("SCARF") -> imgid[12]
itemname.get(position).contains("BALL") -> imgid[13]
else -> imgid[14]
})
return rowView
}
} | ServingClient/app/src/main/java/servingclient/servingclient/GUI/CustomAdapter.kt | 1590519443 |
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.5.1-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.models
/**
*
* @param propertyClass
* @param href
*/
data class Link(
val propertyClass: kotlin.String? = null,
val href: kotlin.String? = null
)
| clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/models/Link.kt | 2545381222 |
package gestures
import furhatos.gestures.defineGesture
import furhatos.gestures.BasicParams
/**
* Take a breath right before Speaking.
* Leave about 1 second before beginning to speak. This method would benefit from slower motor movements
*/
val BreathIn = defineGesture("BreathIn") {
frame(0.35){
BasicParams.PHONE_AAH to 0.0
BasicParams.NECK_TILT to -14.0
}
frame(0.7){
BasicParams.PHONE_AAH to 0.4
BasicParams.NECK_TILT to -14.0
}
frame(1.4){
BasicParams.PHONE_AAH to 0.0
}
frame(5.8){
BasicParams.NECK_TILT to 5.0
BasicParams.EYE_SQUINT_LEFT to 0.3
BasicParams.EYE_SQUINT_RIGHT to 0.3
}
reset(6.2)
} | Dog/src/main/kotlin/furhatos/app/dog/gestures/breathIn.kt | 2900490804 |
package com.mcxiaoke.koi.ext
import android.app.Activity
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
/**
* User: mcxiaoke
* Date: 16/1/27
* Time: 11:26
*/
inline fun <reified T : Context> Context.newIntent(): Intent =
Intent(this, T::class.java)
inline fun <reified T : Context> Context.newIntent(flags: Int): Intent {
val intent = newIntent<T>()
intent.flags = flags
return intent
}
inline fun <reified T : Context> Context.newIntent(extras: Bundle): Intent =
newIntent<T>(0, extras)
inline fun <reified T : Context> Context.newIntent(flags: Int, extras: Bundle): Intent {
val intent = newIntent<T>(flags)
intent.putExtras(extras)
return intent
}
inline fun <reified T : Activity> Activity.startActivity(): Unit =
this.startActivity(newIntent<T>())
inline fun <reified T : Activity> Activity.startActivity(flags: Int): Unit =
this.startActivity(newIntent<T>(flags))
inline fun <reified T : Activity> Activity.startActivity(extras: Bundle): Unit =
this.startActivity(newIntent<T>(extras))
inline fun <reified T : Activity> Activity.startActivity(flags: Int, extras: Bundle): Unit =
this.startActivity(newIntent<T>(flags, extras))
inline fun <reified T : Activity> Activity.startActivityForResult(requestCode: Int): Unit =
this.startActivityForResult(newIntent<T>(), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(requestCode: Int,
flags: Int): Unit =
this.startActivityForResult(newIntent<T>(flags), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(
extras: Bundle, requestCode: Int): Unit =
this.startActivityForResult(newIntent<T>(extras), requestCode)
inline fun <reified T : Activity> Activity.startActivityForResult(
extras: Bundle, requestCode: Int, flags: Int): Unit =
this.startActivityForResult(newIntent<T>(flags, extras), requestCode)
inline fun <reified T : Service> Context.startService(): ComponentName =
this.startService(newIntent<T>())
inline fun <reified T : Service> Context.startService(flags: Int): ComponentName =
this.startService(newIntent<T>(flags))
inline fun <reified T : Service> Context.startService(extras: Bundle): ComponentName =
this.startService(newIntent<T>(extras))
inline fun <reified T : Service> Context.startService(extras: Bundle,
flags: Int): ComponentName
= this.startService(newIntent<T>(flags, extras))
| core/src/main/kotlin/com/mcxiaoke/koi/ext/Intent.kt | 737824361 |
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_18_R1
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import net.minecraft.world.entity.ai.goal.PathfinderGoal
/**
* This pathfinder is a solution to Paper causing normal pathfinders to sometimes get ignored.
*/
class CombinedPathfinder(val pathfinderProxy: Map<PathfinderProxy, Cache>) : PathfinderGoal() {
/**
* Override ShouldExecute.
*/
override fun a(): Boolean {
for (proxy in pathfinderProxy.keys) {
val cache = pathfinderProxy.getValue(proxy)
if (cache.isExecuting) {
val shouldContinue = proxy.shouldGoalContinueExecuting()
if (!shouldContinue) {
proxy.onStopExecuting()
cache.isExecuting = false
} else {
proxy.onExecute()
}
} else {
val shouldExecute = proxy.shouldGoalBeExecuted()
if (shouldExecute) {
proxy.onStartExecuting()
cache.isExecuting = true
proxy.onExecute()
}
}
}
return true
}
/**
* Override continue executing.
*/
override fun b(): Boolean {
return false
}
/**
* Override isInterrupting.
*/
override fun D_(): Boolean {
return true
}
/**
* Override startExecuting.
*/
override fun c() {
}
/**
* Override reset.
*/
override fun d() {
}
/**
* Override update.
*/
override fun e() {
}
class Cache {
var isExecuting = false
}
}
| petblocks-bukkit-plugin/petblocks-bukkit-nms-118R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_18_R1/CombinedPathfinder.kt | 3831690698 |
package com.episode6.hackit.mockspresso.mockito.integration
import com.episode6.hackit.mockspresso.BuildMockspresso
import com.episode6.hackit.mockspresso.annotation.Dependency
import com.episode6.hackit.mockspresso.annotation.RealObject
import com.episode6.hackit.mockspresso.basic.plugin.injectBySimpleConfig
import com.episode6.hackit.mockspresso.mockito.Conditions.mockCondition
import com.episode6.hackit.mockspresso.mockito.mockByMockito
import com.episode6.hackit.mockspresso.testing.matches
import com.nhaarman.mockitokotlin2.mock
import org.fest.assertions.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import javax.inject.Named
/**
* Test mocking using kotlin ext methods
*/
class MockitoKotlinMockingTest {
private interface TestDep1
private interface TestDep2
private interface TestDep3
private class TestObj(
val dep1: TestDep1,
@Named("dep2") val dep2: TestDep2,
val dep3: TestDep3)
@get:Rule val mockspresso = BuildMockspresso.with()
.injectBySimpleConfig()
.mockByMockito()
.buildRule()
@Mock private lateinit var dep1: TestDep1
@Dependency @field:Named("dep2") private val dep2: TestDep2 = mock()
@RealObject private lateinit var testObj: TestObj
@Test fun assertDepsAreMocks() {
assertThat(testObj.dep1).isEqualTo(dep1).matches(mockCondition())
assertThat(testObj.dep2).isEqualTo(dep2).matches(mockCondition())
assertThat(testObj.dep3).matches(mockCondition())
}
}
| mockspresso-mockito/src/test/java/com/episode6/hackit/mockspresso/mockito/integration/MockitoKotlinMockingTest.kt | 2859758077 |
package com.baulsupp.okurl.authenticator.oauth2
import com.baulsupp.okurl.authenticator.authflow.AuthFlow
import com.baulsupp.okurl.authenticator.authflow.AuthFlowType
import com.baulsupp.okurl.credentials.ServiceDefinition
import okhttp3.OkHttpClient
abstract class Oauth2Flow<T>(override val serviceDefinition: ServiceDefinition<T>) : AuthFlow<T> {
override val type = AuthFlowType.Oauth2
lateinit var client: OkHttpClient
val options = mutableMapOf<String, Any>()
override suspend fun init(client: OkHttpClient) {
this.client = client
}
fun defineOptions(options: Map<String, Any>) {
this.options.putAll(options)
}
abstract suspend fun start(): String
abstract suspend fun complete(code: String): T
}
| src/main/kotlin/com/baulsupp/okurl/authenticator/oauth2/Oauth2Flow.kt | 967990877 |
package block.heat
import com.cout970.magneticraft.tileentity.heat.TileHeatExchanger
import net.minecraft.block.material.Material
import net.minecraft.block.state.IBlockState
import net.minecraft.tileentity.TileEntity
import net.minecraft.world.World
/**
* Created by cout970 on 04/07/2016.
*/
//TODO add to game or remove
@Suppress("unused")
object BlockHeatExchanger : BlockHeatBase(Material.ROCK, "heat_exchanger") {
override fun createTileEntity(worldIn: World, meta: IBlockState): TileEntity = TileHeatExchanger()
} | ignore/test/block/heat/BlockHeatExchanger.kt | 4177627006 |
package com.myapp.repository
import com.myapp.domain.Micropost
import com.myapp.dto.request.PageParams
interface FeedRepository {
fun findFeed(userId: Long, pageParams: PageParams): List<Micropost>
} | src/main/kotlin/com/myapp/repository/FeedRepository.kt | 2521556033 |
package github.nisrulz.example.usingdagger2
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import github.nisrulz.example.usingdagger2.databinding.FragmentMainBinding
import javax.inject.Inject
class MainFragment : Fragment(), MainView {
private lateinit var binding: FragmentMainBinding
private val module by lazy { MainModule(this) }
var presenter: MainPresenter? = null
@Inject set
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Setup Dagger
DaggerMainComponent
.builder()
.mainModule(module)
.build()
.inject(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Use the inflater to inflate the layout via the Binding class
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
} | UsingDagger2/app/src/main/java/github/nisrulz/example/usingdagger2/MainFragment.kt | 1758132056 |
package com.waz.zclient.core.backend.di
import com.waz.zclient.core.backend.datasources.remote.BackendRemoteDataSource
import org.koin.core.KoinComponent
import org.koin.core.get
/**
* Dependency provider that enables lazy loading of [BackendRemoteDataSource], letting network layer initialize itself
* before creating the dependency.
*/
class BackendRemoteDataSourceProvider : KoinComponent {
fun backendRemoteDataSource(): BackendRemoteDataSource = get()
}
| app/src/main/kotlin/com/waz/zclient/core/backend/di/BackendRemoteDataSourceProvider.kt | 3250786548 |
package io.particle.android.sdk.utils
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
fun Context.appHasPermission(permission: String): Boolean {
val result = ContextCompat.checkSelfPermission(this, permission)
return result == PackageManager.PERMISSION_GRANTED
}
| cloudsdk/src/main/java/io/particle/android/sdk/utils/Permissions.kt | 1890153072 |
package io.particle.mesh.ui.setup
import android.media.AudioManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.VideoView
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.fragment.findNavController
import com.squareup.phrase.Phrase
import io.particle.android.common.buildRawResourceUri
import io.particle.mesh.common.QATool
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.ui.BaseFlowFragment
import io.particle.mesh.ui.R
import kotlinx.android.synthetic.main.fragment_manual_commissioning_add_to_network.*
class ManualCommissioningAddToNetworkFragment : BaseFlowFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.fragment_manual_commissioning_add_to_network,
container,
false
)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
action_next.setOnClickListener {
// FIXME: this flow logic should live outside the UI
try {
findNavController().navigate(
R.id.action_manualCommissioningAddToNetworkFragment_to_scanCommissionerCodeFragment
)
} catch (ex: Exception) {
// Workaround to avoid this seemingly impossible crash: http://bit.ly/2kTpnIb
val error = IllegalStateException(
"Navigation error, Activity=${activity.javaClass}, isFinishing=${activity.isFinishing}",
ex
)
QATool.report(error)
[email protected]?.finish()
}
}
setup_header_text.text = Phrase.from(view, R.string.add_xenon_to_mesh_network)
.put("product_type", getUserFacingTypeName())
.format()
setUpVideoView(videoView)
}
private fun setUpVideoView(vidView: VideoView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// stop pausing the user's music when showing the video!
vidView.setAudioFocusRequest(AudioManager.AUDIOFOCUS_NONE)
}
vidView.setVideoURI(activity!!.buildRawResourceUri(R.raw.commissioner_to_listening_mode))
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
vidView.start()
}
override fun onStop(owner: LifecycleOwner) {
vidView.stopPlayback()
}
})
vidView.setOnPreparedListener { player -> player.isLooping = true }
}
}
| meshui/src/main/java/io/particle/mesh/ui/setup/ManualCommissioningAddToNetworkFragment.kt | 1746784331 |
/* 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.telemetry
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import mozilla.components.support.utils.ext.getPackageInfoCompat
object FenixProductDetector {
enum class FenixVersion(val packageName: String) {
FIREFOX("org.mozilla.firefox"),
FIREFOX_NIGHTLY("org.mozilla.fenix"),
FIREFOX_BETA("org.mozilla.firefox_beta"),
}
fun getInstalledFenixVersions(context: Context): List<String> {
val fenixVersions = mutableListOf<String>()
for (product in FenixVersion.values()) {
if (packageIsInstalled(context, product.packageName)) {
fenixVersions.add(product.packageName)
}
}
return fenixVersions
}
fun isFenixDefaultBrowser(defaultBrowser: ActivityInfo?): Boolean {
if (defaultBrowser == null) return false
for (product in FenixVersion.values()) {
if (product.packageName == defaultBrowser.packageName) return true
}
return false
}
private fun packageIsInstalled(context: Context, packageName: String): Boolean {
try {
context.packageManager.getPackageInfoCompat(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
return false
}
return true
}
}
| app/src/main/java/org/mozilla/focus/telemetry/FenixProductDetector.kt | 3118001112 |
package com.senorsen.wukong.network
import android.util.Log
import com.google.common.net.HttpHeaders
import okhttp3.OkHttpClient
import okhttp3.Request
object MediaProviderClient {
private val TAG = javaClass.simpleName
private val client = OkHttpClient()
fun resolveRedirect(url: String): String {
if (!url.startsWith("http")) return url
val request = Request.Builder()
.head()
.header(HttpHeaders.USER_AGENT, "")
.url(url).build()
client.newCall(request).execute().use { response ->
when {
response.isSuccessful && response.code() == 200 -> {
Log.d(TAG, response.toString())
return response.request().url().toString()
}
else ->
throw HttpClient.InvalidResponseException(response)
}
}
}
fun getMedia(url: String): ByteArray {
val request = Request.Builder()
.header(HttpHeaders.USER_AGENT, "")
.url(url).build()
client.newCall(request).execute().use { response ->
when {
response.isSuccessful ->
return response.body()!!.bytes()
else ->
throw HttpClient.InvalidResponseException(response)
}
}
}
}
| wukong/src/main/java/com/senorsen/wukong/network/MediaProviderClient.kt | 494802065 |
/*
* 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
*
* 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.example.android.camera.utils
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.view.OrientationEventListener
import android.view.Surface
import androidx.lifecycle.LiveData
/**
* Calculates closest 90-degree orientation to compensate for the device
* rotation relative to sensor orientation, i.e., allows user to see camera
* frames with the expected orientation.
*/
class OrientationLiveData(
context: Context,
characteristics: CameraCharacteristics
): LiveData<Int>() {
private val listener = object : OrientationEventListener(context.applicationContext) {
override fun onOrientationChanged(orientation: Int) {
val rotation = when {
orientation <= 45 -> Surface.ROTATION_0
orientation <= 135 -> Surface.ROTATION_90
orientation <= 225 -> Surface.ROTATION_180
orientation <= 315 -> Surface.ROTATION_270
else -> Surface.ROTATION_0
}
val relative = computeRelativeRotation(characteristics, rotation)
if (relative != value) postValue(relative)
}
}
override fun onActive() {
super.onActive()
listener.enable()
}
override fun onInactive() {
super.onInactive()
listener.disable()
}
companion object {
/**
* Computes rotation required to transform from the camera sensor orientation to the
* device's current orientation in degrees.
*
* @param characteristics the [CameraCharacteristics] to query for the sensor orientation.
* @param surfaceRotation the current device orientation as a Surface constant
* @return the relative rotation from the camera sensor to the current device orientation.
*/
@JvmStatic
private fun computeRelativeRotation(
characteristics: CameraCharacteristics,
surfaceRotation: Int
): Int {
val sensorOrientationDegrees =
characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
val deviceOrientationDegrees = when (surfaceRotation) {
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> 0
}
// Reverse device orientation for front-facing cameras
val sign = if (characteristics.get(CameraCharacteristics.LENS_FACING) ==
CameraCharacteristics.LENS_FACING_FRONT) 1 else -1
// Calculate desired JPEG orientation relative to camera orientation to make
// the image upright relative to the device orientation
return (sensorOrientationDegrees - (deviceOrientationDegrees * sign) + 360) % 360
}
}
}
| CameraXVideo/utils/src/main/java/com/example/android/camera/utils/OrientationLiveData.kt | 2570073423 |
package `in`.shabhushan.cp_trials
object PositionAverages {
fun posAverage(
s: String
) = s.split(", ").let { list ->
var common = 0
(0 until list.size - 1).forEach { row ->
(row + 1 until list.size).forEach { column ->
common += list[row].filterIndexed { index, element ->
element == list[column][index]
}.length
}
}
val total = (list.size.toDouble() * (list.size.toDouble() - 1.0)) / 2.0
common / (total * list.first().length) * 100
}
fun posAverage2(
s: String
) = s.split(", ").let { list ->
val total = list.first().length * (list.size.toDouble() * (list.size.toDouble() - 1.0)) / 2.0
list.mapIndexed { index, string ->
list.drop(index + 1).sumBy { secondString -> string.zip(secondString).count { it.first == it.second } }
}.sum() * 100.0 / total
}
}
| cp-trials/src/main/kotlin/in/shabhushan/cp_trials/PositionAverages.kt | 669212403 |
package `in`.shabhushan.cp_trials.dsbook.`chapter2-recursion`
/**
* Input: 2
* Output:
* 0 0
* 0 1
* 1 0
* 1 1
*/
fun binaryStrings(n: Int): List<String> = if (n == 1) listOf("0", "1") else {
binaryStrings(n - 1).flatMap {
// for each entry, append 0 and 1
listOf("0$it", "1$it")
}
}
| cp-trials/src/main/kotlin/in/shabhushan/cp_trials/dsbook/chapter2-recursion/generateBinaryString.kt | 2443760832 |
/*
* 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.android.horologist.networks.data
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import java.time.Instant
@ExperimentalHorologistNetworksApi
public sealed class Status(public val order: Int) {
@ExperimentalHorologistNetworksApi
public object Available : Status(order = 1) {
override fun toString(): String = "Available"
}
@ExperimentalHorologistNetworksApi
public class Losing(public val instant: Instant) : Status(order = 2) {
override fun toString(): String = "Losing"
}
@ExperimentalHorologistNetworksApi
public object Lost : Status(order = 3) {
override fun toString(): String = "Lost"
}
@ExperimentalHorologistNetworksApi
public object Unknown : Status(order = 4) {
override fun toString(): String = "Unknown"
}
}
| network-awareness/src/main/java/com/google/android/horologist/networks/data/Status.kt | 1434442309 |
package info.papdt.express.helper.ui.dialog
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import info.papdt.express.helper.*
import info.papdt.express.helper.R
import info.papdt.express.helper.dao.SRDatabase
import info.papdt.express.helper.event.EventIntents
import info.papdt.express.helper.model.Category
import info.papdt.express.helper.model.MaterialIcon
import info.papdt.express.helper.ui.ChooseIconActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import moe.feng.kotlinyan.common.*
class EditCategoryDialog : DialogFragment() {
companion object {
const val REASON_EDIT = 0
const val REASON_CREATE = 1
const val EXTRA_REASON = "reason"
const val REQUEST_CODE_CHOOSE_ICON = 20001
fun newCreateDialog(): EditCategoryDialog {
return EditCategoryDialog().apply {
arguments = Bundle().apply {
putInt(EXTRA_REASON, REASON_CREATE)
}
}
}
fun newEditDialog(oldData: Category): EditCategoryDialog {
return EditCategoryDialog().apply {
arguments = Bundle().apply {
putInt(EXTRA_REASON, REASON_EDIT)
putParcelable(EXTRA_OLD_DATA, oldData)
}
}
}
}
private var reason: Int = -1
private lateinit var oldData: Category
private lateinit var data: Category
private lateinit var titleEdit: EditText
private lateinit var iconView: TextView
private var positiveButton: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments!!.let {
reason = it.getInt(EXTRA_REASON, -1)
require(reason == REASON_CREATE || reason == REASON_EDIT)
if (reason == REASON_EDIT) {
oldData = it.getParcelable(EXTRA_OLD_DATA)!!
}
}
if (savedInstanceState == null) {
when (reason) {
REASON_EDIT -> {
data = Category(oldData)
}
REASON_CREATE -> {
data = Category(getString(R.string.category_default_title))
}
}
} else {
data = savedInstanceState.getParcelable(EXTRA_DATA)!!
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelable(EXTRA_DATA, data)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(context).apply {
titleRes = when (reason) {
REASON_CREATE -> R.string.edit_category_dialog_title_for_create
REASON_EDIT -> R.string.edit_category_dialog_title_for_edit
else -> throw IllegalArgumentException()
}
view = createContentView()
positiveButton(R.string.save) { _, _ ->
when (reason) {
REASON_CREATE -> {
sendLocalBroadcast(EventIntents.saveNewCategory(data))
}
REASON_EDIT -> {
sendLocalBroadcast(EventIntents.saveEditCategory(oldData, data))
}
}
}
cancelButton()
if (reason == REASON_EDIT) {
neutralButton(R.string.delete) { _, _ ->
sendLocalBroadcast(EventIntents.requestDeleteCategory(data))
}
}
}.create().apply {
setOnShowListener {
[email protected] = (it as AlertDialog).positiveButton
checkEnabledState()
}
}
}
@SuppressLint("InflateParams")
private fun createContentView(): View {
val view = LayoutInflater.from(context!!).inflate(R.layout.dialog_edit_category, null)
titleEdit = view.findViewById(R.id.category_title_edit)
iconView = view.findViewById(R.id.category_icon_view)
titleEdit.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
data.title = s?.toString()?.trim() ?: ""
checkEnabledState()
}
})
iconView.typeface = MaterialIcon.iconTypeface
updateViewValues()
titleEdit.setSelection(titleEdit.text.length)
val chooseBtn = view.findViewById<Button>(R.id.choose_btn)
chooseBtn.setOnClickListener {
if (!isDetached) {
val intent = Intent(it.context, ChooseIconActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivityForResult(intent, REQUEST_CODE_CHOOSE_ICON)
}
}
return view
}
private fun updateViewValues() {
titleEdit.setText(data.title)
iconView.text = data.iconCode
}
private fun checkEnabledState() {
CoroutineScope(Dispatchers.Main).launch {
var shouldEnabled = !data.title.isEmpty()
if (shouldEnabled) {
when (reason) {
REASON_CREATE -> {
if (SRDatabase.categoryDao.get(data.title) != null) {
shouldEnabled = false
}
}
REASON_EDIT -> {
if (oldData.title != data.title
&& SRDatabase.categoryDao.get(data.title) != null) {
shouldEnabled = false
}
}
}
}
positiveButton?.isEnabled = shouldEnabled
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
when (requestCode) {
REQUEST_CODE_CHOOSE_ICON -> {
if (resultCode == RESULT_OK && intent != null) {
data.iconCode = intent[ChooseIconActivity.EXTRA_RESULT_ICON_CODE]!!.asString()
updateViewValues()
}
}
}
}
private fun sendLocalBroadcast(intent: Intent) {
context?.let { LocalBroadcastManager.getInstance(it).sendBroadcast(intent) }
}
} | mobile/src/main/kotlin/info/papdt/express/helper/ui/dialog/EditCategoryDialog.kt | 2372777085 |
package com.example.android.eyebody
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| EyeBody2/app/src/test/java/com/example/android/eyebody/ExampleUnitTest.kt | 3263078552 |
package com.eden.orchid.groovydoc
import com.eden.orchid.api.generators.OrchidCollection
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.groovydoc.pages.GroovydocClassPage
import com.eden.orchid.groovydoc.pages.GroovydocPackagePage
import java.util.stream.Stream
@Description("A groovydoc Collection represents the pages for all the classes and packages in your Groovy project. A " +
"page is matched from a groovydoc Collection with an 'itemId' matching either the simple class name or the " +
"fully-qualified class or package name."
)
class GroovydocCollection(generator: GroovydocGenerator, collectionId: String, items: List<OrchidPage>)
: OrchidCollection<OrchidPage>(generator, collectionId, items) {
override fun find(id: String): Stream<OrchidPage> {
if(id.contains('.')) {
return items.stream()
.filter { page ->
if (page is GroovydocClassPage) {
page.classDoc.qualifiedName == id
}
else if (page is GroovydocPackagePage) {
page.packageDoc.name == id
}
else {
false
}
}
}
else {
return items.stream()
.filter { page ->
if (page is GroovydocClassPage) {
page.classDoc.name == id
}
else {
false
}
}
}
}
}
| plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/GroovydocCollection.kt | 2639751296 |
package org.jetbrains.dokka.testApi.context
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.DokkaPlugin
import org.jetbrains.dokka.plugability.ExtensionPoint
import org.jetbrains.dokka.utilities.DokkaConsoleLogger
import org.jetbrains.dokka.utilities.LoggingLevel
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.full.memberProperties
@Suppress("UNCHECKED_CAST") // It is only usable from tests so we do not care about safety
class MockContext(
vararg extensions: Pair<ExtensionPoint<*>, (DokkaContext) -> Any>,
private val testConfiguration: DokkaConfiguration? = null,
private val unusedExtensionPoints: List<ExtensionPoint<*>>? = null
) : DokkaContext {
private val extensionMap by lazy {
extensions.groupBy(Pair<ExtensionPoint<*>, (DokkaContext) -> Any>::first) {
it.second(this)
}
}
private val plugins = mutableMapOf<KClass<out DokkaPlugin>, DokkaPlugin>()
override fun <T : DokkaPlugin> plugin(kclass: KClass<T>): T = plugins.getOrPut(kclass) {
kclass.constructors.single { it.parameters.isEmpty() }.call().also { it.injectContext(this) }
} as T
override fun <T : Any, E : ExtensionPoint<T>> get(point: E): List<T> = extensionMap[point].orEmpty() as List<T>
override fun <T : Any, E : ExtensionPoint<T>> single(point: E): T = get(point).single()
override val logger = DokkaConsoleLogger(LoggingLevel.DEBUG)
override val configuration: DokkaConfiguration
get() = testConfiguration ?: throw IllegalStateException("This mock context doesn't provide configuration")
override val unusedPoints: Collection<ExtensionPoint<*>>
get() = unusedExtensionPoints
?: throw IllegalStateException("This mock context doesn't provide unused extension points")
}
private fun DokkaPlugin.injectContext(context: DokkaContext) {
(DokkaPlugin::class.memberProperties.single { it.name == "context" } as KMutableProperty<*>)
.setter.call(this, context)
}
| core/test-api/src/main/kotlin/testApi/context/MockContext.kt | 1539339735 |
import java.io.*
import java.net.*
/**
* A simple java server socket
* Listens on all IPs and port 8080
* @author jsirianni
*/
object SimpleServer {
/**
* Main method does the following:
* Sets global variables; fqdn, port, file, path
* Creates a client socket
* Calls downloadFile() method three times, downloading three different files
*/
@Throws(IOException::class)
@JvmStatic fun main(args: Array<String>) {
// Specify port to listen on
val port = 8080
// Create the socket and accept any incoming connection
val s = ServerSocket(port)
// Accept any incoming connection
val conn = s.accept()
// Create buffered reader and print stream to read and write to the client
val fromClient = BufferedReader(InputStreamReader(conn.getInputStream()))
val toClient = PrintStream(conn.getOutputStream())
// Read client message
var msg = ""
do {
msg = fromClient.readLine()
println(msg)
} while (!msg.isEmpty())
// Send generic response header to client
val resp = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 70\r\nConnection: close\r\n\"";
toClient.println(resp)
// Send html body
val body = "This is not the real content because this server is not yet complete.\r\n"
// Close the connection
conn.close()
} // End Main
} // end class | In_Class_3_Kotlin/src/Server.kt | 2427572874 |
package signatures
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import utils.Tag
import utils.TestOutputWriter
fun TestOutputWriter.renderedContent(path: String = "root/example.html"): Element =
contents.getValue(path).let { Jsoup.parse(it) }.select("#content")
.single()
fun Element.signature(): Elements = select("div.symbol.monospace")
fun Element.tab(tabName: String): Elements = select("div[data-togglable=\"$tabName\"]")
fun Element.firstSignature(): Element = signature().first() ?: throw NoSuchElementException("No signature found")
fun Element.lastSignature(): Element = signature().last() ?: throw NoSuchElementException("No signature found")
class Parameters(vararg matchers: Any) : Tag("span", *matchers, expectedClasses = listOf("parameters"))
class Parameter(vararg matchers: Any) : Tag("span", *matchers, expectedClasses = listOf("parameter")) | plugins/base/base-test-utils/src/main/kotlin/renderers/SignatureUtils.kt | 3884666588 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.domain.playback
import com.doctoror.fuckoffmusicplayer.domain.queue.Media
import java.util.*
/**
* Playback service control
*/
interface PlaybackServiceControl {
fun resendState()
fun playPause()
fun play(queue: List<Media>, position: Int)
fun playAnything()
fun pause()
fun stop()
fun stopWithError(errorMessage: CharSequence)
fun prev()
fun next()
fun seek(positionPercent: Float)
}
| domain/src/main/java/com/doctoror/fuckoffmusicplayer/domain/playback/PlaybackServiceControl.kt | 678470979 |
package rss.sample.com.samplerss.Adapter
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import rss.sample.com.samplerss.Interface.ItemClickListener
import rss.sample.com.samplerss.Model.RootObject
import rss.sample.com.samplerss.R
@Suppress("DEPRECATION")
class FeedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),View.OnClickListener,View.OnLongClickListener{
var txtTitle: TextView
var txtPubdate:TextView
var txtContent:TextView
private var itemClickListener : ItemClickListener?=null
init {
txtTitle = itemView.findViewById<TextView>(R.id.txtTitle)
txtPubdate = itemView.findViewById<TextView>(R.id.txtPubdate)
txtContent = itemView.findViewById<TextView>(R.id.txtContent)
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
fun setItemClickListener(itemClickListener: ItemClickListener){
this.itemClickListener = itemClickListener
}
override fun onClick(p0: View?) {
itemClickListener!!.onClick(p0,position,false)
}
override fun onLongClick(p0: View?): Boolean {
itemClickListener!!.onClick(p0,position,true)
return true
}
}
class FeedAdapter(private val rootObject: RootObject, private val mContext: Context) :RecyclerView.Adapter<FeedViewHolder>(){
private val inflater: LayoutInflater
init {
inflater = LayoutInflater.from(mContext)
}
override fun getItemCount(): Int {
return rootObject.items.size
}
override fun onCreateViewHolder(p0: ViewGroup?, p1: Int): FeedViewHolder {
val itemView = inflater.inflate(R.layout.row,p0,false)
return FeedViewHolder(itemView)
}
override fun onBindViewHolder(p0: FeedViewHolder?, p1: Int) {
p0?.txtTitle?.text = rootObject.items[p1].title
p0?.txtContent?.text = rootObject.items[p1].link
p0?.txtPubdate?.text = rootObject.items[p1].pubDate
p0?.setItemClickListener(ItemClickListener { view, position, isLongClick ->
if (!isLongClick){
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(rootObject.items[position].link))
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
mContext.startActivity(browserIntent)
}
})
}
}
| SampleRss/app/src/main/java/rss/sample/com/samplerss/Adapter/FeedAdapter.kt | 3770490922 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.prefab.api
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class PackageTest {
@Test
fun `isValidVersionForCMake works`() {
assertTrue(isValidVersionForCMake("1"))
assertTrue(isValidVersionForCMake("1.2"))
assertTrue(isValidVersionForCMake("1.2.3"))
assertTrue(isValidVersionForCMake("1.2.3.4"))
assertFalse(isValidVersionForCMake(""))
assertFalse(isValidVersionForCMake("."))
assertFalse(isValidVersionForCMake("1."))
assertFalse(isValidVersionForCMake(".1"))
assertFalse(isValidVersionForCMake(" 1 "))
assertFalse(isValidVersionForCMake("1.2."))
assertFalse(isValidVersionForCMake("1.2.3."))
assertFalse(isValidVersionForCMake("1.2.3.4."))
assertFalse(isValidVersionForCMake("1.2.3.4.5"))
assertFalse(isValidVersionForCMake("a"))
assertFalse(isValidVersionForCMake("1.a"))
assertFalse(isValidVersionForCMake("1.2.a"))
assertFalse(isValidVersionForCMake("1.2.3.a"))
assertFalse(isValidVersionForCMake("1a"))
assertFalse(isValidVersionForCMake("1.2a"))
assertFalse(isValidVersionForCMake("1.2.3a"))
assertFalse(isValidVersionForCMake("1.2.3.4a"))
}
}
| api/src/test/kotlin/com/google/prefab/api/PackageTest.kt | 3569920234 |
package com.booboot.vndbandroid.diff
import androidx.recyclerview.widget.DiffUtil
class StringDiffCallback(private var oldItems: List<String>, private var newItems: List<String>) : DiffUtil.Callback() {
override fun getOldListSize() = oldItems.size
override fun getNewListSize() = newItems.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition] == newItems[newItemPosition]
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition] == newItems[newItemPosition]
} | app/src/main/java/com/booboot/vndbandroid/diff/StringDiffCallback.kt | 3428291826 |
package io.gitlab.arturbosch.detekt.rules.complexity
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Metric
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.ThresholdRule
import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
class MethodOverloading(config: Config = Config.empty,
threshold: Int = ACCEPTED_OVERLOAD_COUNT) : ThresholdRule(config, threshold) {
override val issue = Issue("MethodOverloading", Severity.Maintainability,
"Methods which are overloaded often might be harder to maintain. " +
"Furthermore, these methods are tightly coupled. " +
"Refactor these methods and try to use optional parameters.")
override fun visitClass(klass: KtClass) {
val visitor = OverloadedMethodVisitor()
klass.accept(visitor)
visitor.reportIfThresholdExceeded(klass)
super.visitClass(klass)
}
override fun visitKtFile(file: KtFile) {
val visitor = OverloadedMethodVisitor()
file.children.filterIsInstance<KtNamedFunction>().forEach { it.accept(visitor) }
visitor.reportIfThresholdExceeded(file)
super.visitKtFile(file)
}
internal inner class OverloadedMethodVisitor : DetektVisitor() {
private var methods = HashMap<String, Int>()
fun reportIfThresholdExceeded(element: PsiElement) {
methods.filterValues { it > threshold }.forEach {
report(ThresholdedCodeSmell(issue, Entity.from(element), Metric("OVERLOAD SIZE: ", it.value, threshold)))
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
val name = function.name ?: return
methods.put(name, methods.getOrDefault(name, 0) + 1)
}
}
}
private const val ACCEPTED_OVERLOAD_COUNT = 5
| detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/MethodOverloading.kt | 1048529147 |
package io.gitlab.arturbosch.detekt.api
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
class ExcludesSpec : Spek({
given("an excludes rule with a single exclude") {
val excludes = Excludes("test")
it("contains the `test` parameter") {
val parameter = "test"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains an extension of the `test` parameter") {
val parameter = "test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different parameter") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
it("returns all matches") {
val parameter = "test.com"
val matches = excludes.matches(parameter)
assertThat(matches).hasSize(1)
assertThat(matches).contains("test")
}
}
given("an excludes rule with multiple excludes") {
val excludes = Excludes("here.there.io, test.com")
it("contains the `test` parameter") {
val parameter = "test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains the `here.there.io` parameter") {
val parameter = "here.there.io"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a parameter spanning over the excludes") {
val parameter = "io.test.com"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
}
given("an excludes rule with lots of whitespace and an empty parameter") {
val excludes = Excludes(" test, , here.there ")
it("contains the `test` parameter") {
val parameter = "test"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("contains the `here.there` parameter") {
val parameter = "here.there"
assertThat(excludes.contains(parameter)).isTrue()
assertThat(excludes.none(parameter)).isFalse()
}
it("does not contain a different parameter") {
val parameter = "detekt"
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
it("does not match empty strings") {
val parameter = " "
assertThat(excludes.contains(parameter)).isFalse()
assertThat(excludes.none(parameter)).isTrue()
}
}
})
| detekt-api/src/test/kotlin/io/gitlab/arturbosch/detekt/api/ExcludesSpec.kt | 2180742087 |
package eu.kanade.tachiyomi.ui.catalogue.filter
import android.support.graphics.drawable.VectorDrawableCompat
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.CheckedTextView
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.items.AbstractSectionableItem
import eu.davidea.viewholders.FlexibleViewHolder
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.util.getResourceColor
class SortItem(val name: String, val group: SortGroup) : AbstractSectionableItem<SortItem.Holder, SortGroup>(group) {
override fun getLayoutRes(): Int {
return R.layout.navigation_view_checkedtext
}
override fun getItemViewType(): Int {
return 102
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>): Holder {
return Holder(view, adapter)
}
override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: Holder, position: Int, payloads: List<Any?>?) {
val view = holder.text
view.text = name
val filter = group.filter
val i = filter.values.indexOf(name)
fun getIcon() = when (filter.state) {
Filter.Sort.Selection(i, false) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_down_white_32dp, null)
?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) }
Filter.Sort.Selection(i, true) -> VectorDrawableCompat.create(view.resources, R.drawable.ic_arrow_up_white_32dp, null)
?.apply { setTint(view.context.getResourceColor(R.attr.colorAccent)) }
else -> ContextCompat.getDrawable(view.context, R.drawable.empty_drawable_32dp)
}
view.setCompoundDrawablesWithIntrinsicBounds(getIcon(), null, null, null)
holder.itemView.setOnClickListener {
val pre = filter.state?.index ?: i
if (pre != i) {
filter.state = Filter.Sort.Selection(i, false)
} else {
filter.state = Filter.Sort.Selection(i, filter.state?.ascending == false)
}
group.subItems.forEach { adapter.notifyItemChanged(adapter.getGlobalPositionOf(it)) }
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SortItem
return name == other.name && group == other.group
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + group.hashCode()
return result
}
class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) {
val text: CheckedTextView = itemView.findViewById(R.id.nav_view_item)
}
} | app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/filter/SortItem.kt | 2863240457 |
package com.morph.engine.graphics.shaders
import com.morph.engine.core.Camera
import com.morph.engine.graphics.Color
import com.morph.engine.graphics.components.RenderData
import com.morph.engine.graphics.components.light.Light
import com.morph.engine.math.Matrix4f
import com.morph.engine.math.Vector2f
import com.morph.engine.math.Vector3f
import com.morph.engine.math.Vector4f
import com.morph.engine.physics.components.Transform
import org.lwjgl.opengl.GL20.*
import java.util.*
abstract class Uniforms {
private var uniforms: HashMap<String, Int> = HashMap()
protected lateinit var shader: Shader<*>
fun init(shader: Shader<*>) {
this.shader = shader
}
abstract fun defineUniforms(shader: Int)
abstract fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>)
abstract fun unbind(t: Transform, data: RenderData)
protected fun addUniform(name: String, shader: Int) {
val location = glGetUniformLocation(shader, name)
uniforms[name] = location
}
fun setUniform1i(name: String, value: Int) {
val location = uniforms[name]
location?.let { glUniform1i(it, value) }
}
fun setUniform1f(name: String, value: Float) {
val location = uniforms[name]
location?.let { glUniform1f(it, value) }
}
fun setUniform2f(name: String, value: Vector2f) {
val location = uniforms[name]
location?.let { glUniform2f(it, value.x, value.y) }
}
fun setUniform3f(name: String, value: Vector3f) {
val location = uniforms[name]
location?.let { glUniform3f(it, value.x, value.y, value.z) }
}
fun setUniform3f(name: String, value: Color) {
val location = uniforms[name]
location?.let { glUniform3f(it, value.red, value.green, value.blue) }
}
fun setUniform4f(name: String, value: Vector4f) {
val location = uniforms[name]
location?.let { glUniform4f(it, value.x, value.y, value.z, value.w) }
}
fun setUniform4f(name: String, value: Color) {
val location = uniforms[name]
location?.let { glUniform4f(it, value.red, value.green, value.blue, value.alpha) }
}
fun setUniformMatrix4fv(name: String, value: Matrix4f) {
val location = uniforms[name]
location?.let { glUniformMatrix4fv(it, true, value.toArray()) }
}
}
| src/main/kotlin/com/morph/engine/graphics/shaders/Uniforms.kt | 1107019518 |
/*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.processors.MaterializeEntitySetProcessor
import com.openlattice.authorization.Principal
import com.openlattice.edm.type.PropertyType
import com.openlattice.hazelcast.StreamSerializerTypeIds
import org.springframework.stereotype.Component
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
@Component
class MaterializeEntitySetProcessorStreamSerializer
: SelfRegisteringStreamSerializer<MaterializeEntitySetProcessor>, AssemblerConnectionManagerDependent<Void?> {
companion object {
@JvmStatic
fun serializeAuthorizedPropertyTypesOfPrincipals(
out: ObjectDataOutput, authorizedPropertyTypesOfPrincipals: Map<Principal, Set<PropertyType>>
) {
out.writeInt(authorizedPropertyTypesOfPrincipals.size)
authorizedPropertyTypesOfPrincipals.forEach { (principal, authorizedPropertyTypes) ->
PrincipalStreamSerializer.serialize(out, principal)
out.writeInt(authorizedPropertyTypes.size)
authorizedPropertyTypes.forEach {
PropertyTypeStreamSerializer.serialize(out, it)
}
}
}
@JvmStatic
fun deserializeAuthorizedPropertyTypesOfPrincipals(input: ObjectDataInput): Map<Principal, Set<PropertyType>> {
val principalsSize = input.readInt()
return ((0 until principalsSize).map {
val principal = PrincipalStreamSerializer.deserialize(input)
val authorizedPropertySize = input.readInt()
val authorizedPropertyTypes = ((0 until authorizedPropertySize).map {
PropertyTypeStreamSerializer.deserialize(input)
}.toSet())
principal to authorizedPropertyTypes
}.toMap())
}
}
private lateinit var acm: AssemblerConnectionManager
override fun getTypeId(): Int {
return StreamSerializerTypeIds.MATERIALIZE_ENTITY_SETS_PROCESSOR.ordinal
}
override fun destroy() {
}
override fun getClazz(): Class<MaterializeEntitySetProcessor> {
return MaterializeEntitySetProcessor::class.java
}
override fun write(out: ObjectDataOutput, obj: MaterializeEntitySetProcessor) {
EntitySetStreamSerializer.serialize(out, obj.entitySet)
out.writeInt(obj.materializablePropertyTypes.size)
obj.materializablePropertyTypes.forEach { (propertyTypeId, propertyType) ->
UUIDStreamSerializerUtils.serialize(out, propertyTypeId)
PropertyTypeStreamSerializer.serialize(out, propertyType)
}
serializeAuthorizedPropertyTypesOfPrincipals(out, obj.authorizedPropertyTypesOfPrincipals)
}
override fun read(input: ObjectDataInput): MaterializeEntitySetProcessor {
val entitySet = EntitySetStreamSerializer.deserialize(input)
val materializablePropertySize = input.readInt()
val materializablePropertyTypes = ((0 until materializablePropertySize).map {
UUIDStreamSerializerUtils.deserialize(input) to PropertyTypeStreamSerializer.deserialize(input)
}.toMap())
val authorizedPropertyTypesOfPrincipals = deserializeAuthorizedPropertyTypesOfPrincipals(input)
return MaterializeEntitySetProcessor(
entitySet, materializablePropertyTypes, authorizedPropertyTypesOfPrincipals
).init(acm)
}
override fun init(acm: AssemblerConnectionManager): Void? {
this.acm = acm
return null
}
} | src/main/kotlin/com/openlattice/hazelcast/serializers/MaterializeEntitySetProcessorStreamSerializer.kt | 4203614617 |
package com.estore.controller
import com.estore.commerce.order.entity.Order
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController
@RestController
class OrderController {
@GetMapping("/order/{orderId}")
fun get(@PathVariable orderId: String) = Order(orderId)
} | EStore/Rest/src/main/kotlin/com/estore/controller/OrderController.kt | 3450203008 |
package testing
/**
* Created by zaqwes on 3/29/15.
*/
//fun main(args : Array<String>) {
// println("Hello, world!")
//}
//fun main(args : Array<String>) {
// if (args.size == 0) {
// println("Please provide a name as a command-line argument")
// return
// }
// println("Hello, ${args[0]}!")
//}
/*fun main(args : Array<String>) {
for (name in args)
println("Hello, $name!")
}*/
fun main(args: Array<String>) {
val language = if (args.size == 0) "EN" else args[0]
println(when (language) {
"EN" -> "Hello!"
"FR" -> "Salut!"
"IT" -> "Ciao!"
"seyfer" -> "seed!"
else -> "Sorry, I can't greet you in $language yet"
})
} | buffer/jvm-tricks/lang_cores/kotlin/src/testing/first.kt | 635231282 |
package nl.pixelcloud.foresale_ai.api.game.response
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by Rob Peek on 16/06/16.
*/
open class CreateGameResponse {
@SerializedName("Id")
@Expose
open var gameId: String? = null
} | foresale-ai/app/src/main/java/nl/pixelcloud/foresale_ai/api/game/response/CreateGameResponse.kt | 2565246631 |
@file:JsNonModule
@file:JsModule("lodash")
package lodash
external fun debounce(func: () -> Unit, wait: Int? = definedExternally, options: Any? = definedExternally): Function<Any>
external fun capitalize(string: String): String | guide/computed/main/lodash/Lodash.kt | 843899923 |
package io.gitlab.arturbosch.detekt.generator.printer.rulesetpage
import io.gitlab.arturbosch.detekt.generator.collection.Rule
import io.gitlab.arturbosch.detekt.generator.out.MarkdownContent
import io.gitlab.arturbosch.detekt.generator.out.bold
import io.gitlab.arturbosch.detekt.generator.out.code
import io.gitlab.arturbosch.detekt.generator.out.codeBlock
import io.gitlab.arturbosch.detekt.generator.out.crossOut
import io.gitlab.arturbosch.detekt.generator.out.description
import io.gitlab.arturbosch.detekt.generator.out.h3
import io.gitlab.arturbosch.detekt.generator.out.h4
import io.gitlab.arturbosch.detekt.generator.out.item
import io.gitlab.arturbosch.detekt.generator.out.list
import io.gitlab.arturbosch.detekt.generator.out.markdown
import io.gitlab.arturbosch.detekt.generator.out.paragraph
import io.gitlab.arturbosch.detekt.generator.printer.DocumentationPrinter
object RuleSetPagePrinter : DocumentationPrinter<RuleSetPage> {
override fun print(item: RuleSetPage): String {
return markdown {
if (item.ruleSet.description.isNotEmpty()) {
paragraph { item.ruleSet.description }
} else {
paragraph { "TODO: Specify description" }
}
item.rules.forEach {
markdown { printRule(it) }
}
}
}
private fun printRule(rule: Rule): String {
return markdown {
h3 { rule.name }
if (rule.description.isNotEmpty()) {
paragraph { rule.description }
} else {
paragraph { "TODO: Specify description" }
}
if (rule.severity.isNotEmpty()) {
paragraph {
"${bold { "Severity" }}: ${rule.severity}"
}
}
if (rule.debt.isNotEmpty()) {
paragraph {
"${bold { "Debt" }}: ${rule.debt}"
}
}
if (!rule.aliases.isNullOrEmpty()) {
paragraph {
"${bold { "Aliases" }}: ${rule.aliases}"
}
}
if (rule.configuration.isNotEmpty()) {
h4 { "Configuration options:" }
list {
rule.configuration.forEach {
if (it.deprecated != null) {
item {
crossOut { code { it.name } } + " (default: ${code { it.defaultValue }})"
}
description { "${bold { "Deprecated" }}: ${it.deprecated}" }
} else {
item { "${code { it.name }} (default: ${code { it.defaultValue }})" }
}
description { it.description }
}
}
}
printRuleCodeExamples(rule)
}
}
private fun MarkdownContent.printRuleCodeExamples(rule: Rule) {
if (rule.nonCompliantCodeExample.isNotEmpty()) {
h4 { "Noncompliant Code:" }
paragraph { codeBlock { rule.nonCompliantCodeExample } }
}
if (rule.compliantCodeExample.isNotEmpty()) {
h4 { "Compliant Code:" }
paragraph { codeBlock { rule.compliantCodeExample } }
}
}
}
| detekt-generator/src/main/kotlin/io/gitlab/arturbosch/detekt/generator/printer/rulesetpage/RuleSetPagePrinter.kt | 3584407466 |
package de.westnordost.streetcomplete.quests.address
sealed class HousenumberAnswer
data class ConscriptionNumber(val number: String, val streetNumber: String? = null) : HousenumberAnswer()
data class HouseNumber(val number: String) : HousenumberAnswer()
data class HouseName(val name: String) : HousenumberAnswer()
data class HouseAndBlockNumber(val houseNumber: String, val blockNumber: String) : HousenumberAnswer()
object NoHouseNumber : HousenumberAnswer()
data class StillBeingConstructed(val currentBuildingValue: String) : HousenumberAnswer()
object WrongBuildingType : HousenumberAnswer()
| app/src/main/java/de/westnordost/streetcomplete/quests/address/HousenumberAnswer.kt | 89789799 |
package me.jahnen.libaums.server.http.server
import android.util.Log
import me.jahnen.libaums.core.fs.UsbFileInputStream
import me.jahnen.libaums.server.http.UsbFileProvider
import me.jahnen.libaums.server.http.exception.NotAFileException
import com.koushikdutta.async.AsyncServer
import com.koushikdutta.async.http.server.AsyncHttpServerRequest
import com.koushikdutta.async.http.server.AsyncHttpServerResponse
import com.koushikdutta.async.http.server.HttpServerRequestCallback
import java.io.FileNotFoundException
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
/**
* Created by magnusja on 16/12/16.
*/
class AsyncHttpServer(private val port: Int) : HttpServer, HttpServerRequestCallback {
override lateinit var usbFileProvider: UsbFileProvider
private val server = com.koushikdutta.async.http.server.AsyncHttpServer()
override var isAlive = false
override val hostname: String
get() = ""
override val listeningPort: Int
get() = port
init {
server.get("/.*", this)
}
@Throws(IOException::class)
override fun start() {
server.listen(port)
isAlive = true
}
@Throws(IOException::class)
override fun stop() {
server.stop()
// force the server to stop even if there are ongoing connections
AsyncServer.getDefault().stop()
isAlive = false
}
override fun onRequest(request: AsyncHttpServerRequest, response: AsyncHttpServerResponse) {
val uri: String
try {
uri = URLDecoder.decode(request.path, "utf-8")
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "could not decode URL", e)
response.code(404)
response.send(e.message)
return
}
Log.d(TAG, "Uri: $uri")
try {
val fileToServe = usbFileProvider.determineFileToServe(uri)
response.sendStream(UsbFileInputStream(fileToServe), fileToServe.length)
} catch (e: FileNotFoundException) {
response.code(404)
response.send(e.message)
} catch (e: NotAFileException) {
response.code(400)
response.send(e.message)
} catch (e: IOException) {
response.code(500)
response.send(e.message)
}
}
companion object {
private val TAG = AsyncHttpServer::class.java.simpleName
}
}
| httpserver/src/main/java/me/jahnen/libaums/server/http/server/AsyncHttpServer.kt | 2126014610 |
/*
* Copyright 2014 DogmaLabs
*
* 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.boardgamegeek.ui.widget
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.NinePatchDrawable
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.withStyledAttributes
import com.boardgamegeek.R
class ForegroundImageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
private var foreground: Drawable? = null
private val rectPadding = Rect()
private var foregroundPadding = false
private var foregroundBoundsChanged = false
init {
context.withStyledAttributes(attrs, R.styleable.ForegroundImageView, defStyleAttr, defStyleRes) {
foregroundPadding = getBoolean(R.styleable.ForegroundImageView_foregroundInsidePadding, false)
// Apply foreground padding for nine patches automatically
if (!foregroundPadding) {
if ((background as? NinePatchDrawable)?.getPadding(rectPadding) == true) {
foregroundPadding = true
}
}
setForeground(getDrawable(R.styleable.ForegroundImageView_android_foreground))
}
}
/**
* Supply a Drawable that is to be rendered on top of all of the child views in the layout.
*
* @param drawable The Drawable to be drawn on top of the children.
*/
override fun setForeground(drawable: Drawable?) {
if (foreground !== drawable) {
foreground?.callback = null
unscheduleDrawable(foreground)
foreground = drawable
if (drawable != null) {
setWillNotDraw(false)
drawable.callback = this
if (drawable.isStateful) drawable.state = drawableState
} else {
setWillNotDraw(true)
}
requestLayout()
invalidate()
}
}
/**
* Returns the drawable used as the foreground of this layout. The foreground drawable,
* if non-null, is always drawn on top of the children.
*
* @return A Drawable or null if no foreground was set.
*/
override fun getForeground(): Drawable? {
return foreground
}
override fun drawableStateChanged() {
super.drawableStateChanged()
if (foreground?.isStateful == true) {
foreground?.state = drawableState
}
}
override fun verifyDrawable(who: Drawable): Boolean {
return super.verifyDrawable(who) || who === foreground
}
override fun jumpDrawablesToCurrentState() {
super.jumpDrawablesToCurrentState()
foreground?.jumpToCurrentState()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
foregroundBoundsChanged = true
}
override fun draw(canvas: Canvas) {
super.draw(canvas)
if (foreground != null) {
val foreground = this.foreground as Drawable
if (foregroundBoundsChanged) {
foregroundBoundsChanged = false
val w = right - left
val h = bottom - top
if (foregroundPadding) {
foreground.setBounds(rectPadding.left, rectPadding.top, w - rectPadding.right, h - rectPadding.bottom)
} else {
foreground.setBounds(0, 0, w, h)
}
}
foreground.draw(canvas)
}
}
@SuppressLint("ClickableViewAccessibility")
@TargetApi(VERSION_CODES.LOLLIPOP)
override fun onTouchEvent(e: MotionEvent): Boolean {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
if (e.actionMasked == MotionEvent.ACTION_DOWN) {
foreground?.setHotspot(e.x, e.y)
}
}
return super.onTouchEvent(e)
}
override fun drawableHotspotChanged(x: Float, y: Float) {
super.drawableHotspotChanged(x, y)
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
foreground?.setHotspot(x, y)
}
}
}
| app/src/main/java/com/boardgamegeek/ui/widget/ForegroundImageView.kt | 2474124280 |
package com.boardgamegeek.mappers
import com.boardgamegeek.entities.BriefBuddyEntity
import com.boardgamegeek.entities.UserEntity
import com.boardgamegeek.io.model.Buddy
import com.boardgamegeek.io.model.User
import com.boardgamegeek.provider.BggContract
fun User.mapToEntity() = UserEntity(
internalId = BggContract.INVALID_ID.toLong(),
id = id.toIntOrNull() ?: BggContract.INVALID_ID,
userName = name,
firstName = firstName,
lastName = lastName,
avatarUrlRaw = avatarUrl,
)
fun Buddy.mapToEntity(timestamp: Long) = BriefBuddyEntity(
id = id.toIntOrNull() ?: BggContract.INVALID_ID,
userName = name,
updatedTimestamp = timestamp,
)
| app/src/main/java/com/boardgamegeek/mappers/UserMapper.kt | 1551031897 |
package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
class LastPlayDateAscendingSorter(context: Context) : LastPlayDateSorter(context) {
@StringRes
public override val typeResId = R.string.collection_sort_type_play_date_min
@StringRes
override val descriptionResId = R.string.collection_sort_play_date_min
override fun sort(items: Iterable<CollectionItemEntity>) = items.sortedBy { it.lastPlayDate }
} | app/src/main/java/com/boardgamegeek/sorter/LastPlayDateAscendingSorter.kt | 2762853045 |
// This file was automatically generated from json.md by Knit tool. Do not edit.
package example.exampleJson09
import kotlinx.serialization.*
import kotlinx.serialization.json.*
val format = Json { allowSpecialFloatingPointValues = true }
@Serializable
class Data(
val value: Double
)
fun main() {
val data = Data(Double.NaN)
println(format.encodeToString(data))
}
| guide/example/example-json-09.kt | 110051788 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.registry.type.data
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.server.registry.internalCatalogTypeRegistry
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.spongepowered.api.data.type.LlamaType
val LlamaTypeRegistry = internalCatalogTypeRegistry<LlamaType> {
fun register(id: String) =
register(LanternLlamaType(minecraftKey(id)))
register("creamy")
register("white")
register("brown")
register("gray")
}
private class LanternLlamaType(key: NamespacedKey) : DefaultCatalogType(key), LlamaType
| src/main/kotlin/org/lanternpowered/server/registry/type/data/LlamaTypeRegistry.kt | 1965510257 |
package com.mercadopago.android.px.tracking.internal.views
import com.mercadopago.android.px.model.exceptions.MercadoPagoError
import com.mercadopago.android.px.tracking.internal.TrackFactory
import com.mercadopago.android.px.tracking.internal.TrackWrapper
import com.mercadopago.android.px.tracking.internal.model.ApiErrorData
class ErrorViewTracker(errorMessage: String, mpError: MercadoPagoError) : TrackWrapper() {
private val data = mutableMapOf<String, Any>().also {
it["error_message"] = errorMessage
it["api_error"] = ApiErrorData(mpError).toMap()
}
override fun getTrack() = TrackFactory.withView(PATH).addData(data).build()
companion object {
private const val PATH = "$BASE_PATH/generic_error"
}
} | px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/views/ErrorViewTracker.kt | 4228712126 |
package pyxis.uzuki.live.richutilskt.service
import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Binder
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.WindowManager
import pyxis.uzuki.live.richutilskt.impl.F1
import pyxis.uzuki.live.richutilskt.utils.locationManager
import pyxis.uzuki.live.richutilskt.utils.sensorManager
import pyxis.uzuki.live.richutilskt.utils.windowManager
import java.io.IOException
import java.util.*
@SuppressLint("MissingPermission")
class RLocationService : Service() {
private val gpsLocationListener = LocationChangeListener()
private val networkLocationListener = LocationChangeListener()
private val sensorEventListener = SensorListener()
private val localBinder = LocalBinder()
private val TWO_MINUTES = 1000 * 60 * 2
private val MIN_BEARING_DIFF = 2.0f
private val FASTEST_INTERVAL_IN_MS = 1000L
private var bearing: Float = 0f
private var axisX: Int = 0
private var axisY: Int = 0
var currentBestLocation: Location? = null
private var locationCallback: LocationCallback? = null
override fun onBind(intent: Intent?) = localBinder
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
override fun onCreate() {
super.onCreate()
getLocation()
}
override fun onDestroy() {
super.onDestroy()
stopUpdates()
sensorManager.unregisterListener(sensorEventListener)
}
/**
* get location of user.
* this service using 3 methods for fetch location. (Mobile, GPS, Sensor)
*/
fun getLocation() {
val lastKnownGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
val lastKnownNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
var bestLastKnownLocation = currentBestLocation
if (lastKnownGpsLocation != null && isBetterLocation(lastKnownGpsLocation, bestLastKnownLocation)) {
bestLastKnownLocation = lastKnownGpsLocation
}
if (lastKnownNetworkLocation != null && isBetterLocation(lastKnownNetworkLocation, bestLastKnownLocation)) {
bestLastKnownLocation = lastKnownNetworkLocation
}
currentBestLocation = bestLastKnownLocation
if (locationManager.allProviders.contains(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, gpsLocationListener)
}
if (locationManager.allProviders.contains(LocationManager.NETWORK_PROVIDER) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, networkLocationListener)
}
bestLastKnownLocation?.bearing = bearing
locationCallback?.handleNewLocation(currentBestLocation as Location)
val mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
sensorManager.registerListener(sensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL * 5)
}
/**
* Set callback for location service.
* any location updates will invoke this callback (except new location data is not-best-location.)
*/
fun setLocationCallback(callback: (Location) -> Unit) {
locationCallback = object : LocationCallback, (Location) -> Unit {
override fun invoke(location: Location) {
callback.invoke(location)
}
override fun handleNewLocation(location: Location) {
callback.invoke(location)
}
}
}
/**
* Set callback for location service.
* any location updates will invoke this callback (except new location data is not-best-location.)
*/
fun setLocationCallback(callback: F1<Location>) {
locationCallback = object : LocationCallback, (Location) -> Unit {
override fun invoke(location: Location) {
callback.invoke(location)
}
override fun handleNewLocation(location: Location) {
callback.invoke(location)
}
}
}
/**
* stop location update service
*/
fun stopUpdates() {
locationManager.removeUpdates(gpsLocationListener)
locationManager.removeUpdates(networkLocationListener)
sensorManager.unregisterListener(sensorEventListener)
}
/**
* get Address from CurrentBestLocation
*
* @return List<Address> or null
*/
fun Context.getGeoCoderAddress(): List<Address>? {
val geoCoder = Geocoder(this, Locale.ENGLISH)
try {
return geoCoder.getFromLocation(currentBestLocation?.latitude ?: 0.0, currentBestLocation?.longitude ?: 0.0, 1)
} catch (e: IOException) {
Log.e(RLocationService::class.java.simpleName, "Impossible to connect to Geocoder", e)
}
return null
}
private fun Context.getFirstAddress(): Address? {
val addresses = getGeoCoderAddress()
if (addresses != null && addresses.isNotEmpty())
return addresses[0]
else
return null
}
/**
* get AddressLine
*
* @return addressLine of current Best Location
*/
fun Context.getAddressLine(): String = getFirstAddress()?.getAddressLine(0) ?: ""
/**
* get locality
*
* @return locality of current Best Location
*/
fun Context.getLocality(): String = getFirstAddress()?.locality ?: ""
/**
* get postal code
*
* @return postal code of current Best Location
*/
fun Context.getPostalCode(): String = getFirstAddress()?.postalCode ?: ""
/**
* get country name
*
* @return country name of current Best Location
*/
fun Context.getCountryName(): String = getFirstAddress()?.countryName ?: ""
private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean {
if (currentBestLocation == null) {
// μ΄μ μ μ μ₯ν κ²μ΄ μλ€λ©΄ μλ‘ μ¬μ©
return true
}
val timeDelta = location.time - currentBestLocation.time
val isSignificantlyNewer = timeDelta > TWO_MINUTES // μκ°μ°¨ 2λΆ μ΄μ?
val isSignificantlyOlder = timeDelta < -TWO_MINUTES // μλλ©΄ λ μ€λλμλμ§
val isNewer = timeDelta > 0 // μ κ· μμΉμ 보 νμ
// λ§μΌ 2λΆμ΄μ μ°¨μ΄λλ€λ©΄ μλ‘μ΄κ±° μ¬μ© (μ μ κ° μμ§μ΄κΈ° λλ¬Έ)
if (isSignificantlyNewer) {
return true
} else if (isSignificantlyOlder) {
return false
}
// Check whether the new location fix is more or less accurate
val accuracyDelta = (location.accuracy - currentBestLocation.accuracy).toInt()
val isLessAccurate = accuracyDelta > 0 // κΈ°μ‘΄κ±°κ° λ μ νν¨
val isMoreAccurate = accuracyDelta < 0 // μ κ·κ° λ μ νν¨
val isSignificantlyLessAccurate = accuracyDelta > 200 // 200μ΄μ μ¬κ°νκ² μ°¨μ΄λ¨
val isFromSameProvider = isSameProvider(location.provider, currentBestLocation.provider) // κ°μ νλ‘λ°μ΄λμΈμ§
if (isMoreAccurate) {// λ μ ννλ©΄?
return true
} else if (isNewer && !isLessAccurate) {// μλ‘μ΄ λ°μ΄ν°μ΄κ³ μ κ·κ° μ ννκ±°λ κ°μλ
return true
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {// μλ‘μ΄ λ°μ΄ν°μ΄κ³ λ무 μ°¨μ΄λμ§ μκ³ κ°μ νλ‘λ°μ΄λμΈ κ²½μ°
return true
}
return false
}
private fun isSameProvider(provider1: String?, provider2: String?): Boolean = if (provider1 == null) provider2 == null else provider1 == provider2
private inner class LocationChangeListener : android.location.LocationListener {
override fun onLocationChanged(location: Location?) {
if (location == null) {
return
}
if (isBetterLocation(location, currentBestLocation)) {
currentBestLocation = location
currentBestLocation?.bearing = bearing
locationCallback?.handleNewLocation(currentBestLocation as Location)
}
}
override fun onProviderDisabled(provider: String?) {}
override fun onProviderEnabled(provider: String?) {}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
}
private inner class SensorListener : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
if (sensor?.type == Sensor.TYPE_ROTATION_VECTOR) {
Log.i(RLocationService::class.java.simpleName, "Rotation sensor accuracy changed to: " + accuracy)
}
}
override fun onSensorChanged(event: SensorEvent?) {
val rotationMatrix = FloatArray(16)
SensorManager.getRotationMatrixFromVector(rotationMatrix, event?.values)
val orientationValues = FloatArray(3)
readDisplayRotation()
SensorManager.remapCoordinateSystem(rotationMatrix, axisX, axisY, rotationMatrix)
SensorManager.getOrientation(rotationMatrix, orientationValues)
val azimuth = Math.toDegrees(orientationValues[0].toDouble())
val newBearing = azimuth
val abs = Math.abs(bearing.minus(newBearing).toFloat()) > MIN_BEARING_DIFF
if (abs) {
bearing = newBearing.toFloat()
currentBestLocation?.bearing = bearing
}
}
}
private fun readDisplayRotation() {
axisX = SensorManager.AXIS_X
axisY = SensorManager.AXIS_Y
when (windowManager.defaultDisplay.rotation) {
Surface.ROTATION_90 -> {
axisX = SensorManager.AXIS_Y
axisY = SensorManager.AXIS_MINUS_X
}
Surface.ROTATION_180 -> axisY = SensorManager.AXIS_MINUS_Y
Surface.ROTATION_270 -> {
axisX = SensorManager.AXIS_MINUS_Y
axisY = SensorManager.AXIS_X
}
}
}
inner class LocalBinder : Binder() {
val service: RLocationService
get() = this@RLocationService
}
interface LocationCallback {
fun handleNewLocation(location: Location)
}
} | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/service/RLocationService.kt | 1349326143 |
package io.rover.sdk.notifications
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.rover.core.R
import io.rover.sdk.core.assets.AssetService
import io.rover.sdk.core.data.NetworkResult
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.onErrorReturn
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.core.streams.subscribeOn
import io.rover.sdk.core.streams.timeout
import io.rover.sdk.notifications.domain.NotificationAttachment
import io.rover.sdk.notifications.ui.concerns.NotificationsRepositoryInterface
import org.reactivestreams.Publisher
import java.util.concurrent.TimeUnit
/**
* Responsible for adding a [Notification] to the Android notification area as well as the Rover
* Notification Center.
*/
class NotificationDispatcher(
private val applicationContext: Context,
private val mainThreadScheduler: Scheduler,
// add this back after solving injection issues.
private val notificationsRepository: NotificationsRepositoryInterface,
private val notificationOpen: NotificationOpenInterface,
private val assetService: AssetService,
private val influenceTrackerService: InfluenceTrackerServiceInterface,
/**
* A small icon is necessary for Android push notifications. Pass a resid.
*
* Android design guidelines suggest that you use a multi-level drawable for your application
* icon, such that you can specify one of its levels that is most appropriate as a single-colour
* silhouette that can be used in the Android notification drawer.
*/
@param:DrawableRes
private val smallIconResId: Int,
/**
* The drawable level of [smallIconResId] that should be used for the icon silhouette used in
* the notification drawer.
*/
private val smallIconDrawableLevel: Int = 0,
/**
* This Channel Id will be used for any push notifications arrive without an included Channel
* Id.
*/
private val defaultChannelId: String? = null,
private val iconColor: Int? = null
) {
fun ingest(notificationFromAction: io.rover.sdk.notifications.domain.Notification) {
Publishers.defer {
processNotification(notificationFromAction)
}.subscribeOn(mainThreadScheduler).subscribe {} // TODO: do not use subscriber like this, it will leak
}
/**
* By default, if running on Oreo and later, and the [NotificationsAssembler.defaultChannelId] you
* gave does not exist, then we will lazily create it at notification reception time to
* avoid the
*
* We include a default implementation here, however, you should consider registering your own
* channel ID in your application initialization and passing it to the NotificationAssembler()
* constructor.
*/
@RequiresApi(Build.VERSION_CODES.O)
fun registerDefaultChannelId() {
log.w(
"Rover is registering a default channel ID for you. This isn't optimal; if you are targeting Android SDK >= 26 then you should create your Notification Channels.\n" +
"See https://developer.android.com/training/notify-user/channels.html"
)
// Create the NotificationChannel
val name = applicationContext.getString(R.string.default_notification_channel_name)
val description = applicationContext.getString(R.string.default_notification_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(defaultChannelId, name, importance)
mChannel.description = description
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = applicationContext.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
private fun processNotification(notification: io.rover.sdk.notifications.domain.Notification): Publisher<Unit> {
// notify the influenced opens tracker that a notification is being executed.
influenceTrackerService.notifyNotificationReceived(notification)
verifyChannelSetUp()
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder(applicationContext, notification.channelId ?: defaultChannelId ?: NotificationChannel.DEFAULT_CHANNEL_ID)
} else {
@Suppress("DEPRECATION") // Only in use to support legacy Android API.
NotificationCompat.Builder(applicationContext)
}
builder.setContentTitle(notification.title)
builder.setContentText(notification.body)
iconColor?.let {
builder.color = it
}
builder.setStyle(NotificationCompat.BigTextStyle())
builder.setSmallIcon(smallIconResId, smallIconDrawableLevel)
notificationsRepository.notificationArrivedByPush(notification)
builder.setContentIntent(
notificationOpen.pendingIntentForAndroidNotification(
notification
)
)
// Set large icon and Big Picture as needed by Rich Media values. Enforce a timeout
// so we don't fail to create the notification in the allotted 10s if network doesn't
// cooperate.
val attachmentBitmapPublisher: Publisher<NetworkResult<Bitmap>?> = when (notification.attachment) {
is NotificationAttachment.Image -> {
assetService.getImageByUrl(notification.attachment.url)
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.onErrorReturn { error ->
// log.w("Timed out fetching notification image. Will create image without the rich media.")
NetworkResult.Error<Bitmap>(error, false)
}
}
null -> Publishers.just(null)
else -> {
log.w("Notification attachments of type ${notification.attachment.typeName} not supported on Android.")
Publishers.just(null)
}
}
return attachmentBitmapPublisher
.doOnNext { attachmentBitmapResult ->
when (attachmentBitmapResult) {
is NetworkResult.Success<*> -> {
builder.setLargeIcon(attachmentBitmapResult.response as Bitmap)
builder.setStyle(
NotificationCompat.BigPictureStyle()
.bigPicture(attachmentBitmapResult.response as Bitmap)
)
}
is NetworkResult.Error -> {
log.w("Unable to retrieve notification image: ${notification.attachment?.url}, because: ${attachmentBitmapResult.throwable.message}")
log.w("Will create image without the rich media.")
}
null -> {
/* no-op, from errors handled previously in pipeline */
}
}
notificationManager.notify(
notification.id,
// "ROVR" in ascii. just to further avoid collision with any non-Rover notifications.
0x524F5652,
builder.build().apply {
this.flags = this.flags or Notification.FLAG_AUTO_CANCEL
}
)
}.map { Unit }
}
private val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(applicationContext)
@SuppressLint("NewApi")
private fun verifyChannelSetUp() {
val notificationManager = applicationContext.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val existingChannel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.getNotificationChannel(defaultChannelId)
} else {
return
}
if (existingChannel == null) registerDefaultChannelId()
}
companion object {
/**
* Android gives push handlers 10 seconds to complete.
*
* If we can't get our image downloaded in the 10 seconds, instead of failing we want to
* timeout gracefully.
*/
private const val TIMEOUT_SECONDS = 8L
}
}
| notifications/src/main/kotlin/io/rover/sdk/notifications/NotificationDispatcher.kt | 2196769974 |
package six.ca.crashcases.fragment.data
/**
* @author hellenxu
* @date 2020-10-02
* Copyright 2020 Six. All rights reserved.
*/
enum class AccountType {
VIP,
STANDARD,
GUEST
} | CrashCases/app/src/main/java/six/ca/crashcases/fragment/data/AccountType.kt | 470781626 |
package nl.hannahsten.texifyidea.structure.latex
import com.intellij.psi.PsiElement
import com.intellij.ui.breadcrumbs.BreadcrumbsProvider
import nl.hannahsten.texifyidea.LatexLanguage
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexEnvironment
import nl.hannahsten.texifyidea.util.name
/**
* @author Hannah Schellekens
*/
open class LatexBreadcrumbsInfo : BreadcrumbsProvider {
override fun getLanguages() = arrayOf(LatexLanguage)
override fun getElementInfo(element: PsiElement) = when (element) {
is LatexEnvironment -> element.name()?.text
is LatexCommands -> element.commandToken.text
else -> ""
} ?: ""
override fun acceptElement(element: PsiElement) = when (element) {
is LatexEnvironment -> true
is LatexCommands -> true
else -> false
}
} | src/nl/hannahsten/texifyidea/structure/latex/LatexBreadcrumbsInfo.kt | 4293564999 |
package com.percent.config
import java.io.File
class ProguardConfig(private val pathToFiles: String) {
val customRules by lazy {
File(pathToFiles).listFiles().toList().toTypedArray()
}
val androidRules by lazy {
"proguard-android-optimize.txt"
}
}
| buildSrc/src/main/kotlin/com/percent/config/ProguardConfig.kt | 1156643964 |
package io.rover.sdk.core.assets
import android.graphics.Bitmap
import io.rover.sdk.core.data.NetworkResult
import org.reactivestreams.Publisher
import java.net.URL
/**
* A pipeline step that does I/O operations of (fetch, cache, etc.) an asset.
*
* Stages will synchronously block the thread while waiting for I/O.
*
* Stages should not block to do computation-type work, however; the asset pipeline is
* run on a thread pool optimized for I/O multiplexing and not computation.
*/
interface SynchronousPipelineStage<in TInput, TOutput> {
fun request(input: TInput): PipelineStageResult<TOutput>
}
sealed class PipelineStageResult<TOutput> {
class Successful<TOutput>(val output: TOutput) : PipelineStageResult<TOutput>()
class Failed<TOutput>(val reason: Throwable) : PipelineStageResult<TOutput>()
}
interface AssetService {
/**
* Subscribe to any updates for the image at URL, fully decoded and ready for display.
*
* It will complete after successfully yielding once. However, it will not attempt
*
* The Publisher will yield on the app's main UI thread.
*/
fun imageByUrl(
url: URL
): Publisher<Bitmap>
/**
* Use this to request and wait for a single update to the given image asset by URI. Use this
* is lieu of [imageByUrl] if you need to subscribe to a single update.
*/
fun getImageByUrl(
url: URL
): Publisher<NetworkResult<Bitmap>>
// TODO: the aggregation behaviour will go in the Asset Service.
/**
* Request a fetch. Be sure you are subscribed to [imageByUrl] to receive the updates.
*/
fun tryFetch(
url: URL
)
}
| core/src/main/kotlin/io/rover/sdk/core/assets/Interfaces.kt | 2992217543 |
package V12.vcsRoots
import jetbrains.buildServer.configs.kotlin.v10.*
import jetbrains.buildServer.configs.kotlin.v10.vcs.GitVcsRoot
object V12_HttpsGithubComBlazemeterBlazemeterTeamcityPluginGit : GitVcsRoot({
uuid = "85215b31-0a56-4631-80db-b887bcfafb76"
extId = "V12_HttpsGithubComBlazemeterBlazemeterTeamcityPluginGit"
name = "https://github.com/Blazemeter/blazemeter-teamcity-plugin.git"
url = "https://github.com/Blazemeter/blazemeter-teamcity-plugin.git"
authMethod = password {
userName = "dzmitrykashlach"
password = "zxx32d0d0b60a93b71c38001e55fbdf48f61ade0569e1203941ef4e9ec6edeb277439b13a0073a13c50775d03cbe80d301b"
}
})
| .teamcity/V12/vcsRoots/V12_HttpsGithubComBlazemeterBlazemeterTeamcityPluginGit.kt | 3424572975 |
package com.prt2121.pojo.rx
/**
* Created by pt2121 on 11/7/15.
*/
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.application.Platform
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.util.Duration
import rx.Scheduler
import rx.Subscription
import rx.functions.Action0
import rx.subscriptions.BooleanSubscription
import rx.subscriptions.CompositeSubscription
import rx.subscriptions.Subscriptions
import java.util.concurrent.TimeUnit
import java.lang.Math.max
class JavaFxScheduler internal constructor() : Scheduler() {
override fun createWorker(): Worker {
return InnerJavaFxScheduler()
}
private class InnerJavaFxScheduler : Worker() {
private val innerSubscription = CompositeSubscription()
override fun unsubscribe() {
innerSubscription.unsubscribe()
}
override fun isUnsubscribed(): Boolean {
return innerSubscription.isUnsubscribed
}
override fun schedule(action: Action0, delayTime: Long, unit: TimeUnit): Subscription {
val s = BooleanSubscription.create()
val delay = unit.toMillis(max(delayTime, 0))
val timeline = Timeline(KeyFrame(Duration.millis(delay.toDouble()), object : EventHandler<ActionEvent> {
override fun handle(event: ActionEvent) {
if (innerSubscription.isUnsubscribed || s.isUnsubscribed) {
return
}
action.call()
innerSubscription.remove(s)
}
}))
timeline.cycleCount = 1
timeline.play()
innerSubscription.add(s)
return Subscriptions.create(object : Action0 {
override fun call() {
timeline.stop()
s.unsubscribe()
innerSubscription.remove(s)
}
})
}
override fun schedule(action: Action0): Subscription {
val s = BooleanSubscription.create()
Platform.runLater(object : Runnable {
override fun run() {
if (innerSubscription.isUnsubscribed || s.isUnsubscribed) {
return
}
action.call()
innerSubscription.remove(s)
}
})
innerSubscription.add(s)
return Subscriptions.create(object : Action0 {
override fun call() {
s.unsubscribe()
innerSubscription.remove(s)
}
})
}
}
companion object {
val instance = JavaFxScheduler()
}
} | src/main/kotlin/com/prt2121/pojo/rx/JavaFxScheduler.kt | 2516697487 |
package me.ykrank.s1next.widget.track.event
import com.github.ykrank.androidtools.widget.track.event.TrackEvent
/**
* Created by ykrank on 2016/12/29.
*/
class ViewForumTrackEvent(id: String, name: String) : TrackEvent() {
init {
group = "ζ΅θ§ηε"
addData("id", id)
addData("name", name)
}
}
| app/src/main/java/me/ykrank/s1next/widget/track/event/ViewForumTrackEvent.kt | 1538672822 |
package net.ndrei.teslapoweredthingies.items
import net.ndrei.teslacorelib.items.BaseAddon
import net.ndrei.teslacorelib.tileentities.SidedTileEntity
import net.ndrei.teslapoweredthingies.TeslaThingiesMod
import net.ndrei.teslapoweredthingies.common.IAnimalAgeFilterAcceptor
import net.ndrei.teslapoweredthingies.common.IAnimalEntityFilter
/**
* Created by CF on 2017-07-07.
*/
abstract class BaseAnimalFilterItem(registryName: String)
: BaseAddon(TeslaThingiesMod.MODID, TeslaThingiesMod.creativeTab, registryName), IAnimalEntityFilter {
override fun canBeAddedTo(machine: SidedTileEntity)
= (machine is IAnimalAgeFilterAcceptor) && machine.acceptsFilter(this)
}
| src/main/kotlin/net/ndrei/teslapoweredthingies/items/BaseAnimalFilterItem.kt | 756248790 |
/*
* Copyright Β© 2014-2019 The Android Password Store Authors. All Rights Reserved.
* SPDX-License-Identifier: GPL-2.0
*/
package com.zeapo.pwdstore.pwgen
internal object RandomPasswordGenerator {
/**
* Generates a completely random password.
*
* @param size length of password to generate
* @param pwFlags flag field where set bits indicate conditions the
* generated password must meet
* <table summary ="bits of flag field">
* <tr><td>Bit</td><td>Condition</td></tr>
* <tr><td>0</td><td>include at least one number</td></tr>
* <tr><td>1</td><td>include at least one uppercase letter</td></tr>
* <tr><td>2</td><td>include at least one symbol</td></tr>
* <tr><td>3</td><td>don't include ambiguous characters</td></tr>
* <tr><td>4</td><td>don't include vowels</td></tr>
* <tr><td>5</td><td>include at least one lowercase</td></tr>
</table> *
* @return the generated password
*/
fun rand(size: Int, pwFlags: Int): String {
var password: String
var cha: Char
var i: Int
var featureFlags: Int
var num: Int
var character: String
var bank = ""
if (pwFlags and PasswordGenerator.DIGITS > 0) {
bank += PasswordGenerator.DIGITS_STR
}
if (pwFlags and PasswordGenerator.UPPERS > 0) {
bank += PasswordGenerator.UPPERS_STR
}
if (pwFlags and PasswordGenerator.LOWERS > 0) {
bank += PasswordGenerator.LOWERS_STR
}
if (pwFlags and PasswordGenerator.SYMBOLS > 0) {
bank += PasswordGenerator.SYMBOLS_STR
}
do {
password = ""
featureFlags = pwFlags
i = 0
while (i < size) {
num = RandomNumberGenerator.number(bank.length)
cha = bank.toCharArray()[num]
character = cha.toString()
if (pwFlags and PasswordGenerator.AMBIGUOUS > 0 &&
PasswordGenerator.AMBIGUOUS_STR.contains(character)) {
continue
}
if (pwFlags and PasswordGenerator.NO_VOWELS > 0 && PasswordGenerator.VOWELS_STR.contains(character)) {
continue
}
password += character
i++
if (PasswordGenerator.DIGITS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.DIGITS.inv()
}
if (PasswordGenerator.UPPERS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.UPPERS.inv()
}
if (PasswordGenerator.SYMBOLS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.SYMBOLS.inv()
}
if (PasswordGenerator.LOWERS_STR.contains(character)) {
featureFlags = featureFlags and PasswordGenerator.LOWERS.inv()
}
}
} while (featureFlags and (PasswordGenerator.UPPERS or PasswordGenerator.DIGITS or PasswordGenerator.SYMBOLS or PasswordGenerator.LOWERS) > 0)
return password
}
}
| app/src/main/java/com/zeapo/pwdstore/pwgen/RandomPasswordGenerator.kt | 54167106 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.java
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.LightPlatformTestCase
class JavaModuleFormatterTest : AbstractJavaFormatterTest() {
override fun setUp() {
super.setUp()
LanguageLevelProjectExtension.getInstance(LightPlatformTestCase.getProject()).languageLevel = LanguageLevel.JDK_1_9
}
fun testEmpty() {
doTextTest("module A.B { }", "module A.B {\n}")
}
fun testCommentBody() {
doTextTest("module m { /* comment */ }", "module m { /* comment */\n}")
}
fun testStatements() {
doTextTest("module m { requires java.base; exports a.b; }", "module m {\n requires java.base;\n exports a.b;\n}")
}
fun testQualifiedExports() {
doTextTest("module m { exports a.b to m1,m2,m3; }", "module m {\n exports a.b to m1, m2, m3;\n}")
}
fun testProvidesWith() {
doTextTest("module m { provides I with C1,C2,C3; }", "module m {\n provides I with C1, C2, C3;\n}")
}
} | java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaModuleFormatterTest.kt | 1648472993 |
package tv.superawesome.sdk.publisher.common.models
data class QueryAdditionalOptions(val options: Map<String, String>) {
companion object {
var instance: QueryAdditionalOptions? = null
}
} | superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/models/QueryAdditionalOptions.kt | 613915929 |
package tv.superawesome.sdk.publisher.common.network.retrofit
import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.buffer
import okio.sink
import tv.superawesome.sdk.publisher.common.components.Logger
import tv.superawesome.sdk.publisher.common.datasources.NetworkDataSourceType
import tv.superawesome.sdk.publisher.common.models.UrlFileItem
import tv.superawesome.sdk.publisher.common.network.DataResult
import java.io.File
class OkHttpNetworkDataSource(
private val client: OkHttpClient,
private val applicationContext: Context,
private val logger: Logger,
) : NetworkDataSourceType {
override suspend fun getData(url: String): DataResult<String> {
logger.info("getData:url: $url")
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
return if (response.isSuccessful) {
DataResult.Success(response.body?.string() ?: "")
} else {
DataResult.Failure(Error("Could not GET data from $url"))
}
}
override suspend fun downloadFile(url: String): DataResult<String> {
logger.info("downloadFile")
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
val urlFileItem = UrlFileItem(url)
val downloadedFile = File(applicationContext.cacheDir, urlFileItem.fileName)
return try {
val sink = downloadedFile.sink().buffer()
sink.writeAll(response.body!!.source())
sink.close()
logger.success("File download successful with path: ${downloadedFile.absolutePath}")
DataResult.Success(downloadedFile.absolutePath)
} catch (e: Exception) {
logger.error("File download error", e)
DataResult.Failure(Error(e.localizedMessage))
}
}
} | superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/network/retrofit/OkHttpNetworkDataSource.kt | 3543821369 |
package cool.util
import cool.lexer.TokenConstants
object Errors {
public fun printError(lineNumber: Int, message: String) {
val message = "ERROR: line: " + lineNumber + " " + message
println(message)
}
public fun printError(lineNumber: Int, key: Int) {
val message = "ERROR: line: " + lineNumber + " Expected:" + keyToString(key)
println(message)
}
private fun keyToString(key: Int): String {
return when (key) {
TokenConstants.ASSIGN -> " \"<-\" "
TokenConstants.AT -> " \"@\" "
TokenConstants.BOOL_CONST -> " BOOL_CONST "
TokenConstants.CASE -> " \"case\" "
TokenConstants.CLASS -> " \"class\" "
TokenConstants.COLON -> " \":\" "
TokenConstants.COMMA -> " \",\" "
TokenConstants.DARROW -> " \"->\" "
TokenConstants.DIV -> " \"/\" "
TokenConstants.DOT -> " \".\" "
TokenConstants.ELSE -> " \"else\" "
TokenConstants.EQ -> " \"=\" "
TokenConstants.ESAC -> " \"esac\" "
TokenConstants.FI -> " \"fi\" "
TokenConstants.IN -> " \"in\" "
TokenConstants.INT_CONST -> " INT_CONST "
TokenConstants.LBRACE -> " \"{\" "
TokenConstants.LPAREN -> " \"(\" "
TokenConstants.LT -> " \"<=\" "
TokenConstants.MINUS -> " \"-\" "
TokenConstants.OBJECTID -> " OBJECTID "
TokenConstants.OF -> " \"of\" "
TokenConstants.RBRACE -> " \"}\" "
TokenConstants.RPAREN -> " \")\" "
TokenConstants.SEMI -> " \";\" "
TokenConstants.TYPEID -> " TYPEID "
else -> " Unenxpected symbol "
}
}
} | src/cool/util/Errors.kt | 3036441647 |
package fernandocs.currencyconverter.view
import android.support.v4.app.Fragment
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
open class MvvmFragment : Fragment() {
private val subscriptions = CompositeDisposable()
fun subscribe(disposable: Disposable): Disposable {
subscriptions.add(disposable)
return disposable
}
override fun onStop() {
super.onStop()
subscriptions.clear()
}
} | app/src/main/java/fernandocs/currencyconverter/view/MvvmFragment.kt | 4268960553 |
/*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.ui.drag
import android.view.DragEvent
import android.view.View
class TabFragmentSideDragListener(private val dragEventCallback: () -> Unit) : View.OnDragListener {
override fun onDrag(p0: View?, p1: DragEvent?): Boolean {
return when (p1?.action) {
DragEvent.ACTION_DRAG_ENDED -> {
true
}
DragEvent.ACTION_DRAG_ENTERED -> {
dragEventCallback()
true
}
DragEvent.ACTION_DRAG_EXITED -> {
true
}
DragEvent.ACTION_DRAG_STARTED -> {
true
}
DragEvent.ACTION_DRAG_LOCATION -> {
true
}
DragEvent.ACTION_DROP -> {
true
}
else -> false
}
}
}
| app/src/main/java/com/amaze/filemanager/ui/drag/TabFragmentSideDragListener.kt | 824601677 |
/*
* 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 chrislo27.discordbot.impl.baristron
import chrislo27.discordbot.Bot
import chrislo27.discordbot.Userdata
import chrislo27.discordbot.cmd.Command
import chrislo27.discordbot.cmd.CommandContext
import chrislo27.discordbot.cmd.CommandHandler
import chrislo27.discordbot.cmd.HelpData
import chrislo27.discordbot.cmd.impl.*
import chrislo27.discordbot.impl.baristron.cmds.TagCommand
import chrislo27.discordbot.impl.baristron.cmds.TestingCommand
import chrislo27.discordbot.impl.baristron.goat.GoatCommand
import chrislo27.discordbot.tick.TickManager
import chrislo27.discordbot.util.*
import sx.blah.discord.api.ClientBuilder
import sx.blah.discord.api.events.EventSubscriber
import sx.blah.discord.api.events.IListener
import sx.blah.discord.handle.impl.events.MessageReceivedEvent
import sx.blah.discord.handle.impl.events.ReadyEvent
import sx.blah.discord.handle.obj.IGuild
import sx.blah.discord.handle.obj.IUser
import sx.blah.discord.util.EmbedBuilder
import sx.blah.discord.util.MessageList
import java.util.*
class Baristron(builder: ClientBuilder) : Bot<Baristron>(builder) {
override val commandHandler: CommandHandler<Baristron> = CommandHandler(this)
init {
tickManager = TickManager(this)
MessageList.setEfficiency(client, MessageList.EfficiencyLevel.MEDIUM)
commandHandler.addCommands {
it.add(CommandsCommand(Permission.DUNGEON, "commands", "cmds"))
it.add(HelpCommand(Permission.DUNGEON, "help", "?"))
it.add(ChangeUsernameCommand(Permission.ADMIN, "changeusername"))
it.add(ChangeNicknameCommand(Permission.ADMIN, "changenickname"))
it.add(ChangeAvatarCommand(Permission.ADMIN, "changeavatar"))
it.add(object : ChangePrefixCommand<Baristron>(Permission.MODERATOR, "changeprefix") {
override fun savePrefix(context: CommandContext<Baristron>, prefix: String) {
Userdata.setString("baristron_prefix_${context.guild!!.id}", prefix)
}
})
it.add(object : Command<Baristron>(Permission.NORMAL, "info") {
override fun handle(context: CommandContext<Baristron>) {
sendMessage(builder(context.channel).withEmbed(EmbedBuilder().withTitle("About this bot").withColor(
Utils.random.nextInt(0xFFFFFF + 1)).withThumbnail(client.ourUser.avatarURL).withDesc(
"[Baristron](https://github.com/chrislo27/Baristron) is a multi-purpose bot by" +
" [chrislo27](https://github.com/chrislo27) written in " +
"Kotlin using the " +
"[Discord4J](https://github.com/austinv11/Discord4J) library." +
" It was originally written in Java, and thus this current version" +
" will not have 100% of the same features as the old version did.")
.appendField("Experimental!",
"This experimental version of Baristron is called Baristron Neo.",
false).build()))
}
override fun getHelp(): HelpData = HelpData("See info about this bot.",
linkedMapOf("" to "See info about this bot."))
})
it.add(TestingCommand(Permission.ADMIN, "test"))
it.add(TagCommand(Permission.NORMAL, "tag", "tags"))
it.add(GoatCommand(Permission.ADMIN, "goat"))
it.add(ServerLockdownCommand(Permission.NORMAL, "lockdownserver"))
}
client.dispatcher.registerListener(GuildUpdateListener())
client.dispatcher.registerListener(IListener { it: ReadyEvent ->
// client.dnd("testing the v6 waters")
})
}
@EventSubscriber
fun onMessage(event: MessageReceivedEvent) {
commandHandler.handleEvent(event)
}
override fun tickUpdate() {
}
override fun getPrefix(guild: IGuild?): String {
return Userdata.getString("baristron_prefix_" + guild?.id, "%%")!! // FIXME %% -> %
}
override fun getEmbeddedPrefix(guild: IGuild?): String? {
return Utils.repeat(getPrefix(guild), 3)
}
override fun getPermission(user: IUser, guild: IGuild?): Permission {
if (user == client.applicationOwner) return Permission.ADMIN
var p = Permission.valueOf(
Userdata.getString("permission_" + user.id, Permission.NORMAL.getName())!!.toUpperCase(Locale.ROOT))
if (p.getOrdinal() < Permission.MODERATOR.getOrdinal() && guild?.owner == user) {
p = Permission.MODERATOR
}
return p
}
override fun setPermission(user: IUser, perm: IPermission?) {
if (perm == null) {
Userdata.removeString("permission_" + user.id)
return
}
Userdata.setString("permission_" + user.id, perm.getName())
}
override fun onLogin() {
}
override fun onLogout() {
}
}
enum class Permission : IPermission {
DUNGEON,
NORMAL,
TRUSTED,
DISCORD4J,
MODLOG,
MODERATOR,
ADMIN;
override fun getName(): String {
return this.name
}
override fun getOrdinal(): Int {
return this.ordinal
}
}
| src/chrislo27/discordbot/impl/baristron/BotBaristron.kt | 754175134 |
package com.chrisprime.primestationonecontrol.bases
import android.support.annotation.IdRes
import android.support.annotation.NonNull
import android.support.annotation.StringRes
import com.chrisprime.primestationonecontrol.activities.PrimeStationOneControlActivity
import com.chrisprime.primestationonecontrol.dagger.ApplicationComponentInstrumentationTest
import com.chrisprime.primestationonecontrol.dagger.InjectorInstrumentationTest
import com.chrisprime.primestationonecontrol.utilities.TestUtilities
/**
* This should be the default base UI test, using the default entry point
* Created by cpaian on 9/24/16.
*/
abstract class BaseUiTest @JvmOverloads protected constructor(clearUserDataBeforeLaunch: Boolean = false) : BaseInstrumentationTest<PrimeStationOneControlActivity>(PrimeStationOneControlActivity::class.java, clearUserDataBeforeLaunch) {
override fun injectComponentsForInstrumentationTest() { //Must perform injection one subclass down without a generic subtype
InjectorInstrumentationTest.initializeApplicationComponent()
(InjectorInstrumentationTest.applicationComponent as ApplicationComponentInstrumentationTest).inject(this)
}
fun navigateTo(@NonNull screenshotTag: String, @StringRes navItemTextResId: Int, @IdRes idToWatchFor: Int) {
TestUtilities.openNavDrawer()
TestUtilities.watchForText(navItemTextResId)
screenshot("DrawerOpenFor$screenshotTag")
TestUtilities.tapViewWithText(navItemTextResId)
TestUtilities.watchForId(idToWatchFor)
screenshot("${screenshotTag}View")
}
}
| app/src/androidTest/java/com/chrisprime/primestationonecontrol/bases/BaseUiTest.kt | 2777355142 |
package ca.six.demo.biz.splash
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import ca.six.demo.R
import ca.six.demo.biz.home.HomeActivity
import ca.six.demo.core.BaseActivity
class SplashActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
println("szw SplashPage : $retrofit")
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (MotionEvent.ACTION_UP == event.action) {
startActivity(Intent(this, HomeActivity::class.java))
}
return super.onTouchEvent(event)
}
}
| deprecated/Tools/DaggerRxJavaProject/app/src/main/java/ca/six/demo/biz/splash/SplashActivity.kt | 731774862 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.